Solution to $x=100e^{-x/100}$?

Question: How do you solve $$x=100e^{-x/100}$$
If I use $\ln$ then $\ln(x/100)=-x/100$. How do I get from that to  $x=56.7$?
Answer: Not solvable in a closed form using algebraic functions. It is a typical and well-known trascendental equation that has as a solution a special function called the Lambert W function.
This function is defined as a principal branch of the solution of
$$xe^{x}=y\rightarrow x=W(y)$$
In your case, this is almost directly what you have. Rearrange:
$$\frac{x}{100}e^{x/100}=1$$
giving
$$x=100W(1)$$
You need to solve for it numerically, or call ProductLog in Mathematica, which implements this function.

A numerical solution is pretty straight-forward with a calculator. Write
$y=x/100$ and now you have
$$y=e^{-y}$$
Start somewhere reasonable (like $y=1$) and repeatedly plug it into this expression. You get a reasonable approximation in a few iterations: $1,0.3678,0.6922,0.5004,0.6062,0.5453,0.5796,0.5601,0.5711,0.5648,0.5684,0.5664,0.5675,\ldots$.
Comment: By the way, ${\rm W}_0 (1)$ is the well known Omega constant $\Omega$.
Answer: If you want to solve numerically $$f(y)=y-e^{-y}=0$$ you can use very fast numerical methods.
For example, Newton iterations will write $$y_{new}=\frac{y+1}{e^{y}+1}$$ Starting at $y=1$ will provide the following successive iterates : $0.537883$, $0.566987$, $0.567143$ which is the solution.
As another example, Halley iterations will write $$y_{new}=\frac{2 y+2 e^y (y+2)+e^{2 y} (y (y+2)+2)+3}{2 \left(e^y+1\right)^3}$$ Starting at $y=1$ will provide the following successive iterates : $0.566599$, $0.567143$ which is the solution.
Answer: As the function $x\to x+\log x$ is increasing and onto, there is a unique solution to the equation
$$
\log x = -x.
$$
This solution has no expression in terms of elementary functions.

The solution of your problem is obtained multiplying by 100.

Solution to $x=100e^{-x/100}$?


Nonlinear least squares transformation

Question: Suppose that I wish to estimate the parametes $\alpha$ and $\beta$
in the following regression model:
$$
Y=K^{\alpha}L^{\beta}\epsilon
$$
A standard procedure is to take logs and estimate
$$
\text{log}\left(Y\right)=\alpha\text{log}\left(K\right)+\beta\text{log}\left(L\right)+\text{log}\epsilon
$$
Now, even if $\epsilon$ is statistically mean independent of $K,L$
in the original multiplicative model, it is not necessarily the case
in the second model. This is because of Jensen's inequality, and the
fact that if there is heteroskedasticity in the original model, then
the conditional mean of$\text{log }\epsilon$ will vary, depending
on the form of heteroskedasticity, and if it is related to levels
of $K$ and $L.$ In that case, OLS will produce biased estiamtes
on $\alpha$ and $\beta.$ My question is as follows- in the original
model: can we not redefine the minimization problem as:
$$
\text{min}\sum_{i=1}^{N}\left(\frac{Y}{K^{\alpha}L^{\beta}}\right)^{2}
$$
to obtain NLS estimates instead? This should obviate the endogeneity problem in my opinion..is this OK?
Comment: I realized this is not a well-defined minimization problem: alpha and beta would be set to infinity in this process...
Comment: It's easy to see why: quadratic measures work best for simmetric errors around zero. your error is probably centered abkve zero
Answer: The mean independence assumption is mostly a technical assumption that guarantees some desirable properties of the OLS and other estimators.
This means that it matters to make it at the level of estimation. In other words, we first apply the logarithmic transformation and then we impose the assumption of mean-independence.
Another standard approach is to insert the error term as $e^{\epsilon}$ in the output function.

Nonlinear least squares transformation


What is the cause of an AABB error in Unity regarding Instantiated objects?

Question: Edited:
Image showing the error log. So I have a script which identifies the list of items, removes the current ones and then re-spawns the original objects. This works 80 percent of the time but spits out an AABB error the other 20 and I don't know what the cause is. Any ideas?
Comment: Please share the complete error message.
Comment: and code too please
Answer: The AABB is related to Bounding Box representing an axis aligned bounding box. Your AABB might not have proper alignment which is why you are receiving the error. There is a script that shows how your objects draw their bounding boxes so that you can set them up easily.
<code>using UnityEngine;
using System.Collections;

public class BoundingBox: MonoBehaviour
{
    void OnDrawGizmos()
    {
        Renderer rend = GetComponent<Renderer>();
        if (rend)
        {
            Gizmos.color = Color.yellow;
            Gizmos.DrawWireCube(rend.bounds.center, rend.bounds.size);
        }
    }

//If your object is not within the bounding boundaries, then you can set your mesh up manually like this;

     void Start()
     {
       var meshFilter = GetComponent<MeshFilter>();
       meshFilter.mesh.bounds = new Bounds(transform.position, new Vector3(10, 5, 1));
     }
}

</code>


Difficulty splitting bimodal data

Question: I'm working with a bimodal data set and need to split this bimodal data to 1) estimate the proportion of data points in each distribution and 2) the mean of each distribution.
I have approached this a couple ways, 1) by fitting mixed models, and 2) by estimating a cutoff value between the peaks. Fitting mixed models using a few packages in R (mixtools, mclust, and mixsmsn) worked well for me for a long time. However, I have new data where all of these methods have failed to fit my data. I've also tried various log transformations of my data, but I still can't get accurate fits.
I'm stumped. I've tried experimenting with providing estimated parameters for the model fits in mixtools, mclust, and mixsmsn but still no luck fitting. I think that every method I have tried thinks that the lower bimodal peak in the trouble data is just noise, but I know it is not!
Histograms of bimodal data:

link to bimodal data (no issue fitting)
link to trouble data
Answer: The assumption of those mixed models (at least mclust and mixtools::normalmixEM2comp) is that the data is a mixture of Gaussians. I think in your "trouble" case, the first peak is just not Gaussian enough. So, if you want to stay with approach 1, it might be possible to model your data as a mixture of a Gaussian and a point-probability. But this is not easy, I'm not sure R has ready-made functions for that purpose.
Looking at the histograms, it seems you have two nice peaks, well-separated with a big valley. In that case, it might be easier to look for the valley than to look for a mixture (your approach number 2). For example, here is a very simple and naive approach of smoothing the histogram and looking for a negative peak:
trouble_data <- read.csv("https://raw.githubusercontent.com/jenniferbethann/bimodaldata/main/troubledata.csv",
                header=TRUE)$trouble_data

troub <- log10(trouble_data)

hist(troub, freq = FALSE, breaks = 100)
smtroub <- density(troub)
lines(smtroub, col="darkblue")
abline(v = smtroub$x[which(peakPick::peakpick(-smtroub$y,neighlim = 1))],col="red")

Created on 2020-12-09 by the reprex package (v0.3.0)
Better approaches should exist, in particular those developed for image analysis. For example you can take a look at the methods available in ImageJ. The package autothresholdr provides them in R but requires the data to be integers and has problems if it doesn't start at 0. We can try to run it by transforming the data a bit more:
trouble_data <- read.csv("https://raw.githubusercontent.com/jenniferbethann/bimodaldata/main/troubledata.csv",
                         header=TRUE)$trouble_data

troub <- as.integer(1000*log10(trouble_data))
troub <- troub - min(troub)

hist(troub, freq = FALSE, breaks = 100)

# my previous method
smtroub <- density(troub)
lines(smtroub, col="darkblue")
abline(v = smtroub$x[which(peakPick::peakpick(-smtroub$y,neighlim = 1))],col="red")

methods <- c("IJDefault", "Huang", "Huang2", "Intermodes", "IsoData", "Li",
             "MaxEntropy", "Mean", "MinErrorI", "Minimum",
             "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag",
             "Triangle", "Yen")
auto_thresholds <- sapply(methods,
                          function(x) tryCatch(autothresholdr::auto_thresh(troub, x),
                                               error=function(e) NA))

abline(v=auto_thresholds,
       col="green")

Created on 2020-12-09 by the reprex package (v0.3.0)
So it looks like the InterModes method does perform well, the others not so much.

Difficulty splitting bimodal data


Related question to : If $u \in H^1(U)$, then $Du=0$ a.e. on the set $\{u=0\}$

Question: This problem was asked in here. I need to ask something.

Provide details for the following alternative proof that if $u \in H^1(U)$, then $$Du = 0 \text{ a.e. } \, \text{ on the set } \{u=0\}. $$
  Let $\phi$ be a smooth, bounded and nondecreasing function, such that $\phi'$ is bounded and $\phi(z)=z$ if $|z| \le 1$. Set $$u^\epsilon(x) := \epsilon \phi(u/\epsilon).$$ Show that $u^\epsilon \rightharpoonup 0$ weakly in $H^1(U)$ and therefore $$\int_U Du^\epsilon \cdot Du \, dx = \int_U \phi'(u/\epsilon) |Du|^2 \, dx \to 0.$$ Employ this observation to finish the proof.

I solved it under 2 assumptions: $U$ is bounded, and $C_c^{\infty}(U)$ is dense in $L^2(U)$. The proof is at below.
1) Is the assumtion that $U$ is bounded essential? If not, how to prove without this assumption?
2) Is it true that $C_c^{\infty}(U)$ is dense in $L^2(U)$ for any open set $U \subset \Bbb R ^n$? I guess this answer will be negative, since I found only that $C_c^{\infty}(\Bbb R ^n)$ is dense in $W^{1,p}(U)$ ($1 \le p < \infty$) if $U$ has boundary of class $C$ (Leoni, Thm10.29). But then how can I solve this problem?
My proof: To show $u^\epsilon \to 0 $ weakly in $H^1$, we need to show that $u^\epsilon, D_{x_i} u^\epsilon \to 0$ weakly in $L^2$.
For $v \in L^2$, $|| v u^\epsilon||_1 \le  ||v||_2 ||u^\epsilon||_2 \le ||v||_2 \epsilon M vol(U) \to 0$ (as $\epsilon \to 0$) since $|u^\epsilon| \le \epsilon M$ for some $M>0$. So $u^\epsilon \to 0$ weakly in $L^2$.
Since $C_c^{\infty}(U)$ is dense in $L^2(U)$, $\exists v_n \to v$ in $L^2$. Then $||(v-v_n)D_{x_i} u^\epsilon||_1 \le ||v-v_n||_2 ||D_{x_i}u^\epsilon||_2 \le ||v-v_n||_2 M' || D_{x_i}u ||_2$ since $|D_{x_i}u^\epsilon| = |\phi' D_{x_i}u| \le M' |D_{x_i}u|$. Since $\int v D_{x_i} u^\epsilon = \int (v-v_n) D_{x_i} u^\epsilon + \int v_n D_{x_i} u^\epsilon$ and $\int v_n D_{x_i} u^\epsilon= - \int u^\epsilon D_{x_i} v_n $, $D_{x_i} u^\epsilon \to 0$ weakly in $L^2$.
The result follows as in here
Comment: $C_c(U)$ is dense in $L^p(U)$ for all $p \in [1, \infty)$. Then you can use smooth functions to approximate continuous function. (Found in Rudin's real and complex anaylsis)
Answer: 1) If $U$ is not bounded, just write it as a countable union of open bounded sets, however, I don't see where you need to use the boundedness of $U$.
2) Yes, this is true and the proof can be found in a lot of places. For example, it can be found in Brezis book chapter 4.
Comment: In the proof, I used $\epsilon M vol(U) \to 0$. But if $vol(U)$ is not finite, this is not true.


