Is the REFERER set if you redirect to a new web page using location.href =?

Question: If you redirect a user to a new web page using the javascript location.href = <url>, what REFERER header does the destination web server see?
Answer: With some exceptions, the header sent is of the page with the redirect on it, not the referrer of the page that did the redirect. This is in contrast to server-side redirects, which preserve the original referrer.
So, if a visitor goes from A.html to B.html, and B.html triggers a location.href redirect to C.html, the web server will see B.html as the referrer. (If you did the redirect from B.html to C.html on the serverside, A.html would be the referrer for C.html.)
Older versions of Internet Explorer will send a blank header, as will (as always) redirects from HTTPS to HTTP.
Comment: Sorry, could you clarify what you mean by "the referrer beforehand"?
Answer: it sees the page it came from, just like clicking on a link.
To test this from any page, redirect to a phpinfo() page or any other page that echos headers, for example:
window.location='http://hosting.iptcom.net/phpinfo.php';

(page pulled from random google search)
Answer: Most browsers will pass a HTTP_REFFERER with location.href, but IE in some cases does not.
If the refferers are really important to you, then you could do this:
function goTo(url) {
 var a = document.createElement("a");
 if(!a.click) { //Only IE has .click so if it doesnt exist use the simple method where the refferer is passed on other browsers.
  location.href = url;
  return;
 }
 a.setAttribute("href", url);
 a.style.display = "none";
 (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(a);
 a.click();
}


Distribution of $\frac{\sum_{i=1}^n X_iY_i}{\sum_{i=1}^n X_i^2}$ where $X_i,Y_i$s are i.i.d Normal variables

Question:
Suppose $X_1,\ldots,X_n,Y_1,\ldots,Y_n$ are i.i.d $\mathcal N(0,1)$ random variables.
I am interested in the distribution of $$U=\frac{\sum_{i=1}^n X_iY_i}{\sum_{i=1}^n X_i^2}$$

I define $$Z=\frac{\sum_{i=1}^n X_iY_i}{\sqrt{\sum_{i=1}^n X_i^2}}$$
Then, $$Z\mid (X_1=x_1,\ldots,X_n=x_n)=\frac{\sum_{i=1}^n x_iY_i}{\sqrt{\sum_{i=1}^n x_i^2}}\sim \mathcal N(0,1)$$
As this conditional distribution is independent of $X_1,\ldots,X_n$, the unconditional distribution should also be the same. That is, I can say that $$Z\sim \mathcal N(0,1)$$
Relating $U$ and $Z$, I have $$U=\frac{Z}{\sqrt{\sum_{i=1}^n X_i^2}}$$
Now since I saw that $Z\mid (X_1,\ldots,X_n)\stackrel{d}{=}Z$, I can say that $Z$ is independent of $X_1,\ldots,X_n$.
So I have
$$U=\frac{1}{\sqrt n}\frac{Z}{\sqrt{\frac{\sum_{i=1}^n X_i^2}{n}}}=\frac{T}{\sqrt n}$$, where $T$ is distributed as a $t$ distribution with $n$ degrees of freedom.

I think conditioning is the easiest way to see the result here. But is this a perfectly rigorous argument and is there any direct/alternative way of finding distributions of such functions of linear combinations of i.i.d Normal variables?
Comment: This looks just like the least squares estimator in a regression without constant. It is, under the assumptions given, known to be normally distributed with mean $\beta$ (that would be zero if the $Y$ are independent of the $X$, too) and variance covariance matrix $\sigma^2(X'X)^{-1}$. You'd arrive at a t-distribution if you also need to estimate $\sigma^2$.
Comment: Re your independence argument: Let $(X,Y)$ be standard bivariate Normal.  Define $Z=|X|$ when $Y\ge 0$ and otherwise $Z=-|X|.$ You can easily check that the marginal distribution and conditional distributions of $Z$ (given $Y$) are standard Normal, but certainly $Z$ is not independent of $Y$!  *Equivalence in distribution is usually too weak to imply independence.*
Comment: @whuber the conditional distribution of Z given Y cannot be a standard normal: given Y, Z can only be of the same sign.
Comment: In the special case of $n=1$ we have $X_1Y_1/X_1^2 = Y_1 / X_1$, and the ratio of two independent standard normals [is Cauchy distributed](https://en.wikipedia.org/wiki/Ratio_distribution#Uncorrelated_central_normal_ratio).
Comment: I think your approach looks very reasonable to me. I didn't test it myself but it might be an alternative to start with Chi-square distribution in the denominator?
Comment: @StubbornAtom is this self-study?
Comment: @MartijnWeterings No.
Comment: What do you need this variable for? What is the problem exactly with the rigour of the argument?
Comment: @MartijnWeterings I don't need it for anything. Problem was not much about rigour; I was interested in an alternative proof (if there exists one) that doesn't involve conditional distributions.
Comment: @a.arfe You are correct, thank you: in that comment I wrote "conditional" where I intended "marginal."
Comment: What if you didn't define $Z$ at all. Based on your argument, $U|X_i$ is also independent of $X_1,X_2,..X_n$. So, now $U \sim N(0,1)$?
Comment: @Xi'an I think your comment is about $Z$ (which has a square root in the denominator), whereas mine is about $U$ (third line, no square root).
Answer: Although this is a conditional argument as well, using the characteristic function is faster:
\begin{align*}
\mathbb E\left[\exp\left\{ \iota t\sum_i Y_i X_i\Big/{\sum_j X_j^2}\right\}\right] &=
\mathbb E\left[\left.\mathbb E\left[\exp\left\{\iota t Y_i X_i\Big/{\sum_j X_j^2}\right\}\right]\,\right|\,\mathbf X \right]\\
&=\mathbb E\left[\left.\mathbb E\left[\prod_i \exp\left\{\iota t Y_i X_i\Big/{\sum_j X_j^2}\right\}\right]\,\right|\,\mathbf X \right]\\
&=\mathbb E\left[\prod_i\left.\mathbb E\left[ \exp\left\{ t Y_i X_i\Big/{\sum_j X_j^2}\right\}\right]\,\right|\,\mathbf X\iota \right]\\
&=\mathbb E\left[\prod_i \exp\left\{- t^2 X_i^2 \Big/2\left\{\sum_j X_j^2\right\}^2\right\}\right]\\
&=\mathbb E\left[ \exp\left\{- t^2 \Big/2{\sum_j X_j^2}\right\}\right]\\
\end{align*}
Invoking Wolfram's integrator, this expectation is equal to
$$\int_0^∞ \zeta^{n/2 - 1} \frac{\exp(-\zeta - t^2/\zeta)}{Γ(n/2)}\ \text{d}\,\zeta = \frac{2 t^{n/2} K_{-n/2}(2 t)}{Γ(n/2)}$$
where $K_n$ is the modified Bessel function of the second kind. Hence, except for $n=1$ this is not the characteristic function of the Cauchy distribution. This looks instead like the characteristic function of the Student's $t$ distribution.
Comment: Do you use the independence of $X_i$ and $Y_i$ here? I don't seem to use it in my attempt, so I am thinking if this assumption changes anything.
Comment: Yes I do, when going from third to fourth line in the equation.


Get class which isn't in any namespace

Question: How can I get access to a class which isn't in any namespace ? I'm writing building scripts.
Comment: What are you currently trying, and what is the error message you're getting?
Answer: You simply refer to it by class name. Eg:
public class Foo
{
}

You simply refer to it as Foo.

Get class which isn't in any namespace


Meaning of 'resolution' in regression

Question: I'm reading a paper and wonder what 'resolution' mean in this context.

To speed the regression process, we use scale factors to quantize each
of these variables as integers. The resolution of variable 1 (Time)
is one second. The resolution of the dimensionless variable 2 is 0.1. The resolution of variable 3 (Altitude) is 200 ft.

Does resolution mean 'unit' in this context?
Comment: I read this as the smallest possible difference between values reported.  so that you are measuring to the nearest mm, km, g or whatever.  So times for 100 m sprint or dash were reported to a resolution of 0.1 s when I was young and now are reported to a resolution of 0.01 s.
Comment: "Quantize" evidently means to *bin* the data.  The "resolution" is the common width of the bins.  Without more context, it is unclear how this procedure would "speed the regression process," if at all.  Typically it does not improve the statistical features of the regression, because it loses some information.
Answer: It means that you can tell when objects are separated by $200$ feet of altitude. If they are separated by $201$ feet, they appear to have different altitudes. If they are separated by $199$ feet, they do not.
This terminology is common in sciences that use microscopes (telescopes, too). A microscope that can distinguish features that are a nanometer apart lets you see more detail than your naked eye that can distinguish features that are millimeters or perhaps centimeters apart. You might get a better sense of how this works by reading about microscopes, since it turns out that there's really nothing statistical about this issue.

Meaning of 'resolution' in regression


MYSQL query doubt - storing selected value to variables

Question: i am using a stored procedure. i declared 2 varaibles . shown below
DECLARE pProductCode          VARCHAR(15);

 DECLARE pProductVersion       VARCHAR(30);

i am selecting ProductCode and prodcuctVersion using a query from a table . shown below
 SELECT  ProductCode, ProductVersion
        FROM packages
       WHERE PackageID = pPackageID;

my question is how can i store the selected values productcode and productversion to the declared variables pProductCode and pProductVersion respectively.
i tried this
 SELECT pProductCode = ProductCode, pProductVersion = ProductVersion
        FROM packages
       WHERE PackageID = pPackageID;

but its not working
Answer: In MySQL to store a column in a variable we use a SELECT INTO statement.  For example:
SELECT ProductCode, ProductVersion
  INTO pProductCode, pProductVersion
  FROM packages
 WHERE PackageID = pPackageID;

packageID is a parameter.


DropDownList SelectedIndexChanged not getting fired

Question:
Possible Duplicate:
ASP.Net: DropDownList's SelectedIndexChanged event not firing

I created a new ASP.NET default website from Visual Studio. I have used a drop down list control on my .aspx page and set the data source for it, which is working fine.
However, I need to use the SelectedIndex_Changed event for this DDlist, which is not getting fired due to unknown reasons. I have tried putting breakpoints inside the event, but it doesn't even fall inside the function.
Any idea what could be wrong?
Comment: Did you set it's AutoPostBack property to true?
Answer: Try setting AutoPostBack to True
Answer: Just check that have you put AutoPostBack="true" in dropdown!
Answer: Assuming you haven't changed the AutoPostBack property to False, make sure that your databound ListItems have unique values. Also, the event is SelectedIndexChanged, not SelectedIndex_Changed,


Expected number of red balls after blue balls

Question: So this question was asked in a recent online test of an HFT.
There are 5 red balls and 7 blue balls arranged in a line. Find the expected number of blue balls that are immediately followed by red balls.
Can someone suggest how to use linearity of expectation here:

I came up with the following relation
$E_{n,r}=\frac{r*(r-1)}{n*(n-1)}E_{n-2,r-2}+\frac{r*(n-r)}{n*(n-1)}E_{n-1,r-1}+\frac{(n-r)*(n-r+1)}{n*(n-1)}E_{n-2,r}$.

where n: is the total number of balls and r is the total number of red balls. Is there any flaw in my approach?

PS:
Do ask if more clarifications are required.
Answer: You can check if your formulation gives the same answer as mine. As asked by you, I shall  use linearity of expectation to greatly simplify the computations.
P(a blue ball is in any position) $=\frac7{12}$
P(a red ball is in any position) $= \frac5{12}$
Also, for P( a blue ball is immediately followed by a red one), the probability of a blue-red pair occupying any two adjacent positions will be the same by symmetry, hence the same as a blue-red pair occupying positions $1$ and $2$
Let $X_i$ be an indicator variable that $=1$ if a blue-red pair starts at $i$, and $0$ otherwise, then
$P[X_i]=\frac7{12}\frac5{11}=\frac{35}{132}$
Now the expectation of an indicator variable is just the  probability of the event it indicates,
thus $\mathbb E[X_i]= \frac{35}{132}$
Such blue-red pairs can start at any of the first $11$ positions, thus by linearity of expectation, which operates even when the random variables are not independent,
$\mathbb E[X]=11\cdot\frac{35}{132}=\frac{35}{12}$


Pandas - Column Addition for duplicate or list values in a column in Dataframe

Question: Lets say a dataframe looks like this
  one  two
a  1.0  1.0
b  2.0  2.0
c  3.0  3.0
d  NaN  4.0

Adding new three column is like this
df["three"] = df["one"] * df["two"]

Result
   one  two     three
 a  1.0  1.0    1.0
 b  2.0  2.0    4.0
 c  3.0  3.0    9.0
 d  NaN  4.0    NaN

How about colum values that contains duplicate lists or list, and I need to create a new column and add the number with highest value
Example
    one  two
 a  1.0  [12,1]
         [12,1]
 b  2.0  2.0
 c  3.0  3.0
 d  NaN  4.0

So I want like this
    one  two        flag
 a  1.0  [12,1]      12
         [12,1]
 b  2.0  [200,400]   400
 c  3.0  3.0         3.0
 d  NaN  4.0         4.0

Thanks
Comment: Can you add for second DataFrame `df.to_dict('list')` to question ?
Answer: If there is list or nested lists or floats you can flatten lists with max:
df = pd.DataFrame({"two":  [[[12,1],[12,1]] ,[200,400] ,3.0,4.0 ]})

from typing import Iterable

#https://stackoverflow.com/a/40857703/2901002
def flatten(items):
    """Yield items from any nested iterable; see Reference."""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            for sub_x in flatten(x):
                yield sub_x
        else:
            yield x

df['new'] = [max(flatten(x)) if isinstance(x, list) else x for x in df['two']]
print (df)
                  two    new
0  [[12, 1], [12, 1]]   12.0
1          [200, 400]  400.0
2                 3.0    3.0
3                 4.0    4.0

EDIT: For max in new DataFrame for all columns use aggregate function max:
df = df_orig.pivot_table(index=['keyword_name','volume'],
                    columns='asin',
                    values='rank',
                    aggfunc=list)

df1 = df_orig.pivot_table(index=['keyword_name','volume'],
                     columns='asin',
                     values='rank',
                     aggfunc='max')

out = pd.concat([df, df1.add_suffix('_max')], axis=1)

Comment: I tried the updated answer, but it create new columns for each column.What I want instead is to get max value of all columns and put it in new colum. This one works `[max(flatten(x)) if isinstance(x, list) else x for x in df['column1']]`. But it will only get the max of the specific column. Lets say it has columns ['column1','column2','column3']. I just dont know how to get the max for all columns like `[max(flatten(x)) if isinstance(x, list) else x for x in df[['column1','column2','column3']]]` <-(this will not work)
Comment: Instead of column `two` (df['two']) , I have a dynamic columns of asins as per this question https://stackoverflow.com/questions/72435171/transforming-list-of-dicts-to-pandas-dataframe-with-dynamic-header-columns/72435254?noredirect=1#comment127964770_72435254, so its asin might contain duplicated or repeated lists
Comment: i recreated it https://onlinegdb.com/xzM_j8e7T
Comment: I also tried  ` for col in df.columns:
                          df["new"] = [max(flatten(x)) if isinstance(x, list) else x for x in col ]`
Comment: @ira - answer was edited.
Comment: I need to retain the original values in each columns and create a new colum to store the max value for each rows
Comment: @ira - answer was edited.
Comment: @ira - so need `df1 = df[['column1','column2','column3']].applymap(lambda x: max(flatten(x)) if isinstance(x, list) else x)` ?
Comment: After some digging into pandas docu, I solved it by adding ` margins=True,
            margins_name="max_value"` in pivot_table, but I am wondering some of rows not calculated properly, so the max_values not all accurate...


Why is ThemeProvider (Material UI) not working for me here?

Question: I've used Material UI quite a lot, so this is baffling. I've looked through the docs, I've checked my code, I can't see the issue. I want my H2 tag in the nested component to use Arial. However, it's rendering using Times. I'm not sure why.
Here's my index.tsx:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { Provider } from "react-redux";
import configureStore from "./redux/stores/main";
import * as serviceWorker from "./serviceWorker";
import { createMuiTheme } from "@material-ui/core";
import myTheme from "./styling/mainTheme";
import { ThemeProvider } from "@material-ui/styles";

const theme = createMuiTheme({
  typography: {
    fontFamily: ["Arial"].join(",")
  }
});

ReactDOM.render(
  <ThemeProvider theme={theme}>
    <Provider store={configureStore()}>
      <App />
    </Provider>
  </ThemeProvider>,
  document.getElementById("root")
);

serviceWorker.unregister();

My app component:
import React from "react";
import { useSelector } from "react-redux";
import HeaderContainer from "../containers/layout/header/HeaderContainer";
import { ThemeProvider, useTheme } from "@material-ui/styles";
import theme from "../styling/mainTheme";
import { createMuiTheme } from "@material-ui/core";

const App: React.FC = () => {
    const theme = useTheme();
  return (

          <HeaderContainer />

  );
};

export default App;

The header container (will contain logic):
  import * as React from 'react';
import Header from '../../../components/layout/header/Header';

export interface HeaderContainerProps {
}

export default class HeaderContainer extends React.Component<HeaderContainerProps> {
  public render() {
    return
  }
}

And finally the header:
import * as React from "react";
import { styled } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";

export default function Header() {
    return (
        <AppBar>

Hello

        </AppBar>
    )
}

I've tried putting the ThemeProvider in different components, but my h2 is still rendering as Times. Would be great if someone could spot the issue. Thanks
Answer: Checking the documents of material-ui it turns out you have imported some of the things from library in a wrong way. Like the docs state -
import { useTheme } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

Which can basically be
import { useTheme, createMuiTheme } from '@material-ui/core/styles';

Same goes for ThemeProvider
import { ThemeProvider } from '@material-ui/core/styles';

Comment: Hi, thanks for this. I would say that's an ES6 syntax issue rather than a MUI thing - but at any rate I think the issue might be because of how I'm using the appbar. I'll have another look. Thanks for your help
Comment: I get what you mean. Importing using destructuring and all but instead of importing `import { useTheme, createMuiTheme } from '@material-ui/core/styles` like this you are importing `import { ThemeProvider, useTheme } from "@material-ui/styles";`. I haven't used material ui yet but i think the import is a bit wrong.
Answer: In MUI V5 you need to import ThemeProvider and createTheme from @mui/material/styles instead of @mui/styles.
import * as React from 'react';
import ReactDOM from 'react-dom';
import {red} from '@mui/material/colors';
import { ThemeProvider, createTheme } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: {
      main: red[500],
    },
  },
});

