Como mudar foto da capa

Question: Como atualizar foto dessa capa a partir de meu computador com javascript, button input type=" file" ou com nodejs.

Segue o código:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <button style="font-size:24px">Atualizar foto de capa </button>

    <input type="file" name="">

Página teste

Comment: Alterar a imagem em tempo real?
Answer: Para atualizar a imagem em tempo real você pode tentar assim:

  function showThumbnail(filess) {
    var url = filess.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (filess.files && filess.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
      var reader = new FileReader();
        reader.onload = function (e) {
          document.getElementById('fotoCapa').setAttribute('src', e.target.result);
      }
      reader.readAsDataURL(filess.files[0]);
    }
  }
<input type="file" id="upload" onchange="showThumbnail(this);"/>

Se quiser salvar essa imagem pode utilizar ajax ou enviar como um formulário.
A respeito do ajax em JavaScript puro esse site possui um exemplo completo: SITE
Comment: É isso mesmo, só que teria de ser sem jquery. Precisaria que fosse em javascript puro.

E como faz para salvar em ajax para ficar gravado na página, há algum site, tutorial para ensinar? Obrigado desde já!
Comment: @Intube editei minha resposta para javascript puro

Como mudar foto da capa


Fatal error when restoring PostGreSQL DB from dump: undefined function system_run_automated_cron

Question: I'm trying to simply install Drupal 7.8 on PostGreSQL 9.1, backup the DB, and then restore from it ... nothing else, just to test out backing up my sites, but the site will not come back up!
Here are my steps:

install Drupal & get through configuration to the "you're done" screen
dump the DB (pg_dump > file.sql)
drop the DB (dropdb)
create a new DB with the same info (createdb)
restore the DB (psql < file.sql)

