Cloudflare country code for language negotiation

Question: Cloudflare.com provides CF_IPCountry http header.
This can be retrieved in php with
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

as they say. It'll return XX if the country cannot be determined.
How can this header be used to negotiate language?
(I want to use it so that if users come for example from France, then to be redirected t www.site.com/fr/ homepage, and if they come for any other country in the world go to www.site.com/en/ homepage?)
My research:
There are 2 modules for Drupal 7, but I don't think they can do what I want.
One module is http://drupal.org/project/ip2locale, which is dev version and not updated for a year, and the other is http://drupal.org/project/smart_ip, which says it breaks caching because it adds session variable.
They both don't use cloudflare as source of ip.
Is there any php snippet that I can add somewhere, so that $_SERVER["HTTP_CF_IPCOUNTRY"] takes me to the locale I want?
If you ask me why I want to use cloudflare header, I suppose that maybe it's faster to determine country and more updated with ips, than other free solutions.
Thanks
Answer: Drupal provides a hook for those module that implements a new method for detecting the language to use: hook_language_negotiation_info(). This hook gets information about some callbacks, including the one that returns the language ID.
As example of hook, you can look at locale_language_negotiation_info(), and to the three callbacks used for the first provider: locale_language_from_url(), locale_language_switcher_url(), and locale_language_url_rewrite_url().
Any provider the modules implement are listed on admin/config/regional/language/configure, where the administration user can enable each of them.

The providers that are enabled are called to provide a language ID. For what I can understand code similar to the following one should work.
function mymodule_language_negotiation_info() {
  $providers = array();

  $providers['mymodule_cloudflare_provider'] = array(
    'callbacks' => array('language' => 'mymodule_language_from_cloudflare'),
    'weight' => -4,
    'name' => t('Cloudflare'),
    'description' => t("Use Cloudflare to detect the language used where the user is actually located."),
  );

  return $providers;
}

function mymodule_language_from_cloudflare($languages) {
  if (isset($_SERVER["HTTP_CF_IPCOUNTRY"])) {
    $langcode = mymodule_get_langcode($_SERVER["HTTP_CF_IPCOUNTRY"]);
    if (isset($languages[$langcode])) {
      return $langcode;
    }
  }

  return FALSE;
}

mymodule_get_langcode(), the function for which I didn't write the code, should return the language code from the country code returned from Cloudflare.com.
Answer: This module looks to provide some of that functionality:
https://www.drupal.org/project/language_header
It doesn't do the mapping between country code -> language code however :(


Confusion surrounding differentiation of parameter vector ridge regression

Question: Let $\mathbf{\beta}$ be the parameter vector of a ridge regression.
Now we can say that:
\begin{equation}
\frac{\partial \lambda \beta^T \beta}{\partial \beta}=2\lambda\beta.
\end{equation}
Why is this?
I thought that $$\frac{d}{dx} x^t x = 2x^t$$
Which would imply that:
\begin{equation}
\frac{\partial \lambda \beta^T \beta}{\partial \beta}=2\lambda\beta^{T}.
\end{equation}
Comment: See https://stats.stackexchange.com/questions/257579 and, also, search our site for [matrix cookbook](https://stats.stackexchange.com/search?q=matrix+cookbook).  The thread at https://stats.stackexchange.com/questions/234024/question-with-matrix-derivative-why-do-i-have-to-transpose/234071#234071 looks particularly useful concerning the transpose.
Answer: Both are correct based on which layout notation (i.e. numerator or denominator) is being used. Unfortunately, this is not explicitly stated in most sources and you need to infer it.


How to forecast intermittent demand when the future days with 0 demand are known in advance

Question: I have an intermittent time series of the demand of some products. I have read some very useful answers (such as Forecasting Intermittent Demand with zeroes in times series ) as to how one would go about predicting such time series.
In my case though I know already which periods in the future will have no demand as I know days when the products will not be available in the shops.
How would one incorporate this information in the prediction? Should I use something like the croston method and just set to 0 the periods when I know that the demand will be zero? This seems to me like it wouldn't be using all the available information
Comment: Are sales always (or at least almost always) nonzero when product is available?
Comment: Yes there are almost always non-zero
Comment: @StephanKolassa turns out that in some of the time series can also be zero when the product is available. Would you have any suggestions for this case? I can rephrase the question or open a new one if you would find that preferable. Thank you!
Comment: In that case I would take a look at negative binomial regression. The eponymous textbook by Hilbe is very good.
Answer: First of all, it makes sense to treat historical zeros due to stockouts separately. (These do not represent unconstrained demands.) I would simply remove these historical periods from the training data so they do not bias your predictions for in-stock periods.
This means that methods that rely on the time series having no "holes", like ARIMA or Exponential Smoothing, will have a problem. So I would go with a simple regression with seasonal dummies, possibly a trend predictor, and predictors for all other drivers like promotions. Use OLS for fast selling products, and some kind of negative binomial regression for slower movers.
If this is a problem, you could also use Boolean predictors for historical stockouts and use a forecasting method that incorporates regressors, like ARIMAX or regression with ARIMA errors.
In forecasting, just forecast with your model. If you know there will be no product, overwrite the forecast with a zero.
This should do as a first pass. You can later elaborate. Perhaps if your product is out of stock, people shift demand to other products (so you might model substitution effects on other products), or they postpone buying the product (so you might model higher demand right after stockouts). If stockouts can be anticipated by the customer, they might even pull demand forward in time.
Comment: That was really helpful, thank you! Regarding the seasonal dummies, can I still incorporate it in the model even though my time-series will be irregular after removing the historical zeros? For example I might remove more Mondays that Tuesdays
Comment: Yes, you can. Just include one dummy for each day of the week (minus one so you are not overparameterized). Your software should convert a factor variable DayOfWeek automatically into the appropriate number of dummies. And it doesn't matter if one dummy is 1 more often than another one.


pegar valor de uma variável JS e colocar em um input value

Question: estou querendo pegar um valor de uma variável javascript e colocar dentro de um input value pra enviar via get.
Meu JS esta assim:

$(window).load(function() {
  var count = 10;

  $('a[name=alex]').click(function() {
    document.getElementById("resultado").innerHTML = "" + count + "";
    count += 10;
  });

});

Pontuação

000

  <input type="text" value="resultado" id="resultado">

Não estou conseguindo colocar o resultado no value, esta mostrando perfeito, mas, no input não pega.
Answer: A propriedade innerHTML serve pra escrever ou retornar o conteúdo de um elemento HTML, no caso o atributo que queres mudar é o value
document.getElementById("resultado").value = count;

Veja funcionando

$(window).load(function() {
  var count = 10;

  $('a[name=alex]').click(function() {
    document.getElementById("span").innerHTML = "" + count + "";
    document.getElementById("input").value = count;
    count += 10;
  });

});

Pontuação

000

  <input type="text" value="resultado" id="input" name="resultado">
  teste

Outros adendos:

O atributo id é vinculado a apenas um elemento em cada pagina html;
Se por acaso quiser trabalhar do mesmo modo com elementos que sejam do mesmo tipo, deve usar document.getElementsByName("name_do_elemento") ou ainda document.getElementsByClassName("name_da_class") que são meios mais genéricos de pegar múltiplos elementos que possuam mesmo nome ou mesma classe, respectivamente;
Deves ainda levar em conta que cada elemento se trabalha de uma forma, inputs do tipo texto se altera o valor para se obter o resultado esperado, e não o conteúdo, já elementos do tipo div, ou span, se altera o conteúdo, por exemplo.


Cannot remove border from linked woocommerce product image

Question: I just updated a storefront theme to 2.5.5 for https://bestfamily.gr and I noticed that when I click to a product image or image link a border is displayed.
I put in my css
img.attachment-woocommerce_thumbnail.size-woocommerce_thumbnail.lazyloaded {
    text-decoration: none !important;
    border: 0 none !important;
}

or
a[href$=jpg], a[href$=jpeg], a[href$=jpe], a[href$=png], a[href$=gif] {
    text-decoration: none !important;
    border: 0 none !important;
}

but still nothing. In the previous version of theme no border was shown
I am using imagify and wp-rocket with lazyloading if this helps.
Answer: You have to change the :focus
Try this:
a:focus, button:focus, .button.alt:focus, input:focus, textarea:focus, input[type="button"]:focus, input[type="reset"]:focus, input[type="submit"]:focus, input[type="email"]:focus, input[type="tel"]:focus, input[type="url"]:focus, input[type="password"]:focus, input[type="search"]:focus {
    outline-color: transparent;
}

Comment: any other way to accomplish it?
Comment: You can use `outline-color: unset;` Also you don't have to remove it from all elements keep the ones you want to appear


Order is not geting created, but transition is happening in cart

Question: I am doing an Offsite redirection payment with Drupal Commerce.
I have a custom payment workflow defined in my_module.workflow.yml as follows:
order_linktypeplus_validation:
  id: order_linktypeplus_validation
  group: commerce_order
  label: 'linktypeplus order workflow'
  states:
    draft:
      label: Draft
    pending:
      label: Pending
    completed:
      label: Completed
    canceled:
      label: Canceled
  transitions:
    place:
      label: 'Place order'
      from: [draft]
      to: pending
    fulfill:
      label: 'Fulfill order'
      from: [draft, pending]
      to: completed
    cancel:
      label: 'Cancel order'
      from: [draft, pending]
      to: canceled

So as per this when the order is placed, First order will be moved to the Pending state (which is working fine). And for some orders, I need to get it completed without the pending state (ie. from draft to completed)
I was doing this in my controller after offsite payment had been successfully done and returned to the site:
 $order->unlock();
 $order->setData($paymentGateway, $data);
 if ($order->getState()->getId() != 'completed') {
      $order->getState()->applyTransitionById('fulfill');
  }
 $order->save();

When I checked in the cart tab next to orders, the item was still in the cart. but its status says Order moved from Draft to Completed by the Fulfill order transition. But the order is not created.
Any idea on how to resolve this issue?
Answer:
But the order is not created.

What do you mean by that? The order in your screenshot has the completed state?
Comment: The screenshot is of the `Cart` tab. The order tab is not showing this. The `Completed` state is showing is for payments(i guess)


Node.js DNS lookup - how to set timeout?

Question: I'm very new to Node.js and I'm having an issue using node.dns.resolveNs function.
Some domains are completely down and it takes about a minute to get the response, which is usually "queryNs ETIMEOUT". Is there a way for me to set it to a shorter period, for example 10 seconds?
Comment: searching npm I also found https://github.com/tjfontaine/node-dns which also supports timeouts....?
Comment: Consider this more recent package instead which isn't deprecated: https://github.com/mafintosh/dns-socket
Answer: I am not sure of any way to set a timeout directly on the function call, but you could create a small wrapper around the call to handle timing out yourself:
var dns = require('dns');

var nsLookup = function(domain, timeout, callback) {
  var callbackCalled = false;
  var doCallback = function(err, domains) {
    if (callbackCalled) return;
    callbackCalled = true;
    callback(err, domains);
  };

  setTimeout(function() {
    doCallback(new Error("Timeout exceeded"), null);
  }, timeout);

  dns.resolveNs(domain, doCallback);
};