Webform conditional calculation depending on selected options count

Question: Users register for a conference via a webform. There are options for choosing a city [mandatory] and 1-4 dates [at least 1 date has to be checked]. E.g. user checks NYC + 2015-08-07 and 2015-09-01.
The price for the conference bases on the days count: if all 4 days has been checked = X USD; if 1, 2 or 3 of 4 days = Y USD/day.
Now, I have to calculate the price based on total count of checked dates and send it to the user in confirmation e-mail. How to do it?
Answer: You have to use javascript for this and multiply the price with the number of days (the number of checkboxes checked).


How can I increase space on the Filesystem linux?

Question: I am renting a dedicated server with Parallel Plesk on it (which I hate and I try to use command line).
I have a filesystem that is full,"df -H" prints this:
Filesystem             Size   Used  Avail Use% Mounted on
/dev/md1               4.0G   4.0G   361k 100% /
/dev/mapper/vg00-usr   4.3G   1.4G   3.0G  32% /usr
/dev/mapper/vg00-var   4.3G   2.8G   1.6G  64% /var
/dev/mapper/vg00-home
                       4.3G   4.4M   4.3G   1% /home
none                   1.1G    24M   1.1G   3% /tmp
tmpfs                  1.1G      0   1.1G   0% /usr/local/psa/handlers/before-local
tmpfs                  1.1G      0   1.1G   0% /usr/local/psa/handlers/before-queue
tmpfs                  1.1G      0   1.1G   0% /usr/local/psa/handlers/before-remote
tmpfs                  1.1G      0   1.1G   0% /usr/local/psa/handlers/info
tmpfs                  1.1G      0   1.1G   0% /usr/local/psa/handlers/spool