No steps in between (except when I've tried to avoid the error by putting the site into maintenance mode and/or clear the cache). No adding content, no nuthin'!
But when I access my site, I get the following error message:
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [function.unserialize]: Error at offset 0 of 1009 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [function.unserialize]: Error at offset 0 of 38585 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Warning:  Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 185
[22-Nov-2011 17:07:44] PHP Warning:  array_keys() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 89
[22-Nov-2011 17:07:44] PHP Notice:  unserialize() [function.unserialize]: Error at offset 0 of 38585 bytes in /Applications/MAMP/htdocs/drupal-postgres/includes/cache.inc on line 405
[22-Nov-2011 17:07:44] PHP Warning:  Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 185
[22-Nov-2011 17:07:44] PHP Warning:  array_keys() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/drupal-postgres/includes/module.inc on line 89
[22-Nov-2011 17:07:44] PHP Fatal error:  Call to undefined function system_run_automated_cron() in /Applications/MAMP/htdocs/drupal-postgres/includes/common.inc on line 2573

Anyone have any thoughts? This CAN'T be this hard!
Thanks a million!
Comment: I've just tried to do the same thing using MySQL and it worked fine! Any thoughts, PostGres folks?
Answer: After looking into this a bunch, I just decided to move the DB to MySQL. I hated to have to do it, but support for sql-dump in drush is limited to MySQL, and Backup and Migrate is as well. Kills me to have to run two DB servers (all my other applications use PostGres), but desperate times call for desperate measures.
I would hope some day that these modules would support PostGres. As Drupal supports both, so should the modules.
Some notes to others when using Backup and Migrate and Backup and Migrate Files

File ownership travels with the files, so I've had to "chown apache" files that get moved
It looks like the Temporary Directory setting is stored as a machine-specific folder, so be sure to update this on the destination machine
Clear the cache on the destination machine. I had a case where a tpl.php file wasn't being used until I did this.
Answer: Check this up: http://drupal.org/node/926636
I have got almost the same errors while migrating to a different server as well as upgrading from postgres 8.4 to 9.0. Altering the bytea setting does the job so far!
Answer: You can also changed settings in the postgresql.conf so you don't have to altering the table each time you make a backup
bytea_output = 'escape'     # hex, escape
Answer: Shot in the dark here, but I would take your backup a different way.  You have two options:
One is to the Backup and Migrate module.  I would set up the profile to ensure that tables are locked and drop into maintenance mode during backup to ensure that it is consistent.  I would also exclude all of the content from the cache tables.  While you are at it, set up a backup schedule.
The other is to use drush and it's sql-dump command.  The author mentions that the proper options are used to ensure a backup, and you can also exclude table contents.
You could also try restoring your backup file and manually doing a TRUNCATE TABLE or DELETE FROM on all of the cache tables.


Como pegar a string do JSon sem saber o que tem nele?

Question: Eu uso o jo.getString("nome") para pegar o valor de um arquivo JSon, tem como eu pegar este nome sem ter que colocar o "nome" dentro do getString?
Comment: Qual o contexto da pergunta? qual a linguagem? você pode criar um exemplo **verificável**?
Answer: Bom acho que isso não é possível pelo fato do jSON trabalhar com chave e valor ou seja
{"nome":"Alessandro"} para acessar o valor 'Alessandro' você deve acessar pela sua key ou chave que no caso é o "nome" e isso no android você usa o getString("nome") se for uma string que você desejar obter.
Comment: É possível sim.


Maclaurin Series of $1-x+\frac{x^2}{2!}-\frac{x^3}{3!}\ldots$

Question: I was asked to find the sum of the following series:
\begin{equation}1-\ln 3 + \frac{(\ln 3)^2}{2!} - \frac{(\ln 3)^3}{3!}\ldots\end{equation}
I generalized it to the power series:
\begin{equation} \sum_{n=1}^\infty (-1)^n\frac{x^n}{n!}\end{equation}
But I don't think I can compute the sum of this series. So then I tried to do this:
\begin{align*}1-\ln x &= 1-(x-\frac{x^2}{2!}+\frac{x^3}{3!}\ldots)\\
&=1-x+\frac{x^2}{2!}-\frac{x^3}{3!}\ldots\end{align*}
Which seemed to be in the right shape, so I thought $1-\ln(1+\ln3)$ was my answer, but it obviously wasn't hence the question. Can anyone give me some hints on whether I shold be comparing it to another series, or if I misused The Constant Multiple Law for Series?
Comment: I think you need to double-check your series expansion for the natural log, that factorial doesn't seem right. I would also suggest you check out the series expansion for $e^x.$
Comment: I think it's the series expansion of $$e^{-x}$$ and not of log x.
Comment: Do you know the series if ever minus ($-$) was a plus?
Comment: @SandipanSamanta Yeah, I realized now. A new thing to add to my notes though!
Comment: @StephenDonovan tysm, I'm still struggling with infinite series.
Answer: Here is a hint: do you know the series for the exponential? For $x\in\mathbb{R}$,
$$
e^x = \sum_{n=0}^\infty a_n x^n
$$
where $a_n=??$
Then, try to see how you can use this for your problem.

As a side note, regarding your attempt: the power series for $\log$ does not have any factorial: $\log (1+x) = \sum_{n=1}^\infty\frac{(-1)^{n-1}x^n}{n}$, for $|x|<1$.
Comment: Just as a passing comment, this series isn't only used for real $x$ as stated in the answer, but also for complex numbers and matrices. (in fact I believe this is the definition of the exponential of a matrix)
Comment: @StephenDonovan Good point regarding complex numbers. As for the definition: it sometimes is used as the defintiion, sometimes some other definition (as solution of a differential equation, as a reciprocal, etc.) is used, and the equivalence of defintiions then has to be proven.
Comment: This is the series for $\log(1+x)$.
Comment: @ShubhamJohri Thanks! Somehow I missed that obvious typo (oops...). Fixed.
Comment: Thanks, I still get mixed up with all of the factorials that are floating around in my brain.


Question about practice

Question: I wanted to ask this question for a long time now and finally doing it. Sometimes when I practice on guitar, my hands and fingers just feel odd. It feels like my fingers does not want to play, I do silly mistakes and play badly, but sometimes, I convert my practice to masterpiece shreds and play my best, with the blasting speed and good rhythm.
Any advice? Is it me or do you people feel like that too?
Comment: That definitely happens to me also. That's why I try to practice above the level I'm gigging at. If I have a bad day at a gig, I want to still be playing stuff all right because it's easier than my absolute best.
Comment: Isn't it strange? Haven't found any solution yet
Comment: Please consider more informative subject
Answer: I think it's because we're human. Humans are fallible - proved by many every day! If we were machines, we'd do the same thing at the same level each time. But we're not. We get tired, we are in 'the wrong mood', we have other things that seem to take precedence, etc., etc.
If the practice isn't working, then why continue? There'll always be a better time later. There's a need to establish a good practice regime, but also a good time for this to happen. May be first thing in the morning, when one is fresh, or last thing at night, when all the worries of the day have been sorted (or ignored). Being in the right frame of mind is so important, too. So, try many different times - but also different rooms/venues.
Answer: That used to happen to me quite a bit when I took a sabbatical from my day job and started playing guitar all day long. I can only attribute my experience to fatigue and over training.  I could feel that my fingers and hands were stiffening up.
What you are experiencing could very well be related to how much muscle fatigue your hands and fingers have been subjected to prior to the time you practice.  For example if you use your fretting hand all day doing other task such as typing, driving, holding things (especially anything with more weight than a pencil) or texting - it's quite possible that by the end of the day your hands are just tired.
Also, if you practice too much without rest, you can stress out the muscles and they will protest by responding more sluggishly (even the entire next day).  Tired muscles don't respond as efficiently as well rested ones do.
Certain mineral deficiencies can also contribute to muscle cramping and fatigue.  I try to eat a banana or avocado every day to maintain potassium levels in my body and take a magnesium supplement.
Good hydration is very important.  If you are using any type of diuretic substance (caffeine, energy drinks, nasal decongestants, prescription meds) all of your muscles (including the ones in your hands) will have a greater tendency to tighten up or cramp.  Be sure you drink plenty of water all the time.
It is also a good idea to start every practice session with some gentle warm up and stretching exercises.  End each practice session with some more stretching which will help dissipate any lactic acid build up in muscles that have been subjected to higher intensity use (such as when engaging in masterpiece shreds at blasting speed).
If your body is trying to tell you that it is tired, it's best to listen.  If you find that your fingers just don't seem to want to work like they should, that might be a sign that you need to rest.  And perhaps add the proper nutrients and hydration.
Hopefully if you follow some of my suggestions above - all of your practice sessions will find you playing masterpiece shreds with few mistakes.
Remember to keep it fun!
Comment: @NeilMeyer - new user apparently accepted the answer but did not realize he could also upvote it.  Looks like some folks have discovered the nuggets of wisdom in the answer by now and upvoted.  Thanks for yours if you were one of them.
Answer: This odd sensation could simply just be a bunch of muscles that otherwise do not get a lot of exercise may start to begin developing now. You develop muscle with in the fine motor reflexes that do not otherwise develop much when a person does not play any dexterity based instrument.
I would only worry about it if you start experiencing pain but until then consider that your practicing routine is developing muscles.

Question about practice


When does a topological group embed topologically in its group of homeomorphisms?

Question: Let $X$ be a topological group. $X$ acts freely on itself by left multiplication; this gives us an injective group homomorphism $\Phi: X\rightarrow \operatorname{Homeo} X$. Under what conditions is $\Phi$ also a homeomorphism to its image, in the compact-open topology on $\operatorname{Homeo} X$?
(Is this always true? True if $X$ is locally compact? Is it at least true if $X$ is a Lie group? Etc. Ideally, what's the most general condition and what's the argument?)
Comment: It's obviously true if $X$ is compact Hausdorff. I would venture to say it's true when $X$ is locally compact Hausdorff.
Comment: Suppose $X$ is locally compact and locally connected, then by a theorem of Arens (see this answer http://mathoverflow.net/questions/58690/compact-open-topology-on-mathrmhomeox/61430#61430 by Johannes Ebert) the homeomorphisms of $X$ equipped with the compact open topology form a topological group.

Under these conditions, since $\Phi$ is a group homomorphism between topological groups, we only need check openness onto its image on a neighborhood of $1$
Answer: The map $\Phi:G\to C(G,G)$ is always continuous. Indeed, if $K,U$ are compact and open in $G$ respectively, and $g\in\Phi^{-1}([K,U])$, where $[K,U]$ is the set of all continuous maps $f:G\to G$ such that $f(K)\subset U$, then for any $k\in K$ we can choose open nighborhoods $V_k(g)$ and $V(k)$ of $g$ and $k$ respectively such that $V_k(g)\cdot V(k)\subset U$. We then extract a finite open cover $V(k_1),\dots,V(k_n)$ of $K$, and set $$V=\bigcap_{i=1}^n V_{k_i}(g)$$
This is an open neighborhood of $g$, and for any $g'\in V$, $g'K\subset U$, i.e. $V\subset\Phi^{-1}([K,U])$

Suppose $G$ is a locally compact and locally connected topological group, so that the homeomorphisms of $G$ equipped with the compact open topology form a topological group. By a homogeneity argument using the fact that $\mathrm{Homeo}(G)$ is a topological group, it is enough to show that $\Phi$ is an open mapping at $1$.
Let $V$ be an open neighborhood of $1$ in $G$. It is enough to show that there are a compact set $K$ and an open set $U$ such that
$$\Phi(1)=\mathrm{id}_G\in\Phi(G)\cap[K,U]\subset\Phi(V)$$
Just choose $U$ and $K$ such that $1\in K\subset U$ and $UU^{-1}\subset V$. Then $\Phi(G)\cap[K,U]$ is open in the induced topology on $\Phi(G)$, and if $\Phi(g)\in\Phi(G)\cap[K,U]$ for some $g\in G$, then $gK\subset U$ so that $g\in UK^{-1}\subset V$.


Heteroscedasticity in Regression

Question: I have seen a tutorial video where a person is advising to check for heteroscedasticity in a regression by plotting the IV against the DV. Is this a problem? Are there any drawbacks with this approach?
I know that I was always told to plot the standardised residual against the predicted values.
Comment: You can use either to see heteroscedasticity; see my answer here: [What does having "constant variance" in a linear regression model mean?](http://stats.stackexchange.com/a/52107/7290)
Answer: If there is one and only one predictor or covariate or independent variable $x$ then a scatter plot of the response or dependent variable $y$ versus $x$ is a good way of checking the relationship in several respects, including but not only

whether the relationship between the variables is approximately linear as is needed for linear regression $y = b_0 + b_1 x$ to make sense.
whether there are any of the following which can complicate analysis: skewness or long-tailed distribution of either variable; heteroscedasticity of variation around a putative regression line; gaps or granularity in the distribution; possible univariate or bivariate outliers.

In each case other plots may be even better, including plots focused directly on either univariate distribution or plots based on residuals.
If there are two or more predictors then it is unlikely that one plot can be used to show all aspects of behaviour. Usually it is better to plot residuals in a focused way. The most useful single plot can be a plot of residuals (vertical axis) versus fitted or predicted values (horizontal axis) which can always be drawn, regardless of how many predictors there are.
Note on terminology:

The terms dependent variable (sometimes DV) and independent variable (sometimes IV) remain widespread, despite repeated suggestions that they should be dropped in favour of others that are more evocative. Objections to those terms include: "dependence" and "independence" are already overloaded terms in probability and statistics; many beginning students have found it hard to remember the difference, to their own confusion and others'; the abbreviations DV and IV are respectively in common use as meaning "Deo volente" (God willing) and in specific econometric use as meaning "instrumental variable".
The terms against and versus divide the world. Some of us, including this writer, think of plotting what is on the vertical axis versus what is on the horizontal axis,
which can be justified as sanctioned by mathematical and physical tradition and logic. Others flip it round: for example, economists presumably have reasons for how they plot supply, demand and price.
Comment: @whuber One comment was more in jest than the other. In some economic circles the use of instrumental variables seems to be largely an act of faith, so there may be a more than tangential connection.
Comment: +1 If the economists are going to create ambiguous abbreviations, that's on them: the rest of the world shouldn't have to change theirs in response!  But I love the alternative meaning of "DV" and find it perfectly descriptive of the apparent behavior of many DVs in regressions, as well as the feelings one sometimes gets when trying to model their behavior. :-).
Answer: Plotting the IV against the DV is only a good check for heteroskedasticity in a simple linear regression.  In a multiple regression, heteroskedasticity refers to different variances of the residuals in any subgroup, which might be identifiable only with multiple IVs entered into the model
Comment: I would like to point to a possible ambiguity in this characterization of heteroscedasticity: the variance of the response variable, when broken down by subgroups, will almost *always* appear to be heteroscedastic in a multiple regression.  You must be referring to the variances *after controlling for all the variables*--that is, the residual variances (even though you haven't mentioned residuals at all). But then what is "identifiable only with multiple IVs" supposed to mean?

Heteroscedasticity in Regression


R e1071 tune plot does not give me the best gamma?

Question: I am using the R e1071 library for the SVM (Support Vector Machine) algorithm.
And I used tune to find out the best Cost and gamma parameters.
Though the plot doesn't seem to provide the actual best prediction.
Here is some details:
<code>gammalist <- c(0.005,0.01,0.015,0.02,0.025,0.03,0.035,0.04,0.045,0.05)
obj <- tune(svm, Class~., data = trainData, ranges = list(gamma = gammalist, cost = 2^(2:4)), tunecontrol = tune.control(sampling = "fix") )
plot(obj)
</code>
Here is the plot obtained:

The plot leads me to believe 0.02 is roundabout the best gamma.
But I actually tested manually several others and find better results for 0.042.
On a 200 sample, I get 23 errors with gamma=0.042, and 26 errors with gamma=0.02.
How do you explain this?
Answer: When you say "better results" and provide the different errors you got, is that evaluated in-sample or out-of-sample?
SVM tuning will attempt to give you the best tuning parameters for out-of-sample prediction.  But for in-sample "performance," higher gamma and higher cost will always do "better."  I put 'performance' and 'better' in quotes here, b/c higher values of gamma and cost will not actually give you a better estimate of the underlying mapping between independent and outcome variables, but will "overfit" the training data.  Keep in mind, SVM is capable of arbitrary complexity, so if you let it, it will perfectly fit your data.  (That's assuming there are no instances of identical X's producing different Y's, but that almost surely won't happen with continuous data.)  When you fit so tightly, if actually harms predictive ability, b/c there is a lot of spurious complexity in the prediction function, so my guess is that gamma=0.02 will outperform out-of-sample, while gamma=0.042 will dominate in-sample. If you're interested in prediction, go with 0.02. There aren't many reasons to go with in-sample performance, but there are instances when you want to be a little liberal with the cost and gamma parameters.  (For example, if you're using SVM-regression to produce a residual which has purged variation related to all of the explanatory variables, a little over-fitting can be beneficial.)  But in most cases, go with the out-of-sample prediction accuracy.
However, if you evaluated this out-of-sample and found that the higher gamma did better, then I must say that I'm surprised.  It's theoretically possible for the performance manifold (the 3-d surface of out-of-sample MSE, cost and gamma) to be very spike-y, which can lead to poor tuning outcomes, but looking at the plot above, it looks pretty well-behaved.
Hope that helps!


How do I prove a claim on a recursive formula?

Question: I have to prove that $F(n) \le n^2 $  for n $\ge$ 1
with $i\le 2: F(i)= i$
and for $i>2, F(i) = i + 0.5*F(i-1) +0.5*F(i-2) $
After doing some research, I am pretty confident that I have to use induction, I know how to prove my base cases and what IH to use but I get stuck at the last part of the proof. This is how far I've gotten:
$\text{Base case: }\; F(1) = 1 $ and $1 \le 1^2$
$\text{Base case: }\; F(2) = 2 $ and $2 \le 2^2$
$IH: F(i)\le i^2$ holds and $F(i-1)\le (i-1)^2$ holds for $n\ge1$
To show: $F(i+1)\le(i+1)^2$
$F(i+1) = (i+1) + 0.5*F(i) + 0.5*F(i-1)$
By IH: $0.5*F(i) + 0.5*F(i-1) \le 0.5*(i^2 + (i-1)^2)$
My question now is, what do I do with the i+1 since I have no assumptions about this and I also do not know where to get them. And how do I get to what I have now on the right hand side to $(i+1)^2$
Comment: You just need to press on. Expanding the expression you have gives $i^2-i+\frac{1}{2}$. Adding $i+1$ gives $i^2+\frac{3}{2}<(i+1)^2$.
Answer: You are almost done.
Inductive step. Suppose the claim holds for $n$ and $n-1$. Let us prove it for $n+1$.
You have
$$F(n+1)=n+1+\frac12(F(n)+F(n-1))\le n+1+\frac12(n^2+(n-1)^2)$$
by inductive hypotesis. A few calculations yield:
$$F(n-1)\le n^2+\frac32<n^2+2n+1=(n+1)^2$$


Ajax call results in 404

Question: I'm porting an applet (tested standalone) to embedd it into a Drupal site.
It includes some Ajax processes, which work fine in the original version.
Once adapted for Drupal, they all result in 404.
Below is a simplified excerpt of how I'm working.
myModule.module
function myModule_menu() {
  return [
    'myModule-ajax' => [
      'page callback'     => '_myModule_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

// ...

function _myModule_ajax_handle() {
  // here is a deliberately simplified return
  return '{"test": "Ajax result sample"}';
}

JS part
(function($) {

// Set common $.ajax properties.
$.ajaxSetup({
  url: 'myModule-ajax',
  //method: 'POST',
  dataType: 'json',
  error: function(jqXHR, status, error) {
    console.log(status + ': ', error);
  }
});

getSqlObj('Depts'); // -> sqlDepts

// ...

function getSqlObj(objName) {
  $.ajax({
    data: {
      ajax: 'get' + objName
    },
    success: function(response) {
      // ...
    }
  })
}

})(jQuery);

With Firefox devtools I can see that the right url was called, in this case:
myModule-ajax?ajax=getDepts
but the status is 404, and the returned data is the fully rendered current page, with a message replacing the current node content:

Requested page "/mySite/fr/myModule-ajax?ajax=getDepts" not found

So I wonder not only why I get a 404 status, but also why I get this data returned.
NOTE: among a number of tries with differently expresses urls, I noticed another weirdness: at the time of url affectation (in $.ajaxSetup() above), Drupal.settings.basePath is undefined (in fact, Drupal.settings exists but is empty).
In the other hand, it contains all expected data when examined through the console just after the fail.
Comment: Alternatively you can use [drupal_json_output()](https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_json_output/7.x) instead of returning a json formatted string. Is this ajax suppose to be post or get?
Comment: @DMAC Thanks for your interest to my issue. As commented in the code above, my current return is a (temporary) simplification, for the 1st tests. But I agree that I should use `drupal_json_output()` in the real work. Since you cited it, I'm pretty interested about `POST` vs `GET` (`POST` is what I'll actually need, because some data to send may be of some weight). But adding `method: POST` seems to be ignored: always results in a `GET` in the Drupal context! I didn't understand that, and didn't find more information about that. So if you can share any advice about it, thanks in advance.
Answer: A post request is when you are sending information to the server and returning  response data, get is just simply just grabbing data. This is an example of a post AJAX request I have working in Drupal, stripped down. It is assuming data is being passed from the ajax call into PHP then is returned back to JS.
Create your AJAX path with hook_menu() in your custom module
function hook_menu(){
  $items = array();

  $items['my_ajax_path'] = array(
    'title'             => 'My Ajax path that does stuff',
    'page callback'     => 'myPageCallBack',
    'type'              => MENU_CALLBACK,
  );

  return $items;
}

Create your page callback for your menu defined in hook_menu() in custom module
function myPageCallBack(){
 if(isset($_POST['myData'])){
   $postData = $_POST['myData']
   return drupal_json_output($postData);
 }
}

AJAX Call in your custom JS file (location is up to you but i find this is easy to maintain, you can add js to a page using drupal_add_js)
function call_AJAX(myVariable){
    jQuery.ajax({
      url: "/my_ajax_path?action=myPageCallBack",
      type: "POST",
      data: {myData: myVariable},
      dataType: "json",
      success: function(data){
            alert(data);
            if(data == ''){
                alert('There was an error processing the form. Please try again later.');
                return;
            }
        },
        error: function(xhr, status, error){
                console.log(xhr);
                console.log(xhr.status);
        },
    });
}

I stripped this out of a working example quickly and didn't test it outside of my working environment as i'm actually leaving work right now, but using the above code i can make post ajax requests no issue. Let me know if this works for you!
Comment: Thanks for this answer. But, no offense, it doesn't help much, and it's my bad, because I indeed was too short in the explanation of my issue. In fact I'm pretty used to work with Ajax (both through `GET` or `POST`) _outside of Drupal_. More over, for my first try with Drupal, my real code (not simplified as in my OP) looks pretty like your example. My current issue is that for some reason I'm facing a behaviour that don't match my experience: the unexpected (and unexplained) 404, the fact that I got back a full rendered page. And to have noticed is that specifying `POST` gave me a `GET`!
Comment: Anyway, note: your answer helps me in the sense that it makes me reasonably sure of the way I used. Now the issue is clearly in "something else" (likely in either my global Drupal context or in the rest of my code). So I wonder where and what I could look at, in order to identify what's wrong...
Comment: What exactly is your requirement? I am having a hard time understanding what you are asking?
Comment: What I'm asking? TL;DR; what my title said: why am I getting 404 on Ajax call. But as I precised in my previous comment above, after reading your answer I got pretty sure it didn't come from an erroneous way of doing things, but likely from "something else". So I continued doing some tests, and you can read the following and the end of the story at my new post: http://drupal.stackexchange.com/questions/224886/route-not-registered-likely-hook-menu-not-called.

Ajax call results in 404


AngularJS: clean dom elements from include

Question: I need to clean span elements out of an HTML include, going by this example. However it just returns the first plain text string in the include and drops everything else (the include has over a dozen href links that I want to preserve).
  $scope.footermenu = function () {
      $http.get('includes/mainmenu.html').success(function(data) {
        var menusrc = data;
        $(menusrc).find('span').remove();
        var nospans = $(menusrc).html();
        return nospans;
      });
    };
});

Answer: I could not get replace() to work here in nearly 4-hours of trying every trick google could find, so I went back to the regex. I had forgotten that angular adds class="ng-scope" to every dom element under its purview (AFAICT), so I needed to stick that in my regex to get it working. Also note "msrc" is being pulled in from the dom, though this did not seem to make a material difference to the particular problem:
  $scope.footermenu = function () {
        var msrc = $('#menu').html();
        var nospans = function() {
          return msrc.replace(/(.*?)<\/span>/g,'');
        }
        var mcln = $('
').append( nospans() ).html();
        alert(mcln);
    };

A fair bit of clean-up needed and additional modifications to the footer code, but past that hurdle anyway. Thanks to @munsai for that rather crucial tip. It was pointed out elsewhere that msrc !== $(msrc), so this solution bypasses that particular issue (assuming that info is correct).


Incomprehensible lowering of VGG19's accuracy if data is preprocessed

Question: I'm using the VGG19 convolutional network for image recognition (to be specific, the keras implementation). I've downloaded the ILSVRC2012 validation dataset and the ground truth from here, to check if the accuracy of VGG19 matches my expectation. Note that the labeling of the linked ground truth is different from the default ground truth labeling provided by ImageNet.
Since VGG19 expects input of the shape (224, 224, 3), one has to choose a way of dealing with input which is not of square shape. I avoided naive resizing which violates the aspect ratio (because it might change the ground truth). What I did is the following:

Filter the validation dataset such that only images remain which satisfy 0.95 <= height / width <= 1.05 (i.e. which are nearly of square shape). Almost 4000 images fulfill this property.
resize those images to 224 × 224 and call this smaller dataset D.
a) Evaluate (Top 1 classification) VGG19 on D, which results in an accuracy of ~ 59.48%
b) Preprocess every image in D using keras.applications.vgg19.preprocess_input, call that new dataset P and evaluate (Top 1 classification) VGG19 on P, which results in an accuracy of ~ 52.46%

So now my two questions are:

Why is the performance of VGG19 significantly lower than ~ 75%, which is the Top 1 accuracy on the validation dataset the authors of VGG claim to achieve?
Why does preprocessing lower the accuracy even further?

Since D only contains the 4000 nearly square shaped images, a bias might explain the overall bad performance. To check this, I center-cropped every image from the validation dataset, resized it to 224 × 224 and repeated the evaluation on those – with similar results (~ 60% vs ~ 54%).

My setup: Keras 2.2.2, Tensorflow-GPU 1.10, Ubuntu 16.04
Comment: @AlexR. As you mentioned, I took the validation dataset, rescaled every image's smaller side to 256, took a central 224 × 224 crop and then evaluated VGG19 on those images. The result is 64.37%, which is still far from 75%.
Answer: I guess I found one error:
I loaded the validation images via OpenCV (cv2 module) by executing cv2.imread, which returns a Numpy array, where the color channel ordering is BGR. Using keras.applications.vgg19.preprocess_input on that Numpy array accidentally reverts the channel ordering back to RGB (although the target ordering is BGR) and then subtracts the mean BGR pixel [103.939, 116.779, 123.68].
After realizing that, I performed the following evaluation:

Center-crop each image of the validation dataset using a box of maximal size

Scale the cropped images to 224 × 224 using cv2.resize(..., interpolation = cv2.INTER_LANCZOS4)

a) Evaluate VGG19 on the non-centered batch -> accuracy of ~ 63.25%
b) Center the pixel color values of the batch by image_batch = np.subtract(image_batch, [103.939, 116.779, 123.68], dtype = np.float32) and evaluate VGG19 on that -> accuracy of ~ 70.21%

This is now way closer to the expected 75% accuracy. The gap might be credited to the way I evaluate VGG (single center crop vs multi-crop/dense evaluation an the paper) but I'd like to ask you guys:
Did I miss an additional preprocessing step?

A side note: It's worth writing
image_batch = np.subtract(image_batch, [103.939, 116.779, 123.68], dtype = np.float32)

instead of just
image_batch -= [103.939, 116.779, 123.68]

because the latter one results on my machine in a float64 array, which is some kind of overkill (in terms of size and GPU performance).


Como faço para que os elementos interno do ASIDE permaneçam horizontalmente?

Question: Como faço para que os elementos interno do ASIDE permanecerem horizontalmente na mesma linha, um ao lado do outro sem quebrar ao redimensionar o navegador.
CSS
aside{
  background-color: #222;
  margin-top: 10px;
  margin-left: 10px;
  width: 100%;
  max-width: 1200px;
  margin-bottom: 10px;
  box-sizing: border-box;

}
aside figure{
  float: left;
  margin-bottom: 20px;
  margin-right: 10px;
}

aside figure img{ /* redimensionar imagem */
    max-width: 300px;
    width: 100%;
}

HTML

Answer: Altere seu código CSS por:
aside{
  background-color: #222;
  margin-top: 10px;
  margin-left: 10px;
  width: 100%;
  max-width: 1200px;
  margin-bottom: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
}
aside figure{
  width: 25%; /*Para o caso de 4 colunas. Altere conforme a necessidade*/
  margin-bottom: 20px;
  margin-right: 10px;
}

aside figure img{ /* redimensionar imagem */
    max-width: 300px;
    width: 100%;
}

Comment: Funcionou perfeitamente! Muito obrigado.


Returned int always zero + how to use object from Main method in sub-method

Question: I am trying to write a simple Java program for school that does the following:
Gym Membership: "Write code that will input the customer's age and number of months, and print the monthly rate and total amount to be charged. Prompt the user for the appropriate input, and display a meaningful output message. Make sure that the months are greater than 0 and the age is greater than 0."
My problems are:

custMonths int is always getting returned as 0 and I don't know why.
I can't seem to find a way to loop back to the start of my selectAge method if the user gives bad input (negative number or zero).

Here is my Java code:
import java.util.*;

public class GymMembership {
public static void main (String[] args) {
    //create test customer (customer0) via the constructor
    GymMembership customer0 = new GymMembership(70, 12);
    customer0.selectAge(customer0.custAge);
    customer0.printCustomer();
    customer0.getMonthlyRate(customer0.ageNamed);

    //prompt user for two integer inputs to create customer1
    Scanner scnr = new Scanner(System.in);
    System.out.println("Enter customer age, then number of months for contract: ");
    GymMembership customer1 = new GymMembership(scnr.nextInt(), scnr.nextInt());
    customer1.selectAge(customer1.custAge);
    customer1.printCustomer();
}

//the constructor
GymMembership(int custAge, int custMonths) {
    this.custAge = custAge;
    this.custMonths = custMonths;
}
//instance variables
private int custAge;
private int custMonths;

int monthlyRate;
int childRate = 15;
int adultRate = 25;
int seniorRate = 20;

String ageNamed;
public String selectAge(int custAge) {
    Scanner x = new Scanner(System.in);
    int age = custAge;
    ageNamed = "badInput";
        do {
            if (age >= 1 && age <= 18) {
                ageNamed = "child";
            }
            else if (age >= 19 && age <= 64) {
                ageNamed = "adult";
            }
            else if (age > 64 && age <= 120) {
                ageNamed = "senior";
            }
            else {
                ageNamed = "badInput";
                System.out.println("Age must be a positive number between 1 and 120.");
                break;
            }
        } while(ageNamed.equals("badInput"));
    return ageNamed;
    }

public int getMonthlyRate(String ageNamed) {
    if (ageNamed.equalsIgnoreCase("child")) {
        monthlyRate = 15;
    } else if (ageNamed.equalsIgnoreCase("adult")) {
        monthlyRate = 25;
    } else {
        monthlyRate = 20;
    }
    return monthlyRate;
}

public void printCustomer() {
    if (ageNamed.equals("badInput") != true) {
        System.out.println("The customer is a/an " + ageNamed + " and is " + custAge + " years old.");
        System.out.println("The customer is signed up for a " + custMonths + " month contract.");
        System.out.println("The monthly rate is " + monthlyRate);
    }
    else {
        selectAge(customer1.custAge); //this is broken since I cannot access customer1 object from this "printCustomer" method.
        }
    }
}

I realize I am very likely making some bad beginners mistakes here as well, but am not quite sure what they are.
Comment: Please see edits to answer and ask if any questions
Comment: This was very helpful, thank you!! :)
Answer: You seem to be over-complicating things. Some issues here including