nsLookup('stackoverflow.com', 1000, function(err, addresses) {
  console.log("Results for stackoverflow.com, timeout 1000:");
  if (err) {
    console.log("Err: " + err);
    return;
  }
  console.log(addresses);
});

nsLookup('stackoverflow.com', 1, function(err, addresses) {
  console.log("Results for stackoverflow.com, timeout 1:");
  if (err) {
    console.log("Err: " + err);
    return;
  }
  console.log(addresses);
});

The output for the above script:
Results for stackoverflow.com, timeout 1:
Err: Error: Timeout exceeded
Results for stackoverflow.com, timeout 1000:
[ 'ns1.serverfault.com',
  'ns2.serverfault.com',
  'ns3.serverfault.com' ]

Comment: Really, I liked it so much, I am adapting it so that the callback can be generic, and it can become a neat way to call any network call with a custom timeout...
Comment: You have to be careful about the number of concurrent requests (as you don't really timeout them, this is just an emulation).
Answer: Node.js dns.resolve* use c-ares library underneath, which supports timeouts and various other options natively. Unfortunately Node.js doesn't expose those tunables, but some of them can be set via RES_OPTIONS environment variable.
Example: RES_OPTIONS='ndots:3 retrans:1000 retry:3 rotate' node server.js

ndots: same as ARES_OPT_NDOTS
retrans: same as ARES_OPT_TIMEOUTMS
retry: same as ARES_OPT_TRIES
rotate: same as ARES_OPT_ROTATE

See man ares_init_options(3) for details what each option means, for instance here http://manpages.ubuntu.com/manpages/zesty/man3/ares_init_options.3.html
Comment: This should be marked as the best answer IMO. Thank you @redbaron! Tuning this parameters have reduced my AWS lambda execution time from ~5 minutes to 30 seconds.
Comment: Now its possible to set timeout and tries. https://nodejs.org/api/dns.html#resolveroptions
Comment: It seems this env var can affect more than just dns.resolve - I tried setting it to reduce occasional DNS timeouts and found that it prevented my app from connecting to MongoDB successfully. Use with care.
Answer: Also it good to know that lookup may block your application.
We developed a module that replaces/extends node's dns.lookup method. The main goal is to bypass issues with blocking of thread pool. So module caches responses, has multi-records resolving and TTL support. Also we have good unit and functional tests with 100% coverage. Module was tested in production and highload environments. Under MIT license.
Here it is: https://github.com/LCMApps/dns-lookup-cache
I believe it may help!
Answer: The latest Node.js (starting from v14.x) does support configuring timeout while resolving DNS.
Sample Code:
const {Resolver} = require('dns').promises;
const dnsResolver = new Resolver({timeout: 250, tries: 2});

dnsResolver.resolve('invalid-example.com').then(function(records) {
    console.log('dns response', records);
}).catch(e => {
   console.log('Exception in dnsResolver', e);
})

Reference: NodeJS Docs
Comment: How is this not the accepted answer?
Answer: building upon @redbaron's answer, you can set the RES_OPTIONS variable during runtime to set the timeout for the c-ares library used by dns.resolve*:
// this will timeout for (1000 * 3 * 2) ms
process.env.RES_OPTIONS='ndots:3 retrans:1000 retry:3 rotate';

Answer: Wrapper for resolveNs with timeout:
const dns = require("dns");

const nsLookup = (domain, timeout) => {
  return new Promise((resolve, reject) => {
    let finished = false;

    const timer = setTimeout(()=>{
      finished = true;
      reject();
    }, timeout);

    const callback = (_err, result) => {
      clearTimeout(timer);
      if (!finished) resolve(result);
    };

    dns.resolveNs(domain, callback);
  });
};

Answer: Use the Resolver object, which takes a timeout params in it's constructor args...
e.g.
const { Resolver }= require('dns').promises;

const yourTimeout = 5000; // milliseconds

const resolver = new Resolver({timeout: yourTimeout});

const response = await resolver.resolve('www.google.com');

Comment: Doesn't work as expected on Windows though. On MacOS works just fine.


Constructing two non-isomorphic irreducible $\mathbb Q[x]$ modules with the underlying abelian group $\mathbb Q\times\mathbb Q$.

Question: I'm trying a problem which asks me to construct two non-isomorphic irreducible $\mathbb Q[x]$ modules with the underlying abelian group $\mathbb Q\times\mathbb Q$. I've managed to prove (using isomorphism theorem) that irreducible modules are  $\mathbb Q[x]/I$ with maximal ideals $I$. So I take the ideals $I_1=(x^2-2), I_2=(x^2-3)$. Then $\mathbb Q[x]/I_1$ and $\mathbb Q[x]/I_2$ are irreducible and also not isomorphic because any isomorphism will yield an isomorphism between $\mathbb Q(\sqrt 2)$ and $\mathbb Q(\sqrt 3)$.
My question is: Is the above argument ok? Also how do I rigorously argue for the part concerning the underlying groups? My modules are 'isomorphic' to $\mathbb Q(\sqrt 2)$ and $\mathbb Q(\sqrt 3)$, and intuitively the groups are $\mathbb Q\times\mathbb Q$ since any element in, say, $\mathbb Q(\sqrt 2)$, can be seen as an ordered pair $(a,b)$ or rationals. But how do I make this precise?
Answer: Your choice is perfectly fine. For the isomorphism of abelian groups, you know that the residue classes of $1,x$ form a $\mathbb Q$-basis of $\mathbb Q[x]/(x^2-2)$, i.e. we have an isomorphism $\mathbb Q[x]/(x^2-2) \cong \mathbb Q^2 = \mathbb Q \times \mathbb Q$ as $\mathbb Q$-vector spaces, in particular of abelian groups.
You could also look at this from the following perspective:
A $\mathbb Q[x]$-module structure of $\mathbb Q^2$ is the same as an endomorphism of $\mathbb Q^2$ i.e. 2x2-matrix. The module is irreducible iff the characteristic polynomial is irreducible. You picked the matrices $\begin{pmatrix}0&2\\1&0\end{pmatrix}$ and $\begin{pmatrix}0&3\\1&0\end{pmatrix}$.


What is the difference between Non-Negative Matrix Factorization (NMF) and Factor Analysis (FA)?

Question: I am performing an Exploratory Factor Analysis (EFA) for a multivariate dataset, where variables are all measurements of the same physical measure, only in different locations in space.
My purpose is to extract a few latent variables (i.e., factors) that can possibly be interpreted as common sources causing the observations, and then to use these factors for future analysis (after assigning each factor to a "source").
EFA works pretty well, but I can get also negative factor scores, which I am not sure are physical solutions. I came across PMF (Positive Matrix Factorization) or NMF/NNMF (Non-Negative Matrix Factorization) and was wondering if it makes sense to use it for my purpose as well.
What would be the difference between the two algorithms?
For instance, the decomposed matrix I get with NMF (W) is quite similar to the factor scores I get with EFA (only there is a certain stochastic behaviour).
Yet, I can't understand a few things:

In EFA, the factor scores are normalized signals. What units is the decomposed W matrix? is it in the same units of my measurements?

If running NMF with different seeds produces different solutions, what solution should I take? should I run it many times?

If (1) is true, can I use the W matrix in the same way I intended to with my factor scores? (i.e., each column in W matrix would be the factor scores of a "common factor"?)

Would be great to get some help...
Comment: Have you tried PCA?
Comment: No, just Factor Analysis. I'm not sure I want to use PCA. Why are you asking?
Comment: If you're looking to reduce the dimensionality of the data it's a good place to start. It's basically the same as taking the SVD, another matrix decomposition, of centered and scaled data.
Comment: I will edit my question, since it seems like it wasn't clear... I don't necessarily want scaled data, I was just wondering what are the differences between the two methods
Answer: NMF/PMF are typically used to make low-rank decompositions. They can be used like a truncated SVD, just for dimension reduction. They can also be used like factor analysis, to attempt to identify latent variables that theory says underly the data.
A truncated rank-$k$ SVD asks for the best decomposition of the data matrix $X$ into $UDV^T$ where $U$ and $V$ have $k$ orthonormal columns and are chosen to minimise the  sum of squared errors in  reconstructing the elements of $X$.  An approximate NMF decomposes $X$ as $GH^T$ where $G$ and $H$ have $k$ columns and all the entries are non-negative.  There are also sparse  NMF algorithms that (surprise!) additionally make the factors sparse.
One classic application of NMF/PMF is in analytic chemistry.  For example, in particulate air pollution research,  $X$ may be a matrix whose $(s,t)$ entry is the mass concentration of chemical species $s$ at measurement time $t$. The decomposition of rank $k$ corresponds to a model with $k$ sources of particles, with $G_{sk}$ being the percentage concentration of species $s$ in source $k$ and $H_{kt}$ the mass concentration of particles from source $k$ at time $t$. Clearly these  will be non-negative.  Ideally $G$ will be somewhat sparse -- you would like to measure species that are, if not unique to a source, at least specific to a group of sources
[Update: even in this application the interpretation of $G$ and $H$ does depend on how they are scaled. It's always true that $G$ is species-source information and $H$ is source-time information, but getting $H$ to be mass concentrations requires scaling the rows of $H$ to sum to total particle mass concentration]
PMF (at least, the software of that name) does a non-negative decomposition but optimises a user-specified weighted sum of squared errors in reconstruction, where the weights are based on assay error either (preferably) known previously or (typically) estimated from replicates.   This is a harder problem computationally. The software also allows constraints on the estimated decomposition -- eg, that species $7$ is found only in source $3$, or that the concentration of species 2 in source 4 is greater than 5%.
In air pollution analysis PMF (especially) is often seen as estimating the true sources, the way factor analysis estimates latent variables. In some ways it does better than factor analysis, since the non-negativity constraints reduce the non-identifiability (rotational freedom) of factor analysis.
But you can run PMF/NMF on data without having any theoretical commitment to any specific model for latent variables, which would be  undesirable for factor analysis.  For example, NMF has been used in text mining for clustering documents without specifying cluster:word relationships in advance, and in the Netflix prize competition for clustering movies.
Comment: In that context, yes. If you get $X_{st}$ from X-ray fluorescence, for example, you don't get good values for  any element lighter than aluminium. You might get a separate estimate of carbon, but even so the percentages in $G$  don't add up to 100%
Comment: Thanks a lot for the detailed answer. "getting  to be mass concentrations requires scaling the rows of  to sum to total particle mass concentration" means that I include any error/uniqueness which is not due to "sources" within H?


Reinstall a patch with composer - update one module only

Question: Can I update a patch without running composer update ? In other words: can I update one module only?
Answer: Yes, use the following:
composer update --prefer-source drupal/menu_block


node_save does not save language

Question: I cannot programmatically create a node in anything other than en language.
My site has 3 languages:

en
fr
de

And the code for creating a node is:
define('DRUPAL_ROOT', ...);
require_once DRUPAL_ROOT . 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$node = new stdClass();
$node->type = "foobar";
node_object_prepare($node);
$node->title = 'test title';
$node->uid = 1;
$node->language = 'fr'; // *** this doesn't seem to work

if ($node = node_submit($node)) {
  node_save($node);
}

No matter what I type in the $node->language = '...'; the result is always the same. The node is created in the English language. I confirm that via looking at admin/content.
I've even tried stuffing this variable with a proper language object which I got out of the enabled languages of my site:
$languages = language_list('enabled');
$lang = $languages[1]['de'];
$node->language = $lang;

Comment: As side note, `node_submit()` always returns the parameter passed to the function; there is no need to check the value returned from the function.
Answer: The behavior was an unfortunate side-effect of the admin_language module and the setting Force use of default language.
The "offending" code is at http://drupalcode.org/project/admin_language.git/blob/0167e36c45661502ee6907a5b2b7cad8538b19cf:/admin_language.module#l112
Disabling this options solves the issue.
Answer: Some of the hooks might not be firing, instead of node_save($node), try drupal_execute($form_id, $form_state)
That last link was bad... lullabot's should help:
http://www.lullabot.com/articles/quick-and-dirty-cck-imports
doh... drupal 7. Looks like they have changed it to drupal_form_submit
http://www.lukaswhite.com/blog/post/2011/drupal-7-drupal_execute-has-gone-say-hello-to-drupal_form_submit
Comment: Thanks for the answer. I've seen that sometimes people do suggest `drupal_form_submit` instead of `node_save` but I'd really like to know if and how this simple task (saving non English) can be achieved with `node_save`.

node_save does not save language


How to organize lots of data and extract information

Question: I am working in a project where I need to extract data from lots of files provided to me in different formats (.exe, .doc, .txt, .dbf, and even .pdf). The data I am interested in are water quality and hydrological variables measured at different sites, with different periodicities (monthly, daily, hourly) and sometimes at different depths. The organization of the files is not easy either. For example, some Excel files contain several tables in the same sheet.
So, I need some software, R package or Python module that can help me organize this mess and extract the relevant data. What do you suggest?
Comment: I somewhat doubt that a single package or even several packages will solve this problem.  You'll probably need to combine many tools in a fairly ad hoc manual way.  You may want to ask a more specific question since general advice will not be very helpful.
Comment: If you're looking for a single thing that will extract and prep all your data, you're looking for an assistant that you can assign the job to. You can code your own solution if you know a programming language (and can compile code on your computer), or you can extract the data from each file manually. Which of those is better/easier will depend on the skills you already have, how diversely formatted your tables are, and how many tables you need to process.
Comment: @Upper_Case : Well, actually I hoped to avoid that. My ideal software would analyse all the entry files to see which blocks of data had similar structure and held similar kinds of data. Helpful if it extracted tables from doc files and found repeated blocks of data, too. Then I could take over to tell the program how to parse the data from the different types of structure, and let it do the job. With all this big data thing I thought someone would already have done something similar...
Comment: @Iodebari: Things like that have definitely been done, but not necessarily in an implementation that will meet your needs right out of the box and that is available to you. There's no harm in looking for something like that, of course, but the specific data you're looking to extract and the specific formats and layouts of the files may or may not match any existing, publically available solution.
Answer: I would use MySQL to organize the data and then access it through R or Python (see RMySQL package for R or MySQLdb for Python). MySQL allows you to structure and manage your complex data, and for the actual statistical analysis you can fetch only the data you need.
To complete the answer (thanks to @Ian_Fin for the observation): For data extraction I think you need to create a php/java program to parse your different files and then save them to the database.
Comment: @Ian_Fin: I doubt there is a solution in, say R, for the variety of formats lodebari indicates. My solution was related to the way s/he "can organize the mess". For data extraction probably s/he needs to create a php / java program to parse them and then save them to the database.


Find $\lim_{x\to-\infty}\frac{x}{\sqrt{x^2+2}}$

Question: Find $\displaystyle \lim_{x\to-\infty}\frac{x}{\sqrt{x^2+2}}$ without a calculator.
L'Hopital's rule only gives me the limit for one side. Not two. How would I solve this problem?
Answer: It is clear that our function $f(x)$ is negative when $x$ is negative.  Let $g(x)=(f(x)^2$. Is the value of
$$\lim_{x\to -\infty}g(x)$$
obvious? What can we conclude about our problem?
Answer: Noting that $x\lt 0$, we have$$\lim_{x\to -\infty}\frac{x}{\sqrt{x^2+2}}=\lim_{x\to -\infty}\frac{-(-x)}{\sqrt{x^2+2}}=\lim_{x\to -\infty}-\sqrt{\frac{(-x)^2}{x^2+2}}=\lim_{x\to -\infty}-\sqrt{\frac{1}{1+(2/x^2)}}=-1.$$
Answer: One definition of the absolute value function is $|x| = \sqrt{x^2}$.  For negative values of $x$, observe that
$$\frac{x}{|x|} = \frac{x}{-x} = -1$$
Thus,
\begin{align*}
\lim_{x \to -\infty} \frac{x}{\sqrt{x^2 + 2}} & = \lim_{x \to -\infty} \frac{x}{\sqrt{x^2\left(1 + \dfrac{2}{x^2}\right)}}\\
& = \lim_{x \to -\infty} \frac{x}{|x|\sqrt{\left(1 + \dfrac{2}{x^2}\right)}}\\
& = \lim_{x \to -\infty} \frac{x}{|x|} \lim_{x \to -\infty} \frac{1}{\sqrt{\left(1 + \dfrac{2}{x^2}\right)}}\\
& = -1 \cdot \frac{1}{\sqrt{1 + 0}}\\
& = -1 \cdot 1\\
& = -1
\end{align*}
Answer: Notice that in this case $\sqrt{x^{2}} = -x$, for $x<0$. Then
$lim_{x\to - \infty}=\frac{x}{\sqrt{2+x^2}} = lim_{x \to -\infty} = \frac{x}{-x\sqrt{\frac{2}{x^2}+1}} = lim_{x \to -\infty}\frac{-1}{\sqrt{\frac{2}{x^2}+1}} = -1$
Answer: Here's an answer that's no better than those of André Nicolas and mathlove.
First, notice that $x=\text{sgn}(x)|x|$, where $\text{sgn}(a)$ is $-1$, $0$, or $1$ depending as $x$ is negative, zero, or positive. Second, notice that $|x|=\sqrt{x^2}$. So we have
$$
\frac x{\sqrt{x^2+2}}=\text{sgn}(x)\frac{\sqrt{x^2}}{\sqrt{x^2+2}}\,.
$$
Now combine the two radicals (which is all right to do, because both radicands are nonnegative), to get a rational expression inside, whose limit at $\pm\infty$ is $1$.


How could I add NAT with private subnet to this Cisco 2500 config?

Question: There's this Cisco 2500 with one V.35 port going to an HDSL DCE, and the ethernet port to a Cisco PIX; there are also other IPs (subnet 80.something) in the configuration on the serial side that are used to route traffic to the DSL provider.
I'm wondering if it is possible to remove the PIX and move everything on the Cisco 2500 - I can usually manage to do this when the public IP is on the wan-facing port and the private IP on the lan one, but I don't know how could I add a private IP to the 2500 and use the public one for nat when they're both on the same internal interface.
The current config for the 2500 looks like:
<code>ip subnet-zero
!
interface Ethernet0
 description connected to PIX
 ip address 217.x.x.1 255.255.255.248
 ip nat inside
 no ip directed-broadcast
 no ip mroute-cache
 no cdp enable
!
interface Serial0
 no ip address
 no ip directed-broadcast
 no ip mroute-cache
 encapsulation frame-relay
 bandwidth 1024
 no cdp enable
!
interface Serial0.1 point-to-point
 ip address 80.x.x.x 255.255.255.252
 ip nat outside
 frame-relay interface-dlci xxx IETF
 bandwidth 1024
 no ip directed-broadcast
 no cdp enable
!
ip classless
ip route 0.0.0.0 0.0.0.0 Serial0.1
</code>
The PIX has 217.x.x.2 on its WAN interface and uses the 2500's 217.x.x.1 as default gateway.
I would like to remove the PIX and connect the LAN directly to the Cisco 2500, which would have 192.168.1.1/24 on its Ethernet port and NAT everything out from one of the 217.x.x.X IPs. After that I will probably want to also add other static IPs to the Cisco from the 217.x.x.X/29 subnet and use them to portforward some services to internal servers.
Answer: There's lots of documentation on cisco.com about NAT services.
Try starting at:
http://www.cisco.com/en/US/partner/prod/collateral/iosswrel/ps6537/ps6586/ps6640/prod_qas0900aecd801ba55a.html
As a general guide, you would want 'ip nat outside' on s0/0.1, 'ip nat inside' on e0.
You would make a NAT pool using your 217.x.x.1/29 addresses, that things on the inside could use.  They would not appear on an interface anymore.


JQUERY Further More Ordering DIV's A-Z

Question: I just asked a question about ordering but it was only the first part of what I needed. I want to ask the full question now to see if its possible:
Its for a chat webpage and users can be online (active), offline (noactive) or have a message pending (msg) or no message pending (nomsg). Also keep the ID name in mind for A-Z
eg:

Is it possible to order this as follows:
1. active msg (A-Z)
2. active nomsg (A-Z)
3. noactive msg (A-Z)
4. noactive nomsg (A-Z)
thx
Answer: The most basic way to do this would be to create 4 arrays (one for each case of active/msg), and separate the divs into those arrays. Then, sort each array. Lastly, either write the divs to the page in order of the arrays, or combine them into one array and write that one to the page. This allows you, if you later decide to, to change the ordering of active vs inactive/msg vs no message by simply swapping a couple lines.

JQUERY Further More Ordering DIV's A-Z


Drupal Rest Service - Create node problem

Question: I'm using POSTER add-on (Firefox) to create a node.(REST service). I couldn't able to create node having select/checkbox item. Getting following error in response.
["An illegal choice has been detected. Please contact the site administrator"]
How to resolve this? I'm able to create node if post data doesn't contains select/checkbox data. My problem is exactly related to the following link. But I couldn't find solution.
drupal 7 + services 3 - inserting nodes with select fields
If I replace 'und' to 'en' in json format, the node is being created but with null values.
I've found following messages under Recent log messages.
Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain()
Warning: Illegal offset type in isset or empty in list_field_validate()
Illegal choice in LABEL element.
Here 'LABEL' is the label(name) of the filed
Answer: Yes.. finally I got solution for my problem. Here is the solution.
In JSON format, Here is the correct way to handle LIST type fields
"field_select_options":{"und":["4"]}
(Initially I tried "field_select_options":{"und":[{"value":"4"}]} which results error in response.)
Thanks, I got the solution from https://drupal.org/node/1971484


Refresh a um div

Question: Estou com problemas em aplicar na minha plataforma o seguinte código Javascript:

Porque a
 em questão ta num ficheiro aparte e faço include dela em todas as páginas ou seja nunca irei saber qual é a página em que o script irá correr e no código em cima tenho que especificar uma página ex: index.php
Comment: O que é que não funciona? podes descrever o problema?
Comment: O problema e que como não sei em que pagina vou estar o scricpt nunca chega a correr pq tenho que lhe dizer qual e a pagina actual como pode ver no codigo `load("index.php #refresh");`
Comment: :/ ainda não percebi. Essa string que passas ao .load() deve ser diferente dependendo que em que página está?
Comment: sim onde esta `index.php` deve ser a o nome da pagina ponto a sua extensão
Comment: Podes dar um exemplo de como são os urls das páginas ?
Comment: por exemplo `home.php` , `avisos.php`
Answer: Uma maneira fácil é a de atribuir uma variável no arquivo principal (antes da inclue), em seguida, fazer referência a essa variável no arquivo incluído.
Parent File:
$myvar_not_replicated = __FILE__; // Make sure nothing else is going to overwrite
include 'other_file.php';

Included File:
if (isset($myvar_not_replicated)) echo "{$myvar_not_replicated} included me";
else echo "Unknown file included me";

Answer: Se compreendi bem queres usar nesta string $scores.load("index.php #refresh") o nome do ficheiro da página que tens no url.
Por exemplo o url/página dominio.com/home.php deve fazer com que o .load() vá buscar "home.php #refresh".
Para fazeres isso podes usar uma expressão regular, filtrando esse nome:
var nome = window.location.href.match(/\/(\w+)\.php/);
if (nome) nome = nome[0];

e depois usar esse nome no .load() assim:
var nome = window.location.href.match(/\/(\w+)\.php/);
if (nome) nome = nome[0];
var $scores = $("#refresh");
setInterval(function() {
    $scores.load(nome + " #refresh");
}, 30000);

Podes ver a regex aqui (link), o que ela procura é por uma barra \/ seguida de 1 ou mais letras capturando-as (\w+), e que seja seguido de .php.
Testa o código e diz se funciona como queres.
Comment: Funciona sim senhor obrigado

Refresh a um div


Simplify a sum of n products

Question: Given the following sum formula:
$\sum\limits_{i=1}^{n} (i\cdot 2^{n-i}) $
Can you help me out to a simplify the formula and provide an formula without a Sigma sign?
I know that I cannot just split the Sigma like that:
$\sum\limits_{i=1}^{n} (i\cdot 2^{n-i}) \ne (\sum\limits_{i=1}^{n} i) \cdot (\sum\limits_{i=1}^{n}2^{n-i}) $
I am wondering if there is something else I can do
Comment: Expressions of this sort can be analyzed via geometric series.  For an infinite version, note that $f(x)=\frac {1}{1-x}=\sum_{i=0}^{\infty} x^i$ and differentiation yields $f'(x)=\sum_{i=1}^{\infty} ix^{i-1}$ which is akin to yours (you'll need to work with partial sums for the geometric series, of course).
Comment: Already asked zillion times.
Comment: Let the sum be $S$. Calculate $S = 2S - S$ by rearranging indices.
Comment: Did you write it correctly?  As written it is just $2^{n-1}\times \sum_{i=1}^ni$
Comment: @lulu sorry, there was a mistake in the question. I have edited the question. Thanks for the heads up
Comment: This is not a sum of $n$ products. It is a sum of products where the first term consists of $n$ products.
Answer: Hint:
$$1\cdot2^{n-1}+2\cdot2^{n-2}+\cdots n\cdot2^0
\\=0\cdot2^{n-1}+1\cdot2^{n-2}+\cdots (n-1)\cdot2^0+2^{n-1}+2^{n-2}+\cdots2^0
\\=\frac{1\cdot2^{n-1}+2\cdot2^{n-2}+\cdots n\cdot2^0}2-\frac{n\cdot2^0}2+2^n-1.$$
Comment: It looks great to me.
Comment: why was this hint downvoted ?? +1
Comment: +1 for encouraging the OP to attempt and improve. Just in case, I never downvoted this post.
Comment: Is there anything wrong with this hint ??
Comment: @YvesDaoust Thanks for the hint! So there is a small arithmetic sequence for every item in the main sequence! Huh! never thought about that
Comment: Maybe personal attack here…?
Comment: @Stasel: I am not sure to understand what you mean.
Answer: Following xbh's hint:
$$S=\sum\limits_{i=1}^{n} (i\cdot 2^{n-i})=\color{red}{1\cdot 2^{n-1}}+2\cdot 2^{n-2}+\cdots+\color{blue}{(n-1)\cdot 2^1}+n\cdot 2^0\\
2S=2\sum\limits_{i=1}^{n} (i\cdot 2^{n-i})=1\cdot 2^{n}+\color{red}{2\cdot 2^{n-1}}+\cdots+(n-1)\cdot 2^2+\color{blue}{n\cdot 2^1}.$$
Subtract $2S-S$:
$$S=2^n+\color{red}{2^{n-1}}+\cdots+\color{blue}{2}-n=\frac{2(2^n-1)}{2-1}-n=2^{n+1}-2-n. $$

Simplify a sum of n products


Consulta por mês e ano (Php + SQL)

Question: Tenho um sistema em PHP no qual utilizo o plugin do datatables, consigo classificar por data, mas o usuário quer estipular o período para consulta, por exemplo:
Selecionar do dia 01/01/2016 até 31/01/2016 e todos os dados desse período serem exibidos.
Tenho que criar os campos para o usuário selecionar o mês de pesquisa desejado e com isso eu preciso criar uma query para cada mês de um determinado ano que o usuário selecionar ou existe outra forma, o que fazer nesse caso?
Exemplo: Eu teria que fazer uma query para jan, fev, mar, abril.. e por ano 2015, 2016, 2017 e ...?
Answer: O código abaixo ira retornar todos os registros que estão entre esse intervalo de datas
SELECT suascolunas
FROM sau tabela
WHERE colunaData BETWEEN dataInicio AND dataFinal;

Comment: Conheço essa query, a dúvida é como aplicar isso no sistema.
Certamente vou criar dois campos do tipo data para o usuário selecionar o período que deseja, após isso envio as informações digitadas para essa query? Seria isso?

     `SELECT suascolunas

     FROM sau tabela

     WHERE colunaData BETWEEN $dataInicio AND $dataFinal;`
Comment: Só vi agora a mensagem. Isso mesmo, esta correto. Só lembrando que o no sql a data precissa ser assim > 'Y-m-d'
Answer: No MySQL tem uma função chamada Month que você pode usar para buscar algo de acordo com o mês do ano..
Um exemplo:
SELECT nome,endereco
FROM clientes
WHERE Month(data-nascimento) = '06'

No código acima fiz um exemplo para buscar uma lista de aniversariantes do mês de Junho.

Consulta por mês e ano (Php + SQL)


Postfix - Illegal address syntax warning

Question: I have a recurring error message in my postfix logs regarding a malformed address in the RCPT command. presumably because of the questionmark characters (which originaly was a single "é" character.
<code>postfix/smtpd[8315]: warning: Illegal address syntax from localhost[127.0.0.1] in RCPT command: <firstname.lastname@example.com??.com>
</code>
This has been recurring every minute for several days. I've tried restarting postfix, but it pops up again.
I am somewhat of a postfix newbie, so I'm not sure what I need to do. How do I get rid of it? and/or, Is this a problem?
Answer: "é"  is part of the Extended ASCII Char set, not the base ASCII (ISO-8859-1 or ISO Latin1) character set so it needs to be properly encoded to be sent through postfix (or really any MTA)
It looks like the client that is trying to send mail isn't properly encoding the IDN(Internationalized Domain Name). Postfix doesn't support IDNs - SMTP is an ASCII only standard -  encoding of the IDN to ACE (ASCII Compatable Encoding) is a client side issue, not a server side issue.
Comment: Yes, I understand this part. How do I get rid of the message now it seems 'stuck' in the postfix system?
Comment: postfix should've rejected it instantly. If it didn't, find the queue ID in `mailq` and give it to `postsuper -d`. (I have a feeling some program of yours is constantly trying to send that message...)
Comment: thanks grawity, that seems to have been the issue, although I never got to the bottom of it.
Answer: Postfix support codage ASCII; upgrade your Postfix ===> SMTPUTF8


Model Window Shows Same Content

Question: So I'm making a dental website, this page I'm working on is for dental cases. So let's say there are three dental treatments, Dental Implants, Root Canal and Tooth Extraction. I'm developing something like, if someone clicks on Dental Implants, he can see a modal window, for the cases for that particular treatment. When he clicks on one of the cases, he can see a slideshow for that case. It works perfectly, but the only thing is that when I click on the dental implants or fracture case, I'm seeing the same modal window content. I found the code from w3school's website. Is there any way I can have multiple modal windows with different content? Thanks so much.
Screenshot of the window
Answer: I have a large project that use what you want. I'll try to reduce other codes for you understand better. I'll need to include in your bootstrap plugin.
1) Bellow you'll see two pictures with initial image and after click on some image:

2) Html (I insert dynamically all of datas by jquery with request on a server):

            <button type="button" class="close" data-dismiss="modal">×</button>

3) jquery (call for first line carousel and for the second inside modal)
      $(document).ready(function () {
        $('.galeriaImagens').click(function () {
            var descricaoLegenda = $(this).children('div.carousel-caption').children('.fourth-slide-legenda').text();
            var listaLegenda = $('#fith-slide').children('.carousel-inner').children('.item')
                .children('.carousel-caption').children('.fith-slide-legenda');
            $('#fith-slide').find('.item.active').removeClass('active');
            $.each(listaLegenda, function (index, value) {
                if (descricaoLegenda == value.innerText)
                {
                    var selecao = value;
                    $(selecao).parents('.item').addClass('active');
                }
            });
            var totalItems = $('#fith-slide .item').length;
            var currentIndex = $('#fith-slide div.active').index() + 1;
            $('.numSlide5Texto').html('' + currentIndex + '/' + totalItems + '');
            $('#fith-slide').bind('slid', function () {
                currentIndex = $('#fith-slide div.active').index() + 1;
                $('.numSlide5Texto').html('' + currentIndex + '/' + totalItems + '');
            });
        });

        // slide 1 - imagens
        var urlDestino = "";
        var idEnvio = 0;
        var nrReg = 0;
        var idProduto = 0;
        var frente = "S";
        function slide1() {
            $.ajax({
                url: urlDestino,
                type: "POST",
                data: { "id": idEnvio, "idProduto": idProduto, "nrRegistro": nrReg },
                async: true,
                dataType: "json",
                success: function (data) {
                    if (document.getElementById("fourth-slide").getAttribute("produto1-ini") == 0) {
                        if (data.lista.length == 0 || data.lista == "0") {
                            $('#fotos-imovel').hide();
                            $('.fotos-imovel-icone').hide();
                        }
                    }
                    if (data.lista.length == 0)
                        return;
                    if (data == "") {
                        return;
                    }
                    var i = data.lista.length;
                    if (i > 0) {
                        i = i - 1;
                    }
                    var item = document.getElementById("fourth-slide").getAttribute("produto1-seq");
                    if (frente == "N") {
                        var qtdPagina = document.getElementById("fourth-slide").getAttribute("produto1-qtpagina");
                        qtdPagina = parseInt(qtdPagina);
                        item = item - (3 + qtdPagina);
                    }

                    if (i == 2) {
                        item++;
                        $('#produto1-item1').html(item + " / " + data.qtd);
                        $('#produto1-legenda1').html(data.lista[0].Descricao);
                        $('#produto1-imagem1').attr("src", data.lista[0].EnderecoImagem);
                        $('#produto1-imagem1').attr("title", data.lista[0].Descricao);
                        $('#produto1-imagem1').attr("alt", data.lista[0].DescricaoAlternativa);
                        $('#produto1-imagem1').attr("width", data.lista[0].Largura);
                        $('#produto1-imagem1').attr("height", data.lista[0].Altura);
                        item++;
                        $('#produto1-item2').html(item + " / " + data.qtd);
                        $('#produto1-legenda2').html(data.lista[1].Descricao);
                        $('#produto1-imagem2').attr("src", data.lista[1].EnderecoImagem);
                        $('#produto1-imagem2').attr("title", data.lista[1].Descricao);
                        $('#produto1-imagem2').attr("alt", data.lista[1].DescricaoAlternativa);
                        $('#produto1-imagem2').attr("width", data.lista[1].Largura);
                        $('#produto1-imagem2').attr("height", data.lista[1].Altura);
                        item++;
                        $('#produto1-item3').html(item + " / " + data.qtd);
                        $('#produto1-legenda3').html(data.lista[2].Descricao);
                        $('#produto1-imagem3').attr("src", data.lista[2].EnderecoImagem);
                        $('#produto1-imagem3').attr("title", data.lista[2].Descricao);
                        $('#produto1-imagem3').attr("alt", data.lista[2].DescricaoAlternativa);
                        $('#produto1-imagem3').attr("width", data.lista[2].Largura);
                        $('#produto1-imagem3').attr("height", data.lista[2].Altura);
                        $('#produto1-imagem1').parent().show();
                        $('#produto1-imagem2').parent().show();
                        $('#produto1-imagem3').parent().show();
                        $('#fourth-slide').attr('produto1-ini', data.lista[0].IdImagem);
                        $('#fourth-slide').attr('produto1-fim', data.lista[2].IdImagem);
                        $('#fourth-slide').attr('produto1-seq', item);
                        $('#fourth-slide').attr('produto1-qtpagina', 3);
                    }
                    else if (i == 1) {
                        item++;
                        $('#produto1-item1').html(item + " / " + data.qtd);
                        $('#produto1-legenda1').html(data.lista[0].Descricao);
                        $('#produto1-nome1').text(data.lista[0].NomeclienteProduto);
                        $('#produto1-imagem1').attr("src", data.lista[0].EnderecoImagem);
                        $('#produto1-imagem1').attr("title", data.lista[0].Descricao);
                        $('#produto1-imagem1').attr("alt", data.lista[0].DescricaoAlternativa);
                        $('#produto1-imagem1').attr("width", data.lista[0].Largura);
                        $('#produto1-imagem1').attr("height", data.lista[0].Altura);
                        item++;
                        $('#produto1-item2').html(item + " / " + data.qtd);
                        $('#produto1-nome2').text(data.lista[1].NomeclienteProduto);
                        $('#produto1-imagem2').attr("src", data.lista[1].EnderecoImagem);
                        $('#produto1-imagem2').attr("title", data.lista[1].Descricao);
                        $('#produto1-imagem2').attr("alt", data.lista[1].DescricaoAlternativa);
                        $('#produto1-imagem2').attr("width", data.lista[1].Largura);
                        $('#produto1-imagem2').attr("height", data.lista[1].Altura);
                        $('#produto1-legenda2').html(data.lista[1].Descricao);
                        $('#produto1-imagem1').parent().show();
                        $('#produto1-imagem2').parent().show();
                        $('#produto1-imagem3').parent().hide();
                        $('#fourth-slide').attr('produto1-ini', data.lista[0].IdImagem);
                        $('#fourth-slide').attr('produto1-fim', data.lista[1].IdImagem);
                        $('#fourth-slide').attr('produto1-seq', item);
                        $('#fourth-slide').attr('produto1-qtpagina', 2);
                    }
                    else {
                        item++;
                        $('#produto1-item1').html(item + " / " + data.qtd);
                        $('#produto1-legenda1').html(data.lista[0].Descricao);
                        $('#produto1-nome1').text(data.lista[0].NomeclienteProduto);
                        $('#produto1-imagem1').attr("src", data.lista[0].EnderecoImagem);
                        $('#produto1-imagem1').attr("title", data.lista[0].Descricao);
                        $('#produto1-imagem1').attr("alt", data.lista[0].DescricaoAlternativa);
                        $('#produto1-imagem1').attr("width", data.lista[0].Largura);
                        $('#produto1-imagem1').attr("height", data.lista[0].Altura);
                        $('#produto1-imagem1').parent().show();
                        $('#produto1-imagem2').parent().hide();
                        $('#produto1-imagem3').parent().hide();
                        $('#fourth-slide').attr('produto1-ini', data.lista[0].IdImagem);
                        $('#fourth-slide').attr('produto1-fim', data.lista[0].IdImagem);
                        $('#fourth-slide').attr('produto1-seq', item);
                        $('#fourth-slide').attr('produto1-qtpagina', 1);
                    }
                  }
            });
        };
        if (document.getElementById("fourth-slide").getAttribute("produto1-ini") == 0) {
            frente = "S";
            idEnvio = 0;
            urlDestino = "/Produto/BuscaImagemFrente";
            nrReg = 3;
            idProduto = $('#IdProduto').val();
            slide1();
        }
        $('#frente-produto1-slide').on('click', function () {
            frente = "S";
            var idFim = document.getElementById("fourth-slide").getAttribute("produto1-fim");
            idEnvio = idFim;
            urlDestino = "/Produto/BuscaImagemFrente";
            nrReg = 3;
            idProduto = $('#IdProduto').val();
            slide1();
        });
        $('#tras-produto1-slide').on('click', function () {
            frente = "N";
            var idIni = document.getElementById("fourth-slide").getAttribute("produto1-ini");
            idEnvio = idIni;
            urlDestino = "/Produto/BuscaImagemTras";
            nrReg = 3;
            idProduto = $('#IdProduto').val();
            slide1();
        });
        $('#fourth-slide').carousel({
            interval: false
        });

        // slide 4 - imagens - galeria de imagens
        var urlDestino = "";
        var idProduto = 0;
        function slide4() {
            $.ajax({
                url: urlDestino,
                type: "POST",
                data: { "idProduto": idProduto },
                async: true,
                dataType: "json",
                success: function (data) {
                    if (data == "") {
                        return;
                    }
                    var i = data.length;
                    if (i > 0) {
                        i = i - 1;
                    }
                    var y = 0;
                    for (x = 0; x < data.length; x++) {
                        if (data[x].IdPostagemImagem == 3) {
                            y++;
                            if (y == 1) {
                                $('#slide5-legenda1').html(data[x].Descricao);
                                $('#slide5-imagem1').attr("src", data[x].EnderecoImagem);
                                $('#slide5-imagem1').attr("title", data[x].Descricao);
                                $('#slide5-imagem1').attr("alt", data[x].DescricaoAlternativa);
                            }
                            else {
                                $('#fith-slide .carousel-inner').append('
' +
                                '' +
                                '

' +
                                data[x].Descricao + '

');
                            }
                        }

                    }
                }
            });
        };
        urlDestino = "/Produto/BuscaTodasImagens";
        idProduto = $('#IdProduto').val();
        slide4();
        $('#fith-slide').carousel({
            interval: false
        });

    });

4) Controller (with two calls from jquery):
        [HttpPost]
    public async Task<JsonResult> BuscaImagemFrente(int? id, int idProduto, int nrRegistro)
    {
        int qtdTot = await (from d in db.Imagem
                           join p in db.Produto on d.IdProduto equals p.IdProduto
                           where  p.IdProduto == idProduto
                                 && d.IdPostagemImagem == 3
                           select d.IdProduto).CountAsync();
        int dep = 0;
        if (id == 0)
        {
            dep = int.Parse((from d in db.Imagem
                  join p in db.Produto on d.IdProduto equals p.IdProduto
                  where  p.IdProduto == idProduto
                         && d.IdPostagemImagem == 3
                             orderby d.IdImagem
                             select d.IdImagem).FirstOrDefault().ToString());
            id = dep - 1;
        }
        if (id >= 0)
        {
            var frente = await (from d in db.Imagem
                          join p in db.Produto on d.IdProduto equals p.IdProduto
                          where d.IdImagem > id && p.IdProduto == idProduto
                                && d.IdPostagemImagem == 3
                                orderby d.IdImagem
                                select new
                          {
                              d.IdImagem,
                              d.IdProduto,
                              d.EnderecoImagem,
                              d.CorFundoLegenda,
                              d.Descricao,
                              d.IdEmpresa,
                              d.Largura,
                              d.Altura,
                              d.IdPostagemImagem,
                              d.DescricaoAlternativa,
                              d.DescricaoLegenda,
                              d.PosicaoHorizontalLegenda,
                              d.Detalhamento
                          })
                          .Take(nrRegistro).ToListAsync();
            return Json( new { lista = frente, qtd = qtdTot });
        }
        else
        {
            return Json(0);
        }
    }

            [HttpPost]
    public async Task<JsonResult> BuscaImagemTras(int? id, int idProduto, int nrRegistro)
    {
        int qtdTot = await (from d in db.Imagem
                           join p in db.Produto on d.IdProduto equals p.IdProduto
                           where   p.IdProduto == idProduto
                                 && d.IdPostagemImagem == 3
                           select d.IdProduto).CountAsync();
        if (id > 0)
        {
            var frente = await (from d in db.Imagem
                                join p in db.Produto on d.IdProduto equals p.IdProduto
                                where d.IdImagem < id && p.IdProduto == idProduto
                                && d.IdPostagemImagem == 3
                                orderby d.IdImagem descending
                                select new
                                {
                                    d.IdImagem,
                                    d.IdProduto,
                                    d.EnderecoImagem,
                                    d.CorFundoLegenda,
                                    d.Descricao,
                                    d.IdEmpresa,
                                    d.Largura,
                                    d.Altura,
                                    d.IdPostagemImagem,
                                    d.DescricaoAlternativa,
                                    d.DescricaoLegenda,
                                    d.PosicaoHorizontalLegenda,
                                    d.Detalhamento
                                })
                                  .Take(nrRegistro).OrderBy(x => x.IdImagem).ToListAsync();
            return Json(new { lista = frente, qtd = qtdTot });
        }
        else
        {
            return Json(0);
        }
    }
    public async Task<JsonResult> BuscaTodasImagens(int idProduto)
    {
        var retorno = await (from d in db.Imagem
                            join p in db.Produto on d.IdProduto equals p.IdProduto
                            where p.IdProduto == idProduto
                                    && (d.IdPostagemImagem == 3 || d.IdPostagemImagem == 9)
                            orderby d.IdPostagemImagem, d.IdImagem
                            select new
                            {
                                d.IdPostagemImagem,
                                d.EnderecoImagem,
                                d.Descricao,
                                d.DescricaoAlternativa,
                                d.DescricaoLegenda
                            })
                        .ToListAsync();
        return Json(retorno);
    }
    [HttpPost]
    public async Task<JsonResult> BuscaDadosPlanta(int idProduto)
    {
        var frente = await (from d in db.Imagem
                        join p in db.Produto on d.IdProduto equals p.IdProduto
                        join e in db.EspecificacaoProduto on p.IdProduto equals e.IdProduto
                        where  p.IdProduto == idProduto && d.IdPostagemImagem == 9 &&
                              e.IdEspecificacaoProduto == d.IdEspecificacaoProduto
                            //orderby d.IdEspecificacaoProduto
                            orderby d.IdPostagemImagem, d.IdImagem
                            select new
                        {
                            e.IdEspecificacaoProduto,
                            e.DescricaoEspecificacaoProduto,
                            e.DetalhamentoEspecificacaoProduto,
                            d.IdImagem,
                            d.IdProduto,
                            d.EnderecoImagem,
                            d.CorFundoLegenda,
                            d.Descricao,
                            d.IdEmpresa,
                            d.Largura,
                            d.Altura,
                            d.IdPostagemImagem,
                            d.DescricaoAlternativa,
                            d.DescricaoLegenda,
                            d.PosicaoHorizontalLegenda,
                            d.Detalhamento
                        }).ToListAsync();
        return Json(frente);
    }

