Motivation behind the definition of monomorphism and epimorphism in category theory

Question: Let $\mathcal{C}$ be a (locally small) category and let $X$ and $X'$ be objects in $\mathcal{C}$.

(Definition $1$) We say that $f\colon X\to X'$ is a monomorphism if for any object $Y$ in $\mathcal{C}$, the map
$$\operatorname{Hom}(Y, X)\to \operatorname{Hom}(Y, X')$$
given by $g\mapsto f\circ g$ is a one-to-one function.
(Definition $1'$) We say that $f\colon X\to X'$ is a monomorphism if there exists $g\colon X'\to X$ such that $g\circ f=\operatorname{Id}_X$.

Of course both definitions generalize one-to-one functions in the category of sets, but Definition $1$ is the one which is used in the literature. However I want to know why my definition, namely Definition $1'$, is not as useful as the first one to be adopted as the standard way of defining monomorphisms. As a related question, is there any relation between the two versions? Does one definition imply the other one?
My own guess is Definition $1$ is chosen because of Yoneda's lemma.
Similarly one can give the following definitions for an epimorphism:

(Definition $1$) We say that $f\colon X\to X'$ is an epimorphism if for any object $Y$ in $\mathcal{C}$, the map
$$\operatorname{Hom}(X',Y)\to \operatorname{Hom}(X, Y)$$
given by $g\mapsto g\circ f$ is a one-to-one function.
(Definition $1'$) We say that $f\colon X\to X'$ is an epimorphism if there exists $g\colon X'\to X$ such that $f\circ g=\operatorname{Id}_{X'}$.
(Definition $1''$) We say that $f\colon X\to X'$ is an epimorphism if for any object $Y$ in $\mathcal{C}$, the map
$$\operatorname{Hom}(Y, X)\to \operatorname{Hom}(Y, X')$$
given by $g\mapsto f\circ g$ is an onto function.

My questions are similar to the case of monomorphism of categories. My guess is that a reason for choosing Definition $1$ as the "right" definition of an epimorphism is "duality."
Any answers or comments are highly appreciated.
Edit I thought it might be a good idea to include two possible ways of defining an isomorphism in order to compare them.

(Definition $1$) We say that $f\colon X\to X'$ is an isomorphism if there exists $g\colon X'\to X$ such that $f\circ g=\operatorname{Id}_{X'}$ and $g\circ f=\operatorname{Id}_X$.
(Definition $1'$) We say that $f\colon X\to X'$ is an isomorphism if it is both a monomorphism (in the sense of Definition $1$) and an epimorphism (as in Definition $1$).
Comment: I assume you are aware of the equivalence between Definitions 1' and 1'' for epis.
Comment: Actually, not every monomorphism in $\mathbf{Set}$ is split. (Consider functions with empty domain.)
Comment: @drhab I think darij is right about the equivalence of 1' and 1'' for epis.
Comment: I abusively thought that he was comparing 1 and 1'' and overlooked that in the second part there where $3$ definitions. I have deleted my comment on @darijgrinberg. I hope that Zhen Lin will say more. He is one of the experts I had in mind.
Comment: @Sam Please do not modify your question after answers have been posted.
Comment: @Zhen I have not "changed" my original question. The additional part is only added for the benefit of the future readers of this post on MSE. Regarding the last part of my question I think it is worth mentioning that any isomorphism in the sense of Definition 1 is an isomorphism in the sense of Definition 1'.
Answer: If in a category $r\circ s={\rm id}$ then $r$ is by definition a
retraction and $s$ is by definition a section. So somehow you are
wondering: is monomorphism the same concept as section and is epimorphism
the same concept as retraction? In category $\textbf{Set}$ where monomorphisms
can be described as injective functions and epimorphisms as surjective
functions it is indeed true that a function is surjective iff it is
a retraction, but it is not true that a function is injective iff
it is a section. The 'spoilers' are functions $f:\emptyset\rightarrow X'$
where $X'\neq\emptyset$. They are (vacuously) injective but no function $g:X'\rightarrow\emptyset$
exist. In general sections are special monomorphisms and retractions are special epimorphisms (see the comment of Najib on this answer). Often there are classes that are 'in between'. There is much more to say on this subject, but I am not really
an expert and think that there are people on this site who can do
much better. This is only showing you one obstacle.
Comment: "Retractions" are also often called "split epimorphisms" and "sections" are also called "split monomorphisms".
Answer: Monomorphisms are defined the way they are because that is what works in many concrete categories of interest: $\mathbf{Set}$, $\mathbf{Grp}$, $\mathbf{Ring}$, etc. Even $\mathbf{Top}$ is an example if you expect monomorphisms to be injective continuous maps (as opposed to, say, topological embeddings). Moreover, with this definition, the Yoneda embedding sends monomorphisms to componentwise injective natural transformations, which is  as much as what one can hope for.
By constrast, epimorphisms are defined the way they are because we want duality. It is true that epimorphisms in $\mathbf{Set}$ are surjections. It is also true in some concrete categories like $\mathbf{Ab}$ and $\mathbf{Top}$, but it is not true in other concrete categories: for instance, in the category of Hausdorff spaces and continuous maps, the epimorphisms are precisely the continuous maps with dense image.
I should also mention that a morphism is a split epimorphism if and only if the Yoneda embedding sends it to a componentwise surjective natural transformation. Indeed, the "only if" direction is clear, and if $f : A \to B$ is a morphism such that
$$\mathrm{Hom}(T, f) : \mathrm{Hom}(T, A) \to \mathrm{Hom}(T, B)$$
is surjective for every $T$, then taking $T = B$, we find there is a morphism $s : B \to A$ such that $f \circ s = \mathrm{id}_B$, as claimed.

Addendum. There are categories in which morphisms that are simultaneously monomorphisms and epimorphisms are not necessarily isomorphisms. The easiest example is $\mathbf{Top}$: a continuous map that is both injective and surjective is not necessarily a homeomorphism.


Under what circumstances is this function continuous?

Question: I'm aware of the fact that if $f_1,f_2 ,\cdots ,f_n $ are continuous functions then $$f(x)=\max\{f_1(x)\cdots f_n(x) \} $$ is continuous as well, but I'm dealing with the following question: If $ A_x$ is a finite not empty set for every $
x \in \mathbb{R}$ then is it true that $x \mapsto \max A $  is a continuous maping?
I'm doing this because I'm trying to figure out if $$x \mapsto \max\left\{\frac{1}{n} \,\middle|\, 1-nx\geq 0 \right\} $$ is continuous for those $ x$ for the set is not empty.
Comment: Not sure if I understood you correctly, but your function (assuming $n$ is a positive integer) evaluates to 1 whenever the set is non-empty, and so it's continuous on its domain
Answer: As defined, your function is continuous because it's constant.
If you consider the min function, $$x \mapsto \min\left\{\frac{1}{n} \,\middle|\, 1-nx\geq 0 \right\},$$ then it is discontinuous at every $x=1/n$, $n\in\mathbb N$.
Comment: You are right. My wrong, it was with min.


PHP undefined array key error MSSQL and PHP

Question: I keep getting this error:

Warning: Undefined array key "user_id" in C:\laragon\www\auth\public\details.php on line 23
ID:

This is the code:
<?php
$pdo = require __DIR__ . '/../src/bootstrap.php';

$user_id=$_GET['user_id'];
if(!is_numeric($user_id))
{
    echo "Data Error";
    exit;
}

 $sql = 'SELECT user_id,email from users
        WHERE user_id = :user_id';

    $statement = db()->prepare($sql);
    $statement->bindParam(':user_id', $user_id, PDO::PARAM_STR);
    $statement->execute();

    $row= $statement->fetchAll(PDO::FETCH_ASSOC);

    var_dump($row);
    // die();

echo " ID: $row[user_id],";

I can see I am getting an array with the User_id and email this is the output to screen I get:
I have tried wrapping user_id in single quotes, double quotes, no quotes. Nothing seems to work.
array(1) { [0]=> array(2) { ["user_id"]=> string(2) "27" ["email"]=> string(15) "email@example.com" } }
Warning: Undefined array key "user_id" in C:\laragon\www\auth\public\details.php on line 23
ID: ,

I am using Microsoft SQL Server 2019
Laragon for the webhost
I have tried wrapping user_id in single quotes, double quotes, no quotes. Nothing seems to work.
Error was the same
Comment: SQL Server 2022 is the newest, and there's tags for all [SQL Server releases](https://stackoverflow.com/questions/tagged/sql-server+or+sql-server-20*)
Comment: *"I am using Microsoft SQL Server 2019"* then  why have you tagged [[tag:sql-server-2012]]? Which are you *actually* using, 2012 or 2019?
Comment: Because you're getting an array containing all the rows in the result set, surely you'll need to `echo $row[0]['user_id']` to show the first one? Your `var_dump()` shows that you have an array of arrays. As there should only be one row in the database with that user_id because you'll have that set as a unique column, there's no need for `fetchAll()` here.
Comment: I couldn't find a tag for sql-server-2019 2012 seemed to be the newest. I am considering moving to MySQL the support for MSSQL is much smaller and the cost too. Thanks anyway.
Answer: Your $row variable is an array of arrays. You need to access the individual row first, before you can access its column.
echo "ID: ".$row[0]['user_id'];

Since you are filtering on a single User ID, it's probably better to use fetch(), which will fetch just one row.
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo "ID: ".$row['user_id'];

Comment: $row = $statement->fetch(PDO::FETCH_ASSOC);
echo "ID: ".$row['user_id'];

That did it! You can't imagine how close I have been so many times! I just never got the correct combination.

Thank you so much!


MSE huge when estimating regression from small samples

Question: I am trying to test the predictive accuracy of regression using training sets of varying sizes.
Y <- rnorm(100)
X <- replicate(5, Y+rnorm(100) )
data <- as.data.frame(cbind(Y,X))

Let's say the training set is 2% of the data:
train <- nrow(data) * 0.02
test <- nrow(data) - train

I repeat the process for 1000 times:
MSE <- vector()
for( i in 1:1000){

train.elements <- sample(1:nrow(data),train)
train.set <- data[train.elements,]
test.set <- data[setdiff(1:nrow(data), train.elements),]

# then I fit a regression model:

    model <- lm(train.set[,1]~ train.set[,2]+train.set[,3]+train.set[,4]+train.set[,5])

#I now use this model to predict the values in the test set:
predictions <- predict.lm(model,data=test.set)

MSE[i] <- mean((test.set[,1] - predictions)^2)

}

My problem is that due to the small sample size the MSE sometimes is extremely huge.
Is this normal? I am unable to plot a curve of the MSE as a function of training set size because the MSE for small sample sizes are so large.
Comment: Please see my edit I forgot to divide by 1/test set size. Is this correct now?

On real data I still get enormous estimates sometimes.
Comment: Looks better. Why don't you simply use `mean`?
Comment: I replaced it with mean. I still get enormous estimates with some of the real world data I am working with. Most of the time the MSE is a small number but occasionally it ends up with a huge estimate like 4000.
Answer: When I just ran your code a few times, my maximum MSE was 9.6. Still a lot, but not 4000. You may want to use set.seed() to make your analysis reproducible.
Your dataset has just 100 rows. You use 2% of that for model fitting, that is, just two data points. You try to fit five independent variables.  R therefore uses the first IV (train.set[,2]) and puts a straight line through your two data points, discarding the other three IVs.
Then, in predicting, you simply extrapolate the [,2] component of your test set along the straight line you fit.
And of course, your straight line is enormously variable. The slope can differ extremely, since you just picked two lines at random. (Since your Y has zero relationship to the IVs, the correct slope should be zero.) If you get a large slope simply because of the variability of your parameter estimate, you will get predictions that are far away from where they should be.
Don't fit five IVs to just two data points. Rules of thumb suggest at least 15 or 20 data points per degree of freedom.


how to add my application inside launcher app?

Question: im using my own launcher i take this launcher app from github  https://github.com/strider2023/Black-Launcher--Android-  is install launcher in phone but i also wants to add my application in launcher so when launcher install my application also install inside launcher and automatically my app start after launcher start. this is launcher manifist file  below  my appplication class file is MainActivity.java how do i start my application after start launcher???
<code> <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.touchmentapps.black"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15"/>

<permission
    android:name="com.android.launcher.permission.INSTALL_SHORTCUT"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="normal" />

<permission
    android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="normal"/>

<permission
    android:name="com.android.launcher.permission.READ_SETTINGS"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="normal"/>

<permission
    android:name="com.android.launcher.permission.WRITE_SETTINGS"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="normal"/>

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.SET_WALLPAPER_HINTS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.BIND_APPWIDGET" />
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />

 <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:hardwareAccelerated="true"
    android:largeHeap="true">
    <activity
        android:name=".BlackLauncherActivity"
        android:launchMode="singleTask"
        android:clearTaskOnLaunch="true"
        android:stateNotNeeded="true"
        android:windowSoftInputMode="adjustPan"
        android:theme="@style/Theme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.MONKEY"/>
        </intent-filter>
    </activity>
    <activity android:name=".Activity2"/>
</application>

   </manifest>
</code>
Comment: this may help you, http://stackoverflow.com/q/12673134/1619597, But your question is not clear.
Answer: As far as i understand your question, you want to see your app displayed in the launcher ?
This is related to intent-filters : http://developer.android.com/guide/components/intents-filters.html
Black launcher looks for applications that are flagged as being "LAUNCHER" applications. As you can see in their code here : https://github.com/strider2023/Black-Launcher--Android-/blob/master/Black%20Launcher/src/com/touchmentapps/black/functions/AppInfoHandlerFunctions.java
You have to add your activity tag in your Manifest file  and include the LAUNCHER category.
<code><activity
        android:name=".MyActivity"
        android:launchMode="singleTask"
        android:clearTaskOnLaunch="true"
        android:stateNotNeeded="true"
        android:windowSoftInputMode="adjustPan"
        android:theme="@style/Theme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>
Comment: im using this manifiest of blacklauncher just tell me how do i add my Mainactivity.java file in this manifiest??
Comment: @SmartGuy just add the activity xml tag to your manifest , as described above. Black Launcher will look for activities with the category LAUNCHER to display.
Comment: @SmartGuy, you don't add this to the blacklauncher's manifest, but to YOUR application's manifest!


Are the values of these two continuous functions equal?

Question: Consider the function $f$ defined on the nonnegative reals such that
$f(x)=x$ for all nonnegative $x$ and the continuous function $g$ defined on the nonnegative reals such that $g(0)=0$, $g^{\prime}(3)=987654321$, and $g^{\prime}(x) = 1$ for all nonnegative $x \neq 3$.
Does $f(x)=g(x)$ for all nonnegative $x$? Why or why not?
This does not make sense to me because $\int_\limits{0}^cf^{\prime}(u)\text{ d}u=\int_\limits{0}^cg^{\prime}(u)\text{ d}u$ for all $c$, which
should imply $f(x)=g(x)$ for all nonnegative $x$, but that would imply that the derivatives are always equal.
Comment: [Darboux's Theorem](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) tells us that the derivative of any differentiable function satisfies the intermediate value theorem, which your $g'(x)$ does not.  Hence it can not be the derivative of a function.
Comment: @yuri12345 You have asked the same question three times in a row now. You will keep getting the same sort of answers this way. If you don't understand an answer, or are looking for a different explanation, then either use the comments or edit the question specifying what you still need. Do not post a new identical question.
Answer: We have a continuous function $g :[0,\infty) \to \mathbb R$ such that $g(0) = 0$, $g'(3) = 987654321$ and $g'(x) = 1$ for $x \ne 3$. This means that $g$ is differentiable. Hence we have $g(x) = x$ on $[0,3)$ and $g(x) = x +c$ on $(3,\infty)$. By continuity we see that $g(3) = 3$ and $c = 0$. Thus $g'(3) = 1 \ne 987654321$. Therefore there does not exist any $g$ as in your question.
Thus the natural answer seems to be "no". However, you may also argue that the answer is "yes" for purely formal logical reasons. The logical structure of your question is the following implication:
If $f, g :[0,\infty) \to \mathbb R$ are functions satisfying suitable properties, we have $f = g$.
In other words
For all functions $f, g :[0,\infty) \to \mathbb R$, if $f, g$ satisfy suitable properties, then $f = g$.
There does not exist a function $g$ as required, thus this statement is true.


Trying to chain multiple actions together in my component

Question: In my react component I am trying to chain together multiple actions like so:
componentDidMount() {
  dispatch(Actions.fetchUser(userId)).then(() => {
    dispatch(Actions.fetchAbc(abcId)).then(() => {
      dispatch(Actions.fetchDef(defId));
    });
  });
}

Each action is following the same pattern as fetchUser, where it returns a dispatch:
fetchUser: (userId) => {
  return dispatch => {
    let url = "....";
    axios.get(url)
      .then(function(resp) {
        dispatch({
          type: Constants.SomeAction,
          user: resp.data.user,
        });
      });
  };
},

In my component I am seeing an error:

Uncaught TypeError: Cannot read property 'then' of undefined

The error is on the same line as the first .then call (fetchUser).
Is this not the correct way to chain together my actions?
Timing wise I have to do one after the other.
Answer: Dispatching a thunk returns the return value of the thunk function, but yours isn't returning anything. Try:
fetchUser: (userId) => {
  return dispatch => {
    let url = "....";
    // return the promise so you can chain on it
    return axios.get(url)
      .then(function(resp) {
        dispatch({
          type: Constants.SomeAction,
          user: resp.data.user,
        });
      });
  };
},

You need to make sure you're returning the promise returned by axios, as that is what you want to chain off with the subsequent then.

Looking more broadly at cases where you have to ensure actions are dispatched in a particular order, it will differ a bit based on whether your actions are synchronous or asynchronous (where you async actions will generally return a promise).
Synchronous events are easy, you can simply call them sequentially:
dispatch(syncAction1())
dispatch(syncAction2())
dispatch(syncAction3())

For async actions, you'll want to ensure that each action returns a promise, and then chain them off each (rewriting your componentDidMount function to point out some other issues):
dispatch(Actions.fetchUser(userId))
  // You need to ensure that your handler functions returns the result of the
  // next async dispatch
  .then(() => {
    return dispatch(Actions.fetchAbc(abcId))
  })
  // More simply, if you're only doing on thing then you can use the shorter
  // form of arrow function, which implicitly returns the result
  .then(() => dispatch(Actions.fetchDef(defId))

If you have situations where you need a combination of the two, you can do that too:
dispatch(syncAction1())
dispatch(asyncAction2())
  .then(() => {
    dispatch(syncAction3())
    return dispatch(asyncAction4())
  })
  .then(() => dispatch(asyncAction5))

(Where the async actions are thunks that return a promise, but the sync actions could be either plain objects or synchronous thunks.)
Comment: For actions that don't really have any return value, how can I mimick one that just returns true?  I tried ```return true``` but i'm guessing it has to be asyc somehow?
Comment: It depends on what you're trying to do. If you want to chain off the action (as in your question) you need to return the promise that you want to chain off (i.e. the promise chain starting with your axios call, which will ultimately resolve with the action your dispatching on success). You're not returning it because you're interesting in the return value as much as knowing when the promise has resolved.
Comment: I have some actions that just dispatch, no axios call is made.  So how can I just return a ```return true``` in that case but asynch?
Comment: There's no need to do anything special with async actions, you just do the next action afterwards as a separate dispatch (not chained off the previous one). Have added some more examples about ensuring dispatch order with a mix of sync and async actions, but if you still have questions might help to have a more concrete example.


EnumMap> - how to have unique values for every key

Question: I'm trying to make something like this.
Let's say my EnumMap looks like this EnumMap<Animals, Set<Integer>>.
I have keys like: Dog,Fish,Cat from Animals class.   And I want to print all values from Animals Dog, Fish and Cat.

Dog has values: - 1,2,3
Fish has values - 4,5,6
Cat has values: - 2,5,7

As you can see, Cat has 2 from Dog, and 5 from Fish.  So the output will be: 1,2,3,4,5,6,2,5,7.
I want to remove duplicates during adding process to EnumMap.
So it should be like: 1,2,3,4,5,6,7. I cannot filter later after adding all values. How can I do this?
Comment: On a side note - this is not a valid `EnumMap` because the key is a `String`. It won't compile.
Comment: Please provide a [minimal, complete and verifiable example](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: @Kartik I already provided example. Right? What I want to achieve and how it should looks like. Btw. It was only the example in my EnumMap in project I have object of concrete class.
Answer: This should help:
public class Test {

    private Map<Animal, Set<Integer>> m = new EnumMap<>(Animal.class);

    public Test() {
        m.put(Animal.DOG, Set.of(1, 2, 3));
        m.put(Animal.FISH, Set.of(4, 5, 6));
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.addValueIfNotPresent(Animal.CAT, 2);
        t.addValueIfNotPresent(Animal.CAT, 5);
        t.addValueIfNotPresent(Animal.CAT, 7);

        System.out.println(t.m);
    }

    private void addValueIfNotPresent(Animal key, Integer value) {
        if (m.values().stream().flatMap(Collection::stream).noneMatch(value::equals)) {
            m.compute(key, (animal, integers) -> {
                if (Objects.isNull(integers)) {
                    Set<Integer> s = new HashSet<>();
                    s.add(value);
                    return s;
                } else {
                    integers.add(value);
                    return integers;
                }
            });
        }
    }

    enum Animal {DOG, CAT, FISH}
}

Output:
{DOG=[3, 2, 1], CAT=[7], FISH=[4, 6, 5]}

This is not very optimized and clean, but should give you an idea on how to proceed.


Iframe of different website

Question: I need to check if parent iframe website is different from inner iframe
var obj = parent.location.href;
if(typeof obj !== "undefined")
{
      //different
}
elss
{
     //same
}

This works fine with chrome...but gives and error on firefox/i.e
(permission denied to access property 'tostring')
plz Suggest an alternate solution
Comment: try putting the code in try catch?
Comment: try{ /* code here \*/ } catch(e){ /* error handling */ }
Comment: well u got the answer. if permission denied then you already know that the websites are different.
Comment: @gp please add ur answer on answer section , so that i can choose ur ans as best
Comment: If they're on different domains, you won't be able to access each others contents.
Comment: i know .... i just wana know if they are same or not ( dats why i am matching undefined)
Comment: @gp. issue is below code is not getting executed on firefox/ie
Comment: @gp how to add try catch ?
Answer: This would work even when cross origin access is allowed. If it's not allowed, suppress the error using try catch.
var same = false;
try{
    var parentLocation = parent.location.href;

    if(parentLocation == location.href){
        same = true;
    }
}catch(e){
    //error => permission denied => different website
}

Iframe of different website


a problem with Stokes' theorem(curl)

Question: If L is the circle which you get from the intersection between the sphere $$ x^2+y^2+z^2=1, y=x\sqrt(3) $$
and $$  I= \int_L (y-z)dx+(z-x)dy+(x-y)dz $$
so |I| equals to?
but i dont understand how the intersection is a circle
if i compare between them im getting  $$ 4x^2+z^2=1 $$
but this thing is an ellipse
what am i doing wrong?
Comment: The intersection looks like an ellipse if you look at it from the side owing to the tilt of the intersecting plane. But it'll be a circle if you look at it 'head on.'
Comment: @Semiclassical can you further explain
Comment: You might wish to add a 'conic sections' tag to your question.
Answer: Your confusion arises because the equations of conic sections in 2D and 3D are different.
It is not enough to write $4x^2+z^2=1$ to specify an ellipse in 3D - in fact, that is the equation of a cylinder with an elliptical cross-section, and the y-axis as cylinder axis. However, if you add $y=0$, it becomes an ellipse.
Now imagine cutting this elliptic cylinder with a plane. If you use planes parallel to the xz plane by picking a constant y, you'll get ellipses. But if you cut the elliptic cylinder with a plane of just the right inclination to the xz plane you can actually specify a circle in space.
Comment: great, thanks,
but i still cant manage to solve this problem
cant you show me how to?(at least the very beginning)
Comment: i think i  got it
is it right to say that the integral equals to:$$ rotF*n =-(2i+2j+2k)*(\sqrt(3),0,0) $$

a problem with Stokes' theorem(curl)


Como Fazer com que um checkbox não seja selecionado se não houver seleção de outro anterior?

Question: Tenho um pilha de mensalidades, onde cada uma se encontar em um select.
Gostaria que, a principio, todas elas estivessem desabilitadas excepto o primeiro check, e que ao habilitar o primeiro check, o segundo check pudesse estar disponível para ser habilitado, e se eu desabilitar o primeiro check, o segundo volta a estar indisponível (disable) para ser habilitado e assim por diante.
Ou seja só posso selecionar um checkbox se o chekbox anterior estiver selecionado
Gostaria de fazer isso co jquery ou php puro ou com outras sugestões.
<input type="checkbox" > Janeiro
<input type="checkbox" > Fevereiro
<input type="checkbox" > Março
<input type="checkbox" > Abril`

Comment: não seria nada semelhante a isso? https://pt.stackoverflow.com/questions/158010/habilitar-e-desabilitar-bot%C3%A3o-salvar
Comment: e qual a sua dúvida? pode colocar o código html e javascript do que já fez para podemos ajudar?
Answer: Pode ser feita uma função para quando clicar num checkbox verificar se o mesmo está marcado, se estiver habilita o próximo, caso contrário desabilita o próximo e desmarca também mesmo desabilitado.
Inicialmente é melhor deixar somente o primeiro habilitado no HTML.

$(".meses").click(function(){
  let meses = document.querySelectorAll(".meses");
  for (let i = 0; i < meses.length; i++) {
    if (meses[i].checked && i+1 < meses.length){
      meses[i+1].removeAttribute("disabled");
    } else {
      if (i+1 < meses.length) {
        for (let j = i+1; j < meses.length; j++) {
          meses[j].checked = false;
          meses[j].setAttribute("disabled", "true");
        }
      }
    }
  }
});

<input class="meses" value="1" type="checkbox">Janeiro
<input class="meses" value="2" type="checkbox" disabled="disabled">Fevereiro
<input class="meses" value="3" type="checkbox" disabled="disabled">Março
<input class="meses" value="4" type="checkbox" disabled="disabled">Abril
Comment: Muito Obrigado Caríssimo... Isso foi de grande ajuda....


How to print out search results

Question: I created a custom searchpage.tpl.php to print out search form and search results using the following code:

<?php
print drupal_get_form('search_form');
?>

<div class="search-result <?php print $search_zebra; ?>">

    <a href="<?php print $url; ?>"><?php print $title; ?>

    <?php if ($snippet) : ?>

<?php print $snippet; ?>

    <?php endif; ?>

It shows the search form correctly and when I search a phrase, URL changes to http://domain.com/search/node/phrase
But it doesn't show the search results, How can I make it work please?
Comment: search-api has not any 6 version, and in drupal core search module there is not any searchpage.tpl.php. please check your question, it seams something wrong in it
Comment: Thanks, but as I mentioned above I CREATED a custom `searchpage.tpl.php`. anything related to search redirects to this page.
Answer: Here's the solution:

<?php
print drupal_get_form('search_form');
?>

<?php
$keys = arg(2);
print search_data($keys, $type = 'node');
?>

How to print out search results


System of 4 quartic equations

Question: \begin{align*}a &=\sqrt{4+\sqrt{5+a}},\\ b &=\sqrt{4-\sqrt{5+b}},\\ c &=\sqrt{4+\sqrt{5-c}},\\ d &=\sqrt{4-\sqrt{5-d}}.\end{align*}
Compute $abcd$.
I set up each as a quartic and got $a^4-8a^2-a+11=0$ and similar equations for $b,c,d$, but am unable to figure out how to format the roots as a product of all of them.  Could someone give me a bit of a hint?  Thank you.
Answer: We get that $a$, $b$, $-c$ and $-d$ are distinct roots of the polynomial
$$x^4-8x^2-x+11.$$
Hence,
$$x^4-8x^2-x+11=(x-a)(x-b)(x+c)(x+d)$$
so
$$abcd=11.$$
Comment: @rk_347 As you showed, $a$ is a root of $x^4-8x^2-x+11$. Doing the same thing with $b$ yields to the same polynomial. For $c$, the same techniques gives that $c$ is a root of $x^4-8x^2+x+11$ and hence $-c$ is a root of $x^4-8x^2-x+11$. You also get this for $d$.
Comment: Wait, where did you get a,b,-c, and -d from?
Answer: Notice that $a, b, c, d$ are the roots of the equation
$$(x^2 - 4)^2 = 5 + x$$
$$x^2 - 4 = \pm\sqrt{5 + x}$$
$$x^2 = 4 \pm \sqrt{5 + x}$$
$$x = 4 \pm \sqrt{5 + x}, -(4 \pm \sqrt{5 + x})$$
$$x = 4 \pm \sqrt{5 + x}, 4 \pm \sqrt{5 - x}$$
Now, the quartic equation corresponding to the first equation is, as you've expanded,
$$x^4 - 8x^2 - x + 11 = 0$$
By Vieta's Formulas, the product of the roots ($a, b, c, d$) is given by
$$abcd = (-1)^4\frac{11}{1} = 11$$

System of 4 quartic equations


CSS & JS & images = 404 for WordPress blog in Rails + Nginx environment

Question: I'm pulling out my hair on this one.
You can see yourself here - http://starterpad.com/blog/ - that all the images, CSS, and JS files are 404 errors.
The main StarterPad site (http://starterpad.com) is running Rails, and it seems fine.  But the /blog is WordPress and it has seen better days.
Here's our nginx.conf file:
<code>user  apache;
worker_processes  2;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    passenger_root /usr/local/rvm/gems/ruby-2.0.0-p247/gems/passenger-4.0.24;
    passenger_ruby /usr/local/rvm/wrappers/ruby-2.0.0-p247/ruby;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile       on;
    tcp_nopush     on;
    reset_timedout_connection on;

    keepalive_timeout  65;

    gzip  on;

#    include /etc/nginx/conf.d/*.conf;

server {
  server_name www.starterpad.com;
  return 301 $scheme://starterpad.com$request_uri;
}

  upstream starterpad {
    server unix:///var/www/starterpad.com/shared/tmp/sockets/puma.sock fail_timeout=0;
  }

  server {
    listen 80;
    server_name starterpad.com vps.starterpad.com;
    root /var/www/starterpad.com/current/public;
    error_log /var/www/starterpad.com/shared/log/nginx_error.log;
    access_log off;

    error_page 403 404          /404.html;
    error_page 422              /422.html;
    error_page 500 502 503 504  /500.html;

    location ^~ /assets|uploads/ {
        gzip_static on;
        expires max;
        add_header Cache-Control public;
    }

    location @starterpad {
        proxy_pass http://starterpad; # match the name of upstream directive which is defined above
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    location / {
        try_files /index.html $uri.html $uri @starterpad;
    }

    location /blog/ {
        #try_files $uri $uri/ /blog/index.php?$args;
        #deny all;
        root /var/www/starterpad.com/blog;
        rewrite /wp-admin$ $scheme://$host$uri/ permanent;
        include wpsecure.conf;
        index index.php;
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }
    location ~ \.php {
        root /var/www/starterpad.com/blog;
        try_files $uri = 404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
  }
}
</code>
Here's some errors from the error log, but they don't seem helpful to me:

2015/01/26 22:16:06 [error] 11511#0: *11 open()
  "/var/www/starterpad.com/blog/blog/wp-content/themes/sparkling/inc/css/font-awesome.min.css"
  failed (2: No such file or directory), client: 126.96.36.199, server:
  starterpad.com, request: "GET
  /blog/wp-content/themes/sparkling/inc/css/font-awesome.min.css?ver=4.1
  HTTP/1.1", host: "starterpad.com", referrer:
  "http://starterpad.com/blog/"
2015/01/26 19:22:26 [error] 10431#0: *28798 FastCGI sent in stderr:
  "Unable to open primary script:
  /var/www/starterpad.com/blog/b6d767d2f8ed5d21a44b0e5886680cb9/generator.php
  (No such file or directory)" while reading response header from
  upstream, client: 126.96.36.199, server: starterpad.com, request:
  "POST /b6d767d2f8ed5d21a44b0e5886680cb9/generator.php HTTP/1.1",
  upstream: "fastcgi://127.0.0.1:9000", host: "starterpad.com",
  referrer:
  "http://starterpad.com/blog/wp-content/uploads/2014/12/SoftwareProgrammer-750x410.jpg"

I've read so many Stack Overflow and other pages, tried almost everything in the nginx.conf, but for the life of me I can't get it to work.
Any ideas?  You'd be my frickin' hero!
Comment: Yes, the first error makes it blatantly obvious what's going on.
Comment: Look at your error log.
Comment: nginx error log has nothing useful.  Is there another error log I should be looking at?
Comment: I posted a couple possibly-useful error messages above
Comment: Oh duh!  Double /blog lol
Comment: Now I can view images and such, but the actual blog is down lol...can't figure out what nginx config changes so EVERYTHING works...reverting back
Comment: GOT IT, thanks @MichaelHampton - if you want to answer the question I'll give it to you.
Answer: Figured it out (thanks to MichaelHampton).  The changed rows are in bold below.

location /blog/ {
root /var/www/starterpad.com;
include wpsecure.conf;
index index.php;
try_files $uri $uri/ /index.php?q=$uri&$args;
}
location ~ .php$ {
root /var/www/starterpad.com/blog;
try_files $uri $uri/ /index.php?q=$uri&$args;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_split_path_info ^(.+.php)(.*)$;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
include fastcgi_params;
}


Render plane on a glClipPlane

Question: How can I render a plane on the surface of a glClipPlane clipping plane?  The plane is rendered by drawing a polygon between a series of points that are located on the plane.  Right now, it's producing some very fun stitching.
I assume glPolygonOffset won't help me here?
It is possible for me to just translate the plane a tiny bit over to one side of the plane, but I would prefer a simpler and more elegant solution, if one exists.
Answer: I assume you are not using GLSL? If you have GLSL 1.30, you can just set a vertex's gl_ClipDistance [N] >= 0.0 for clip plane N and the point will not be clipped. If you do that for every vertex in the polygon you want to span your plane, the polygon will not be clipped (against that plane anyway).
As for glPolygonOffset (...) that affects the depth computed during rasterization. It happens after clipping, and likewise clipping has nothing to do with polygon depth, so you are correct it will not help. You will have to translate your vertices before/during primitive assembly for this to work, so that either means performing translation in a vertex shader or using the fixed-function modelview matrix.
Comment: No, I don't have GLSL at the moment... I might look into it later but for now thanks for the answer.  I ended up just biting the bullet and transforming the vertices in the modelview matrix.

Render plane on a glClipPlane


Tips on improving my football skills

Question: I should probably start by saying I'm not a particularly sporty person, I did as little as possible whilst growing up, but in the last 7 years or so (and in my past two jobs) I've been playing 5-a-side football a couple of times a week. I started off terribly, and yes, I'm still pretty terrible.
The people I play with are supportive, but I feel like I need to take a step back and entirely re-think the way I play. My biggest problem is a complete lack of composure on the ball, if I'm under any sort of pressure in defence I usually lose it, if I'm under pressure in attack I either lose it or just blast it towards the goal
One other thing I struggle with is that regardless of whether I'm shooting or passing, I either do a toe-punt or a Quaresma-esque hit of the ball with the outside of my boot. I really struggle to get any sort of control or power using the inside of my foot.
What's frustrating is when I'm watching football a lot of people have commented on how good my understanding of it is, often seeing things that other people don't - but when I'm thrown into a situation where I'm actually on the pitch my footballing intelligence is precisely zero as I constantly panic and give away the ball.
Any tips on how to improve my game would be much appreciated.
Comment: Like you said, the main thing probably is to remove the panic factor. That should go a long way in improving your play on the pitch. Keep calm and pass/shoot the ball. That being said, would leave it to the more experienced footballers out here to give a proper and more valuable suggestion.
Comment: I liked the honesty in this post. As it's been already more than 4 years since you asked for help, I'm wondering if the provided answers helped you and whether you improved your play or not.
Comment: Thank you! Sorry for the late reply but yes absolutely the replies have been very helpful :) It can be difficult to monitor your own progress I guess (in my head, I haven't really improved) but others are always saying the opposite. I _try_ to be more confident which was a big thing for me. My technique is bad, partly down to a dodgy knee, but I've learnt to sort of just embrace that now :)
Answer: Wow, where do I begin...? :)
First off, I would recommend anyone to identify in which facets of the game you are lacking (which you have done more or less). I think the biggest factor in improving yourself (no matter if it's football or public speaking or anything else) is to be objectively critical of yourself.
You have pointed out two important aspects of the game, namely technique and mental composure in the game (lets put aside the physical composure for a second). These are two very different aspects, which require different approaches to improve. What's common between them is practice. The more you play the more accustomed to playing you will get. This doesn't mean that you will automatically get better at playing, but you will undoubtedly feel more comfortable on the pitch. That aside, let's take a look at it one thing at a time:
The technique: this is obviously the hard bit. Shooting, dribbling, heading, accurate passing/crossing are all very dependent on good technique. Technique on the other hand is built on being proficient in the fundamentals, like which side of the foot you should use in order to send the ball to different directions.
Another good example is how you control the ball when it comes at you rolling or flying. You might have seen some players get really high/fast balls without a bounce, that for instance requires good skill and control, typically sign of a player who's got the fundamentals down. As @gbianchi has pointed out, this type of fundamental skills are much easier to learn at younger age, then it'll just sit in the backbone.
That said, how can you improve? I cannot give you an exhaustive list but here are a couple tips:

A good shot always starts with a good composure, if you are off-balance or haven't placed your support leg at the right position, your shot will ultimately be a wasted effort.
practice with using different parts of your shooting foot (inside, tip, outside, heel...) in front of a wall. Just to see how the ball reacts to your shot/pass. Likewise the point of contact with the ball is also very important. You need to get a feel for how the ball will react to different kinds of contact with your foot.
to increase your composure on the ball, ask a friend to help you out with the following drill: put one foot on the ball (the one you feel most comfortable with). Then ask your friend to try to get to the ball, while you just move the ball away from him, using your own body between the ball and your "opponent" (check this video out)

The mental composure: This bit could be easier than improving your technique, since it's entirely in your head and have almost nothing to do with your body.
First off, as I said the more you play the more comfortable you will be with the ball. Most important thing you need to learn/figure out is to not be afraid of the ball. I cannot stress this enough. Even professionals end up being afraid of the ball at times, avoiding the ball and responsibility that comes with it.
Avoiding the ball is a terrible thing in two ways; 1) it will seriously hinder your improvement 2) it will leave your teammates in tough spots at times. There is no such thing as keeping a low profile in this type of team sports (especially in 5-a-side), you should always be available to take a pass from a teammate.
Once you have established that getting the ball is not a thing to be scared off, you should concentrate on reminding yourself that making a mistake is not the end of the world. This is very crucial to understand that mistakes are part of the game, and as it happens there is only one thing you should focus on, making amends. You lost the ball by a bad pass/unnecessary dribble? Win it back! Cleared the ball towards an attacker? Cover the shot! Team sports are all about taking responsibility, once you take responsibility for your mistakes your self-confidence will improve as well as your teammates opinion of you.
All that said, here are a couple of tips to reduce your stress while playing defense:

Last man in defense? Don't go dribbling; last man plays safe: ALWAYS!
Unless you are extremely fast in your reaction times, don't rush the incoming attacker. Back up slowly covering the zone and the shot. Attackers (especially those who are skilled in dribbling) will almost always try and trick you into committing to a false move, and go the other way.
When outnumbered your action kinda depends on how good your goalie is. If the goalie is confident against long shots (i.e. has good reflexes), cover the run and the pass. Otherwise cover the shot.

Game intelligence: probably the hardest thing to improve. It's easy to "read" the game, sitting in a sofa at home, seeing the tele-cam cover half of the field from above. It takes much practice and honestly a bit of talent to be able to read the game properly while playing (please note that I do not claim to have the talent myself :))
I almost exclusively play defense in futsal (indoor 5-aside) and I think it definitely helps with game intelligence. You learn to observe how others play. Paying attention to tendencies in different players' game is a great asset for a defender/midfielder. Oh, and don't just watch the ball, as a defender you should always know where your opponent is. "Is he still where he was last I checked, or is he taking a diagonal run?"
When playing as a more attacking role; keep in mind that you don't need to do something elaborate to be effective. I personally never felt particularly comfortable with dribbling, instead I prefer short quick passes, 1-2 plays as well as through passes to a teammate, or taking a deep run to outflank the defense.
SUMMARY:
Practice is king! Play more: practice what you are bad at before/after a game, stick to what you are good at during the game. Take initiative, talk to your teammates/friends on your progress. Most of all, make sure you have fun when you play. If you treat it very seriously you'll probably get too nervous. It's supposed to be fun, right? ;)
Comment: This is fantastic, thank you so much! I'm certainly going to start taking more responsibility and try to fix my mistakes (people always comment on how I unnecessarily apologise a lot) and try not to shy away from the ball in future - to ensure I give my team mates an option like you said.

I'll continue to practice and generally just try to stay more switched on, more alert, and more open to improving my game and learning from others. Thanks again :)
Answer: Well.. Any answer here could be a little subjetive about this.
I would start saying that even if you understand the game, that doesn't mean that your body will do what your head wants to do.
The other factor is practice. When you are a young boy, your body learns movements a lot better that when you are growing. that's why players usually are young people. It's very hard to learn how to move your body while you are growing up. The best you can do at this point, is do a lot of drills on passing, movements and shots. You will not learn in the course of a game, at least not without help. The other thing you need is a coach (any type, even a friend that do the things in a right way), it can help you pointing out flaws he see, or at least showing you how to do particular things.
But even if you do all that things, there is a chance that your play never gets better. There are a lot of cases where coach where not great players, and great players are horrible coach (just see maradona coaching).
also, besides 5 a side soccer can make you go attacking and defending, start playing only one position until you get a better aproach on it.
Comment: Many thanks - I've spoke with the people I play with and they pretty much all agree the thing I need to work on most is the sidefoot so I'll focus on that :) Also asked if I should focus on attacking/defending and they said because I don't tire as much as others, I should continue to do what I'm doing... but I may try sitting back/staying forward for a couple of games and seeing how it goes :)
Answer: I'm a good player with fantastic dribbling,the one thing that helps me is being happy and having fun while I play in other word being relaxed, if you think too much during a game you become nervous and make terrible mistakes, I once played in a match where I dribbled past 5 defenders with ease before setting up a goal that same me also played in another match where a pass was played to me and I kicked the ball to the opposition instead of trapping it, the key in soccer is to always try to be happy and relaxed, when you are relaxed you have more time to think and make proper descisions that could lead to goals heck. You can even decide to dribble a few people along the way. Hope this helped.

Tips on improving my football skills


A minor scale definition: am I missing something?

Question: I've recently had a discussion with a woman, let's call her Jane, who maintained that the A minor scale features G# rather than a natural G. According to her, the scale goes A, B, C, D, E, F, G#, A. While I'm moderately proficient (though I definitely lack authority) in harmony and general theory, I was pretty sure the scale is actually all natural, going by what I consider a basic principle, that C major and A minor are both all-natural scales, and that minor scales are "the same" as the major scale three semitones above them.
So I defended my position, and the discussion got heated. I said that maybe she was thinking of the harmonic or melodic minor scale (I never learned which is which), but that I was talking about the natural A minor scale and that one has no G#. Jane went on saying that if you're writing or playing in A minor then of course the dominant chord is E major, not E minor, because G#, and that you would never resolve the harmony using E minor. She concluded that I'm blatantly wrong, and that since Bach and the equal temperament the minor scale has always included a sharp seventh.
Now, the reason I'm asking here what is right and what is wrong is that Jane is a conservatory graduate in Piano and Harmony, and (you probably guessed it) I'm not. Maybe I'm just seeing things at a lower-intermediate level, and maybe I can't realise that my knowledge is basic handbook stuff, but she knows that a certain set of harmonic rules that I don't know mandate that you never use the actual natural minor scale. I don't know, I'm making this up, but I can imagine that there is a reason I don't understand.
So, to sum up:

what does the A minor scale actually look like?
if I'm writing a piece in A minor, should I use E minor or E major?
is it possible that I am, like, "right but actually wrong" when I say A minor has no G#?

PS: as to the second and third question, I know that any note may have a place in any scale if just to create an intentional dissonance. I'm talking about classical harmony: think Bach, that she herself even mentioned.
Comment: Ask Jane if the III chord in the key of Am is a C or a C+. Both G and G# are used in A minor. Case closed.
Comment: @JohnBelzaguy One other thing that A minor songs sometimes like to do is that neither E nor Emi are anywhere to be heard but instead what feels like the dominant is the G chord. (There's probably a proper term for it somewhere.) Lady in Black, for instance, and many others.
Comment: @Divizna Yes, in the relative major key of C that is considered an "interrupted" or "deceptive" cadence, V-vi.  In minor it becomes a VII-I but sonically has a similar sense of resolution. The reason is because the 3rd of the G chord resolves like a leading tone to the 3rd of the Am chord.
Answer: When I first started learning about music, in the 1950s, it was generally accepted that the 'normal' minor scale was the Harmonic Minor, with its sharpened leading note.   Without this, there was no leading note, no dominant chord with a strong tendency back to the tonic, basically no Common Practice harmony.  We knew about the Melodic Minor scale of course, and even the Natural Minor (though that belonged mainly to folk songs).  But Harmonic Minor was king, and we were taught that a sure-fire way of recognising whether an open-key piece was in C major or A minor was to look for the G♯ accidentals.
Modern music theory - particularly 'jazz theory'- is more inclined to consider Natural Minor the norm (though it's interesting that 'cycle of 5ths' progressions are still very popular, often with the sharpened leading notes that create 'secondary dominants').
Jane is giving the old-school answer.  But unless she graduated conservatory a LONG time ago (and has closed her mind to subsequent ideas) she should really be taking a less entrenched position!
Comment: Jazz theory, natural minor? I'd have said jazz melodic.
Comment: @tim that only really starts to come up when learning about alternative sounds to overlay over diatonic harmony. Learning jazz you tend to go through learning the modes first, and as such nat minor is considered the default minor scale. You're more likely to think in terms of leading tones before really digging into the various other minor scales, in my experience. Thinking fully 'jazz melodic minor' pops up first when using the altered scale over a dominant, and for most jazz players is more of a 'parallel pool' to dip into rather than a default.
Comment: Of all the (very exhaustive) answers, I think this one hit the correct reason for Jane's position. Thank you!
Answer: There are actually more than one A minor scales.
What's generally understood as "A minor" is the Aeolian scale, and has a G.
The one that has a G# is the harmonic A minor scale.
I've never been able to wrap my mind around the melodic minor scale that, apparently, has F# and G# when going up but G and F when going down. (No I have no idea how that works.)
And these three are those you hear about the most, but the list goes on.
In any case, it's very common to use a major dominant chord in the harmony of minor key songs, so a song in A minor is more likely to feature an E or E7 chord, which contains a G#, than an Emi chord with a G in it.
Common, but not a rule. There's still plenty of songs with a minor dominant, too.
And to answer

if I'm writing a piece in A minor, should I use E minor or E major?

You are the composer. You can write a piece in A minor featuring the Emi chord, and another piece in A minor that uses the E chord, yet another where both will get a turn, and yet another where just neither of them appears. Any of those possibilities is fine.
Comment: @Laurence But the melody doesn't go neatly up and neatly down, it changes direction at any time, and jumps around in thirds and fourths and sixths, and then stays in place for a bunch of times, it can *start* on the ambiguous note. If I wanted to sit down and think "now I'll compose a tune in the melodic minor", I'd have absolutely no idea how to do that, or what the rules are for it to be considered the melodic minor and not something else. And what am I supposed to do about the chords that come with it? How does it, you know, *work*?  In the real music? What do I *do* with such a scale?
Comment: "I've never been able to wrap my mind around the melodic minor scale that, apparently, has F# and G# when going up but G and F when going down. (No I have no idea how that works.)"   You have just described precisely how it works!  When the melodic line rises, it retains the sharpened leading note, and sharpens the 6th as well so as to avoid an 'un-melodic' augmented 2nd.  Coming down, ^7 is not acting as a leading note so we cam smooth things out the other way.
Comment: First and foremost, we do not write music using 'scales'. Keys, yes, but melodic minor is not a key. And often not only using 'scale' notes. You'll find, that often, in music you're writing, (in Am) that G# fits better when the melody is rising, and G nat. fits better when it's falling. Hence the melodic minor, to reflect that. Not always! It's your piece, to write as you want.
Comment: @Tim I guess you mean we do not limit ourselves to only use scales and particularly not only use one scale? Sounds a bit weird to throw out a huge chunk of music theory when putting on you composer-hat... I use scales all the time when listening/playing (usually playing them out of order but the same set of notes) because a lot of music is simple enough.
Comment: @Emil - we get sooo many questions here regarding how notes 'out of scale' have the audacity to be in pieces. Basically, it's a bit of theory that's *just not true*.
Comment: @Tim I am not sure what you mean with 'not true'. It is basically a default map for sheet music and fingerboard / fretboard. But yes beginners are probably frustrated with the other notes because they are slightly harder to find.
Comment: @Emil - of course it's a default map - scales are ordered lists of notes used in a key, rather like an alphabet. However, what I mean is students seem t be taught, and cling onto, the concept that a piece in a key should only have the notes from that key's scale used. And the other notes (chromatic) not used in a diatonic scale aren't hard to find - there's only 5 of them left.
Comment: @Tim I have played for fun maybe four years now but I didn't see the larger structures of the scales until like last week, like how it looks like larger grids slightly overlapping eachother, since I was too focused on one or two strings at a time. Unless you really dig into the  larger scale patterns you can miss a lot. And I know I get lost easily once I play tones outside, I usually end up in a different key then because I forgot what I was doing. I just mentioned it because I think they are harder to make sound nice for a beginner like me, it is usually hit or miss.
Comment: They're called 'chromatic', because they're out of key, and add 'colour' to the piece. But so many folk seem to be entrenched in the 'fact' that they shouldn't be there at all...
Comment: @Tim Yeah the question "how dare that tone/chord be in this song" is not a question you'd get from me. I mean if the "outsider" notes were verboten then you could hardly have the C-C7-F progression everywhere and see a sharp in the middle of a bar in sheet music ever. So it seems pretty obvious they're fine.
Comment: But I'd say I kinda do use scales in my songwriting. Of course, with a common scale like C major I don't think of it, it's in the back of my head. But I know that these seven tones "belong", these other five are "outsiders", here's my tonic (C), dominant (G or G7), and subdominant (F) that neatly cover the scale, and the Ami-Emi-Dmi set also goes with it well. Doesn't mean I'm not gonna throw in a nice Fmi or D7, or put a black-key note in the melody too if I feel like it. Totally will.
Comment: What it means is that I have a sort of basic scaffolding. And if I wanted to write a song in an unusual scale mode (say the Aeolian dominant, I want to do that one someday) then the first thing I'd do would be to figure out that scaffolding. Then I'd start playing around with it. Probably stick close at first until I get a feeling for it, then I might dare go wilder. When the scale is ambiguous, I can't do that. Ascending and descending... my tune goes A G# G# B, is that ascending or descending? If I were trying to use the A melodic minor, would I put a G or G# there? It's just confusing.
Comment: "I've never been able to wrap my mind around the melodic minor scale that, apparently, has F# and G# when going up but G and F when going down": think "Hit the Road Jack" or any other song with chords such as Am-G-F-E7-Am.  Then, during the E7 chord, imagine a scale-wise ascent from E to A.  A frequent choice for the intervening pitches is F sharp and G sharp.
Answer: Jane is part right, so are you!
Three (or more, read on) minor scales are in common use. A scale is simply a set of notes which work well together, played in ascending and descending order.
As such, the natural minor scale uses exactly the same notes as the major scale associated with it - the relative.
The harmonic minor scale uses a sharpened leading note (G♯ in key Am), in order to produce a better dominant harmony/chord.
The melodic minor scale then changes the 6th note to a sharpened 6th, in order to close the 3 semitone gap produced in the harmonic minor. Classically, that's ascending, and it reverts to natural minor notes descending. There's also the jazz version, using raised 6th and 7th notes both ways.
But - there are more! Minor scales come in the guise of minor modes, all having a m3 from root to 3rd note. Dorian and Phrygian come to mind, apart from others from foreign lands.
So, in fact, Jane, with her 'experience', is less right than you! She must have played and studied many pieces, of all genres, that use both the natural and raised leading note! Show her these, and probably subsequent answers, to enlighten her!!
John's point is a very good one - Em exists in key Am, whereas C+ is rare. The former having G♮, the latter G♯.
Answer: I learned from a more "classical" point of view that the natural minor was the "basic" scale associated with a minor key. I did learn to play natural, melodic, and harmonic minors on various instruments though.
Some of the problem comes from the misleading assumption (made in some texts) that keys are derived from scales. In my opinion, it's easier and more consistent to extract scales from keys. I don't know much about how pop or jazz theorists look a things. Most music from the 1600s to the 1900s or so is written in a key, not from a scale. (I think many of the composers thought of the basic organization being a hexachord.) I see lots of questions on the internet that imply people are taught (or self-taught) that music is organized by scales rather than by keys. There are several scales that can be extracted from the notes belonging to a key. It's simple for the major mode; the minor mode has some major differences though.
The major mode has 7 notes which may be arranged in order (with the tonic as the first note) to give the major scale pattern. The minor mode also has 7 notes but two of these notes are mutable; scale steps 6 and 7 occur in two forms. For notational convenience, it's useful to use the key signature of the relative major for minor keys; the notes are arranged to have the third note a minor third above the tonic.
The different minor scales are extracted from the majority (or plurality or perceived plurality) of choices made with the mutable notes. Goetschius ("Exercises in Melodic Writing") gives some examples as do other authors.


Drupal's "Add to Cart" field shows product variations instead of individual options

Question: This is probably a very novice question, but I'm working on a website that uses Drupal Commerce. There is a field defined for the product display called: Product variations which is of the format Add to Cart form.
On most products, this field correctly shows a combination of size and color dropdowns, whereas for some products, it just puts all products variations in a drop down and shows that instead of the color/size combination.
Any idea what might be going wrong or how to debug this issue?
Wrong:

Correct:
Answer: It looks like the products you've referenced from the "wrong" image do not all share the same attribute fields in common. One frequent mistake in this regard is forgetting to toggle the checkbox on the field edit form to instruct Drupal Commerce to treat a product field as an attribute field on Add to Cart forms.
Comment: Can you elaborate please where that check box you are referring to is? Also, both these products belong to the same exact content type.
Comment: There are screenshots in the documentation: https://drupalcommerce.org/user-guide/product-attributes-variations


How to pass a com.sun.jna.Structure from Java to struct in C, using JNA

Question: I'm going off of this example of how to pass a com.sun.jna.Structure containing a com.sun.jna.StringArray from Java into native C code using JNA, and having trouble obtaining the Structure contents successfully in the C code.
Note that I can pass a struct from the C code to a Structure in Java successfully, but I'm having trouble creating a Structure in the Java code and successfully sending it to the C code as a struct.
This is the code in question:
String[] user_name_array = new String[3];
user_name_array[0] = "test_user_1";
user_name_array[1] = "test_user_2";
user_name_array[2] = "test_user_3";
StringList.ByReference members = new StringList.ByReference();
members.length = 3;
members.strings = new StringArray(user_name_array);
MyNativeLibrary.myMethod(members);

Seems simple enough, but it's not working.
It gets into the C code successfully as expected, but the Pointer in the Structure is empty, and the length is zero.
Here is the StringList Structure in the Java:
public static class StringList extends Structure {
    public volatile long length;
    public volatile Pointer strings;
    public static class ByValue extends StringList implements Structure.ByValue {}
    public static class ByReference extends StringList implements Structure.ByReference {
        public ByReference() { }
        public ByReference(Pointer p) { super(p); read(); }
    }
    public StringList() { }
    public StringList(Pointer p) { super(p); read(); }
}

Here is the corresponding struct in the C code:

typedef struct string_list {
    uint64_t length;
    const char **strings;
} string_list;

And here is the method definition in the C code:
const char* my_method(struct string_list *members)
{
   //.................
}

Using ndk-gdb, and breaking into this function, this is what it shows:

(gdb) break my_method
(gdb) cont
Continuing.

Breakpoint 1, my_method (members=0x9bee77b0) at ../app/my_code_file.c:368
(gdb) p *members
$1 = {length = 0, strings = 0x0}

It seems like it should work, so why aren't the values making it into the C code?  What am I missing?
Also note that I can successfully send a StringArray directly to the C code from the Java code if it's not inside a Structure:
Java:
//This works!
StringList members = MyNativeLib.myTestFunction(3, new StringArray(user_name_array));

C:
//This works!
string_list* my_test_function(uint64_t length, const char **strings)
{
    //......
}

It seems that in this case, JNA works as expected.  So, why doesn't it work with a Structure as the documentation states it should?
Comment: @DougStevenson  It looks like that is a solution for how to pass a StringArray, not for how to pass a Structure containing a StringArray, so not a good dupe target....
Comment: Don't mark the fields as `volatile`.  When you do that, JNA won't write to them unless you do an explicit `Structure.writeField()`.
Comment: You won't get automatic mapping of java structures to C structures.  You'll have to programmatically pull the members of interest out of a passed jobject object using JNI, with string arrays being the most taxing thing to process.  It's kind of a pain.
Comment: Possible duplicate of [passing string array from java to C with JNI](http://stackoverflow.com/questions/5972207/passing-string-array-from-java-to-c-with-jni)
Comment: Maybe this is more helpful.  http://stackoverflow.com/questions/3923299/how-to-pass-c-structs-back-and-forth-to-java-code-in-jni
Comment: Yeah, I think the function needs to accept a jobject and be mapped to the implementation of a java 'native' method.  You can generate headers for the C-side of a java native method using the javah command line.  There is a whole lot of ceremony involved in passing data around.  It might also be worthwhile to look at SWIG which cuts a lot of that out.
Comment: @DougStevenson Thanks for the info. Shouldn't JNA take care of the data mapping though? The documentation seems to suggest that: http://jna.java.net/nonav/javadoc/overview-summary.html#structures   If that documentation is correct, it seems that the example I'm going from should be correct, right?
Comment: If you build jna, include it, and specifically call through it on the Java side, sure.  I haven't  done this myself, but again, it's not going to jump in for free.
Comment: @DougStevenson What's interesting is that if I use `StringArray` directly as a parameter, it does jump in for free! Going to just go with that for now since it works, but still interested in figuring out how to make it work with a Structure.  Thanks again!
Answer: Don't mark the fields as volatile. When you do that, JNA won't write to them unless you do an explicit Structure.writeField().


SQLigt: extract only specific month

Question: I am struggling to select specific month with SQLite.
SELECT *
FROM order
WHERE strftime('%m', transaction_date) = '10';

I have tried this and it shows "[21:55:30] Query finished in 0.000 second(s)." but nothing showed up in Grid View. This is what I have in order table. I have tried changing the date to 10-23-2015 format as well but it didn't work. I don't want to use LIKE because these is an assumption that I can't see the date format.
Comment: Can you show us an example of data in the `transaction_date` column?
Comment: Thanks for your help. I have edited the original post.
Comment: Your transaction_date column might not be a datetime type. try string splitting and getting the second.
Comment: @TahaPaksu There is no datetime type in SQLite.  Dates are stored as text.
Comment: Thanks @TimBiegeleisen, I forgot. Long time no use.
Answer: Dates are stored as text in SQLite, so you can just use substring here:
SELECT *
FROM order
WHERE SUBSTR(transaction_date, 1, 2) = '10';

SQLigt: extract only specific month


Can not compile to a native executable with Clozure CL on OS X 10.10 Yosemite

Question: I have created a simple hello world (hello.lisp) ,code:
(defun main ()
    (format t "Hello,World"))

, program to test CCL's native executable compilation. I proceed to compile and load buffer from the CCL GUI (using version Clozure Common Lisp Version 1.10-store-r16266  (DarwinX8664)).
When i test it:
    ? (main)
    Hello,World
    NIL
    ?

It finds the main function. When i proceed to compile it with:  (save-application "/tmp/h" :toplevel-function #'main :prepend-kernel t), it proceeds with the operation and CCL exits.
The file is created and is arround ~56MB. When i try to run it though I get the following output:

Error: There is no applicable method for the generic function:
           #
         when called with arguments:
           (# :NOTE-CURRENT-PACKAGE #)
  While executing: #, in process toplevel(6).
  Error: There is no applicable method for the generic function:
           #
         when called with arguments:
           (# :BREAK-OPTIONS-STRING T)
  While executing: #, in process toplevel(6).
  Error: There is no applicable method for the generic function:
           #
         when called with arguments:
           (# :BREAK-OPTIONS-STRING T)
  While executing: #, in process toplevel(6).
  Error: There is no applicable method for the generic function:
           #
         when called with arguments:

And the errors proceed. What do I do wrong? Is it a bug?
Thank you
Answer: I found the keywords :note-current-package and :break-options-string in the cocoa-ide of the sources.  Since prepend-kernel t prepends the kernel that was used in the current session, it seems that you would include the cocoa-ide startup in your application.  However, the methods dispatching on those keywords only dispatch on ´ns-application`s, which your new application seems not to be.
The solution might be to prepend a kernel without cocoa-ide, either by loading your code into a non-GUI image, or by using the pathname of such a kernel for the :prepend-kernel argument.
Answer: To create executables of Clozure CL on Mac OS X:

for non-GUI applications, you need to install Clozure CL from the repository: Installing Clozure CL. You need to download CCL from there. This version comes with an executable Lisp (kernel + image), which hasn't the GUI loaded.
for GUI applications you need to use the Application Builder. The corresponding function is ccl::build-application. GUI applications on Mac OS X need some infrastructure, which is created then. Note that CCL comes with a example application in ccl/examples/cocoa/currency-converter/. Personally I would also prefer to use CCL from the repository - it's usually a bit newer than the version in the Mac Application store.


Proving the divisibility of $4[(n-1)!+1]+n$ by $n(n+2)$ in the condition of $n,n+2 \in P$ where $P$ is the set of prime numbers

Question:
Let $n$ and ($n+2$) be two prime numbers. If any real value of $n$ satisfies that condition, then prove that $$\frac{4{[(n-1)!+1]}+n}{n(n+2)} = k$$ where $k$ is a positive integer.

SOURCE: BANGLADESH MATH OLYMPIAD (Preparatory Question)
My Attempt:
I know a basic formula of modular arithmetic only and that is:
$(n-1)! \equiv -1\pmod n$ ....(but I don't know why it's true)
However, out of curiosity and after gaining nothing but few knowledge about modulus, I noticed that $(n-1)! +1$ would be divisible by n. Moreover, we will get same result from $4[(n-1)!+1]$. Similarly, $4[(n-1)!+1]+n \equiv 0 \pmod n$.
But how can I show the divisibilty of the above term by $(n+2)$ and in the same case what will be its remainder? Further, how can I prove the above condition and what is the essence that $n$ and $(n+2)$ must be supposed to be prime number and nothing else? And if they are not so, can't the desired proof be solved?
Any reference according to post or small hint will be very helpful for me. Thanks in advance.
Comment: No need to apologize, this is a standard process here - if you don't find it, there is chance others will. And still that does not guarantee that found question has information you need, in which case you can post new question with specific details you want to be addressed (ideally with referring to that question and why it does not address it).
Comment: @Sil I've got all the information whatever I need in that question and I've no specific detailes even. So, I would better let the question remaining duplicate.
Answer: The hint:
$$(n+1)!+1\equiv0\pmod{n+2}.$$
Answer: If $P$ is a prime then, $P|(P-1)!+1$,or $P|(P-3)!(P²-3P+2)+1$.So these means $P|2(P-3)!+1$.
In your question $N+2$ is prime. If you arrange the numerator then you get $2[2(N-1)!+1]+N+2$.
Now as $N+2$ is a prime then $(N+2)|2(N-1)!+1$. So, $N+2$ the divides the numerator.
Comment: Where's the [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)?


How to implement tree (touch graph) in android?

Question: Please have a look at example - http://www.youtube.com/watch?v=zu2uVo3sxCg&feature=player_embedded.
Is there any library to implement something similar (the tree) with android? If not, then is there any example in any other language I can look into?
Upd. Can I use http://sourceforge.net/projects/touchgraph/files/GraphLayout/?
Answer: I'm not sure if this would be the best solution, but take a look at this: http://code.google.com/p/libgdx/ and the developers site: http://www.badlogicgames.com/wordpress/
Something like that could pretty easily be accomplished with this library. Good luck!
Answer: It's probably not up to date for you but for others who are looking for a library to visualize and interact with graph structures.
https://github.com/oss-bandb/GraphView


Supremum of projections in von Neumann algebra

Question:
Let $\{P_i:i\in I\}$ be a set of projections in a von Neumann algebra $M$ and $J\subseteq I$ be finite. Then $P_J:= \bigvee_{i\in J} P_i$ is the smallest projection $P$ such that $\left(\sum_{i\in J}P_i\right)P=\left(\sum_{i\in J}P_i\right)$.

I'm able to show that $P_J$ is a projection and $\left(\sum_{i\in J}P_i\right)P_J=\left(\sum_{i\in J}P_i\right)$. But I'm unable to show it is the smallest.
If $Q$ is another projection such that $\left(\sum_{i\in J}P_i\right)Q=\left(\sum_{i\in J}P_i\right)$, then how to show $P_J\leq Q$. Since $P_J$ is the supremum, it suffices to show that each $P_i\leq Q$ but I couldn't show this either.
Answer: You can write the equality as
$$
\Big(\sum_{i\in J}P_i\Big)(I-Q)=0.
$$
Since the product of these selfadjoints is selfadjoint, they commute. From here we get
$$
0\leq (I-Q)P_j(I-Q)\leq \Big(\sum_{i\in J}P_i\Big)(I-Q)=0.
$$
As $P_j$ is a projection, it follows that $(I-Q)P_j=0$, that is $QP_j=P_j$. From here we get directly that $QP_J=P_J$, as $Q$ acts as the identity on each of $P_jH$.
Comment: Exactly. $ \ \ \ $
Comment: Do you mean any two self-adjoint elements commute?
Comment: No. They commute precisely when the product is selfadjoint.
Comment: Ah. So you mean the product is zero, hence self-adjoint. Therefore they must commute. I get it now!


how to add color field after Commerce Fancy Attributes has been installed?

Question: In my website I used drupal commerce, and I would like to display product my its color in product display page. This is the link I reference https://www.drupal.org/project/commerce_fancy_attributes, I have successfully installed that module. That guide said create a 'Color' vocabulary, add a text field called "Color" that will hold hex values. But I can't find the 'hex' in field type. So I can't continue the next step. I would appreciate any suggestion you could give me.
Thanks
Answer: You should create a simple "text field".


Erro com LEFT JOIN em LINQ

Question: A minha query está retornando como erro

Additional information: Object reference not set to an instance of an object.

Quando tento fazer uma categoria que não possui produto exibir "(Inexistente)":
        var lst = from c in BDProduto.categorias
                  join p in BDProduto.produtos on c.IdCategoria equals p.IdCategoria into g
                  from gr in g.DefaultIfEmpty()
                  select new
                  {
                      IDCategoria = gr.IdCategoria,
                      Categoria = gr.Categoria,
                      IDProduto = gr.IdProduto,
                      Produto = gr == null ? "(Inexistente)" : gr.Produto
                  };

        foreach (var item in lst)
        {
            Console.WriteLine("IDCategoria: {0}, Categoria: {1}, IDProduto: {2}, Produto: {3}",
                              item.IDCategoria, item.Categoria, item.IDProduto, item.Produto);
        }

Answer: você não pode acessar uma propriedade de um objeto Nulo, no caso o gr, mas acredito que IdCategoria, Categoria e IdProduto sejam propriedades de c, então faça assim:
var lst =
    from categoria in BDProduto.categorias
    join produto in BDProduto.produtos on categoria.IdCategoria equals produto.IdCategoria into ljProduto
    from lProduto in ljProduto.DefaultIfEmpty()
    select new
    {
        IDCategoria = categoria.IdCategoria,
        Categoria = categoria.Categoria,
        IDProduto = categoria.IdProduto,
        Produto = lProduto == null ? "(Inexistente)" : lProduto.Produto
    };

foreach (var item in lst)
{
    Console.WriteLine("IDCategoria: {0}, Categoria: {1}, IDProduto: {2}, Produto: {3}",
                      item.IDCategoria, item.Categoria, item.IDProduto, item.Produto);
}

Comment: Toby, o seu código funcionou, mas IdProduto não aparece resultado, retorna sempre 0 (zero). Ele faz parte de Produto, só a propriedade IdCategoria que faz parte de Produto e Categoria.
Comment: @KellySoares, Neste caso você precisa fazer com IDProduto o mesmo que fez com Produto, verifique se o objeto é nulo antes de tentar acessar produto.IdProduto

Erro com LEFT JOIN em LINQ


How can I add a SQL result of a PHP statement (fromMySQL) in an existing HTML file

Question: I have an html file that contains a table with table rows

       <select id="so"></select>

I have a PHP that selects from mySQL DB and returns username
if ($results->num_rows > 0) {
    // output data of each row
    while($row = $results->fetch_assoc()) {
        $name=$row["first_name"];
        echo "<option>
                 $name
              </option>";
    }
} else {
    echo "0 results";
}

I am trying to incorporate the result of the php into my index.html file within the table so that the option shows up in the table
How can I get the data from PHP into an already built html table row?
Any help would be appreciated.
Comment: You can either place the results into an object you can echo out in the middle of your table code or use something like AJAX to retrieve the data and place the data into your table using JavaScript.
Comment: If you want to add content, after the html page is already loaded by your visitor, you only can do that with an asynchrone javascript call (ajax).  Please provide some more code and explanation about what you want.
Answer: for this work you should use ajax to load data in html file ...
you can do it with javascript :
create a function for load your php file :
function loadAjax(address,elementId) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
     document.getElementById(elementId).innerHTML = xhttp.responseText;
    }
  }
  xhttp.open("GET", address, true);
  xhttp.send();
}

after create it you can use it when you want (for example after load of page). you should pass address of your php file and id of html element that you want the answer load into it .
for more learn :
http://www.w3schools.com/ajax/
Comment: Why should the OP try this? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. It should include, if possible, an example of the code to be used.
Answer: There are couple of methods that can be used here. If the HTML and PHP are in the same file you could do this:
<?php
if ($results->num_rows > 0) {
    $options = ''; // declare the variable to hold the options
    // output data of each row
    while($row = $results->fetch_assoc()) {
        $name=$row["first_name"];
        $options .= "<option>$name</option>"; // add the options to the variable
    }
} else {
    $options = "0 results";
}
?>

And then add the $options to the HTML:

           <select id="so">
               <?php echo $options; ?>
           </select>

Another option, though not as neat, is to embed the PHP in the HTML:

           <select id="so">
    <?php
    if ($results->num_rows > 0) {
        // output data of each row
        while($row = $results->fetch_assoc()) {
            $name=$row["first_name"];
            echo "<option>
                     $name
                  </option>";
        }
    } else {
        echo "0 results";
    }
    ?>

           </select>

Yet another option would be to use AJAX to call the PHP from the HTML page and return the results to the right location. For instance, if you wanted to use jQuery you could follow a tutorial to learn the basics and then apply that to your code.
Comment: Why he should mix HTML and PHP, if I is not necessary ?
Comment: He doesn't have to @PrafullaKumarSahu. I have included an AJAX tutorial that he might use to learn AJAX methods and then apply to their situation. The upshot is that there is more than one method to accomplish what the OP is asking.
Comment: Is it not better to use PDO and a class to get the job done ?
Comment: It is hard to determine exactly which API the OP is using to get the data and it is not always necessary to instantiate a class to get these things done.
Comment: I am not saying necessary , I am asking which is better, to use raw code snipers or class and objects ?
Comment: It is totally dependent upon the situation.
Comment: if it needs repetition , it is better to use class and functions and if for a single instance, we can use snippets , am I correct ?
Comment: Like I said, it is totally dependent on the situation. Where possible you should exercise whatever means needed to maintain the DRY (Don't Repeat Yourself) methodology.
Comment: I am still not getting any entries in the dropdown.
My PHP and Html are 2 separate files.
Comment: If they are two separate files you will have to use either AJAX *or* you can include the PHP file in the HTML if your server will interpret HTML as PHP.
Answer: Two way to get the job done:-
1)Use a class, that is you should, and using its object you can retrieve the data and use it on the webpage .
ex:-  see this class, it needs a lot of improvements and changes, but still can give you some idea . I am also trying to learn PDO well, not a PRO, but can be helpful to you.Comments on this class will help you get the idea .
2)Using AJAX, You can request for this data on loading the document or you can request it via get, post, request.. on any event.If you know ajax, you can use that class and ajax, or if you do not have an idea about AJAX, you can get a lot of resources to learn ajax. after this if you need my assistant, I will try to help you.
Comment: Why should the OP try this? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. It should include, if possible, an example of the code to be used.
Comment: Visit the gist code I have asked to visit, the class contains some comments on it.
Comment: You should post code here, so that it is preserved for future visitors to SO.
Comment: If code is too much lengthy is it still recommendable to post here ?
Comment: Probably not, but if the OP and other visitors do not have Git access they will not be able to view your code.
Comment: I was not having git access, just learned to use it as I feel , it is good for programmers, they will also feel the same, I guess.
Comment: That will not always be the case.
Comment: may be, but what you will suggest , programmers should learn to use it or totally no need of this .
Comment: Not everyone who posts a question is a programmer or will version their code or want to learn how to use Git. We cannot and should not try to force them to.
Comment: if some is coding, I should consider him as user or coder ?
Comment: If you read the tons of PHP posts on this site you will read a great number of them that begin with *"I am not a coder or programmer,  but...."*


Redundant NFS on Amazon EC2

Question: I'm interested in building two fault tolerant/redundant NFS servers with failover at Amazon EC2. I'm familiar with tools/technologies like DRBD, Heartbeat, etc. Does Amazon provide any specific way of achieving this through their platform?
A suitable example might be that files are kept on a separate, redundant EBS -- if a failure occurs, a new instance is automatically launched from a pre-built AMI, the EBS volume is mounted, and the IP address is transitioned seamlessly.
Is this possible? Are there better platforms than Amazon? Can you give me a broad idea of the underlying architecture we're talking about to pull this off?
Answer: On AWS, using GlusterFS with an Elastic Load Balancer and auto scaling EC2 instances should achieve what you want. I can't comment about any other IaaS.
Amazon does provide some of what you need to achieve your objective - and allows you to implement the rest.
Amazon's EC2 servers are essentially VPSes - you can setup Heartbeat/Corosync/Pacemaker, etc on them (although last time I checked, you cannot use broadcast on their network - you can use unicast though - udpu).
You mention two ideas which Amazon addresses (somewhat) separately: fault tolerance and redundancy.
There is no built in mechanism for redundancy on EC2, although depending on what you are looking for, there are some ways to achieve it.

Theoretically, S3 is designed with multiple layers of redudancy and "designed to provide 99.999999999% durability of objects over a given year". Their SLA is for 99.9% availability per year. If you want to go that route for static files, you can mount an S3 bucket using s3fuse as a local file system. This is fairly slow however, and not really advisable for most purposes (code, databases, server software, etc).
EBS snapshots will provide you with a compressed, differential point-in-time image of your EBS volume. These are great as a backup - and you can launch new instances from a snapshot - they are not, however true redundancy.
For any solution of actual redundancy, you must set it up yourself. One approach designed for this problem is GlusterFS. You can setup your bricks as distributed, replicated, or both, and data will be spread across the system - it is resilient to the removal of individual nodes, and they have a pre-built AMI that you can launch multiple instances from to build a cluster.

Fault tolerance, on the other hand, is better provided for by the Amazon platform:

The EC2 network offers multiple regions and availability zones - which (theoretically) provide isolated and/or geographically separated data centres to avoid single points of failure
Amazon offers monitoring (Cloudwatch) of a variety of instance metrics (CPU, network, disk I/O, etc), as well as custom metrics. These can be used as a trigger for launching new instances from a pre-built AMI, a process called 'Auto scaling'.
EC2 has Elastic IP addresses - these are public IP addresses that can be reserved and quickly remapped to another instance on demand, allowing you to avoid the delays of DNS propagation when an instance goes down.
Finally, Amazon has Elastic Load balancers - these are supposed to be designed to avoid a single point of failure, and to scale with incoming traffic (they do not suffer from the same bandwidth limitations that a single instance setup as a load balancer would be subject to). ELBs are able to monitor the 'health' of the back end instances, and work with auto scaling to maintain an appropriate number of instances.

In addition to the above, you can pass custom parameters to your newly launched instances, or retrieve information about your currently running instances fairly easily - which may allow you to script some of the setup (and, of course, AWS does have an API that will let you script all the actions they offer - including remapping an elastic IP address, launching new instances, detaching/attaching EBS volumes, etc).
You described 'files are kept on a separate, redundant EBS...[which is then] mounted'. Firstly, on EC2, an EBS volume can only be attached to one instance at a time (so to copy data to it, the EBS volume would need to be attached). It is up to you to maintain redundancy (you can setup RAID arrays of EBS devices, or do pretty much anything else). The problem though, is that sometimes EBS volumes are not detached when an instance actually crashes - you can force detach them though (which has a better, but not perfect success rate), and you can snapshot a EBS volume, even in use (which you could then create a new EBS volume from and launch an AMI using). It is better (lower time to recover, more flexible, etc) though, to maintain replicas of your data across multiple instances, as opposed to across multiple EBS volumes on the same instance.
Comment: Not too familiar with S3 so excuse my ignorance but I'm curious: If s3 is so popular with fast website caching then why would `s3fuse` be slow?
Comment: a) It's usually better to use CloudFront as a CDN. b) There are a number of problems with S3 as a file system i) you have to change the full file - you can't append or change one byte, etc - which in itself rules out most uses. ii) It is 'eventually consistent' - you can write something, and even if confirmed, if you read it back right away, you may not get the expected result iii) lower throughput than EBS (typically about 50% max) iv) higher latency than EBS v) less flexible (permissions, quotas, etc). These aren't issues when serving a remote user, but are for a local file system.
Comment: I believe S3 guarantees 11 nines of durability, not availability. Your files may at times be unavailable but they're exceedingly unlikely to be permanently lost.
Comment: @ceejayoz: You are absolutely right. It is 99.9% availability and 11 nines of durability. Thanks. Fixed.
Answer: Another option is to use Zadara Storage, that is an NFS "as a service".
Because it is a service you don't need to manage the NFS server stack, and it is HA by default.
You don't even need to pay for the NFS server instances.
You can connect all the EC2 machines to your shares using standard NFS.
Disclosure: I'm with Zadara Storage.
Comment: "You don't even need to pay for the NFS server instances" is a pretty silly thing to say. You pay for the service, which pays for the instances, right?