You've got user I/O within the GymMembership class where it doesn't belong. Get it out and into its own UI class or simply the main method.
This includes not using Scanner within GymMembership as you're creating more than one Scanner based on System.in, a dangerous thing to do. Leave that in main.
Get the input in main, and then use it to create your GymMembership object. Repeat as needed.
I/O validation for age and months should also be in main. Again GymMembership should concern itself with just simply holding the state and behaviors of the object.
Or I suppose you could give GymMembership a static boolean method that checks for valid age and months, and use that in the main method to tell if data entered is valid.
The selectAge method is completely unnecessary as you're setting the age in the GymMembership's constructor. Again most of that code should be in the I/O section (main).
This, selectAge(customer1.custAge); isn't valid or necessary. You're within the GymMembership class, the current object's age field is visible to you directly, use it.
Your getMonthlyRate(...) method is dangerous in that it requires that a separate unnecessary field be calculated and passed in as a String, and this String is completely unnecessary, and likely this is causing you problems. The class already knows the information needed to calculate the rate via the age and months fields -- get rid of the String parameter and use the class's own fields.

e.g.,  the GymMembership class could be as simple as something like:
public class GymMemb2 {
    private int age;
    private int months;

    public GymMemb2(int age, int months) {
        this.age = age;
        this.months = months;
    }