Comment: I did put different IDs. And I'd love to see the example.
Comment: Ok...when I get to my work an 1 hour I will send it.
Comment: That's it...I tried to reduce more that I could but with the entire project for you see. I think this can help you.
Comment: I can't thank you enough. I hope you have a nice day.
Comment: If this help you. .please check Up.

Model Window Shows Same Content


Going from cartesian to cylindrical coordinates - how to handle division with $0$

Question: I have three point charges with the cartesian coordinates:
$q_1(a,0,0) \: \: \: q_2(0,a,0) \: \: \: q_3(0,0,a) $,
I want to convert these into both cylindrical and spherical coordinates.
The cartesian coordinates are written like this: $(x,y,z)$
The cylindrical coordinates are written like this: $(r,\theta,z)$
The spheircal coordinates are written like this: $(\rho,\theta,\phi)$
From https://en.wikipedia.org/wiki/List_of_common_coordinate_transformations I found these conversion formulas going form cartesian to cylindrical:
$r=\sqrt{x^2+y^2}$
$\theta=\arctan(\frac{x}{y})$
$z=z$
My Problem
Now, I want to convert the cartesian coordinates $(a,0,0)$ into cylindrical. We go like this
$$r=\sqrt{a^2+0^2}=a $$
$$\theta=\arctan(\frac{a}{0})=??? $$
$$z=z $$
My problem is that I don't how to handle the $\theta$ calculation when the y-coordinate is $0$. Can somebody help me here, or maybe I'm using a wrong formula?
Comment: Check this text: https://math.libretexts.org/Bookshelves/Calculus/Book%3A_Calculus_(OpenStax)/12%3A_Vectors_in_Space/12.7%3A_Cylindrical_and_Spherical_Coordinates
Answer: You need to use the arctan2 function, which takes all 4 quadrants into account.
Comment: @Carl You mean when $r = 0$? In that case, you can choose any angle $\theta$.
Comment: Thank you for your answer. But what do I do for the point $(0,0,a)$? The arctan2 function is not defined when $x = 0$ and $y = 0$. Is the cylindrical coordinates then just $(0,0,a)$?