The server I'm renting has 1TB of hard drive. Why are these so small, how can I increase my storage ? (I'm pretty beginner with Linux).
Thank you
Comment: it doesn't have to be /dev/md1, resizing /var would be great and I could move all to there.
Comment: my server is currently down as I wasn't fast enough, thank you for the answers but I'll accept one only after I get my SSH back :(
Answer: You are running LVM which should make this easy.  These devices which are mounted are "logical volumes" which are allocated from one big chunk of space called a "volume group".  Running vgdisplay should show you details about the volume group.  Here's what mine currenlty looks like, yours should look similar:
--- Volume group ---
VG Name               vg00
System ID
Format                lvm2
Metadata Areas        1
Metadata Sequence No  10
VG Access             read/write
VG Status             resizable
MAX LV                0
Cur LV                9
Open LV               2
Max PV                0
Cur PV                1
Act PV                1
VG Size               186.26 GiB
PE Size               4.00 MiB
Total PE              47683
Alloc PE / Size       39165 / 152.99 GiB
Free  PE / Size       8518 / 33.27 GiB
VG UUID               ekYzHp-b4n9-8971-nBBZ-kOfH-Cfd1-ZcEf12

The important bit here is the "Free PE" line which shows that we have some "Free physical extents" which can be allocated to our logical volumes. You can allocate space to a logical volume with lvresize.  perhaps something like lvresize --size +100M /dev/mapper/vg00-var to increase by 100 megabytes.
After resizing the logical volume, you'll have to resize the contained filesystem.  How to do this would be filesystem dependent.  If it is ext2/ext3/ext4, you would use resize2fs /dev/mapper/vg00-var.  And the changes should be immediately apparent.
Comment: ok I have done that, but now Apache is not starting by default (I have to do an apachectl -k restart each time I reboot the server), and mysql isn't working at all, mysql.sock was somewhere in /var and now its not there anymore
Comment: You would have to use `resize4fs` in case of `ext4`
Answer: Use du to see where your space is. Your space is unallocated if you you really have it. Try vgdisplay to see if it is in the LVM volume group. It might well be unallocated on your drives.
There are a lot of possibilities but I'd guess space would be in the volume group but unallocated. In this case use lvextend to give more space to the volumes you like. After volume is resized you can use resize2fs to online increase your the desired filesystem's space.
update: now I see md1 is out of space, easiest is to move your data off that filesystem. If that's not possible, please give a detailed information about space allocation on your devices (e.g. vgdisplay -v, fdisk -p, etc.)
Answer: You can re-size your /var by expanding your Logical Volume ==> Volume Group. Can you post your "vgdisplay" & "lvdisplay" outputs.


Plot residuals from a known linear model in R

Question: This question is similar to this one, where I would like to plot the residuals, except that my residuals are known, since I'm simply comparing simulated and observed values with an expected 1:1 linear relationship.
For example, consider a data.frame subset:
sub <- data.frame(observed=c(-0.75, 0, 1.84, -0.33, -1.6),
                  simulated=c(-0.73644, 0.00422, 1.69897, 0.04321, -1.59478))
sub$residual <- with(sub, observed - simulated)
sub

  observed simulated residual
1    -0.75  -0.73644 -0.01356
2     0.00   0.00422 -0.00422
3     1.84   1.69897  0.14103
4    -0.33   0.04321 -0.37321
5    -1.60  -1.59478 -0.00522

par(pty="s")
plot(simulated ~ observed, sub)
abline(0, 1)  # expected 1:1 line
sub.lm <- lm(simulated ~ observed, sub)
abline(sub.lm, col="red")  # the best-fit line is close to the 1:1

The wrong approach would be to inspect and plot the imperfect linear model fit:
plot(sub.lm)   # these are useful plots, but slightly different than I would expect
resid(sub.lm)  # and these are obviously different than calculated directly

          1           2           3           4           5
-0.06967768 -0.03752067 -0.08096466  0.31321064 -0.12504764

How can I perform a similar analysis/plot with the known residuals from a perfect 1:1 linear model?
What I've tried so far is:
plot(residual ~ 1, sub)

But it isn't quite the same as plot(sub.lm) from above.
Comment: You want the residuals as if your model was 1:1 ?  But you are doing a regression between the observed and the simulated. why ?  What do you want to do ?
Answer: The most obvious thing to do is to plot residuals vs predicted (i.e. simulated) - you can plot this directly, without reference to a program to fit regression.
However, if you want to use a regression to fit it, you need an intercept of 0 and an offset of simulated, if your program allows for an offset. (In R that's lm(observed~0,offset=simulated))
That fit can be used produce most of the usual diagnostic plots, but not all (leverage, for example, is 0, so the leverage based plots won't work).
Comment: This is exactly what I was looking for!


Why is my Screen not showing the output even though there are no errors

Question:
Blockquote

I have uses route and routes. I am not having any errors but there is no output on the screen what is reason for that? Please let me know
I was trying to do single page application. I was building text analyzer app. Initially it did not worked when i used switch(it was showing error saying switch not found in react-router-dom, later I fixed it by replacing switch with routes. Now everything is correct and its not showing any error but there is no display on the output screen.
This is my app component
import "./App.css";
import Alert from "./components/Alert";
import Navbar from "./components/Navbar";
import Overview from "./components/Overview";
import Textform from "./components/Textform";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
return (
    <>
      <Router>
        <Navbar title="Text Analyzer" Homepage="Homepage"mode={mode}
          togglemode={togglemode}/>
        <Alert alert={alert} />

          <Routes>
            <Route exact path="/overview" element={<Overview />} />
            <Route exact path="/" element={
                <Textform heading="Enter the text to analyze" mode={mode}
                  showalert={showalert}/>}
            />
          </Routes>

      </Router>
    </>
  );
}
export default App;

This is my navbar component
import React from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";

export default function Navbar(props) {
  return (
    <nav
      className={`navbar navbar-expand-lg navbar-${props.mode} bg-${props.mode}`}
    >

        <Link className="navbar-brand" to="/">
          {props.title}
        </Link>
        <button
          className="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >

        </button>

              <Link className="nav-link active" aria-current="page" to="/">
                Home
              </Link>

              <Link
                className="nav-link active"
                aria-current="page"
                to="/overview"
              >
                Overview
              </Link>

            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="flexSwitchCheckDefault"
              onClick={props.togglemode}
            />

              Enable Darkmode

            <input className="form-check-input" type="checkbox"           role="switch" id="flexSwitchCheckDefault" onClick={props.togglemode}
            />

              Enable Redmode

  );
}
Navbar.propType = {
  title: PropTypes.string.isRequired,
  Homepage: PropTypes.string.isRequired,
};
Navbar.defaultProps = {
  title: "set title here",
  Homepage: "about text here",
};

Answer: import "./App.css";
import Alert from "./components/Alert";
import Navbar from "./components/Navbar";
import Overview from "./components/Overview";
import Textform from "./components/Textform";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
function App() {
return (
    <>
      <Router>
        <Navbar title="Text Analyzer" Homepage="Homepage"mode={mode}
          togglemode={togglemode}/>
        <Alert alert={alert} />

          <Routes>
            <Route exact path="/overview" element={<Overview />} />
            <Route exact path="/" element={
                <Textform heading="Enter the text to analyze" mode={mode}
                  showalert={showalert}/>}
            />
          </Routes>

      </Router>
    </>
  );
}
export default App;

Use this code snippet.
Maybe you have removed "function App() {"from the app.js file.
Its works for me when I add this.
Let me know if you face any other issues.


Why is comparison query in Bigquery giving me "unrecognized name" error

Question: Please help me out, and what the problem is here and how I can fix it. I wanted to compare results, but got an error message. please where did I get it wrong?. I ran a query to know if values of a column in a table are correct. Hence I added three columns to double check. Then ran a query to query the two columns for any inconsistencies. I got an error message instead.
pics of first query and result
pics of second query for comparison and the error message
Answer: Your column named "New_Total" was a temporary column which not save to dataset "Avocado_data.avocado_prices".
If you want to compared like that you can use subquery and the code should be like this:
<code>SELECT * FROM
(
    SELECT
        region,
        year,
        Small_Bags,
        Large_Bags,
        XLarge_Bags,
        Total_Bags,
        Small_Bags + Large_Bags + XL_Large_Bags AS New_Total
    FROM Avocado_data.avocado_prices
)
WHERE Total_Bags != New_Total
</code>


Is std::declval outdated because of guaranteed copy elision?

Question: The standard library utility declval is defined as:
template<class T> add_rvalue_reference_t<T> declval() noexcept;

To add a rvalue reference here seemed like a good idea, if you think about the language when it was introduced in C++11: Returning a value involved a temporary, that was subsequently moved from.
Now C++17 introduced guaranteed copy elision and this does not apply any more. As cppref puts it:

C++17 core language specification of prvalues and temporaries is
fundamentally different from that of the earlier C++ revisions: there
is no longer a temporary to copy/move from. Another way to describe
C++17 mechanics is "unmaterialized value passing": prvalues are
returned and used without ever materializing a temporary.

This has some consequences on other utilities implemented in terms of declval. Have a look at this example (view on godbolt.org):
#include <type_traits>

struct Class {
    explicit Class() noexcept {}
    Class& operator=(Class&&) noexcept = delete;
};

Class getClass() {
    return Class();
}

void test() noexcept {
    Class c{getClass()}; // succeeds in C++17 because of guaranteed copy elision
}

static_assert(std::is_constructible<Class, Class>::value); // fails because move ctor is deleted

Here we have a nonmovable class. Because of guaranteed copy elision, it can be returned from a function and then locally materialised in test(). However the is_construtible type trait suggests this is not possible, because it is defined in terms of declval:

The predicate condition for a template specialization
is_constructible<T, Args...> shall be satisfied if and only if the
following variable definition would be well-formed for some invented
variable t:
T t(declval<Args>()...);

So in our example, the type trait states if Class can be constructed from a hypothetical function that returns Class&&. Whether the the line in test() is allowed cannot be predicted by any of the current type traits, despite the naming suggests that is_constructible does.
This means, in all situations where guaranteed copy elision would actually save the day, is_constructible misleads us by telling us the answer to "Would it be constructible in C++11?".
This is not limited to is_constructible. Extend the example above with (view on godbolt.org)
void consume(Class) noexcept {}

void test2() {
    consume(getClass()); // succeeds in C++17 because of guaranteed copy elision
}

static_assert(std::is_invocable<decltype(consume), Class>::value); // fails because move ctor is deleted

This shows that is_invocable is similarly affected.
The most straightforward solution to this would be to change declval to
template<class T> T declval_cpp17() noexcept;

Is this a defect in the C++17 (and subsequent, i.e. C++20) standard? Or am I missing a point why these declval,  is_constructible and is_invocable specifications are still the best solution we can have?
Comment: `Class c2(c1);` fails. Why should `is_constructible` say it doesn't? In your example you're not constructing a new object at all.
Comment: very related/maybe dupe: https://stackoverflow.com/questions/20303250/is-there-a-reason-declval-returns-add-rvalue-reference-instead-of-add-lvalue-ref.  Also: https://stackoverflow.com/questions/25707441/why-does-stddeclval-add-a-reference
Comment: @AyxanHaqverdili `Class c2(c1)` is trying to construct from `Class&` (or `Class const&`). And this would be denied correctly by `is_constructible`
Comment: @Tobi Type of `c1` is `Class`, not `Class&`.
Comment: @AyxanHaqverdili, the type of the variable `c1` is. But the type of the expression is a reference.
Comment: @Tobi no, that's not right. Type of an expression cannot be a reference. http://eel.is/c++draft/expr#type-1
Comment: @NathanOliver These are pre-C++17
Answer:
However the is_construtible type trait suggests this is not possible, because it is defined in terms of declval:

Class is not constructible from an instance of its own type. So is_constructible should not say that it is.
If a type T satisfies is_constructible<T, T>, the expectation is that you can make a T given an object of type T, not that you can make a T specifically from a prvalue of type T. This is not a quirk of using declval; it is what the question is_constructible means.
What you're suggesting is that is_constructible should answer a different question than the one it is intended to answer. And it should be noted, guaranteed elision means that all types are "constructible" from a prvalue of its own type. So if that was what you wanted to ask, you already have the answer.
Comment: @Tobi: I think the way to think about it is that use of a prvalue to initialize something is not *construction* at all.
Comment: The "*all types* are constructible" is quite convincing in your answer... But for the preceding paragraph: Why shouldn't `is_constructible` mean from prvalue here, we already have `is_constructible` and `is_constructible` to denote "construct from a given object". And how would that argument generalize to `is_invocable`?
Comment: @Tobi: "*Why shouldn't `is_constructible` mean from prvalue here*" Because there's no such thing as a prvalue *type*. Expressions are prvalues, but types are not.
Comment: IMO declval should best approximate the inversion of decltype. And given a prvalue to decltype, it gives the type of the expression "T", which has _no_ rvalue references around. IMO this is a quirk of declval. And IMO this is independent of is_constructible. `is_same_v())>` looks desirable.
Comment: @David And though it's independent from the ideal behavior of `declval`, why should `string s(10)` not be described to "construct" a string? Isn't it even the case that a _constructor_ is called?
Comment: _And it should be noted, guaranteed elision means that all types are "constructible" from a prvalue of its own type._ I think this is an excellent example for what is wrong here. Why not make it just intuitively work? If I wanted to test against xvalue constructibility, I could pass `T&&`. If I wanted to test for prvalue constructibility, I would pass `T`.
Comment: As another answer noted, all this is probably for forwarding consistency. When I view it in that context, it all makes sense. Forwarding prvalues as prvalues is not possible. But IMO other attempts at explaining why something may not be "constructible" from a prvalue are not convincing.
Comment: What if you wanted to ask if `struct X { X(Class); };` is constructible from a prvalue of type `Class`? It certainly isn't constructible from an xvalue of type `Class`
Comment: @Artyer: Why would you want to ask if a type is constructible *specifically* from a prvalue?
Answer: The std::declval function is primarily meant for forwarding. Here's an example:
template<typename... Ts>
auto f(Ts&&... args) -> decltype(g(std::declval<Ts>()...)) {
    return g(std::forward<Args>(args)...);
}

In that common case, having std::declval returning a prvalue is wrong, since there's no good way to forward a prvalue.
Comment: Seeing it in that context makes sense to me. Though why not write `std::forward` in the return type? `args` is visible here. Feel it needs a better example.
Comment: @JohannesSchaub-litb Yeah I came up with a simple example that shows forwarding. A more useful example of `std::forward` would be inside type traits and other places where you don't have `args...`
Answer: In C++23, with the addition of std::reference_converts_from_temporary/std::reference_constructs_from_temporary, there is now precedence for T being a prvalue, T& being an lvalue and T&& being an xvalue in a type trait.
It is defined in the standard in terms of VAL<T>, which is basically declval<T>() if T is a reference type, otherwise a prvalue of type T.
This VAL<T> is very similar declval_cpp17<T>(). It would be useful in the examples you've mentioned.
However, the definition of std::is_constructible_v can never be changed to whether T t(VAL<Args>...); compiles. Too many existing call sites that look something like:
template<typename... Args> requires(std::is_constructible_v<T, Args...>)
void construct(Args&&... args);

Which would have to be changed to is_constructible_v<T, Args&&...> to be correct.
I believe add_rvalue_reference_t exists in declval since it's meant to be used with perfect forwarding. I.e., std::forward<T>(expr) would have the same type and value category as std::declval<T>(). This should have been std::declval<T&&>() all along, but it can't be changed now.


FirewallD is not running in CentOS Linux 7.1.1503

Question: I wanted to add a port 5004 for tcp connection. So I run the command:
firewall-cmd --permanent --add-port=5004/tcp

However I got an error:
FirewallD is not running

So by some research, I run the command to check the status.
systemctl status firewalld

It shows:
firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled)
Active: inactive (dead)

So what I need to do?
Comment: `systemctl restart firewalld`?
Comment: crashed? Try restarting it (sudo) systemctl start firewalld (sudo if you are not root and may run systemctl start as root using it)
Comment: Thanks, reboot is working. Please convert the comment to the answer.
Answer: Try
systemctl restart firewalld


how to make a simple tabs with next and previous links

Question: I use this code to make a simple tabs and it works fine.
$(document).ready(function() {
    $(".tabs-menu a").click(function(event) {
        event.preventDefault();
        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");
        var tab = $(this).attr("href");
        $(".tab-content").not(tab).css("display", "none");
        $(tab).fadeIn();
    });
});

My question is, if possible to add next and prev links?
:: DEMO ::
Comment: Of course you can...
Comment: https://css-tricks.com/jquery-ui-tabs-with-nextprevious/
Answer: try:
$('#prev').click(function(){
   $(".current").prev('li').find('a').click();
});
$('#next').click(function(){
   $(".current").next('li').find('a').click();
});

================================================

edit

add first and last class

Tab 1

Tab 4

hide prev at first
 prev

and:
 $(".tabs-menu a").click(function(event) {
    event.preventDefault();
    var li = $(this).parent();
    $(this).parent().addClass("current");
    $(this).parent().siblings().removeClass("current");
    var tab = $(this).attr("href");
    $(".tab-content").not(tab).css("display", "none");
    $(tab).fadeIn();

    //new code
    if (li.hasClass('first')) {
        $('#prev').hide();
    } else {
      $('#prev').show();
    }

    if (li.hasClass('last')) {
        $('#next').hide();
    } else {
       $('#next').show();
    }
});

and DEMO
Comment: thank's for this clever answer. any way to hide `prev` if you are in first `tab` and hide `next` if your in last `tab` just like this https://css-tricks.com/examples/TabsNextPrev/
Answer: I had a play with your demo and added this for next:
$(".next").click(function(event){
    event.preventDefault();
    var current = $(".current");
    current.next().addClass("current");
    current.removeClass("current");
    var tab = $(".current a").attr("href");
    $(".tab-content").not(tab).css("display", "none");
    $(tab).fadeIn();

});

Might help you get started.
Or checkout the CSS tricks article linked above
Answer: You may try this also.

$(document).ready(function () {
    $(".tabs-menu a").click(function (event) {
        event.preventDefault();
        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");
        var tab = $(this).attr("href");
        $(".tab-content").not(tab).css("display", "none");
        $(tab).fadeIn();
    });

    $(".next").click(function () {
        $(".current").next('li').find('a').trigger('click');
    });

    $(".prev").click(function () {
        $(".current").prev('li').find('a').trigger('click');
    });

});
body {
    padding: 20px;
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.5;
    font-size: 14px;
}
ul, li{
    list-style-type: none;
}
.tabs-menu {
    height: 30px;
    float: left;
    clear: both;
}
.tabs-menu li {
    height: 30px;
    line-height: 30px;
    float: left;
    margin-right: 10px;
    background-color: #ccc;
    border-top: 1px solid #d4d4d1;
    border-right: 1px solid #d4d4d1;
    border-left: 1px solid #d4d4d1;
}
.tabs-menu li.current {
    position: relative;
    background-color: #fff;
    border-bottom: 1px solid #fff;
    z-index: 5;
}
.tabs-menu li a {
    padding: 10px;
    text-transform: uppercase;
    color: #fff;
    text-decoration: none;
}
.tabs-menu .current a {
    color: #2e7da3;
}
.tab {
    border: 1px solid #d4d4d1;
    background-color: #fff;
    float: left;
    margin-bottom: 20px;
    width: auto;
}
.tab-content {
    width: 660px;
    padding: 20px;
    display: none;
}
#tab-1 {
    display: block;
}

Tab 1

Tab 2

Tab 3

Tab 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet purus urna. Proin dictum fringilla enim, sit amet suscipit dolor dictum in. Maecenas porttitor, est et malesuada congue, ligula elit fermentum massa, sit amet porta odio est at velit. Sed nec turpis neque. Fusce at mi felis, sed interdum tortor. Nullam pretium, est at congue mattis, nibh eros pharetra lectus, nec posuere libero dui consectetur arcu. Quisque convallis facilisis fermentum. Nam tincidunt, diam nec dictum mattis, nunc dolor ultrices ipsum, in mattis justo turpis nec ligula. Curabitur a ante mauris. Integer placerat imperdiet diam, facilisis pretium elit mollis pretium. Sed lobortis, eros non egestas suscipit, dui dui euismod enim, ac ultricies arcu risus at tellus. Donec imperdiet congue ligula, quis vulputate mauris ultrices non. Aliquam rhoncus, arcu a bibendum congue, augue risus tincidunt massa, vel vehicula diam dolor eget felis.

            <button class="next">Next</button>

Donec semper dictum sem, quis pretium sem malesuada non. Proin venenatis orci vel nisl porta sollicitudin. Pellentesque sit amet massa et orci malesuada facilisis vel vel lectus. Etiam tristique volutpat auctor. Morbi nec massa eget sem ultricies fermentum id ut ligula. Praesent aliquet adipiscing dictum. Suspendisse dignissim dui tortor. Integer faucibus interdum justo, mattis commodo elit tempor id. Quisque ut orci orci, sit amet mattis nulla. Suspendisse quam diam, feugiat at ullamcorper eget, sagittis sed eros. Proin tortor tellus, pulvinar at imperdiet in, egestas sed nisl. Aenean tempor neque ut felis dignissim ac congue felis viverra.

            <button class="prev">Prev</button>
            <button class="next">Next</button>

Duis egestas fermentum ipsum et commodo. Proin bibendum consectetur elit, hendrerit porta mi dictum eu. Vestibulum adipiscing euismod laoreet. Vivamus lobortis tortor a odio consectetur pulvinar. Proin blandit ornare eros dictum fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur laoreet, ante aliquet molestie laoreet, lectus odio fringilla purus, id porttitor erat velit vitae mi. Nullam posuere nunc ut justo sollicitudin interdum. Donec suscipit eros nec leo condimentum fermentum. Nunc quis libero massa. Integer tempus laoreet lectus id interdum. Integer facilisis egestas dui at convallis. Praesent elementum nisl et erat iaculis a blandit ligula mollis. Vestibulum vitae risus dui, nec sagittis arcu. Nullam tortor enim, placerat quis eleifend in, viverra ac lacus. Ut aliquam sapien ut metus hendrerit auctor dapibus justo porta.

            <button class="prev">Prev</button>
            <button class="next">Next</button>

Proin sollicitudin tincidunt quam, in egestas dui tincidunt non. Maecenas tempus condimentum mi, sed convallis tortor iaculis eu. Cras dui dui, tempor quis tempor vitae, ullamcorper in justo. Integer et lorem diam. Quisque consequat lectus eget urna molestie pharetra. Cras risus lectus, lobortis sit amet imperdiet sit amet, eleifend a erat. Suspendisse vel luctus lectus. Sed ac arcu nisi, sit amet ornare tellus. Pellentesque nec augue a nibh pharetra scelerisque quis sit amet felis. Nullam at enim at lacus pretium iaculis sit amet vel nunc. Praesent sapien felis, tincidunt vitae blandit ut, mattis at diam. Suspendisse ac sapien eget eros venenatis tempor quis id odio. Donec lacus leo, tincidunt eget molestie at, pharetra cursus odio.

            <button class="prev">Prev</button>


How to check if an object is a class

Question: I have a piece of code that I need to translate from python to matlab. I'm getting stuck with the isclass() method in the python code:
inspect.isclass(object)

As far as I know, this checks whether or not the object is a class and returns true or false accordingly.
Is there a way to do this in matlab?
The matlab isa function seems like it would be a good fit, but it doesn't seem to be able to check for classes.
Comment: @Wolfie I need to check if something is a class or an object. I just realized I can use isobject to check it instead
Comment: "Is a class or an object"? I think nomenclature is a bit confused here. A value can never be "a class", it can be an object of a specific class. `isobject` will tell you if the value is of a custom class (a.k.a. user-defined class). There is also a `isdouble`, `ischar`, `isstring`, `iscell`, `isstruct`, etc. `class` returns the name of the value's class (i.e. the type of the value), and `isa` compares `class` to a given string.
Comment: Whatever you're doing, you're probably doing it wrong. You shouldn't need to be guessing about what you've got! Downcasting is a code smell.
Comment: @Chuck MATLAB is a duck-typed language, you sometimes need to check the types of the inputs to a function.
Comment: What kind of  class do you want to check for? Everything is a class, whether that class is `double` or `table` or `myCustomObject`... The `isa` function lets you check for a specific class
Comment: Added the Python tag because it seems like you actually need to understand what `instance.isclass` is doing (e.g. https://stackoverflow.com/questions/4081819/why-does-python-inspect-isclass-think-an-instance-is-a-class) before trying to translate. Please [edit] your question to include your Python version, the linked question suggests the behaviour of that function changed at some point.
Answer: If you are trying to check whether a variable is in a class, try the isa function and pass 'class' as the type.
bol = isa(x, 'class');

If you are trying to check whether something is a classs, try the isa function and pass 'meta.class' as the type.
bol = isa(x,'meta.class');

Comment: What does this do? I've tried it with `x` a user-class object, and it returns False.
Comment: Right. This checks if a variable x is in any other class. You want to know if x is a class? I will update my answer.
Comment: I think OP wants the `isobject` function. I'm just curious about this answer. `isa(x,'meta.class')` returns false for me, and `isa(?x,'meta.class')` returns true, no matter what `x` is.
Comment: As far as I can tell, `isa(a,b)` is the same as `strcmp(class(a),b)`. This is why I'm curious about what you write here, it's new to me. I'm trying  to get it to work, but failing. :/
Comment: You are likely right about isobject.
Comment: I am investigating the issue you are mentioning with my colleagues. From the doc on isa: If A is an object, then isa returns 1 if the class of A, or any superclass of A, belongs to the specified category.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/251118/discussion-between-iohans-and-cris-luengo).

How to check if an object is a class


Integral Test: Anticipating That Integral is Lesser Than Riemann Sum

Question: I am given the following $f(x)$ value:
$f(x) = \frac{1}{x^2+x}$
The question says that it is possible to "anticipate" that the integral of $f(x)$ would be less than the sum of the series of $f(x)$. How is it possible to determine that? Do we use a mode of comparison with a function $g(x) = \frac{1}{x}$, that has its integral value less than the sum of its series?
Comment: If $f(x)$ is decreasing, then the riemann sum, which can be viewed as "sum of rectangles", will be larger than the series sum
Comment: Though isn't it only if we were to apply a left-hand Riemann sum on a decreasing function? If we use a right-hand Riemann sum, then the sum will be lesser than the integral value
Answer: Basically you can interpret the series sum as left riemann sum from 0 to infinity as step size  1 for monotonically decreasing function so with a simple drawing you can reach a conclusion.
Comment: I am sure you didn't intend to, but this is exactly what I wrote in the comments, and it's not clear whether you just looked at my comment and wrote this answer... Anyways whatever
Comment: @GarethMa  apparently I upload the answer late but it was because of the internet connection I didn't saw your comment but I don't want any gain from my answer thanks for kindly warning
Comment: It is fine, just keep the answer, it's concise and clear.
Comment: @GarethMa Thanks :)
Comment: Your infinite sum start from 0 and for each step I mean 1 increase in dummy variable n graphically corresponds to left Riemann sum. For visual demonstration https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRToR8HBV6qPewaUc0SnfMGD0Bj6VO0ln6-UBAs-WVlGqLn5lWf&usqp=CAU could be helpful.
Comment: @Butane If in the sigma notation we have $n=1$ as the starting value, shouldn't we use right-hand Riemann sum? The comparison is between an integral that starts from 1 to infinity and the sum with $n=1$ to infinity.
Comment: @geo_freak no again from the left consider it as you are calculating the area under the columns that their height determined by the left value of the function for each step.
Comment: Even you can consider it as moving your origin one step ahead because summation's start one step size later.
Comment: But I don't understand how we know to use Left Hand sum but not Right Hand Riemann sum in this case
Comment: left sum use rectangles whose  left top vertices are on the function and right sum uses rectangles with right top vertices are on the curve. So, for summation of the areas of the rectangles we use the function that passes through the left top vertices of the rectangles.