    public int getAge() {
        return age;
    }

    public int getMonths() {
        return months;
    }

    public double getMonthlyRate() {
        // calculations using age and months for monthly rate
        // return result
    }

    public String print() {
        String text = "age: " + age + ", months: " + months;
        // also add monthly rate info
        return text;
    }

}

Then in the main method, create the new Scanner(System.in) again, do this only once, and use it to get input. Within the main you'd use a while loop to keep looping until valid input has been entered, and then create your gym membership object(s). I think that the GymMembership class shouldn't have any println's within it but rather return Strings that may be printed by main if it desires.
Also at the end of main, close the Scanner by calling .close() on it. This should only be done with the program is completely done getting user input, since once closed it may not be reopened.
Comment: Thanks very much, @DontKnowMuchButGetterBetter ! I still can't seem to get int customerMonthlyRate to return anything but zero. Any idea why?
Comment: NM, another rookie mistake. Just forgot to call the method on the object in Main! :)


Wpf TreeViewItem Contextmenu Command binding not working

Question: I want to create a ContextMenu for TreeViewItems and pass a parameter as TreeViewItem data context (not TreeView data context).
I'm getting the error below for the command binding. What is the problem?
I also tried TreeViewItem, MenuItem and ContextMenu as AncestorType.
I also tried AncestorLevel as 1, 2, 3, but it did not change the result.
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TreeView', AncestorLevel='1''. BindingExpression:Path=DataContext.DeleteFolderCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')

Here is my code:
<TreeView ItemsSource="{Binding Folders}">
   <TreeView.ItemContainerStyle>

   </TreeView.ItemContainerStyle>
</TreeView>

Answer: A ContextMenu is is not part of the same visual tree as its associated control, so RelativeSource bindings do not work.
Bind the Tag property of a TreeViewItem to the DataContext of the parent TreeView instead. Then you can access this property through the PlacementTarget property on the context menu, which is set to the corresponding TreeViewItem.
<TreeView.ItemContainerStyle>

</TreeView.ItemContainerStyle>

Comment: it is a perfect workaround solution. Thanks. What would the solution be if the tag property was used for another purpose?
Comment: @ErhanUrun Then you could create an attached property and use it the same way.


How to host laravel on VM Instance

Question: I want to deploy laravel on VM Instance, I am following this link, when I completed upto setting up of database, I could not see my applications landing page, it instead shows Apache2 Debian Default Page, is it because I didnt configured Server name and Server Admin in this section?
<VirtualHost *:80>
    ServerName laravel.imarishwa.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/your-project-directory/public

    <Directory /var/www/html/your-project-directory>
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Or is there any other reason?
Answer: Yes, when you miss server name and open address in browser data fetch from default document root address of apache.
you can use this sample for edit your apache virtualhost
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    ServerAdmin email@example.com
    DocumentRoot /var/www/example.com/public_html

    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>

How to host laravel on VM Instance


Fourier series of a even function

Question: We define $f(x)=\textbf{1}_{[-\pi/2,\pi/2]}(x)$, $x \in [-\pi,\pi]$. We consider a Fourier series of $f$.
For $n \in \mathbb{Z}$, we have
\begin{align*}
\widehat{f}(n)&:=\frac{1}{2\pi}\int_{-\pi}^\pi f(x)e^{-inx}\,dx=\frac{1}{2\pi}\frac{\widehat{f}(n)+\widehat{f}(-n)}{2}\\
&=\frac{1}{2\pi}\int_{-\pi/2}^{\pi/2}\cos(nx)\,dx=\frac{1}{\pi n} \sin(n\pi/2).
\end{align*}
Therefore, the Fourier series $\sum_{n \in \mathbb{Z}}\widehat{f}(n)e^{inx}$ does not converge uniformly on $[-\pi,\pi]$. However, can we prove that this series converges for each $x \in [-\pi,\pi]$?
Answer: The short answer is no, Because you do not have pointwise convergence of the fourier series at points of discontinuity. This is called the Gibbs phenomenon.
https://en.wikipedia.org/wiki/Gibbs_phenomenon
You can find the formal description in the article, which can be directly applied to your function.
Comment: Yes, indeed. I also recommend reading the article :)
Comment: Thank you for your comment. So, the series converges on $[-\pi,\pi]/\{\pm \pi/2\}$, right?

Fourier series of a even function


Saving a Formsets with request.user

Question: How do I save a formset with the request.user? I cannot seem to get my form to save the request.user object on save when using Django Formsets.
forms.py
class CreditOptionsForm(forms.ModelForm):
    crew_position = forms.ModelChoiceField(CrewPosition.objects.all(),
        widget=autocomplete_light.ChoiceWidget('CrewPositionAutocomplete'), required=False)

    class Meta:
        model = CreditOptions
        exclude = ('user',)

OptionFormset = formset_factory(CreditOptionsForm, extra=3)

models.py
class CrewPosition(models.Model):
    name = models.CharField(max_length=150)

    def __unicode__(self):
        return self.name

class CreditOptions(models.Model):
    year = models.IntegerField(max_length=4, help_text='e.g. 1995', null=True, blank=True)
    project_name = models.CharField(max_length=150, null=True, blank=True)
    crew_position = models.ForeignKey(CrewPosition, null=True, blank=True)
    user = models.ForeignKey(User, null=True, blank=True)

views.py
from .forms import CreditForm, SkillsForm, OptionFormset

@login_required(login_url='/')
def add_skills(request, template_name):
    user = request.user
    formset = OptionFormset(user=user)
    if request.method == 'POST':
        formset = OptionFormset(request.POST, user=user)
        if formset.is_valid():
            for form in formset.forms:
                form.save()
            messages.success(request, "Successfully created your profile.")
            return redirect(urlresolvers.reverse('skills'))
    return render(request, template_name, {
        'formset': formset
    })

When I save, the user never gets saved. I have tried in my for loop:
form.save(commit=False)
form.user = user
form.save()

But this does not save the user as well.
Answer: Passing user as parameter has no effect since you've excluded it explicitly.
Just add the user while saving, like so:
@login_required(login_url='/')
def add_skills(request, template_name):
    user = request.user
    formset = OptionFormset()
    if request.method == 'POST':
        formset = OptionFormset(request.POST)
        if formset.is_valid():
            for form in formset.forms:
                f = form.save(commit=False)
                f.user = user
                f.save()
            messages.success(request, "Successfully created your profile.")
            return redirect(urlresolvers.reverse('skills'))
    return render(request, template_name, {
        'formset': formset
    })

Also form.save(commit=False) returns a model object. So you should assign user to this returned object's user field.

Saving a Formsets with request.user


If $M$ and $N$ are simple $R$-modules, and there is nonzero map from projective cover $P_N\to M$, is $N\cong M$?

Question: Suppose $M$ and $N$ are simple modules over a commutative ring $R$, and $P_N$ is the projective cover of $N$. If there is a nonzero morphism $P_N\to M$, does this imply $N\cong M$?
I'm not too familiar with projective covers other than the definition I read on the stacks project. Since $M$ is simple, the morphism $P_N\to M$ is an epimorphism. Since $M$ and $N$ are simple, I know it's enough just to have some nonzero map between them.
Answer: Let $K\subset P_N$ be the kernel of the map $f:P_N\to M$.  Since $p:P_N\to N$ is a projective cover, $p(K)$ must be a proper submodule of $N$, and hence $0$ since $N$ is simple.  It follows that $p$ factors through $P_N/K=M$ to give a nonzero map $M\to N$.