Digital pianos and/or midi keyboards with narrower keys

Question: Are there any digital pianos on market with good key action but with narrower keys?
Or at least MIDI-keyboards that have the proper length of the keys, but with slightly reduced width?
Comment: @BobRhodes: As [this question](http://music.stackexchange.com/questions/20290/is-there-a-standard-width-for-piano-keys) shows, this is a de facto standard at best, but there seem to be no significant deviations.
Comment: No, key size is standardized.  I wouldn't recommend that you work with a non-standard keyboard width anyway, because you would have a lot of difficulty playing any other keyboard.
Comment: @JBeurer Well, I've played a harpsichord with narrower keys than a piano.  It was like playing a different instrument, and it's always a good idea to learn more than one.  But I can easily reach an octave or a seventh or ninth without looking on the piano, because I know where they are. I don't recommend that the OP learn an instrument with narrower keys because he won't be able to play most of the keyboards out there.  So, my answer was intended as a practical one, and I'll stick with it as such.
Comment: @BobRodes why are all my comments gone?
Comment: @JBeurer I don't know. Either a technical problem, or some moderator deleted them, or some other explanation that doesn't occur to me.
Answer: Some keyboards (mostly portable, keytars, or entry models for children) come with slim keys (this, for instance). However I am not sure if there is a good idea to start learning from them. Here it says may not be good idea to play one size at home and another everywhere else.
Answer: purchase original F. Chopin Pleyel http://piano.pleyel.fr/piano-classique/piano-a-queue-p204-bleu-noir.html?lng=EN not sure that modern has narrow keys, the other unrealistic way is to ask people from Yamaha, Korg, Casio and Roland to make a digital copy of Chopins and Bachs instruments. My Yamaha with dynamic light keys has a 3-4 mm narrower octave than the ones with hammer action pianos.


A space over which continuous functions must have $2$ fixed points

Question: The Brouwer fixed-point theorem implies that any continuous automorphism mapping the closed disk to itself must have a fixed point.
Does anyone know of a path-connected (and otherwise "well-behaved") topological space such that any continuous automorphism mapping it to itself must have at least two fixed points?
I add the "path-connected" constraint because without it, it is very easy to construct a space with this property. Simply take the union of a point and a finite line segment (that does not contain the point) in 2-space, and this object satisfies the desired property because the point must be mapped to itself (making one fixed point) and the closed interval must be mapped to itself and also contain one fixed point (by Brouwer).
Comment: Constant functions always have one fixed point - so there are no such spaces.
Comment: What is an automorphism of a topological space?
Answer: If your topological space is a graph (as in edges connecting vertices), then any continuous automorphism must send vertices of degree $3$ or more to vertices of the same degree. Therefore you can construct spaces for which any automorphism has at least $N$ fixed points, by just ensuring that the graph has enough vertices of distinct degrees.


Test Stack White not getting some WPF elements by automation id

Question: I need to get the main menu items (PanelItem) within a DevComponents NavigationPane. I am using Test Stack White's Window.GetMultiple(SearchCriteria.ByAutomationId("xyz")) method which works fine for sub menu items (ButtonDropdown, see example below). I am also able to get the second test button ("TestButton2") but I don't get "TestButton1" and "PanelItem" (and "NavigationPane" neither). Does anyone have an idea why this is?
<code>xmlns:dc="clr-namespace:DevComponents.WpfRibbon;assembly=DevComponents.WpfRibbon"
...
<dc:NavigationPane AutomationProperties.AutomationId="NavigationPane" Name="Test01">

    <Button AutomationProperties.AutomationId="TestButton1">Test button 1</Button>
    <dc:PaneItem AutomationProperties.AutomationId="PanelItem">
        <StackPanel>
            <Button AutomationProperties.AutomationId="TestButton2">Test button 2</Button>
            <dc:ButtonDropDown AutomationProperties.AutomationId="ButtonDropDown"></dc:ButtonDropDown>
...
</dc:NavigationPane>
</code>
Answer: I understand now. :) The very good Stack White documentation recommends using the https://archive.codeplex.com/?p=uiautomationverify tool which lets you pick a running application and shows the visible elements of that application in a tree. So I realized that my first test button is not visible and the PaneItems are no clickable elements. I think I need to click the main menu items programmatically (not with Stack White).


