Site down after VM restart

Question: I have a standard WordPress installation on GCP. I needed to edit the php.ini file, which I did. And, then restarted my VM, so that all services such as PHP, Apache etc. also get restarted.
However, the site is now no longer accessible. Neither from the domain name, nor using the external IP address. Any ideas on how to bring it back up?
In deployments, I do see a warning icon, but it's impossible to figure out what the issue is, and how to fix it.
Deployments
VM
Comment: Connect via ssh and read the logs? The IP listed in GCP answers on SSH.
Answer: Is the VM's IP address ephemeral or reserved?
The IP address in your screenshot 126.96.36.199 does not match the DNS resource record 126.96.36.199 for the domain portfoliodoc.app.
Consult this guide, reserve an IP address and update your DNS server.
Reserve a static external IP address
After updating DNS with the correct IP address you will have to wait for DNS to propagate (minutes to hours).

Site down after VM restart


Manage whole crontab files in Ansible

Question: I have a crontab containing around 80 entries on a server. And I would like to manage that crontab using Ansible.
Ideally I would copy the server's crontab to my Ansible directory and create an Ansible task to ensure that crontab is set on the server.
But the cron module only seems to manage individual cron entries and not whole crontab files.
Manually migrating the crontab to Ansible tasks is tedious. And even if I find or make a tool that does it automatically, I feel the YAML file will be far less readable than the crontab file.
Any idea how I can handle that big crontab using Ansible?
Comment: Just use the `copy` module to copy the crontab to the appropriate location?
Comment: I do not have root privileges.
Comment: Maybe use http://docs.ansible.com/assemble_module.html? If you don't have root, how are you going to modify crontab anyway?
Comment: A user does not need root privileges to update his crontab.
Answer: I managed to find a simple way to do it. I copy the crontab file to the server and then update the crontab with the shell module if the file changed.
The crontab task:
<code>---
- name: Ensure crontab file is up-to-date.
  copy: src=tasks/crontab/files/{{ file }} dest={{ home }}/cronfile
  register: result
- name: Ensure crontab file is active.
  shell: crontab cronfile
  when: result|changed
</code>
In my playbook:
<code>- include: tasks/crontab/main.yml file=backend.cron
</code>
Comment: Upvoted! Tip: you should backup the old cron first in case there were manual edits made outside of Ansible.
Comment: Agreed. It is a good practice @ChrisMcCauley!
Answer: Maintain idempotency by doing it this way:
<code>- name: crontab
  block:
    - name: copy crontab file
      copy:
        src: /data/vendor/home/cronfile
        dest: /home/mule/cronfile
        mode: '0644'
      register: result

    - name: ensure crontab file is active
      command: crontab /home/mule/cronfile
      when: result.changed

  rescue:
    - name: delete crontab file
      file:
        state: absent
        path: /home/mule/cronfile
</code>
Answer: I solved this problem like this:
<code>- name: Save out Crontabs
  copy: src=../files/crontabs/{{ item }} dest=/var/spool/cron/{{ item }} owner={{item}} mode=0600
  notify: restart cron
  with_items:
  - root
  - ralph
  - jim
  - bob
</code>
The advantage of this method (versus writing to an intermediate file) is that any manual edits of the live crontab get removed and replaced with the Ansible controlled version. The disadvantage is that it's somewhat hacking the cron process.
Comment: "The advantage ... any manual edits of the live crontab get removed" - I'd see that as a bug.  It can easily be solved by backing up the existing cron first.

Manage whole crontab files in Ansible


Report of coupon and users

Question: I have users who are partners and users who are clients. When clients submit an order, they use a custom coupon code associated with each partner. (Each partner has a Mycodes field set within their profile.)
Previously, at the end of the month, we would download the sales into an Excel sheet and calculate the commissions of each partner using the partner's coupon codes.
Now I want to do this on the website using a view. I created a view for the coupons but I cannot compare the coupon code against the partner's Mycodes field.
I have written the sql query in phpMyAdmin (one line with two JOIN), but I can not put that into views and filter that based on current userID:
<code>SELECT
  uc_order_line_items.order_id AS OrderID,
  uc_orders.order_status AS Currently,
  uc_orders.created AS ThisDate,
  uc_orders.delivery_first_name AS Name,
  uc_orders.delivery_last_name AS Surname,
  uc_orders.delivery_phone AS Phone,
  uc_orders.primary_email AS Email,
  field_data_field_mycodes.entity_id AS UserID,
  uc_orders.order_total AS Total
FROM
  uc_order_line_items
JOIN
  field_data_field_mycodes
ON
  uc_order_line_items.title = field_data_field_mycodes.field_mycodes_value
JOIN
  uc_orders
ON
  uc_orders.order_id = uc_order_line_items.order_id
WHERE
  field_data_field_mycodes.entity_id=
</code>
Comment: Just to clarify, what is the field type of "Mycodes"? Is it a plain text or an entity reference?
Comment: it can be anything that can link these two! I am open to any idea
Comment: Okay, there's a few different ways to solve this problem. Looking at your SQL query, I'm confused at what you're looking for.
Comment: Are you wanting a View that calculates the commission each partner gets? Or just to display the orders for each partner? Or all of the orders, grouped by each partner?
Comment: Just the list of the orders of each partner would be enough. This is what I can not do in Views: where current user's mycodes = uc_order_line_items.title
Comment: Try creating a contextual filter on the field `uc_order_line_items.title`. Then, you just need to find a way to input the current user's `mycodes` into the contextual filter.
Answer: Thanks to Chris I tried that with 3 different base tables, but none worked.
This might not be the answer but it is for the people who might read this article as an option. After spending more than 2 days, I decided to go with the craziest approach yet "doable": I created a login table in the database, wrote one login page and one report page in PHP (less than 650 lines of codes with all those sort and filter), and I was done in about 5 hours. Link to that login went into Drupal, and that was it.
Drupal is a very great tool but I guess Views needs to add a free-hand SQL query, and, also a free-hand javascript insertion per page. these could really save programmers a lot saving hours of work...

Report of coupon and users


Pricing at the hourly rate only until this exceeds the daily rate

Question: Pricing at the hourly rate only until this exceeds the daily rate
Example: if a rent costs \$1 per hour, \$10 per day and a booking for 11 hours will be charged \$10. For two complete days it will charge as \$20. For 2 complete days and 2 hr the price will be \$22. The same principle goes for weekly and monthly bookings. Is there any equation in general for this problem ?
Comment: The question doesn't make sense the way it is posed. Please add some clarifications... maybe in your example replace the numbers with variables?!
Answer: To clarify the problem, I will assume that:
1) rental for part of an hour is charged for a full hour,
2) a "full day" is $24$ hours,
3) rental is for a continuous interval of time,
4) rental for each full day is $\$10$,
5) rental for hours after the full days is $\$1$ per hour, with a maximum charge of $\$10$.
My formula uses these functions:
1) $\lceil x\rceil$ is the ceiling function: $x$ rounded up to the smallest integer that is greater than or equal to $x$.
2) $\lfloor x\rfloor$ is the floor function: $x$ rounded down to the greatest integer that is less than or equal to $x$.
3) $x \bmod y$ is the remainder of $x$ when divided by $y$.
4) $\min(x,y)$ is the minimum function: the lesser of $x$ and $y$.
Then the formula for the rental for $h$ hours is
$$10\left \lfloor\frac{h}{24} \right \rfloor
  +\min \left(\lceil h \bmod 24 \rceil ,10\right)$$
This formula could be done with fewer special functions, but that would make the formula longer and more difficult looking.


Differentiability at (0,0).

Question: I always get stuck when I've to show something is differentiable,like in the following question:
$f(x,y) = \begin{cases} \dfrac{x^3y^3}{x^4+y^4} & \text{if $(x,y)\neq(0,0)$} \\ 0 & \text{if $(x,y)=(0,0)$} \end{cases}$
show that f is differentiable at (0,0) ...
First I thought of showing that partial derivatives exist for the
point (0, 0).
$$\frac{\partial f}{\partial x}(0,0)=\lim_{x\rightarrow 0}\frac{f(x,0)-f(0,0)}{x-0}=\lim_{x\rightarrow 0}\frac{\frac{0}{x^4}}{x}=\lim_{x\rightarrow 0}\frac{{0}}{x^5}= 0$$
later in relation to y:
$$\frac{\partial f}{\partial y}(0,0)=\lim_{y\rightarrow 0}\frac{f(0,y)-f(0,0)}{y -0}=\lim_{y\rightarrow 0}\frac{\frac{0}{y^4}}{y}=\lim_{y\rightarrow 0}\frac{{0}}{y^5}= 0$$
alright both partial derivatives exists and are equal,so now we have to show that :they are continuous near (0,0)..
but that doesn't prove the limit is differentiable, what can I do?
I thought of using the following formula for a corollary.
$$E(h,k)=f(x_0 +h, y_0 +k)-f(x_0, y_0)-\frac{\partial f}{\partial x}(x_0,y_0)h -\frac{\partial f}{\partial y}(x_0,y_0)k$$
however:
$$E(h,k)=\frac{(x_0+h)^3(y_0+k)^3} {(x_0 + h)^4 + (y_0 +k)^4}  -\frac{x^3 y^3}{x^4 + y^4}-0h -0k$$
Comment: Check your work.  $f(x,0)$ is not equal to $x^3/x^4$.
Comment: Is $x\neq 0$ then $f(x,0)=\frac{x^3\cdot 0^3}{x^4+0^4}=0$. What is the definition of differentiability that you're using?
Comment: What definition do you have for differentiability?
Comment: but in the function $f(x,y)$ is $\frac {x^3 y^3}{x^4+y^4}$
Comment: First I thought of showing that partial derivatives exist for the
point (0, 0).
Answer: As you have correctly computed that $\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=0$.
A function is said to be differentiable at a point $(a,b)$ iff there exist $\phi(h,k)$ and $\psi(h,k)$ from $\mathbb{R}^{2}\to\mathbb{R}$ such that
$f(a+h,b+k)=h\frac{\partial f}{\partial x}\vert_{(a,b)}+k\frac{\partial f}{\partial y}\vert_{(a,b)}+h\phi(h,k)+k\psi(h,k)$ such that  $\phi(h,k)\to 0\quad \text{and}\quad\psi(h,k)\to 0$ as $(h,k)\to(0,0)$.
So if our given function is differentiable.
Then $f(0+h,0+k)=h\frac{\partial f}{\partial x}+k\frac{\partial f}{\partial y}+h\phi(h,k) +k\psi(h,k)$ where $\psi$ and $\phi$ both $\to 0$ as $(h,k)\to (0,0)$ .
Then $\dfrac{h^3k^3}{h^4+k^4}=h\phi(h,k)+k\psi(h,k)$.
Take $\displaystyle\phi(h,k)=\frac{h^{2}k^{3}}{2(h^{4}+k^{4})}$
and $\displaystyle\psi(h,k)=\frac{k^{2}h^{3}}{2(h^{4}+k^{4})}$.
Then both $\phi$ and $\psi$ tend to $0$ as $(h,k)\to(0,0)$.
Hence you have differentiability.
In a Equivalent formulation of Differentiability.
A function is differentiable at a point $(a,b)$ iff there exist $\psi(h,k)$
$f(a+h,b+k)=h\frac{\partial f}{\partial x}\vert_{(a,b)}+k\frac{\partial f}{\partial y}\vert_{(a,b)}+\sqrt{h^{2}+k^{2}}\cdot \psi(h,k)$ such that $\psi(h,k)\to 0$ as $(h,k)\to(0,0)$.
In this case you just take $\displaystyle\psi=\frac{h^3k^3}{(h^4+k^4)\sqrt{(h^{2}+k^{2})}}$ . Then this would also imply differentiablity.
It's just a matter of what convention you follow. Many people like this norm formulation. I myself prefer the previous one. They are both equivalent.
Lastly, I would say that you should try and use polar coordinates to show that $\psi$ and $\phi$ tend to $0$. It is very easy. $\cos^{4}(\theta)+\sin^{4}(\theta)\geq \frac{1}{2}$ always.
Comment: Could you tell me why in the corollary you added it all up and what does the:
$\frac{\partial f}{\partial x}h |_(a,b)$
and what does it mean ϕ  and ψ?
Comment: @Skye $\frac{\partial f}{\partial x}|_{(a,b)}$ just means evaluated at $(a,b)$. Nothing else. And $\phi$ and $\psi$ are two functions from $\mathbb{R}^{2}\to\mathbb{R}$ such that both tend to $0$ as $(h,k)\to(0,0)$
Comment: Got it, can you show me where I can study a formula you presented at the beginning?
Comment: It's just a formulation of differentiation. Many people also wirte it as $\frac{f(a+h,b+k)-hf_{x}-kf_{y}}{\sqrt{h^{2}+k^{2}}}\to 0 $ as $(h,k)\to (0,0)$. Here $f_{x}$ means partial derivative. I wouls suggest you the book by Satish Shirali and Harikrishna Lal Vasudeva on multivariable calculus for this reference. It is frankly imo the best book on the topic and it helped me a lot at the undergrad level.
Comment: Also @Skye you can mark as answer if it has answered your question
Comment: can you explain the part that originated "Take $ ϕ(h,k)=\frac{h^2 k^3} {2(h^4 +k^4)}$?where did the 2 come from?
Comment: @Skye If you look at what I wrote....you will see that I said "differentiable iff there exist functions $\phi$ and $\psi$. So we are doing exactly that. We are constructing functions $\phi$ and $\psi$ which satisfy the given constraints. Since we are able to construct such function , it is differentiable. And to answer your query , the $2$ is kept so that RHS = LHS. so that when you add $h\phi + k\psi$ you end up with the LHS. Otherwise you will get a useless $2$ in the numerator.
Comment: Hi Mr. Gandalf, I again... was wondering why we just can't say by showing that the partial derivatives of f are
in continuous (0, 0).
Doesn't that prove that f is differentiable at (0,0)?
Comment: The continuity of partial derivatives provide a sufficient condition for differentiability. If you want to use that it is fine....but why bother if we can show it directly? .
Comment: It would be like using a theorem to show something which directly follows from definition.