Redundant NFS on Amazon EC2


Notifying an instance as down using a ServiceCache in Curator

Question: The documentation for Curator (http://curator.apache.org/curator-x-discovery/index.html) says:
If a particular instance has an I/O error, etc. you should call ServiceProvider.noteError() passing in the instance.
I am using a ServiceCache to get my instances, rather than a ServiceProvider (see Using selection strategies with a cache in Curator).
Where can I find the noteError() method here? I can't find it on the cache object
Comment: It turns out I gave you misleading information and you may not need to directly use a service cache at all. See my other answer here: https://stackoverflow.com/a/57059811/2048051
Answer: There is no noteError() on a ServiceCache, however as @Randgalt notes (https://stackoverflow.com/a/57059811/2048051) the best way is to not use a ServiceCache but rather just use ServiceProvider, because in the background that uses a cache anyway, and it has the noteError() method available.
https://issues.apache.org/jira/browse/CURATOR-531 has been raised to make the documentation clearer


Django Staticfiles não encontrado css não carrega

Question: Estou desenvolvendo uma aplicação django, está tudo rodando perfeitamente, mas o arquivo estático não está sendo renderizado no no meu templete.
Fiz as configurações no 'settings' mas mesmo assim não funciona. abaixo está como coloquei o as configurações no settings como puxei o arquivo estático no templete.
Configurações no settings:
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    'static',
]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Como estou puxando no template:
{% load static %}

<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{% static 'style.css' %}">
    <title>{% block title %}{% endblock %}</title>

Esse é o erro que o terminal retorna:
[07/Jan/2021 20:07:37] "GET / HTTP/1.1" 200 576
[WinError 3] O sistema não pode encontrar o caminho especificado: 'C:\\Users\\rodri\\OneDrive\\Documentos\\PYTHON\\DJANGO\\projeto_final\\clientes_admin\\staticfiles/style.css'
[07/Jan/2021 20:07:37] "GET /static/style.css HTTP/1.1" 404 13

Answer: Rodrigo, escreva o caminho completo pra pasta que contém o arquivo estático:
STATICFILES_DIRS = [

    "/home/projeto/app/static",

]

e verifica também se nos INSTALLED_APPS está mencionado 'django.contrib.staticfiles',
Answer: No settings.py  tente usar essas configurações:
Primeiro Passo:
DEBUG = True # caso estiver False  o projeto esta em modo de produção

ALLOWED_HOSTS = [] # caso esteja False adicione na lista ["*"]

caso essas indicações estiverem Okay!
Segundo passo:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'seuApp,  #adicione a tua aplicação, não o nome do projeto.

Caso estiver tudo certo prossiga :
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["templates"],# defina essa orientação ao templates.
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Se estiver certo passe para próxima indicação:
No final, Quando é criado um projeto  na ultima linha fica assim:
STATIC_URL = '/static/' #usado durante o desenvolvimento.
#adicione
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

dentro do app crie a pasta : static, dentro desta pasta ponha os css e htmls
no html
{% load static %}

<link rel="stylesheet" href="{% static 'style.css' %}">

a variavel DEBUG  como False o Django não ira carregar arquivos html e css para ele carregar em modo de produção tera que usar api.