Diferenças no build no jenkins?

Question: Configurei Jenkins para "buildar" um projeto a partir de um repositório git, eu estou usando maven:

Warning: JAVA_HOME environment variable is not set. Apache Maven 3.3.3
  (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T08:57:37-03:00)
  Maven home: /opt/maven Java version: 1.7.0_95, vendor: Oracle
  Corporation Java home:
  /usr/lib/jvm/java-1.7.0-openjdk-220.127.116.11.x86_64/jre
  Default locale:
  en_US, platform encoding: UTF-8 OS name: "linux", version:
  "2.6.32-573.el6.x86_64", arch: "amd64", family: "unix"

Tentei executar "setando" também a JAVA_HOME:
<code>[root@centos64 ~]# mvn -version
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T08:57:37-03:00)
Maven home: /opt/maven
Java version: 1.7.0_95, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.7.0-openjdk-220.127.116.11.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-573.el6.x86_64", arch: "amd64", family: "unix"
</code>
Quando eu executo o build pelo jenkins o build roda imcompleto:

Quando eu executo pelo terminal ele acontece correto:

Em ambos os casos o build é finalizado com sucesso.
Não sei exatamente o que está acontecendo.
Comment: Você configurou a variável de ambiente JAVA_HOME no linux? Pelo que eu entendi você "setou" o JAVA_HOME na configuração do maven
Comment: Eu executei export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-126.96.36.199.x86_64/jre depois export PATH=$PATH:$JAVA_HOME/bin
Answer: Eu estava cometendo dois erros:
1 - Eu não estava especificando a branch correta no jenkins
2 - Por alguma razão, que eu não sei exatamente o porque, o pull não estava sendo executado, deletei meu workspace e recriei novamente, isso funcionou.
Obrigado a todos !