Differentiability at (0,0).


How to Parse json array as key value pair where position is key in android kotlin

Question: I have json like below:

Here links as an array under values array. I have to get key and value from links array, like key will be 0 and value will be "http://www.example.com/....".
There may be multiple links in the links array like in 0 position, 1 position like that.
How to get this as key pair?
I am trying in the below way:
dataBinding.itemUserControlTvPhone.setOnClickListener {
                    val failedQtyMapper = jacksonObjectMapper()
                    if (data?.get(position)?.links != null) {
                        var jsonStr = failedQtyMapper.writerWithDefaultPrettyPrinter()
                            .writeValueAsString(
                                data?.get(position)?.links ?: ""
                            )
                        Log.e("jsonString:=", jsonStr)

but getting jsonString as
    E/jsonString= ["http://www.example.com/reports/ Place Tp 2021-08-17 19_16_29_440.csv"]

But I need this jsonString as a key value pair. How to do this?
Comment: What do you mean with "as a key pair"?
Comment: I mean key value pair  @ Ivo
Comment: But what do you exactly mean by that? What type is that? Do you mean a `Pair`? It looks to me `position` is the key and `data?.get(position)?.links` the value? then just do `Pair(position, data?.get(position)?.links)` ?
Comment: I tried your way and it's giving output as,   E/jsonString:=: {
      "first" : 0,
      "second" : [ "http://www.example.com/reports/ Place Tp 2021-08-17 19_16_29_440.csv" ]
    }  @Ivo
Answer: Since links is a list, each item in it will have an index from 0 to list.size - 1
You can do something like
   links?.forEachIndexed { index, item ->
        var jsonStr = "$index: $item"
        Log.e("jsonString:=", jsonStr)
    }


how to configure sendmail with multiple ssl certificates for multiple domains

Question: I need to configure a server to host multiple email domains on a single IP, and thus install multiple ssl certificates.
Miraculously, I have been able to get apache and dovecot to work with multiple certificates/domains on a single IP, but I can't find any recent info on sendmail.  So I can receive emails on the second domain, but when I go to send, I get a certificate error unless I send as the first domain which is the one sendmail has configured.  I have a lot of customizations so would like to stick with sendmail if possible.  But if the only option is to go with postfix, then I may have to (if postfix will do multiple domains on a single IP).  Or, if I have to do multiple IPs, that would use up a lot of IPs and I'm not sure I can do that.
Thanks in advance.
Comment: Is the single IP a strict requirement?  If you could add more IPs, you could have multiple instances of SendMail (one for each IP) and have each one use a separate TLS cert, hostname, etc.
Answer: Not a real answer but too long for a comment...
1 IP-address, multiple certificates --> that sounds like you want support for server name indication and I can't find any conclusive evidence that sendmail supports that (or not for that matter).
If indeed you can only configure a single certificate and you can't invest in a UCC/SAN certificate:
A potential work-around is to use a single hostname as the primary MX record for all your domains and get a TLS certificate with that hostname i.e. smtp.example.com is the primary MX for not only example.com but for example.org and and example.net as well.
That is a not such a bad idea as sendmail will normally only identify itself by a single hostname anyway and that hostname ought to match with reverse DNS record for your IP-address. And your reverse DNS can also only point to a single hostname.
Related as well: Is enforcing encryption for SMTP a good idea (yet)?


How can I update all content of a content type with a newly added field?

Question: I have a content type with a set of fields.
Hundred(s) of pieces of content have been created from this content type.
I recently had to go back and add a new field to the content type.
In order for all content of that content type that I previously created to show the newly added field, I have so far been going into each piece of content and adding in the field. This is going to take forever.
Is there another tool or process I can use to update all previously created content with the new field added to the content type?
Answer: if I understand correctly you need to update node in range of new date? right? so if this is the case why not use EntityFieldQuery() to list of this nodes then node_save() or field_attach_update() to update the new value.
if this is the case I'd be happy to give you some snippets to help you do this.
Answer: I would recommend Views Bulk Operations for this.  You can make a quick view to select the content with a modify action to set the value.  No programming needed.
VBO is a great tool to keep handy for a lot of stuff like this.
Answer: Step 1
Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Set a data value, for each of those fields you want to be updated.
Step 2
Create a view of the nodes for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.
Tutorial
To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
Comment: @lcunning merci for the accept (and +1)!
Answer: Existing Question, Please refer the below link
As they mention use Devel module to Run PHP code.
Bulk Field Update


host_vars not working in ansible

Question: I need to use host_vars in my ansible file to install a package on remote host, i am trying to pull a variable by the name  package from host_vars dir in which a  file ansi2 reside  which is the hostname of remote machine,, the name of my main yaml file is service.yml and reside in /etc/ansible ....
---
 - hosts: all
   become: yes
   ignore_errors: yes
   gather_facts: no
   tasks:

   - name: install vim
     yum: name={{ package }} state=present

Dir Structure:
[root@ansi1 ansible]# pwd
/etc/ansible
[root@ansi1 ansible]#
[root@ansi1 ansible]# ls -l ansi2/host_vars/
total 4
-rw-r--r-- 1 root root 19 Jun 13 08:15 ansi2
[root@ansi1 ansible]#

[root@ansi1 ansible]# cat ansi2/host_vars/ansi2
---
package: "vim"

Error:
TASK [install vim] *************************************************************
task path: /etc/ansible/service.yml:7
fatal: [ansi2.example.com]: FAILED! => {
    "failed": true,
    "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'package' is undefined\n\nThe error appears to have been in '/etc/ansible/service.yml': line 7, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n   tasks:\n   - name: install vim\n     ^ here\n"
}
...ignoring

Answer: As per your output, inventory hostname is ansi2.example.com.
You should change file name ansi2 to match your inventory hostname.

host_vars not working in ansible


How to change WooCommerce order total in admin orders list

Question: I need to add a fee to WooCommerce order total in admin orders list.
When I make a R$65 sale, my payment gateway charges a tax, and I receive R$64,36.
How to make show R$64,36 as the order total, but only on admin orders list, if the customer goes to his My Account orders list, we need to show R$65,00 over there.
Answer: You can use woocommerce_get_formatted_order_total filter hook as follows:
add_filter('woocommerce_get_formatted_order_total', 'filter_formatted_order_total', 10, 2);
function filter_formatted_order_total( $formatted_total, $order ) {
    global $pagenow;

    if ( 'edit.php' === $pagenow && isset($_GET['post_type']) && 'shop_order' === $_GET['post_type'] ){
        // HERE define the payment fee
        $payment_fee = 0.64;

        $formatted_total = wc_price( $order->get_total() + $payment_fee, array( 'currency' => $order->get_currency() ) );
    }
    return $formatted_total;
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.


Error: Type 'MouseCursor' not found. (fl_chart)

Question: This problem was caused by adding fl_chart v 0.40.0 to my pubspec.yaml on my Flutter project.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Version v 0.40.0 of fl_chart introduced breaking changes. A temporary solution was to downgrade to version v 0.36.4. It worked but still looking into why v 0.40.0 throws that error


I need a reference for: Existence and Uniqueness of a general ODEs with a linear operator

Question: I'm looking for a reference of a theorem that establishes the existence and uniqueness of the following general ODE:
Let $Q_n$ is a finite dimentional Hilbert space and let the operator $A:Q_n\to Q_n$ is a self adjoint and a positive definite linear operator. Let $f\in L^2(0,T;Q_n)$ and $g\in Q_n$  We search $u(t)\in Q_n$ such that for any $t\in [0,T]$,
$\dfrac{du(t)}{dt}+Au(t)=f(t),$
$u(0)=g.$
Note that $u\in L^2(0,T;Q_n)$
Comment: Be more specific: What is $A$? Is it a bounded operator on a Banach space or an unbounded one?
Comment: If $Q_n$ is a finite dimentional Hilbert space, I only know (for instance) that the operator $A:Q_n\to Q_n$ is a self adjoint and a positive definite linear operator.
Comment: I edited the main post, thanks for your help =)
Answer: Assuming $f(t)$ is continuous, the existence and uniqueness of
$\dfrac{du}{dt} = Au + f(t), \tag{1}$
with
$u(0) = g, \tag{2}$
follows immediately as an application of the general theorems on existence and uniqueness for ODEs, which may be found, among other places, in Ordinary Differential Equations, by Jack K. Hale, published by Dover Press in 2009.  See Chapters 0 and I for a thorough discussion, especially Theorem 3.1 of section I.3.  Many other texts and treatises on ODEs also cover this material.
In the particular case at hand, in accord with the general theory (which may be found in Hale's book), existence and uniqueness follow from the Lipschitz continuity of the right-hand side in the variable $u$ and its continuity in $t$ which, since $Au$ is a linear map and $f(t)$ is continuous, are easy to establish.  Indeed for any linear map such as $A$, $\Vert Au_1 - Au_2 \Vert  \le \Vert A \Vert \Vert u_1 - u_2 \Vert$, which establishes the Lipschitz continuity of $u \to Au$.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!
Comment: Above answer supplied before the question was edited to stipulate $f \in L^2(0, T; Q_n)$.
Answer: The solution of your initial value problem is
$$
u(t)=\mathrm{e}^{-tA}g+\int_0^t\mathrm{e}^{-(t-s)A}f(s)\,ds.
$$
All graduate textbooks on ODEs study this extensively.
See for example:

Coddington & Levinson,
Hartmann.


TFS State Changed Date not Working

Question: We're using the Scrum 1.0 template for TFS. We're trying to do a work item query and I've noticed the State Changed Date for all of our items is empty. If I do a search for Changed Date, that works fine, but doesn't produce the desired results...
Why would this be the case?
Comment: I'm looking for the last date the state was changed....one would think this should be stored in the state changed date field........
Comment: It's unclear what results you are looking for then.
Answer:
Export the WIT (Task, Bug or Impediment) using the Process Editor or witadmin to a file.
Add the following block within the  element:
<FIELD refname="Microsoft.VSTS.Common.StateChangeDate" name="State Change Date" type="DateTime">
   <WHENCHANGED field="System.State">
     <SERVERDEFAULT from="clock" />
   </WHENCHANGED>
   <WHENNOTCHANGED field="System.State">
    <READONLY />
   </WHENNOTCHANGED>
 <HELPTEXT>Date and time that the value of the State field changed. </HELPTEXT>
</FIELD>

Save the file, and import it back to TFS using the Process Editor or witadmin..
Click the Refresh button on Team Explorer.
From this point forward changing the state of a work item will be queryable.
Comment: An answer with just a link isn't a good idea. Leads to link rot. Can you please restate/summarize the solution in your answer?

TFS State Changed Date not Working


You believe that there's a fly somewhere less then 6 feet away from you.

Question: You believe that there is a fly somewhere less than $6$ feet away from you. If you believe that he is located Uniformly in a circle of radius $6$ feet away from you, what is the probability that he is more than $2$ feet away from you?
My work:
This is clearly a continuous uniform distribution question, and I know that we need to account for area here for the density function since the fly is within a circular radius. So I believe we use the joint pdf $f(x,y) = \cfrac{1}{36\pi}$ to help us calculate the probability the fly is more than $2$ feet away from me since if I integrate over the area of the circle I get $1$. But I don't know where to go from here and how I can use this info to help me calculate the probability. Also what would the bounds of $f(x,y) = \cfrac{1}{36\pi}$ be? I know that $(x,y)$ would be whatever's in the circle, but what would that be?
Any help with finding the bounds or probability would be greatly appreciated!
Thank You!
Comment: Can the fly fly?
Comment: Are we to assume that you are $100\%$ certain in your belief?
Comment: Yes, I believe so, the textbook doesn't say but I believe it's implied, because I wouldn't know how to calculate it otherwise?
Comment: Hint: Try calculating the probability of the complement event, that is the probability that the fly is within $2$ feet from you.
Answer: First do a drawing

Your probability is simply the "favourable area" (purple area) divided by the "total area" (big circle area). Integration is not needed because the distribution is Uniform. Anyway if you want to integrate you will find the same result. Try it!
Simply do the ratio of the 2 areas to get the probability. It is easier to calculate the probability that the fly is LESS than 2 feet from you.... thus you requested probability is the complement
$$P[X>2]=1-\frac{\pi 2^2}{\pi 6^2}=1-\frac{4}{36}=\frac{8}{9}$$
Answer: Just for fun, you could do an integral in polar coordinates, where $dA=rdrd\theta$. That is how you would do it using the "uniform density".
$\displaystyle \int_0^{2\pi}\int_2^6 \frac r {36\pi} dr d\theta=\frac 1 {36\pi}\int_0^{2\pi}16d\theta=\frac{32\pi}{36\pi}=\frac 8 9$
Comment: You helped me swat a fly, +1. I hope that fly doesn't find its way to the downvote button.
Comment: Lol @TeresaLisbon


Sobrescrever dados em tabela com DataTables

Question: Toda vez que faço um change no select ele chama esta função, ela pega o id do imposto selecionado e faz as pesquisa pelas(filhas) regras de impostos, preciso atualizar a tabela toda vez que dá change porém acontece esse erro:
DataTables warning: table id=regrasimpostos - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
function pesquisaRegrasImpostos(imposto){
    if (imposto != "") {
        $.ajax({
            url: `/pesquisa/regraimposto/${imposto}`,
            success: function(data){
                $("#regrasimpostos").DataTable({
                    "processing": true,
                    "serverSide": true,
                    "ajax": `/pesquisa/regraimposto/${imposto}`,
                    "columns": [
                        {"data" : "impostoNome"},
                        {"data" : "modelo"},
                        {"data" : "pessoa"},
                        {"data" : "contribuinte"},
                        {"data" : "estado"},
                        {"data" : "cfop"},
                        {
                            "data" : null,
                            defaultContent: `<a href="#" title="Editar" data-id="impostoID" onclick="editarRegra('variavel')"><i class="edit icon"></i></a>`
                        }
                    ]
                })
            },
            error: function(error){
                alert(JSON.stringify(error));
            }
        });
    }
}

Comment: Se o datatables for `1.10.xxx` pode adicionar a opção `destroy: true,` no construtor.
Answer: Você não deve inicializar o componente mais de uma vez, assim como também não faz sentido realizar duas requições ajax para popular a tabela, veja que você faz uma no início da sua function e outra quando declara a url no atributo ajax do construtor do DataTable.
Inicialize o componente apenas uma vez, no carregamento da página, e utilize sua api para alterar o conteúdo, ajax.url().load().

$(document).ready(function() {
  $("#regrasimpostos").DataTable({
    "processing": false,
    "serverSide": false,
    "data" : null,
    "columns": [{
        "data": "impostoNome"
      },
      {
        "data": "modelo"
      },
      {
        "data": "pessoa"
      },
      {
        "data": "contribuinte"
      },
      {
        "data": "estado"
      },
      {
        "data": "cfop"
      },
      {
        "data": null,
        defaultContent: `<a href="#" title="Editar" data-id="impostoID" onclick="editarRegra('variavel')"><i class="edit icon"></i></a>`
      }

    ]
  });
});

function pesquisaRegrasImpostos(imposto) {
  if (imposto != "") {
    var datatable = $("#regrasimpostos").dataTable().api();
    datatable
      .ajax
      .url('/pesquisa/regraimposto/${imposto}')
      .load();

  }
}
@import '//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css'

      Nome
      Modelo
      Pessoa
      Contribuinte
      Estado
      CFOP

Comment: Muito bom amigo, show!!! valew!!


Change the actual file for Logins

Question: I have a site and I'd like to customize the login page. I'm using a customized version of the Stark Theme and I'd like to know if there is any way to change the actual file behind the login form so it looks a bit more uniform with the rest of the site. So without creating a new file and redirecting.
Any help?
Comment: You can do so with theme overrides but it depends on what you want to alter as to what you need to override. Is it the layout of the form you want to change, or the layout of the whole page, or something else?
Comment: what is different?
Comment: @rooby mainly looking to alter the layout and look, (link fonts, etc.). because the page layout was generated from my html.tpl.php
Comment: Look, and somewhat layout, can be modified just with css, but that is outside the scope of this site. You can also override the page.tpl.php specifically for that page.
Answer: You can try iTweak Login module to customize the login page. This module have so many settings to customize login form page as well as login block.
You can also try FreshLogin module. It will provide a complete different template.It  can customize as you want.

Change the actual file for Logins


Can I have the output of an audio interface redirected to a headset that's connected directly on the PC?

Question: I used to connect my guitar on my PC using a Rocksmith cable, and would use Guitar Rig 5 as my amp simulator.
I recently bought an Audio Interface (Behringer U-PHORIA UMC204HD) and I'm impressed that it greatly reduced the latency of what I hear on my headset.
However, my headset is USB, so I cannot connect it directly to the UMC204HD. I need to connect it to the PC and use ASIO4ALL to use the audio interface as the input device and my headset as the output device.
This works, but there is the downside that, when Guitar Rig 5 is running, I can only hear it on my headset and nothing else.
Is there a way to hear the output of the guitar and also hear the other applications running on the PC at the same time?
If so, would it increase my latency too much?
I'm new to all of this, so please let me know if I hadn't provided enough information on my question.
Edit: I've managed to make it work by using a virtual cable, setting the audio interface output as the input of the cable and my headset as the output. The problem with this approach is that it increases the latency A LOT, so it really disrupts my playing (especially fast licks).
Comment: I admire the enthusiasm, but I think pointing a muso to how to build a driver is like responding to "I need milk" with "First, build your cowshed…" :P
Comment: I suspect the magic happens at kernel level and not user level because I only got it working with virtual cable and a special asio driver and not the official asio driver from the maker. I think to get better latency you might need to either write a better kernel driver yourself (probably very advanced stuff) or buy a headset or adapter that has the right contact for the interface.
Comment: I think this is the page about writing drivers for windows https://learn.microsoft.com/en-us/windows-hardware/drivers/. But the other half of the problem is implementing the ASIO protocol and that I have no idea how to do at all.
Comment: The driver like this has already been implemented: https://github.com/dechamps/FlexASIO. Running it in shared mode is very likely to have worse latency than ASIO4All and much worse than the official ASIO driver.
Comment: @Tetsujin You'd be surprised to find out this muso is actually a developer, haha. However, I'm not skilled enough to write a kernel, at least not for now.
Comment: I think a huge proportion of Stack Exchange users are at least developer-adjacent :)
Answer: Your USB headset is a USB audio interface in itself, so what you're trying to do is, use one USB audio interface for audio input from the guitar, and another USB audio interface for audio output to the headset. This does not work very well, if at all. How well it works, or if it works at all, depends on at least your operating system (Windows, Mac OS, Linux), the drivers for the audio interfaces, and the applications (Cubase, Ableton Live, or whatever).
The real, actually working solution is to get non-USB headphones with a plain old analog audio cable, connect them to your audio interface's phones output, and use the same device for both input and output. This is the setup the ASIO system has been designed for.
Comment: Hey, thanks for the answer.
I thought about this, but I'm not sure I can find a wireless headphone with a p2 connection, at least not where I live (Brazil).
Answer: I actually made it work for me with a virtual cable. I tweaked around and managed to find a low latency setup, or at least low enough for me to play the songs I like. I'm sharing my configuration in case anyone comes across a similar problem.
I'm using the ASIO4ALL driver version 2.15 (though I think the latest version, whenever you're reading this, should work).
In my ASIO configuration, I have the corresponding input from the audio interface active, as well as the output of the virtual cable, as shown below. I've set the buffer size of 512 samples, which works just fine for my gear (if your latency is too high, try drecreasing the buffer size, but the audio might clip).

