TypeScript Type Inference Issue with Object Properties in Functional Definitions

Question: I'm encountering some type inference problems in Typescript while defining functional objects. Here's a simplified version of the code:
type TFn = {
    input: I,
    func: (input: I) => R
}

type TObj<T extends { [key: string]: [object, any] }> = { [K in keyof T]: TFn<T[K][0], T[K][1]> }

function def<T extends { [key: string]: [object, any] }>(formObject: TObj<T>) {
    return formObject;
}

const res = def({
    fnc1: {
        input: {hel: 0},
        func: (d) => {
            d.hel // throws: property hel does not exist on type object
            return '';
        },
    },
});

const re = res.fnc1.func({}); // re: any, but it should be string

Playground link to code
If I replace the [object, any] with object and make it simple void return, it is working for the input parts. here is the link: Playground
Answer: That inference doesn't work because typescript has no way to obviously map the properties back to the generic type. By packing your input and return value into an array type that has absolutely nothing to do with your actual data's shape/type/structure it can't infer what type you want.
One solution is to just use a generic that is shaped like the data you want:
type TFn = {
    input: I,
    func: (input: I) => R
}

function def<T extends Record<string, TFn<object,unknown>>>(formObject: T) {
    return formObject;
}

const res = def({
    fnc1: {
        input: {hel: 0},
        func: (d) => {
            d.hel // this is still an error
            return '';
        },
    },
});

const re: string = res.fnc1.func({}); // this works now

(playground) This will be able to partially infer the type, however because we just need something that extends the TFn it doesn't properly handle covariance (the thing that ensures that the input field and the argument to func are the same type) so it still can't give full help to you there.
After a bit of playing with it I'm not sure how to get the behaviour you want although it is likely possible. That said, I'm not clear on how this data structure is likely to be used since if you intent res.fnc1.func({}) to be a valid call without specifying hel field then it is possible I am misunderstanding what exactly you actually want.


Drupal7 - User/Registration customizing

Question: Please any one help me to how I can do customizing User/Registration page in Drupal 7. For example I have a select option for user group, suppose if I choose 'others' option ' then user is allowed to create new group in separate text box.
I'm new to Drupal. Please anyone help me
Answer: In Drupal 7 you can use Select (or other) module for your requirement

Select (or other) module : Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When
  'other' is selected a textfield appears for the user to provide a
  custom value.
Comment: Great.. I will try this

Drupal7 - User/Registration customizing


Mutual exclusion across user session in Citrix environment

Question: I have an application that runs in Citrix environment. The application can be run simultaneously by several users in different user sessions. In my application I am writing to a file which should be mutually exclusive across all the user sessions. I tried Mutex to avoid writing to a file from different user sessions but using Mutex failed as in some scenarios different user sessions could not detect whether the Mutex object was already created.
Could any one tell me which of the below approach is better to achieve mutual exclusion across all the user sessions:

Using Named pipes :
If named pipe already exists then application will wait till the pipe gets closed by the application instance which had opened it. Otherwise create the named pipe to indicate the acquiring of lock.
Using a lock file:
Create a normal file on disk to indicate the acquiring of lock and delete when unlock needs to be done.
Answer: You don't need to use a lock file. You can use the built in file system sharing mechanism.
When you open the file by calling CreateFile() you determine the sharing access for subsequent attempts to open the file with the dwShareMode parameter. For example, set this to 0 and no other process will be able to open the file.
Comment: @aJ When a process is finished writing, it calls `CloseHandle` on the file handle and then it's available again. Basically the interface to the filesystem already implements mutual exclusion for you. You really must not try to do it any other way!
Comment: @aJ If the writing is quick and there's little contention, then you could just loop with a sleep. Otherwise you could go back to your mutex and use the global namespace rather than the local namespace which I'd guess was what you did wrong before.
Comment: Thanks. But I would like open later when the other process finishes its task of writing to that file. Basically mutual exclusion
Comment: But the process has to wait till the other process calls CloseHandle. Does OS supports any mechanism to "know" when the other process finishes its writing?
Comment: Ah! Global namespace--that might help me. Let me try. Thanks a lot.
Comment: @aJ Prepend "Global\" to your mutex name. It's all in the CreateMutex documentation. I'd still set the share mode properly because other processes (not your process with the mutex protection) may try to write to the file.
Comment: Why not use CreateFile() as David mentioned and then just call CloseHandle manually when your program is done writing to the file?


Are there any versions of ModSecurity that work well with supported versions of Nginx?

Question: I'm trying to build Nginx and ModSecurity together in order to use the OWASP- Core Rule Set Project.
According to the modsecurity download page, the latest version of modsecurity (2.9.1) is not currently stable when used with nginx.  This is consistent with my experience (not working properly on either Nginx 1.8.x or 1.9.x).  I've also tried the nginx_refactoring branch of ModSecurity, but that's non-functional too, and hasn't seen a commit in nearly 2 years anyway.
I know there is a new version of modsecurity coming up (libmodsecurity), but that isn't ready yet.
Is there any combination of ModSecurity and a supported version of Nginx that is known to be working?
Answer: Now is working, basically you need:

Compile ModSecurity Branch  v3/master (necessary because you need the common core
libmodsecurity)
Compile ModSecurity-nginx connector
Compile nginx  with add-module ModSecurity-nginx
Clone and configure  OWASP ruleset and config to Nginx

This would work
https://www.howtoforge.com/tutorial/nginx-with-libmodsecurity-and-owasp-modsecurity-core-rule-set-on-ubuntu-1604/


Moving the Up/Down Vote Widget to end of content

Question: I am brand new to Drupal but not to OOPHP.  I am assuming responsibility for a site which uses Up/Down Vote 6.x.
The issue is that the posts are very long and hold many many images and it doesn't look like the module supports any widget position other than at the top of
.
I would like to move it to just above the footer links of the node, after the content.
I have been googling this without success.  Can anyone advise me or direct me to the relevent docs?
Answer: Widget is getting displayed using hook_node_view code in vud_node.module...
/**
 * Implementation of hook_node_view().
 */
function vud_node_node_view($node, $view_mode, $langcode) {
  // avoid showing the widget in some node builds
  $exclude_modes = array(
    NODE_BUILD_PREVIEW,
    NODE_BUILD_SEARCH_INDEX,
    NODE_BUILD_SEARCH_RESULT,
    NODE_BUILD_RSS,
  );
  if (in_array($node->build_mode, $exclude_modes)) {
    break;
  }
  if (($can_edit=user_access('use vote up/down on nodes')) || user_access('view vote up/down count on nodes')) {
    $node_type = in_array($node->type, variable_get('vud_node_types', array()), TRUE);
    $widget_showmode = variable_get('vud_node_widget_show', VUD_NODE_DISPLAY_BOTH);
    $tag = variable_get('vud_tag', 'vote');
    $widget = variable_get('vud_node_widget', 'plain');
    $vote_on_teaser = (bool)variable_get('vud_node_widget_vote_on_teaser', TRUE);
    $teaser = $a3;

    $widget_message_code = VUD_WIDGET_MESSAGE_ERROR;
    if (!$can_edit) {
      $widget_message_code = VUD_WIDGET_MESSAGE_DENIED;
    }
    elseif (!$vote_on_teaser) {
      $widget_message_code = VUD_NODE_WIDGET_MESSAGE_TEASER_DENIED;
    }

    if ($node_type) {

      switch ($widget_showmode) {
        case VUD_NODE_DISPLAY_TEASER_ONLY:
          if ($teaser == 1) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$vote_on_teaser || !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_FULL_ONLY:
          if ($teaser == 0) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_BOTH:
          if ($teaser == 1) {
            $readonly = !$vote_on_teaser || !$can_edit;
          }
          else {
            $readonly = !$can_edit;
          }
          $node->content['vud_node_widget_display'] = array(
            '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, $readonly, $widget_message_code),
            '#weight' => -10,
          );
          break;
      }

    }
  }
}

Implement hook_node_view_alter in your custom module and change the weight to higher value so that it will be displayed at bottom...
In Drupal modules extends permissions by defining them using hook_permission.. You can find list of permissions in "admin/people/permissions" ..
For vote up / down set permissions in above page.. See screenshot below..
Comment: Thank you!  Will do now.  On a separate issue users are reporting that only Admin can see the voting widget.  The config does not have settings pertaining to that.  Any thoughts?  Perhaps I should post as new question.
Comment: See updated answer for permissions issue..
Comment: Looks like this is implemented in `vud_node_nodeapi` in vud_node.module in this version
Comment: Thank you very much!  I appreciate your help!  My config does not show this setting.  I have posted a new question with screenshots of config tabs and modules here http://drupal.stackexchange.com/questions/110864/vote-up-down-widget-only-visible-to-admins  I sure would appreciate it if you would take a look!
Comment: Turns out I needed to administer user permissions in /admin/users/permissions
Comment: I checked the whole module source for references to vud_node_node_view and did not find any at all.  Is that possibly a 7x change?
Comment: Yeah .. I was referring to 7.x...


A sequence and convergence

Question: Let $\{x_n\}$ and $\{y_n\}$ be sequences of real numbers which converge to $\ell$ and $m$ respectively. Show that
$$\lim_{n\to \infty} \frac{1}{n}\sum_{k=1}^{n}x_ky_{n+1-k}=\ell m$$
This is a problem I found in a book, it seemed to be routine, but now I can't solve it.
What I tried :

Let us take some $\epsilon>0$. Now after a stage $N$, both $|x_n-\ell|<\epsilon$ and $|y_n-m|<\epsilon$. Now I wanted to break the sum $$\left|\frac{1}{n}\sum_{k=1}^{n}x_ky_{n+1-k}-\ell m\right|$$in two parts, one upto $N$, and other one for $N+1$ to $n$. Now we need this to be arbitrarily small. But here I am lost. I don't know how to proceed anymore. Because when I take $x_i's$ to make up a finite sum, then the $y_j's$ are there too with $j$ very large. I think this is the main idea, but unable to do anything further. Can someone help me? Thanks.
Answer: First, recall that if $x_n\to x$, and if $\widehat{x_n}=\displaystyle \frac 1 n\sum_{i=1}^n x_i$ then $\widehat{x_n}\to x$. Now, you have $$\lim_{n\to \infty} \frac{1}{n}\sum_{k=1}^{n}x_ky_{n+1-k}=xy$$
Subtract $\displaystyle y\frac 1n\sum_{k=1}^n x_k $ to get $$\frac 1 n\sum_{i=1}^nx_k(y_{n+1-k}-y)$$
It suffices we show this converges to $0$, since $\displaystyle y\frac 1n\sum_{k=1}^n x_k \to xy$, that is, we may assume that $y_i\to 0$. By subtracting $\displaystyle x\frac 1n \sum_{k=1}^n(y_{n+1-k}-y)$ we may as well assume $x_i\to 0$.
Given $\varepsilon >0$, pick $M>0$ and $n>M$, and write $$\frac{1}{n}\sum\limits_{i = 1}^n {{x_i}{y_{n + 1 - i}}}  = \frac{1}{n}\sum\limits_{i = 1}^M {{x_i}{y_{n + 1 - i}}}  + \frac{1}{n}\sum\limits_{i = M + 1}^n {{x_i}{y_{n + 1 - i}}} $$
Now choose $M$ such that $i>M$ gives $|x_i|<\varepsilon/B$ where $B$ is a bound for $|y_i|$ and such that $i>M$ gives $|y_i|<\varepsilon/A$ where $A$ is a bound for $|x_i|$. Then when $n>2M$, $$\eqalign{
  & \frac{1}{n}\sum\limits_{i = 1}^M {\left| {{x_i}} \right|\left| {{y_{n + 1 - i}}} \right|}  + \frac{1}{n}\sum\limits_{i = M + 1}^n {\left| {{x_i}} \right|\left| {{y_{n + 1 - i}}} \right|}  \leqslant   \cr
  & \frac{A}{n}\sum\limits_{i = 1}^M {\left| {{y_{n + 1 - i}}} \right|}  + \frac{B}{n}\sum\limits_{i = M + 1}^n {\left| {{x_i}} \right|}  \leqslant   \cr
  & \frac{A}{n}\frac{\varepsilon }{A} + \frac{B}{n}\left( {n - M} \right)\frac{\varepsilon }{B} = M\frac{\varepsilon }{n} + \left( {n - M} \right)\frac{\varepsilon }{n} = \varepsilon  \cr} $$