Deixar uma tela responsiva de acordo com a resolução do monitor

Question: Bom dia!
Tenho uma tela de login, que estou fazendo com bootstrap 4.
Como eu faria para ajustar o layout da pagina para que que a imagem de background não fique faltando ou que exploda.
Como da pra ver na imagem abaixo, em monitores de 1440 x 1032 fica faltado uma parte de baixo da imagem de background

<link rel="stylesheet" href="theme.css" type="text/css">

            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()

Efetuar login.

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

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

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

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

                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)

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

            }

SASS
$enable-rounded:            true !default;
$enable-shadows:            true;
$enable-transitions:        true;
$enable-hover-media-query:  false;
$enable-grid-classes:       true;
$enable-print-styles:       true;

// Variables
//
// Colors

$theme-colors: (
  primary: #12bbad,
  secondary: #4f70ce,
  light: #f3f3f3,
  dark: #151515,
  info: #ccc,
  success: #28a745,
  warning: #ffc107,
  danger: #dc3545
);

$body-bg: white;
$body-color: #333;

$body-color-inverse: invert($body-color) !default;
$link-color: #12bbad;

// Fonts
$font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
$headings-font-family: $font-family-base;
$display-font-family: $font-family-base;
$font-weight-normal: 200;
$headings-font-weight: 200;
$lead-font-size:   1.30rem;

$spacer: 1.5rem;

@import 'bootstrap-4.1.3';

html,body {
   height:100%;
}

.cover {
    min-height:100%;
  display:flex;
  align-items:center
}

.bg-gradient {
  overflow: hidden;
  color: color-yiq(map-get($theme-colors, 'primary'));
  background: linear-gradient(-30deg, theme-color("secondary") 0%, theme-color("primary") 50%, theme-color("primary") 100%);
}

.filter-dark {
  overflow: hidden;
  position: relative;
  color: color-yiq(map-get($theme-colors, 'dark'));
    &:before {
    position: absolute;
    top:0px;
    left:0px;
    width:100%;
    height: 100%;
    content: ' ';
    background: rgba(map-get($theme-colors, 'dark'), 0.75);
  }
}

.filter-light {
  overflow: hidden;
  position: relative;
  color: color-yiq(map-get($theme-colors, 'light'));
    &:before {
    position: fixed;
    top:0px;
    left:0px;
    width:100%;
    height: 100%;
    content: ' ';
    background: rgba(map-get($theme-colors, 'light'),0.75);
  }
}

.filter-color {
  overflow: hidden;
  position: relative;
  color: color-yiq(map-get($theme-colors, 'primary'));
    &:before {
    position: absolute;
    top:0px;
    left:0px;
    width:100%;
    height: 100%;
    content: ' ';
    background: rgba(map-get($theme-colors, 'primary'), 0.75);
  }
}

.filter-gradient {
  overflow: hidden;
  position: relative;
  color: color-yiq(map-get($theme-colors, 'primary'));
    &:before {
    position: absolute;
    top:0px;
    left:0px;
    width:100%;
    height: 100%;
    content: ' ';
    background: linear-gradient(-30deg, transparentize(theme-color("secondary"), 0.1) 0%, transparentize(theme-color("primary"), 0.1) 50%, transparentize(theme-color("primary"), 0.05) 100%);
  }
}

.filter-fade-in {
  overflow: hidden;
  position: relative;
  &:before {
    position: absolute;
    top:0px;
    left:0px;
    width:100%;
    height: 100%;
    content: ' ';
    background: linear-gradient($body-bg, transparentize($body-bg, 0.2),transparentize($body-bg, 0.9),transparentize($body-bg, 1));
    }
}

Answer: Se o seu problema é apenas como o background de uma página de login vc pode usar o background direto no body, e usa as propriedades background-size e background-position para ajustar a imagem, no caso do exemplo que fiz eu alinhei a imagem colada no bottom na vertical e centralizada na horizontal background-position: bottom center e para o background ocupara o tamanho correto use background-size: cover
OBS: Aqui no snippet não fica muito bom pq ele não tem altura suficiente e tem que fazer o tratamento responsivo, mas exiba em "Página toda" que vc vai ver melhor como está ficando. Tentei usar uma imagem similar para vc ter uma ideia de como vai ficar.

html, body {
  height: 100%;
}
  body {
    background-image: url(https://d2gg9evh47fn9z.cloudfront.net/800px_COLOURBOX27495652.jpg);
    background-size: cover;
    background-position: bottom center;
    background-repeat: no-repeat;
  }
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

      <form>

            Email address
            <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
            We'll never share your email with anyone else.

            Password
            <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">

            <input type="checkbox" class="form-check-input" id="exampleCheck1">
            Check me out

          <button type="submit" class="btn btn-primary">Submit</button>
      </form>

Comment: Opa!, vlw mais um vez.
Aproveitando, se eu quisesse colocar uma imagem em cima do form, teria alguma forma de deixar ela fixa no centro?
Eu tentei com código abaixo, só mexendo no margim-left, mas nesse caso, claro que vai quebrar quando mudar a resolução, teria alguma dica?
Comment: @Jhensen cara no background-size vc coloca o tamanho da imagem tipo 500px 300px, e no background-position vc coloca center center, assim uma imagem de fundo vai ficar centralizada no meio da tela. Ou vc quer que a imagem esteja realmente por cima do form deixando ele encoberto por baixo da imagem?
Comment: O background ta resolvido.
Só que eu resolvi botar uma logo em cima do form de login. Acima do "Efetuar Login", ai eu queria centralizar essa logo acima desse form. Ja inseri a imagem e tal, mas só não consegui alinhar ao centro do form.
Comment: @Jhensen agora ficou mais fácil de entender. Vi que vc postou uma pergunta nova, que seria o correto mesmo para não bagunçar essa etc. Vou ver se te respondo la
Comment: @Jhensen te respondi lá na outra pergunta
Answer: Uma das soluções viáveis e bem simples, em vez de adicionar o background em um style, você poderia criar uma class como no exemplo abaixo:
No exemplo abaixo em vez de utilizar o "background-image" eu utilizei o "background" e adicionei o no-repeat e alinhei a imagem no centro, para funcionar corretamente apliquei o "position: absolute;"

.py-5 {
    background: url('https://i.imgur.com/lUGkKdy.png') no-repeat center center;
    -webkit-background-size: cover; /* Safari and Chrome */
    -moz-background-size: cover;  /* Firefox */
    -o-background-size: cover; /* Opera */
    background-size: cover;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
}

            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()

Efetuar login.

                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

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

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

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

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

                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)

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

            }

Comment: Opa!, Obrigado pela ajuda amigo!
Aproveitando, se eu quisesse colocar uma imagem em cima do form, teria alguma forma de deixar ela fixa no centro?
Eu tentei com código abaixo, só mexendo no margim-left, mas nesse caso, claro que vai quebrar quando mudar a resolução, teria alguma dica?
Comment: no caso você quer adicionar um logo acima do form?
Comment: isso, acima do h4. Até ja inseri, mas só que não centralizada. Ai minha duvida é se tem uma forma correta de centralizar essa imagem. Sei que tem algumas formas, mas qual seria a ideal? essa a minha dúvida
Comment: Existe inúmeras formas de deixa do jeito que você quer, mas não tem como eu te ajudar sem mais informações sobre o código, eu recomendo você abrir outra pergunta e fornecer mais informações da pagina e deixa o código um pouco mais limpo para melhor compreensão, com o código de cima até dar para te ajudar, mas na hora que você for aplicar no modelo pode dar conflito com outras class.
Comment: Blz, fiz um novo post pra ficar mais claro. https://pt.stackoverflow.com/questions/344270/alinhar-uma-logo-no-centro-do-form


Extract archive with password that contain double quote

Question: i want to extract an archive called test.rar with 7zip but nothing worked for me
Archive: test.rar
Password(with quote):"."
I tried
& "C:\Program Files (x86)\7-Zip\7z.exe" t  -p'"".""' test.rar
& "C:\Program Files (x86)\7-Zip\7z.exe" t -p""."" test.rar
& "C:\Program Files (x86)\7-Zip\7z.exe" t "-p"."" test.rar
& "C:\Program Files (x86)\7-Zip\7z.exe" t -p'"."' test.rar
& "C:\Program Files (x86)\7-Zip\7z.exe" t -'p"."' test.rar
& "C:\Program Files (x86)\7-Zip\7z.exe" t -p'"".""' test.rar

Comment: Does this answer your question? [Extract password archive with double quote in windows command line](https://stackoverflow.com/questions/40438074/extract-password-archive-with-double-quote-in-windows-command-line)
Comment: How about extracting the archive manually with the GUI this time and using another password without double quotes next time?  ;-)
Answer: Up to at least PowerShell 7.1, passing arguments with embedded " characters to external programs such as 7z.exe is fundamentally broken, unfortunately.
While there are workarounds, the simpler solution is to provide the password via stdin.
The post that Mark Tolonen links to shows this technique for cmd.exe, via <, its input-redirection operator, which PowerShell does not support, however.
Instead, use PowerShell's pipeline to supply data that an external program receives via stdin.
Assuming that the verbatim password is ".":
'"."' | & "C:\Program Files (x86)\7-Zip\7z.exe" t test.rar


Navbar opacity on scroll vuejs

Question: I want to change the opacity of my fixed navbar background when user scrolling the page. Initially navbar background should be transparent and when scrolling down it background needs to be change to white.
Like this example https://codepen.io/michaeldoyle/pen/Bhsif
I have found various examples for this scenario using jquery. But I need to achieve this using vuejs.
$(window).scroll(function() {
  if ($(document).scrollTop() > 200) {
    $('nav').addClass('transparent');
  } else {
    $('nav').removeClass('transparent');
  }
});

I tried above code inside my vue page. I put it inside mounted(). But it doesn't work. I need to done this using vue. Not like above jquery.

  <router-link to="/about" @click.native="closeNavBarFromChild">About</router-link>

  <router-link to="/product" @click.native="closeNavBarFromChild">Product</router-link>

This is how my navbar component looks like.
nav.navbar{
   -webkit-transition: all 0.4s ease;
   transition: all 0.8s ease;
}

.navbar-inverse {
    background-color: rgba(255,255,255,0);
}

nav.navbar.transparent {
  background-color:rgba(0,0,0,1);
}