Then, on the Windows Volume Mixer, I've set the virtual cable input to be my audio interface's input and the output to be my headphones, as below:

Lastly, I've checked the box "Listen to this device" on the sound configuration of the virtual cable output.

I hope this helps whoever might run into the same situation.
Also, as @ojs mentioned, an alternative would be to use FlexASIO, though I haven't tested it.
Comment: If this means something like 25 ms latency or even more, and you're still happy with it, then ok, who am I to say you shouldn't do it. :) But if you try it with regular wired headphones connected to the same audio interface with a proper low latency, I think you'll be tempted to keep it that way and forget about the wirelessness.
Comment: Also, if you are using 512smp buffer at 192kHz, you could get the same latency with 128smp buffer at 48kHz, with less overhead (=less dropouts and possibly room to decrease your buffer even further)
Comment: For solutions like this, latency is always the killer. I'd recommend that OP measure their round trip latency if they go this route- I used a setup like this for some time and ended up with 25ms latency at best.  Better than not having sound, but I could never play 16th notes cleanly.  I've read that 12ms is about the upper limit of acceptable for a guitar, and I think that's about right.
Comment: The alternative, virtually latency-free alternative is wired headphones **plus** an interface that can do its own amp modelling. I have a Line6 UX2 from the early 2ks, with amp farm built-in, direct out as well as to DAW. I can put delay/rev etc on the headphones or control room without sending it to the track. Can't beat it. Same price as the Behringer these days, no longer supported on Mac [Mojave last working OS] but people say it still works on Win10.