Comment: Your last lines seems not necessary. Suppose that $x_k\to 0$, $y_k\to 0$, then $y_k$ is bounded, say by $M$, and hence $$|\frac{1}{n}\sum_{k=1}^{n} x_ky_{n+1-k}|\leq \frac{M}{n}\sum_{k=1}^{n}| x_k| \to 0$$
Comment: @Kelenner In some sense, I am repeating the proof of the fact that Cesaro summation preserves sums. True.
Answer: first reduce to $x_k, y_k\to 0$ (for simplicity).  let $|x_k|\leq M, |y_k|\leq N$.  then
$$
\frac{1}{2n}\sum_{k=0}^{2n}x_ky_{2n-k}\leq M\max_{k\geq n}\{\delta_k\}+N\max_{k\geq n}\{\epsilon_k\},
$$
which goes to zero as $n\to\infty$.
(i'm just splitting the list $\epsilon_k\delta_{n-k}$ in half, which bounds the index of one of the factors below by something that goes to infinity as $n$ does.)
Answer: As you have said, we consider two cases:
Case 1: if $l=0$, for $\epsilon >0, \exists N\in\mathbb{N}, st |x_n|<\epsilon,\forall n\geq N .$ Then $\bigg |\frac{1}{n}\sum_{k=1}^n x_ky_{n+1-k}-0\bigg|=\bigg |\frac{1}{n}(\sum_{k=1}^N x_ky_{n+1-k}+\sum_{k=N+1}^n x_ky_{n+1-k})\bigg|<\frac{1}{n}(\sum_{k=1}^N |x_k|\cdot \sum_{k=1}^N y_{n+1-k})+\frac{\epsilon}{n} \sum_{k=1}^N |y_k|\rightarrow 0, n\rightarrow \infty$
(Notice that $y_k\rightarrow m$, so $\sum_{k=1}^N y_{n+1-k}$ is bounded)
Case 2: if $l\neq 0$, $\bigg|\frac{1}{n}\sum_{k=1}^n x_ky_{n+1-k}-lm\bigg|=\bigg|\frac{1}{n}\sum_{k=1}^n (x_k-l)y_{n+1-k}+\frac{1}{n}\sum_{k=1}^n l\cdot y_{n+1-k}-lm\bigg|=\bigg|\frac{1}{n}\sum_{k=1}^n (x_k-l)y_{n+1-k}+l\cdot(\frac{1}{n}\sum_{k=1}^n  y_{n+1-k}-m)\bigg| \leq \bigg|\frac{1}{n}\sum_{k=1}^n (x_k-l)y_{n+1-k} \bigg|+l\cdot \bigg| \frac{1}{n}\sum_{k=1}^n y_k-m\bigg|\rightarrow 0, n\rightarrow \infty$.
($ \bigg|\frac{1}{n}\sum_{k=1}^n (x_k-l)y_{n+1-k} \bigg|\rightarrow 0, n\rightarrow \infty $because of case 1)

A sequence and convergence


Specify SSL details for Kafka brokers in python

Question: I need to connect to kafka instance which has multiple brokers with SSL.
I am using kafka-python to consume and process data.
I have seen link where they used kafka-python to connect to single broker with SSL.
Link : http://maximilianchrist.com/python/databases/2016/08/13/connect-to-apache-kafka-from-python-using-ssl.html
Specific code
consumer = KafkaConsumer(bootstrap_servers='my.server.com',
                          security_protocol='SSL',
                          ssl_check_hostname=True,
                          ssl_cafile='CARoot.pem',
                          ssl_certfile='certificate.pem',
                          ssl_keyfile='key.pem')

I need to know since there are multiple brokers how to specify multiple ssl_ca, ssl_cert, ssl_key in constructor ??
Answer: SSL should be set up such that the client can authenticate with any of your brokers. I recommend you take a look at this tutorial to get a better idea on SSL basics https://docs.confluent.io/current/kafka/encryption.html#kafka-ssl-encryption
Comment: Archaic question but I am commenting since those questions are recurring. The doc you are presenting refers to Java Kafka Clients. On Python side things are a bit different therefore this answer is not helpful
Answer: Old question but because I faced the same issue (available answers most of the time are Java oriented, which has a different architecture using keystores and truststores), I am posting a working solution. Please note I am using confluent Kafka, but the solution should work the same with minor changes for other python kafka libraries.
Kafka brokers is just a single string of comma separated values. If each broker has different certificate, then just copy all server certificates in a single .pem file.
A consumer which consumes from 3 brokers with separate certificates should look as follows:
kafka_brokers = 'broker_1,broker_2,broker_3'
ssl_ca_location = 'all_server_certs.pem'
consumer = Consumer({
    'bootstrap.servers': kafka_brokers,
    'security.protocol': 'SSL',
    'enable.ssl.certificate.verification': 'true',
    'ssl.certificate.location': 'client-cert.pem',
    'ssl.ca.location': ssl_ca_location,
    'ssl.key.location': 'client-key.pem',
    'group.id': 'my_group',
    'auto.offset.reset': 'earliest'
    })


How do I convert a Hawaiian guitar to Spanish Guitar?

Question: I have a 4 months old hawaiian guitar.  I do not like playing the Hawaiian guitar, and I want to change instruments. I have a standard bengali Hawaiian guitar with all its accessories and I want to play spanish acoustic guitar. How do I convert it into spanish guitar?
Comment: I'm not entirely sure what this is asking. Would you be willing to clarify?
Comment: I like the "Yemaha" brand name. Close, but no cigar ...  ;)
Answer: It looks like your guitar has ball end steel strings. By the look of the photo, all you need to do is buy a set of nylon strings and secure them to the wooden bridge using the traditional loop knot. The metal trapeze tailpiece can be removed. If this is difficult, just place a little bit of padding between it and the guitar top. Your photo doesn't show the headstock, but it's likely you have smaller diameter steel capstans on the tuning machines, rather than the larger diameter plastic ones fitted to classical/spanish guitars. They will work fine; just attach the strings to the capstans as normal. BTW, I love the cross culturality suggested by, 'standard bengali Hawaiian guitar'.


Has anyone noticed that EF Core 1.0 2015.1 has made the queries very inefficient

Question: After upgrading to Asp.Net Core 2015.1 I have noticed that a lot of EF queries have become a lot slower to run.
I have done some investigation and found that a lot of the queries with where filters now get evaluated in Code, rather than passing the filters to SQL as part of a where clause to run with the query.
We ended up having to re-write a number of our queries as stored procedures to get back performance. Note these used to be efficient prior to the 2015.1 release. Something obviously was changed, and a lot of queries are doing select all queries on a table and then filtering the data in code. This approach is terrible for performance, e.g. reading a table with lots of rows, to filter everything but maybe 2 rows.
I have to ask what changed, and whether anyone else is seeing the same thing?
For example: I have a ForeignExchange table along with a ForeignExchangeRate table which are linked via ForeignExchangeid = ForeignExchangeRate.ForeignExchangeId
await _context.ForeignExchanges
                .Include(x => x.ForeignExchangeRates)
                .Select(x => new ForeignExchangeViewModel
                {
                    Id = x.Id,
                    Code = x.Code,
                    Name = x.Name,
                    Symbol = x.Symbol,
                    CountryId = x.CountryId,
                    CurrentExchangeRate = x.ForeignExchangeRates
                        .FirstOrDefault(y => (DateTime.Today >= y.ValidFrom)
                                          && (y.ValidTo == null || y.ValidTo >= DateTime.Today)).ExchangeRate.ToFxRate(),
                    HistoricalExchangeRates = x.ForeignExchangeRates
                        .OrderByDescending(y => y.ValidFrom)
                        .Select(y => new FxRate
                        {
                            ValidFrom = y.ValidFrom,
                            ValidTo = y.ValidTo,
                            ExchangeRate = y.ExchangeRate.ToFxRate(),
                        }).ToList()

                })
                .FirstOrDefaultAsync(x => x.Id == id);

And I use this to get the data for editing a foreign exchange rate
So the SQL generated is not as expected. It generates the following 2 SQL statements to get the data
SELECT TOP(1) [x].[ForeignExchangeId], [x].[ForeignCurrencyCode], [x].[CurrencyName], [x].[CurrencySymbol], [x].[CountryId], (
SELECT TOP(1) [y].[ExchangeRate]
FROM [ForeignExchangeRate] AS [y]
WHERE ((@__Today_0 >= [y].[ValidFrom]) AND ([y].[ValidTo] IS NULL OR ([y].    [ValidTo] >= @__Today_1))) AND ([x].[ForeignExchangeId] = [y].[ForeignExchangeId])
)FROM [ForeignExchange] AS [x]
WHERE [x].[ForeignExchangeId] = @__id_2

and
SELECT [y0].[ForeignExchangeId], [y0].[ValidFrom], [y0].[ValidTo], [y0].[ExchangeRate]
FROM [ForeignExchangeRate] AS [y0]
ORDER BY [y0].[ValidFrom] DESC

The second query is the one that causes the slowness. If the table has many rows, then it essentially gets the whole table and filters the data in code
This has changed in the latest release as this used to work in the RC versions of EF
One other query I used to have was the following
         return await _context.CatchPlans
            .Where(x => x.FishReceiverId == fishReceiverId
                     && x.FisherId == fisherId
                     && x.StockId == stockId
                     && x.SeasonStartDate == seasonStartDate
                     && x.EffectiveDate >= asAtDate
                     && x.BudgetType < BudgetType.NonQuotaed)
            .OrderBy(x => x.Priority)
            .ThenBy(x => x.BudgetType)
            .ToListAsync();

and this query ended up doing a Table read (the entire table which was in the tens of thousands of rows) to get a filter subset of between 2 and 10 records. Very inefficient. This was one query I had to replace with a stored procedure. Reduced from approx 1.5-3.0 seconds down to milliseconds. And note this used to run efficiently before the upgrade
Comment: can you share some of your EF queries ?
Comment: updated to share examples
Comment: Instead of rewriting your perfectly valid queries, you'd better upgrade to EF Core RTM, where some of those issues are fixed (for instance the first example with `Include`). Or, IMHO even better downgrade to EF6 and wait EF Core 1.1 or later.
Answer: This is a known issue on EF core 1.0.The solution right now is to convert all your critical queries to sync one.The problem is on Async queries right now.They'll sort out this issue on EF core 1.1.0 version.But it has not been released yet.
Here is the Test done by the EF core dev team member :

You can find out more info here :EF Core 1.0 RC2: async queries so much slower than sync
Another suggestion I would like to do.That is try your queries with .AsNoTracking().That too will improve the query performance.
.AsNoTracking()

Sometimes you may want to get entities back from a query but not have
  those entities be tracked by the context. This may result in better
  performance when querying for large numbers of entities in read-only
  scenarios.
Comment: One of the main things I was trying to say regarding the slow down in query speed, is that I believe it was working faster in the pre-releases EF than the latest release.
This implies that I think something was broken between rc2 and the 1.0 release.


Enviar mensagem Whatsapp pelo link no site

Question: Gostaria de saber como enviar uma mensagem por um link para um determinado número. Já consegui fazer para Android, mas para iPhone não funciona.
Link:

Comment: @FelipeAvelar na verdade não sei como fazer para iPhone. Gostaria de algo que funcione nos dois.
Comment: Fala Moises, Eu não programo pra Iphone então não vou saber te explicar, mas no próprio site do WhatsAPP tem a explicação do que você deve fazer, segue o link: [https://www.whatsapp.com/faq/pt_br/iphone/23559013](https://www.whatsapp.com/faq/pt_br/iphone/23559013) Abraços.
Comment: Pode colocar o que você já tentou fazer para o iPhone?
Comment: Possível duplicata de [Inserir Botão Whatsapp Share em páginas HTML](http://pt.stackoverflow.com/questions/70475/inserir-bot%c3%a3o-whatsapp-share-em-p%c3%a1ginas-html)
Answer: Para uso no iPhone, use este formato:
whatsapp://send?text=Texto da mensagem com link http://google.com
Answer: É possível também criar um link usando a API do WhatsApp e determinar qual o número de destino. Funciona também com os aplicativos desktop:
Enviar mensagem

Importante: é preciso inserir o código do país (55) e o DDD.


Passando valor de uma label para o Arduino via serial

Question: Desenvolvi um WindowsForm que contém uma label que faz a verificação de uso de CPU e exibe suas variações, e um botão que conecta o software com o arduino na porta serial disponível. Criei também um textBoxReceber, para verificar se o arduino esta recebendo algum valor, mas ai é que esta o problema, eu não estou conseguindo enviar os valores atualizados para o arduino. Segue o trecho do código.
private void startMonitor()
    {
        MachineMonitor machineMonitor = new MachineMonitor("B-NTIDDT001");
        while (true)
        {

            var ram = "Mem RAM: " + machineMonitor.GetUsageMemoryPercentage() + " %";
            var cpu = "CPU: " + machineMonitor.GetUsageCPUPercentage() + " %";

            if (this.lblCpu.InvokeRequired)
            {
                lblCpu.Invoke((MethodInvoker)delegate () { this.lblCpu.Text = cpu; });
                this.ValorR = cpu;
            }
            else
            {
                this.lblCpu.Text = cpu;
            }

            Thread.Sleep(1000);
        }

Aqui está o método que recebe os valores de uso de CPU e RAM e passa para a lblCpu.
private void btConectar_Click(object sender, EventArgs e)
    {
        if (serialPort.IsOpen == false)
        {
            try
            {
                serialPort.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                serialPort.Open();
            }
            catch
            {
                return;
            }
            if (serialPort.IsOpen == true)
            {
                btConectar.Text = "Desconectar";
                comboBox1.Enabled = false;
            }
        }
        else
        {
            try
            {
                serialPort.Close();
                comboBox1.Enabled = true;
                btConectar.Text = "Conectar";
            }
            catch
            {
                return;
            }
        }
    }

Minha conexão com as portas seriais disponíveis.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        lblCpu.Text = RxString;
        RxString = serialPort.ReadExisting();
        this.Invoke(new EventHandler(trataDadoRecebido));
    }

    private void trataDadoRecebido(object sender, EventArgs e)
    {
        textBoxReceber.AppendText(RxString);
    }

Como podem ver, eu não consigo pegar o dados da lblCpu e repassar para meu Arduino. Eu fiz um método lblCpu_Click, dai funcionou porém não quero ter que ficar clicando na lblCpu toda hora, gostaria que atualizasse constantemente sem minha interferência.
Answer: Para isso você deve usar um timer e fazer um loop de tempo, ou seja você vai escolher um tempo determinado, com por exemplo de 1 em 1 minuto para o método "lblCpu_Click ser acionado.


how to record video in one device at that same time play that video live in another device

Question: I have to record video by using camera in one android device,at that same time i have to play that recording video live in another android device.what should i do for recording video and playing at same time in another device.
Comment: Camera interfaces, video protocols, network topology, buffering etc.  This is a bit broad, don't you think?
Answer: What you need to do is create a thread for recording a video and in the same time stream it to the next device using a TCP socket connection. you can have the full code for this in the spy-droid application ,go here https://code.google.com/p/spydroid-ipcamera/ in this spydroid application that have created this live video streaming server that can be accessed from any device or any computer by simply typing the ip and port number in the browser itself. after downloading the spydroid source code you can import the packages to your project and can use them in your project
Comment: in spy-droid i could not be able to figure out communication bw one android device to another device for video streaming.make me clear about this doubt
Comment: What is that you don't understand
Comment: ya i could not be able to understand
Comment: i mean which part that u find not understandable
Comment: my problem is i should implement live video from one device to another device.i saved video file in sd card and i transfered to another device through socket connection and i received that file in another device.saved in sd card and played successfully but i should implement live video.so what i should do? plz help me


Which finger on right hand to use to play G note on piano in Twinkle Twinkle Little Star?

Question: When my daughter learned piano the first time one year ago, the teacher let us use this fingering:

CC GG AA G FF EE DD C
11 55 55 5 44 33 22 1

We stop learning for a while and we start again. However, this new teacher let us use this fingering:

CC GG AA G FF EE DD C
11 44 55 4 44 33 22 1

We are quite confused.
Comment: Fingering is rarely an absolute question of right or wrong.  How old is your daughter?
Answer: Both are acceptable, so in this case, I suggest using the fingering recommended by the current teacher. However, if making the change is proving difficult, then have a parent-teacher conversation to acknowledge the difficulty and ask to use the old fingering for this song. A good teacher will be flexible. (And the best teachers would already have recognized the confusion and allowed the student to play in the familiar way or gauged how to surmount any difficulty in switching.)
The differences between the two fingerings amount to the following:

The 55 55 5 fingering ("repeated 5s") requires two shifts of the hand (from G to A, then back to G); whereas, the 11 44 55 4 44 fingering ("repeated 4s") requires "opening" the hand (from C [11] to G [44] and only one shift (from G [4] to F [44]). Also, the two hand-shifts in the "repeated 5s" fingering happen close together in the music, while the adjustments in the "repeated 4s" fingering are more separated from each other.

In the "repeated 4s" fingering, the hand movements better match the phrasing of the music, the hand-shift coming at a break between phrases.

Twink - le, twink - le, lit - tle star.
1       1   4       4   5     5   4
    (hand "opens")                     (hand shift)

1       1   5       5   5     5   5
                (hand shift)(hand shift)

How I won - der what you are.
4   4 3     3   2    2   1
4   4 3     3   2    2   1

An advantage to the "repeated 5s" fingering is that the hand never has to leave "five-finger position", a common starting point for learning in which each finger is on consecutive notes — C D E F G.
Comment: I would prefer the new fingering because it introduces the idea of changing hand position to prepare for what is coming.
Comment: @GrandAdagio I like it. Very clever. The hand movement matching the direction of the music is a great benefit. The only reason I can think of not to use it with a beginner is that it can be confusing to play the same note with different fingers, but that would depend on the particular learner.
Comment: @Peter I'm with you, for the same reason. And it's better fingering practice anyway, so good to instill proper fingering early.
Comment: How about  5 4 for G G, then 3 4 for F F ? This way the hand moves along the keys' changing direction?
Comment: Thank you Aaron. I'm flattered :) Happy New Year!
Answer: In the early stages of learning piano, the hand(s) will be anchored over just 5 notes - and tunes will accommodate this. That makes it easy to play tunes - no need to look at the keys. But when the tune strays beyond the 5 notes, something has to change.
One option is to stretch and allow the pinky to play ^5 and ^6. The whole hand could actually slide a little to the right for ^6, then back to the 'safe' position for the rest.
Another option is to stretch the whole hand, as new teacher advocates, so ^5 is played by finger 4, putting pinky over ^6. Another good reason this works now is probably tat your daughter has grown somewhat in the intervening year, and that stretch isn't really a stretch. It also prepares her for moving out of that 'safe' 5 fingers for 5 notes syndrome.
With fingering of anything, at any level,I advocate the student trying out all available options, not just blindly following teacher's choice, as there may be an even better one that hasn't been used so far. It will depend on the piece, and the student's physical hand structure, as we all differ . A really good teacher will be able to justify and explain why s/he recommends certain things - ask the question.
Answer: The primary source of confusion is that you think there's a "correct" way. There's none. It's like picking a color for an apple in a picture: should it be green? Red? Yellow?
Sticking to one version when learning might be a good idea because reasonable fingering helps muscle memory. Learning to switch fingerings might also be a good idea because that helps improvise and read a vista (citation required).
At the level of playing "Twinkle Twinkle Little Star" - none of the above really matters.
Comment: It's perhaps more like "What kind of shoes should my daughter wear — pull-on, velcro, buckle, lace-up?" There's no single absolute right answer, but it's not just an arbitrary choice like the apple colour either — depending on the child's age, competence, and other so on, some answers may well be better than others for this specific stage.
Comment: @PLL I can imagine some really bad fingerings, certainly. But, like in case of the shoes, it's not something to overthink. There's a lot of variables, there will be much more tunes than just "Twinkle, twinkle...". I think this is something that is hard to get wrong :)
Comment: @PLL: To put it another way: you will not get a better fingering, specific to your child, by asking for it on the Internet. Same with shoes: we don't know the context, we don't know the shoes, we don't know the child's manual skills, we don't know her motivation. If your kindergarten teacher says that lace-up is fine, then it's probably fine, and certainly not something to be confused about.


How to reinstall python2.7 on CentOS 6 in order to install mod_wsgi

Question: I've installed Python2.7 from source on a CentOS 6 VPS, and I'd like to get a Django site up and running. Unfortunately, everything I've Googled so far says that I'll need to install mod_wsgi, which means I'll need to reinstall Python2.7 with the --enable-shared flag.

Will I need to first uninstall Python2.7?
How can I install mod_wsgi without totally messing up my system?

Thanks in advance. I haven't been able to find a newbie-friendly guide.
Comment: `yum install mod_wsgi` generally works.
Comment: Why are you installing *anything* from source?
Comment: CentOS 6 didn't have the version of Python I needed, so a trusted friend advised that I install it from source. In either case, is there a way to reinstall Python2.7 or otherwise install mod_wsgi?
Answer: mod_wsgi is in the base repositories. You can just run yum install mod_wsgi
However, if you have been playing around installing Python from source, then it may well be that you have screwed up the Python environment. In that case, your best bet will be to reinstall the VPS from scratch and run yum install mod_wsgi.
Assuming you have deployed your Django project in /var/www/djangoproject you will have a tree something like:

/var/www/djangoproject/
├── manage.py
├── djangoapp
│   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── djangoproject
    ├── __init__.py
    ├── __init__.pyc
    ├── settings.py
    ├── settings.pyc
    ├── urls.py
    └── wsgi.py

Which will require an Apache conf (/etc/httpd/conf.d/djangoproject.conf) something like:

 #WSGIPythonPath /var/www/djangoproject/djangoproject
<VirtualHost *>
     ServerAdmin email@example.com
     WSGIScriptAlias / /var/www/djangoproject/djangoproject/wsgi.py
     WSGIDaemonProcess myproj user=apache threads=3
     <Directory />
        Options FollowSymLinks
        AllowOverride None
     </Directory>
     DocumentRoot /tmp
     ServerName www.example.com
     ErrorLog /var/log/httpd/djangoproject_error_log
     CustomLog /var/log/httpd/djangoproject_access_log combined
</VirtualHost>

Comment: Thanks for the reply. I managed to get mod_wsgi installed using yum install as root, and successfully loaded it into apache. I added the .conf file you outlined above, but now I'm getting Internal Server Error when I type in the server address in a browser. I feel like I'm getting close here, but no cigar.
Comment: This is what I have: WSGIPythonPath /var/www/StoreWeb/StoreWeb

    ServerAdmin firstname.lastname@example.com
    WSGIScriptAlias / /var/www/StoreWeb/StoreWeb/wsgi.py
    WSGIDaemonProcess myproj user=apache threads=3

       Options FollowSymLinks
       AllowOverride None

    DocumentRoot /var/www/StoreWeb/StoreWeb/
    ServerName www.example.com
    ErrorLog /var/log/httpd/StoreWeb-error_log
    CustomLog /var/log/httpd/StoreWeb-access_log combined
Comment: Looking at the error log, it looks like it can't import importlib. The relevant lines are "mod_wsgi (pid=15862): Target WSGI script '/var/www/StoreWeb/StoreWeb/wsgi.py' cannot be loaded as Python module." and "mod_wsgi (pid=15862): Exception occurred processing WSGI script '/var/www/StoreWeb/StoreWeb/wsgi.py'.", resulting in "ImportError: No module named importlib". I appears that wsgi is running in Python 2.6.: "/usr/lib64/python2.6/site-packages/django/core/wsgi.py"
Comment: Make sure you have all the necessary modules for your application installed on the server too. `sudo yum install python-importlib` in that case for example.
Comment: K, did that, now it's giving an 'invalid syntax' error in part of the django package in the server error log. And all the references from the log indicate that it's trying to use python2.6 instead of python2.7, which is what my site is written in.
Comment: Python 2.6 is the packaged version in Centos 6 and going to 2.7 will cause you a world of pain. If I were you I'd switch to Centos 7 and do as above. Or modify your syntax to be backward compatible.


Verify that a user's email exists in provided domain using PHP

Question:
Possible Duplicate:
check if email are valid and exists
How to validate an email address in PHP

I am developing a application for sending mail by provided mail address in PHP. now i wanna validate given mail address is really exist in domain or not
<code>  **i.e
    firstname.lastname@example.com (for example its registred in xyz domain)
    email@example.com (for example its nod registred xyz domain)**
</code>
how can i verify it by using PHP.
Thanks in advance
Comment: Are you going to have a list of emails for the domains?
Comment: Have a look at this topic.

http://stackoverflow.com/questions/1976712/using-mx-records-to-validate-email-addresses
Comment: Even if it could be done, it'd be pointless. What if e-mail exists but belongs to someone else?
Answer:
Generate a token
Store that token against the email address in a database
Send an email to that address with a URL that includes the token and a hash of the email address

If someone visits that URL, then the address exists.
SMTP provides a mechanism to ask if a server hosts a particular address, but it is almost always disabled as it is a favourite tool of spammers.
Comment: Correct. There's no other way. Seriously. E-mail is not different from snail mail.
Comment: its mean we must send email to given address there's no alternate way


Constructing a function based on a real-world scenario

Question: A random thought came into my head today when I was in the subway:

Suppose we have a train in a subway where the stations are evenly spaced in a straight line.  The train accelerates for some amount of time, moves with a constant speed for some amount of time, and starts decelerating until it reaches the next station such that the same amount of time spent accelerating and decelerating are the same, and the magnitudes of both are the same.  Create a possible function that illustrates this scenario.

I decided that I would try to use some combination of a sinusoidal function and a linear function, since the train would try to do the same thing during certain periods of time, and the train is moving only in one direction.  I hopped onto Desmos and played around a little bit, and I was able to create a function that gets me somewhat close to what I want.  $$d_1(t)=t-\frac1{2\pi}\sin 2\pi t$$

I chose the constant multiple $\frac1{2\pi}$ to simplify the distance between each station to $1$, and the multiplier $2\pi$ for $t$ to suggest that it takes $1$ unit of time to get from one station to the next.  Choosing the sinusoidal function means that there will be no length of time where the train is moving at a constant speed, and the acceleration and deceleration will be exactly opposite, separated by the point of inflection halfway between the stations.

The problem:  trains usually stop at every station.  I want to, arbitrarily at first, modify the function so that the train waits for the same amount of time as it takes to travel from one station to another.  Eventually, I want to be able to construct a function that can describe the waiting time in some proportion to the traveling time.  I came up with the function
$$d_2(t)=\begin{cases}t-\frac{\lfloor t\rfloor}2-\frac1{2\pi}\sin 2\pi t,& \lfloor t\rfloor \textrm{ is even}\\ \frac{\lceil t\rceil}2,& \lfloor t\rfloor \textrm{ is odd}
\end{cases}$$

This gets me something closer to what I want.

My questions:

What alternative ways of representing the scenario are there?  For example, would it be possible to construct a piecewise function based only on polynomials that meets the criteria above?
Is there a way to represent this particular scenario without use of a piecewise function?
Suppose there must be a stretch of time where the train is moving at a constant speed between stations.  How can I factor that in to the equation for the function?
Suppose the train makes the return trip in a similar manner, and it makes some number of return trips daily.  Does this suggest that it can be written as a periodic function?  If so, what would be the equation for that function?
Comment: Yes, I see where you are coming from, but I want to suppose that the acceleration may or may not be constant -- having the same sign is sufficient (e.g. having an acceleration $x>0$ in one interval, then having the deceleration (or negative acceleration) be the same magnitude, but different sign).  Thanks for input; I will remove that tag since concavity of a function is based on knowledge of calculus.
Comment: You can try to make formal your conditions as differential equations, solving which will give you an infinite family of possible solutions.
Comment: Particularly question 4, because of the periodicity aspect, made me think of Fourier Series: https://en.wikipedia.org/wiki/Fourier_series
Comment: If you want your function to be constant in some sections, than it cannot be analytic. In your situation this translates to the fact that you need a piecewise definition.
Comment: I know you tagged this as precalculus, but if you start by just considering the acceleration, you can then anti-differentiate to get velocity and anti-differentiate again to get distance. From the description you gave, you would end up with a piecewise function of quadratics.
Answer: Just collecting various comments all in one place, and filling in some holes / details.
First, a function $d(t)$ is simply a mapping from values in the domain (in your case: time) to values in the range (in your case: distance).  Whether you can write that function as a "nice" formula of "well-known" expressions, is kinda irrelevant.  I should add though, the confusion between (abstract) functions and (nice) formulas is historic, so if you have the same confusion, you're not alone.  :)
In the context of $d(t)$ being the motion of a train, there are reasonable assumptions to be adopted, e.g. $d$ should be continuous (the train does not "teleport"), differentiable (velocity is well defined) and maybe twice differentiable (acceleration is well defined).  However, even after adopting these, there is nothing special about sinusoids.  (In the context of a moving pendulum, or (idealized) planetary rotation, maybe sinusoids would be natural, but a moving train...?)
Q1: As answered by @79037662 it is surely possible to model the train motion $d(t)$ as piecewise polynomial - and in fact for a train this would probably be more natural than modeling by sinusoids.  Assuming no friction (ha!) a zero acceleration would give constant velocity $v(t)$ and linear $d(t)$, a constant non-zero acceleration would give linear velocity $v(t)$ and quadratic $d(t)$, a linear acceleration would give quadratic $v(t)$ and cubic $d(t)$, etc.  If you have pieces of acceleration you will have pieces of polynomial $d(t)$ and once you have pieces of polynomials you simply have to be careful to "glue" them together.  The piecewise formula might be tedious to write out but there is nothing magical going on.
Q2: As answered by @quarague it is not possible for your function to have a constant stretch and also be analytic, and "analytic" very roughly translates to something with a nice formula (and probably includes most "familiar" functions you have in mind: polynomials, sinusoids, exponentials, etc).  This is actually a non-trivial result.  This applies to both distance (constant distance implying stopping at a station) and velocity:  If you have constant stretches and non-constant stretches (in either distance or velocity), then you will have to write your function as piecewise.
Q3: Constant speed simply means that part of $d(t)$ is linear, e.g. $d(t) = v t + C$.  Here $v$ is the constant velocity.  You get this $d(t)$ by integrating $v$ over $t$.
Q4: As answered by @AdamRubinson Fourier Series would be a way to go, but for the purpose of writing out the function it's probably overkill.  Suppose $d^*(t)$ for $t \in [0,1]$ describes what happens to the train in the first hour, and $d^*(0)=d^*(1)$ s.t. the train makes a complete round trip.  Further suppose the train does this every hour, then you can simply write the overall $d(t)$ as
$$d(t) = d^*(t - \lfloor t \rfloor)$$
Here $\lfloor t \rfloor$ is the standard notation for the "floor" function which denotes the greatest integer $\le t$, so e.g. if $t=13.7$ then $\lfloor t \rfloor = 13$ and $t - \lfloor t \rfloor = 0.7$ gives the fraction part of $t$.  Note that while "floor" is a "standard" function, it is piecewise.  Which in a roundabout way brings us back to the your Q2: you can always describe a piecewise function in a non-piecewise way... if you define a new name for it!  :)
Hope this helps (as opposed to confuses even further!)
Comment: Say $x$ is a variable $ \in (0,1)$, then you seem to be saying you want $f(n+x) = f(n-1 + x) + 1$.  The only _polynomial_ function that does that would be linear; quadratics, cubics etc all never do that.  So if $f$ is polynomial but not linear, then you have to specify $f$ as piecewise polynomial, e.g. maybe use my idea in Q4 or something similar.
Comment: Thanks for a detailed response! Got a final question for you: suppose I wanted to create a polynomial function for my above $d_1(t)$ on, say, $[0,m]$. Is there a way to ensure that the "bumps" that I have are all uniform (like, $(n,n+1)$ acts the same as $(n-1,n)$ except one unit up)?  It is (in addition to my naivety or my lack of training) why I tried to think about it using a periodic function in the first place.


$C([a,b]), \| \cdot \|_\infty$ is complete

Question: I have to prove that $(C([a,b]), \| \cdot \|_\infty )$ is complete. I proved that a Cauchy sequence converges pointwise. Now, let's call $f$ the pointwise limit. I have: \begin{align}
| f_n(x)-f_m(x) | \le \epsilon \ \ \forall n,m > n_0, \forall x
\end{align}
So by the continuity of $| \cdot|$, I can let $n\to\infty$, so I obtain $ f_n\to f $ in $ \|\cdot\|_\infty$. Now I have to prove that $f$ is continuous. Here I'm not completely sure. Let $x_n \to x$ and fix $\epsilon$, I have:
\begin{align}
 |f(x_n)-f(x)| \le |f(x_n)-f_m(x_n)|+|f_m(x_n)-f_m(x)|+|f_m(x)-f(x)|
\end{align}
By the pointwise convergence, I can select $f_m$ s.t.
\begin{align}
& |f(x_n)-f_m(x_n)|\le \epsilon/3, |f_m(x)-f(x)|\le \epsilon/3 \  \ \text{so,} \\&|f(x_n)-f(x)| \le |f_m(x_n)-f_m(x)|+2\epsilon/3
\end{align}
So, by the continuity of $f_m$, $ \exists n_0 \  s.t. \ \  |f_m(x_n)-f_m(x)| \le \epsilon/3$.
Is this proof okay? Is there some other way to prove the continuity of $f$?
Comment: What is $n_0$ doing (it doesn't appear to be used)?  Also $n_0$ might depend on $m$.  Hint: this space is not complete.  Try to find a sequence of functions which approach a jump discontinuity.
Comment: The "$\epsilon/3$" argument is the classic way of proving that a uniform limit of continuous functions is continuous.
Comment: Since $f_n $ is Cauchy, then $\forall \epsilon \exists n_0$ s.t. $| f_n(x)-f_m(x) | \le \epsilon \ \ \forall n,m > n_0, \forall x$. So letting $n\to \infty$, $| f(x)-f_m(x) | \le \epsilon \ \ \forall m > n_0, \forall x$, and taking the $\sup$ over $x$ I get the uniform convergence. I know this space to be complete, it can't be. Can you provide a counter example?
Answer: Your proof is not valid because $m$ depends 0n $n$.
Choose $n_0$ such that $|f_n(x)-f_m(x)|<\epsilon$ for al $x$ for all $n,m \geq n_0$. You have  already noticed that $f(x)=\lim_{n \to \infty} f_n(x)$ exists. Letting $n \to \infty$ we get $|f_m(x)-f(x)|\leq \epsilon$ for al $x$ for all $m \geq n_0$. In particular $$|f_{n_0}(x)-f(x)|\leq \epsilon$$ for all $x$. Now use the inequality
$|f(x)-f(y)|$$ $$ \leq |f(x)-f_{n_0}(x)|+|f_{n_0}(x)-f_{n_0}(y)|+|f_{n_0}(y)-f(y)|\leq 2\epsilon + |f_{n_0}(x)-f_{n_0}(y)|$.
Now complete the proof using the fact that $f_{n_0}$ is continuous.
(We have already proved that $f_m \to f$ uniformly).
Comment: Oh, okay. So, if I want to make my proof correct, I have to use the fact that $f_m \to f$,and select an m big enough, so that those equalities hold for all $x_n$?
Comment: Right. Note that sequential form of continuity makes things messy and that is where your proof gets into trouble.
Comment: Yes it's true, the topological definition is better in this case, I wanted to be sure I understood the mistake. Thanks for your time.


Dynamic open_basedir with mod_vhost_alias

Question: I'm using mod_vhost_alias and want to set dynamically open_basedir for each user. Something like
php_admin_value open_basedir /var/www/vhosts/%1
But it doesn't work. Because I have a lot of virtual hosts (4000-5000) mod_macro does not suit me.
I'm trying to apply this patch
http://wiki.preshweb.co.uk/doku.php?id=apache:securemassvhosting
But with no success. Any suggestions?
Answer: You can use auto_prepend option in php.ini to supply script that will be executed first.
There you can setup open_basedir via ini_set() function based on contents of $_SERVER array.
Comment: Yeah, something like this could do it: `ini_set('open_basedir', "/var/www/hosts/$hostname/:/tmp/");`
Comment: A useful note: php will not let any following `ini_set` to loosen the restriction.
So if you set it to `/var/www/html` in a prepend file, a following `ini_set('open_basedir', "/");` will have no effect.
Answer: May be somebody would be interested. I have successfully changed the patch (http://www.phpbuilder.com/lists/php-developer-list/2000101/0994.php)
<code>*** main/fopen_wrappers.c       2010-04-22 01:22:31.000000000 +0300
--- main/fopen_wrappers.c       2012-03-14 17:22:49.130299133 +0200
***************
*** 145,156 ****
--- 145,168 ----
        char resolved_name[MAXPATHLEN];
        char resolved_basedir[MAXPATHLEN];
        char local_open_basedir[MAXPATHLEN];
+       char *local_open_basedir_sub; /* Substring pointer for strstr */
        char path_tmp[MAXPATHLEN];
        char *path_file;
        int resolved_basedir_len;
        int resolved_name_len;
        int path_len;
        int nesting_level = 0;
+
+       /* Special case for VIRTUAL_DOCUMENT_ROOT in the open_basedir value, which gets changed to the document root */
+       if ((strncmp(basedir, "VIRTUAL_DOCUMENT_ROOT", strlen("VIRTUAL_DOCUMENT_ROOT")) == 0) && SG(request_info).path_translated && *SG(request_info).path_translated )
+       {
+           strlcpy(local_open_basedir, SG(request_info).path_translated, sizeof(local_open_basedir));
+
+           local_open_basedir_sub=strstr(local_open_basedir,SG(request_info).request_uri);
+           /* Now insert null to break apart the string */
+           if (local_open_basedir_sub) *local_open_basedir_sub = '\0';
+
+       } else

        /* Special case basedir==".": Use script-directory */
        if (strcmp(basedir, ".") || !VCWD_GETCWD(local_open_basedir, MAXPATHLEN)) {
</code>
It was tested with php-5.3.10 and it's worked great.


Is the first execution of a function always slower than the second?

Question: I just noticed that if I have the exact same function and measure it's performance, then the first execution is always slower than the second one.
I tried it several times and the result is always the same.
const myF = () => console.log("hello");

console.time("1");
myF();
console.timeEnd("1");

console.time("2");
myF();
console.timeEnd("2");

First I thought the result of the first execution is somehow cached and therefore in the second execution it is faster. But I also tried with different functions that are only slightly different. But again, the result are the same as before: The function executed first is faster than the second one.
const myF = () => console.log("hello");
const myF2 = () => console.log("world");

console.time("1");
myF(); // 1 is slower than 2
console.timeEnd("1");

console.time("2");
myF2();
console.timeEnd("2");

Here I executed the 2nd function first
const myF = () => console.log("hello");
const myF2 = () => console.log("world");

console.time("2");
myF2(); // 2 is slower than 1
console.timeEnd("2");

console.time("1");
myF();
console.timeEnd("1");

Is the way I use the console.time resp. console.timeEnd correct? If so, why would the first execution be slower than the second execution? It's probably something stupid that I missed. I can't imagine the performance of the exact same function to be dependent on which line it is executed....
Tested on Chrome 78.0; Linux 19.04
Answer: Its because of when your function executes first time, compiler interprets that function to machine code(assembly instruction for function) and stores this CPU instruction in memory. When you execute same function second time compilers directly executes interpreted machine code that's why second time function executes faster.
Comment: Why would executing two (slightly) *different* functions show the same effect?
Comment: @thadeuszlay Your anonymous functions are different, but the `console.log` is the same (with different parameters) perhaps that's the bit that's pre-compiled the second time around.
Comment: You are probably right. Is there a way to verify that?


Translate XSD element names to English

Question: I have an XML Schema Definition file .XSD who's elements are in Spanish. I have an XML data file that is also in Spanish that matches the schema definition. I created a dataset from the xsd using xsd.exe and I'm loading the XML into the dataset.
I want to translate the element names to English. I can think of two options off the top of my head. Either scrape the XSD & XML files and translate the elements prior to generating the dataset with esd.exe, or iterate the dataset after I have loaded it with the xml, and translate my objects.
I do have a written document that provides the English names for every element name in Spanish. The problem is there are hundreds of elements and I was trying to avoid coding that manually. Getting precise translations is not that important, it just needs to be readable by an English speaking person.
Here is an example of what an element may look like "Apellidos":
<xs:element name="Apellidos" type="xs:string"/>

that I will translate to "SirName":
<xs:element name="SirName" type="xs:string"/>

I'm looking for ideas and or opinions on a quick way to do this. It's a one time deal so I'm not working about it scaling or being functional for things other than this single xml file.
I'll be taking this dataset and writing out a flat file for English speaking users to read.
Comment: Translate? xsd is meant for validation.. not translation.
Comment: @infant programmer - Sounds like you don't understand the question. I can not read the xsd elements because they are in Spanish.
Answer: Alright, I didn't find the answer that I was looking for. What I ended up doing was sending the XSD off to a person who could translate the elements to English for me. Then I created a dictionary class that represented the Spanish/English combos. I read the XML into the dataset and as I looped through each datacolumn to write my header row, I did a lookup on the column name to the translation dictionary to pull back the English phrase. It was painful but works like a champ.

Translate XSD element names to English


Fuga das Galinhas - Problema de Backtracking

Question: Estou implementando um problema em Java. O problema consiste em um tabuleiro NxN, em onde é colocado uma galinha e X lobos. Eu recebo o tamanho do tabuleiro,  a posição da galinha, o número de lobos e a posição dos lobos via entrada padrão, mais ou menos assim:
8     //tamanho do tabuleiro
2 3   //coluna e linha da galinha
3     //quantidade de lobos
6 0   //coluna e linha lobo1
3 7   //coluna e linha lobo2
2 1   //coluna e linha lobo3

O problema tem as seguintes regras:

A galinha pode se mover uma única casa nas posições norte, sul, este, oeste
Os lobos podem se mover uma casa em qualquer direção
Em uma jogada, a galinha se move em uma das 4 direções possíveis
Os lobos se moverão depois da galinha
Se um lobo estiver na mesma linha/coluna da galinha, ele se move apenas na linha/coluna, perseguindo a galinha
Se ele não estiver na mesma linha/coluna da galinha, ele se move na diagonal correta para a perseguição
Depois de todos os movimentos, é verificado se a galinha foi capturada

O problema consiste em desenvolver um algoritmo baseado em backtracking que, após 10 rodadas, descobre se a galinha consegue fugir ou não dos lobos.
Meu problema está no backtracking dos lobos. Após a galinha ser capturada em uma primeira vez, eu consigo fazer ela voltar para a posição anterior para tentar outra alternativa, mas não consigo fazer os lobos voltarem para a posição anterior. Segue abaixo o meu código:
public class Galinha {
    protected int X;
    protected int Y;

    public Galinha(int x, int y){
        X = x;
        Y = y;
    }

    protected Galinha thisClone() {
        Galinha g = new Galinha(this.X, this.Y);
        return g;
    }
}

public class Lobo {
    protected int X;
    protected int Y;

    public Lobo(int x, int y){
        X = x;
        Y = y;
    }

    public void persegueGalinha(Galinha g){
        if( this.X > g.X)
            this.X--;
        if( this.X < g.X)
            this.X++;
        if(this.Y > g.Y)
            this.Y--;
        if(this.Y < g.Y)
            this.Y++;
    }

    public boolean comeuGalinha(Galinha g){
        return (X == g.X && Y == g.Y);
    }

    public Lobo thisClone() {
        Lobo l = new Lobo(this.X, this.Y);
        return l;
    }
}

public class TrabComplex {

    private static char[][] tabuleiro;
    private static Galinha galinha;
    private static Lobo[] lobos;
    private static int nroLobos;
    private static int rodada = 100;
    private static int cont = 0;

    public static void main(String[] args) {

        int tamanho = 8;
        tabuleiro = new char[tamanho][tamanho];
        galinha = new Galinha(3, 1);
        tabuleiro[galinha.X][galinha.Y] = 'G';
        nroLobos = 3;
        lobos = new Lobo[nroLobos];

        Lobo l1 = new Lobo(7, 0);
        Lobo l2 = new Lobo(0, 6);
        Lobo l3 = new Lobo(3, 6);

        lobos[0] = l1;
        lobos[1] = l2;
        lobos[2] = l3;

        tabuleiro[l1.X][l1.Y] = 'L';
        tabuleiro[l2.X][l2.Y] = 'L';
        tabuleiro[l3.X][l3.Y] = 'L';
        moveGalinha(galinha, lobos);
    }

    public static void printMatriz() {
        for (int i = 0; i < tabuleiro.length; i++) {
            for (int j = 0; j < tabuleiro.length; j++) {
                if (tabuleiro[i][j] == 'L') {
                    System.out.print("L");
                } else if (tabuleiro[i][j] == 'G') {
                    System.out.print("G");
                } else {
                    System.out.print(".");
                }
            }
            System.out.println("");
        }
    }

    public static void moveGalinha(Galinha galinhaLoop, Lobo[] lobosLoop) {
        Galinha galinhaAux = galinhaLoop.thisClone();
        cont++;
        printMatriz();
        System.out.println("--------------------------");
        Lobo[] lobosAux = cloneLobos(lobosLoop);
        for (int x = galinhaLoop.X - 1; x <= galinhaLoop.X + 1; x++) {

            if (cont < rodada && x > -1 && x < 8) {

                tabuleiro[galinhaLoop.X][galinhaLoop.Y] = '.';

                galinhaAux.X = x;
                galinhaAux.Y = galinhaLoop.Y;
                tabuleiro[x][galinhaAux.Y] = 'G';

                for (int i = 0; i < lobos.length; i++) {

                    tabuleiro[lobosLoop[i].X][lobosLoop[i].Y] = '.';
                    Lobo loboAux = lobosLoop[i].thisClone();
                    loboAux.X = lobosLoop[i].X;
                    loboAux.Y = lobosLoop[i].Y;
                    loboAux.persegueGalinha(galinhaLoop);
                    if (!TestaPosicaoLobo(loboAux.X, loboAux.Y)) {
                        loboAux.X = lobosLoop[i].X;
                        loboAux.Y = lobosLoop[i].Y;
                        tabuleiro[lobosLoop[i].X][lobosLoop[i].Y] = 'L';
                    }
                    tabuleiro[loboAux.X][loboAux.Y] = 'L';
                    lobosAux[i] = loboAux;

                    if (lobosLoop[i].comeuGalinha(galinhaLoop)) {
                        System.out.println("Lobo pegou a galinha!");
                        return;
                    }
                }
                moveGalinha(galinhaAux, lobosAux);
            }
        }
        for (int y = galinhaLoop.Y - 1; y <= galinhaLoop.Y + 1; y++) {

            if (cont < rodada && y > -1 && y < 8) {

                tabuleiro[galinhaLoop.X][galinhaLoop.Y] = '.';

                galinhaAux.X = galinhaLoop.X;
                galinhaAux.Y = y;
                tabuleiro[galinhaAux.X][y] = 'G';

                for (int i = 0; i < lobos.length; i++) {

                    tabuleiro[lobosLoop[i].X][lobosLoop[i].Y] = '.';
                    Lobo loboAux = lobosLoop[i].thisClone();
                    loboAux.X = lobosLoop[i].X;
                    loboAux.Y = lobosLoop[i].Y;
                    loboAux.persegueGalinha(galinhaLoop);
                    if (!TestaPosicaoLobo(loboAux.X, loboAux.Y)) {
                        loboAux.X = lobosLoop[i].X;
                        loboAux.Y = lobosLoop[i].Y;
                        tabuleiro[lobosLoop[i].X][lobosLoop[i].Y] = 'L';
                    }
                    tabuleiro[loboAux.X][loboAux.Y] = 'L';
                    lobosAux[i] = loboAux;

                    if (lobosLoop[i].comeuGalinha(galinhaLoop)) {
                        System.out.println("Lobo pegou a galinha!");
                        return;
                    }
                }
                moveGalinha(galinhaAux, lobosAux);
            }
        }
    }

    public static boolean TestaPosicaoLobo(int x, int y) {
        return tabuleiro[x][y] != 'L';
    }

    private static Lobo[] cloneLobos(Lobo[] listaLobos) {
        Lobo[] lobos = new Lobo[nroLobos];
        for (int i = 0; i < listaLobos.length; i++) {
            lobos[i] = listaLobos[i].thisClone();
        }
        return lobos;
    }

   private boolean LobosComeramGalinha(Lobo[] listaLobos, Galinha g){
       for(int i = 0; i < listaLobos.length; i++){
           if(listaLobos[i].X == g.X && listaLobos[i].Y == g.Y){
               return true;
           }
       }
       return false;
   }

}

Comment: Desculpa, mas o que é backtracing? Poderia esclarecer melhor qual é a sua dúvida?
Comment: Backtracking é um metodo de construção de algoritmos.Ele funciona basicamente assim:Uma busca inicial em um programa com backtracking segue o padrão busca em profundidade, ou seja, a árvore é percorrida sistematicamente de cima para baixo e da esquerda para direita. Quando essa pesquisa falha, ou é encontrado um nodo terminal da árvore, entra em funcionamento o mecanismo de backtracking.Esse procedimento faz com que o sistema retorne pelo mesmo caminho percorrido com a finalidade de encontrar soluções alternativas.Ou seja, nada mais é do que um mecanismo de "voltar atras".Se algo falha, volta.
Comment: Tens de manter um registo dos nodos que já percorreste para fazer isso.
Comment: Usa o padrão de projeto [Memento](http://en.wikipedia.org/wiki/Memento_pattern).
Answer: Recomendo que você não tente manter um histórico das posições de cada animal manualmente. Ao invés disso use recursividade e deixe a própria pilha de execução manter esse histórico.
É o que faz por exemplo o algoritmo de flood-fill recursivo, no qual você pode se basear para implementar sua solução.
O flood-fill é um algoritmo de processamento de imagens que altera, pixel por pixel, a cor de uma região de uma imagem por outra cor. A implementação recursiva do algoritmo parte de um pixel inicial dentro dessa região e vai preenchendo os pixels adjacentes (acima, à direita, abaixo e à esquerda) de maneira recursiva. Se o pixel estiver em um local em que não deveria estar (por exemplo fora da área da imagem, ou sobre uma cor já preenchida ou diferente da cor inicial) ele faz backtracking, ou seja, retorna imediatamente e a recursividade entra em ação para atuar sobre o próximo pixel, fazendo isso até que a região esteja totalmente preenchida.
Estude esse algoritmo e veja como ele pode ser usado para resolver o seu problema. Basicamente você terá um método que recebe uma cópia das coordenadas x, y da galinha e dos lobos e testa se a galinha foi pega ou se ela não pode estar na posição atual (por ser fora do tabuleiro ou a posição de um lobo), retornando imediatamente do método nesses dois casos. Lembrando que, ao contrário do flood-fill em que a movimentação é de um único elemento (o pixel), no caso da fuga das galinhas a movimentação é representada pela movimentação de todos os animais no tabuleiro, ou seja, um passo da galinha e em seguida um passo de cada lobo.
Acho que essa informação já é suficiente para queimar um pouco dos neurônios e resolver. Mais que isso e eu acabo dando a solução pronta. :)


Cannot install vue

Question: I usually perform fresh re-installs of packages after a period of non-use, but when I came to perform a fresh install of Vue.js and vue-cli I tried to perform a vue init on a new project but was told that vue was not recognised as an operable or batch file etc.
It is possible that I created a problem when I uninstalled vue-cli, which removed something like 250 packages. Subsequent reinstall only installed 1 package, but I was then unable to get any response from the vue init command other than the above.
I have tried every workaround I could find on SO and elsewhere which boils down to the following: -

Upgrading node and npm
Upgrading git
Cleaning the npm cache

One consistent error message in my attempts to perform npm install vue was that I lacked a package.json file in my C:/Users/user folder (I am said user and I have administrator privileges). I ran npm init to create a blank package.json file in that folder but that didn't work either.
The root problem seems to be that nothing I do re-installs a vue.cmd file in my AppData/Roaming/npm folder, even though this path is properly installed in my environment variables. I have looked if this file has been installed elsewhere on my machine, but it hasn't.
Is it possible to manually download a vue.cmd file and put it exactly where it needs to sit, i.e. in my AppData/Roaming/npm folder? I googled this to no avail. All this is while running Command Prompt as an administrator.
Is anyone else having this problem? Is there something with another JS framework which is currently blocking Vue from being properly installed? (I have also developed projects in React and Angular5.)
Just as an update, this is the package.json file I currently have in my C:/Users/user folder after running npm init from that folder: -
{
  "name": "user",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "npm": "^5.8.0",
    "vue": "^2.5.16"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Comment: TL;DR. Sometimes, summarize helps
Answer: It sounds like you don't have vue-cli installed on your machine
But without any error messages it's impossible to tell.
try npm install -g firstname.lastname@example.com
then run which vue-cli to check the location

Cannot install vue


Does $\vec{a} \times \vec{b} = \vec{a} \cdot \vec{b} \cdot \tan \varphi$ holds true?

Question: Let $|\vec{v}| = v$.
We know that
$$ \vec{a} \cdot \vec{b} = a \cdot b \cdot \cos\varphi $$
and I have recently seen (on an old 'vocabulary' card) that (Edit: here is the mistake happening!)
$$ \vec{a} \times \vec{b} = a \cdot b \cdot \sin\varphi . $$
This would lead to
$$ \vec{a} \times \vec{b} = a \cdot b \cdot \sin\varphi \cdot \dfrac{\cos\varphi}{\cos\varphi} = \vec{a} \cdot \vec{b} \cdot \dfrac{\sin\varphi}{\cos\varphi} = \vec{a} \cdot \vec{b} \cdot \tan\varphi . $$
That
$$ \vec{a} \times \vec{b} = \vec{a} \cdot \vec{b} \cdot \tan\varphi $$
holds true seems very surprising to me.
Edit: Where exactly is the mistake, since the operations yield different types of outcomes?
Comment: lol dot product yields a scalar and cross product yields an orthogonal vector, so this is like asking whether an apple equals a banana
Comment: $$\vec a\times \vec b =\left(\frac{\vec a\times \vec b}{|\vec a\times \vec b|}\right)\,(\vec a\cdot \vec b)\,\tan(\theta)$$Note the unit vector in parentheses.  Take the magnitude of both sides and obtain  $$|\vec a\times \vec b |=|\vec a\cdot \vec b\,\tan(\theta)|$$
Answer: Note that the cross product of $\vec a $ and $\vec b$ is given by
$$\vec a\times \vec b=\left(\frac{\vec a\times \vec b}{|\vec a\times \vec b|}\right)\,|\vec a|\,|\vec b|\,\sin(\theta)$$
where $\frac{\vec a\times \vec b}{|\vec a\times \vec b|}$ is a unit vector that is normal to both $\vec a$ and $\vec b$ and has orientation that conforms to the right-hand rule.

The inner product is simply given by $\vec a\cdot \vec b=|\vec a|\,|\vec b|\,\cos(\theta)$.  Hence, we see that
$$\vec a\times \vec b =\left(\frac{\vec a\times \vec b}{|\vec a\times \vec b|}\right)\,(\vec a\cdot \vec b)\,\tan(\theta) \tag 1$$

Now, taking the magnitude of both sides of $(1)$ yields
$$|\vec a\times \vec b| =|\vec a\cdot \vec b|\,|\tan(\theta)| $$
Answer: A vector can not be equal to a scalar. So the second equality is not true.
Answer: The identity $\vec a \times \vec b = a*b*tan(\phi)$ is wrong. The LHS is a vector, the RHS is a scalar.


Possible to build a 32bit adder from 32 1-bit adders?

Question: I am supposed to complete the module below,  by creating 32 assignment statements
doesn't seem to be the right way of doing this.  I know that i have to carry the cout up,
but when create and test a yAdder using a client module, I get incorrect about like 1 + 1 =  4 billion.  lol.   I know what it should do, I just don't know how to do it in verilog.
    module yAdder(z,cout,a,b,cin);
output [31:0] z;
output cout;
input[31:0] a, b;
input cin;
wire[31:0] in,out;
yAdder1 mine[31:0](z,out,a,b,in);

assign in[0] = cin;
assign in[1] = out[0];
assign in[2] = out[0];
assign in[3] = out[0];
assign in[4] = out[0];
assign in[5] = out[0];
assign in[6] = out[0];
assign in[7] = out[0];
assign in[8] = out[0];
assign in[9] = out[0];
assign in[10] = out[0];
assign in[11] = out[0];
assign in[12] = out[0];
assign in[13] = out[0];
assign in[14] = out[0];
assign in[15] = out[0];
assign in[16] = out[0];
assign in[17] = out[0];
assign in[18] = out[0];
assign in[19] = out[0];
assign in[20] = out[0];
assign in[21] = out[0];
assign in[22] = out[0];
assign in[23] = out[0];
assign in[24] = out[0];
assign in[25] = out[0];
assign in[26] = out[0];
assign in[27] = out[0];
assign in[28] = out[0];
assign in[29] = out[0];
assign in[30] = out[0];
assign in[31] = out[0];
assign cout = out[0];

endmodule

and the 1 bit adder module.
module yAdder1(z,cout,a,b,cin);
output z, cout;
input a, b, cin;

xor left_xor(tmp,a,b);
xor right_xor(z,cin,tmp);
and left_and(outL,a,b);
and right_and(outR,tmp,cin);
or my_or(cout,outR,outL);

endmodule

Answer: Assigning out[0] to all in wires isn't probably the best idea. What you're looking for is probably something like this:
assign {cout,in} = {out,cin};

Comment: So this concates cout with out, and in with cin ?
Answer: For this pre-lab, you're supposed imagine the 32-bit adder just like how we did our 4-bit adder in the last lab, and connect the carry-in/carry-out wires like this:
    assign in[0] = cin;
    assign in[1] = out[0];
    assign in[2] = out[1];
    assign in[3] = out[2];
    assign in[4] = out[3];
    assign in[5] = out[4];
    assign in[6] = out[5];
    assign in[7] = out[6];
    assign in[8] = out[7];
    assign in[9] = out[8];
    assign in[10] = out[9];
    assign in[11] = out[10];
    assign in[12] = out[11];
    assign in[13] = out[12];
    assign in[14] = out[13];
    assign in[15] = out[14];
    assign in[16] = out[15];
    assign in[17] = out[16];
    assign in[18] = out[17];
    assign in[19] = out[18];
    assign in[20] = out[19];
    assign in[21] = out[20];
    assign in[22] = out[21];
    assign in[23] = out[22];
    assign in[24] = out[23];
    assign in[25] = out[24];
    assign in[26] = out[25];
    assign in[27] = out[26];
    assign in[28] = out[27];
    assign in[29] = out[28];
    assign in[30] = out[29];
    assign in[31] = out[30];
    assign cout = out[31];


Primefaces datatable formatação de números

Question: Como eu posso formatar uma coluna (CEP) do datatable com a máscara "00.000-000"?
Exemplo:
Valor: 90560120 - Saída: 90.560-120
Comment: O que você já tentou?
Comment: ``, mas não achei uma forma de colocar o hífen.
Answer: Ainda estou procurando uma forma mais siples, mas acabei solucionando desta forma:
dataTable:
<h:outputText value="#{bean.format('##.###-###', item.cep, true)}" style="float:left"/>

Bean:
public String format(String pattern, Object value, boolean suppressZero) {
    if (!suppressZero || Double.parseDouble(value.toString()) != 0) {
        MaskFormatter mask;
        try {
            mask = new MaskFormatter(pattern);
            mask.setValueContainsLiteralCharacters(false);
            return mask.valueToString(value);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    } else {
        return "";
    }
}

Answer: Se você quer um input então a resposta do @Anderson é mais adequada. Caso queira apenas um OutputText ou OutputLabel eu recomendo criar seu próprio converter, teria uma semântica melhor, um entendimento mais claro do que está sendo feito e é facilmente reutilizado em outras telas.
O seu facelets ficaria:
<h:outputText value="#{seuBean.cep}">
    <f:converter converterId="CEPConverter" />
</h:outputText>

E o converter ficaria:
@FacesConverter("CEPConverter")
public class CEPConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        String[] parts = value.split("-\\.");
        return Integer.parseInt(join(parts));
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        String valueAsString = value.toString();
        return formatCEP(valueAsString.substring(0, 2), valueAsString.substring(2, 5), valueAsString.substring(5));
    }

    private String formatCEP(String part1, String part2, String part3) {
        return part1.concat(".").concat(part2).concat("-").concat(part3);
    }

    private String join(String[] parts) {
        StringBuilder sb = new StringBuilder();

        for(String part : parts) {
            sb.append(part);
        }

        return sb.toString();
    }
}

Essa é uma implementação bem simples, você pode até melhorar/customiza-lá conforme seu entendimento.
Comment: Usando `Converter` como eu poderia passar a máscara como parâmetro?
Comment: Você teria que criar uma **tag**, registrando esse Converter. Posso incluir um exemplo daqui a pouco em minha resposta. Mas a princípio, a resposta do [**lefloh**](http://stackoverflow.com/a/24905680/3404639) e do [**chuckedw**](http://stackoverflow.com/a/29398138/3404639) nessa [**pergunta**](http://stackoverflow.com/questions/11613134/custom-converter-in-jsf-2-with-arguments) abordam esse assunto.
Answer: Acredito que criar um converter que salva apenas os números seja a forma mais simples de resolver esta questão.
package br.com.t2tecnologia;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter("app.numbersConverter")
public class AppNumbersConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null) {
            return null;
        }

        return value.replaceAll("[^0-9+]", "");
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        return object.toString();
    }

}

No .xhtml:

Uso este converter para vários outros dados, como CPF, CNPJ, etc, para armazenar apenas os números na coluna do banco de dados.
Answer: O mais indicado pra usar no seu caso seria o componente inputMask do Primefaces.
No seu caso a tag ficaria assim:

Você pode encontrar mais falando da tag aqui.
Comment: O `p:inputMask` não funcionou, pois estou apenas listando os dados, não editando. Link quebrado!


Determine the dimension of $D_0$ from the equation $\frac{∂n}{∂t}=D_0\frac{∂}{∂x}\Bigg\{n^4\frac{∂n}{∂x}\Bigg\}$

Question: Consider the one-dimensional non-linear diffusion equation:
$$\frac{∂n}{∂t}=D_0\frac{∂}{∂x}\Bigg\{n^4\frac{∂n}{∂x}\Bigg\}$$
where $t$ is time, $x$ is the spatial coordinate, $D_0$ is the coefficient of diffusion and $n$ is the concentration with $[n] = ML^{−3}.$

Determine the dimension of $D_0$.
Bring the equation into non-dimensional form, if it is known that there is a characteristic value of the concentration $n_0$, and a characteristic length scale $L.$

I've been working on these 2 questions for the last couple of hours with no luck. So any help for both answers would be highly appreciated.
Comment: What have you tried?  What do you think the units of $\frac{\partial n}{\partial t}$ are?
Comment: Well in non-dimensional form, the units would be: $ML^{-3}T^{-1}$. Ive tried many things which havent worked. Could you help me get to the answer? @Matt
Answer: For the first part:
$T^{-1}ML^{-3}=[D_0]L^{-1}M^4L^{-12}ML^{-3}L^{-1}$
$T^{-1}ML^{-3}LM^{-4}L^{12}M^{-1}L^3L=[D_0]$
$T^{-1}M^{-4}L^{14}=[D_0]$
For the second:
$\bar D_0=D_0\dfrac{n_0^4}{L^2}$ with $\bar n=n/n_0$ and $\bar x=x/L$
But not completely non-dimensional:
$[\bar D_0]=T^{-1}$


derivative using chain rule

Question: $h(x)c(y)exp(w(y)t(x))$
the derivative of this with respect to y is $h(x)c'(y)exp(w(y)t(x))+h(x)c(y)w'(y)t(x)exp(w(y)t(x))$
I am having trouble with the derivative of this term because using the chain rule with three functions is throwing me off.
so $\frac{d}{dy} [h(x)c'(y)exp(w(y)t(x))+h(x)c(y)w'(y)t(x)exp(w(y)t(x))]$
Answer: Let $f(x,y)= h(x)c(y)$ & $g(x,y)=\omega (y)t(x)$. Then your expression is:
$$= f(x,y)e^{g(x,y)}$$
It is important to note that:
$$\frac{\partial}{\partial y} f(x,y)= f'(x,y)= h(x) c'(y)$$
$$\frac{\partial}{\partial y} g(x,y)= g'(x,y)= t(x) \omega '(y)$$
Taking the first derivative:
$$\frac{\partial }{\partial y}f(x,y)e^{g(x,y)}=f'(x,y)e^{g(x,y)}+f(x,y)g'(x,y)e^{g(x,y)}$$
The second derivative would be:
$$\frac{\partial ^2}{\partial y^2}(f(x,y)e^{g(x,y)}=\frac{\partial}{\partial y}f'(x,y)e^{g(x,y)}+f(x,y)g'(x,y)e^{g(x,y)})$$
$$=\frac{\partial }{\partial y}(f'(x,y)e^{g(x,y)})+\frac{\partial}{\partial y}f(x,y)g'(x,y)e^{g(x,y)}$$
The first term would be:
$$\frac{\partial }{\partial y}(f'(x,y)e^{g(x,y)})= f''(x,y)e^{g(x,y)}+f'(x,y)g'(x,y)e^{g(x,y)}$$
The second term is:
$$\frac{\partial}{\partial y}f(x,y)g'(x,y)e^{g(x,y)}=f'(x,y)g'(x,y)e^{g(x,y)}+f(x,y)g''(x,y)e^{g(x,y)}+f(x,y)(g'(x,y))^2e^{g(x,y)}$$
Altogether the second derivative is then:
$$\frac{\partial ^2}{\partial y^2}(f(x,y)e^{g(x,y)}=f''(x,y)e^{g(x,y)}+f'(x,y)g'(x,y)e^{g(x,y)}+f'(x,y)g'(x,y)e^{g(x,y)}+f(x,y)g''(x,y)e^{g(x,y)}+f(x,y)(g'(x,y))^2e^{g(x,y)}$$
Or in terms of the functions you started with:
$$=h(x)c''(y)e^{\omega (y) t(x)}+2h(x)c'(y)\omega '(y) t(x)e^{\omega (y) t(x)}+h(x)c(y)\omega ''(y) t(x)e^{\omega (y) t(x)}+h(x)c''(y)(\omega '(y) t(x))^2e^{\omega (y) t(x)}$$

derivative using chain rule


Need some explanation for the following bayesian graph

Question: I am trying to understand some lectures. A equation is presented as follows

I am confused with the first liner. Should it be  P(w,y |X) = P(y|X,w)P(X|w) P(w) ?? If the above were correct, would it mean that P(X|w) = 1. How should we explain this?
Thanks
Comment: Is this from some "data science" or "machine learning" class?  A lot of people post stuff like this on here from those sources.  The thing is, that crowd is just toying around with models that are not derived from anything. They just assert probabilistic and statistical relationships, then manipulate them, and fit models to data.  Trying to make sense of it as if it were derived from Bayes' rule or something is usually a mistake.
Comment: @Renard yah watching a lesson over there.... so it doesnt mean anything?
Answer: This is because we assume that $p(w|X) = p(w)$ (seeing values from r.v $X$ doesn't tell anything about distribution of  $w$ that you don't know before.which is pretty reasonable assumption  in case of linear regression )
$$p(w,y|X) = p(y|X,w) p(w|X) = p(y|X,w) p(w)$$

EDIT:Answer to question : Is $y$  marginally independent of
$x$ ? is NO
$y$ is actually function of $x$ (which direct form of dependence)  Here is the rigorous proof . we will use gaussian marginal property that states as follows .

$$\int_{z} \mathcal{N}(x|Az+b, L^{-1}) \mathcal{N}(z|\mu,\Lambda^{-1}) dz = \mathcal{N}(x|A\mu+b ,A\Lambda^{-1}A^{T}+L^{-1})$$

$$p(y|x) = \int_{w} p(y|w,x) p(w|x) dw = \int_{w}p(y|w,x)p(w) dw = \int_{w} \mathcal{N}(w^{T}x , \sigma^2I) \mathcal{N}(w|0,\gamma^2.I) dw = \mathcal{N}(0,\Big(\frac{x^{T}.x}{\gamma^2} + \frac{1}{\sigma^2}\Big).I ) $$
as you can $p(y|x)$ directly depends on $x$!
If your just starting in bayesian modelling . forget about the proof part just understand from the fact that $y = w^{T}.x $ ie( directly depends on $x$)
Comment: I get it! So X, w are considered to be independent of each other.. that's why P(w|X) = P(w)
Comment: could we say that knowing X, does not tell you more about y? Or in your cases, shouldn't it be p(y|X,w)P(w)P(X)?
Comment: @user1538798 added the proof. Ignore it if you don't understand and you can understand it later.
Comment: I get the idea that y is dependent on X from the graph relations... what i said earlier is not correct


Proof that $a\equiv 1\,(\textrm{mod }8)$ implies $a$ is a square modulo $2^n$ for all $n$

Question: I know some elementary proofs of this fact. I was wondering if there's some short slick proof of this fact using the structure of the $2$-adic integers? I'm looking for a proof of this fact that's easy to remember.
Comment: @asdfg: the shortest proof I can think of uses Hensel's Lemma.  Do you count that as "using the structure of the $2$-adic integers"?
Comment: @Pete: Now that you mention it, letting $f(X)=X^2-a$, we have $|f(1)|_2=1/8$ while $|f'(1)^2|_2=1/4$, so $|f(1)|<|f'(1)|_2$ i.e. by Hensel, we find a root in $\mathbb{Z}_2$ and hence modulo every $2^n$. I guess this is as short as it gets.
Comment: $a=17, n=5.\ a\equiv17\mod2^5,$ but 17 is not a square... or didn't I understand your statement?
Comment: @FUZxxl: Is 17 a square *modulo* $2^5$? That is, does there exist $x$ such that $x^2\equiv 17\pmod{2^5}$?
Comment: Ah! I missunderstood. Thank you.
Answer: There is indeed a $2$-adic proof.
$(1+u)^{1/2} = 1+\sum_{k \geq 1} \binom{1/2}{k} u^k$ where $\binom{1/2}{k}= \frac{1/2(1/2-1) \ldots (1/2-k+1)}{k!} = 2^{-k}(-1)^{k-1}\frac{(2k-3) (2k-5) \ldots 3}{k!}$.
We would like the sum to converge, and for this we only need the general term to go to $0$.
$v_2\left(\binom{1/2}{k} u^k\right)=k(v_2(u)-1)-v_2(k!)$.
Furthermore, $v_2(k!) = \sum_{l \geq 1} \left\lfloor\frac{k}{2^l} \right\rfloor < k$, so if $v_2(u)>2$ the series converge and the fact that as formal series (i.e. in $\mathbb{Q}[[u]]$) $\left(1+\sum_{k \geq 1} \binom{1/2}{k} u^k\right)^2=1+u$ tells you that you really find a square root of $1+u$ by taking the limit.
Of course if $v_2(u)>2$ all the terms are in $\mathbb{Z}_2$, so the limit is also in $\mathbb{Z}_2$.
Comment: Awesome. I've always wondered what can be done with those binomials involving fractions after I noticed them while flipping through Stanley's enumerative combinatorics.
Answer: The shortest proof I can think of goes as follows. Hensel is not needed. A counting argument will suffice.
We take as the starting point that the group of units $U_n$ of the ring $\mathbf{Z}/2^n\mathbf{Z}$ has the structure $U_n\simeq C_2\times C_{2^{n-2}}$. Therefore exactly one quarter of elements of $U_n$ are squares.
Assume $n\ge3$. For an odd integer $m$ to be a quadratic residue modulo $2^n$ it is surely necessary for $m$ to be a quadratic residue modulo 8. We easily check (or know in advance) that for $m$ to be a quadratic residue modulo 8 it has to be congruent to 1 modulo 8. Thus exactly one quarter of the odd integers in the range $[0,2^n]$ are quadratic residues modulo 8. As this is a subset of the equinumerous set of squares of $U_n$, the two sets must coincide.
Edit: Or was this exactly (one of) the elementary proof(s) you know? I think that this is easy to remember, though :-)


Android EditText type number fazer aparecer teclado com números e virgula

Question: Estou trabalhando com valores no editText e preciso que o input seja somente com números e virgula para ponto flutuante. Eu tentei com inputType="numberDecimal" mas ao abrir o teclado só permite o ponto e não a virgula. preciso o input no padrão brasileiro... ex: 1,00
<EditText
android:id="@+id/tf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:digits="0123456789,"
android:inputType="numberDecimal"
 />

Alguem ja passou por isso?
Comment: Você teria como apresentar o código em questão aqui @programadorCS ?
Comment: opa, desculpa, havia colocado mas por algum motivo não apareceu na pergunta, coloquei na resposta
Comment: Edit sua pergunta e adicione o código por favor.
Comment: Aqui tem uma solução https://www.youtube.com/watch?v=ydF4sQr8kAs
Comment: Murillo Comino, não funcionou
Comment: O que eu costumo fazer é deixar o input com o "." mesmo, mas altero o textwatcher que pra quando usar o "." troque para ",".
Comment: Murillo Comino  estou dando replace no onTextChanged porem esta travando o componente parece que entra em loop quando digito
Answer: consegui criando um textWatcher para o componente:
 TextWatcher() {
        private String current = "";
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals(current)) {
                String clean = s.toString();
                if(current.contains(",") && clean.contains(".") ){
                    clean = clean.replace(".", "");
                }
                clean = clean.replace(".", ",");
                current = clean;
                editText.setText(current);
                editText.setSelection(current.length());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

A questão é que agora alguns dispositivos no teclado o botão ','(virgula) se transforma em '.' (ponto), preciso que seja o teclado com virgula apenas.
Answer: consegui pessoal, houve uma confusão de teclado de diferentes diapositivos, bug do android.
ao invés de fazer um novo teclado chamei o padrão 12 digitos para ser sempre o mesmo, e limitei digitos e virgula no xml do EditText
xml:
android:digits="0123456789,"
android:inputType="numberDecimal"

java:
editText.setRawInputType(Configuration.KEYBOARD_12KEY);


Sincronização com Team Explorer no VS 2015

Question: Ao tentar fazer um Sync recebo a mensagem:

Cannot pull because there are uncommitted changes. Commit or undo your
  changes before pulling again. See the Output window for details.

Ao tentar fazer um Push recebo a mensagem:

You cannot push branch master to remote origin because there are new
  commits in the remote repository's branch. Pushing this branch would
  result in a non-fast-forward update on the branch in the remote
  repository.

O correto seria fazer um merge, certo? Mas recebo a mensagem:

An error occurred. Detailed message: 1 uncommitted change would be
  overwritten by merge

Onde resolvo este conflito?
Antecipadmente, agradeço
Diógenes
Answer: Pode ter arquivos (novos/alterados) que não estão no seu commit (Untracked files).
É possível identificá-los pelo prompt de comandos do Git. Navegue até o diretório raiz do projeto/repositório (exemplo cd c:/Documentos/SeuRepositorio), digite "git status", por exemplo:

Note que o arquivo "octocat.txt" não está sendo rastreado (é um untracked file).
Se você gostaria de commitar os arquivos, adicione-os ao seu commit, digite "git add ." para o Git reastrear todos os arquivos ou "git add nomeDoArquivo", exemplo "git add octocat.txt".
Em seguida digite git commit -m "Texto do seu commit aqui!" para criar um commit.
Caso contrário, descarte-os (consulte aqui a documentação para maiores detalhes antes de executar os comandos), você poderia usar git reset --hard ou git reset nomeDoArquivo. Para desfazer alterações indesejadas você poderia usar git checkout -- nomeDoArquivo.


Lomax distributions - Kullback Leibler divergence

Question: Does anyone know of a reference for an expression for the Kullback-Leibler divergence between two Lomax (Pareto II) distributions? Not really worried which way the Lomax is parameterized.
Answer: Using the parametrization from Wikipedia
$$
  p(x; \alpha, \lambda) = \frac\alpha\lambda \left( 1+\frac{x}\lambda \right)^{-(\alpha+1)}
$$ with shape $\alpha>0$, scale $\lambda>0$ and define the Kullback.Leibler divergence as at Intuition on the Kullback–Leibler (KL) Divergence
$$   \DeclareMathOperator{\KL}{KL}
\KL(P || Q) = \int_{-\infty}^\infty p(x) \log \frac{p(x)}{q(x)} \; dx
$$ we can see what maple gives us. First, assume equal scale parameters, then I get
$$ \KL(p(\alpha_1,\lambda || p(\alpha_0,\lambda) = \frac{\ln \! \left(\alpha_1 \right) \alpha_1 -\ln \! \left(\alpha_0 \right) \alpha_1 +\alpha_0 -\alpha_1}{\alpha_1}
$$   while the general case looks quite unhelpful, involving some special functions:
$$
   \KL(p(\alpha_1,\lambda_1 || p(\alpha_0,\lambda_0) =
   {{\frac {1}{\lambda_1}\,\Gamma \left( {\alpha_1}+1 \right) }
 \left( -{{\alpha_1}}^{2}
G^{2, 2}_{2, 2}\left(1\, \Big\vert\,^{0, 1-{\alpha_1}}_{0, 0}\right)
{\lambda_1}+{\alpha_1}\,{\lambda_0}\,
G^{2, 2}_{2, 2}\left({\frac {{\lambda_0}}{{\lambda_1}}}\, \Big\vert\,^{-1, -{\alpha_1}}_{-1, -1}\right)
{\alpha_0}+\ln  \left( {\alpha_1} \right) {\lambda_1}\,
\Gamma \left( {\alpha_1} + 1 \right) -\ln  \left( {\alpha_0}
 \right) {\lambda_1}\,\Gamma \left( {\alpha_1} + 1 \right) +\ln
 \left( {\lambda_0} \right) {\lambda_1}\,\Gamma \left( {\alpha_1}+1 \right) -\ln  \left( {\lambda_1} \right) {\lambda_1}\,\Gamma \left( {\alpha_1}+1 \right) -{\alpha_1}\,
G^{2, 2}_{2, 2}\left(1\, \Big\vert\,^{0, 1-{\alpha_1}}_{0, 0}\right)
{\lambda_1}+{\alpha_1}\,{\lambda_0}\,
G^{2, 2}_{2, 2}\left({\frac {{\lambda_0}}{{\lambda_1}}}\, \Big\vert\,^{-1, -{\alpha_1}}_{-1, -1}\right)
 \right) }
$$ where $G$ is the Meijer G function. That does not look too useful, so for practical use one can solve each concrete case with maple:
<code>p := (x,alpha,lambda) -> (alpha/lambda) * (1+x/lambda)^(-(alpha+1))
LomaxKL := (alpha_0,alpha_1,lambda_0,lambda_1) ->  int(
    p(x, alpha_1, lambda_1) * log( p(x, alpha_1, lambda_1)/
    p(x, alpha_0, lambda_0) ),  x=0..infinity)

LomaxKL(2,3,1,1)
                                       1
                       ln(3) - ln(2) - -
                                       3

LomaxKL(1/2,1/3,1,2)
                   3  (1/3)
      -4 - ln(3) + - 2      ln(2)
                   2

           3  (1/3)   /   (2/3)      (1/3)    \
         - - 2      ln\4 2      - 8 2      + 4/
           4

           3  (1/3)   /     (1/3)    (2/3)\
         + - 2      ln\1 + 2      + 2     /
           4

           3  (1/2)  (1/3)       /1  (1/2) /   (1/3)    \\
         - - 3      2      arctan|- 3      \2 2      + 1/|
           2                     \3                      /

           3  (1/3)  (1/2)
         + - 2      3      Pi
           4
</code>
The last in mathematical notation is
$$ -4-\ln \! \left(3\right) + \frac{3 \, 2^{\frac{1}{3}} \ln \! \left(2\right)}{2} -  \\   \frac{3 \, 2^{\frac{1}{3}} \ln \! \left(4 \,2^{\frac{2}{3}} - 8 \, 2^{\frac{1}{3}} +  \\   4\right)}{4} + \frac{3 \, 2^{\frac{1}{3}} \ln \! \left(1 + \\   2^{\frac{1}{3}} + 2^{\frac{2}{3}}\right)}{4} - \\   \frac{3 \sqrt{3}\, 2^{\frac{1}{3}} \arctan \! \left(\frac{\sqrt{3}\, \left(2 \,2^{\frac{1}{3}} +  \\1\right)}{3}\right)}{2} +  \\  \frac{3 \,2^{\frac{1}{3}} \sqrt{3}\, \pi}{4}
$$