Diferenças no build no jenkins?


What makes RDP so great? Is it really faster than connecting to a VM via admin console?

Question: I use VMWare Workstation as my virtualisation application, however, everyone really belives as RDP being the ultimate way to connect to a VM due to speed.
What makes RDP so great? Also, I remember seeing an advert on this site about an RDP alternative with up to a 20x speed increase. Anyone remember the url?
Thanks
Answer: The reason RDP is great is the following:

32-bit color support. 8-, 15-, 16-, and 24-bit color are also supported.
128-bit encryption
File System Redirection
Printer Redirection
Local Port Redirection for serial and parallel ports
Improved bandwidth tuning for RDP clients depending on current connection.

Summary: RDP (kind-of) gracefully degrades the amount of data sent to the terminal while providing encryption and access to the local ports.
You'll notice that if you're on a slow connection the RDP session will downgrade the color support and stop rendering extra's like the wallpaper.
While VMware can do alot of this, RDP is accessible from almost any machine without installing any other software or controls.
Answer: RDP is faster than admin console due to better compression and provides an encrypted means to connect to a Windows host.  However, seeing as you're using Workstation on a local computer[as opposed to over a network], the benefits are most likely negligible.
Answer: When I run a VM in workstation, I access it from the console. It gives me a better "local" experience than accessing it through RDP.
For our servers running on ESX, I generally hit them with RDP. But mostly because I don't need the local experience with them. Loading the VI client, and then opening the console there, rather than running straight up RDP takes a lot longer to actually get in and running with. However, our LAN is robust enough that the console view (once the VMTools are installed), does give a better user experience. Also if I'm working with several server VMs at once, then I'll probably use the console view, since I've generally got the VI Client running already.
If I'm running over VPN, then I'll avoid the VI Console as much as possible, and try to stick with RDP. It has better compression, selectable visual features, etc. When you're bandwidth limited, then it offers the better experience.
Answer: I'm running a Windows XP workstation in VMWare Workstation that I use to do various administrative tasks. The host OS is Linux. I've found RDP to be very good for my needs. It allows me to precisely define how much screen real-estate I want to give that window, rather than rely upon the built in VESA resolutions. I also find the lack of headers, footers, and frames to improve how much screen I can use in that VM without scrolling. RDP has sound passthrough, even on Linux, so I can watch flash video on it just fine when it isn't working so good on Linux (still a far too common occurrence).
I don't use Unity mode because it's still not that great in this OS, though it could do a lot of what I need.


Custom Content Entity Type: links annotation