function App() {
  return <ThemeProvider theme={theme}>...</ThemeProvider>;
}

ReactDOM.render(<App />, document.querySelector('#app'));

source
Comment: Thanks for this. I was importing ThemeProvider from emotion/react and and CreateTheme from mui/system and almost spent half a day trying to figure it out
Comment: This is the answer! thanks. Weird that there is no compilation error.


When given the soprano and bass parts, how do I figure out the alto and tenor?

Question: I missed one class and now I don't understand how to do this assignment plz help
Comment: I'm voting to close this question because, as phrased, it is very unlikely to help anyone else.
Comment: It kinda seems like either you missed more than one class or that class was four hours long.
Comment: Is the problem that you don't know what you're supposed to do, or is it that you're having trouble doing it?
Comment: both I kindve know what to \do but at the same time I have no clue
Comment: I'd love to help but this kind of question isn't covered here. There's a chat channel here that would be a great place to get help. You need a reputation score of 20 to use it, but that can be gained pretty easily. Meanwhile—can you ask your instructor for help? Maybe that's the best bet!
Comment: The purpose of assignments is to exercise (and prove, mostly to yourself) knowledge about a subject, in order to have better understanding of its aspects, which are probably fundamental to your learning. If you missed a class and don't understand its assignment, then your problem is not about *that* understanding. Even if we tried to explain what's being asked, you'd still probably be unable to do it, because either you won't understand our explanation, or you don't have means to solve it, and that's exactly because you missed an important class. Ask your schoolmates or, better, your teacher.
Answer: In each exercise, the soprano and bass notes either imply specific chords, or the musical context does.
The first exercise for example:

Looking at the final two notes, D and F, suggests either a Bb major chord or a D minor chord.
Given the key signature of one flat (either F major or D minor), we can conclude the final chord will be D minor.
The preceding chord has A and E given, which could be A major or A minor. Since A major is the dominant chord of D minor, we can conclude A major as the correct chord.
After repeating this process for the other chords, it just remains to fill out the chords in the alto and tenor using the voice-leading rules that were, presumably, taught in earlier classes.
Comment: @sillysnail417 This page (https://kaitlinbove.com/voice-leading) looks like a good starting place.
Comment: is there a youtube video you could direct me toward that has more in depth information on this because I dont want to like ask too much but I have like 7 new questions stemming from your answer.


Jax-rs Swagger integration - fetching resource list: http://localhost:8080/JAXRS-Example/rest/api-docs

Question: I am trying to integrate JAX-RS and Swagger together. While doing that I see following error is coming. After spending a lots of hours still I am not able to resolve it. Looking quick help from your end.

I've attached my whole source code in the git repository: https://github.com/JavaNeed/JAXRS-Example. Please try to resolve this error.
Comment: Please consider a modern version of swagger.  You are using 1.3.8 which is over 2 years old.  There are samples at https://github.com/swagger-api/swagger-samples that will help get you going.
Answer: I faced similar issues integrating swagger and jax-rs. I finally got them resolved using jersey servlet implementation. See if following project helps you.
https://github.com/sanketsw/jax_rs_REST_Example
Also following link has the details of how to get JSON and YAML specification from JAX-RS API
https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5


Propagation of polynomial coefficient errors in fit

Question: I fit a cubic function (in mathematica)
$$
y(x) = a + b x + c x^2 + d x^3
$$
to my data and obtained a function.
I have the error in each coefficient ($\sigma_a$, $\sigma_b$, $\sigma_c$, $\sigma_d$). Now since I need the model to predict $y$ values for a given $x$ value, I also need a corresponding error for the $y$ value (coming from the errors in the coefficients).
The error in the $x$ value (from our measurements) is negligible. I can't figure out the formula I would use when plugging in an $x$ value to determine its corresponding error in $y$.
I've exhausted my googling capabilities and my textbooks in error analysis. Any help is greatly appreciated.
Comment: Polynomial regression seems like the obvious choice here, given that you are willing to consider you $x$ measurement error negligible.  A "quick and dirty" approach (the first that came to my mind) is to do ordinary least squares of $y$ on $(1,x,x^2,x^3)$.  Then just use standard prediction formula from that.  Perhaps I am missing something?
Comment: you will also need to know the pairwise covariances between each of the coefficient estimates to get a variance for the predicted value of $y$. Assuming the predictor $x$ is not symmetric around 0, the covariance between, $x$ and $x^{2}$, for example, will be non-zero. From there (conditioned on the value of $x$), you just need to use the formula for the variance of a sum.
Answer: The question appears to ask for a predicted value and for a prediction interval about that value.
The predicted value is obtained by means of the formula using the estimated parameters and a specified value of $x$:
$$\hat{y}(x) = \hat{a} + \hat{b} x + \hat{c} x^2 + \hat{d} x^3.$$
In general, the uncertainty in $\hat{y}(x)$ comes from three sources:

Uncertainty in the parameter estimates $\hat{a}$, ..., $\hat{d}$ due to assumed randomness of the original data.  An explicit probability model makes sense of this.  In most settings, the model is additive.  That is, for any datum $(x_i,y_i)$ it assumes
$$y_i = a + b x_i + c x_i^2 + d x_i^3 + \varepsilon_i$$
where $\varepsilon_i$ is a random variable with zero expectation.  Furthermore, absent any information to the contrary, it is often the case that the $\varepsilon_i$ are independent of each other and have similar distributions.  These assumptions allow us to estimate that common distribution from the data.
Uncertainty in the actual value that would be observed at a given value $x$.  This uncertainty is now directly evident in the preceding model: it is the contribution of $\varepsilon$.
Uncertainty in the true value of $x$.  In the original question this is explicitly assumed to be inconsequential.

Therefore we would expect the prediction interval formula to depend on three estimates: (i) the predicted value, (ii) the uncertainty in the predicted value due to the parameter uncertainty in (1) above, and (iii) the estimated variance of $\varepsilon$ (from (2) above).  The parameter uncertainty plays a relatively small role for values of $x$ close to the average of the data $x_i$, but as $x$ moves away from this average, the parameter uncertainty makes an ever greater contribution.
Formulas can be found by searching this site for "prediction interval."  In one thread, @Rob Hyndman gives a general formula that is directly applicable to this question.  It assumes the parameters are estimated using least squares.  For a design matrix $X$, the formula takes the form
$$\hat{y} \pm k_\alpha \hat{\sigma} \sqrt{1 + \mathbf{X}^* (\mathbf{X}'\mathbf{X})^{-1} (\mathbf{X}^*)'}.$$
($\mathbf{X}^*$ is determined by $x$ and $\mathbf{X}'\mathbf{X}$ encodes the variances and covariances of the $x_i$.)
This contains parts we can explicitly match to (i), (ii), and (iii):
(i) The interval is centered around the predicted value $\hat{y}$.
(ii) The parameter uncertainty appears in the term  $\hat{\sigma} \sqrt{\mathbf{X}^* (\mathbf{X}'\mathbf{X})^{-1} (\mathbf{X}^*)'}$.  The stuff inside the square root measures a squared distance between $x$ and the average of the $x_i$.
(iii) The contribution of $\varepsilon$ appears as the "$1$" (multiplied by $\hat{\sigma}$) added to the parameter uncertainty.  We recognize this as the usual Pythagorean formula for the variance of a sum of independent random variables: take the square root of the sum of their squares.
As usual, the coefficient $k_\alpha$ is chosen to achieve a desired level of confidence.  It depends on that level, $1-\alpha$, and on assumptions about how the $\varepsilon_i$ are distributed.

A comment to the original question prompts me to remark that considerations of correlation among the variables $1$, $x$, $x^2$, and $x^3$ are not relevant.  Such correlations do of course exist in general--it is a rare situation in which our variables are mutually orthogonal--but the correlations are already accounted for in the least squares regression machinery.  It is wise to check that the correlations are not so great that they introduce numerical instability in the solutions.  That is unlikely in this particular problem.
Another comment also calls for another follow-up remark to emphasize one point: the presence of the second source of uncertainty (the contribution of $\varepsilon$, which is usually material) shows that we need to do more than consider the variances and covariances of the estimates $\hat{a}$, ..., $\hat{d}$: we also need to incorporate the contribution of $\varepsilon$ in the estimated uncertainty of $\hat{y}(x)$.
Comment: Really appreciate how meticulous and well informed your response is.  I will respond more once I am sure I fully look through and understand your response (Statistics are definitely one of my weaknesses)


Como gerar um ID dinâmico para minha Button com PHP e passar para o JS?

Question: Estou tentando usar o PHP com o Sweet Alert já tentei com ID FIXA e funciona.
Estou tentando isso:
 while ($row = mysqli_fetch_assoc($sql)) {
                            echo '
';
                            echo '' . $row['id_apoio'] . '	';
                            echo '' . $row['nome_apoio'] . '	';
                            echo '' . $row['email_apoio'] . '	';
                            echo '' . $row['tel_apoio'] . '	';
                            echo '' . $row['cel_apoio'] . '	';
                            echo '' . $row['cargo_apoio'] . '	';
                            echo '' . $row['especialidade_apoio'] . '	';
                            echo '' . $row['conselho_apoio'] . '	';
                            echo '<button class="bg-transparent border-0 d-block mx-auto" onclick="location.href=\'cadastro-completo-apoio.php?cadastro='. $row['id_apoio'] .'\'">
	';
                            echo '<button class="bg-transparent border-0 d-block mx-auto" onclick="location.href=\'editar-apoio.php?edita='. $row['id_apoio'] .'\'">
	';
                            echo '<button class="bg-transparent border-0 d-block mx-auto sweet-alert" id="'.$row['id_apoio'].'">
</button>';
                        }
                        ?>

JS:
    document.getElementById('<?php $row['id_apoio']?>').onclick = function(){
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary file!",
            type: "info",
            showCancelButton: true,
            confirmButtonClass: 'btn-primary',
            confirmButtonText: 'Primary!'
        });
    };

o botão servirá para confirmar a exclusão do item
Answer: Não precisa usar id pra pegar o click. Basta pegar por uma classe no botão. Acrescente mais uma classe no botão, algo como deletar, ficando assim as classes:
class="bg-transparent border-0 d-block mx-auto sweet-alert deletar"

Então você irá criar eventos de click para cada botão pela classe .deletar e usar o promise .then do Sweetalert para redirecionar a página pegando o id do botão quer disparou o evento caso você confirme:
const del_buts = document.getElementsByClassName("deletar");
for(let b of del_buts){
   b.onclick = function(){
      let id = this.id;
      swal({
         title: "Are you sure?",
         text: "You will not be able to recover this imaginary file!",
         type: "info",
         showCancelButton: true,
         confirmButtonClass: 'btn-primary',
         confirmButtonText: 'Primary!'
      }).then(function(e){
        if(e){
           location.href='deleta-apoio.php?deleta='+id;
        }
      });
   }
}

Comment: Obrigado, deu certo e consegui entender como funciona essa integração. Se pudesse te dava um abraço. Sam is a beast
Comment: Obrigado mais uma vez, Sam! vc é fera!
Comment: de qualquer forma, não consigo passar a id do usário para fazer o delete.
Comment: ```echo '```

o js é o que vc me passou...
Comment: Atualizei a resposta. Mantenha o id em cada button: `id="'.$row['id_apoio'].'` e retire esse onclick que vc colocou.


Mern Stack: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Question: I have a MERN stack application, Im facing this issue :
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This is my code in the frontend
import React, { useEffect, useState } from "react";

const Home = () => {
  const [workouts, setWorkouts] = useState(null);

  useEffect(() => {
    const fetchWorkouts = async () => {
      const response = await fetch("/api/workouts");
      const json = await response.json();

      if (response.ok) {
        setWorkouts(json);
      }
    };

    fetchWorkouts();
  }, []);

  return (

        {workouts &&
          workouts.map((workout) =>
{workout.title}
)}

  );
};

export default Home;

and this is output when I do console.log(response)
Response { type: "basic", url: "http://localhost:5173/api/workouts", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers(8), body: ReadableStream, bodyUsed: false }
Home.jsx:9:14
my node server return a valid json (array), something like this
[{"_id":"648b46c2b757e7cd377c3fc5","title":"Bench press","reps":15,"load":0,"createdAt":"2023-06-15T17:13:38.124Z","updatedAt":"2023-06-15T17:13:38.124Z","__v":0},{"_id":"648b44d9e5cf2c8682e266b5","title":"Running","reps":1000,"load":0,"createdAt":"2023-06-15T17:05:29.790Z","updatedAt":"2023-06-15T17:05:29.790Z","__v":0},{"_id":"648b43288f596df8bbe0355f","title":"Situps","reps":70,"load":0,"createdAt":"2023-06-15T16:58:16.244Z","updatedAt":"2023-06-15T16:58:16.244Z","__v":0},{"_id":"648b428a8f596df8bbe0355c","title":"Pushups","reps":100,"load":100,"createdAt":"2023-06-15T16:55:38.480Z","updatedAt":"2023-06-15T17:37:02.415Z","__v":0}]
Can anyone help me ? thanks <3
I didnt try anything
Comment: Are you setting the request and response content-type to json?
Comment: @MuriloSchünke, yes in postman its showing this "application/json; charset=utf-8"
Answer: I installed cors package in my node server
npm i cors
const cors = require('cors')
app.use(cors())


Rate of change for the regression model $Y^{\frac{1}{2}}=a+b_1*log(X_1)+b_2*X_2^{\frac{1}{2}}$

Question: Hello I have the regression model $Y^{\frac{1}{2}}=a+b_1*log(X_1)+b_2*X_2^{\frac{1}{2}}$ which works very well however I am trying to interpret it in terms of change for each different $X_i$ term. I know that the first derivative of $Y= a+b*X^{\frac{1}{2}}$ (which gives the rate of change) is:
$\frac{1}{2}*b*X^{-\frac{1}{2}}$;
which is the same as:
$\frac{b}{2*X^{1/2}}$
so that's b divided by twice the square root of the independent variable. Since that's positive when $X$ is positive, $Y$ would increase as $X$ increases, but at a declining rate (this is the same pattern though not the exact same numbers as with the logged version of $X$
I have tried finding the first derivative of the original model but I get $b*\frac{1}{y^{1/2}}$ but then I get stuck.
What would be the rate of change for this model please ?
Comment: I have correctly typed your formulas. However they do not seem coherent, please check I have not made any mistake, and then if you have not.
Answer: I am not sure I fully understand your question, nor that it is the correct place to post.
However, if you are only interested in the derivatives, I can maybe help you.
I see two ways of obtaining them :

Taking the square of your expression : $Y = (Y^{\frac{1}{2}})^2=(a+b_1*log(X_1)+b_2*X_2^{\frac{1}{2}} )^2 $  and then you should be able to derive.
Differentiate your expression

I will use the second
For $X_1$
$$\frac{1}{2}dYY^{-1/2}= b_1\frac{dX_1}{X_1}$$
so that
$$\frac{\partial Y}{\partial X_1} = 2 b_1 \frac{\sqrt{Y}}{X_1} =2 b_1 \frac{a+b_1*log(X_1)+b_2*X_2^{\frac{1}{2}}}{X_1}  $$
For $X_2$
$$\frac{1}{2}dYY^{-1/2}= \frac{1}{2}b_2 dX_2 X_2^{-1/2}$$
so that
$$\frac{\partial Y}{\partial X_2} = \Big(\frac{X_2}{Y}\Big)^{-1/2} = \frac{1}{\sqrt{X_2}} \big(a+b_1*log(X_1)+b_2*X_2^{\frac{1}{2}}\big)  $$
Comment: Ok thanks for that maybe from that the in the case of x_1 x_2, b_1 and b_2 are positive so this will be positive so y will increase with x1 - probably at a diminishing rate but I would need the second derivate for that. The same is also true for x_2 as x_1, b_1 and b_2 are positive so this will be positive so y will increase with x_2 but again I would need the second derivative to confirm if it is diminishing.  Could you or someone help me with the second derivate please
Comment: Can't you do it by yourself ?
Comment: No not with stuff like this ie 2 X I can only do very simple calculus like in my first post.
Answer: Unless I've misunderstood something in your question, you'd just use the chain rule
$$Y^{\frac{1}{2}}=f(\mathbf{X})=a+b_1\log(X_1)+b_2\,X_2^{\frac{1}{2}}$$
$$Y=f(\mathbf{X})^2$$
$$\frac{\partial Y}{\partial X_1}=2f.\frac{\partial f}{\partial X_1}=\frac{2b_1\,f(X)}{X_1}$$
$$\frac{\partial Y}{\partial X_2}=2f.\frac{\partial f}{\partial X_2}=\frac{2f(X)\cdot b_2\cdot \frac{1}{2}}{X_2^\frac{1}{2}}=\frac{ b_2\, f(X) }{X_2^\frac{1}{2}}$$
Comment: That's great Glen thank you I really need to learn more calculus!  For the rate of change I also need to know if it's diminishing which from my understanding you can get from the second derivate, I think it's the second deriving test. Would you be able to help with that then I can piece together the econometric theroy. Thank you
Comment: But it's a function of two variables -- what's the actual condition you need to check? If you need only show it's decreasing with respect of each of $X_1$ and $X_2$ on its own, you can just divide those functions I gave through and see every term of each is decreasing in that variable. You can do that pretty much by inspection. However, do you also need to do something with the mixed second order derivative ($\frac{\partial^2 Y}{\partial X_1\partial X_2}$)??
Comment: Thank you once again for that explanation its very clear now.


Android Studio (AS) 4.1 Kotlin Portrait to Landscaoe does not work

Question: Having read and tested numerous threads here to this topic (most threads to Java, not to Kotlin), I do not succeed in realizing and do not understand, what i do wrong
This is my Portrait test layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is my Portraittext"
        tools:layout_editor_absoluteX="173dp"
        tools:layout_editor_absoluteY="344dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

I created landscape-xml by "create landscape.." This is the landscape-file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is my Portraittext"
        tools:layout_editor_absoluteX="173dp"
        tools:layout_editor_absoluteY="344dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

My Kotlin-file is quity simple:
package com.example.mytest

import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(this,"in portrait", Toast.LENGTH_SHORT).show()
        } else {
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Toast.makeText(this,"in landscape", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

The Configuration does not change nor does any of the 2 "Toast"-statements fire. (In debug mode the onConfigurationChanged function is not entered
My AndroidManifest.xml is this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mytest">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyTest">
        <activity android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="uiMode|orientation|screenSize|keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

This means : quite standard, only extension the
    android:configChanges="uiMode|orientation|screenSize|keyboardHidden">

I checked several entries in this line with orientation, screenSize, uiMode....., but nothing works. When I force the landscape-mode directly, display goes to landscape as expected.
What is wrong with my code?
Comment: Try to use `android:screenOrientation="sensor"` on your `Manifest.xml` on your activity
Comment: How can you lmoe the difference if both files are the same? Even the text on the TextView is the same
Answer: I want to close my question. It works now without any change on my smartphone, but not in the emulator. May be strange, Sorry


Internal Server Error - Downloading attachments

Question: I've recently migrated a Drupal 6.22 site from my local host (Xampp 2.5) to a remote, shared server - Fasthosts hosting services.
After uploading the files through ftp and importing the database, I couldn't access the site at all - it would return a 500 Internal Server Error. Trawling the Drupal forums and searching online, I found out that this was down to the .htaccess file, which I subsquently removed.
This allowed the site to load, but only the homepage. I then found a .htaccess file in the Drupal forum which someone had edited and I uploaded that, which gave me full access to the site - good times! However, after performing a walk-through of the site, I've found that I cannot download any of the attachments I've uploaded to some of the pages.
Is this a .htaccess issue? I've trawled many forums and posted several questions around the place, but no one has given a response yet. My mate highly recommended StackOverFlow, so I hope someone can help!
I've checked the server logs and it's states the error is that the file is not found! But I've deleted and re-uploaded then several times now.
Can anyone advise?
Comment: Problem solved!

There was another .htaccess file in the directory which held the attachments. Not sure whether is good practice or not, but I removed the file and hey presto, can now download the attachments!

Not sure if Drupal writes to this file or not (?!) only time will tell.

It's a quick fix, but a fix nonetheless! I'll spend more time researching this issue for future reference!
Comment: If you have found a solution, please create an answer to your question and mark it accepted, after the allotted time has passed, instead of posting it as a comment.  This will benefit both the site (by not having a question without an answer) and future visitors who have the same question to more easily find the correct answer.
Answer: Drupal can put .htaccess files in some folders. It is likely that something in your Apache setup is different and the .htaccess files are no longer valid on your new server.
Removing the .htaccess file from the sub folder could leave you open to hacks, so it may be worth looking to see what it was trying to do and make sure that you are secure.
Comment: I deleted my .htaccess file form Drupal 6.22 package but I got same error


Calculus 2 Integral Question

Question: I've been trying to resolve a calculus question and seem to be having troubles understanding exactly how to approach it. Some hints are supplied, but they don't exactly seem to help. Thanks to anyone who lends a hand!

Without evaluating the integral, show that the $\int_{0}^{\infty} \frac{ln(x)}{(x^2+1)}dx = 0$. (HINTS: let $x = \frac{1}{u}$ in order to
  re-express the integral in terms of u. Compare the two integrals, and
  recall the basic fact that the only number equal to its negative is
  zero.)
Comment: If we decide not to worry about the convergence issue, just do the substitution mechanically, simplifying expressions as much as you can. For no good reason, I prefer to break up the integral at $x=1$, and use the substitution $u=1/x$ to show that the part from $0$ to $1$ is the negative of the part from $1$ to $\infty$.
Comment: Would you mind elaborating on how I could do this without integrating them? Thanks!
Comment: The existing answer has some details about the calculation. Perhaps more will be added.
Answer: If $x = \frac 1 u$, what is $dx = \frac{dx}{du}  du$? Substitute this expression in. How do the limits of integration change?
What is $\ln(x)$ in terms of $\ln(u)$?
What happens to the denominator if instead of $x^2 + 1$ we write $(\frac 1 u)^2 + 1$, and then simplify?

In more detail, the hint says to do the following.  If $x = \frac 1 u$, then $\frac{dx}{du} = -\frac 1{u^2}$, so we can replace $dx$ with $-\frac{1}{u^2}du$ and the limits of integration $x = 0$ and $x = \infty$ with $\lim_{x \to \infty} u = \lim_{x \to \infty} \frac 1 x = 0$ and $\lim_{x \to 0} u = \lim_{x \to 0} \frac 1 x = \infty$.
Write $I$ for your original integral. Then, at this stage, we have
$$I = \int_\infty^0 \frac{\ln x}{x^2+1}\left(-\frac 1{u^2}\right)\, du = \int_0^\infty \frac{\ln x}{u^2(x^2+1)}du.$$
Here we've switched the upper and lower limits of integration, picking up an extra minus sign in the process, which cancels with the minus sign from $-1/u^2$.
Since $x = u^{-1}$, we also know $\ln x = \ln u^{-1} = - \ln u$. Let's substitute that in. We get
$$I = \int_0^\infty \frac{-\ln u}{u^2(x^2+1)}dx =  -\int_0^\infty \frac{\ln u}{u^2(x^2+1)}du.$$
The denominator is $x^2 + 1 = (\frac 1 u)^2 + 1 = \frac{1+u^2}{u^2}$. Let's substitute that in:
$$ I = -\int_0^\infty \frac{\ln u}{u^2\frac{1+u^2}{u^2}}du =
-\int_0^\infty \frac{\ln u}{1+u^2}du.$$
But this last thing is $-I$, so we have $I = -I$. That means $2I = 0$, so $I = 0$.
Comment: Could you help me a little more? I'm having trouble seeing how I can resolve this without integrating the equation. Ps, doesn't the lower limit in this case not exist after substitution?
Comment: The point is that after you do the substitutions I (and the hints) have suggested in the original integral $I$, you should get $-\int_0^\infty \frac{\ln(u)}{u^2+1} du$, which is $-I$. But if $-I = I$, then $I = 0$ (add $I$ to both sides, then divide by $2$).

As for your postscript, that seems to bey what Andr\'{e} Nicolas was saying about ignoring convergence issues. Of course, the original upper limit $\infty$ in some sense doesn't "exist" either; we're taking an improper integral. The moral is that as $x$ gets big, $u$ gets closer to $0$, and vice versa.

Calculus 2 Integral Question


Compare two arrays where show if an element is greater in an array Javascript

Question: I have two arrays of objects. I need to check if the element called quantity is larger in one of the two arrays.
Example:
Array detail:
[
  {
    provider: { uid: '6271a32082193f4b88e292f0', name: 'Genérico' },
    _id: '628ff19af062bde6a9fd7a3b',
    name: 'MALBORO ARTESANAL "20"',
    quantity: 6,
    subtotal: 3156,
    total: 0,
    quantityOnBd: 6
  },
  {
    provider: { uid: '6271a32082193f4b88e292f0', name: 'Genérico' },
    _id: '628fef9bf062bde6a9fd7986',
    name: 'MALBORO ROJO "20"',
    quantity: 7,
    subtotal: 4368,
    total: 0,
    quantityOnBd: 7
  }
]

Array sale.detail:
[
  {
    provider: { uid: '6271a32082193f4b88e292f0', name: 'Genérico' },
    _id: '628fef9bf062bde6a9fd7986',
    name: 'MALBORO ROJO "20"',
    quantity: 7,
    subtotal: 4368,
    total: 0
  },
  {
    provider: { uid: '6271a32082193f4b88e292f0', name: 'Genérico' },
    _id: '628ff19af062bde6a9fd7a3b',
    name: 'MALBORO ARTESANAL "20"',
    quantity: 6,
    subtotal: 3156,
    total: 0
  }
]

I already have a code in which I use two FOR to know if at a certain moment the quantity is greater in one of the two, it works but I would like to know if there is a better way to do it that is more efficient.
    for (let i = 0; i < detail.length; i++) {
        for (let j = 0; j < sale.detail.length; j++) {
            if (detail[i]['_id'] === sale.detail[j]['_id']) {
                if (detail[i]['quantity'] > sale.detail[j]['quantity']) {
                    return res.status(400).json({msg:'No puedes regresar mas de la cantidad original'});
                }
            }
        }
    }

Comment: seems as "efficient" as you can get - I can't see how you could achieve what you want without iterating both arrays like that
Answer: Something like this:
const map = new Map();
for (const item of detail) {
  let tuple = map[item._id]
  if (!tuple) {
    tuple = {};
    map.set( item._id, tuple ) ;
  }
  tuple.item  = item;
}
for (const sale of sale.detail) {
  let tuple = map[sale._id]
  if (!tuple) {
    tuple = {};
    map.set( sale._id, tuple );
  }
  tuple.sale = sale;
}

for (const [id,{item,sale}] of map.entries() {
  if (!item && sale) {
    console.log(`id:${id} : sale without item`);
  } else if ( item && !sale ) {
    console.log(`id:${id} : item without sale`);
  } else if (item && sale) {
    switch ( Math.sign( item.quantity - sale.quantity ) ) {
    case  0 : console.log(`id:${id} : sale.quantity === item.quantity`); break;
    case  1 : console.log(`id:${id} : item.quantity > sale.quantity`  ); break;
    case -1 : console.log(`id:${id} : item.quantity < sale.quantity`  ); break;
    default:
      throw new Error('unreachable code reached')
    }
  } else {
    throw new Error("unreachable code reached: no sale and no item");
  }
}

Answer: you can save any object in Object use _id in object key, such as
{
  "628ff19af062bde6a9fd7a3b":{
      provider: { uid: '6271a32082193f4b88e292f0', name: 'Genérico' },
      _id: '628ff19af062bde6a9fd7a3b',
      name: 'MALBORO ARTESANAL "20"',
      quantity: 6,
      subtotal: 3156,
      total: 0,
      quantityOnBd: 6
  }
}

full code
const map = {};

detail.forEach(e=>{
  map[e._id] = e;
});

const hasLarger = sale.detail.some(e=>{
  const { _id , quantity:saleQuantity } = e;
  const detailQuantity = map[_id].quantity;
  if(detailQuantity>saleQuantity){
    return true;
  }
  return false;
});
if(hasLarger){
  return res.status(400).json({msg:'No puedes regresar mas de la cantidad original'});
}


i need to put an image from a database to a card

Question: The problem si that the image i want to show an image from a database where an user uploads an image and can been shown to a card with some info lik its name and price but when i tried to do it an icon appears like a paper with green here is my code
 <?php

$sql = "SELECT * FROM members";
$stmt = $conexion->prepare($sql);
$stmt->execute();
?>

<?php
while ($campo = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>

       <img src="data:imagen/jpeg;base64,<?php echo base64_encode( $imagen); ?>" />

<?php echo $campo['firstname']; ?>

Talla <?php echo $campo['talla'];?>

$<?php echo $campo['precio'];?>

 <?php
}

?>

the user uploads an image with a crud in ajax i dont know if anyone want to see that code to
i tried almost anything and nothing seems to work it just look like this
enter image description here
Comment: Please show us where $imagen is set.and also describe what debugging you have done. For example have you checked all the php variables are set correctly e.g. using var_dump?
Comment: There's a typo in the mime type `data:imagen/jpeg;` should be `data:image/jpeg;`
Comment: Hi Valente, I understand that you want to show image from database in web page directly. Though it's possible, I strongly suggest you upload the image in some folder and save that path in database. Then, you can just link that image path in **img src**  variable. This way, it's hassle free and works for all images including very massive sized ones without any issues. This is how most systems work instead of showing from DB directly as base64 encoded. It's a good reference for you https://stackoverflow.com/questions/36995820/display-image-from-the-path-stored-in-mysql
Comment: Also you can store only unique image name in the DB. and store the path as a constant . This will reduce the storage of DB.
Comment: thank you so much with your answers but i resolved the problem it seems that a code i put was wrong and i just edit out but thanks a lot i never expected to people answer this quickly
Answer: What I can see is you have set a while loop on $campo and then called individually in an loop. for image you can try href="{{ $campo['$imagen'] }}" though I would suggest to use foreach loop for this purpose.


All submodules of direct sum of modules?

Question: Let $M_1$ and $M_2$ be submodules. Is it true that all submodules of $M_1 + M_2$ are given by $N_1 + N_2$ where $N_1$ and $N_2$ are submodules of $M_1, M_2$. What about in the infinite case?
$$\bigoplus M_i$$
What do all the submodules look like?
Answer: It is not true. Consider a vector space $k\oplus k$ over a field $k$. This is two dimensional vector space over $k$. It has plenty one-dimensional subspaces (lines through zero). In particular, more than just two following
$$k\oplus 0, 0\oplus k$$
Note that even if $k = \mathbb{Z}/2\mathbb{Z}$, then inside $\mathbb{Z}/2\mathbb{}\oplus \mathbb{Z}/2\mathbb{Z}$ there is a subspace generated by $(1,1)$, which is not the one from the description in your question. For larger fields, there are even more lines.


Alternative proof for compactness under the inverse of a closed mapping

Question: I encountered the following problem in L. Gasínski, N.S. Papageorgiou - Exercises in Analysis - Part 1: (2.63)
"Suppose that $X$ and $Y$ are two topological spaces and $f : X \longrightarrow Y$ is a
closed function such that for every $y \in Y$ , the set $f^{−1}(y) \subseteq X$ is compact. Show that for every compact set $K \subseteq Y$ , the set $f^{−1}(K)\subseteq X$ is compact."
The proof given uses nets. Is there an alternative, nice proof that uses either ultrafilters, open covers or the finite intersection property characterization of compactness? I'm stuck where I should use the closedness of the map.
Answer: First: we may assume that $Y$ is compact, then we need to show that $X$ is compact. I'm dropping the Hausdorff assumptions because they're probably not the interesting one.
Let $(U_i)_{i \in I}$ be an open cover of $X$. For each $J \subset I$, $F_J=X \backslash \bigcup_{j \in J}{U_j}$ is a closed subset of $X$ so $V_J=Y \backslash f(F_J)$ is open. $V_J$ is the set of $y \in Y$ such that every pre-image of $Y$ is in some $U_j$ for $j \in J$.
For every $y \in Y$, $(U_i)_{i \in I}$ is an open cover of $f^{-1}(y)$ so there exists a finite $J_y \subset I$ such that $y \in V_{J_y}$. Thus, the set $(V_{J_y})_y$ is an open cover of $Y$, and there are thus $y_1,\ldots,y_r$ such that $Y$ is covered by the $V_{J_{y_i}}$. Then $X$ is covered by the $U_t$ for $t$ in the (finite) reunion of the $V_{J_{y_i}}$.
Comment: Looks legit, but I suppose this will not greatly change if you restrict your $Y$ to $K$?


SQL Server , How to compare speeds of simple Queries

Question: I have a big query and I am tring to improve it part by part, however due to the caching mechanism, and simplicity of t-sql codes, I don't have a reliable environment for testing the speeds. The queries that I am tring to improve about speeds are all last about 1 or 2 seconds, so I can't see the difference clearly. And creating dummy data for each comparision takes too much time. What do you suggest me to do ? I am using my company database, so removing cache everytime can be harmful I guess.
Edit:
After reading all the comments, I made some tring and I got some idea. But looking all those values in statistics does it exactly what I want ?
Here are the problems that I faced:
Execution Plan: First I run some queries and looked at Execution Plan, at the top - Query cost (Relative to the batch) I couldn't get a value other than 0.00%. Even my query lasts more than 1 minutes. Only thing I get is 0.00%. And under the graphs, all the values are 0%
DB Statistics. Now I am testing two queries. One of them is
SELECT * FROM My_TABLE
/*
WHERE
my_primarykey LIKE '%ht_atk%'
*/
And the second one is the comment free version.
SELECT * FROM My_TABLE
WHERE
my_primarykey LIKE '%ht_atk%'
Here my results from DB Statistics, first query:.
Application Profile Statistics
  Timer resolution (milliseconds)   0   0
  Number of INSERT, UPDATE, DELETE statements   0   0
  Rows effected by INSERT, UPDATE, DELETE statements    0   0
  Number of SELECT statements   2   2
  Rows effected by SELECT statements    16387   15748,4
  Number of user transactions   7   6,93182
  Average fetch time    0   0
  Cumulative fetch time 0   0
  Number of fetches 0   0
  Number of open statement handles  0   0
  Max number of opened statement handles    0   0
  Cumulative number of statement handles    0   0

Network Statistics
  Number of server roundtrips   3   3
  Number of TDS packets sent    3   3
  Number of TDS packets received    252 242,545
  Number of bytes sent  868 861,091
  Number of bytes received  1,01917e+006    981160

Time Statistics
  Cumulative client processing time 0   0,204545
  Cumulative wait time on server replies    25  10,0455

Second Query:
Application Profile Statistics
  Timer resolution (milliseconds)   0   0
  Number of INSERT, UPDATE, DELETE statements   0   0
  Rows effected by INSERT, UPDATE, DELETE statements    0   0
  Number of SELECT statements   2   2
  Rows effected by SELECT statements    14982   15731,3
  Number of user transactions   5   6,88889
  Average fetch time    0   0
  Cumulative fetch time 0   0
  Number of fetches 0   0
  Number of open statement handles  0   0
  Max number of opened statement handles    0   0
  Cumulative number of statement handles    0   0

Network Statistics
  Number of server roundtrips   3   3
  Number of TDS packets sent    3   3
  Number of TDS packets received    230 242,267
  Number of bytes sent  752 858,667
  Number of bytes received  932387  980076

Time Statistics
  Cumulative client processing time 1   0,222222
  Cumulative wait time on server replies    8   10

Every single time I execute, the values are randomly changing and I am not able to catch a good view about which query is faster.
Lastly when I do that:
SET STATISTICS TIME ON
SET STATISTICS IO ON
For both queries, the results are same.
Table 'my_TABLE'. Scan count 1, logical reads 682, physical reads 0, read-ahead reads 0.
So again I couldn't make a comparision between the two queries. how to interpret the results ? Am I looking to the wrong place. How can I compare those two simple queries above ?
Comment: When you use the like with a % at the beginning the query will scan the whole table to compare the contents of your primary key. Unfortunatelly it cannot use any index. That is why the logical reads are always the same no matter if you access the whole table or if you add the where like statement.
Why are you doing a like on the primary key? Is it that ht_atk is like a category concatenated in the primary key or something like that?
Answer: Use the query analyzer to find out the expensive parts of your query (this depends on DB statistics, so use representative data).
This will let you zero in on the parts you should optimize.
Trying to time things with a stopwatch or looking at the time it takes for the results to return to SSMS will be guesswork at best.
Comment: "This will let you zero in on the parts you should optimize." what do you mean by "let you zero" ? I am not a native english speaker, so I didn't get.

Another thing I will ask you is DB Stats. I think you ment about the part which says "Cumulative wait time on server replies" on DB Stats. But it changes everytime I execute my code. For example:

Cumulative wait time on server replies
4 3,30529e+006
8 2,75441e+006
13 2,06581e+006
0 1,83627e+006
36 1,27127e+006

How should I interpret these values? Or am I looking to wrong place?

I also didn't get what your last sentence.
Comment: Zero in means to you will be able to find the exact area of the problem. Also, don't look at `Cumulative wait time`. Look at what parts of the query are taking the largest percentage - that's where the time is spent.
Comment: Hello, I updated the question. Where to see that part by part view. It is in the DB Stats? You can check my DB stats above.
Answer: Run the set statistics time on and set statistics io on then run the big query in text mode. You can put some prints after each part of the query you want to optimize.
You will get lines like:
Table 'Table'. Scan count 1, logical reads 10, physical reads 0, read-ahead reads 0, lob    logical reads 387, lob physical reads 0, lob read-ahead reads 0.

Try to put some data in the tables and check the Scan Count and logical reads for big numbers.
You can also check the Actual Execution Plan and search for any clustered index scan. This may indicate that there is a missing index in some table.
Comment: Those lines didn't differ from one another when I tried the compare the speeds of my two simple queries that I mentioned above while updating my question.
Answer: Good way is too see execution plain. It tell alot about how query will execute and what is taking most of the time. You can even decide to create indexes on that bases. Its very usefull specially of large queries. SQLServer most of the time find best possible way to execute query but you can improve that by providing it with index on field that are used in WHERE and JOIN statements. If you cannot read execution plain which is like graph with estimated cost and timing you can read in detail about it from MSDN.
Comment: In execution plan, cost of everything seems to be %0. Even if my query lasts about 1 minute, still the Query Cost (relative to the batch) seems %0. İs this a problem btw ?
Answer: In query analyzer go to Query > Include Actual Execution Plan and Query > Include Client Statistics.
Use the Execution Plan to identify the most costly parts of your query.  When you mouse over or click any of the nodes it will show you a whole group of statistics.  Try to see if you can rework a join or filter to reduce the number of rows returned.
Use Client Statistics to compare two queries.  Each time you run your query it will add a new column to the client stats page.  You want to look at the bottom group: Time Statistics.
I know some of these are obvious, but here are a few general tips for reducing your load:
-Return only the columns you need.  Sometimes people return all columns, or some identifier columns that they use for coding but the end user doesn't need.
-For each table - reduce the number of rows returned.
-Try not to use temp tables when you don't have to. This causes a 'double dip', or querying the same very large table multiple times.
Answer: as @affan said, the best way is to use the information given by the execution plan. but you can always set up a simple counter with code like
IF @debug > 0 BEGIN
    DECLARE @now DATETIME;
    SET @now = CURRENT_TIMESTAMP;
END

and
IF @debug > 0 BEGIN
    SELECT DATEDIFF(ms,@now,CURRENT_TIMESTAMP)/1000.0 AS Runtime;
END

Comment: Counters are always giving different results. But what I want to see is, %100 true results while looking two queries.


How to get $_POST which has blank parameters

Question: I understand that as per new rules, post request in drupal should be replaced with
$stack->getCurrentRequest()->request;

But I need to know what is the replacement for $_POST which does not have any parameters. Should we use
$stack->getCurrentRequest()->request->get();

or
$stack->getCurrentRequest()->request->all();

?
Answer: $_POST is according to the PHP documentation an associative array.
$stack->getCurrentRequest()->request is a Symfony parameter bag representing this array.
ParameterBag::all() would then be a method to get the entire array.


Receber post de uma view para outra view

Question: Tenho duas Views.

Index
Assincrona

Quando acesso a index, ele chama a View Assincrona e fica um gif carregando até a página toda (Assincrona) ser carregada e mostra na View.
Códigos Controller
public ActionResult Assincrona()
    {
        DateTime data = DateTime.Now;
        mes = Convert.ToInt32(data.Month) - 2;
        dadosCarteiraPGC(2016, mes, null);

        return PartialView("Assincrona", carteiraPGC);
    }

public ActionResult Index()
    {
        return View();
    }

Códigos View

Carregando ...

Códigos JS
var site = site || {};
site.baseUrl = site.baseUrl || "";

$(document).ready(function (e) {
$(".partialContents").each(function(index, item) {
    var url = site.baseUrl + $(item).data("url");
    if (url && url.length > 0 ) {
        $(item).load(url);
    }
});

$("a.nav").click(function() {
    $("body").html("");
});
});

Está funcionando perfeito até eu precisar receber dados via post.
Recupero o valor do mês via [HttpPost]Index, mas não consigo passar para Assincrona quando ela é chamada via View.
Usar TempData[] seria um bom modo de resolver esse problema ou existe outra forma de fazer?
Answer:
Usar TempData[] seria um bom modo de resolver esse problema ou existe outra forma de fazer?

Não. O problema é outro aqui. Você está fazendo um load de algo que não tem e que não pode receber argumentos. Aliás, load não serve para isso que você quer.
O correto seria ou passar esses argumentos por GET ou por POST. Possivelmente você quer algo mais restrito, então o recomendável é POST. A chamada, portanto, precisa ser usando $.ajax():
var site = site || {};
site.baseUrl = site.baseUrl || "";

$(document).ready(function (e) {
    $(".partialContents").each(function(index, item) {
        var url = site.baseUrl + $(item).data("url");
        if (url && url.length > 0 ) {
            $.ajax({
                method: "POST",
                url: url,
                data: { campo1: "Valor1", campo2: 1 } // Coloque aqui seus campos
            })
            .done(function( msg ) {
                alert( "Data Saved: " + msg );
            });
        }
    });

    $("a.nav").click(function() {
        $("body").html("");
    });
});

Feito isso, escreva uma Action que aceite [HttpPost]:
[HttpPost]
public ActionResult Assincrona(ParametrosViewModel viewModel) { ... }


Group data by year and month | django rest framework

Question: I have various reports and I want to retrieve them this way:
year: "2019",
months: [
   {
      month: "01",
      reports: [reports for jan]
   }
   {
      month: "02",
      reports: [reports for feb]
   }
    ]

I've achieved something similar on a full Django project ( see below )  but I'm unable to do the same on drf.
def all_reports_by_month(request):
    reports = Report.objects.all()
    total_reports = reports.count()
    ordered_reports = Report.objects \
        .annotate(month=TruncMonth('date')) \
        .values('month') \
        .annotate(c=Count('id')) \
        .values('month', 'c') \
        .order_by('-month')

    context = {
        'ordered_reports': ordered_reports,
        'total_reports': total_reports

    }
    return render(request, 'dashboard/reports.html', context)

this is the current setup for reports on my DRF back-end right now :
model.py :
class Report(models.Model):
    # each code from shop
    code =  models.ForeignKey(Shop, to_field='code' , on_delete=models.CASCADE)
    clics = models.IntegerField(blank = True, null = True)
    rdv = models.IntegerField(blank = True, null = True)
    date = models.DateField(blank = True, null = True)

serializers.py :
class ReportSerializer(serializers.ModelSerializer):
    class Meta:
        model = Report
        fields = '__all__'

views.py :
class ReportViewSet(viewsets.ModelViewSet):
    queryset = Report.objects.all()
    serializer_class = ReportSerializer

urls.py :
from rest_framework.routers import SimpleRouter
from .views import ReportViewSet
router = SimpleRouter()

router.register('', ReportViewSet, basename='reports')

urlpatterns = router.urls

Thanks!
EDIT:
See answer below
Answer: I've achieved this, I still don't know if its the way to go but voila. it's a good start.
[
    {
        "month": "2020-06-01",
        "count": 746
    },
    {
        "month": "2020-05-01",
        "count": 746
    }
]

The way i did it was to create a new Model called GroupReport, i added 2 fields ( Month and Count ) .
model.py :
class GroupReport(models.Model):
    month = models.DateField()
    count = models.IntegerField(blank = True, null = True)

serializer.py:
class ReportGroupMonthSerializer(serializers.ModelSerializer):
     class Meta:
        model = GroupReport
        fields = ('month','count')

views.py :
class ReportGroupData(ListAPIView):
    queryset = Report.objects.annotate(month=TruncMonth('date')).values('month').annotate(count=Count('id')).values('month', 'count').order_by('-month')
    serializer_class = ReportGroupMonthSerializer


A good Problems and Solutions book accompany Baby Rudin?

Question: I'm reading the book Principles of Mathematical Analysis by Walter Rudin, aka "Baby Rudin". The exercises included are very instructive and helpful, but I'd like to find a book that has more problems (with solutions) that could help me build a better understanding on the topics covered in Baby Rudin.
I found a series "Problems in Mathematical Analysis I-III" by W.J.Kaczor and M.T.Nowak, but seems to me that it does not fit Baby Rudin well. Any recommendation?
Answer: I used Intro to Real Analysis while reading Rudin and noticed many similarities. The structure of the book was very similar, although there are the occasional proofs shown in a different way. For example, Baby Rudin proves that every k-cell is compact by contradiction, whereas Manfred Stoll proves a slightly weaker claim (closed bounded set $[a,b]$ is compact) by using a direct proof, which constructs a set and shows that it is compact and equal to $[a,b]$.
Stoll uses a slightly different layout, it introduces sequences, followed by topology, and treats series after integration, but the book has more approachable exercises. The exercises in Rudin, while not impossible are very difficult (at least they were for me) and it can be frustrating. Manfred Stoll's book contains some easier problems near the beginning of each set of exercises, however, difficult problems do exist.
Solutions do not exist for all the problems, but I still found this book helpful to read alongside baby Rudin.
Comment: For the record, I do not recommend Stoll's book. I used it for both semesters of Real analysis and had didn't like it at all. Maybe with better formatting, it'd be more accessible...


Where's the MessageUI framework?

Question: I'm trying to add the ability to send an email from my iPhone app, and step one appears to be to add the MessageUI Framework to my project and I it doesn't appear in my list of existing Frameworks.  There is something called Message Framework.  Is that it?  Has Apple renamed it?
I did download the MailComposer sample and I can see that that project seems to have the MessageUI.framework in it, albeit not in the Frameworks folder with UIKit, Foundation, and CoreGraphics.
How should I proceed?
Note that I'm running Xcode 3.2 on Mac OS X Version 10.6.1
Comment: What iPhone SDK version have you got installed? It's only available in 3.x.
Answer: This is the real answer - To add it to your project, open up your target information. (You can do this by selecting your build target, and right-clicking to select Get Info). On the 'General' tab, you'll see 'LInked Libraries'. Here you can add new libraries that are actually available. MessageUI.framework is indeed one of those libraries. This should solve your cross-platform build issues. – Malaxeur
Comment: You are my new favorite person.
Answer: I ran into the same thing (I think), check to make sure you're in the iPhone frameworks folder when you go to add framework. Hit M to take you to it, the Mac one has a bunch of M frameworks in it, the iPhone has only 1, message kit (I think), just hit M.
That's what was wrong with mine.
Comment: I'm still not finding it.  What's the path to the iPhone frameworks folder?  When I right click on the Frameworks folder in my project and choose add and Existing Frameworks, a long list appears and MessageUI is not in it.  I see the option for Add Other... on the bottom of the list and can see that I can look in other folders but I haven't been able to locate it specifically.
Comment: Found it!!!  It was at /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.sdk/System/Library/Frameworks/MessageUI.framework
Comment: The top of the open dialog has a recently saved/opened locations scroll box thing, try looking around in there.
Comment: There you go! Rock on, and don't forget the delegate methods. Also, I found this method really useful and change the status bar in the process.

- (void) mailComposeController:(MFMailComposeViewController*)controller
    didFinishWithResult:(MFMailComposeResult)result
      error:(NSError*)error {

 [self becomeFirstResponder];
 [self dismissModalViewControllerAnimated:YES];

 UIApplication *application = [UIApplication sharedApplication];

 if([application statusBarStyle] != UIStatusBarStyleBlackOpaque) {
  [application setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];

 }
}
Comment: I'm very new to this web site Joe.  I think I "voted" you up, but I'm not sure if it was by setting the check mark or by hitting the up arrow.  Let me know if you don't mind.

Also, one important thing.  WHen I added the framework from the folder I mentioned I got a bazillion syntax errors when I built my project.  I found though that if I got the framework from the /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/System/Library/Frameworks all was well!
Comment: I also am new, and you did. Thanks. I think you hit the asker hits the check mark to say that the question was answered (and then the vote goes up) and other people who agree can second that with the arrows (or bury it). Ahh, you may want to double check on that when you compile for device, I think it may break it, and then you just re-add it from "/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/System/Library/Frameworks/MessageUI.framework" I'm not quite sure about it though.

Where's the MessageUI framework?


How do I display a content author's userpoints next to the author's name on posts?

Question: I have set up the User Points module and want to show authors' points next to their name.
What is the simplest way to do this?
Comment: Where and how you want to display these things?
Comment: Name in their posts?
Comment: Good question. I want to show next to their name in posts. (As an example, just like here, where user655 (me) currently has "74" above and Berdir has "7,643" below).
Answer: The API function to get the points is userpoints_get_current_points() *. Just call that function with the uid of the author and display the returned result.
* Note that my API documentation page only lists the Drupal 7 versions, this function works the same way in Drupal 6 and 7 but others might not.
Comment: Ah, thanks. I should've said ... I know the function name. What I'm not clear on is where I should use it. What would be simplest is, e.g., if there were some hook I could call to alter the user name in posts. Or should I create a template? Sorry, I should have made my question more clear.
Comment: There is no common place to do this, you need to to this for example in comment.tpl.php for comments and node.tpl.php for nodes. You can also look at http://drupal.org/project/author_pane and http://drupal.org/project/advanced_forum, these modules provide this, among many other things, automatically for forum posts.
Comment: FWIW, what I ended up doing was a little different. I am creating a custom module and used hook_preprocess to alter the "submitted" text. Thanks for the ideas!
Comment: @berdir is there a way to do this via the views and panels UI?
Answer: I tried putting that code userpoints_get_current_points() * in comment.tpl.php but it seems that it does not work. I can not program by using PHP. Maybe I had to add something?


Showing that $f^{-1}$ has $f_{*}$ as left adjoint.

Question: Here are some of my notes showing $f_{*}$ is left adjoint to $f^{-1}$.

If we consider the category of subsets $Sub(S)$ of a set $S$, which is the corresponding category of the partial ordered set $(\mathcal{P},\subseteq)$. A function $f: S \to T$ leads to two functors $f^{-1}: Sub(T) \to Sub(S)$ and $f_{*}:Sub(S) \to Sub(T)$. It turns out that $f_{*}$ is left adjoint to $f^{-1}$.  Observing that $A \subseteq f^{-1}(f_{*}(A))$ for all $A$, we don't need to specify the unit of the adjunction. It suffices to check then that $A \subseteq f^{-1}(B) \iff f_{*}(A) \subseteq B$.

I have a doubt. Is it not sufficient to prove $A \subseteq f^{-1}(B) \implies f_{*}(A) \subseteq B$ if one knows that the unit and counit formulation of an adjunction are equivalent?
Comment: Could you please expand on why you think that one direction is sufficient?
Comment: @G.Chiusole because of the definition of adjunction I have (that of Barr and Wells 13.2.1 http://www.math.mcgill.ca/triples/Barr-Wells-ctcs.pdf) which says that for each morphism $f$ there is a unique morphism $g$. Since in this context morphisms are inclusion I just see the need to prove that one inclusion implies the other (inclusions as morphisms are unique).
Comment: Define $f_!(A)=\emptyset$ for all set $A$. You have $A\subseteq f^{-1}(B)\Rightarrow f_!(A)\subseteq B$ (this implication is vacuously true). But the converse does not hold for every sets $A$ and $B$. In other words, if you know only a single implication, the converse may not hold, and in this case $(f^{-1},f_!)$ are not adjoint.
Comment: @Roland This is a good example for when we would only consider that implication, but I think OP means that the implication should be considered in conjunction with $A \subseteq f^{-1}(f_*(A))$, in which case it does work out.
Comment: @MarkKamsma When I first read the OP, I initially thought the unit and counit was established. But when I read it again, it didn't seem obvious at all. So this is a counter-example without.
Answer: If we would prove
$$
A \subseteq f^{-1}(B) \quad \Longleftrightarrow \quad f_*(A) \subseteq B, \tag{1}
$$
then this would already prove that it is an adjunction of posets, since this correspondence is automatically natural. So that means there is no need to prove anything about a (co)unit.
Going for the unit approach, it would indeed also be enough to prove $A \subseteq f^{-1}(f_*(A))$ and $A \subseteq f^{-1}(B) \implies f_*(A) \subseteq B$. This works via the general machinery as you mentioned in the comment below your question. Alternatively, we can just prove $(1)$. The forward direction we have already. For the other direction, assume $f_*(A) \subseteq B$. Then $f^{-1}(f_*(A)) \subseteq f^{-1}(B)$, and so $A \subseteq f^{-1}(f_*(A)) \subseteq f^{-1}(B)$ as required.


How do I get last inserted record ID?

Question: I want to get the record ID for the last inserted row in a database table. I am trying to use db_last_insert_id(), but it is throwing an exception.

Call to undefined function db_last_insert_id()

How do I get last inserted record ID?
Comment: That function is not available in D7. http://drupal.org/node/729970
Answer: In Drupal 6 you would use code similar to the following.
db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id('mytable', 'id_fieldname');

The Drupal 7 equivalent code is the following.
$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();

Comment: I want newly inserted record id from a particular table from the db.Actually I need Newly Registered UserId(uid) in Rules how can i acheive it
Comment: Do not forget to specify table name and field name in `function db_last_insert_id($table, $field)`
Answer: If you don't control the particular insert query yourself, you could always use a plain old SQL query:
$last_id = db_query('SELECT MAX(id_col) FROM {table}')->fetchField();

Comment: I tried using Max(uid) , but i am getting the record above the last record
Comment: Then the record hasn't been inserted yet, so there's no new uid available
Comment: I am able to see the new record in the database but i am not getting the Id of that record
Comment: Nope, that's impossible :) If you can see the uid in the database, logically selecting `MAX(uid)` _must_ return that uid. If not your MySQL server is very very broken
Comment: That would be possible only if your function is called just before the last record is inserted.
Answer:   $id = db_insert('mytable')
       ->fields(array(
       'intvar' => 5,
       'stringvar' => 'hello world',
       'floatvar' => 3.14,
       ))
       ->execute();

$id contains the last inserted id of the table.
just do echo $id.
Answer: If fore some reason you need to get a fields value before inserting it this is a work around to do it with.
function _get_id($tableName, $fieldName) {

    $select = db_select($tableName, 'o');
    $fields = array(
        $fieldName,
    );
    $select->fields('o', $fields);
    $result = $select->orderBy($fieldName)->range(0,1)->execute()->fetchAll();
    return $result[0];
}

$lastId = _get_id('table_name' , 'uid');

Answer: A crude trick, but it works:
$myInsertID = db_query("INSERT INTO {fred} (fld1,fld2) VALUES ('a','b')", array(), array('return' => Database::RETURN_INSERT_ID));

or
$myInsertID = db_query("INSERT INTO {fred} (fld1,fld2) VALUES ('%s','%s')", array('a','b'), array('return' => Database::RETURN_INSERT_ID));

How do I get last inserted record ID?


View that Shows Result Links

Question: I have a view that prints the titles of my 10 most recent news item content.  I also want to print the URL to these news items.   How do I do this?  When I edit the view, under Fields, I see a Link field, but the problem is that it prints the word "view" instead of http://mysites.com/my-first-news-item
Answer: I almost got it....the field i'm looking for is called Content:Path.  Right now, it prints /my-first-news-item.  All I need to do now is have it print the domain name as well.....almost there.
EDIT
Figured out the last part.  To print out the absolute path, make sure the field also has the setting Use absolute link (begins with "http://") checked

View that Shows Result Links


Problema com sqlite e boot receiver

Question: Tenho uma aplicação onde o objectivo é colocar o nome de uma paragem e depois do reboot ao dispositivo android receber o nome dessa paragem no reboot receiver
O meu boot receiver encontra-se a funcionar pois já testei só dá erro quando tento aceder dados da minha base de dados sqlite onde o erro é NullPointerException;
Código onde crio a minha base de dados sqlite BDcore.java:
public class BDCore extends SQLiteOpenHelper {
 private static final String NOME_BD = "teste";
  private static final int VERSAO_BD = 6;

    public BDCore(Context ctx){
        super(ctx,NOME_BD , null , VERSAO_BD);

    }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table favoritos(_id integer primary key autoincrement , favid intenger not null  , linha text not null, paragem text not null, horas text not null);");
            db.execSQL("create table utilizador(_id2 integer primary key autoincrement, utilizadorId integer not null);");
            db.execSQL("create table ultutilizador(_id3 integer primary key  autoincrement , ultid intenger not null);");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table favoritos");
    db.execSQL("drop table utilizador");
    db.execSQL("drop table ultutilizador");
            onCreate(db);
        }
    }

Coloco os dados na minha base de dados sqlite através da minha actividade de login do utilizador:
 SQLiteDatabase db;
 BDCore auxBd = new BDCore (this);
    db = auxBd.getWritableDatabase();

 ContentValues valores = new ContentValues();
                valores.put("favid", 3);
                valores.put("linha", "teste");
                valores.put("paragem", "PARAGEMTESTE");
                 valores.put("horas", "teste");
                db.insert("favoritos", null, valores);

O meu boot receiver :
public class BootReceiver extends BroadcastReceiver {
    SQLiteDatabase db;

    String paragem;

    @Override
    public void onReceive(Context context, Intent intent) {

            String[] colunas = new String[]{"_id", "favid", "linha", "paragem" , "horas" };
            Cursor cursor2 = db.query("favoritos", colunas, null, null, null, null, null);
        HorariosActivity.context = context;
            if (cursor2.getCount() > 0) {
                cursor2.moveToFirst();
                do {

                    paragem = cursor2.getString(3);

                }
                while ( cursor2.moveToNext());

            }
        }

    }

Comment: Não está faltado dar `BDCore auxBd = new BDCore (context);
    db = auxBd.getWritableDatabase();` dentro do onReceive?
Comment: exacto reparei agora esquecimento
Answer: Faltou declarar no bootreceive a base de dados.
 BDCore auxBd = new BDCore (context);
        db = auxBd.getWritableDatabase();

Problema com sqlite e boot receiver


MySQL suggestions on DB design of N° values in 1 column or 1 column for value

Question: I need to move my local project to a webserver and it is time to start saving things locally (users progress and history).
The main idea is that the webapp every 50ms or so will calculate 8 values that are related to the user which is using the webapp.
My questions are:

Should i use MySQL to store the data? At the moment im using a plain text file with a predefined format like:
Option1,Option2,Option3
Iteration 1
value1,value2,value3,value4,value5
Iteration 2
value1,value2,value3,value4,value5
Iteration 3
value1,value2,value3,value4,value5
...

If so, should i use 5 (or more in the future) columns (one for each value) and their ID as Iteration? Keep in mind i will have 5000+ Iterations per session (roughly 4mins)
Each users can have 10-20 sessions a day.
Will the DB become too big to be efficient?
Due to the sample speed a call to the DB every 50 ms seems a problem to me (especially since i have to animate the webpage heavily). I was wondering if it would be better to implement a Save button which populate all the DB with all the 5000+ values in one go. If so what could it be the best way?
Would it be better to save the *.txt directly in a folder in the webserver? Something like DB/usernameXYZ/dateZXY/filename_XZA.txt . To me yes, way less effort. If so which is the function that allows me to do so (possible JS/HTML).
Answer: The rules are simple, and are discussed in many Q&A here.
With rare exceptions...

Do not have multiple tables with the same schema.  (Eg, one table per User)
Do not splay an array across columns.  Use another table.
Do not put an array into a single column as a commalist.  Exception:  If you never use SQL to look at the individual items in the list, then it is ok for it to be an opaque text field.
Be wary of EAV schema.
Do batch INSERTs or use LOAD DATA.  (10x speedup over one-row-per-INSERT)
Properly indexed, a billion-row table performs just fine.  (Problem: It may not be possible to provide an adequate index.)
Images (a la your .txt files) could be stored in the filesystem or in a TEXT column in the database -- there is no universal answer of which to do.  (That is, need more details to answer your question.)

"calculate 8 values that are related to the user" -- to vague.  Some possibilities:

Dynamically computing a 'rank' is costly and time-consuming.
Summary data is best pre-computed
Huge numbers (eg, search hits) are best approximated
Calculating age from birth date - trivial
Data sitting in the table for that user is, of course, trivial to get
Counting number of 'friends' - it depends
etc.


How to find Pythagorean triples with one side only?

Question: I was using the formula to find triples, but I can only find two of them.
the pythagorean triple associate with 102 are
102 136 170,
102 280 298,
102 864 870,
102 2600 2602,
$a = m^2 - n^2$
, $b = 2mn$
, $c = m^2 + n^2$
let $a = 102
= (m+n)(m-n)$
since m and n are odds
(m+n)(m-n) would be a multiply of 4, but 102 isn't a multiply of 4
There are no solution when a = 102
let b = 102, mn = 51
case 1 :
m= 51, n=1
we get 102 2600 2602
case 2 :
m= 17, n=3
we get 102 280 298
Answer: This is a common mistake. It's not the case that the formula you give finds all Pythagorean triples. Rather, the formula finds all primitive Pythagorean triples—triples whose greatest common divisor equals $1$. Furthermore, in that formula the $m$ and the $n$ should have opposite parity and be relatively prime.
Since $(m,n)=(51,1)$ and $(m,n)=(17,3)$ are the only relevant factorizations of $\frac{102}2$, and neither of them has integers with opposite parities, we conclude that there are no primitive Pythagorean triples at all with $102$ as a leg.
But we can also look for primitive Pythagorean triples with a leg that is a divisor of $102$, and scale it up appropriately. The divisors of $102$ are $1,2,3,6,17,34,51,102$, and doing this process on each of these divisors individually yields four primitive Pythagorean triples:
$$
(3,4,5), \quad (17,144,145),\quad (51,140,149), \quad (51,1300,1301).
$$
Multiplying these through by $34,6,2,2$ respectively gives the four triples listed in your answer.
The fact that the formula for primitive triples, when the primitivity is ignored, sometimes does produce some Pythagorean triples makes this mistake even easier to make. The moral of the story: we need to appreciate the exact wording of a theorem—including all its hypotheses and its precise conclusion.
Answer: Forgive me for taking the liberty of altering Euclid's formula, normally expressed as $F(m,n)$, here expressed as $F(m,k)$. The following is copied from a paper I am writing on the subject and the $k$ matches up with an alternative formula I have developed. Given
$$A=m^2-k^2\qquad B=2mk\qquad C=m^2+k^2$$
We can find triples, if they exist, with a finite search by solving Euclid's formula function for $k$ and seeing which $m$-values within the limits yield integers. In the following discussion, we first find limits solving for $m$ with $k$ varying from $1$-to-$(m-1)$.
side A
$$A=m^2-1\implies  \lfloor\sqrt{A+1}\rfloor\le m \\A=m^2-(m-1)^2=2m-1\implies m \le\frac{A+1}{2}$$
$$ B=2m(m-1)=2m^2-2m\implies\bigg\lfloor \frac{1+\sqrt{2B+1}}{2}\bigg\rfloor\le m \\  B=2m(1)\implies m\le \frac{B}{2} $$
$$ C=m^2+(m-1)^2=2m^2-2m+1 \implies\bigg\lfloor\frac{ 1+\sqrt{2C-1}}{2}\bigg\rfloor \le m \quad C=m^2+1\implies m\le \lfloor\sqrt{C-1}\rfloor$$
I have provided examples so you can see how it works. $A$ is always odd (without a multiplier) so I have used $A\in\{3,17,51\}$ in the calculations. Also, a primitive $C$ must be of the form $(4n+1)$ so have use $C=17$. You need to multiply the $A$ and $C$ results accordingly.
$$A=m^2-k^2\implies k=\sqrt{m^2-A}\quad\text{where}\quad  \sqrt{A+1} \le m \le \frac{A+1}{2}$$
The lower limit ensures $k\in\mathbb{N}$ and the upper limit ensures $m> k$.
$$A=3\implies \lfloor\sqrt{3+1}\rfloor=2\le m \le \frac{3+1}{2} =2\\\text{ and we find} \quad m\in\{2\}\implies k \in\{1\} $$
$$f(2,1)=(3,4,5)\\$$
$$A=17\implies \lfloor\sqrt{17+1}\rfloor=4\le m \le \frac{17+1}{2} =9\\
\text{ and we find} \quad m\in\{9\}\implies k \in\{8\} $$
$$f(9,8)=(17,144,145)\qquad $$
$$A=51\implies \lfloor\sqrt{51+1}\rfloor=7\le m \le \frac{51+1}{2} =26\quad\text{ and we find} \quad m\in\{10,26\}\implies k \in\{7,25\} $$
$$fF(10,7)=(51,140,149)\qquad \qquad (26,25)=(51,1300,1301)\qquad \qquad $$
$\\$
$$B=2mn\implies k=\frac{B}{2m}\qquad\text{where}\qquad \bigg\lfloor \frac{1+\sqrt{2B+1}}{2}\bigg\rfloor \le m \le \frac{B}{2}$$
The lower limit ensures $m>k$ and the upper limit ensures $m\ge 2$.
$$B=102\implies\qquad \bigg\lfloor \frac{1+\sqrt{204+1}}{2}\bigg\rfloor =7 \le m \le \frac{102}{2}=51\\
 \text{and we find} \quad m\in\{17,51\}\implies k\in\{3,1\}$$
$$F(17,3)=(280,102,298)\qquad \qquad f(51,1)=(2600,102,2602)$$
$\\$
$$C=m^2+k^2\implies n=\sqrt{C-m^2}\qquad\text{where}\qquad \bigg\lfloor\frac{ 1+\sqrt{2C-1}}{2}\bigg\rfloor \le m \le \lfloor\sqrt{C-1}\rfloor$$
The lower limit ensures $m>k$ and the upper limit ensures $k\in\mathbb{N}$.
$$C=17\implies \bigg\lfloor\frac{ 1+\sqrt{17-1}}{2}\bigg\rfloor=2 \le m < \lfloor\sqrt{17-1}\rfloor=4\\
\text{ and we find} \quad m\in\{4\}\Rightarrow k\in\{=1\}$$
$$F(4,1)=(15,8,17)\quad $$


Help explaining (offering intuition/examples of) the score function and fisher's information to students

Question: Next week I will teach my students the score function and its variance (i.e.: fisher information).
I am looking for way(s) to illustrate these concepts so to help my students understand them (and not just calculate them for various distributions, which is what is often done in class).
Any suggestions would be helpful (beyond giving me links to What is the intuition behind the score function? and Likelihood score function 101)
Comment: This was discussed in a CV thread here... http://stats.stackexchange.com/questions/196576/what-kind-of-information-is-fisher-information
Answer: Buse, A (1982). The Likelihood Ratio, Wald, and Lagrange Multiplier Tests: An Expository Note.  The American Statistician, 36:3a, 153-157 is an excellent reference with one major reservation: Lagrange multiplier test should have been called Rao's efficient score test.  I wrote Prof. Rao about this when the paper came out to let him know my frustration that incorrect terminology was being used and he was thankful.  Other than that it's an excellent article.  I've sent you a personal email with the pdf.
Another article by Linda Pickle is also excellent - Stat Comp & Stat Graphics Newsletter Nov. 1991 which I'm sending to you.
Comment: Thank you Frank. I'll say the first reference is interesting. It relies on too many notions for the early stage of the course (not all students know what hypothesis testing or CI are). But I may use it later on. What I ended up doing was to make several plots of the log likelihood of the normal distribution (for estimating mu), with the tangent line, and for samples of n=5 and n=100 - thus demonstrating the variance of the score function (and how it relates to a more curvy likelihood).


"no valid constructor" when serializing a subclass of Path2D.Double

Question: I'm trying to serialize a subclass of Path2D.Double, the serialization works, but the deserialization doesn't because of the following Exception:
Exception in thread "main" java.io.InvalidClassException: CustomShape; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:147)
at java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:755)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1751)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at CustomShape.main(CustomShape.java:38)

Could this be due to the superclass Path2D not implementing Serializable? But then, Path2D.Double itself couldn't be deserialized either.
Here's my Code:
import java.awt.geom.Path2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CustomShape extends Path2D.Double {
    private static final long serialVersionUID = 1L;

    public CustomShape() {
        super();
    }

    public static void main(String[] args) throws Exception {
        //Make Shape
        //Path2D shape = new Path2D.Double(); //works
        Path2D shape = new CustomShape(); //doesn't work
        shape.moveTo(0, 0);
        shape.lineTo(0, 10);
        shape.lineTo(10, 10);
        shape.lineTo(10, 0);
        shape.closePath();

        File file = new File(System.getProperty("user.dir"), "shape");
        //Save Shape
        if (!file.exists()) {
            file.createNewFile();
        }
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(shape);
        out.flush();
        out.close();

        //Load Shape
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        Object obj = in.readObject();
        in.close();

        System.out.println(obj);
    }
}

Comment: Show the declaration of Path2D and its inner class Double.
Comment: @Marko Topolnik they are jre classes. `java.awt.geom.Path2D` has `private` `readObject` and `writeObject` implementations. It seems to handle the package-private `transient double[] doubleChords`
Comment: Sorry, didn't see the imports. I'm looking at the code and fail to see the cause of problem.
Comment: You don't need the file.exists()/file.createNewFile() code. new FileOutputStream() is sufficient.
Answer: I ran into this same problem last week, finally found the answer today. The Path2D object declares its constructor as package-private. Since java serialization requires the first non-serializable parent class has a no-arg constructor, and it's not accessible, any extension of Path2D that is not in Path2D's own package will not deserialize. Honestly I think this is a flub on Java's side, since all the other AWT abstract shapes using Float/Double subclasses declare their default constructors as protected.
If you're curious, I found the root cause by tracing through java.io.ObjectStreamClass.getSerializableConstructor(Class<?>). You'll find that it returns null when it finds a constructor that is not accessible.