Get printed value in ng-bind-html

Question: I need to get text, like is formatted on the ng-bind-html, but in an angular variable. Is a little hard to explain textually, see if is comprehensible in this code and fiddle:
var testApp = angular.module('TestApp', []);

testApp.controller('TestController', function($scope, $sce) {
    $scope.wrappedValue = $sce.trustAsHtml('asdf
°C
aaa
'); //this is my input
    var data = $scope.wrappedValue;
    console.log(data); //here I want to get printed: "asdf\n°C\naaa"
});

http://jsfiddle.net/r565nb2p/3/
I appreciate you attention reading this. Thank you
Comment: You can parse `wrappedValue` to drop HTML tags and keep only text.
Answer: I have made an example on CodePen.io that shows two different ways to get this text parsed.
First attempt:
var data = 'asdf
°C
aaa
';
var tempDiv = document.createElement('div');
tempDiv.innerHTML = data;
console.log(tempDiv.innerText || tempDiv.textContent);

As you can see in this attempt I use a tempDiv that is never added to the DOM. But, since we set innerHTML to hold the exact value on the data variable, we can call innerText/textContent on it.
First one's result diverges a little on what you want, it does not have a separate line for '°C'.
Second attemp
$timeout(function() {
    var iCanHaveAnId = document.getElementById('iCanHaveAnId');
    console.log(iCanHaveAnId.innerText || iCanHaveAnId.textContent);
});

This one results on three rows, as you expect. It takes advantage of $timeout to allow Angular to digest everything first and then go to the div#iCanHaveAnId, which is marked with ng-bind-html directive, and get its content.
Hopefully, one of those strategies will help you.
Comment: Good, thank you, I would prefer if don't have to use JS in the DOM, but I believe there is no other option

Get printed value in ng-bind-html


Visual Studio 2010 C++: malloc()/HeapAlloc always allocates new page for even smallest alloc size

Question: I have a rather large C/C++ project, and I have been trying to track down why it consumes an inordinate amount of memory (judged by the "Working Set" in the Task Manager).
I finally tracked it down to the bizarre behavior that, even for the smallest malloc() requests, it will allocate a full new 4k page.
Code like this
<code>    for(int bla = 0; bla < 1000; bla++)
    {
        char* blu = (char*)malloc(10);
    }
</code>
which should increase memory consumption by a measly 10KB, ends up racking it up by 4MB, since it does 1000 4kB allocations.
The really frustrating part is that I can't reproduce it as standalone. A small app just with the above code works fine. Only the big project exhibits the wrong behavior.
To answer some obvious suggestions right upfront:

I am pulling in the same libraries as the big project, and also made sure the compilation flags are the same
"new" behaves the same way
It happens both in Debug and Release mode
I really tracked it down to the HeapAlloc call which is the culprit. Sadly one can't step into HeapAlloc to investigate further.

Any ideas? I am totally stumped.
Comment: Just fyi whoever is reading this question and its answers later, this was not the issue (it was the heap page issue). The debug heap can do "padding" of mem allocs to detect buffer over/underruns, but it would never inflate mem allocation by a factor 1,000, like the page heap does.
Answer: Windows includes a feature called "Page Heap" which is helpful in locating memory corruption defects. It operates by placing each allocation on a page, which causes the processor to issue an access violation if the program corrupts memory instead of entering undefined behavior territory.
Sounds like somewhere in your big application someone has turned on page heap, or you have triggered some kind of application compatibility setting in Windows in your big application that enabled Page Heap.
Note that this is a Windows setting (HeapAlloc is a Win32 API), not a debug/release compiler setting.
Comment: Wow, thanks a million for your reply! It was actually a registry issue in the end, where my application was flagged as having page heap enabled. After deleting the registry entry it works normally now.


Solve a polynomial given the value of another polynomial

Question: If $$x^2−9x+5=0$$ then what is $$x^4−18x^3+81x^2+42$$
I know I can simply find what x is and plug it in, but given this is a practice question on a problem solving paper I know there is a 'smart' way to do it.
Can someone give a hint to how to approach these questions?
Answer: Hint: the smart way is to find a polynomial of $x^2 - 9x + 5$ which results in $x^4 - 18x^3 + 81x^2 + 42$. Try:
$$
(x^2 - 9x + 5)^2 + \text{_______} \cdot (x^2 - 9x + 5) + \text{_______}.
$$
where you have to fill in the blanks.
Answer: \begin{align}
   x^2−9x+5=0
      &\implies x^2 =               9x -   5 \\
      &\implies x^3 = 9x^2 - 5x =  76x -  45\\
      &\implies x^4 = 76x^2-45x = 639x - 380 \\
\hline
   x^4−18x^3+81x^2+42 &= \cdots
\end{align}
OR
\begin{array}{r}
                                &&&&&& x^2 &-9x &-5 \\
   &&&&--- &--- &--- &--- &--- \\
   x^2 &-9x &+5 &\mid &x^4 &-18x^3 &+81x^2 & +0x &+42 \\
                   &&&&x^4 & -9x^3 & +5x^2 \\
                   &&&&--- &---    &---    \\
                       &&&&& -9x^3 &+76x^2 & +0x \\
                       &&&&& -9x^3 &+81x^2 &-45x \\
                       &&&&&---    &---    &---  \\
                              &&&&&& -5x^2 &+45x &+42 \\
                              &&&&&& -5x^2 &+45x &-25 \\
                              &&&&&&---    &---  &---  \\
                                          &&&&&&&& 67 \\
\end{array}
So $ x^4−18x^3+81x^2+42 = (x^2−9x-5)(x^2−9x+5) + 67 = \cdots$
Answer: $x^2-9x+5=0$
$\Rightarrow x^2-9x=-5$
$\Rightarrow (x^2-9x)^2 = 25$
$\Rightarrow x^4 - 18x^3 + 81x^2 = 25$
$\Rightarrow x^4 - 18x^3 + 81x^2 + 42 = 67$
Answer: What I would do is use the first equation to get an expression first of $x^4$ in terms of the lower terms, then of $x^3$ similarily. Substituing in the second equation successively reduces the degree of the expression you want to compute, and may end up simplifying the whole thing. For the detailed process, see my spoiler below. This method may not be the most efficient, but it worked out without much efforts.

 Multiply the first equation by $x^2$: you will get an expression for $x^4$, that you can then substitute in the second. That is, we have
$$x^4=9x^3-5x^2$$
according to the first equation, so that
$$x^4-18x^3+81x^2+42=-9x^3+76x^2+42$$
Now, multiply the first equation by $x$ to get an expression of $x^3$:
$$x^3=9x^2-5x$$
and hence, substituing in the second equation, we obtain
$$-9x^3+76x^2+42=-9(9x^2-5x)+76x^2+42=-5x^2+45x+42$$
Now, notice that $-5x^2+45x=5(-x^2+9x)$ which, according to the original first equation, simplifies to $5\times 5 =25$. Hence, we obtain as a final result
$$x^4-18x^3+81x^2+42=25+42=67$$


Finding a derivative of the Sine integral

Question:
We have a function $$F(x) = \int_{x}^{x^2} \dfrac{\sin t}{t} dt$$ Find $F'(x)$ for $x \in (1, \infty)$.

I was wondering how to do this. The integral $\int \dfrac{\sin t}{t} dt$ can't be written down in terms of elementary functions, I think. So I don't know how to get a meaningful result from that.
Comment: Split the integral into $-\int_a^x+\int_a^{x^2}$; then use the Fundamental Theorem of Calculus.
Comment: https://en.wikipedia.org/wiki/Leibniz_integral_rule
Answer: Let $H(x)=\int_1^x\frac{\sin t}{t}dt$ an antiderivative of the function $t\mapsto \frac{\sin t}{t}$ then
$$F(x)=H(x^2)-H(x)$$
and by the chain rule you get the desired result.
Answer: the first derivative is given by $$-{\frac {\sin \left( x \right) }{x}}+2\,{\frac {\sin \left( {x}^{2}
 \right) }{x}}
$$
Answer: You can Use Newton, Leibnitz Theorem, for Differentiation under Integral Sign.
$$F(x) = \int_{x}^{x^2}\frac{\sin t}{t}dt\;,$$ Then Differentiate both side w r to $x\;,$ We get
$$\frac{d}{dx}(F(x))= \frac{d}{dx}\left[\int_{x}^{x^2}\frac{\sin t}{t}dt\right] = \frac{\sin x^2}{x^2}\cdot \frac{d}{dx}(x^2)-\frac{\sin x}{x}\cdot \frac{d}{dx}(x)$$
$$F'(x) = \frac{2\sin x^2}{x}-\frac{\sin x}{x}$$
Answer: HINT: If $$F(x)=\int_{\psi(x)}^{\phi(x)} f(t) dt$$ then $$F'(x)=\phi'(x)f(\phi(x))-\psi'(x)f(\psi(x))$$


DAMP / Aquia Dev (mac) apache fails on import of drupal core 7

Question: I'm attempting to switch from Bitnami to Aquia Dev Desktop for the mac (OS 10.8.2). I'd like to be able to develop a couple sites (using core drupal - not the aquia distro) simultaneously in a reliable environment.

Ran the uninstaller on Bitnami and checked that all files were
deleted.
I successfully installed Aquia Dev Desktop, saw that Apache and
MySQL servers were both running, and got the local Aquia Drupal site
when I clicked "Go to my site" in the control panel. So everything
was working fine.
Downloaded Drupal 7 to a folder on my desktop, decompressed, renamed the drupal
folder to my site name (all lower case and no special characters),
and reset the folder permissions to "Read & Write" and applied to
all enclosed folders.
I attempted to import into Aquia Dev Desktop but got "Error -
Process 'Apache Web Server' failed to start".

I tried using the settings panel in Aquia Dev Desktop to reset port from 8082 to 8080 but apache still won't start.  Tried a few other port numbers and no luck.
Here's the complete Apache error log:

[Fri Apr 05 15:05:54 2013] [notice] Apache/2.2.23 (Unix) PHP/5.2.17
  configured -- resuming normal operations [Fri Apr 05 15:06:37
  2013] [notice] caught SIGTERM, shutting down [Fri Apr 05 15:06:43
  2013] [notice] Apache/2.2.23 (Unix) PHP/5.3.18 configured -- resuming
  normal operations [Fri Apr 05 15:16:41 2013] [notice] caught
  SIGTERM, shutting down

I have very little experience with server administration or apache configuration.
Can anyone point me in the right direction?
Answer: This turned out to be a bug in Dev Desktop.  The good folks at Acquia fixed the bug and posted a new version that works nicely.


Decouple backbone.js and jquery

Question: I am evaluating whether I should use BackBone.js
I am only interested in the nice structure of BackBone.
But hesitant to use jQuery for the backend (since i have other JS library used).
Is it true that to use backbone we "must" include jQuery as dependency..?
Comment: "Backbone's only hard dependency is Underscore.js ( >= 1.4.3). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( >= 1.7.0) or Zepto."  <= http://documentcloud.github.io/backbone/
Comment: possible duplicate: http://stackoverflow.com/questions/10241831/is-backbone-js-hard-dependency-on-jquery
Answer: Pretty good question I've asked myself a lot. Basically it's not a problem to exclude jQuery or Zepto, but only if you don't need sync or any Backbone.View.
Backbone uses jQuery.ajax for syncing, which is hard to create manually ( if you want cross-browser support ), and also DOM events, which are heavily integrated in any Backbone.View. Also there is some jQuery related to Backbone.History.
The problem persist anywhere you need those Backbone features, which is almost the ground Backbone functionality.
Comment: thanks drinchev, unfortunately it's hard to get rid of AJAX call. Is it configurable in Backbone to use other AJAX library?
Answer: no backbone isnt dependent on jquery to be used.. its an independent library
Backbone's only hard dependency is Underscore.js ( >= 1.4.3). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( >= 1.7.0) or Zepto.
present here
Comment: You are not right about that. You can exclude jQuery, but your views and sync won't work.
Comment: the question was JQUERY SPECIFIC
Comment: Sharma, thank you for your insight. So you're saying we could use Backbone + Zepto, and all is good in terms of AJAX data fetching?
Comment: by default it uses jquery ajax for fetch/sync but can be overridden and the process is well documented. http://backbonejs.org/#Sync

Decouple backbone.js and jquery


O que são closures e qual sua utilização?

Question: A resposta desta pergunta sobre lambda O que são lambda expressions? E qual a sacada em usá-las? fala sobre closures e expressions tree, contudo, não possui um exemplo claro sobre o que são de fato e qual sua principal utilização. Então, o que são closures e em que situação é importante utilizá-las?
Comment: Relacionado: [closures em Javascript](http://pt.stackoverflow.com/questions/1859/como-funcionam-closures-em-javascript) :) BTW +1
Answer: Conceito
Closure (ou no português, clausura) é uma função que referencia variáveis livres no contexto léxico (tirei isso deste artigo na Wikipédia). Ou seja, é uma função que referencia, por exemplo, variáveis que não estão declaradas em seu corpo.
Normalmente clausuras são anônimas e existem apenas no corpo de outro método.
Por exemplo:
public Fruta FindById(int id)
{
    return this.Find(delegate(Fruta f)
    {
        return (f.Id == id);
    });
}

Neste caso, delegate(Fruta f) { ... } é uma clausura, que referencia a variável id declarada no corpo de FindById (outra função).
Uma clausura pode ser atribuída para uma variável:
Action acao = delegate { Console.WriteLine(umaStringQualquer); };

E ativada em algum momento específico da função ou método:
acao();

Utilização
Suponha que vou usar o método Distinct() implementado em IEnumerable que exige que seja escrito para ele uma classe de comparação como esta:
class Comparador : IEqualityComparer<Fruta>
{
    public bool Equals(Fruta x, Fruta y)
    {
        if (x.Nome == y.Nome)
        {
            return true;
        }
        else { return false; }
    }

    public int GetHashCode(Fruta fruta)
    {
        return 0;
    }
}

Funciona, mas é um pouco prolixo. Com uma clausura, posso utilizar não o Distinct, mas uma extensão de classe mais ou menos assim:
public List<Fruta> AcharMinhaFruta(Fruta fruta)
{
    return minhasFrutas.Select(f => delegate (f) { return f.Nome == fruta.Nome; } ).ToList();
}

Comment: @Vinícius Árvores de Expressão são outras coisas. Melhor abrir outra pergunta.
Comment: Existe alguma relação de Closure e Expression trees? Devo abrir uma outra pergunta para o que são expression trees, ou estas estão interligadas com closure, de fato?


Show $ \lim_{n\rightarrow \infty} 2^{-1/\sqrt{n}}=1$

Question: I am tasked with proving the following limit:
$$ \lim_{n\rightarrow \infty} 2^{-1/\sqrt{n}}=1$$
using the definition of the limit. I think I have done so correctly. I was hoping to have someone confirm my proof. Here is my reasoning:
We want
$$ \left| 2^{-1/\sqrt{n}} - 1 \right| < \epsilon $$
for $\epsilon >0$ given. Rearranging, we have
$$ \left| 2^{-1/\sqrt{n}} - 1 \right| = \left| \frac{1-2^{1/\sqrt{n}}}{2^{1/\sqrt{n}}} \right| \leq \frac{1-2^{1/\sqrt{n}}}{2^{1/\sqrt{n}}} < \epsilon $$
by the Triangle Inequality and since we are forcing this quantity less than $\epsilon$. Rearranging again, we obtain
$$ 1 < 2^{1/\sqrt{n}}\left(1+\epsilon\right) $$
$$ \Rightarrow \ln \frac{1}{1+\epsilon} < \frac{1}{\sqrt{n}} \ln{2} $$
$$ \Rightarrow n > \left(\frac{\ln{2}}{\ln{\frac{1}{1+\epsilon}}} \right)^2 $$
where the inequality sign flipped since $ln\left(\frac{1}{1+\epsilon}\right)$ will be negative for all $\epsilon >0$. The proof should be straightforward:
Proof Let $\epsilon >0 $ be given. Define $N\left(\epsilon\right)=\left(\frac{\ln{2}}{\ln{\frac{1}{1+\epsilon}}} \right)^2$. Then,
$$ n>N\left(\epsilon\right) \rightarrow \cdots \rightarrow \left| 2^{-1/\sqrt{n}}-1\right| < \epsilon $$ QED.
Does this logic seem correct?
Thanks!
Comment: Indeed, if $n>0$, then $2^{\frac{1}{\sqrt{n}}}>1$, so the quantity on the right is negative. An absolute value can't be less than a negative.
Comment: I don't see why this inequality is valid. $$ \left| \frac{1-2^{1/\sqrt{n}}}{2^{1/\sqrt{n}}} \right| \leq \frac{1-2^{1/\sqrt{n}}}{2^{1/\sqrt{n}}}  $$

If $n>0$, I don't think this isn't true. (I hope I'm not having a brain fart)
Comment: ... and if $n<0$, then you can't take its square root anyway.
Comment: Also, $\frac{1}{1+\epsilon}<1$, so its log is negative.  If you divide both sides of an inequality by this negative quantity, the inequality reverses.
Answer: Hint:
Show that $|1 - (1/2)^{1/\sqrt{n}}| \leqslant 2/\sqrt{n}$ using the Bernoulli inequality.
Answer: $2^{-\frac{1}{\sqrt{n}}}={\mathrm e}^{\ln(\,2^{-\frac{1}{\sqrt{n}}})}={\mathrm e}^{-\frac{1}{\sqrt{n}}\ln(2)}=1+{\mathcal O}(\frac{1}{\sqrt{n}})$
Answer: Your logic is correct (minus a few minor problems).
If $n>0$, $2^{-1/\sqrt{n}}$ is always less than 1, so $2^{-1/\sqrt{n}}-1$ is always negative. Assuming $0<\epsilon< 1$,
$$\begin{align*}
\left|2^{-1/\sqrt{n}}-1\right|&=-(2^{-1/\sqrt{n}}-1)\\
&=1-2^{-1/\sqrt{n}}\\
&\leq\epsilon\\
\end{align*}$$
And now we can do some rearranging.
\begin{align*}
2^{-1/\sqrt{n}}\geq1-\epsilon\\
2^{1/\sqrt{n}}\leq \frac{1}{1-\epsilon}\\
\frac{1}{\sqrt{n}}\ln 2 \leq -\ln( 1-\epsilon)\\
n\geq \left(\frac{\ln 2}{\ln (1-\epsilon)}\right)^2
\end{align*}
Comment: I think the other answers are better though. Definitely try them out.
Answer: The minus sign is not essential, we can remove it by inversion. We can assume $n$ to be a perfect square (as $2^{1/\sqrt n}<2^{1/\lfloor\sqrt n\rfloor}$) and study
$$\lim_{n\to\infty}2^{1/n}.$$
Then,
$$\frac{2^{1/n}-1}{2-1}=\frac{2^{1/n}-1}{(2^{1/n})^n-1}=\frac1{(2^{1/n})^{n-1}+(2^{1/n})^{n-2}+\cdots1}<\frac1n.$$


Chopin notation question / what notes do I play?

Question: I am trying to learn Chopin's Op10 no5 ("black keys") [I know it is too advanced for me, but I just enjoy the piece].

The 8--- notation in the first measure of the attached, I believe means play the relevant notes an octave higher? If so, does it only apply to the final b?
The second measure, do I actually play those notes as written on the staff? I ask this because when I see any performances of this piece e.g. on YouTube, they are playing the notes an octave lower??

I usually just play the first measure as written and have been putting the final b in measure one an octave higher and then playing the second measure as written, but am not sure if that is correct, looking at YouTube performances.
Thanks.
Comment: haha 6 flats -- just detune the piano and use the white keys :-) .    //this is purely a joke;  all performers on transposed instruments will understand.
Comment: piano scores makes my eyes hurt, golly look at all those NOTES )-;;
Comment: @NeilMeyer  you should look at the parts for any instrument in Paganninni,   Stravinsky, Zappa,  Miles Davis, ...   .
Comment: Are you *sure* the YouTube performances of this etude play the second measure one octave lower than written, left hand and all? I find this dubious given my memory of the recordings of this piece I recall, which play the second measure as written.
Answer: 8, or 8va means, as you say, play one octave higher than written. It saves all those ledger lines. It starts its effect on the first note and goes for all twelve. The 2nd note in the 2nd bar is exactly the same B♭ as the last note in the first bar.
All the notes in bar 2 are played as is. No octave move for any. And - it's only the right hand notes that are affected by the 8.
As pointed out by Aaron, the effect starts at the figure 8, and continues through until the end of the dotted line, in all music - for this section, bar 1.
Comment: More specifically, the marking remains in effect for the duration of the dotted line.


Database connection "Mysql" is missing and mysql.sock is missing

Question: I was trying to generate model code from cake command line tool. But got this issue.
Warning Error: PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) in [/Users/test/Google_WWW/project_name/lib/Cake/Model/Datasource/Database/Mysql.php, line 177]