Question: I created a Custom Content Entity Type with all the basic CRUD operations. It is working but I do not understand how the links work in the entity annotation and therefore not why they are necessary.
My annotation:
/**
* @ContentEntityType(
*   id = "myent",
*   label = @Translation("My entity"),
*   handlers = {
*     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
*     "list_builder" = "Drupal\myent\Controller\MyentListBuilder",
*     "form" = {
*       "add" = "Drupal\Core\Entity\ContentEntityForm",
*       "edit" = "Drupal\Core\Entity\ContentEntityForm",
*       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
*     },
*     "access" = "Drupal\myent\ContactAccessControlHandler",
*   },
*   base_table = "myent",
*   entity_keys = {
*     "id" = "id",
*     "uuid" = "uuid",
*   },
*   links = {
*     "edit-form" = "/",
*     "delete-form" = "/",
*   },
* )
*/

As you can see I just inserted the necessary slash at the links section. The actual routes to the operations have to be defined in the "myent.routing.yml" no matter what so I do not see why I should write them again in the annotation.
If I remove the links section completely the operations are gone too. So I have to write the links section in the annotation even though they have no additional information for the operations.
What am I missing?
Answer: Years too late but just in case anyone else comes across this issue, I have figured out the answer after much searching.
According to this section in the docs, the links defined in the @ContentEntityType annotation are used in the list builder class (defined by list_builder) to automatically add an 'Operations' dropdown with all of the links to the list.
This will work as long as you keep the parent method in the return statement of returnHeader():
return $row + parent::buildRow($entity);
Changing this to return $row; would render the links section in the annotation useless.


Using cache for twig variables in preprocess function

Question: I implement a menu on a region using a preprocess function to get a link with an anchor for each block of it with a title.
I made a preprocess function for region, in my theme, where I test the region machine name.
I first used the $variables['elements'][XXX]['#id'] to load each block, to find out if the label was set to be display. But I quickly discover that on my server, where the cache is on, the $variables['elements'] only contain an array of cached render.
I then modify my preprocess hook to use the key of the $variables['elements'], witch is finally the block key.
use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_region().
 */
function MYTHEME_preprocess_region(&$variables) {
  if ($variables['region'] == 'one_page') {
    $blocs_menu = array();
    foreach ($variables['elements'] as $key => $values) {
      if (substr($key, 0, 1) == '#') {
        continue;
      }
      $bloc_object = Block::load($key);
      if (is_object($bloc_object)) {
        $bloc_settings = $bloc_object->get('settings');
        if ($bloc_settings['label_display']) {
          $blocs_menu[] = array(
              'id' => $key,
              'label' => $bloc_settings['label'],
          );
        }
      }
    }
    if (count($blocs_menu)) {
      $variables['region_menu'] = $blocs_menu;
    }
  }
}

And in my override file region--one-page.html.twig
{%- if region_menu -%}

{%- for menu in region_menu -%}

{{ menu['label'] }}

{%- endfor -%}

{%- endif -%}

Everything is working well, but I would like to improve the concept :

Be able to detect if the cache is activated on the project
Include in cache my 'region_menu' variable, and generate it only when cache have to be rebuild.

If I understand well, the twig template is also cached, then it is maybe just not really necessary to declare the menu if cache is ON ?
The thing is I'm really lost in the D8 cache API.
I think I have to deal with the cache tags, because I don't have a render to cache.
I would appreciate some help, I cannot find some good (and easy) examples on the documentation or in the core modules.
Answer: Regions are not cached on their own. What you build in a region template will be part of cached pages. If most pages you deliver are cached, this might be OK.
To optimize it build the menu in a block plugin and place the block at the top of the region. The block plugin can get the blocks from  BlockRepository::getVisibleBlocksPerRegion. Use the access cache metadata this method provides for the region, add cache tags for all block entities and the tag config:block_list, so that the menu block gets invalidated when the block layout is modified.
Comment: The region is not the optimal place for providing the cache tags because there can be too much dynamic data in it, like I've explained. But you can leave it as it is (uncached) and rely on page caching, which should cover a lot of case scenarios. When you see that you need to optimize I would recommend a module with a block plugin.
Comment: Thanks for your answer, my idea is to have this functionality directly in the theme and not to develop a module for this.
However, even if regions do not have cache of their own, is this not possible to use custom cache part for this, as in D7 using cache_set ?
Comment: This new menu block is perfect for caching. We know all dependencies and it will stay in the cache as long as nothing changes in the block layout. The region on the other hand contains multiple blocks which may contain more or less dynamic data and thus is far less cacheable than the menu block.
Comment: Sorry I didn't had time before. Do you think it is possible to define such a block directly in the theme ? I really don't want to have a custom module depending on a custom theme, and would prefer to have this behaviour included in the theme.
Comment: I test to create a block module to replace the preprocess_region and the specific template. I use as proposed the getVisibleBlocksPerRegion method, witch list all block of all regions. But I'm now stuck because I cannot know in witch region the block is actually published.
If on some page their is two menu blocks in two regions, I cannot tell one from another and show on each block labels of its region.
An idea how to get the current region of the block ? What I read tell me it is impossible because it is the entity who knows it... Thanks for your help


Relax function on Bellman Ford Algorithms

Question: In a Weighted Directed Graph $G$ (with positive weights), with $n$ vertex and $m$ edges, we want to calculate the shortest path from vertex $1$ to other vertexes. we use $1$-dimensional array $D = (d_1,\cdots,d_n)$, and $D_1=0$ and others filled with $+\infty$. for updating the array we just premit to use the $\mathrm{Relax}(u, v)$ function,

if $(\, D[v] > D[u] + W(u, v) \,)$ then
$\quad D(v) \leftarrow D(u)+W(u,v)$
endif

In which $W(u, v)$ is the weight of $u \implies v$ edge. How many time (at least) we must call the Relax function to ensure that for each vertex $u$, $D[u]$ be equals to length of shortest path from vertex $1$ to $u$.
Solution:

My TA says this is just Bellman-Ford and $m \times n$ times we must call, but maybe i think we can use Dijkstra and need $m$ times.

Anyone could help me?
Answer: If the only thing you are allowed to do is use the Relax function, then indeed you're basically running Bellman-Ford. Your intuition about using Dijkstra is right in the sense that, since all weights are positive, you could apply that algorithm, but then you need to keep track of the vertex that has the current shortest distance from vertex 1. If you're not allowed to do that, then your TA is right.
So there are two solutions, in the first one you call relax $m \times n$ times:

 for _ in 1 .. n:
    for i in 1 ... n:
      for every edge (i, j):
        Relax(i, j)

This code is basically Bellman-Ford, without a posterior check for a negative cycle. This check can be omitted since all weights are positive.
Another solution calls relax $m$ times, but searches for the vertex with the shortest distance at each step:

function MinDistance( S, D ):
    min = None
    for i in S:
      if min is None or D[i] < min:
        min = D[i]
        argmin = i
    return argmin
function InefficientDijkstra():
    S = set()
    D[1] = 0
    S.add(1)
    while not S.empty():
      argmin = MinDistance( S, D )
      for every edge (argmin, j):
        old_dist = D[j]
        Relax(argmin, j)
        if D[j] < old_dist:
          S.add(j)
      S.remove(argmin)

This is a very inefficient way to implement Dijkstra, but it calls the Relax function only $m$ times.
Comment: Dijkstra's algorithm exploits the fact that the _shortest distance_ to some vertex can not become shorter, since all edge weights are positive. This allows Dijkstra's algorithm to run faster than Bellman-Ford, but restricts the algorithm to positive-weight graphs.

If you were to apply Dijkstra, you would need to:
0) Make all vertices as unmarked
1) look up the unmarked vertex with the shortest distance by going through D[u].
2) Call relax on the outgoing edges of u.
3) Mark u.
4) Go to 1 while there are unmarked vertices.
Comment: This means you indeed call relax only $m$ times, but scanning through $D$ to find the vertex with the shortest distance would be linear (unless you use a smarter choice for the data structure), so timewise you're not much faster than Bellman-Ford.
Comment: I've added some pseudocode, hope it's clear
Comment: For Dijkstra you need to find the vertex that is not yet visited and has the current shortest distance, at each step. That's the function you need, I've called it "MinDistance" in the pseudocode.
Comment: Dijkstra "visits" every vertex exactly once. When visiting a vertex, each of its outgoing edges is relaxed. Thus, relax is called for each edge in the graph. That is, $m$ times.


incompatibilidade react-native 0.55.4

Question: react-native init --version 0.55.4 aplicativo

Usei a versão 0.55.4 porque a versão atual esta dando o erro  500
npm install firebase --save

Utilizei esses dois comandos no console, e fui pro projeto colocar a referencia do firebase
import firebase from 'firebase';

Quando dou react-native run-android, aparece o erro 500
Erro no node:

error: unable to resolve module 'firebase' from app.js module firebase
Comment: Tente iniciar o servidor com `npm start` e depois execute o `react-native run-android`
Comment: Não funcionou =/
Answer: Uma solução seria utilizar a lib react-native-firebase para realizar esta integração e é compatível com versões superiores à 0.55 conforme documentação.
Answer: Be happy
import firebase from '@firebase/app';
import '@firebase/auth'
import 'firebase/database';

incompatibilidade react-native 0.55.4


How can I check to see if the current user has an an order in checkout?

Question: I need to create a condition like the following:
 if (current user has an order in checkout){
    go to the checkout page
 }else{
    go to this other page
 }

So far, I'm using:
 if ($order = commerce_cart_order_load($user->uid)) {
      drupal_goto('checkout/')
 }else{
      drupal_goto('someotherpage/')
 }

but it doesn't seem to work. What am i doing wrong? Thanks!
Comment: There is probably a good way to do this in Rules, and make absolutely sure you need that drupal_goto..
Answer:
Preload $user variable.
Remove those / at the end of each url.
Add a semicolon at the end of each PHP line.
global $user;
if ($order = commerce_cart_order_load($user->uid)) {
  drupal_goto('checkout');
}
else {
  drupal_goto('someotherpage');
}


Reverse linked list in Ada

Question: so as you can see I am trying to make a procedure to reverse a linked list, here is the code and the records of the list and the node, I am only obtaining the first number of the list and I think that it could be because pre is null and the head (Current) is pointing to null but I am not sure and I do not know how to solve this, thank you.
Type Node;
Type List is access Node;
Type Node is record
    Info: Integer;
    nx: List;
end record;

 procedure reverselist (L: in out List) is
      Current: List:=L ;
      Pre: List:=null;
      Next: List:=null;
   begin
      if Current.nx /= null then
         while Current.nx /= null loop
            Next:= Current.nx;
            Current.nx:= Pre;
            Pre:= Current;
            Current:= Next;
         end loop;
      end if;

   end reverselist;

Comment: What is `Current`?
Comment: @JeffreyR.Carter Sorry I have translated the code and I forgot to traduce that Actual with Current
Answer: if Current /= null then
         while Current.nx /= null loop
            Next:= Current.nx;
            Current.nx:= Pre;
            Pre:= Current;
            Current:= Next;
         end loop;
         Next:= null;
         Current.nx:= Pre;
         L:= Current;
end if;

Answer: Going forward, also consider the convenience of a doubly linked list such as Ada.Containers.Doubly_Linked_Lists. Given an instance of the package for Integer,
package Integer_Lists is new Doubly_Linked_Lists (Integer);
use Integer_Lists;