Dynamic switching of fragments

Question: My Activity contains two buttons (Next and Back) and a fragment. When the Activity starts, it gets an array of resources.
Such as {"Fish", "Bird", "Animal"};
Or this {"Fish", "Bird", "Animal", "Bird", "Bird"}; etc.
Depending on the contents of the array, the Next button should switch the fragments accordingly:
So: Fragment_Fish.java >Fragment_Bird.java>Fragment_Animal.java.
So: Fragment_Fish.java >Fragment_Bird.java>Fragment_Animal.java. >Fragment_Bird.java>Fragment_Bird.java>
How is it easier to implement in Java, please tell me?
Comment: share your code. also explain how do you expect the app to guess wich fragment you want to switch for...
Comment: If the first element of the array is Fish, then the first fragment Fragment_Fish.java . If the second element of the array is Bird, then when the Next button is clicked, the fragment is Fragment_Fish.java is replaced by the fragment Fragment_Bird.java and so on.
The application will guess which fragment you want to switch to by the order of words in the array.
Comment: post your current code
Answer: I don't understand your problem clearly, I think you want to switch between fragments.
If you want to switch between multiple fragments, you can use navigation components for this.
You can explore about navigation components.
Resources :- Integrate the Navigation component
Comment: `I don't understand your problem clearly, ` best to not try and answer then, as you'd just be guessing, you have enough reputation to ask for clarity with comments, wait until there's enough information to actually answer correctly
Answer:
You need to make an array of the fragments like this:

Fragment[] fragments = new Fragment[]]{new Fragment_Fish(), and other fragments separated with commas};

Make a int variable in the class something like this:

int counter = 0;

Increase the counter on button click and update the fragment. Like this:

buttonNext.setOnClickListener(v -> {
   counter ++;
   if(!counter >= fragments.size()){
      //all the fragments are opened do what you need
      return;
   }
   final FragmentTransaction ft = getFragmentManager().beginTransaction();
   ft.replace(R.id.details, fragments[counter]);
   ft.commit();
   //came to another fragment
});

Comment: `Or this {"Fish", "Bird", "Animal", "Bird", "Bird"};` how is this answer going to work if OP has two entries in the array for the same type of animal ? sounds like this needs to be a dynamic array of fragments built up based on some other criteria first
Comment: well, OP did ask about that, it's in their question ? i copied that exactly from their post, either way, there isn't enough information here to attempt an answer as you'd just be guessing
Comment: doesn't sound like OP really needs an array of fragments, they need a hashmap of fragments. your idea of making use of an array isn't going to scale and isn't going to work for cases where the same animal is needed twice
Comment: ok. I get it @a_local_nobody. That is right. We can use hashmap also. Do u want me to add that too?
Comment: doesn't matter at this point, the question is closed, i'm saying that you should not just jump to the first solution that comes to mind and you should attempt to answer well-asked questions, you'll earn a lot more reputation instead of guessing at low quality posts

Dynamic switching of fragments


GRAPH API Post action always shows 'shared a link via app name'