Error: Database connection "Mysql" is missing, or could not be created. (although it's showing that mysql database is connected at localhost in cakephp directory)

I'm using MAMP.
I searched a lot and found some solutions. For instance,this
   CakePHP: No such file or directory (trying to connect via unix:///var/mysql/mysql.sock)
or I can also make a symbolic link of mysql.sock.
/Applications/MAMP/tmp/mysql/mysql.sock (not present in directory)

But before i do anything, the problem is mysql.sock file isn't present in this directory. I have tried re-installing the MAMP but still no mysql.sock.
Please help me solve this problem ? Can I create my own mysql.sock file..?
Edit: My db config
public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => 'root',
    'database' => 'db_name',
    'prefix' => ''
);

Comment: can you please post your database configuration parameters?
Comment: edited my question, one thing I must say that database is connected without any issues. But for creating model via cakephp cli, it uses mysql.sock that's not present in mamp folder I mentioned.
Comment: what if you try 127.0.0.1 instead of localhost?
Comment: No, still same issue.. Thanks for the reply though !
Answer: MAMP is strange when it comes to mysql. Chances are you need to set up a symbolic link so it knows where to find it. Something like:
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock
Comment: To use it with php-cli, after creating the symbolic link, edit your php.ini: `pdo_mysql.default_socket= /tmp/mysql.sock`, `mysql.default_socket = /tmp/mysql.sock`, `mysqli.default_socket = /tmp/mysql.sock`
Comment: bravo, your solution really work. i stuck in this problem for almost 2 weeks
Comment: Thanks for the reply. I did create a symbolic link but my problem wasn't solved.
Comment: the file is not created at all in my case. can you please tell me how to get mamp to generate the file? but phpmyadmin works perfectly fine
Comment: The blog link above does not work. Also this symlink solution is aimed at MAMP, not MAMP PRO
Answer: After searching and trying a lot of things I finally managed to solve my problem. The answer Chuck Burgess given above could solve the problem, but my scenario was little different that I wasn't able to see mysql.sock file at:
    /Applications/MAMP/tmp/mysql/mysql.sock

I thought my mysql.sock was missing but actually it was there and hidden (THAT's STRANGE! I WENT TO THAT FOLDER using CLI AND SAW THAT). I'm using MAC and files starting with '.' are usually HIDDEN but don't know why mysql.sock was hidden so what I did is in my database configuration file I added 1 parameter (unix_socket) and my problem was solved.
   'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock'

Comment: same here its hidden and can see it via cli. but when i add the unix_socket still i dont get connected.
Answer: In my case it was because I was calling the wrong version of PHP. I.e. I was using /usr/bin/php which when MAMP Pro's php is /Applications/MAMP/bin/php/php5.3.29/bin/php
Comment: Man how do you do this
Answer: I've been struggling with this the whole weekend and finally solved it. Turns out that the php.ini is pointing to a non-existing "extensions dir". Create a phpinfo() file and look at the value of this field:

I noticed that in the mamp php installed folder there is a no-debug-non-zts-20131226 folder, which is different from the value shown in the phpinfo(). What I did was to clone this folder and changed the name to the value of the phpinfo(). Probably you could modify the php.ini file but I didn't want to.
I see that you solved your problem but mine was different so I'm posting this answer to help future googlers looking for a similar problem.
Hope this helps.
Answer: In my case the problem appear just after a power outage. So I fixed it by deleting the /Applications/MAMP/tmp/mysql/mysql.pid file and restarting MAMP.
Comment: this broke my mamp :-(
Answer: With MAMP create a symbolic link in the folder /var/mysql/:
sudo ln -n /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock
Answer: Same problem here, but managed to resolve it connecting to IP:Port, not socket.
'host' => '127.0.0.1', //use 126.96.36.199 instead of localhost
'port' => '8889', //default MAMP MySQL devel port, default production port is 3306

and forget about socket connection.


Question on Separated set

Question: Consider two separated sets $A$ and $B$ of $R^k$. If $a $$\in $$A $ and $b $$\in $$B $ then
$p (t)=(1-t)a+tb$.
Now consider $C=p^{-1}(A) $ and $D=p^{-1}(B) $.
Now prove that  $C $ and $D $ are separated in $R $.
Is it even true. I mean the can have many values. And not necessarily all of the values are gonna lie in same set?? Am I missing something??Any help would be appreciated.
Comment: Are $p$ and $P$ the same?
Comment: Thanks for observing the mistake. Yes they are same
Answer: If they were not separated in $\mathbb{R}$, there would be real sequences $(a_n)$ and $(b_n)$ with $p(a_n)\in A$, $p(b_n)\in B$ and $\lim_{n\to\infty}|a_n-b_n|=0$.
But then we have that
\begin{align}
\lVert p(a_n)-p(b_n)\rVert&=
\left\lVert (1-a_n)\cdot a+a_n\cdot b - \big[(1-b_n)\cdot a+b_n\cdot b\big]\right\rVert\\
&=\left\lVert (b_n-a_n)\cdot a+(a_n-b_n)\cdot b\right\rVert.
\end{align}
Since the norm $\lVert\cdot\rVert$ is continuous this would imply that $\lim_{n\to\infty}\lVert p(a_n)-p(b_n)\rVert=0$, which would contradict $A$ and $B$ being separated in $\mathbb{R}^k$. It follows that $C$ and $D$ must be separated in $\mathbb{R}$.

Question on Separated set


SQL Server 2008 R2 and copy-only default value in SQL Server Management Studio

Question: We are using Tivoli Storage Manager for taking backups of the database but sometimes our consultants need to take separate backup copies of the database using Management Studio. If they forget to mark the "copy-only" flag in Management Studio they will mess up the Tivoli's backups (we are running our databases in FULL-recovery mode).
Is there a way to set the default value of the Copy-Only flag to true in the Management Studio's "Back Up Database"-window?
Answer: Usage of SQL Server Management studio is obligatory?
Prepare a database backup SQL script with all necessary options (BACKUP DATABASE ... WITH COPY_ONLY) and create a shortcut starting sqlcmd utility with this script for this consultant.


Using composer to replace changed files in a library

Question: I was trying some things out with an installed library and ended up changing a few files. I'd like to revert these back to their original state. I know I could just delete the library and install it again but was wondering if there is a composer command to just replace the edited files only. I'm thinking in terms of something like "git reset --hard HEAD" or the like.
Answer: If the library was installed from a zip file no it's not possible. Deleting the vendor/foo/bar directory and running composer install is the easiest way. If you have a git clone of the vendor though then obviously you can git checkout . to reset everything.
Comment: is this still the case?


Why was Japan's second goal in the WC 2022 Japan-Spain match deemed to be valid?

Question: During the 2022 FIFA World Cup match between Japan and Spain, Japan's second goal, scored by Ao Tanaka, was scored after the ball had seemingly gone out of play and been dragged back in by Kaoru Mitoma:

Why was this goal deemed to be valid?
Answer: According to Law 9.1 of The Laws of the Game (emphasis mine):

The ball is out of play when:

it has wholly passed over the goal line or touchline on the ground or in the air

From the angle shown in the question, it does indeed seem as though the ball is out of play. However, from this aerial view, we can see that part of the ball is still just barely on the line, not over it. As a result, the ball is still in play, and the goal is valid. It's really, really close, I grant you, but I think the right call was made as per the Laws of the Game.
Comment: even in that angle the camera isn't completely overhead, a camera in line with the line would show a larger (though still very small) overlap
Comment: @ScottishTapWater But doesn't the question of whether it touches the line give rise to exactly the same sort of dispute as to whether it is over the line? There remains the problem of the overhanging part, which must be exacerbated in rugby with the oval shape.
Comment: And this is why the way rugby does it is better... If any part of the ball touches the line it's out. It's far easier to tell that than when a round object has completely passed over it
Comment: @WS2 No, the overhanging part isn't touching the line is it? It's in the air...
Comment: A rugby ball doesn't roll flat on the grass at all; a football does, very often. Judging whether the football has touched the line drawn on deformed grass or non-deformed grass or rough dirt or on any other surface that isn't perfectly flat is just shifting the challenge to an even worse situation, since you can't even see the ground under the ball.
Answer: See this tweet for the video that match officials used the goal line camera images to check whether the ball was still partially on the line.
https://redd.it/za20rz shows that the ball was still in the game:

This tweet shows a nice simulation to understand 3D:
Comment: While I think everyone agrees it was close one way or the other, I'm not sure that tweet actually shows much. You could reasonably move both the red and blue lines by their width and get a different result.
Comment: The photo shows that the ball was (just) "in" at the moment in time when the photo was taken. It doesn't prove that it was "in" a millsecond earlier or a millesecond later. The fact is, however precise your observations, there are going to be situations that are undecidable, and we then have to turn to whatever clauses in the rule book say who should get the benefit of the doubt...
Comment: Incidentally, I play croquet, where this decision only has to be made for a stationary ball rather than a moving one. Yet I once had three referees spend 10 minutes examining a stationary ball and eventually deciding it was too close to call, and invoking the rule that the striker of the ball gets the benefit of the doubt.
Comment: How do we know that the top image was taken from directly overhead, above the line and perpendicular to the ground?
Comment: @MichaelKay see https://mobile.twitter.com/FIFAcom/status/1598702362243104768?ref_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed%7Ctwterm%5E1598702362243104768%7Ctwgr%5Eddb8d45507cc76312f1a93a6c554ad1e932e76e8%7Ctwcon%5Es1_&ref_url=https%3A%2F%2Fwww.espn.com%2Fsoccer%2Ffifa-world-cup%2Fstory%2F4822287%2Fwhy-japans-winning-goal-vs-spain-was-awarded-by-the-var for the video that match officials used the goal line camera images to check whether the ball was still partially on the line.
Comment: @PhilipKendall agreed, the tweet only demonstrates plausibility by showing how 3D works.
Comment: @MichaelKay "It doesn't prove that it was "in" a millsecond earlier or a millesecond later." True, but the FIFA doesn't like when people share videos (they send DMCA takedown requests really easily). "There are going to be situations that are undecidable": why?
Comment: @MichaelKay Human eyes are limited. I believe some tools offer more accurate measurements.
Comment: @FranckDernoncourt because any measuring apparatus has finite precision. I don't know if the actual line is defined by the white paint on the grass or by some laser beam, but either way, it's not a zero-width mathematical straight line.
Comment: @MichaelKay let's ask: [Are the actual lines on the ground defined by the actual white paint on the grass or by some laser beam?](https://sports.stackexchange.com/q/28530/1832). "because any measuring apparatus has finite precision" true but in most cases they'll solve the pb when the human eyes can't.


Django Rest Framework Related Model Permissions

Question: I'm using DRF to build a simple API. I've 3 related models, User, Device, Data. (One-to-many relation between User-Device and Device-Data)
I've a problem about permissions. Right now, for User-Device relation, authenticated users can only view or edit their own Devices. (And when they create a Device, the relation is automatically established.)
I want users to be able to view, create or edit Data only for their devices. For example, a user can't create a Data or view a Data of a device that doesn't belong to him. I couldn't figure out what is the correct way to achieve this. Can you help me with this?
Here is my views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, permissions
from iot_cloud_app.serializers import *
from iot_cloud_app.permissions import IsOwner

# Create your views here.

class DeviceViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows devices to be viewed or edited.
    """
    serializer_class = DeviceSerializer
    permission_classes = (
        IsOwner,
    )

    def get_queryset(self):
        """
        Filter devices of the user that made the request.
        """
        return Device.objects.all().filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class DataViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows device data to be viewed or edited.
    """
    serializer_class = DataSerializer

    def get_queryset(self):
        """
        Filter data of devices that belongs to user who made the request.
        """
        return Data.objects.all().filter(device__user=self.request.user)

and serializers.py
from django.contrib.auth.models import User, Group
from iot_cloud_app.models import Device, Data
from rest_framework import serializers

class DeviceSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Device
        fields = ('id', 'name', 'type', 'code')

class DataSerializer(serializers.HyperlinkedModelSerializer):
    created = serializers.ReadOnlyField()
    modified = serializers.ReadOnlyField()
    class Meta:
        model = Data
        fields = ('id', 'device', 'payload', 'created', 'modified')

edit: permissions.py
from rest_framework import permissions

class IsOwner(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to do actions.
    """

    def has_object_permission(self, request, view, obj):
        # Permissions are only allowed to the owner of the device.
        return obj.user == request.user

Thanks.
Comment: Can you also add IsOwner permission class?
Comment: I added permissions.py.
Answer: Since you override get_queryset method of DataViewSet class, users will not have access for existing objects, they will see 404 error if object's device is not related to the user. If you need 403 error instead you can implement custom permission class same as IsOwner:
class IsDeviceOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        # Permissions are only allowed to the owner of the device.
        return obj.device.user == request.user

And use it in viewset:
class DataViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows device data to be viewed or edited.
    """
    serializer_class = DataSerializer
    permission_classes = (IsDeviceOwner,)

    def get_queryset(self):
        """
        Filter data of devices that belongs to user who made the request.
        """
        return Data.objects.all().filter(device__user=self.request.user)

To limit device choice on data creation you can implement serializer's validate_device method:
class DataSerializer(serializers.HyperlinkedModelSerializer):
    created = serializers.ReadOnlyField()
    modified = serializers.ReadOnlyField()
    class Meta:
        model = Data
        fields = ('id', 'device', 'payload', 'created', 'modified')
    def validate_device(self, value):
        if value.user != self.context['request'].user:
            raise serializers.ValidationError('Wrong device id')
        return value

Comment: @neverwalkaloner Thank you so much for the validate! This is actually the only way I found to restrict a (malicious?) user to create objects related to a parent objet they do not own. This is rather crucial detail. "has_object_permission" is called but not enforced (just returning False is not enforced) when creating a new object. And "has_permission" does not work because the object is not created yet. Without you "validate_device" function, a user could end up with a bunch of objects he never created. I also use uuid as pk. Incremental integer make it too easy to guess pk.
Comment: Thanks, it did the trick! For this case, why we need both a validator and a permission class? Basically, they're checking the same thing, and if I comment out permission part, it still works as I wished. (only allows creating data for owned devices)
Comment: @MertAkozcan yep, you dont really need permission since you've implemented `get_queryset` which already limited access to objects. But if you need to return 403 error instead of 404 you can use permissions instead of queryset.
Comment: Hi, when I use permissions instead of get_queryset, GET request to data endpoint returns all data records regardless of which user is logged in. Is there a way to prevent this? Thanks you very much for your help.
Comment: @MertAkozcan hm.. I thought it should work:( Try to override `get_object` instead as here: https://gist.github.com/blapid/359d120bcc73609a42cb
Comment: I'm not quite sure what I'm gonna write inside overrided get_object function. What happens in my case is that when a request comes to /data endpoint, it returns all data records unexpectedly. However when a request comes to /data/ raises permission exception as expected. Is this the same situation as in the link you provided?
Comment: @MertAkozcan do you have `get_queryset` method inside `DataViewSet`? You need to add it also.
Comment: What would happen if you don't want to reveal if the Device exists or not. So if you want to return the same message "The Device does not exist or you don't have access to it", instead of returning two different messages: "Wrong Device ID" (in this case) and "Invalid pk - object does not exist."


Windows 2008 dead server to windows 2012 Active directory move

Question: Our windows 2008 AD server has failed, but i am able to read the hard drive via a usb cradle.
We have got a new server now running windows 2012.
Is there anyway I can move the active directory?
Any help, gratefully received.
Thanks
James
Comment: Where's your other domain controller?
Answer: Q: Is there anyway I can move the active directory?
A: No there isn't.
Comment: Move? No. But possible reclaim? Maybe.
Answer: Do you have backups?  (It sounds like the answer is no, but...)  If so, restore the 2008 server (to a VM if necessary), add the 2012 machine as a second DC in the old domain, then demote and remove the 2008 server. Then raise the functional level of the domain on the 2012 DC.  For more details on this process, see MSDN.  This article might also help.
I would also recommend a second domain controller, to help prevent outages in the future.


Is there any way to extend kernel smoothing regression for extrapolation.

Question: Kernel smoother is a typical non-parametric regression method that can be used well for interpolation. However, it can not predict the data outside the range of training data. Why ? If we have a look at the prediction function :
https://en.wikipedia.org/wiki/Kernel_smoother
The prediction function $\hat{Y}(x_0)$ on the provided link  will be the average of positively weighted training output. Therefore,  $\hat{Y}(x_0)$ can not go over the range of training output. Is there any way to modify kernel smoothing regression for extrapolation ?
Thanks
Answer: You can smooth without strong assumptions on the functional form of the relationship (you need to assume the relationship is smooth and not too rapidly-varying). The data may go up a little, or up a lot, or stay fairly flat or go down, or oscillate, and a smoother can follow it -- smoothing methods achieve this by being adaptive enough to fit the main trend of the data but not so adaptive that they just interpolate noise.
You can't extrapolate without some pretty strong assumptions because there's no data there to adapt to. The values in this unseen set of values might go up a little, or up a lot, or stay fairly flat or go down, or oscillate ...

... but there's nothing to tell us which it might be (or indeed something else), unless you make suitable assumptions that might give some way of figuring it out and then your out-of-range predictions will rely on those assumptions.
Note that if I had the grey points and any one of the three sets of coloured points a kernel smoother would describe the smooth relationship using all the points very well -- it would fit both halves of the data, and everything would look just great. Now we cut off the coloured part. Which curve might you pick? What about fifty other smooth curves for the second half that I might have used but didn't?
You can modify smoothers in various ways to project, but if you project more than a couple of observations out they'll rely heavily on what, exactly, you do. That really shouldn't be done automatically because you'll need to rely on things like domain knowledge to make sensible choices about constraints (and you'll need some) on what the function can do and how it relates to the trends in the region of x-space that you have.
Comment: Thanks for your reply. Can you suggest how can we encode those smoothness assumption into the model? I am thinking Bayesian inference here, like the assumption can be encoded by a prior distribution but it is still not clear.
Comment: Kernel smoothers already *have* smoothness assumptions built in. Smoothness alone is patently insufficient (as the plot clearly demonstrates), because it only constrains the few values *very* close to the edge of the data -- beyond that, it could go pretty much anywhere.
Comment: Is there an interactive app on that shows extrapolations a) gray forward, b) red / green / blue backwards in time ?
Comment: The red green and blue points are simply three sets of data that are plausible smooth extensions of the grey one. There's no solid basis on which to prefer one to the other purely on "smoothness" grounds, since the possible future data values all "smooth + noise", even across the threshhold


Old Books with chord progression charts or matrices?

Question: I've heard that there are old books with chord progression charts that tell you which chords are likely/plausible to come after a given chord. A music teacher said there are charts that can get quite large.
One example I know of is Walter Piston's Harmony book, but the chart in the early chapter was quite small, and very basic/diatonic.
Answer: I'm not sure about an old chart that shows chord progressions. The ones you might be thinking of are mostly found in new textbooks, like this one from MusicTheory.net:

But you may be interested in Schoenberg's "Chart of Regions" from his Structural Functions of Harmony:

Here's a smaller, minor version of the chart:

And here's a colorized version of the original, almost as a type of heatmap:

Keep in mind that the charts will change depending on how "old" you mean. If you're looking for a chart with Roman numerals, for instance, you won't get one until at least the 19th century, since it wasn't until Vogler and Weber came along ca. 1800 and began using Roman-numeral notation.

There are other types of geometrical structures that show relationships between chords, like the Tonnetz:

The triangles create triads; the bold triangle C E♭ G, for instance, is a C minor triad. But something like the Tonnetz focuses more on distance between chords than on actually creating harmonic progressions. But the Tonnetz does lead towards something we call neo-Riemannian theory, where the notion of progression (through "transformations" like P, L, and R) is something a bit different:
Comment: Cool, did Weber or Vogler have charts?
Comment: I know of [at least one](https://thornepalmer.files.wordpress.com/2012/02/tableofkeyrelationships.jpg) from Weber, but again it's less about progressions and more about relationships between keys (not chords). I'm not sure about Vogler.
Comment: What about neo-riemmanian theories?
Comment: Good question; a lot of neo-Riemannian theory is based on the *Tonnetz* at the bottom of my answer; I'll add more right now.
Comment: Awesome. Can I ask where that last chart, and first chart was from?
Comment: It's just a chart someone made, but you can read more about what it means [here](https://en.wikipedia.org/wiki/Neo-Riemannian_theory#Triadic_transformations_and_voice_leading).
Comment: and the very first one?
Comment: I just searched online for "chord progressions chart" :-)
Comment: I'm pretty sure the first one is from https://www.musictheory.net/lessons/57. If it is, can we cite it correctly for future users?
Comment: @Dom Good call; just did!
Comment: The only reason I caught it is because I just used it in the answer I just wrote :).
Comment: I'm glad you did! That link actually doesn't work for me, but it might just be my browser...I'll check it out tomorrow on another computer and update it as needed.


PP-plots vs. QQ-plots

Question: What is the difference between probability plots, PP-plots and QQ-plots when trying to analyse a fitted distribution to data?
Comment: It seems wikipedia can help you out with this one: [probability plot](http://en.wikipedia.org/wiki/Probability_plot). [QQ plot](http://en.wikipedia.org/wiki/Q%E2%80%93Q_plot), [PP plot](http://en.wikipedia.org/wiki/P%E2%80%93P_plot). If you have a more specific question please clarify!
Answer: As @vector07 notes, probability plot is the more abstract category of which pp-plots and qq-plots are members.  Thus, I will discuss the distinction between the latter two.  The best way to understand the differences is to think about how they are constructed, and to understand that you need to recognize the difference between the quantiles of a distribution and the proportion of the distribution that you have passed through when you reach a given quantile.  You can see the relationship between these by plotting the cumulative distribution function (CDF) of a distribution.  For example, consider the standard normal distribution:

We see that approximately 68% of the y-axis (region between red lines) corresponds to 1/3 of the x-axis (region between blue lines).  That means that when we use the proportion of the distribution we have passed through to evaluate the match between two distributions (i.e., we use a pp-plot), we will get a lot of resolution in the center of the distributions, but less at the tails.  On the other hand, when we use the quantiles to evaluate the match between two distributions (i.e., we use a qq-plot), we will get very good resolution at the tails, but less in the center.  (Because data analysts are typically more concerned about the tails of a distribution, which will have more effect on inference for example, qq-plots are much more common than pp-plots.)
To see these facts in action, I will walk through the construction of a pp-plot and a qq-plot.  (I also walk through the construction of a qq-plot verbally / more slowly here: QQ-plot does not match histogram.)  I don't know if you use R, but hopefully it will be self-explanatory:
<code>set.seed(1)                           # this makes the example exactly reproducible
N = 10                                # I will generate 10 data points
x = sort(rnorm(n=N, mean=0, sd=1))    #  from a normal distribution w/ mean 0 & SD 1
n.props = pnorm(x, mean(x), sd(x))    # here I calculate the probabilities associated
                                      #  w/ these data if they came from a normal
                                      #  distribution w/ the same mean & SD

   # I calculate the proportion of x we've gone through at each point
props = 1:N / (N+1)
n.quantiles = qnorm(props, mean=mean(x), sd=sd(x))  # this calculates the quantiles (ie
                                                    #  z-scores) associated w/ the props
my.data = data.frame(x=x, props=props,              # here I bundle them together
                     normal.proportions=n.props,
                     normal.quantiles=n.quantiles)
round(my.data, digits=3)                            # & display them w/ 3 decimal places
#         x        props  normal.proportions  normal.quantiles
# 1  -0.836        0.091               0.108            -0.910
# 2  -0.820        0.182               0.111            -0.577
# 3  -0.626        0.273               0.166            -0.340
# 4  -0.305        0.364               0.288            -0.140
# 5   0.184        0.455               0.526             0.043
# 6   0.330        0.545               0.600             0.221
# 7   0.487        0.636               0.675             0.404
# 8   0.576        0.727               0.715             0.604
# 9   0.738        0.818               0.781             0.841
# 10  1.595        0.909               0.970             1.174
</code>

Unfortunately, these plots aren't very distinctive, because there are few data and we are comparing a true normal to the correct theoretical distribution, so there isn't anything special to see in either the center or the tails of the distribution.  To better demonstrate these differences, I plot a (fat-tailed) t-distribution with 4 degrees of freedom, and a bi-modal distribution below.  The fat tails are much more distinctive in the qq-plot, whereas the bi-modality is more distinctive in the pp-plot.
Answer: Here is a definition from v8doc.sas.com:

A P-P plot compares the empirical cumulative distribution function of a data set with a specified theoretical cumulative distribution function F(·). A Q-Q plot compares the quantiles of a data distribution with the quantiles of a standardized theoretical distribution from a specified family of distributions.

In the text, they also mention:

differences regarding the way P-P plots and Q-Q plots are constructed and interpreted.
advantages of using one or another, regarding comparing empirical and theoretical distributions.

Reference:
SAS Institute Inc., SAS OnlineDoc®, Version 8, Cary, NC: SAS Institute Inc., 1999

PP-plots vs. QQ-plots


Not able to fill the textboxes in frameset. ? how can i do that

Question: <code><html>
<head>
<script type="text/javascript">
   function load()
    {
      var the_form = parent.document.frames['myFrame'].document.forms['form1'];
       var source = the_form.elements['Login1_UserName'];
         var target = the_form.elements['Login1_Password'];
        alert('');
          }
 </script>
  </head>

 <frameset>
   <frame name="myFrame" src="http://xyz.com/" onload="load()" />
 </frameset>
  </html>
</code>
Answer: Your frame is on a different domain. Access to frames on different domains (or ports, or protocols) is prohibited by the Same Origin Policy.
Comment: I can access if its a normal java script and the web page is our own companys web page. but its made by third party
Comment: @Nivids yup, that's the  point of the Same Origin Policy. There's no easy workaround for it if you don't control the third party web site
Comment: but if we fire the script on the address bar it works how its possible with iframe it wont work


Hiding file extension and redirecting to https

Question: First off, I know there are many questions similar to this one. I've read everything I can find, but the solutions I see elsewhere don't seem to work for me. I'm really hoping someone can give me some insight here.
I am trying to use Apache's .htaccess directives to force specific pages on my server to use ssl. In addition to those directives, I'm also using some rewrites to mask .php and .html extensions.
I created a page, https-test.html. I want that page specifically to always get redirected so it uses https and so that .html gets stripped off, like https://www.example.com/https-test
However, I seem to always end up with a loop. Reading the Apache docs for 6 hours got me closer, but I'm still missing something.
Below is my annotated htaccess file.
RewriteEngine on

# If port is insecure...
RewriteCond %{SERVER_PORT} ^80$
# And requested URI is /https-test...
RewriteCond %{REQUEST_URI} ^(.*/)https-test$ [NC]
# Then point the server to the secure url:
RewriteRule . "https://www.example.com/https-test" [L,R]

# The next few lines try matching extensionless requests to .php files
# If the requested file is not a directory...
RewriteCond %{REQUEST_FILENAME} !-d
# And we CAN find a .php file matching that name...
RewriteCond %{REQUEST_FILENAME}\.php -f
# Then point us to that .php file and append the query string.
RewriteRule ^(.+)$ $1.php [L,QSA]

# These next few lines were added by the previous project owner
# They're supposed to redirect requests like /foo.html to /foo,
# But I suspect these might be the culprit

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)/$ /$1 [R=301,NE,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ /$1.html [NE,L]

# Next few lines are legacy SEO stuff, some pages were linked to as
# php but now are html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} .php$
RewriteRule ^(.*).php$ /$1.html [L,NE]

So that's the code I have in my htaccess. And if I go to http://www.example.com/https-test in Chrome, I get www.mysite.com redirected you too many times.
Answer: You should probably just rewrite the code a bit. You are trying to match both extensionless files to php and html and doesn't look like you're accounting for each of the conditions. You should add a condition to make sure they are not tryiing to do the same things.
Backup your code, replace your code with this and give it a try. Clear all your cache before trying.
RewriteEngine on
# If port is insecure... redirect for a specific page
RewriteCond %{HTTPS} !^on [OR]
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^http-test/?$ https://www.example.com%{REQUEST_URI} [R=301,L]

# Next few lines are legacy SEO stuff, some pages were linked to as
# php but now are html
RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.php
RewriteRule ^ /%1? [R=301,L]

# The next few lines try matching extensionless requests to .php files
# If the requested file is not a directory and php file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]

#remove trailing slash and is not a php file
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php !-f
RewriteRule ^([^\.]+)/$ /$1 [R=301,NE,L]

#finally redirect extensionless URI to html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ /$1.html [NE,L]

Note I haven't tested this fully.
Comment: Change 301, to 302 to clear the cache and see if that helps. If it works then you can change it back to 301.
Comment: Thanks so much. Your changes certainly make things cleaner and easier to understand.

Those rules work great for the `.php` and `.html` rewrites. Unfortunately, I'm still getting a redirect loop for `https://www.example.com/https-test`. I genuinely don't get it.
Comment: Cleared the heck out of my cache, tried different browsers, still getting a loop...
Comment: OK, so I started outputting some server info via PHP - even when using https, it's reporting https is "off" and port is 80. Wondering if perhaps there's some load balancing or other trickery going on that's causing my issues.
Comment: Thanks again for your help. Turns out the server environment I am in, on Rackspace, uses a load balancer or some other traffic routing, and the `%{HTTPS}` variable is unreliable - you have to use `%{ENV:HTTPS}`, per this link: https://support.rackspace.com/how-to/force-ssl-on-your-php-site/  - I'm going to post an answer to my own question in case it helps anyone else.
Comment: Yes if you are behind a load balancer you have to check differently. However didn't mention you were behind a load balancer. I personally let the load balancer handle the https and offload it there. That way I don't need to worry with it on the apache side. It will just forward the request to whatever port you specify. Also since my answer helped and is technically correct you could upvote/accept it.


Question about SVD and orthogonal matrices

Question: Let $X$ be a $m \times n$ matrix. By SVD, I obtain $X = UDV^T$, where $U$ and $V$ are both orthogonal matrices, and $D$ is a diagonal matrix.
I think the following is true (but not sure why):
$(VDV^T + aI_n)^{-1} = V(D + aI_n)^{-1}V^T$
where $a\in \mathbb{R}$ is some scalar, and $I_n$ is a $n\times n$ identity matrix. Can anyone explain to me why one is able to move $V$ to the left of the matrix inverse and $V^T$ to the right?
Answer: I don't know what the SVD has to do with it but yes, your manipulation is correct.
We are given that $D$ is diagonal and $V$ is orthogonal. Note that $V^{-1} = V^T$ and $(V^T)^{-1} = V$. So, we have
$$
\begin{align}
(VDV^T + aI_n)^{-1}
&= (VDV^T + V(a I_n)V^T)^{-1}
\\ & = (V(D + aI_n)V^T)^{-1}
\\ & = (V^T)^{-1}(D + aI_n)^{-1}V^{-1}
= V(D + aI_n)^{-1}V^T.
\end{align}
$$
Comment: Thanks, and it should be $(D + aI_n)^{-1}$ instead of $(D + aI_n)$ in the last line right?
Comment: Yes, that's right.
Answer: If $V$ is invertible,
$$(VMV^{-1}+aI)^{-1}=(VMV^{-1}+aVV^{-1})^{-1}=(V(M+aI)V^{-1})^{-1}=V(M+aI)^{-1}V^{-1}.$$
If, in addition, $V$ is orthogonal, this is
$$V(M+aI)^{-1}V^T.$$
Nothing else is required.


Relationship does not display related fields Laravel

Question: Using Laravel 5.4
I have 2 tables: origins and coffees.
The relations between them:
In Coffee model:
public function origin()
{
   return $this->belongsTo('App\Origin');
}

In the Origin model:
 public function coffee()
{
   return $this->hasMany('App\Coffee');
}

In my controller I have this method:
$origins = Origin::with(['coffee' => function ($query) {
            $query->where('active', 1);
            $query->orderBy('name', 'asc');
        }])->orderBy('name', 'asc')->get();

In my view:
@foreach($origins as $origin)
    {{ $origin->name }}

{{ $origin->coffee->name }}

@endforeach

I get this error:
Property [name] does not exist on this collection instance.
If I code:
@foreach($origins as $origin)
        {{ $origin->name }}

{{ $origin->coffee }}

    @endforeach

I get all the coffees that belong to the origin.
What am I doing wrong?
Answer: $origin->coffee is a collection, not a single object. Your models also tell us that one Origin model has many Coffee models.
To list all coffees in the current origin:
@foreach($origins as $origin)
    {{ $origin->name }}

    @foreach($origin->coffee as $coffee)

{{ $coffee->name }}

    @endforeach
@endforeach

Comment: Ah, funny, I thought I tried that option but I think I might have made some spelling mistakes or something because it also gave me an error. Anyway, copy and paste your solution and all is fine, thank you!