A Reverse_List procedure can traverse the list in reverse, as discussed in Iteration, to create a new reversed list. Compare this approach to @Jere's Reverse_List.
procedure Reverse_List (L : in out List) is
   T : List;
begin
   for E of reverse L loop
      T.Append (E);
   end loop;
   L := T;
end Reverse_List;

As an alternative to copying elements, the package also offers Reverse_Elements, which "Reorders the elements of Container in reverse order."
Reverse_Elements (L);
Complete example:
with Ada.Containers.Doubly_Linked_Lists; use Ada.Containers;
with Ada.Text_IO;                        use Ada.Text_IO;

procedure DLL is

   package Integer_Lists is new Doubly_Linked_Lists (Integer);
   use Integer_Lists;

   procedure Reverse_List (L : in out List) is
      T : List;
   begin
      for E of reverse L loop
         T.Append (E);
      end loop;
      L := T;
   end Reverse_List;

   procedure Print (L : List) is
   begin
      for E of L loop
         Put_line (Integer'Image (E));
      end loop;
   end Print;

   L : List;

begin

   L.Append (1);
   L.Append (2);
   L.Append (3);

   Put_line ("Before:");
   Print (L);
   --Reverse_List(L);
   Reverse_Elements (L);
   Put_line ("After:");
   Print (L);
end DLL;

Console:
Before:
 1
 2
 3
After:
 3
 2
 1

Comment: An implementation of `Reverse_Elements ` is shown [here](https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=gcc/ada/libgnat/a-cdlili.adb;h=0e25418368bfd6fb51cbe095f258e2e9840d40bf;hb=cfe989ca49dab9a3fda9e5401a932db168848304#l1405).
Answer: I would start by just popping the head off the list repeatedly and building it back in reverse order:
procedure Reverse_List (L : in out list) is
    Temp : List := null;  -- Holds a "popped" head
    Head : List := null;  -- This is the head of the reversed list
begin
    while L /= null loop
        Temp := L;        -- Pop the head of the list off
        L := L.nx;        -- Set the list head to the next item
        Temp.nx := Head;  -- Attach the popped node to the reversed head
        Head := Temp;     -- Reset the reverse head to the new node
    end loop;
    L := Head; -- Now set the input list pointer to the newly reversed list
end Reverse_List;

Full test program:
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello is

    Type Node;
    Type List is access Node;
    Type Node is record
        Info: Integer;
        nx: List;
    end record;

    procedure Reverse_List (L : in out list) is
        Temp : List := null;  -- Holds a "popped" head
        Head : List := null;  -- This is the head of the reversed list
    begin
        while L /= null loop
            Temp := L;        -- Pop the head of the list off
            L := L.nx;        -- Set the list head to the next item
            Temp.nx := Head;  -- Attach the popped node to the reversed head
            Head := Temp;     -- Reset the reverse head to the new node
        end loop;
        L := Head; -- Now set the input list pointer to the newly reversed list
    end Reverse_List;

    nodes : array (1..5) of List :=
        (new Node'(Info => 1, nx =>null),
         new Node'(Info => 2, nx =>null),
         new Node'(Info => 3, nx =>null),
         new Node'(Info => 4, nx =>null),
         new Node'(Info => 5, nx =>null));

    procedure Print(L : List) is
        C : List := L;
    begin
        while C /= null loop
            Put_Line(C.Info'Image);
            C := C.nx;
        end loop;
    end Print;

    L : List := nodes(1);

begin
    Put_Line("Hello, world!");
    nodes(1).nx := nodes(2);
    nodes(2).nx := nodes(3);
    nodes(3).nx := nodes(4);
    nodes(4).nx := nodes(5);

    Put_Line("Before:");
    Print(L);
    New_Line(2);
    Put_Line("After:");
    Reverse_List(L);
    Print(L);
end Hello;

Output:
$gnatmake -o hello *.adb
gcc -c hello.adb
gnatbind -x hello.ali
gnatlink hello.ali -o hello
$hello
Hello, world!
Before:
 1
 2
 3
 4
 5

After:
 5
 4
 3
 2
 1

Reverse linked list in Ada


Muenchian Grouping - Group by not appearing in xml result

Question: I have the following CSV file such that the XSD looks like this:
123456|123456777|Green|Grün
123456|123456888|Red|Rot
987654|987654333|Yellow|Gelb

In XML format it looks like this:
<Product xmlns="http://F.FlatFileSchema1">
    <Products xmlns="">
        <product>123456</product>
        <sku>123456777</sku>
        <parentcolour_EN>Green</parentcolour_EN>
        <parentcolour_DE>Grün</parentcolour_DE>
    </Products>
    <Products xmlns="">
        <product>123456</product>
        <sku>123456888</sku>
        <parentcolour_EN>Red</parentcolour_EN>
        <parentcolour_DE>Rot</parentcolour_DE>
    </Products>
    <Products xmlns="">
        <product>987654</product>
        <sku>987654333</sku>
        <parentcolour_EN>Yellow</parentcolour_EN>
        <parentcolour_DE>Gelb</parentcolour_DE>
    </Products>
</Product>

The aim is to convert this into an xml with the following format:
<?xml version="1.0" encoding="utf-8"?>
<enfinity xsi:schemaLocation="http://www.intershop.com/xml/ns/enfinity/7.0/xcs/impex catalog.xsd http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt dt.xsd" major="6" minor="1" family="enfinity" branch="enterprise" build="build" xmlns="http://www.intershop.com/xml/ns/enfinity/7.0/xcs/impex" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dt="http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt">
  <offer sku="123456777">
    <custom-attributes>
      <custom-attribute name="parentcolour" dt:dt="string" xml:lang="en-US">Green</custom-attribute>
      <custom-attribute name="parentcolour" dt:dt="string" xml:lang="de-DE">Grün</custom-attribute>
    </custom-attributes>
  </offer>
  <offer sku="123456888">
    <custom-attributes>
      <custom-attribute name="parentcolour" dt:dt="string" xml:lang="en-US">Red</custom-attribute>
      <custom-attribute name="parentcolour" dt:dt="string" xml:lang="de-DE">Rot</custom-attribute>
    </custom-attributes>
  </offer>
  <offer sku="123456">
    <variations>
      <mastered-products>
        <mastered-product sku="123456777" domain="MasterRepository"/>
        <mastered-product sku="123456888" domain="MasterRepository"/>
      </mastered-products>
    </variations>
  </offer>
  <offer sku="987654333">
    <custom-attributes>
      <custom-attribute name="parentcolour" dt:dt="string" xml:lang="en-US">Yellow</custom-attribute>
      <custom-attribute name="parentcolour" dt:dt="string" xml:lang="de-DE">Gelb</custom-attribute>
    </custom-attributes>
  </offer>
  <offer sku="987654">
    <variations>
      <mastered-products>
        <mastered-product sku="987654333" domain="MasterRepository"/>
      </mastered-products>
    </variations>
  </offer>
</enfinity>

As you can see all 3 skus do appear in the XML, but an additional product also needs to appear at the end of the skus, i.e. 123456 appears after 123456777 and 123456888, and 987654 appears after 987654333.  So far I am unable to show the variation block for the product level after applying Muenchian grouping.  My current XSL looks like this:
<?xml version="1.0" encoding="UTF-16"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:s0="http://F.FlatFileSchema1" xmlns:xml="http://www.w3.org/XML/1998/namespace" exclude-result-prefixes="s0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:key name="groupbyproduct" match="offer" use="product"/>
    <xsl:template match="/s0:Product">
        <enfinity xsi:schemaLocation="http://www.intershop.com/xml/ns/enfinity/7.0/xcs/impex catalog.xsd http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt dt.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.intershop.com/xml/ns/enfinity/7.0/xcs/impex" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:dt="http://www.intershop.com/xml/ns/enfinity/6.5/core/impex-dt" major="6" minor="1" family="enfinity" branch="enterprise" build="build">
            <xsl:for-each select="Products">
                <offer sku="{sku}">
                    <custom-attributes>
                        <custom-attribute name="parentcolour" dt:dt="string" xml:lang="en-US">
                            <xsl:value-of select="parentcolour_EN/text()"/>
                        </custom-attribute>
                        <custom-attribute name="parentcolour" dt:dt="string" xml:lang="de-DE">
                            <xsl:value-of select="parentcolour_DE/text()"/>
                        </custom-attribute>
                    </custom-attributes>
                </offer>
            </xsl:for-each>

            <xsl:for-each select="offer[count(. | key('groupbyproduct', product)[1]) = 1]">
                <offer sku="{product}">
                    <variations>
                        <mastered-products>

                            <xsl:for-each select="key('groupbyproduct', product)">
                                <mastered-product sku="{sku}" domain="MasterRepository"/>
                            </xsl:for-each>
                        </mastered-products>
                    </variations>
                </offer>
            </xsl:for-each>
        </enfinity>
    </xsl:template>
</xsl:stylesheet>

Comment: Please edit your question and show the **XML** input.
Comment: Sorry should have included that, just put it near the top of the question, thanks so much in advance!
Answer: The key doesn't make sense, I think you want <xsl:key name="groupbyproduct" match="Products" use="product"/> and then instead of the second for-each you want

        <xsl:for-each select="Products[count(. | key('groupbyproduct', product)[1]) = 1]">
            <offer sku="{product}">
                <variations>
                    <mastered-products>

                        <xsl:for-each select="key('groupbyproduct', product)">
                            <mastered-product sku="{sku}" domain="MasterRepository"/>
                        </xsl:for-each>
                    </mastered-products>
                </variations>
            </offer>
        </xsl:for-each>

As for your comment and the complete result you want, it looks as if first grouping and then inside outputting the different data should give the order you want:
    <xsl:for-each select="Products[count(. | key('groupbyproduct', product)[1]) = 1]">
      <xsl:for-each select="key('groupbyproduct', product)">
            <offer sku="{sku}">
                <custom-attributes>
                    <custom-attribute name="parentcolour" dt:dt="string" xml:lang="en-US">
                        <xsl:value-of select="parentcolour_EN/text()"/>
                    </custom-attribute>
                    <custom-attribute name="parentcolour" dt:dt="string" xml:lang="de-DE">
                        <xsl:value-of select="parentcolour_DE/text()"/>
                    </custom-attribute>
                </custom-attributes>
            </offer>
        </xsl:for-each>
        <offer sku="{product}">
            <variations>
                <mastered-products>

                    <xsl:for-each select="key('groupbyproduct', product)">
                        <mastered-product sku="{sku}" domain="MasterRepository"/>
                    </xsl:for-each>
                </mastered-products>
            </variations>
        </offer>
    </xsl:for-each>

Comment: Ah dann I knew I was close, this kind of worked but is there anyway to order the data so that the product will always come after the sku level?  Currently it's displaying all 3 skus and then 2 products, but I need it to display 2 skus and its corresponding product, and then the final sku with its corresponding product
Comment: @tommyhmt, initially I simply tried to convert your existing attempt into something meaningful, your key tried to select elements you didn't even have in your input. As for the order, see the edit, still trying to reuse your code, but nesting it differently.
Comment: that's absolutely spot on, thanks so much for your help again!