Question: I am trying to publish a story through my application. But when I do so it display saying that "Some has shared a link app name"
I don't want it to share as a link but instead something like shown in the following image
Reading through the facebook documents (https://developers.facebook.com/docs/reference/api/post/) I thought it would be achieved by defining status_type to app_created_story but unfortunately that doesn't help either. Secondly I also want to have "Try it now" button underneth the story like in the second image. I assume its done through "actions" (array of objects containing the name and link) but I am unable to achieve the desired results. Any help in this regard would be highly appreciated.
My code is as follows
<code>$attachment = array(
        'access_token'=> "User Access Token",
        'message' => "Message",
        'name' => 'Title',
        'caption' => "Some text",
        'link' => 'https://apps.facebook.com/canvas/',
        'description' => 'Some Text Here',
        'picture' => "http://www.example.com/image.jpg",
        'from' => "application id",
        'status_type' => "app_created_story",

        );
try {
// Proceed knowing you have a user who is logged in and authenticated
    $result = $facebook->api("/userid/feed/",'post',$attachment);
} catch (FacebookApiException $e) {
error_log($e);
//$user = null;
}
</code>
Just to add in the access token i have following three extended permissions: &scope=email,publish_stream,publish_actions
Answer:
I am trying to publish a story through my application. But when I do so it display saying that "Some has shared a link app name"

That's because that is exactly what you are doing – you are posting a link.
The second image you've shown is not a link post, but an Open Graph action – start here to familiarize yourself with the concept: https://developers.facebook.com/docs/opengraph/
Comment: Ok thanks for pointing that out. I tried using Open Graph it is showing in my Activity Log but no timeline. Any clues?


To what frequencies do the overtones (harmonics) created by distortion extend?

Question: I just did a test, recorded my bass guitar through a high gain distortion pedal and then direct to my sound card at 96kHz/24bit, and then using a spectrum analyser, I looked at the frequency content, and saw it for certain notes extending the whole range (upto 48kHz). Now these high frequency overtones were at quite low volume, but still noticeable visibly (of course I can't hear them directly).
How high do these overtones extend, would 192kHz be enough to capture all of them or not (my sound card does not go that high)? I also assume that for electric guitars it does go a bit higher still, but just to get some idea either is fine.
And yes I did DI and not use speakers and microphones which would have put in a much higher noise floor, so please do the same.
Since I'm talking about tones that we can't hear directly (possibly their interaction in chords might be noticeable if they were at a high enough volume), the requirement for the highest overtone is basically whether it's measurable in the sense of being above the noise floor.
Edit (see comment below): When looking at the overtones generated by distortion, how high do the overtones extend measurably different from the noise floor?
Comment: As the answers suggest,  the upper limit worth recording is related to our aural capability, not the actual spectral output of the guitar+synth boxes.  A really good spectrum analyzer, applied to the electronic signal rather than the acoustic output of a speaker, might well indicate power into the MHz range, since the distorted signal has all sorts of "junk" in it.
Comment: Some *acoustic* instruments generate significant amounts of sound energy up to 100 kHz and beyond - for example cymbals, harpsichords, and some organ pipes - and not only for notes with high pitched fundamental frequencies. There is no big deal about generating *electrical* waveforms that go up to the MHz or even GHz region. A well-designed distortion pedal should be filtering out the frequency content that is irrelevant to what it is meant to do - but there are plenty of badly designed ones out there.
Comment: All the answers and comments so far contain lots of good information, but  so far a real answer to my question is missing. So I'll try to restate the question in a way that it's not buried in between descriptions of how I got to the question.
Answer: Depending on the amount of clipping, the waveform of a very distorted signal can approach a square wave. Mathematically, a square wave is an infinite sum of overtones, with each higher overtone at a lower intensity than the previous.
Near the bottom of this page is the infinite sum of a mathematically exact square wave: http://mathworld.wolfram.com/FourierSeriesSquareWave.html Each term in the sum represent an overtone, and only the odd ones are present. (notice the n=1,3,5... under the sigma - the summation symbol, and the infinity sign above) So theoretically the answer to your question is that the frequencies extend infinitely.
However, no real-world electronics can actually produce a mathematically perfect square wave, so the overtones aren't infinite in real life. We can get very close to a square wave with electronics, so in reality the highest overtone present could be very, very high frequency indeed.
Can we generate a frequency using distortion so high that we can't record it? Probably. Digital signals used for clock and recording purposes are intended to be square waves. Again, in reality they cannot be made to be perfect square waves, but think about the fact that we can approximate a square wave at 192 kHz. That means the overtone series for that approximate square wave starts at 192 kHz and goes up a long way from there. At the very least, we need to be able to keep several of the lowest overtones intact in the wiring and signalling used for recording or we would have sync and encoding issues.
If you're more than just curious about this, then I'm not sure how useful this information will be in the real world. Hardly ever can humans hear above 20 kHz, and above 48 kHz is unheard of except through bone conduction (suggesting the ossicles in the middle ear are part of the upper limit). More limiting is the abilities of 99% of the sound storage and reproduction devices in the world, which can top out as low as 16 kHz and are rarely designed to go about 20 kHz. Even if we could put a firm number on the frequency of the highest overtone one could generate with a distortion pedal, that number would likely be so far beyond anything with could use that it's not worth spending too much time on.
Comment: digital clocking is done in the megahertz range, way beyond the audio range.  Thus we do get very good square wave approximations for 192k clock signals.
Comment: since the Amek console I mentioned costs in the $500k range, I think it could be called "esoteric!"  :)
Comment: There are good reasons to record digitized audio at higher sample rates, irrespective of human hearing. One important issue is that any artefacts created by signal processing (equalization, filtering, etc)  can be pushed into the inaudible frequency range and then deleted, rather than irreversibly polluting the frequency range that you can hear. For the same reason, it's important to filter out any frequencies that are too high to sample from the *analog* signal, *before* you digitize it, and that is much easier with a wider range (e.g. 20-48kHz, not 20-24) to roll off the filter response
Comment: also...there are a number of higher-end production desks that will pass 80k or even 90k audio signal.  The Amek 9098i being one.  Certainly you don't find that capability on pro-sumer gear.
Comment: @dwoz There are definitely devices that can operate well above 48 kHz, but the real issue, IMHO, is having tweeters/drivers can can effectively extend that far. As far as I've seen, only esoteric and expensive professional or audiophile equipment even aspires to ultrasonic acoustics.
Answer: The short answer is that recording distorted bass guitar at higher sampling rates than 96k/24bit is not going to result in any kind of perceivable difference, other than using up lots of disk storage much more quickly.
The long answer is that current music recording technology ignores supersonic frequencies and there's still some debate about whether anything is lost.
As Wilcox alludes to, the higher the frequency capture, the better the square waves look.  What he really is trying to say there is that the IMPULSE RESPONSE is better when we toss in the high frequencies.  Those high frequencies don't become perceived as notes, but they CAN influence the spatialization cues we perceive.
In countless discussions with professional audio engineers and mixers, they express a preference for higher bit rates not because they're yearning for some "high-frequency shimmer" but rather because the audio image "seems to be more defined in space."   This is explainable not because they have golden ears, but because the source material has more coherent transients.  It's a very subtle thing though...most low-mid level gear renders the question moot for almost all listeners.
Most professional audio engineers that I've spoken with notice that 96k is easier to get to "lay in," but that going to 192k only introduces more computer management issues without a real sonic benefit.
Comment: When I think about Sgt. Pepper's being recorded on two synchronized four-tracks, and then *Supposed Former Infatuation Junkie* (by Alanis Morisette) being recorded on 20-bit, 48 kHz ADAT, I stop worrying about sample rates and bit depths and track counts. None of it matters without a good song, and none of it will hold back a great song.
Comment: The 4-track tape machines used by Ken Scott to record Sgt. Pepper were arguably better machines than any ADAT.  :)    In that era, high-end analog was definitely better than digital, though that is not necessarily true today.


Android - set button width programmatically inside a tablerow

Question: I have an application that generates buttons inside a table view as shown below:
TableLayout table = (TableLayout) findViewById( R.id.tableLayout1 );

    for(int i = 0 ; i < Gatorade.getVariant().length ; i++){
           int buttonsInRow = 0;
           int numRows = table.getChildCount();

           TableRow row = null;

           if( numRows > 0 ){
                row = (TableRow) table.getChildAt( numRows - 1 );
                buttonsInRow = row.getChildCount();
           }

           if( numRows == 0 || buttonsInRow == 3 ){
                row = new TableRow( this );
                table.addView( row );
                buttonsInRow = 0;
           }
           if( buttonsInRow < 3 ){
                Button b = new Button( this );
                b.setText(Gatorade.getVariant()[i]);
                //b.setWidth(pixels)
                //b.setWidth()

                row.addView( b, 100, 50 );

           }
}

Is there a way to programmatically set the button width to wrap_content and height to match_parent?
If this is not possible, is there a way to programmatically evenly space out the buttons in the row?
Thanks.
Answer: Try This:
LayoutParams lp = new TableRow.LayoutParams(android.widget.TableRow.LayoutParams.WRAP_CONTENT,android.widget.TableRow.LayoutParams.MATCH_PARENT);
btn.setLayoutParams(lp);

Try use Weight in button. Give table row weightsum=10. and divide it to buttons as per your req. like btn1.weight=3; btn2.weight=5;btn3.weight=2; this is like using % in HTML. if you set
weightsum = 10 that means it will use 100% of its parent view. and using weight=3 for button means it will use 3/10 of total row size. it is just for width so you need to set width =0 for every view where you are assigning weight.
for weight use like this:
LayoutParams lp = new TableRow.LayoutParams(0,android.widget.TableRow.LayoutParams.MATCH_PARENT,3f);

where 3f is weight. but first setweight sum to 10 in tablerow.
Hope it Helps!!!
Comment: Thanks it helped a lot. However, it seemed that the button content was too long and the third row was barely visible anymore. Any ideas on how to evenly distribute buttons in a table row?


How to hide field if blank

Question: I have a view created which has a column 'Price'. I also I have another column 'Special Price' in the same view, but 'exclude from display' is selected.
In views, click the price field > rewrite results > Rewrite the output of this field > I added the below:

$[field_price]
Special $[field_special_price]

I would like to display the special price only if the special price field has a value. If the special price field has no value, I only want to display the price field value. I am not sure how I can modify it ?
Thanks,
 D

I am new to drupal. Sorry if I am not clear.
In the views, I would like to put price and special price in the same column. I will add some css to special price. If I un-selected exclude from display for special price, then special price will be in another column which I do not want to do.
Please visit the page and see the price column.
http://bettylist.com/ac/myview
Thanks.
Answer: Then dont exclude special price from display and customize that field. There's an option @ No results behavior, where you need to check Hide if empty.
THEN, all you need to do is to style the two fields where they're both present.
That's the simplest way. There is another way, where you exclude both from display and add another field at the end "Global text area", where you can play with the tokens and rewrites.
Answer: Follow these steps:

Rewrite output of [field_special_price]
Make it Special $[field_special_price]
Make sure that under no results behavior, "hide rewriting if empty" is checked.
Now rewrite the output of [field_price].
Make it [field_price]
[field_special_price]

Also [field_special_price] should have weight less than [field_price]. I think you know this well.
Comment: Thank you Himanshu. I was able to follow your instruction and got what I needed. My site now shows simply both prices when both are present. Another question I have is how to cross out the price amount if there is a special price? I guess I need some css for that. If you can provide some help, it will be great.
Comment: sorry not getting exactly your requirement
Comment: Now, that I can see special price column only if special price has value. I like to know if special price has value, how can I cross out the price value? If there is not special price, then do not cross out the price value. Do I need some IF ELSE statements somewhere? Ex: If special price > 0 then  price  End If. Please help
Comment: Never mind. I was able to figure this out. Thank you again.
Comment: Nice, saw your comment just now. You're champ :)

How to hide field if blank


Regexp: excluding a word but including non-standard punctuation