this is the css part that i used.
Comment: `But it doesn't work` - in what way? errors in the console? what doesn't work about it?
Comment: nothing appears in console. I just use http://jsfiddle.net/m7yww8oa/157/ this simple example for testing. nothing happens. I put that jquery code inside mounted(). Is that right?
Comment: Oh, I thought you were using vuejs
Answer: Set your listener in created lifecycle hook:
export default {
  created () {
    window.addEventListener('scroll', this.onScroll);
  },
  destroyed () {
    window.removeEventListener('scroll', this.onScroll);
  },
  methods: {
    onScroll (event) {
      // add/remove class
    }
  }
}

Navbar opacity on scroll vuejs


"Unexpected shutdown" message on Hyper-V guest machines

Question: We have a couple of Dell Poweredge servers running Hyper-V. Both host machines and the guest VMs are using Server 2008 R2 Enterprise with Service Pack 1 installed. The guest machines were built as VMs rather than converted from physical servers. Whenever a guest VM is restarted we get the "unexpected shutdown" dialog next time we log on.
This happens whether we reboot the guest from an RDP session, do it through the Hyper-V manager or if the host machine is restarted.
I've double checked that the integration services "disk" has been inserted and run successfully and have done so since SP1 was installed on the host. Under the integration services settings for the guest VM the relevant box is ticked for Operating System Shutdown.
I've looked at http://technet.microsoft.com/en-us/library/ee207413%28v=ws.10%29.aspx and checked that the version of integration services is the same on host and client - 6.1.7601.17514
Does anyone have any suggestions what to check next or why this might be happening? Thanks.
Comment: strangely enough lately we are seeing the same issue on both hypervisors that we use esxi 4,5 and hyper-v. Not all the time just more frequently then in the past.  And yes the guest are all w2k8r2sp1
Comment: I should also say that the shutdown delay has not been exceeded so they should be clean but they are not.
Answer: This is an old issue but I've come across with this with VMs running Server 2008 R2 after migrating the host to Hyper-V 2012 R2
Check if all device drivers were upgraded. Please see more detailed instructions at http://alexappleton.net/post/69391495030/two-unknown-devices-in-windows-server-2008-r2-under
Answer: The "unexpected shutdown" message means that not all the writes to the disk were flushed before the VM turned off or rebooted.  I can't tell you why this occurred from what you've written, but I can suggest that you look for reasons within the VMs that the storage might be doing strange things (like odd anti-malware packages, etc.) or outside the VM (like a RAID controller or SAN) that may be skipping flushes.


Two dimensional array of class and the constructor call in C++

Question: I have a problem in which I have a class, and I need a two-dimensional array of that class. Normally I would do this using vectors, but unfortunately I am working with a library where this is not really possible, which lead to me realizing how little I know about conventional C arrays.
I did some research on this topic and found many answers on how to properly make a two-dimensional array in c++, and even two-dimensional arrays for classes. The problem was only that all solutions ommited the calling of the constructor, something which i need. Take the following example:
class cClass
{
public:
    int x;
    int y;
    cClass()
    {
    }
};

int main(int argv, char argc[])
{
    cClass ** cClass_testClass = new cClass*[5];
    for (int i = 0; i < 5; ++i)
    {
        cClass_testClass[i] = new cClass[5];
    }
    system("PAUSE");
    return 0;
}

To my understanding, this creates a two-dimensional 5x5 array of the class 'cCLass'. And it'll work because the constructor doesn't really do anything. Now say I would rather have the x and y values in the class to correspond to the x and y values in the array, and I for some reason could only do this in the constructor itself, how would I approach this? Any help would be greatly appreciated.
Comment: Note that you're allocating memory, and never releasing it - each new[] should be matched by a delete[], i.e. `delete [] cClass_testClass[i]` for each `i`, and `delete [] cClass_testClass` to delete the arrays' array.
Answer: If you're going to do an array of class cClass, you'll need it to have a constructor with no parameters, and that's the constructor that will be called upon allocation of the array (new cClass[5]).
To solve your problem, create a two-dimensional array of pointers to cClass:
cClass*** cClass_testClass = new cClass**[5];
for (int i = 0; i < 5; ++i)
{
    cClass_testClass[i] = new cClass*[5];
    for(int j = 0; j < 5; ++j)
    {
        cClass_testClass[i][j] = new cClass(i, j);
    }
}

And don't forget to eventually delete all the dynamically allocated memory!


D7 images not loading from css or from direct urls

Question: I have a site that I have developed off-line and now loaded onto the production server.  None of the images load on the server (despite being present in the appropriate directories).  This applies to images loaded by css (for example:
.section-contact div#header {
background-image: url('/www.bernwodebenefice.com/images/contact_banner.png');}

It also applies to direct links from nodes.  For example:

(these samples are from the rendered code and are what I expected).
I do not have this problem with any of my other sites running on the same host.  For example:
div#header {background-image: url(/sites/all/themes/Endurance80/css/images/e80_2013.gif); height: 263px; }

This works perfectly.  And urls within the site work nicely using the same sort of link addresses.
I guess I have got some parameter somewhere not set right...  (I copied .htaccess and php.ini from a working site to the failing site in the hopes it was a rewrite problem... nope)
Any thoughts?
Peter
Comment: Have you tried ``
Answer: Have you tried

and
.section-contact div#header {
  background-image: url('../images/contact_banner.png');
}

where images is a folder in your theme dir e.g: images/contact_banner.png relative to css file in e.g: css/style.css.
Comment: Thanks for the reply.   I moved the css images to "sites/default/themes//css/images" and modified the css to point to "images/xxxx_banner.png" (no leading slash).  That had two effects:  the banner images now work and all the rest of the images now work (even though I did not move them at all).

Thanks for the support.
Answer: Why are your ulrs in your first two examples start with a slash? If you are not intentionally doing it, it can most probably be related with your settings.php. Check and make sure that your base_url is defined correctly.
Comment: Hi - thanks very much for the reply.  Yes, the leading "/" was deliberate.   As you can see above I have fixed the problem, but I will check out the settings folder as you suggest and see if that works - settings.php was the only file not transfered from the development site, so it could well hold a different base_url.

Thanks for your support - I'll come back on this (but not till the end of the week)
Comment: Just to feedback on that last point about base_url.  I tried this and it crashed the site.  So I reset it rapidly and have not diagnosed further!  (apologies for the delayed response - been ill).


Azure API Connection - how to recover user info

Question: I need to list sql users that are being used by some azure API Connection. How can I retrive this information? I can view server and database via properties, but the user seens to be hiden.
Answer: Just received an answer from Azure support team confirming that there is no way to recovery this information via azure portal.
What they said it was possible, it is to check Azure SQL Database logs or open sessions (while executing the logic app) to get the user from the session.
Comment: Thanks, this is exactly what I was looking for. Please accept your answer.


Proving that the set of differentiable functions with $\left|f'(t)\right|\leq K$ is dense in the set of Lipschitz continuous functions?

Question: Let $M_K$be the set of all continuous functions $f$ in $C_{[a,b]}$ satisfying a Lipschitz condition, i.e., the set of all $f$ such that
$$
\left| f(t_1)-f(t_2)\right| \leq K \left| t_1-t_2\right|
$$
for all $t_1,t_2 \in [a,b]$, where $K$ is a fixed positive number. I would like to prove that $M_K$ is the closure of the set of all differentiable functions on $[a,b]$ such that $\left|f'(t)\right|\leq K$.
My Try: I have proved that $M_K$ is a closed set and know that any such differentiable function is in $M_K$. Now I need to prove that for any $f\in M_K$ there exists a sequence of such differentiable functions $\{g_n\}$ such that $g_n\rightarrow f$. Any help?
By $C_{[a,b]}$, I mean the set of all continuous functions on the interval $[a,b]$ with distance:
$$
d(f,g) = \max_{a\leq t\leq b} \left|f(t)-g(t)\right|
$$
Answer: Hint: Extend $f$ to a $K$-Lipschitz function on $\mathbb{R}$. Then use the standard method to approximate $f$ with a sequence $f_n$ obtained by convoluting with a sequence of mollifiers
$$f_n(x) = \int_{\mathbb{R}} f(x-y)\omega_n(y) = \int_{\mathbb{R}} f(y)\omega_n(x-y)$$
It is easy to see that $f_n$  are also $K$-Lipschitz, and since they are smooth, $\,|f_n'| \le K$.


In ember app chrome beta version - Failed to find a valid digest in the 'integrity' attribute for resource

Question: In chrome beta version I got the below error in one of my app,

Failed to find a valid digest in the 'integrity' attribute for
  resource
  'http://localhost:8000/assets/vendor-2d2d91b98d3771c414a0b039e0b4d8c1.js'
  with computed SHA-256 integrity
  'RtMfPvtdjkEbERLgZ70Z5f8rCHbsou/DcqEZCXiM8ME='. The resource has been
  blocked.