Question: I want to find strings that contain words in a particular order, allowing non-standard characters in between the words but excluding a particular word or symbol.
I'm using javascript's replace function to find all instances and put into an array.
So, I want select...from, with anything except 'from' in between the words. Or I can separate select...from from select...from (, as long as I exclude nesting. I think the answer is the same for both, i.e. how do I write: find x and not y within the same regexp?
From the internet, I feel this should work: /\bselect\b^(?!from).*\bfrom\b/gi but this finds no matches.
This works to find all select...from: /\bselect\b[0-9a-zA-Z@\(\)\[\]\s\.\*,%_+-]*?\bfrom\b/gi but modifying it to exclude the parenthesis "(" at the end prevents any matches: /\bselect\b[0-9a-zA-Z@\(\)\[\]\s\.\*,%_+-]*?\bfrom\b\s*^\(/gi
Can anyone tell me how to exclude words and symbols within this regexp?
Many thanks
Emma
Edit: partial string input:
left outer join [stage].[db].[table14] o on p.Project_id = o.project_id

left outer join
(
select
     different_id
    ,sum(costs) - ( sum(brushes) + sum(carpets) + sum(fabric) + sum(other) + sum(chairs)+ sum(apples) ) as overallNumber
    from
    (
    select ace from [stage].db.[table18] J

Javascript:
sequel = stringInputAsAbove;
var tst = sequel.replace(/\bselect\b[\s\S]*?\bfrom\b/gi, function(a,b) { console.log('match: '+a); selects.push(b); return a; });
console.log(selects);

Console.log(selects) should print an array of numbers, where each number is the starting character of a select...from. This works for the second regexp I gave in my info, printing: [95, 251]. Your \s\S variation does the same, @stribizhev.
The first example ^(?!from).* should do likewise but returns [].
The third example \s*^\( should return 251 only but returns []. However I have just noticed that the positive expression \s*\( does give 95, so some progress! It's the negatives I'm getting wrong.
Comment: What about `/\bselect\b[\s\S]*?\bfrom\b/gi`?
Comment: Please post example strings, and also specify the expected output.
Comment: Parsing SQL with regexp suffers from the same problem as parsing any other language with regexp: it probably won't work very well and if it does it will be very painful.
Comment: Without any input strings to test against, I do not know if I should post my suggestion or not :) Please let me know if you really have strings with newline symbols and that you just need to match the leftmost "from", not the rightmost "select".
Comment: @stribizhev - thanks for your comment. The SQL strings will all be different. I don't have any \n symbols but the code is on a new line, and deleting these to bring "from" on a line with "select" has solved some problems (possibly with code other than that posted - i have tried many, many variations). I'll post up some SQL strings. thanks
Comment: How do you want to handle `select fromage from french_cheeses`?
Answer: Your \bselect\b^(?!from).*\bfrom\b regex doesn't work as expected because:

^ means here beginning of a line, not negation of next part, so
the \bselect\b^ means, select word followed by beginning of a
line. After removal of ^ regex start to match something
(DEMO) but it is still invalid.
in multiline text .* without modification will not match new line,
so regex will match only select...from in single lines, but if you
change it for (.|\n)* (as a simple example) it will match
multiline, but still invalid
the * is greede quantifire, so it will match as much a possible,
but if you use reluctant quantifire *?, regex will match to first
occurance of from word, and int will start to return relativly
correct result.
\bselect\b(?!from) means match separate select word which is not
directly followed by separate from word, so it would be
selectfrom somehow composed of separate words (because
select\bfrom) so (?!from) doesn't work and it is redundant

In effect you will get regex very similar to what Stribizhev gave you: \bselect\b(.|\n)*?\bfrom\b
In third expression you meke same mistake: \bselect\b[0-9a-zA-Z@\(\)\[\]\s\.\*,%_+-]*?\bfrom\b\s*^\( using ^ as (I assume) a negation, not beginning of a line. Remove ^ and you will again get relativly valid result (match from select through from to closing parathesis ) ).
Your second regex works similar to \bselect\b(.|\n)*?\bfrom\b or \bselect\b[\s\S]*?\bfrom\b.
I wrote "relativly valid result", as I also think, that parsing SQL with regex could be very camplicated, so I am not sure if it will work in every case.

You can also try to use positive lookahead to match just position in text, like:
(?=\bselect\b(?:.|\n)*?\bfrom\b)

DEMO - the () was added to regex just to return beginning index of match in groups, so it would be easier to check it validity

Negation in regex
We use ^ as negation in character class, for example [^a-z] means match anything but not letter, so it will match number, symbol, whitespace, etc, but not letter from range a to z (Look here). But this negation is on a level of single character. I you use [^from] it will prevent regex from matching characters f,r,o and m (demo). Also the [^from]{4} will avoid matching from but also form, morf, etc.
To exlude the whole word from matching by regex, you need to use negative look ahead, like (?!from), which will fail to match, if there will be chosen word from fallowing given position. To avoid matching whole line containing from you could use ^(?!.*from.*).+$ (demo).
However in your case, you don't need to use this construction, because if you replace greedy quantifire .*\bfrom with .*?\bfrom it will match to first occurance of this word. Whats more it would couse problems. Take a look on this regex, it will not match anything because (?![\s\S]*from[\s\S]*) is not restricted by anything, so it will match only if there is no from after select, but we want to match also from! in effect this regex try to match and exclude from at once, and fail. so the (?!.*word.*) construction works much better to exclude matching line with given word.
So what to do if we don't what to match a word in a fragment of a match? I think select\b([^f]|f(?!rom))*?\bfrom\b is a good solution. With ([^f]|f(?!rom))*? it will match everything between select and from, but will not exclude from.
But if you would like to match only select...from not followed by ( then it is good idea to use (?!\() like. But in your regex (multiline, use of (.|\n)*? or [\s\S]*? it will cause to match up to next select...from part, because reluctant quantifire will chenge a plece where it need to match to make whole regex . In my opinion, good solution would be to use again:
select\b([^f]|f(?!rom))*?\bfrom\b(?!\s*?\()

which will not overlap additional select..from and will not match if there is \( after select...from - check it here
Comment: Thanks for this. The regex101 link is also amazing - I didn't know about that site. Can you tell me: how do I make a negation using ^ ? Do I need brackets or something. Your regex works perfectly to find select...from and the explanations are useful - but I still don't know how to create the negative criterion. I.e. select...from without a from in the middle. Or select...from without a following '('. thanks for any help.


Finding specific ideals of a ring

Question: How does one go about finding all the ideals of a ring (quadratic extension) containing a specific number?
In particular find all the ideals of $\mathbb Z(\sqrt{-29})$ which contain the integer 30.
Comment: What do you know about quadratic number rings? Do you know that its the full ring of integers, that contains = divides for ideals, and how primes split?
Answer: Suppose $\alpha$ represents the square root of a negative integer, so that we may think of $R=\Bbb Z[\alpha]$ as a subset of the complex plane. The following Proposition will make our task a great deal simpler (though its proof is non-trivial).
Lemma 1: Suppose $a+bi,c+di$ with $a,b,c,d\in\Bbb R$, $i^2=-1,$ and $a,b$ not both zero. Then $c+di$ is a real multiple of $a+bi$ if and only if $ad-bc=0$. [I leave the proof to you.]
Lemma 2: Suppose $a+bi,c+di$ with $a,b,c,d\in\Bbb R$ and $ad-bc\neq 0$. Then for any $x+yi$ with $x,y\in\Bbb R$, there exist unique $\beta,\gamma\in\Bbb R$ such that $x+yi=\beta(a+bi)+\gamma(c+di).$ [I leave the proof to you.]
Lemma 3: Suppose $a,b,c,d$ are as in Lemma 2. Then for any real $x_1,x_2$, we have $$|x_1(a+bi)+x_2(c+di)|\leq |x_1||a+bi|+|x_2||c+di|,$$ with equality only if $x_1=x_2=0$. [I leave the proof to you.]
Proposition: If $I$ is an additive subgroup of $\langle R,+\rangle$, then exactly one of the following is true:

(i) $I=\{0\}$.
(ii) There exist $m,n\in\Bbb Z$ not both zero such that $$I=\{km+kn\alpha:k\in\Bbb Z\}.$$
(iii) There exist $m_1,n_1\in\Bbb Z$ not both zero and $m_2,n_2\in\Bbb Z$ not both zero, such that $m_1n_2-m_2n_1\neq 0$ and $$I=\{j(m_1+n_1\alpha)+k(m_2+n_2\alpha):j,k\in\Bbb Z\}.$$

Proof of Proposition:
${}\quad{}$It is clear that (i) and (ii) can't both happen, and that (i) and (iii) can't both happen. I leave it to you to show that if (ii) happens, then (iii) can't happen, so (ii) and (iii) can't both happen, either. Hence, at most one of conditions (i) through (iii) may hold. It remains to show that at least one holds.
${}\quad{}$Suppose that neither (i) nor (ii) holds, so that we need only show (iii) holds. Note that if $m+n\alpha\in I$ is non-zero--and since (i) fails to hold, there is at least one such $m+n\alpha\in I$--then $|m+n\alpha|^2=m^2-n^2\alpha^2$ is a positive integer (since $\alpha^2$ is a negative integer, and $m$ and $n$ are integers not both zero). Hence, there exist $m_1,n_1\in\Bbb Z$ not both zero such that $m_1+n_1\alpha\in I$ and such that $|m_1+n_1\alpha|^2\leq|m+n\alpha|^2$ for all non-zero $m+n\alpha\in I$. Now, since (ii) doesn't hold, then there exist $m+n\alpha\in I\setminus\{km_1+kn_1\alpha:k\in\Bbb Z\}.$ In particular, there exist $m_2,n_2\in\Bbb Z$ such that $m_2+n_2\alpha\in I\setminus\{km_1+kn_1\alpha:k\in\Bbb Z\}$ and such that $|m_2+n_2\alpha|^2\le|m+n\alpha|^2$ for all $m+n\alpha\in I\setminus\{km_1+kn_1\alpha:k\in\Bbb Z\}.$
${}\quad{}$Now, if $m_1n_2-m_2n_1=0,$ then since $\alpha=i\sqrt{-\alpha^2}$ we have by Lemma 1 that there is a real number $x$ such that $m_2+n_2\alpha=x(m_1+n_1\alpha),$ and since $m_2+n_2\alpha\notin\{k(m_1+n_1\alpha):k\in\Bbb Z\},$ then $x$ is not an integer, and so there is an integer $j$ such that $j<x<j+1$. Since $m_2+n_2\alpha=x(m_1+n_1\alpha),$ then $$|j(m_1+n_1\alpha)-(m_2+n_2\alpha)|^2=|(j-x)(m_1+n_1\alpha)|^2=|j-x|^2|m_1+n_1\alpha|^2.\tag{#}$$ Since $j<x<j+1$, then $0<x-j<1$, so $0<|j-x|<1$, so $0<|x-j|^2<1$, and so since $|m_1+n_1\alpha|\neq 0,$ it follows from $(\#)$ that $$0<|j(m_1+n_1\alpha)-(m_2+n_2\alpha)|^2<|m_1+n_1\alpha|^2.\tag{##}$$ But $j(m_1+n_1\alpha)-(m_2+n_2\alpha)\in I,$ so $(\#\#)$ contradicts our choice of $m_1+n_1\alpha.$ Hence, we must have $m_1n_2-m_2n_1\neq 0$.
Finally, we show that $I=\{j(m_1+n_1\alpha)+k(m_2+n_2\alpha):j,k\in\Bbb Z\},$ so that (iii) holds. We already know that $I\supseteq\{j(m_1+n_1\alpha)+k(m_2+n_2\alpha):j,k\in\Bbb Z\}$ since ideals are additively closed. Take any $m+n\alpha\in I$. By Lemma 2, there exist unique $\beta,\gamma\in\Bbb R$ such that $$m+n\alpha=\beta(m_1+n_1\alpha)+\gamma(m_2+n_2\alpha).$$ We wish to show that $\beta,\gamma$ are integers. By way of contradiction, suppose not. Since $\beta,\gamma$ are real non-integers, then there exist integers $j,k$ such that $0<|\beta-j|\le\frac12$ and $0<|\gamma-k|\le\frac12$. Then since $|m_1+n_1\alpha|^2\le|m_2+n_2\alpha|^2$ implies $|m_1+n_1\alpha|\leq|m_2+n_2\alpha|,$ we have $$\begin{align}|m+n\alpha-j(m_1+n_1\alpha)-k(m_2+n_2\alpha)| &= |(\beta-j)(m_1+n_1\alpha)+(\gamma-k)(m_2+n_2\alpha)|\\ &< |\beta-j||m_1+n_1\alpha|+|\gamma-k||m_2+n_2\alpha|\\ &\le \frac12|m_1+n_1\alpha|+\frac12|m_2+n_2\alpha|\\ &\le |m_2+n_2\alpha|,\end{align}$$ where the strict inequality comes from Lemma 3. Since $m+n\alpha-j(m_1+n_1\alpha)-k(m_2+n_2\alpha)\in I$ by additive closure, it then follows from our choice of $m_2+n_2\alpha$ that $m+n\alpha-j(m_1+n_1\alpha)-k(m_2+n_2\alpha)$ is an integer multiple of $m_1+n_1\alpha$. But then $m+n\alpha-k(m_2+n_2\alpha)=\beta(m_1+n_1\alpha)+(\gamma-k)(m_2+n_2\alpha)$ is an integer multiple of $m_1+n_1\alpha,$ so $(\gamma-k)(m_2+n_2\alpha)$ is, too. Since $m_2+n_2\alpha$ isn't an integer multiple of $m_1+n_1\alpha$, it follows that $\gamma=k$ (so $\gamma$ is an integer), but then $\beta(m_1+n_1\alpha)$ is an integer multiple of $m_1+n_1\alpha,$ whence $\beta$ is an integer. Thus, assuming that $\beta,\gamma$ not both integers leads to the desired contradiction. $\Box$

The above Proposition has a tremendous upside for you in the case that $\alpha=\sqrt{-29}$, since ideals are necessarily additive subgroups of $\langle R,+\rangle$. It remains to you to see under what conditions the additive subgroups of type (i) through (iii) can be ideals--you'll need to confirm which have the property that $x\in I$ and $r\in R$ implies $r\cdot x\in I$--then figure out which ideals (if any) of each type have $30$ as an element.

Finding specific ideals of a ring


How do I use multiple fonts ie a composite font in HexaPDF

Question: Our users are giving us Emoji and a lot of other weird characters and the built-in Helvetica can't handle it. Neither can Google's Noto fonts by themselves - I need to figure out how to declare the Noto Font Family in HexaPDF and I can't figure out how to do that with the given documentation. OpenSans was an improvement, but I still want more glyph coverage than that.
Update:
I used this method to set the font:
def self.pdf_summary_font
  @@pdf_summary_font ||= File.open(Rails.root.join('public',
'OpenSansEmoji.ttf'), 'r')
end
canvas = page.canvas(type: :overlay)
canvas.font(self.class.pdf_summary_font, size: 10)

However, no Noto font ever worked with this - I would get errors like "Missing glyph - 'A'"
The best I could do was to use OpenSansEmoji, and replace missing glyphs with the following block:
  begin
    style = HexaPDF::Layout::Style.new(font: canvas.font, fill_color: color, stroke_color: color, align: :left, valign: :center)
    fragment = HexaPDF::Layout::TextFragment.create(str, style)
    layouter = HexaPDF::Layout::TextLayouter.new(style)
    layouter.fit([fragment], w, h).draw(canvas, x1, y2)
  rescue HexaPDF::Error => e
    if e.message.include?('Glyph for')
      glyph =  e.message.match(/\{(.*?)\}/).captures.first
      str = str.grapheme_clusters.map do |char|
        if char.dump.include?(glyph)
          "\u{FFFD}"
        else
          char
        end
      end.join

      retry
    end

Answer: Have a look at https://hexapdf.gettalong.org/documentation/reference/api/HexaPDF/index.html and the configuration option "font_map". This allows you to declare any TrueType file and use it.
You could also use the path to the font file directly with the Canvas#font method.
If you need to cover a wide array of characters you need to use a single font that covers all of them, one of the fonts included in this ZIP file should probably work (Google says 582 languages, 237 regions included).
Comment: @getalong, thanks for your reply, any input on the solution I posted?
Comment: @EntaroAdun Could you provide a sample string that doesn't work for you?
Comment: @EntaroAdun Also have a look at the 'font.on_missing_glyph" configuration option - see https://hexapdf.gettalong.org/documentation/reference/api/HexaPDF/index.html . This allows you to specify custom behaviour for missing glyphs.


Why does deleting a node ALSO invoke hook_node_update?

Question: I need to respond to an update event and regenerate a file, but when the node is deleted, the file should also be deleted. However, the problem is, everytime a node is deleted, the hook_node_update is ALSO called, which regenerates the file.
How can I differentiate between a node being updated (NOT deleted) and a node being deleted?
Comment: I just added a basic hook_node_update and hook_node_delete to a fairly clean install and I am only seeing the update print when I update a node and the delete firing on delete (with no update). Do you have any custom validate or submit functions that might be causing the hook_node_update to fire? Can you recreate this issue on a clean install?
Answer: Thanks for your answers, much appreciated!
I finally managed to find the cause. The "problem" is caused by the module https://www.drupal.org/project/field_collection. My node has a field that is a field_collection, and apparently, when deleting a node, the field_collection items are first deleted from the node, which is then saved (which causes the update hook to fire), and only then the node itself is actually deleted.
It's pretty easy to workaround this issue once you actually KNOW what is causing it, in my case I modified the update hook to check for field_collection items in the node, if there were none it means the node is about to be deleted...
Answer: Following are the set of hooks which are invoked from node_delete function, which shows update hook will not be invoked.
<code>    node_invoke($node, 'delete');
    module_invoke_all('node_delete', $node);
    module_invoke_all('entity_delete', $node, 'node');
    field_attach_delete('node', $node);
</code>
Make sure you are not updating any other node when action is delete of node, something like
<code>   function my_module_node_delete($node) {
     node_save('any_node_id');
   }
</code>
Answer: No more workarounds needed.
This issue has been fixed in the latest dev version of Field collection:
https://www.drupal.org/node/2385985
Answer: Good question and good point!
But this is not just apply when you have field_collection but also any attached entity may have the same effect (hook node update may be called when  field_attach_delete is called in node_delete_multiple function), this can include the attached entity files (if you enabled file entity for example) and referenced nodes when you have chosen the option for deleting a parent node delete a child node!
Drupal automatically first delete attached entities and save the node each time (and hook node update will be called) and then continue the process (for example if you three field_collection fields, you will have three calls of hook node update (each time it deletes a field_collection from your node)!
In my case, my hook node update must react to deletion of a field_collection and I can't find any simple solution to determine the difference between an update of the node (when it is deleting a field_collection) and deleting the node (when again first it is deleting a field_collection and call node update)!
Anyway great question and mentioning an important point!


How to flip text horizontally?

Question: i'm need to write a function that will flip all the characters of a string left-to-right.
e.g.:

Thė quiçk ḇrown fox jumṕềᶁ ovểr thë lⱥzy ȡog.

should become

.goȡ yzⱥl ëht rểvo ᶁềṕmuj xof nworḇ kçiuq ėhT

i can limit the question to UTF-16 (which has the same problems as UTF-8, just less often).
Naive solution
A naive solution might try to flip all the things (e.g. word-for-word, where a word is 16-bits - i would have said byte for byte if we could assume that a byte was 16-bits. i could also say character-for-character where character is the data type Char which represents a single code-point):
String original = "ɗỉf̴ḟếr̆ęnͥt";
String flipped = "";
foreach (Char c in s)
{
   flipped = c+fipped;
}

Results in the incorrectly flipped text:

ɗỉf̴ḟếr̆ęnͥt
̨tͥnę̆rếḟ̴fỉɗ

This is because one "character" takes multiple "code points".

ɗỉf̴ḟếr̆ęnͥt
ɗ ỉ f ˜ ḟ ế r ˘ ę n i t ˛

and flipping each "code point" gives:

˛ t i n ę ˘ r ế ḟ ˜ f ỉ ɗ

Which not only is not a valid UTF-16 encoding, it's not the same characters.
Failure
The problem happens in UTF-16 encoding when there is:

combining diacritics
characters in another lingual plane

Those same issues happen in UTF-8 encoding, with the additional case

any character outside the 0..127 ASCII range

i can limit myself to the simpler UTF-16 encoding (since that's the encoding that the language that i'm using has (e.g. C#, Delphi)
The problem, it seems to me, is discovering if a number of subsequent code points are combining characters, and need to come along with the base glyph.
It's also fun to watch an online text reverser site fail to take this into account.

Note:

any solution should assume that don't have access to a UTF-32 encoding library (mainly becuase i don't have access to any UTF-32 encoding library)
access to a UTF-32 encoding library would solve the UTF-8/UTF-16 lingual planes problem, but not the combining diacritics problem
Comment: Interesting question but why are you trying to flip the string?  Lots of modern environments for displaying text can display it right-to-left for you.  What are you trying to do?
Comment: @DavidGrayson Pseudo-localization testing.
Comment: Oh noes! Another made-up problem! :)
Answer: The term you're looking for is "grapheme cluster", as defined in Unicode TR29 Cluster Boundaries.
Group the UTF-16 code units into Unicode code points (=characters) using the surrogate algorithm (easy), then group the characters into grapheme clusters using the Grapheme_Cluster_Break rules. Finally reverse the group order.
You will need a copy of the Unicode character database in order to recognise grapheme cluster boundaries. That's already going to take up a considerable amount of space, so you're probably going to want to get a library to do it. For example in ICU you might use a CharacterIterator (which is misleadingly named as it works on grapheme clusters, not 'characters' as Unicode knows it).
Comment: Yeah, you certainly wouldn't want to do it from scratch! But it's generally not too bad with a library to throw at it.
Comment: Sounds like a good avenue to pursue - but my god it looks well over my head.
Answer: If you work in UTF-32, you solve the non-base-plane issue.  Converting from UTF-8 or UTF-16 to UTF-32 (and back) is relatively simple bit twiddling (see Wikipedia).  You don't have to have a library for it.
Most of the combining characters are in a few ranges.  You could determine those ranges by scanning the Unicode database (see Unicode.org).  Hardcode those ranges into your application.  With that, you can determine the groups of codepoints that represent a single character.  (The drawback is that new combining marks could be introduced in the future, and you'd need to update your table.)
Segment appropriately, reverse the order (segment by segment), and convert back to UTF-8 or UTF-16 (or whatever you want).
Comment: UTF-32 still has the gotcha that *not every character is 4-bytes*. Still have the problems of diacritics.
Comment: @IanBoyd: That's the point I was attempting to make in the second paragraph.
Answer: Text Mechanic's Text Generator seems to do this in JavaScript. I'm sure it would be possible to translate the JS into another language after obtaining the author's consent (if you can find a 'contact' link for that site).
Comment: It doesn't reverse property (e.g. it generates `tͥnę̆rếḟ̴fỉɗ`)

How to flip text horizontally?


Subtract n from min value and then remainder of n from max value

Question: As the title says, I want to subtract n from min value and then remainder of n from max value. I thought I had this cracked until one of the values exceeds n.
My formula is =IF(C4=D4,C4-(B4/2),IF(C4<D4,MIN(SUM(C4:D4)-B4,0),MAX(SUM(C4:D4)-B4,0)))
The expected result in E4 should be 100 and F4 should be 69. What can I do to my existing formula to make this work correctly?
Comment: This seems as single worksheet issue. Am I missing something? OP, can you please clarify what are you trying to achieve? What is `remainder` for you in this case?
Comment: This is quite off-topic for Stack Overflow. Please see the information in the EXCEL tag: "General help regarding MS Excel for single worksheet functions is available at [Super User](https://superuser.com)".
Comment: @pnuts: Hi pnuts, (A) The functions the OP is trying to use are extremely simple, and most probably to implement a very specific business logic of his own. Basic Excel tutorials are strongly advised in this case. (B) By carefully reading this question, you'll notice there are lots of missing details on it. Zipa did his best effort to try to answer the question, but without editing the question to provide these details, it is impossible to get to a conclusion. Since the OP has to rewrite the question anyway for it to be a quality question, then why not to do it in the right place? Best Regards
Comment: I know what you mean. When the question refers to Excel VBA programming, then it is always welcome. Otherwise, I follow what is in the Excel tag's description, and in [this meta discussion](https://meta.stackexchange.com/questions/90919/which-stack-exchange-site-is-best-for-microsoft-excel-questions/90920). The Excel-formula tag mentions questions about the "structure, syntax, or output of an Excel formula", which is not the case. I'd love to answer Excel question here, but I feel some lack of support of S.O.'s question editor. A place specifically for spreadsheet questions would be great.
Answer: For E4 it seems that you want:
=IF(C4=D4,C4-(B4/2),IF(C4<D4,MIN(C4,D4-B4,0),MAX(C4,D4-B4,0)))

But I'm not sure what are you trying to do with F4.
Comment: @pnuts Good point, results are rubbish, if question update occurs at some point I'll edit the answer :)


EF: Clear Collection Property without First Getting Data

Question: I have a class called Facility.  Facility has a collection property on it called Employees.  I'm using the disconnected layer of EF.  I want to clear the Employees collection from a specific facility, but I don't want to make two trips to the DB: (1) getting all the employees, and then (2) clearing the.  How can I do this?
Here's what I've tried...
Facility f = new Facility()
{
    Id = 4,
    Employees = new List<Employee>()
};
context.Facilities.Attach(f);
context.Entry<Facility>(f).Collection(fac => fac.Employees).IsLoaded = true;

context.SaveChanges();

I think I'm close, but it doesn't work.  Thanks for the advice.
Comment: `Employees` entity has a FK property to `Facility`, right?. What do you want to do with the related employees, delete them?. Could you post your entities?
Comment: I don't want to delete the employees.  I just want to clear the relationship; therefore, I want to keep my current employees as well as my facility, but I want to clear the employees FROM the facility.  In essence, it will look like a new facility.
Comment: And the relationship between `Employees` and Facility is optional? In other words, `FacilityId` FK in `Employees` allows null values?
Answer: If you want to use EF only, you're always going to need some roundtrip. In the end, EF needs to generate DELETE ... WHERE Id = x statements. How would it know the values for x without first grabbing them from the database?
But of course you can do this in a more efficient way than fetching the complete Employee objects. It's enough to get the Id values. Then you can use these Ids to create stub entities that you mark as Deleted:
var ids = context.Empoyees.Where(e => e.FacilityId == 4)
                 .Select(e => e.Id).ToArray();

foreach(int id in ids)
{
    var emp = new Empoyee { Id = id }; // Stub entity
    context.Entry(emp).State = System.Data.Entity.EntityState.Deleted;
}

context.SaveChanges();

This is pure EF. But you can also use EntityFramework.Extended. This allows you to execute a statement like
context.Empoyees.Where(e => e.FacilityId == 4)
       .Delete();


Php and Mysqli how to echo break of line

Question: Hi guys when I save with php some part of text (with break of lines) for example:
this is

an example

in my database I see like I wrote it

But when I echo this data from my database I see it wrong

Can you help me?
My code is this
echo '
' . $date . "
";
echo '
' . $posts . "
";

Comment: What is wrong with the display? Looks OK from here.
Answer: you can check nl2br function (http://php.net/nl2br)
echo '
' . $date . "
";
echo '
' . nl2br($posts) . "
";

Answer: The problem is that HTML doesn't break line with newline character.
PHP provides a function that converts newlines to
 tags.
http://www.w3schools.com/php/func_string_nl2br.asp


positive values of $a$ for which the equation $\lfloor x+a \rfloor = \sin \left(\frac{\pi x}{2}\right)$ will have no solution

Question: The  positive values of $a$ for which the equation $\displaystyle \lfloor x+a \rfloor = \sin \left(\frac{\pi x}{2}\right)$ will have no solution is,
where  $\lfloor x \rfloor = $ floor function of $x$
Options
$(a)\;\;(0,1)$
$(b)\;\; (1,2)$
$(c)\;\; (0,2)$
$(d)$ None of these
$\bf{My\; Try::}$ Using the formula $x-1<\lfloor x \rfloor \leq x.,$ we get $\displaystyle (x+a)-1< \lfloor x+a \rfloor \leq (x+a)$
Now Given $\displaystyle \lfloor x+a \rfloor = \sin \left(\frac{\pi x}{2}\right).$ So $\displaystyle (x+a) - 1<\sin \left(\frac{\pi x}{2}\right)\leq (x+a)$
Now we will solve $\displaystyle (x+a)-1<\sin \left(\frac{\pi x}{2}\right)$ and $\displaystyle (x+a)\leq \sin \left(\frac{\pi x}{2}\right)$ for Common values of $x$
But I Did Understand How can I solve it
Help me
Thanks
Answer: observe that $\sin(\frac{\pi x}{2})$ only takes integer values for integer $x$'s, hence we can restrict our attention to $x \in \mathbb{Z}$ and so the floor function becomes obsolete. Now, the situation is even better, since there aren't plenty of integer values $\sin$ can take - it's just $-1,0$ and $1$, therefore, since it's a test question the simplest way would be to check all the posibilities. Let me do point a) and I hope you'll finish the rest by yourself following what I do.
first let $a = 0$. we want an integer $x$ such that $x = \sin(\frac{\pi x}{2})$. all values we need to check are $1,0,-1$. $x=1$ works, so we're done, that can't be the answer.
we could now cross answer a) as a wrong one, but nevertheless let me do the case of $a=1$ so that its more instructive
if $a = 1$ then we're looking for $x$ s.t.
$$ x+ 1 = \sin(\frac{\pi x}{2})$$
because of what've said about the range of $\sin$ we only need to check $x = 0$, $x = -1$ and $x = -2$.
$x = 0$ won't work since it leads to
$$1 = 0$$
$ x = -1$ doesn't work either cause we get
$$ 0 = -1$$
finally $x = -2$ gives
$$-1 = 0$$ which isn't true either, so for $a=1$ there are no solutions to your equation.
Comment: W|A shows two solutions for $a=1$. http://www.wolframalpha.com/input/?i=floor%28x%2B1%29%3Dsin%28pi+x%2F2%29
Comment: it's a numerical computation which in this case yields a wrong result, check it for yourself / try to find a gap in my proof
Comment: although the answer would change if we defined the floor function in such a way that $[x] < x$ for all $x$, i.e. $[1] = 0$, but that's uncommon and I'm pretty sure it's not the case in wolfram


SQL Calling Columns in Temporary Tables

Question: So I would like to preface that this IS an assignment for school, but I'm not asking for the answer, I'm just wondering if there is a way to call upon columns from a temporary/renamed table. Also, I'm wondering if a subquery or some other technique would be better suited/if I'm on the right track.
The context of my code is that we have a table 'sailors' with columns 'sname,' 'age,' 'rating,' and 'sid (which seems irrelevant for this particular question)'
I'm to find the names of the sailors older than the oldest sailor with a rating of 3. Here's what I have currently, it's probably rough. Thanks!
select *, max(age)
from sailors as ThreeStarGeriatric
where rating = 3
union
select *
from sailors
where sailors.age > ThreeStarGeriatric.age;

Comment: [Google-fu](http://devzone.advantagedatabase.com/dz/webhelp/advantage8.1/adssql/using_temporary_tables_in_sql_statements.htm) is your 2nd best resource for coding. Also, try your code and tell us the error you get. I bet you it'll give you a great error code that will set you on the right path. Also, [SQLFiddle](http://sqlfiddle.com/) exists now. Wish I had that when I was in school
Comment: You can use HAVING, but it's not a good idea.
Comment: Try thinking about your question in Query speak... select name from sailor where age is greater than select age of oldest sailor where rating = 3
Comment: Points for humor `ThreeStarGeriatric`
Comment: Thanks guys! ^  G B, I used a subquery with those constraints. It pretty much looked like what mech posted.
Answer: you COULD use a subquery:
SELECT sname FROM sailors WHERE age > (SELECT MAX(age) FROM sailors WHERE Rating=3)

"names of the sailors older than the oldest sailor with a rating of 3"
Comment: Thanks for the help, the thought to use a subquery in the where clause didn't occur to me until after I'd posted. It seems obvious now, haha.

SQL Calling Columns in Temporary Tables


How do I calculate the following probability?

Question: Let's say there are 5 cats and 20 dogs and you get a random group of 2 animals. What is the probability that you end up with a dog and a cat? All possible combinations where you get a cat and a dog are $5\cdot20$ and all possible combinations are $C_{25}^2=\frac{25\cdot24}{2!}$ so $P(\text{a cat and a dog})=\frac{5\cdot20\cdot2!}{25\cdot24}=\frac{1}{3}$. However my textbook says the probability is actually $\frac{1}{6}$ and i can't figure out why. Do you have any idea?
Answer: Your solution is correct.  The probability of selecting a cat and a dog when two of the $25$ animals are selected at random is
$$\Pr(\text{a cat and a dog}) = \frac{\dbinom{5}{1}\dbinom{20}{1}}{\dbinom{25}{2}} = \frac{1}{3}$$
The probability of selecting a dog and a cat in that order is
$$\Pr(\text{dog then a cat}) = \frac{20}{25} \cdot \frac{5}{24} = \frac{1}{6}$$
However, the way the problem is worded, you would also have to consider the probability of selecting a cat and a dog in that order, which is
$$\Pr(\text{cat then a dog}) = \frac{5}{25} \cdot \frac{20}{24} = \frac{1}{6}$$
Adding those two probabilities gives your correct answer.