As github thread pointed out that its fixed but I am getting this error in ember-cli-2.14.1 and "ember-cli-sri": "^2.1.0", so I am going to include integrity=''. I would like to know , is there any consequences for this change?
Comment: In your linked thread, someone mentions seeing this error message in the production build and someone else points out that [that is probably a different issue](https://github.com/ember-cli/ember-cli/issues/5040#issuecomment-230599490).

I am seeing this problem now with ember-cli 2.18.2 and (non-beta) Chrome 66 (possibly since 65) and only when reloading my app after deploying a new version - it goes away after clearing the browser cache, but I would like to know the root cause, too.
Answer: the script or css you draw in(maybe in CDN) has changed.But your html used integrity to ensure the file not changed. for example:


Replace once part of the query in Emacs

Question: I have such requirement for search&replace in Emacs:
I have a bunch of
'A', 'High'
'B', 'High'
'C', 'High'
'D', 'High'

And the list goes on.
I want to replace them to be:
A = 'High'
B = 'High'
C = 'High'
D = 'High'

Can I query for the pattern, say '#', 'High' and replace it with #= 'High?
Answer: Move point to beginning of buffer.
M-x query-replace-regexp.
Enter '\([^']+\)', '\([^']+\)' as regexp and \1 = '\2' as replacement.
Press ! to replace all at once, or keep pressing y/n
for each match.

Replace once part of the query in Emacs


Why do I get a build warning "button is assigned but its value is never used" in the Xamarin.Forms hello world example?

Question: I'm following the hello xamarin quickstart project https://developer.xamarin.com/guides/xamarin-forms/getting-started/hello-xamarin-forms/quickstart/ for Xamarin.Forms and I'm getting a warning The private field Phoneword.MainPage.translateButon is assigned but its value is never used  in the generated code files
/Demo/Phoneword/obj/Debug/Phoneword.MainPage.xaml.g.cs(46,46): Warning CS0414: The private field `Phoneword.MainPage.translateButon' is assigned but its value is never used (CS0414) (Phoneword)

Here's the XAML
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="XamDemo.MainPage">
    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness" iOS="20, 40, 20, 20" Android="20, 20, 20, 20" WinPhone="20, 20, 20, 20" />
    </ContentPage.Padding>
    <ContentPage.Content>
        <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Orientation="Vertical" Spacing="15">

            <Entry x:Name="phoneNumberText" Text="1-855-XAMARIN" />
            <Button x:Name="translateButon" Text="Translate" Clicked="OnTranslate" />
            <Button x:Name="callButton" Text="Call" IsEnabled="false" Clicked="OnCall" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Why am I getting that warning?  The project seems to work fine and the translate button does call a method so it is being used.  I don't get the same warning for callButton which seems like it was declared in the same way.  What's going on?
Answer: A translateButon field is generated in the Phoneword.MainPage.xaml.g.cs file because of the x:Name="translateButon" attribute.
This attribute gives you access to the Button element if you wanted to do anything with it in the MainPage.cs code file.
But all you need to do is done in the Xaml, namely what action should happen on click. So the warning will disappear if you remove the x:Name="translateButon" attribute.
Comment: Ok, that makes sense.  I see now that it didn't have the same warning for the call button because that object was referenced in the code behind.


Fatal error on Drush run

Question: I've installed Drush following http://www.zyxware.com/articles/4497/drupal-installing-latest-version-of-drush-on-linux-system-and-troubleshooting.
Now, when I try to run Drush, I get this error message.

PHP Fatal error: Class Symfony\Component\Console\Style\SymfonyStyle contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Console\Output\OutputInterface::isQuiet, Symfony\Component\Console\Output\OutputInterface::isVerbose, Symfony\Component\Console\Output\OutputInterface::isVeryVerbose, ...) in /var/www/html/tubimer/vendor/symfony/console/Style/SymfonyStyle.php on line 33
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Class Symfony\Component\Console\Style\SymfonyStyle contains 4 abstract methods and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Console\Output\OutputInterface::isQuiet, Symfony\Component\Console\Output\OutputInterface::isVerbose, Symfony\Component\Console\Output\OutputInterface::isVeryVerbose, ...) in /var/www/html/tubimer/vendor/symfony/console/Style/SymfonyStyle.php, line 33

How do I fix these errors?
Comment: Use the official documentation to install drush 8 globally http://docs.drush.org/en/8.x/install/
Comment: What Drupal version are you using?
Comment: Drupal 8.4 requires Drush 9, Drupal 8.3 requires Drush 8.
Answer: I suggest you to run -
<code>composer self-update
composer update
</code>
It might solve your problem, but if it doesn't then try to install latest version of drush. I installed drush using https://www.drupal.org/node/1248790.
However, there is a full documentation on how to install drush for specific operating system. Link to documentation - https://www.drupal.org/node/1791676

Fatal error on Drush run


What transceiver can convert 10GBASE-KR or 10GBASE-KX4 to 10GBASE-T or 1000BASE-KX to 1GBASE-T?

Question: A pci-e network card supports 1000BASE-KX, 10GBASE-KX4 and 10GBASE-KR on SFP connector, but the required mode for twisted pair support on RJ45 (8P8C connector) is 1G- or 10GBASE-T.
What type of transceivers can connect previous mentioned SFP+ related standards to 1000/10000BASE-T modes/protocols?
What are examples for block diagrams or datasheets, that describe this mode or protocol conversion in detail?
( Example for common type of these adapters: fs
and a resource for general (but 2012) transceiver internals
En-/Decoding: 8b/10b <=1GBit/s, 64B/65B >1Gbit/s <=5Gbit/s, 64b/66b >5Gbit/s =10Gbit/s )
Comment: I really do not understand the question. What do you mean by, "_SFP+ related modes_?" There is SFP for 1000Base-T and SFP+ for 10GBase-T. SFP/SFP+ is not limited to fiber.
Comment: That really doesn't make sense. The standard of 1000Base-T means that anything with 1000Base-T is compatible. If a standard is followed, then anything supporting that standard will work.
Comment: https://www.prolabs.com/assets/uploads/docs/INF-8074_SFP-Form-Factor.pdf page 21 shows pinout of 20 pins SFP+, but for backplane connectors it does not seem that there is a standardized pinout available.
Comment: An SFP/SFP+ is an active interface that plugs directly into a host (router, switch, PC, etc.). It provides the physical interface to the cabling. That physical interface can be one of a variety of copper or fiber ethernet standards. Thjat is the big reason for the SFP/SFP+: you can have a device with an SFP/SFP+ cage that can accept a variety of modules to meet the physical cabling requirements of a site. The 1000Base-K variant are meant for a backplane of the device, and have a distance limitation of 1 meter, which is fine for inside the host, but not for a cable plant.
Comment: @RonMaupin "They are compatible with the 10Gbase-T /5Gbase-T / 2.5Gbase-T / 1000base-T standards as specified in IEEE Standard 802." Almost an answer from inside this datasheet (vendor sopto) http://www.sopto.com.cn/upload/201907/25/201907251646537757.pdf Thx@all for support and engagement (question about availability of coding translation from host interface mediums in transceivers will be answered in comments, with knowledge appearing)
Comment: BTW, the 10Gbase-T SFP+ are typically quite expensive, it might be cheaper to go with a direct attached cable or use a NIC with RJ45 (and keep the SFP+ card for something else)
Comment: Every transceiver module (within standard of IEEE 802.ap, and 802.3an-2006) should be able to transmit packets from backplane and fibre network standard to 10GBASE-T, for e.g., if physical interfaces are provided. Public information has been updated since this question started. Answered at
https://serverfault.com/questions/1064474/what-transceiver-modules-can-convert-10gbase-kr-or-10gbase-kx4-to-10gbase-t-or-1 , details on 'physical layer model' https://en.wikipedia.org/wiki/10_Gigabit_Ethernet#Physical_layer_modules
Answer: BASE-K is backplane Ethernet. Are you sure that NIC is intended to be cabled external to a chassis?
Plug both types of modules into a switch. A single module handles one medium type as fast as possible. Given the power and physical space restrictions, a module that talked over multiple mediums would be exotic. If it exists at all.
Comment: Thx. What I called "mode" Synopsys calls "(interconnect) medium interfaces". If i understand correctly (https://www.synopsys.com/designware-ip/technical-bulletin/ethernet-dwtb-q117.html) only 10Gbase-KX4 and 10Gbase-CX4 are compatible medium interfaces for connecting with common desktop 10Gbase-T or 1Gbase-T Rj45 PHYs if multi data rate capable (https://www.edn.com/design/communications-networking/4374010/Designing-with-10GBase-T-transceivers)? 10Gbase-KR is a different PHY, because of 64B/66B (R) coding. But what's the transceivers input medium interface and definition for that?
Comment: supplement: There is a block diagram that shows BASE-KX4 to BASE-T conversion for 8b10b coding. 10GBASE-SR to 10GBASE-T, 64b66b, is shown by a www  log.


How to make sure my behavior is triggered before AJAX?

Question: I have a form elements that looks like this:
  $form['properties'][$property->idProperty] = array(
    '#title' => $property->Label,
    '#ajax' => array(
      'callback' => 'mymodule_filter_ajax',
      'wrapper' => 'mymodule-filter-result',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#attributes' => array(
      'autocomplete' => 'off',
      'class' => array('exclusive'),
      'exclusivity_group' => array ( $property->ExclusivityGroup )
    ),
  );

The point of it is to have only one element from each group used at a time. To enforce that exclusivity, I created behavior like this:
(function($) {
  Drupal.behaviors.behavior_name = {
    attach: function (context, settings) {

      $('select.exclusive', context).on('change', function(){
        // Make all not selected
        $("[exclusivity_group='"+$(this).attr('exclusivity_group')+"']").not(this).find("option").attr('selected', false);
        // select "all"
        $("[exclusivity_group='"+$(this).attr('exclusivity_group')+"']").not(this).find("option[value='all']").attr('selected', true);
      });
    }
  };
})(jQuery);

Note that both code blocks above are simplified, please don't criticize it too much as this is not actual code I'm using posted verbatim.
How can I make sure my behavior acts before AJAX? If it happens to act after AJAX, I may end up with two fields set to something other than 'all', and that's specifically what I wanted to avoid. I may use $triggering_element to detect if it was one of "exclusive" fields, and I probably will, even if only as a secondary precaution, but I would strongly prefer to have things happening right in the JavaScript part.

I tried using this answer, but I don't think I understand how it works. I tried:
  $('select.exclusive', context).each(function(){
    console.log($(this).attr('id'));
    Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
      console.log(element.html());
    };
  });

First console.log returns IDs as expected. And it works, beforeSend is, indeed, changed as it should, it's function gets executed when needed. Sadly console.log(element.html()); returns content of a whole form, not the triggering element of AJAX, so I'm not able to safely enforce exclusiveness - I don't know which element was changed last, so no way to select other elements.
Answer: I got it working now. The way to do it was:

Get all elements that are in "exclusive" groups using classes, .each over them
For each element, change beforeSubmit using $(this).attr('id') as index for ajax table
Because I was not able to get element to point to a specific element (it always pointed to entire form), I used helper variable at the beginning of .each loop.

Resulting code is like this:
(function($) {
  Drupal.behaviors.behavior_name = {
    attach: function (context, settings) {

      $('select.exclusive', context).each(function(){
        var triggering_element = $(this);
        Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
          // Make all not selected
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option").attr('selected', false);
          // select "all"
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option[value='all']").attr('selected', true);

        };
      });
    }
  };
})(jQuery);


Exponential sums/Laplace transform for $L^1\cap L^2$

Question: This is perhaps completely trivial, but I'm not sure:
Suppose we have a function $f(x)\in L^1\cap L^2, (-\infty,\infty)$ and a trigonometric sum over a countably infinite set of complex numbers which converge (perhaps distributionally) to $f(x)$. Perhaps something like:
$$f(x)=\sum_{s\in S} \eta_se^{|x|\sigma+ix\omega}$$
where $S$ is a countably infinite set of complex numbers $s=\sigma+i\omega$ with $\sigma\ge 0$ and $\eta_s$ are some weights.
QUESTION: must it be the case that $\sigma=0$ for all $s$? The idea is that we have something like a Fourier Transform with a discrete spectrum and the possibility of exponential growth for the basis (which i am curious if we can rule out).
I think this question is related to the Fourier and Laplace transforms. I have a feeling that the answer is yes because Fourier Inversion is valid for functions in $L^1\cap L^2$ (which implies that $\sigma=0$). I don't know if there is more to show, such as if there is a $\sigma_s>0$ then the exponential growth cannot be neutralized by other $\sigma_s$'s.
thank you
Comment: No; take the index set to be over all complex numbers with (say) integer coordinates, and define $\eta_s = 1$ if $s = -1+i$ and $0$ otherwise. Then $f(x) = e^{-x+ix} \in L^1\cap L^2$. Note that you can't write $f$ as a proper Fourier series, since it's not periodic.
Comment: @kieransquared thank you for this.... you pointed out an issue with my question.... i think i really meant to ask for $Re(s)\ge 0$. ill adjust the question now.
Comment: Unclear. $\sigma=\sigma_s$ ? $\sum_{s\in S}$ where $S$ is a countably infinite subset of $\Re(s)\ge 0$ ? Did you mean that for all $x\in \Bbb{R}$ the series converges to $f(x)$ ?
Comment: @reuns yes, so similar to a FT with discrete spectrum, but with the possibility of exponential growth in the basis.
Comment: Why don't you edit/clarify your question?
Answer: No because an exponential sum can converge pointwise to $0$ for all $x$.
I interpret your question as given 3 sequences $(\sigma_n),(\omega_n), (\eta_n)$ with $\sigma_n\ge 0$ and the $\sigma_n+i\omega_n$ distinct, if $$f(x)=\sum_{n=1}^\infty \eta_n e^{\sigma_n |x|+i\omega_n x}$$ converges for all $x$, to $f(x)$, such that $f\in L^1 \cap L^2$, should we have that $\forall n,\sigma_n = 0$?
For a counter-example, start with $F_1(y) = 1_{y\in [0,1]}$,
then for each $n$, find the least (for the lexicographical order) integers $k\ge 0,a\in \Bbb{Z},b\le 0$ such that $$\forall y, \qquad F_n(y)\ge \frac1n 1_{y\in [\pi^{-n}+a/2^k,\pi^{-n}+(a+1-b)/2^k]}$$ and set $F_{n+1}(y)=F_n(y)-\frac1n 1_{y\in [\pi^{-n}+a/2^k,\pi^{-n}+(a+1-b)/2^k]}$.
If no such $k,a,b$ exist set $F_{n+1}=F_n$.
It is not hard to see that $F_n$ converges to $0$ in $L^1$, that $\lim_{n\to \infty} F_n'$ is a series of weighted Dirac delta peaks at distinct abscissa, and that the Fourier transform of $F_n'$ is an exponential sum at distinct frequencies and which converges to $0$ pointwise. Multiplying it with $e^{|x|}$ gives a counter-example.


Reported speech

Question: I want to know the following sentence
Wrong : "He said that all students should focus during the lesson so they would not get hurt."
Right :  "He said that all students should focus during the lesson so they will not  get hurt."
Why is it will not but not would not?
Comment: Better suited for https://ell.stackexchange.com/
Comment: How is it related to **_math_**.stackexchange.com? Try asking at https://english.stackexchange.com/
Answer: This isn't particularly math related, but saying would not may imply a hypothetical situation. It is like saying if you don't pay attention you may get hurt but it isn't certain. Saying will not implies that if you do not pay attention to the lesson it is certain you will get hurt and regret it. I'm by no means an English professor, just my thought, definitely ask on: https://english.stackexchange.com/
Cheers!

Reported speech


Contact page MVC workflow

Question: All my previous projects have had this workflow on Contact pages

User submits form
Controller gets $_POST details
Controller validates details (and sets error messages if necessary)
Controller sends email
Controller redirects to thanks page

Is this the standard workflow?
I used to validate everything in controllers, and then did some more reading and they recommended against it. Therefore, should I send the $_POST details to a helper type object and let it do all the work (validation/sending)?
Answer: In controller we should only check validation. The main validation should be on model before operations with DB.
Answer: The controller file need to check & validate the user input data.
After getting & accumulating all the data, it needs to transfer the data to the Model file for checking with the database (if needed) & then need to do some other works from here (like setting sessions / cookies, or sending mails, or firing hooks, ...). However, the control must come back to the same controller method, as all the previous model functionalities must be fired by a method call, from the same controller method.
The proper view method must be called now, and then the output must be rendered to the console.
Hope it helps.
Answer: Validation is typically performed in the Model, not in the Controller.
This is because data structures are usually defined in the Model and  it is best to compare the acquired data immediately before manipulation (i.e. inserting into a database, etc.).

Contact page MVC workflow


direct jsp page by button onclick event without form tag

Question: can we use input tag button without form tag and how to direct to another jsp page through onclick event?
I am trying to do this task by below code Here am trying to direct one editsurvey,jsp page through button onclick event without form tag.Can anyone explain the way I am using correct or incorrect?

<%--
  Created by IntelliJ IDEA.
  User: rajee
  Date: 2/16/15
  Time: 10:17 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="java.sql.*"%>

    <title>Welcome to survey</title>

<%
    ResultSet rset;
    String sur_id = request.getParameter("surveyid");
    session.setAttribute( "surveyid", sur_id );
    int new_survey_id = Integer.parseInt(sur_id);

    if (request.getParameter("surveyid") == null) {
        out.println("Please enter your name.");
    } else {
        out.println("Hello "+request.getParameter("surveyid")+"!");
    }
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
    String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
    Statement stmt = con.createStatement();
    rset = stmt.executeQuery(query);

    while(rset.next()){
//        out.println(rset.getString(1));
//        out.println(rset.getString(2));
//        out.println(rset.getString(3));
//        out.println(rset.getString(4));
        %>

Survey_Id	<%=rset.getString(1)%>

Family name	<%=rset.getString(2)%>

First name	<%=rset.getString(3)%>

Middle name	<%=rset.getString(4)%>

gender	<%=rset.getString(5)%>

dat of birth	<%=rset.getString(6)%>

income	<%=rset.getString(7)%>

complete address	<%=rset.getString(8)%>

coordinates	<%=rset.getString(9)%>

mobile number	<%=rset.getString(10)%>

email address	<%=rset.getString(11)%>

present Internet provider	<%=rset.getString(12)%>

comments	<%=rset.getString(13)%>

remarks	<%=rset.getString(14)%>

<input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();">	&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="button" value="delete">	&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="button" value="print">	&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
                    <input type="button" value="send mail">	&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

        <%
    }

%>

Answer: HI i think you can use the following code
<button type="submit" formaction="demo_admin.asp">Submit as admin</button>

In the formaction attribute you can use your form name where you want to redirect.


Matlab function ppval delivers strange results

Question:
The Matlab functions mkpp/ppval allow the construction of a piecewise
  polynomial. The function y(t) = t delivers for t=0.7 the correct
  result y(0.7) = 0.7,  if the range is set to [0 1]. If the range is
  expanded to [-1 1] the result should be the same. However, Matlab
  returns the value 1.7

MATLAB Version: 126.96.36.1992 (R2014a)
MATLAB License Number: DEMO
Operating System: Mac OS X  Version: 10.9.5 Build: 13F34
Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
% Get the value of the polynom y(t) = t in the section [0 1]
y = ppval(mkpp([0 1],[1 0]), 0.7)
% y(0.7) = 0.7

% Expand the section to [-1 1]
% The result should be the same
y = ppval(mkpp([-1 1],[1 0]), 0.7)
% y(0.7) = 1.7 How that???

Answer: From the documentation for mkpp, mkpp([a b], [cn ... c1 c0]) represents the polynomial cn*(x-a)^n + ... + c1*(x-a) + c0. In other words, the second argument contains the coefficients to a polynomial in x-a rather than a polynomial in x.
So, in your case, your piecewise polynomial is actually x-(-1) = x+1, explaining the 1.7 result you get.
Answer: I believe that mkpp shifts each piecewise polynomial onto the interval defined in the first input - meaning that the left edge of the interval is treated as x=0 in the polynomial.
So the first polynomial defined above goes from y = 0 to y = 1 over the interval x = 0 to x = 1, while the second goes from y = 0 to y = 2 over the range x = -1 to x = 1.


Why there is checked and unchecked exception in Java

Question:
Possible Duplicate:
Java: checked vs unchecked exception explanation
Why are exceptions named checked and unchecked?

Why is the two exception types in Java named "checked" and "unchecked"? What is the reason behind choosing this type of exceptions ?
Comment: Have you used search before asking?
Comment: At least you should google first then post question here.
Comment: I just found this post by Googling it.
Answer: Checked exceptions extend java.lang.Exception, while unchecked exceptions extend java.lang.RuntimeException, or java.lang.Error.
Exception extends java.lang.Throwable, while RuntimeException extends Exception, and Error, like Exception, extends java.lang.Throwable.
When deciding whether you should be using a checked vs. unchecked exception, always remember these rules:

ExceptionS are cases an application would want to handle.
RuntimeExceptionS are cases you (usually) can't handle, due to programming error. You shouldn't catch RuntimeExceptionS, they should be targeted in your unit testing, and fixed in your production code.
ErrorS are cases you can't handle because of critical errors, such as system problems (e.g. file system has failed). You shouldn't ever throw, catch or subclass an Error, unless you're building something such as a compiler for the JVM.
Answer: The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes.The compiler doesn't forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.
unchecked exception classes are exempted from compile-time checking in java because they can occur at many points in the program and recovery from them is difficult or impossible. They also depend on the logic of the programmer. For example the OutOfMemory Exception is thrown when JVM cannot allocate any more memory to the program


Proving an equation has a unique solution

Question: Prove that $ a^2-2ax+(2ax-a^2N)e^{(-a/x)}=0$ has a unique solution.
(Note: $x>0, a>0, N$:positive integer). Thanks.
Comment: Is $a$ a constant?
Comment: Yes,$a$ and $N$ are constants. $x$ is variable.
Answer: Let $f(x) = a -2x +(2x-aN) e^{-a \over x}$. $\lim_{x \to \infty} f(x) =
\lim_{x \to \infty} \left( a(1-Ne^{-a \over x}) + 2x(e^{-a \over x} - 1)\right)= -a(1+N)$ (using l'Hôpital), $\lim_{x \downarrow 0} f(x) = a>0$.
$f'(x) = -e^{-a \over x} \left( {{a}^{2}N+2{x}^{2}{e}^{\frac{a}{x}}-2{x}^{2}-2ax \over x^2} \right)$.
For positive $x$, we have $2x^2(e^{a \over x}-1) \ge 2 ax$, hence $f'(x) < 0$. The result follows.
Comment: That was sloppy of me.
Comment: Thanks for a prompt solution. Have a nice weekend.
Comment: You are very welcome!
Answer: Hint
The equation represents the intersection of two monotone functions $$f(x)=\frac{2ax-a^2}{2ax-a^2N}=\frac{2x-a}{2x-aN}$$ $$g(x)=e^{-a\over x}$$ You find $f(0)=\frac{1}{N} \gt 0$ and $g(0)=0$. On the other side, the derivatives are  $$f'(x)=-\frac{2 a (n-1)}{(2 x-a n)^2} \lt 0$$ $$g'(x)=\frac{a e^{-\frac{a}{x}}}{x^2} \gt 0$$
I am sure that you can take from here.
Comment: Another approach. Thanks a lot.
Comment: You are very welcome ! Cheers :)