Backup table from custom module using backup and migrate

Question: I have a module that allows a user to add to a custom table in bulk via a custom form. But before they do so I'd like to backup that table to the private folder. Does anyone know if it is possible to create a new profile in the Backup and Migrate module and save a table using code in a custom module?
So what I'd like to do is programmatically create a Backup and Migrate profile in my modules .install file. Then in my custom form submit function, trigger the backup using that profile.
Answer: I've had a look at the Backup and Migrate code and I've come up with a solution, one that works for me at least.
I've created a function that gets the default profile data, then alters that to save only the tables I want. It seems to work well but if anyone can see any possible problems with this solution please do let me know.
The function:
<?php
/**
 * @param $tables
 *  An array of table names that will be backed up.
 * @param $filename
 *  Text prepended to the date when naming the backup file.
 */
function _MYMODULE_backup_custom_tables($tables, $filename = 'custom-backup') {
  module_load_include('module', 'backup_migrate');

  // get default profile settings
  backup_migrate_include('files', 'profiles');
  $settings = _backup_migrate_profile_saved_default_profile();

  // set the destination to our private folder
  $settings->destination_id = 'manual';
  $settings->source_id = 'db';

  // get a list of all tables from the database
  $schema = drupal_get_schema();
  ksort($schema);
  $drupal_tables = array();
  foreach ($schema as $table => $table_schema) {
    $drupal_tables[$table] = $table;
  }

  // remove from the database table list the tables we would like to save
  foreach ($tables as $table) {
    unset($drupal_tables[$table]);
  }

  // alter default filters so only the tables we want will be backed up
  $settings->filters['destinations']['db']['nodata_tables'] = array();
  $settings->filters['destinations']['db']['exclude_tables'] = $drupal_tables;

  // change the filename so we can identify the backup in the directory
  $settings->filename = $filename;

  // backup tables
  backup_migrate_perform_backup($settings);
}
?>

The function can then be used like this:
<?php
// the names of the tables we want to save
$tables = array(
  'custom_table_one',
  'custom_table_two',
);

// the text to use when naming the backup file
$filename = 'my-custom-backup';

_MYMODULE_backup_custom_tables($tables, $filename);
?>


Trouble using a richfaces tabPanel with dynamic tabs

Question: I saw on richfaces showcase that the best way to use rich:tabPanel with dynamic tabs is with a4j:repeat, but this doesn't work in my application.
This is my code:

<h:head>
    <title>Java EE 6 Starter Application</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</h:head>
<h:body>
    <h:form>

            <ui:insert name="topArea"/>

            <ui:insert name="mainArea"/>

            <ui:insert name="footerArea"/>

    </h:form>
</h:body>

In topArea,  I have this menu:
<rich:panelMenu>
    <rich:panelMenuItem label="Clienti" name="Clienti"  action="#{tabsBean.addTab()}"     render="tabsPanel" />
</rich:panelMenu>

in mainArea, I have this tabPanel:
<rich:tabPanel id="tabsPanel" switchType="client"  activeItem="#{tabsBean.activeTab}" >
    <a4j:repeat  value="#{tabsBean.tabs}" var="tab">
        <rich:tab name="#{tab.name}">
            <f:facet name="header">#{tab.name}</f:facet>
            <h:form>
                <h:outputText value="Enter Name:" />
                <h:inputText id="input" />
                <h:outputText value="Enter you interests:" />
                <h:inputTextarea cols="17" rows="3" />
                <h:outputText value="Choose your favourite color" />
                <h:selectOneMenu>
                    <f:selectItem itemLabel="Red" itemValue="0" />
                    <f:selectItem itemLabel="Black" itemValue="1" />
                    <f:selectItem itemLabel="Green" itemValue="2" />
                    <f:selectItem itemLabel="White" itemValue="3" />
                </h:selectOneMenu>
            </h:form>
        </rich:tab>
    </a4j:repeat>
</rich:tabPanel>

My troubles are:

The tabs are not created
Why does the showcase use a nested form? Won't nested forms cause trouble?

Thanks
Comment: which version of richfaces you are using?
Answer: Dynamic tabs with a4j:repeat are supported since 4.3.0.Final only, refer here for more details:
http://www.bleathem.ca/blog/2013/01/dynamic-panels-with-a4jrepeat.html
For earlier versions c:forEach items="#{tabsBean.tabs}" var="tab" can be used.
Comment: I tried to use c:forEach items="#{tabsBean.tabs}" var="tab",  but in this case i have the following trouble within of the tabs "a4j:commandLink , a4j:commandButton doesn't work at first click but work only after second click"


What is This Strange Ternary-Looking Operation?

Question: I've been reading through the Flux library source code, and in a few places I see this notation:
?: ?

I'm not sure if this is a strange use of the ternary operator, or something else entirely.
Several good examples of confusing usage of this can be found in the function declaration starting on line 245 of the FluxContainer.js file:
function createFunctional<Props, State, A, B>(
    viewFn: (props: State) => React.Element<State>,
    getStores: (props?: ?Props, context?: any) => Array<FluxStore>,
    calculateState: (prevState?: ?State, props?: ?Props, context?: any) => State,
    options?: Options,
): ReactClass<Props> {
    /** Omitted Implementation Details **/
};

What is happening here, such as in props?: ?Props?
Answer: That's a flow type notation.
The param?: ?Type notation means that param is an optional parameter and that Type is a maybe type. It basically accepts the Type plus undefined and null.


Mirrored Audio Frames

Question: I'm following along with The Audio Programming Book by Richard Boulanger. In Chapter two we create several basic audio rate oscillators using C and the standard libraries to generate simple WAV files.
Both my implementation and the book's code exhibit a strange issue:
I am able to generate a simple sine wave using sin() (from math.h), but noticed the playback has a bit of static. Upon investigation I noticed that occasionally, some of the audio frames at peak amplitude are getting "flipped" to a negative value.
To debug this situation, I'm outputting the values of the audio frames generated to stdout and this flipping behavior lines up with the peak value of 0.999999.
When I scale the output by 0.99 this problem disappears. What's going on?
Answer: Looking at siggen.c I was able to find the real problem has to do with the maximum value conversion to short datatype:
portsf.c:78
#define MAX_16BIT (32768.0)

portsf.c:1618
ssamp = (short) psf_round(fsamp * MAX_16BIT);

When we have a float sample near 1.0 this results in the conversion (short)(32768). Given that a short can only hold up to 32767 the value gets wrapped to the smallest short possible, -32768.
To fix this, I suggest modifying line 1618 to instead read:
ssamp = (short) psf_round(fsamp * 32767.0);

This will reduce the peak-to-peak value range by 1, but well worth avoiding this problem in my opinion

Mirrored Audio Frames


Cast de vetor char para ponteiro

Question: Galera como funciona um cast em um vetor char para um ponteiro int?
por exemplo:
char vetor[2];
int *p;
p = (int *)&vetor;

Alguém pode me explicar essa linha?
Comment: Esse código irá pegar cada elemento do vetor char, converter pra inteiro e colocar no vetor de inteiros..
Comment: Até onde entendo, isso cria um ponteiro para um valor inteiro que por sua vez é o endereço de memória vetor de char (do primeiro elemento do vetor). Fora de contexto assim, não serve pra nada.
Answer: Primeiramente é necessário entender o que exatamente um ponteiro armazena, independentemente do tipo do ponteiro ele terá como principal função armazenar um endereço, que pode ser qualquer local da memória como variáveis, funções de seu programa e até mesmo funções externas como de DLLs e outros. Em maquinas 32 bits os ponteiros tem geralmente 4 bytes, que pode apontar qualquer lugar dos primeiros quase 4GB de memória e em maquinas 64 bits os ponteiros costumam ter 8 bytes, que é o suficiente para mapear qualquer lugar da memória de quantidades muito maiores.
Quando você tem um tipo com um ponteiro (por exemplo: void* out int*), você apenas esta informando ao compilador, quantos bytes a partir do endereço esta representando o valor. Veja esta imagem:

Como você pode ver na imagem acima, o ponteiro p2 apenas aponta para o endereço 5 e pelo fato de seu tipo ser int (4 bytes), quando você vai obter o valor em que o ponteiro p2 esta apontando ele vai obter os bytes do endereço 5 + os do tamanho informado ao ponteiro (4 neste caso), ou seja, o valor do int será os valores das posições da memória 5, 6, 7 e 8.
Quando você tem um ponteiro void, este ponteiro continua com sua função de armazenar endereços, porem não é possível obter valor, pois o tipo void não representa nenhum tamanho, assim a única utilidade de se ter um ponteiro void é o armazenamento do endereço na memória.
Mas lembre-se novamente, independentemente se o tipo do ponteiro é void ou int ele continua a ocupar os 4 bytes (ou 8 em 64 bits) para armazenar o endereço em que ele esta apontando.
No caso do seu código, quando você aponta int *p; para char vetor[2]; o ponteiro int *p; somente armazenara o endereço de char vetor[2];, este cast p = (int *)&vetor; é somente para passar o endereço de vetor como se fosse o mesmo tipo, porem não será possível você obter o valor desse endereço sem fazer outro cast, pois ao tentar obter o valor de *p como se ele fosse um int, ele acabaria obtendo o valor de dois bytes a mais que não pertence ao char vetor[2];, veja o porque:

Como você pode ver na imagem acima o char vetor[2]; ocupa 2 bytes (pois cada char ocupa 1 byte), quando você passa o endereço do char vetor[2]; para int *p; com um cast e tentar obter o valor de int *p; ele consideraria que o valor seria o endereço em que o *p aponta mais o tamanho do tipo a ele informado (neste caso int = 4 bytes), ou seja, ele obteria os dois bytes da array vetor, e ainda obteria dois bytes a mais de fora da array vetor para formar um valor int.
Se você quer passar caracteres, números ou strings em forma de ponteiro int, isto é possível, mas depois você tem que fazer outro cast para representar novamente o valor, veja este exemplo.
// Transforma em ponteiro int
char vetor[] = "Hello World!";
int *p = (int *)&vetor;
// Trannsforma em ponteiro char
char *text = (char*)p;
printf("%s", text);
// Output: Hello World!

Porem se o foco é somente passar um endereço, é melhor que se utiliza ponteiro void que não vai obter bytes a mais na memória do que o tamanho determinado. Veja este exemplo de ponteiro void que aponta para função:
#include <stdio.h>

int GetFive()
{
    return 5;
}

typedef int (*FUNÇÃO)();

void MostraRetornoDaFunção(void* função) // Esta função recebe uma função como um ponteiro void
{
    int (*fun)() = (FUNÇÃO)função; // Aqui é necessario fazer um cast para mostrar que o *void é uma função
    int a = fun();
    printf("%d", a);
}

int main()
{
    void *funcPtr = &GetFive;
    MostraRetornoDaFunção(funcPtr);

    printf("\n");
    system("PAUSE");
}

Então basicamente o cast servira apenas para passar o endereço para o ponteiro como se a variável apontada fosse do mesmo tipo, e o tipo servira apenas para saber quais bytes após o endereço apontado será usado como valor.
Espero ter ajudado
Comment: 11/10 Perfeita Explicação

Cast de vetor char para ponteiro


remote login to ubuntu server via SSH

Question: I have 3 Ubuntu machines. First one (A) is my local machine, second one (B) is a gateway to the third (C) Ubuntu server. I can SSH from my local machine, A, to B and then SSH from B to C. I can't SSH from A to C directly.
What I need is to remotely log (graphical) into C from B? and if possible from A? I'm no network guy and the tunneling concept and port 3389 is confusing me.
Appreciate your help.
Comment: You did not explain why port 3389 was confusing you and why you have to use it? I guess it is equivalent the port 7722 from the well described example below? Maybe the question would be clearer then to some down voters (actually I voted you up, because I found the solution via this question! )
Answer: Confusing or not, you need tunneling. The easiest:
ssh -L 7722:address.of.C:22 address.of.B

will log you into B. At the same time, it will set up a tunnel between the current machine's port 7722 (can be any unused port over 1024, I arbitrarily selected 7722) and C's port 22 (the ssh port). Then, in another terminal,
ssh -X -p 7722 localhost

will open a SSH connection to your local port 7722, which is being tunneled to C's 22. It is functionally equivalent to ssh address.of.C while the above tunnel exists.
When you are done, just exit the second connection to leave C, then exit the first connection to deconstruct the tunnel.

If you don't have two terminals to work with, it is a bit more complex since you need a way to refer to the tunnel in order to be able to close it later.
ssh -fNM -S /tmp/tunnel.B.to.C.control 7722:address.of.C:22 address.of.B

ssh -X -p 7722 localhost

ssh -O exit -S /tmp/tunnel.B.to.C.control address.of.B

Here, /tmp/tunnel.B.to.C.control is an arbitrary name of file in a location where you can create a file. The first command sets up a tunnel and exits (instead of logging in), but stays in memory and records its activities in the named file. The last command then releases the tunnel, the memory and the file.
Comment: Thanks! Can you recommend me a nice tutorial about SSH covering the topic?

remote login to ubuntu server via SSH


find text in html with javascript and return following string

Question: I'm writing a simple chrome extension that looks for the name of a wordpress theme a page is running. Would it be the easiest to parse for "wp-content/theme" and then return the next word after theme?
Example:
Find - wp-content/theme/
<code><link rel="stylesheet" id="pagelines-pro-css" href="http://example.com/wp-   content/themes/platformpro/"
</code>
Return text - Plateforpro
Answer: Except that themes can be inside subfolders of theme. You gotta watch out for that.
Answer: you could get the link with jQuery and check if it is the link with the wordpress theme and then get the last part like this:
<code>$('link').each(function() {
    var href = $(this).attr('href');
    if (href.indexOf('wp-content/themes') != -1) {
        if (href.lastIndexOf('/') == href.length - 1) {
            href = href.substring(0, length- 2);
        }
        var theme = href.substring(href.lastIndexOf(/), href.length - 1);
    }
}
</code>
Comment: Except now that the last part might me style.css or similar (especially in wordpress.com).
Comment: So what's wrong? I don't get your comment. Could you explain so I can improve my answer? @dda
Comment: It means that the last part might not be the subfolder where the theme resides, but the css file itself. My advice would be split the string at '/', pop the last element, if it's a file (xxxx.yyy), pop the previous element, and THAT should be the folder. OTOH, if it's not a file, then good.
Comment: that's true, but my answer works for a link as given in the question, so how could I have known? But i'll improved it later today. @dda
Comment: You couldn't know, of course. I happen to have a blog hosted on wordpress.com and it just happens to fall in the /theme/subfolder/coraline/style.css?m=... case.


pegar nome de usuário logado com Spring Security

Question: Olá, venho aqui pedir ajuda sobre Spring Security.
Gostaria de saber como consigo pegar o nome do usuário logado. Eu utilizo autenticação com login e senha porém quando utilizo o método de busca ele me retorna o login, sendo que preciso pegar o nome do usuário.
public String getUsuarioLogado() {
            FacesContext context = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
            usuarioLogado = (Usuario) session.getAttribute("usuarioLogado");
            Authentication authentication = (Authentication) SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
               authentication.getName();
            }
            return authentication.getName();

    }

Comment: Olá! Poderia nos passar o código que está utilizando para pegar o login? Apenas para termos uma base do que já tentou fazer. Provavelmente você conseguirá a informação que precisa no `SecurityContextHolder.getContext().getAuthentication()`.
Comment: Obrigado por Responder Dherik
Comment: Quais os campos da classe Usuario? O nome que  quer fica nesta classe?
Answer: A maneira mais fácil de acessar as informações do usuário logado é pelo SecurityContextHolder:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

String nome;

if (principal instanceof UserDetails) {
    nome = ((UserDetails)principal).getUsername();
} else {
    nome = principal.toString();
}

Comment: mais essa variavel nome eu passo ela aonde?
Comment: @Dherik, dentro de um método Async isso pode vir a falhar?
Comment: @danilo não vai falhar
Comment: @CíceroRégisOliveira a variável nome foi só para ilustrar como pegar a informação do usuário logado
Comment: Ajudou muito, no meu caso ainda para melhorar no meu sistema, retornei um objeto do tipo Usuario fazendo um cast (Usuario) para converter e deu certo, obrigado pela resposta!


Is this an anomaly detection problem?

Question: The following is a plot of a response (y) variable.  It's a continuous variable (one month future returns on a set of stocks).  I'm particularly interested in predicting the tails.
Many machine learning algorithms optimize on something like mean square error (mse). They equally weight the error of each observation. In this set of 2850 returns we care more the roughly 3-6% of the observations at the extremes than the others. Let's say we are going to buy the 50 stocks with the highest predicted returns and short the 50 with the lowest. We really want these rankings to be correct. Yet most algorithms will care as much about the 95% as the 5%.
My main question/request is should this be treated as anomaly detection? And please point me to links or references to dealing with this sort of problem.
Here's what I'm hoping to learn.  Is there a way to weight some observations more than others? Is there a way to create a custom cost function?  I've heard of boosting.  Is there a way to boost the model specifically at the extremes?
Answer: I'd recommend looking into the mathematical tools developed and utilized for probabilistic risk assessment. This field was developed in the early 80's to help manage the risks of nuclear power, but has obviously spread to other areas of engineering. Essentially, it looks at those tails for you. It looks at the extremes, because...well, those are the rare conditions under which engineered systems fail.
Comment: This is more a comment than an answer.

Is this an anomaly detection problem?


How to solve the recurrence $()=5(/2)+^3()$ using iteration method

Question: How do we solve the recurrence $()=5(/2)+^3()$ using the Iteration method?
I solved the recurrence using a master method - master method
Now using the iteration method
$()=5(/2)+3() = 5(5T(/4)+(n/2)^3)*log(n/2))+n^3*logn$ $=$ ... $= 5^i(n/2^i)+n^3*log(n) * ∑(n^3*(5^k) *log(n/2^k) ) / 8^k) $
How is it equal to $Θ(n^3log(n))$ ?
Comment: Does it have to be iteration method?
Comment: @DanielV yes, I try to solve it by the iteration method
Comment: What does $i$ stand for?
Answer: Let $u_k:=T(2^k)$. Then substituting $n=2^k$ in the given equation, $$u_k=5u_{k-1}+8^kk$$
This can be solved in the usual way, $$u_k=\tfrac{1}{3} 8^{k+1} (k-\tfrac{5}{3}) + C5^k$$ Substituting $k=\log_2n$, $5^k=5^{\log_2n}=n^{\log_25}$, $$T(n)=\tfrac{8}{3}n^3(\log_2 n-\tfrac{5}{3})+Cn^{\log_2 5}=O(n^3\log_2 n)$$
Answer: Do the substitution:
$$\begin{array} {rcl}
T(n) &=& n^3\log(n) \\
     &+& 5(n/2)^3\log(n/2)\\
     &+& 5^2(n/2^2)^3\log(n/2^2)\\
     &+& 5^3(n/2^3)^3\log(n/2^3)\\
     &+& \dots \\
\\
&=& n^3\log(n) \\
     &+& 5/2^3 n^3 (\log n - \log 2)\\
     &+& 5^2/2^6 n^3 (\log n - 2\log 2)\\
     &+& 5^3/2^9 n^3 (\log n - 3 \log 2)\\
     &+& \dots \\
\\
&=& n^3\log(n) (1 + 5/2^3 + 5^2/2^6 + 5^3/2^9 + \dots) \\
&-& n^3\log(2) (0 + 1\cdot 5/2^3 + 2\cdot 5^2/2^6 + 3 \cdot 5^3/2^9 + \dots )\\
\end{array}$$
That's a geometrics series and an arithmetico-geometric series.  But you don't actually need to calculate them to get the asymptotic behavior, since it is just going to be some positive constants.


how to parse id from php page to html-jquery page via jsonp

Question: I have problem to get jsonp from my server by id.
I am sure that my php is good, but i don't know how to parse id from php server to htlm-jquery.
My php page is:
<?php

header('Content-type: application/json');

include 'config.php';

$con = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect: " . mysql_error());
mysql_select_db($dbname, $con);

$id=$_GET['id'];

$sql = "select * from ios where id=$id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
$records[] = $row;

}

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

////////////////////
?>

And this works great, i got json object by id in php.
You can check for example http://www.dr-trkuljic.com/tekst.php?id=1 (you can try with id 2, 3, and 4) you will get result.
But i don't know how to parse that in jquery in my html page
I am using this in my html page:
 $(document).ready(function(){
    var output = $('.nesa');
    $.ajax({
        url: 'http://www.dr-trkuljic.com/tekst.php',
        dataType: 'jsonp',
        data: 'id',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function(data, status){
            $.each(data, function(i,item){

                //var ispisi = '
' + item.naziv + '
' ;

                var ispisi = item.naziv + item.tekst;

                output.append(ispisi);
            });
        },
        error: function(){
            output.text('There was an error loading the data.');
        }
    });
});

So, my question is how to parse (show) by id in my html page?
To be precise how that result from my server http://www.dr-trkuljic.com/tekst.php?id=1 get in my html page?
Thank you.
Answer: 1 If you are on the same domain
In php change
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

to
echo json_encode($records);

JS success:
success: function(data, status){

    var jsonData = JSON.parse(data);
    var total = jsonData.length;

    for(var i = 0; i < total; ++i){
        var ispis = jsonData[i].naziv + " " + jsonData[i]item.tekst;
        console.log("My ispis ", ispis);
    }
}

2 if you want to use JSONP. (get response from another domain or phonegapp )
When you need a response from another domain you can't use AJAX request, what you can do is load a new script in document for example in  tag, You load that script as js script with your response. Inside that js script you put your response in some variable, and also you can call some function that is defined in already loaded js file. for example
echo "var myVar = " . json_encode($records) . '; myCallbackFunc();';

Than load that file as js file to your document
and somewhere in that or where ever js that you want to get response - myVar will contain your response that you can use, and when response load your callback function will be called
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.dr-trkuljic.com/tekst.php?id=1';
head.appendChild(script);

function myCallbackFunc(){
    // Do something with myVar

    var total = myVar.length;

    for(var i = 0; i < total; ++i){
        var ispis = myVar[i].naziv + " " + myVar[i]item.tekst;
        console.log("My ispis ", ispis);
    }
}

EDIT
Just double check if server response - javascript syntax is ok.
Comment: i am not on same domain. I am trying to build phonegap app, so my html is not on same domain and i need to use jsonp. I didn't quite understand what you write. Could you write me what goes in html file. Thanks
Answer: As I felt my previous answer was incorrect, allow me to edit:
After you remove the '(' and ')' from around the json array, you can simply use this quick and easy shorthand format for your jQuery http call: (all parsing is already performed because of the Content-Type header). You are then free to access the appropriate properties of the object.
For further examples on how to use jQuery's $.get() and $.post(), etc... visit this link:
http://api.jquery.com/category/ajax/shorthand-methods/
$(document).ready(function(){
    var output = $('.nesa');
    var idNumber = 1;

    $.get('http://www.dr-trkuljic.com/tekst.php', {id: idNumber}, function(data, status){
        $.each(data, function(i,item){

            //var ispisi = '
' + item.naziv + '
' ;

            var ispisi = item.naziv + item.tekst;

            output.append(ispisi);
        });
    }).fail(function(){
       output.text('There was an error loading the data.');
    });
});

To overcome cross-domain errors, you can send this header in your php file with the appropriate url of where you're working from:
header("Access-Control-Allow-Origin: http://your-domain-or-localhost");

Comment: Thank you for trying to help me. Could you please suggest me example how to do that, i am really not familiar with jquery. Thanks
Comment: To start out with, apparently you have an error in your json from your php file. I am coming up with a parse error because your json array is surrounded with a set of parenthesis: i.e. ([{}]). This should start and end with just the square brackets: [].
Comment: Thank you again for trying to help me. With this example i got Cross-Origin Request Blocked, because i am trying to connect with my local machine to my server. I am using this tutorial for this: http://samcroft.co.uk/2011/updated-loading-data-in-phonegap-using-jquery-1-5/   Also i can't use id:1, because in that way i would limit query just to 1. I need something that when i click id=1 get 1, or id=1000 get 1000 and so on. Do you have any idea what to do? Thank you.
Comment: I have updated the answer with a variable replacing the id#. I'll leave it up to you to determine how the variable is assigned, but that should get you going. As for the cross-origin requests, I have added an example header to be placed in your php file to be sent back to your browser. Also, you can achieve this by looking into the  .httaccess file on your server to allow cross-domain requests.


When using aTSA and Forecast Packages together forecast() function and Arima() gives error

Question: I have been trying to use aTSA and Forecast package together and noticed that the Arima() function works but the forecast() give error. Does anyone have a solution for this or encountered this? I am especially trying to use stationary.test() from aTSA and that was the main reason I called the library.
error: Error in forecast(.) : 'object' should be 'Arima' or 'estimate' class estimated from arima() or estimate()
As soon as I removed aTSA, the above worked.
fitArima_CO <- Arima(train_CO, order=c(4,1,1))

  fit_CO %>%
    forecast() %>%
    autoplot() +
    autolayer(test_CO, colour = TRUE, series = 'Test Data') +
    ylab("Adjusted CO") +
    guides(colour=guide_legend(title = "Data Series"), fill=guide_legend(title = "Prediction Interval")) +
    scale_color_manual(values=c("gold"))

Answer: Unfortunately the aTSA package does not play nicely with other time series packages. In particular, its forecast() function will overwrite the forecast() function from the forecast package.
The stationarity.test() function will do an ADF test by default. You can easily do the same test using the adf.test() from the tseries package.
Comment: Dr. Hyndman, thank you so much sir. I have been benefiting a lot from your material available online for my project which is a time series forecasting of pollutants in Toronto and I am learning everything on my own. Thank you for sharing your wisdom.


Múltipla seleção não funciona no IE

Question: Fiz um post em como com uma escolha, selecionar todos os itens. Recebi uma resposta, que resolveu. bem, resolveu apenas no Chrome, mas no IE não funciona. Como a pergunta mudou a "direção", então resolvi fazer um outro post. Inclui outras versões do jquery e mesmo assim não funcionou.
Esse é o código do meu select(html).

                                Autorização Prévia:

                                    <select id="ddl_autorizacaoprevia" multiple="multiple" >
                                        <option value="0">TODAS AS AUTORIZAÇÕES</option>
                                        <option value="T">TÉCNICA / ADMINISTRATIVA</option>
                                        <option value="A">SISTÊMICA</option>
                                        <option value="N">NÃO PRECISA</option>
                                    </select>

Esse é o jquery que faz a seleção de todos os itens em um único clique:
$('#ddl_autorizacaoprevia option').click(function () {

                var that = $(this);
                if (that.val() == 0) {
                    $('#ddl_autorizacaoprevia option').each(function () {
                        $(this).attr('selected', 'selected');
                    });
                } else {
                    $('#ddl_autorizacaoprevia option').each(function () {
                        $(that).removeAttr('selected');
                    });
                    $(that).attr('selected', 'selected');
                }
            });

Então, esse código funciona bem no Chrome, mas não funciona no IE. O que pode ser? Só funciona com Ctrl+Clique, aí consigo selecionar todos, mas somente ao clicar o primeiro índice(índice = 0), aí não seleciona todos os itens, mas no Chrome funciona e o browser homologado pela empresa é o IE e não chrome, logo tenho que fazer funcionar no IE.
Comment: Segundo o que descreveu e baseado no código que postou, é esse o comportamento lógico que deve ocorrer. Quando clica num valor que não seja o ZERO, desmarca todos os outros e marca somente o que está "clicado". Está confuso na sua descrição sobre o que realmente não funciona ou qual o comportamento que deseja.
Comment: Ok, o que eu quero dizer que esse comportamento só funciona no Google Chrome. No IE não funciona. O código é funcional, só não no IE.
Comment: Se eu faço uma pergunta, querendo duas resposta, recebo downvote e um conselho a abrir outro post. Aí abro outro post e recebo downvote do mesmo jeito, porque parece ser uma pergunta repetida, por usar o mesmo código, porem com pergunta diferente. Queria entender.
Comment: Nessa linha `$('#ddl_autorizacaoprevia option').each(function () ` se eu removo o option, consigo fazer a seleção múltipla, mas apenas se não houver nenhum selecionado. Caso eu selecione algum e depois clico no Item de índice 0, aí não funciona mais. Mas se recarrego a página(deseleciono tudo), dessa forma funciona. Entendi que o IE não "gosta" do option.
Answer: Olá,
acho que não precisava de tudo isso, faça o teste com esse código:
$('#ddl_autorizacaoprevia option:first-child').click(function () {
    $('#ddl_autorizacaoprevia option').each(function () {
         $(this).attr('selected', 'selected');
    });
});

Veja este exemplo aqui:
https://jsfiddle.net/1vwb5nxp/
EDIT
Fiz uma implementação em javascript puro pra ver se resolve o seu problema, segue o código:
function qs(q) {
   return document.querySelector(q);
}
function qsa(q) {
   return document.querySelectorAll(q);
}
qs("#ddl_autorizacaoprevia option:first-child").onclick = function (ev) {
    var todos = qsa('#ddl_autorizacaoprevia option');
    Array.prototype.slice.call(todos).forEach(function (e) {
        e.setAttribute('selected', 'selected');
    });
}

Exemplo do código: https://jsfiddle.net/kws9vrzp/
EDIT 2
Outra opção para ver se funciona no IE:
Código HTML (note que tirei o atributo multiple e coloquei o atributo size):

                            Autorização Prévia:

                                <select id="ddl_autorizacaoprevia" size=4 >
                                    <option value="0">TODAS AS AUTORIZAÇÕES</option>
                                    <option value="T">TÉCNICA / ADMINISTRATIVA</option>
                                    <option value="A">SISTÊMICA</option>
                                    <option value="N">NÃO PRECISA</option>
                                </select>

Javascript - Note que eu atribuo o multiple por aqui:
function qs(q) {
   return document.querySelector(q);
}
function qsa(q) {
   return document.querySelectorAll(q);
}

qs("#ddl_autorizacaoprevia option:first-child").onclick = function(){
   var select = qs("#ddl_autorizacaoprevia");
   var tamanho = select.length;
   select.multiple=true;
   select.focus();
   for(var i=0;i<tamanho;i++){
      select.options[i].selected=true
   }
}

Exemplo pode ser visto funcional aqui: https://jsfiddle.net/Ls77e84e/
EDIT 3
Fiz algumas adaptações, mas foi a maneira que consegui fazer pegar o que foi pedido no Internet Explorer, veja se interessa:

    Autorização Prévia:

        <select id="ddl_autorizacaoprevia" size=4 >
            <option value="T">TÉCNICA / ADMINISTRATIVA</option>
            <option value="A">SISTÊMICA</option>
            <option value="N">NÃO PRECISA</option>
        </select>
        <input id='selecionarTudo' type="checkbox"> TODAS AS AUTORIZAÇÕES

JS:
function gi (q) {
        return document.getElementById(q);
    }
    gi("selecionarTudo").onclick = function () {
        var el = this;
        var select = gi("ddl_autorizacaoprevia");
        var tamanho = select.length;
        if(this.checked == true){
            select.multiple = true;
            // select.focus();
            for(var i=0;i < tamanho;i++){
                select.options[i].selected = true;
            }
    //Caso ache válido pode descomentar essa linha;
            //select.disabled = true;
        } else{
            select.multiple = false;
            select.disabled = false;
            for(var i=1;i < tamanho;i++){
                select.options[i].selected = false;
            }
        }
    }

JSFiddle: https://jsfiddle.net/yjqgq37L/
Comment: Guilherme Lopes, abri o seu fiddle no IE e não funcionou. Experimente abri-lo no IE e veja se funciona? Comigo aqui não funfou.
Comment: Estou sem o IE para testar aqui, veja o EDIT para ver se resolve.
Comment: Guilherme, continua não funcionando no IE. Na empresa em que estou, só interessa o IE. Não funcionou mesmo. Li que o IE tem problemas com o Option do Select. E parece que procede essa informação.
Comment: Qual é a versão do IE que interessa?
Comment: A minha aqui é a 11.0.24(atualizada). Versões anteriores também usam. O site é usado por mais 1.000 usuários da empresa, em todo o Brasil. Não tenho como te informar, mas o IE é o único navegador homologado, logo pode ser qualquer versão. Esses testes foram feitos na versão citada.
Comment: Fiz uma adaptação nessa última edição e funcionou, caso ajude, está ai.
Comment: Valeu mesmo pela ajuda. Não é isso. Estamos conversando com a área de negócio da empresa e apresentando uma outra solução. Espero que eles aceitem, mas mesmo assim, eu agradeço, Guilherme, pela ajuda. Essa última, com um checkbox fora, está fora do escopo.

Múltipla seleção não funciona no IE


"default" is not exported by "tailwind.config.js"

Question: I want to use a theme variable for Tailwind inside the Nuxt code for Storybook. Everything looks fine in development but when I build Storybook, I get an error "default" is not exported by "tailwind.config.js".

I tried to follow what is written here but I still get errors. Could anybody help me with a good solution for this?
vite.config.js
import path from 'node:path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      'tailwind.config.js': path.resolve(__dirname, 'tailwind.config.js'),
    },
  },
  optimizeDeps: {
    include: [
      'tailwind.config.js',
    ],
  },
  build: {
    commonjsOptions: {
      include: ['tailwind.config.js', 'node_modules/**'],
    },
  },
})

tailwind.config.js
// /** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    screens: {
      mobileS: '320px',
      mobileM: '375px',
      mobileL: '425px',
      tablet: '500px',
    },
  },
}

inside the component
import tailwindConfig from 'tailwind.config.js'
import resolveConfig from 'tailwindcss/resolveConfig'

const screens = resolveConfig(tailwindConfig).theme?.screens
console.log(screens)

Comment: If you use tailwind.config.js as es module then don't define it as commonjs. Did you try to not use module.exports and commonjsOptions?
Comment: Instead of `import` try with `require` - or instead of `module.exports = ` try with `export default`
Answer: tailwindcss added native ESM (and TypeScript) support in v3.3.
https://tailwindcss.com/blog/tailwindcss-v3-3#esm-and-type-script-support.
In my case, I migrated the tailwind.config.js by changing imports & exports:
Before:
const colors = require('tailwindcss/colors');
const plugin = require("tailwindcss/plugin");

module.exports = { ... }

After:
import colors from "tailwindcss/colors";
import plugin from "tailwindcss/plugin";

export default { ... }

within my vite codebase, I was then able to access config values like this
import resolveConfig from "tailwindcss/resolveConfig";

import tailwindConfig from "../../tailwind.config.js";

const { theme } = resolveConfig(tailwindConfig);

theme.colors.gray[500]

Comment: This answer must be marked as right


TECLADO DIMINUI AO SETAR android:inputType="number""

Question: Colocando tal configuração em um EditText, ao compilar o teclado fica "largado" na tela
segue o xml da EditText
<code>   <EditText
            android:id="@+id/edtIP"
            android:layout_width="652dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:gravity="center"
            android:singleLine="false"
            android:inputType="number"
            android:textSize="20dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="parent" />
</code>
ficando da seguinte forma:
Answer: Este é o comportamento mesmo. Ao configurar o input type para number o android automaticamente abre o teclado numérico, ou altera do teclado completo para o numérico, se você não quiser esse comportamento o mais fácil é alterar o input type para text.
<code>android:inputType="text"
</code>
Comment: Vou deixar o teclado original e atribuir uma mascara para deixar o usuario digitar somente numeros, obrigado!
Comment: Eu gostaria que ele ficasse numerico porém com o comportamento do teclado normal!
Comment: @iDecks esse comportamento você não controla. Isso varia de aparelhos. Se houver alguma forma de controlar isso, seria usando o contexto, mas eu acredito que não há. O que você pode fazer é montar o seu próprio teclado...
Comment: @iDecks é uma opção interessante.


How to completely un-install SQL Server

Question: I had installed SQL Server 2008 SP2 Eval and got into some problems. Another post in this forum helped me to retry installation - Problems installing SQL Server 2008 SP2
However when i rerun installation it just loops back with no results. Is there one batch of commands which will make the PC just forget it ever had SQL Server in it, remove all registry, folders, and traces whatsoever,  and allow me to do a fresh install ?
Thanks,
Chak.
Answer: After uninstall use something like CCleaner to get rid of registry problems.
Also make sure your not choosing an option on uninstall to save settings.
Answer: To answer the question, there isn't a tool specific to removing a hosed SQL server installation.
The main problem you are seeing that is causing the install loop, is that reg and directory entries still exist.
Best way, is to uninstall all the components that it will let you from Add/Remove Programs. Then, physically delete the SQL server directories and registry entries.
There was this  tool back in the day for automatically removing Office and other MS products that worked fantastically on just about anything else on a machine, but is no longer supported. If you do a search for the .exe file, it exists all over the place.
From personal experience, and dealing with all flavors of SQL on a daily basis, I would recommend seeking out the tool if you find items in Add/Remove Programs that will not come out.
Answer: Try manually unstalling SQL: http://support.microsoft.com/kb/955404

How to completely un-install SQL Server


Block nmap xmas scan from detecting my server's open port

Question: I have blocked all the basic nmap scans using iptables by making a rule in the INPUT chain that if the no of packet send from a particular ip within 10 seconds exceeds a particular limit then put that ip in blacklist and deny the further packets. This way the nmap SYN Stealth Attack, SYN connect, UDP and all other basic scans are blocked Now I want to block nmap xmas scan. Can somebody tell me how to do that.
I have written the following rules:
$ iptables -A INPUT -m state --state NEW -m recent --set --name NEW
$ iptables -A INPUT -m recent --update --seconds 10 --hitcount 5 --rttl --name NEW -j DROP
Thanks in advance
Comment: Hiding open ports adds nothing. Security be obscurity is no security at all.
Comment: @ChrisS You mean security through obscurity **by itself** is not security. Unless you would like to fork over your passwords, keys, banking credentials, IDs etc.? Remember when `/etc/passwd` actually had the salted+hashed passwords and how easy it was to get a server to send it to you? Even so if the firewall detects a ports can then there's no problem at all blocking all packets from then on. That only makes sense - their intentions are dubious at best.
Answer: Can you be more specific about the rule that you've configured?
As you've described it, it would block an X-mas scan; a packet lit up with flags like a Christmas tree would still be a packet "sent from a particular IP" - but if that's truly how you've set up your rules, then you're likely going to unintentionally ban hosts sending legitimate traffic at a rate that violates the rule.
Don't put a lot of effort into security by obscurity.  You service is open to the internet, and a scanner can simply slow their scan rate to a crawl to defeat your rate limit, or they can randomly hit the open port before the block kicks in.  Blocking scans is not a substitute for securing your service.
Comment: +1, although the fact that "Blocking scans is not a substitute for securing your service" doesn't mean scan blocking shouldn't be implemented as well.
Answer: <code>iptables -A INPUT -p tcp --tcp-flags ALL ALL -j LOG --log-prefix "XMAS A: "
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

iptables -A INPUT -p tcp --tcp-flags ALL FIN,PSH,URG -j LOG --log-prefix "XMAS B: "
iptables -A INPUT -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP

iptables -A INPUT -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j LOG --log-prefix "XMAS C: "
iptables -A INPUT -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP
</code>
nmap -sX sends the xmas type B that I have above (I just made "type b" up).
the canonical xmas is type A.
http://techhelplist.com/index.php/tech-tutorials/43-linux-adventures/120-nmap-linux-iptables-xmas-packets
obviously you can add in the time limit stuff.
Comment: Dead link. Internet Wayback Machine to the rescue: https://web.archive.org/web/20130506045630/https://techhelplist.com/index.php/tech-tutorials/43-linux-adventures/120-nmap-linux-iptables-xmas-packets


Given $y=\frac{3+sin(2x)}{2+cos(2x)}$ find the equation of the tangent

Question: Given the function $y=\frac{3+\sin(2x)}{2+\cos(2x)}$ find an equation of the tangent C at the point C such that $x=\frac{\pi}{2}$.
I calculated the derivative ($\frac{6+\sin(2x)+4\cos(2x)+2}{(2+\cos(2x))^2}$), substituted $x$ with $\frac{\pi}{2}$ and got the slope of $-2$. The equation of the tangent hence has the form of $y=-2x+m$. What I should do to find the $m$?
Answer: Let $\xi$ be the value of the function at $\pi/2$; then $(x,y)$ lies on the tangent line through $(\pi/2, \xi)$ iff $y - \xi = -2(x-\pi/2)$, which is equivalent to $y = -2x + \xi + \pi$.


Understanding how to compile C++ project

Question: I'm new to coding and Visual Studio. I know and understand how to create, save and compile a new C++  project in Visual Studio. I understand that a new VS project creates a solution file in the directory which then I can use to open the project, etc.
What I don't understand is how to compile a C++ project which doesn't have a VS solution file. I mean, do I have to manually create a project and import files and then build it?
Please take this GitHub project as an example. Under information, it clearly states the following:

<code>                              Building
</code>
To build a static library (./lib/ompeval.a) on Unix systems, use make.
To enable -msse4.1 switch, use make SSE4=1. Run tests with ./test. For
Windows there's currently no build files, so you will have to compile
everything manually. The code has been tested with MSVC2013, TDM-GCC
5.1.0 and MinGW64 6.1, Clang 3.8.1 on Cygwin, and g++ 4.8 on Debian.

Now, what I don't understand is how do I build this project in my VS software so that I can successfully run it? Any help would be appreciated. Thank you.
Comment: That ReadMe seems to be pretty clear on this part: *"For Windows there's currently no build files, so you will have to compile everything manually."* There are multiple ways of doing this, creating new VS project is one of them.
Comment: There is a Makefile that can wok on windows if you use mingw instead of Visual Studio. The .a files are static libraries that gcc produces. In Visual Studio it may just work if you create a Windows console project and just add the files.
Answer: As you said it, create a new project in Visual Studio and just import the source and header files. Looking at the makefile, there doesn't seem to be any pre or post build events so you can import the files and compile them right away (as long as the code is platform compatible ofc).
You may have to create multiple projects. One for the static library and one for the test files, since Visual Studio projects usually have one output type only. Mostly one of the presets: dynamic library (dll), static library (lib) or executable (exe).
Comment: Visual studio projects can have any kind of output, they just have built-in settings for dll, lib and exe.
Comment: @VTT true, but since OP is new to VS it's negeletiable imo, Anyway, fixed.


Add multiple objects into an array using JS

Question: Need to create a specific array of objects with the given objects.
Now I have used object of assign.
Here is
var str = [{componentName: "Transformer", type: "PUB", beanName: "TransformerExtractor", state: "enabled", config: {"test":"test"}},{componentName: "DBEE", type: "PUBSUB", beanName: "DBEErExtractor", state: "enabled", config: {"test":"test"}}];

var A1 = [];

var B1 = [];

finalOutput = [];

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

    alert(str.length);

    var output = {};

    output.flowId = "Flow1234";

    output.flowAlias = "Flow1234";

    output.description = "Flow1234";

    output.state = "Enabled";

    A1.push(output);

    alert (A1);

    B1.push(str[i]);

    alert (B1);

    finalOutput = [A1, B1].map(o => Object.assign({}, A1, o));
}

alert (finalOutput);

return finalOutput;

Could you please tell me how do I get my expected result like [{A1,B1(from first set of variable str),{A1,B1(from 2nd set of variable str)]
Comment: [How to push object into array](https://stackoverflow.com/questions/40250139/push-object-into-array/40251425)
Comment: Please create a minimal reproducible example, your code is far from minimal and that makes it hard to read.
Comment: Are you trying to achieve `A1+B1` and `A1+C1 ` ?
Comment: push-object is not working for getting my expected result
Comment: Okay i see, this might be helpful [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
Comment: see the answer by nina, it demonstrates the use of it. it will also overwrite the duplicate keys.
Comment: Yes Kratos and using Nina's solution I am getiing like below {"str1":{"0":"componentName":"Transformation","type":"PUBSUB","beanName":"transformer","state":"enabled","config":"{\n\"area\": \"testVM\",\n\"pubTo\": \"trf_p\",\n\"subFrom\": \"db_p\",\n\"project\": \"testVM\",\n\"section\": \"FT\"\n}"},"1":"componentName":"testComponent","type":"PUB","beanName":"testComponent","state":"enabled","config":"{\"testComponent\":\"testComponent\"}"},"flowId":"ABC100","flowAlias":"","description":"","state":"enabled","creationDate":""}}
Comment: Now I want to avoid 0 and 1. Also the common section need to add to each of that part
Comment: Hi Kratos, I have edited my code by using Object Assign, yet still fighting to get desired data. Could you please help me.
Answer: Taking the data from the last edit, you could define a template object for the data you like to add to a new object along to the objects of the array.

var data = [{ componentName: "Transformer", type: "PUB", beanName: "TransformerExtractor", state: "enabled", config: { test: "test" } },{ componentName: "DBEE", type: "PUBSUB", beanName: "DBEErExtractor", state: "enabled", config: { test: "test" } }],
    template = { flowId: "Flow1234", flowAlias: "Flow1234", description: "Flow1234", state: "Enabled" },
    result = data.map(o => Object.assign({}, template, o));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comment: Thanks Nina for your solution. Although using your idea I am getting like below
{"str1":[{"0":"flowId":"ABC100","flowAlias":"","description":"","state":"enabled","creationDate":""},"1":"flowId":"ABC100","flowAlias":"","description":"","state":"enabled","creationDate":""}},{"0":"componentName":"Transformation","type":"PUBSUB","beanName":"transformer","state":"enabled","config":"{\n\"project\": \"testVM\",\n\"section\": \"FT\"\n}"},"1":"componentName":"testComponent","type":"PUB","beanName":"testComponent","state":"enabled","config":"{\"testComponent\":\"testComponent\"}"}}]}
Comment: it looks, you have different data, then posted.
Comment: Sorry again. Still  I am fighting. I have edited my code here https://jsfiddle.net/e03onuxk/
Comment: it's a complete different data set. please post what you have and what you want.
Comment: Thanks Nina. This is my code https://jsfiddle.net/e03onuxk/4/  and expected result will be like above.
Comment: you try to add data to an object which you already have. `A1` to `A1`, which is confusing.
Comment: According to my fiddle https://jsfiddle.net/e03onuxk/5/  I want to get {A1,One set of B1},{A1,another set of B1} and so on.
Comment: please ask a new question with raw data, your try and the wanted result.
Comment: Could you please give  me a hint here since my ask question limit has been expired for this month :(
Comment: alternatively, you could append this question with the data, you have and the wanted result out of it. actually it's quite unclear, **why** you want to get a different result than posted from me and others.
Comment: Hi Nina, I have edited my code by using Object Assign, yet still fighting to get desired data.
Comment: you want to add `flowId`, `flow...`, and so on to every object of `str`?
Comment: Yesss Nina but I could not make it done :(
Comment: please have a look.
Comment: Thanks a lot Nina. This is working for me and today I have learnt a new in JS. Thanks again.
Answer: You could use lodash if you just want merge them
data = _.merge(A1, B1)

Comment: getting below error
Uncaught ReferenceError: _ is not defined
Comment: you need to add **lodash** to your project
Comment: Here I can't use this. I have edited my code here https://jsfiddle.net/e03onuxk/


Como mudar a cor de um SVG dinamicamente com props no React?

Question: Estou tentando mudar a cor de um SVG através das props, mas não estou conseguindo.
Meu componente Hexagon que no qual eu recebo a cor via props e verifico com um switch:
function Hexagon({ size, text, color }) {
  let hexagonColor;
  switch (color) {
    case "green2":
      hexagonColor = style.green2;
      break;
    default: {
      hexagonColor = style.green2;
    }
  }
  return (

{text}

  );
}

Aqui é onde eu chamo o componente e passando a cor:
function Navbar() {
  return (

        <Hexagon text="Planejar" color="green2" />
        <Hexagon text="Planejar" color="green2" />

        <Hexagon text="Planejar" color="green2" />
        <Hexagon text="Planejar" color="green2" />

  );
}

Aqui está o meu arquivo CSS:
.green2 path {
  fill: #8e18d2;
}

Já verifiquei e a classe realmente aparece no componente, veja na imagem abaixo
Comment: onde está `style`: (`style.green2`)?
Comment: Acho que um SVG que vc incorpora como  vc não consegue trocar cor assim, pelo menos não no html.... da uma olhada aqui as vezes te ajuda https://pt.stackoverflow.com/questions/286686/mudar-a-cor-de-um-svg-por-um-bot%c3%a3o/286696#286696
Comment: Você pode tentar usar SVG como um componente com o [SVGR](https://react-svgr.com). O seletor `.green2 path` não vai funcionar porque a tag `img` não irá renderizar o SVG dentro dela, você pode ver pela própria print da tag que não possui nenhum `` ou `` ali.
Comment: @Pedro se é um css anexo ao componente, não é só colocar o nome ?
Comment: O svg nada mais é do que um arquivo XML, você pode setar um cor em javascript nele, exemplo: `` -> `document.querySelector(".svgClass").getSVGDocument().getElementById("svgInternalID").setAttribute("fill", "red")`
Comment: novic o style.green2 esta no arquivo css meu
Comment: @ Rafael Tavares nunca vi esse SVGR, vou dar uma olhada, é q eu n queria ter q instalar uma lib so pra fazer isso
Comment: @Novic n entendi muito bem o q vc disse ;-;
Comment: Vcs tinham razao pessoal, como img ele n rendenderiza nunca, tive que importar como um componente mesmo, Obrigado a todos pela ajuda. vo posta a resolução nos comentários
Comment: [Veja esse exemplo](https://stackoverflow.com/questions/9872947/changing-svg-image-color-with-javascript)
Answer: Consegui resolver apenas importante o svg como um componente, pois a img nao renderiza o svg na tela, fiz da seguinte forma
import { ReactComponent as HexagonSVG } from "./hexagon.svg";

Logo abaixo, foi apenas usar ele como um componente mesmo, dessa maneira
<HexagonSVG
        className={`${style.hexagon} ${hexagonColor} ${hexagonSize}`}
 />


Sobre passagem por referência e por valor

Question: Não consigo entender quando usar um ou outro. neste código, usei as duas formas e não vi alteração no final. Qual a diferença e quando devo usar um ou outro
Crie um procedimento que receba dois valores por referência e ordene-os
em ordem crescente. Crie um algoritmo principal para chamar o
procedimento e exibir os valores após a ordenação.
Algoritmo "procedimento"

Var
 x, y: inteiro

   Procedimento crescente(var A,B: inteiro)
   var
   cres: inteiro
   inicio

   Se (a < b) entao
         para cres de a ate b faca
            Escreva(cres)
            cres <- cres + 1
         fimpara
      Senao
        para cres de b ate a faca
             Escreva(cres)
             cres <- cres + 1
        fimpara
      Fimse

   FimProcedimento

Inicio

  x <- 10
  y <- 20

  crescente(x, y)

Fimalgoritmo

Answer: Fiz um pequenos ajustes no seu programa. Não fique triste comigo! : )
Procurei explicar da melhor forma possível!
Algoritmo "procedimento"
Inicio

    Var x, y: inteiro

    x <- 10
    y <- 20

    crescente(x, y)

    escreva(x)
    escreva(y)

Fim

/*
  Comentario:
    Neste procedimento o primeiro parâmetro A é passagem por referência, porque precede de var,
                           então o valor de A será alterado mudando o valor de x.
                       o segundo parâmetro B é passagem por valor,
                           então o valor de B será alterado SOMENTE dentro do procedimento e não vai alterar o valor de y.
*/
Procedimento crescente(var A, B: inteiro)

  inicio
        Se (A < B) entao
            para A ate B faca
                Escreva(A)
                A <- A + 1
            fim-para
        Senao
             para B ate A faca
                Escreva(B)
                B <- B + 1
             fim-para
        fim-se
   fim

Fim-Procedimento

Fim-algoritmo
Vamos executar o seu programa:
X = 10  (Valor inicial)
Y = 20  (Valor inicial)
fez a chamada do procedimento: crescente(10,20)
executando dentro do procedimento crescente:
A = 10
B = 20
Como 10 é menor do que 20 vai entrar na primeira condição (Se (A < B)).
Então vai executar o laço de repetição (para) vai executar de 10 a 20 e acaba a estrutura de repetição.
A = 10
exibe 10
A = 11
exibe 11
...
A=20
sai do procedimento crescente.
acrescentei dois comandos escreva para x e y depois do procedimento crescente.
exibe 20 (valor final de x)
exibe 20 (valor final de y)
Boa prática de programação é fazer uma boa indentação do seu código para tornar claro o entendimento do código e ajuda muito na manutenção (possíveis mudanças que precisam ser feitas).
[visualg]
Comment: Obrigado, é um pouco confuso pra mim. Aliás bastante. Vou rodar esse código, digamos que se eu tirar o var, pra ver o que acontece
Comment: Por nada! Se tirar o VAR o parâmetro torna-se por valor.  O VAR que define parâmetro por referência. No início é assim mesmo, tem que persistir, pois com a prática que aprende.


Unity C# OnTrigger/OnCollision Sound

Question: Note: It's a 2D Game
I'm trying to get an audio clip to play when the Character comes into contact with an object that has a Box Collider around it.
I've tried OnTrigger/OnCollision methods but neither are playing any sound. I've also tried many solutions online but still no sound on collision. My Clip works on Awake, but not as intended.
Checklist:

The Player has a "Player" tag.
The Player has a Rigidbody 2D and a Collider 2D
The Oject Collider has 'Is Trigger' ticked
The Object has an AudioSource
The Object has an Audio Script
The Object has a Box Collider 2D for the collision around it
The Audio Clip is attached to the AudioSource component

Here's the current Script (Attached to Object):
I'd be very thankful!
public class Audio : MonoBehaviour
{

    public AudioSource audioClip;

    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            audioClip.Play ();
        }
    }
}

Comment: The box collider of the object is marked as trigger you mean? Is that collider the same size as object or bigger (it should be bigger)?
Comment: Yes I did mean the collider around the object, sorry! And yes, the collider is wider than the object itself, which is a sprite. The collider is 2x the size of the object itself. As I want the clip to play as the Player enters the collider space.
Comment: Is this 2D or 3D? There are different versions of collider, rigidbody and the OnTriggerX/OnCollisionX functions for 2D and 3D.
Comment: It is a 2D platformer.
Comment: Ok, you changed your stuff to use 2D components, but how about `OnTriggerEnter`? Do you use that or `OnTriggerEnter2D`?
Comment: Tried both OnTriggerEnter2D and OnCollisionEnter2D, neither play the sound for me.
Comment: are you perhaps using 3d primitives with the 2d Colliders stuff. Thats the only way I managed to replicate your issue. With Sprites and 2d Colliders your code works just fine.
Comment: Solved by adding the object into the Scripts audio clip box after attaching it onto the object....xD
Comment: Do not put SOLVED: in a title on this site. This is a Q&A site, not a forum. Instead post an answer to your your own question then mark the answer accepted.
Answer: In order to find out what is wrong, you can start by simplifying the problem.
You can start by doing something simple in OnTriggerEnter2D, that you know will work, such as a Debug.log
void OnTriggerEnter2D(Collider2D collision)
{
    Debug.Log(this.gameObject.name+ " collided with "+collision.gameObject.name)
}

This way, you will know if it's the collision or the audio that's the problem.
It may be, that the collision works, but you are unable to hear the audio because of wrong settings or some other minor detail you have missed.

Unity C# OnTrigger/OnCollision Sound


Gnuplot rowstacked histogram plot with black and white hatch patterns

Question: I have to create Graphs like this image below, I tried to use gnuplot and zplot to create this, but the patterns are not as expected. Did someone know some library or anything to create this pattern(as image bellow). I appreciate for that. Thanks
Answer: What you need is the following histogram type with different fill style patterns
For example if you would want a black&white stacked histogram, then you could create them by doing the following:
file1 = 'hist1.dat'

set style data histogram
set style histogram rowstack
set style fill pattern

set xtics border in scale 0,0 nomirror rotate by 90  offset character 0, -6, 0
set boxwidth 0.9 absolute

set key outside right top vertical Left
set key samplen 2.5 spacing 0.85

set ylabel "Cost BreakDown (%)" font ",18" offset character 2.5,0,0

 plot newhistogram , file1 u 2:xtic(1) t "Math" lc rgbcolor "black" lt 1 fs pattern 1, '' u 3 t "Innvocation" lc rgbcolor "black" lt 1  fs pattern 2

where the contents of file1 could be like this
Read-GetAttr 19 12
Read-If-Mod 47 23

The above will render the following graphic:

You can further add more layers on the stack by having the corresponding data and changing the fillstyle pattern fs. Further you can also change them to coloured histograms by using different rgbcolor values
Posting this here in case this may be useful for someone else in the future:
I also pulled up some work that I did previously, You can download a complete working example of coloured stacked Histograms with data files and gnuplot script from the following link:
Coloured Stacked Histograms Working Example
Comment: You may want to use colours in addition to the fill style patterns in order to distinguish them or try a different output terminal which may allow more than 9 patterns.
Comment: I know, that the `lua tikz` terminal has 12 patterns, see [Fill bars in gnuplot with dots or other patterns](http://stackoverflow.com/a/23034300/2604213) for an example, also about customizing the fill patterns.
Comment: @indi60 Note, that the patterns may vary a bit depending on your output terminal. Use the `test` command (see e.g. http://stackoverflow.com/a/19420678/2604213) to see the available patterns.
Comment: @Christop brings up a good point. I should add that the plot above was generated by output terminal set to `set term pngcairo`, you could use others such as `set term post eps` according to your need.
Comment: @ZahaibAkhtar thanks for explanation. Yes I understand to created it now. But here, gnuplot only have 8 pattern. what do you suggestion if we have more that 8 legend.
Comment: @Christoph, yes I am doing what you suggest. but still need more pattern option for this. thanks
Comment: Was anyone able to reproduce the exact same patterns presented in the image with the eps or pdfcairo terminal ? Because I cannot ...
Comment: @ValerioSchiavoni with `set term post eps color` I'm getting exactly the same pattern on an eps.
Comment: @ValerioSchiavoni Ahh I see, I was referring to my solution. Haven't checked the patterns in the original image, not sure if the original image was generated using Gnuplot in the first place. I guess only OP can answer that.


How do you call a button in another sheet using another button in Excel?

Question: I have a command button in Sheet1 and I want to activate it using button (form control) in Sheet2.
I have written on Module1 (almost same code with command button in Sheet1)
Function DataUpdate()
If (validateVer() = False) Then
    Exit Function
End If

Dim AsCn, AsRs, SQL
Dim x, y, WDATE, NGQTY, FAQTY, RWQTY, RNQTY, TotalCell, TotalCellx
Dim FA_TBL As Variant   ' (y, x)
Dim RW_TBL As Variant   ' (y, x)
Dim RN_TBL As Variant   ' (y, x)
Dim NG_TBL As Variant   ' (y, x)

'Sheet => Table
Sheet1.Range("C2:GS2").Select
Selection.ClearContents
FA_TBL = Sheet1.Range("A2:GS2")
Sheet1.Range("C4:GS4").Select
Selection.ClearContents
RW_TBL = Sheet1.Range("A4:GS4")
Sheet1.Range("C5:GS5").Select
Selection.ClearContents
RN_TBL = Sheet1.Range("A5:GS5")
Sheet1.Range("A9:GS208").Select
Selection.ClearContents
Sheet1.Range("C9").Select
NG_TBL = Sheet1.Range("A8:GS208")

...
Sheet1.Range("A2:GS2") = FA_TBL
Sheet1.Range("A4:GS4") = RW_TBL
Sheet1.Range("A5:GS5") = RN_TBL
Sheet1.Range("A8:GS208") = NG_TBL

...
Sheet1.Range("A8:" & TotalCellx & "100").Select
Selection.Sort Key1:=Range(TotalCellx & "9"), Order1:=xlDescending, Header:=xlGuess _
    , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    SortMethod:=xlPinYin
Sheet1.Range("C9").Select
End Function

I have written on Module2 (code for my form control button at Sheet2):
Sub Command1_Click()
Sheet1.Range("C8:GF8").Value = Sheet1.Range("C240:GF240").Value
Sheet1.Range("B7").Value = Sheet1.Range("B240").Value
r = DataUpdate()
End Sub

However, I get the

"Run-time error '1004': Select method of Range class failed".

Is there any way I can call or link my command button at Sheet1 to my form control button at Sheet2?
Comment: A better option is to [avoid using `Select`](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba), as you don't need to.
Comment: But it also gets and error if I remove Select.
Comment: What's the error message and on what line?
Answer: In Sheet1
Public Sub ClickMe()
   MsgBox "You Clicked"
End Sub

In Sheet2 CommandButton Click Code
Private Sub CommandButton1_Click()
   Sheets("Sheet1").ClickMe
End Sub

Making the Routine Public makes it callable from outside the Sheet


Finding exponential limit

Question:
Finding $$\lim_{n\rightarrow \infty}n^{-n^2}\bigg\{(n+1)\bigg(n+\frac{1}{2017}\bigg)\bigg(n+\frac{1}{2017^2}\bigg)\cdots\cdots \cdots \bigg(n+\frac{1}{2017^{n-1}}\bigg)\bigg\}$$

My Try: Assume $$l=\lim_{n\rightarrow \infty}n^{-n^2}\prod^{n}_{r=1}\cdot\bigg(n+\frac{1}{2017^{r-1}}\bigg)$$
$$\ln (l) = -\lim_{n\rightarrow \infty}n^2\ln(n)+\lim_{n\rightarrow \infty}\sum^{n}_{r=1}\ln\bigg(n+\frac{1}{2017^{r-1}}\bigg)$$
could some help me how to solve it, thanks
Comment: Seems that the first expression is wrong? Should the $n^{-n^2}$ be to the left of the $\Pi$?
Answer: Each term in parentheses is not larger than $n+1$.  So $l$ is not greater than the limit of $n^{-n^2}(n+1)^{n}$, which is zero.
Comment: There is a typo. There are $n$ terms in the product so you should have $(n+1)^n$ instead of $(n+1)^{n+1}$ but this typo does not make any difference to the answer. Also "smaller" should be replaced with "not greater" because $l$ is equal to $0$. +1 for a simple approach to a complicated looking problem.
Comment: Thanks,but I think that there is no typo.  Notice that besides the 2017 terms there is an additional $n+1$.  Corrected the "smaller".
Comment: you can check again. the number of terms in product is $n$ including the first factor $(n +1)$.
Comment: Oh right I see!  I must be getting old.  At least my argument is still correct even with this typo -:)
Comment: Yes your argument was correct even with the typo (the term $n^{-n^{2}}$ dominates other factor and brings the whole thing down to zero) and that's why you already got an upvote from my end.
Answer: My reasoning:
Leave the productory, since you have to be careful about sums and limits inside sums and so on.
The major term of the productory will be $n^n$. The others are neglected by the dominating term $n^{-n^2}$.
Hence you are left with $n^{-n^2 + n}$ .
Which goes to $0$
Comment: Yes, "that". If you have a sound proof, simply post it. (Unrelated: FYI, "Productories" does not seem to be an English word.)
Comment: No. Please be aware that using "identities" such as $$\lim_{n\to\infty}\sum_{k=1}^nx_{k,n}=\sum_{k=1}^\infty\lim_{n\to\infty}x_{k,n}$$ is a sure way to reach chaos.
Comment: Too lazy to write $\lim$. It's understood.
Comment: Actually it is not.
Comment: @Did The productory major term will be $n^n$, the other can be neglected due to the limit. Hence one remains basically with $n^{-n^2 + n}$ which goes as $n^{-n^2}$ which is zero.
Comment: @Did Oh that! Well my reasoning is independent from that. I could delete that part, actually. My other reasoning was just about using the productory and stop. But if it's wrong then please post an answer so I will learn something :D Productories always confused me.
Comment: @Did Haha I know, I am just lazy and many times I invent words :D
Comment: Ah, now we have a precise statement, which is wrong, since the $n$th term is not less than $$n^{-n^2+n}$$
Comment: @Did Ugh. Ok let's do this: wait till I'm at home. Being on a train doesn't help...
Comment: This must be a very slow train.

Finding exponential limit


Basic Question Regarding the Universal Property of the Tensor Product.

Question: (All vector spaces are over a fixed field $F$).

Universal Property of Tensor Product. Given two finite dimensional vector spaces $V$ and $W$, the tensor product of $V$ and $W$ is a vector space $V\otimes W$, along with a multilinear map $\pi:V\times W\to V\otimes W$ such that whenever there is multilinear map $A:V\times W\to X$ to any vector space $X$, there exists a unique linear map $\bar A:V\otimes W\to X$ such that $\bar A\circ \pi = A$.

Notation. We write $\pi(v,w)$ as $v\otimes w$.
First Question: Is the map $\pi :V\times W\to V\otimes W$ sujective?
I think it should be surjective since $\pi(V\times W)$ also satisfies the universal property of tensor product of $V$ and $W$. Since $V\otimes W$ is given by a universal property, it is unique upto a unique isomorphism and thus $\pi$ should be surjective.
Please correct me if I am wrong anywhere in the the above said things.
Main Question:
Assuming all is well so far, I am confused in the following:
Let $(e_1,\ldots, e_m)$ and $(f_1,\ldots, f_n)$ be bases for $V$ and $W$ repectively.
I was wondering what member of $V\times W$ maps to $e_1\otimes f_1 + e_2\otimes f_2$.
Since $\pi$ is surjective, some member should map to it.
But I am lost as to how to find it.
Can somebody help?
Answer: The map $\pi$ is not linear, so the image of $\pi$ is not a vector space and can not satisfy the universal property.
We have
$\pi((e_1,f_1)+(e_2,f_2))
\ne \pi((e_1,f_1))+\pi((e_2,f_2))$.
A multilinear map is just linear in a single component if we fix all other components.
Comment: This clears a lot of things. Thanks.
Comment: Maybe I should add that we know  $\pi( V \times W) $ spans $ V \otimes W $ since it contains a basis namely $\{ e_i \otimes f_j : 1 \le i \le m, 1 \le j \le n \}$. Using this we know that $V \otimes W$ has dimension $mn$, so we know that $\pi$ can not be surjective because $V \otimes W$ has dimension $m+n$.
Comment: @user60589 You wrote $\otimes$ instead of $\times$.
Answer: In general it is not possible for $\pi$ to be surjective because the domain has a smaller dimension than the range provided then dimension of each factor is at least $2$. If $V$ has dimension $m$ and $W$ has dimension $n$, then $V\times W$ has dimension $m+n$ and $V\otimes W$ has dimension $mn$.
$\pi(V\times W)$ is not a subspace of $V\otimes W$, but it contains a basis, hence its span is the whole space.
Comment: @caffeinemachine You're welcome.
Answer: I am new to this stuff, so take my answer with a grain of salt. Your map $\pi$ is usually thought of as the inclusion map, is my understanding. So it need not be surjective. But $\pi$ maps the image of $V\times W$ into $V\otimes W$ injectively.
Comment: $\pi$ is not surjective (usually) indeed (nor is it injective). But what do you mean by $\pi$ mapping the image of $V \times W $ into $V \otimes W$ injectively? The image of $V \times W$ is already a subset of $V \otimes W$.
Comment: Am I wrong in thinking that $\pi(V\times W)$ satisfies the universal property?
Comment: I think if $\pi$ is surjective then it does. But we don't know necessarily know that $\pi$ is surjective, right?
Comment: I meant that every element in the image of $\pi$ has a unique preimage. That is $\forall\,y\in\pi(V\times W)\,\exists!\,x\inV\times X$ such that $\pi(x)=y$.
Comment: @LaarsHelenius I'm not sure that that works. Remember that $\lambda(v\otimes w)=(\lambda v)\otimes w=v\otimes (\lambda w)$.

So for a fixed $v$ and $w$, wouldn't $(v/k,kw)$ all have the same image $v\otimes w$ for any non-zero scalar $k$?


How to prove spectral radius is a matrix single eigenvalue?

Question: I have some difficulty in proving the following proposition about non-negative matrix which means that every element of it is non-negative.

Suppose $A$ is a non-negative matrix. If there exist a $k\geq 1$ such that $A$ is a
      positive matrix, then $\rho (A)$ is a single eigenvalue.

According to the Perron-Frobenius theorem, $\rho(A^k)$ is a single eigenvalue of $A^k$. $\rho(A^k) = \rho(A)^k$.
We only need to prove that $\rho(A)$ is a solution of $\det(\lambda-A)=0$ mutiplicity one. Or some equivelent forms of single eigenvalue.
Answer: The statement is trivial if you've been taught Perron-Frobenius theorem for irreducible matrices (since $A^k>0$, $A$ must be irreducible and hence $\rho(A)$ is simple, by PFT). But you sound like you've only been taught PFT for positive matrices.
In this case, let $\rho(A),\lambda_2,\ldots,\lambda_n$ be the eigenvalues of $A$ over $\mathbb C$. Then the eigenvalues of $A^k$ are $\rho(A^k),\lambda_2^k,\ldots,\lambda_n^k$ respectively. Since $A^k$ is positive, PFT says that $\rho(A^k)$ is a simple eigenvalue of $A^k$. Thus $\lambda_2^k,\ldots,\lambda_n^k\ne\rho(A^k)=\rho(A)^k$. In turn, $\lambda_2,\ldots,\lambda_n\ne\rho(A)$ and hence $\rho(A)$ is a simple eigenvalue of $A$.


How to animate overlay drawing in MKMapView

Question: I'm drawing MKCircleView overlay on MKMapView. it works fine, except that I need to animate drawing of this overlay.
I know that I need to use:
[UIView beginAnimations:nil context:NULL];
[UIView commitAnimations];

,but I don't know where to put this animation code.
Thanks.
Comment: you put this code where you want to animate...simple! If you want to know how to use it, you just have to put the **code of change** you want to animate between `begin` and `commit`. You can find plenty of examples on SOF itself.
Answer: not sure what you're looking for.. but for example:
[UIView beginAnimations:@"fade" context:nil];
[UIView setAnimationDuration:0.6f];
theView.alpha = 0.0f;
theView.transform = CGAffineTransformMakeScale(0.01,0.01);
theView.alpha = 1.0f;
[UIView commitAnimations];

Comment: I need to animate moving overlay from one location to another location on MKMap. Actually, the issue i'm facing is how to "move" ovarlay on map. currenlty, i'm just remove overlay from old location and add it again in new location, the issue with this, you could not animate this moveoment.
Comment: There should be another theView.transform = CGAffineTransformMakeScale(1,1);   The code was used to take a view scale it to from tiny to full size and fade in from no opacity to full opacity.  The example above was just used for to display structure
Comment: I have the same question. I want to animate movement of overlay. how can i acheive ?


Structs não alimentado

Question: Prezados(as) programadores(as) em C, boa noite,
peço-lhes ajuda para o seguinte caso: quero alimentar um array de structs a cada interação em uma linha de um arquivo, o problema é que, apesar de conseguir ler a linha do arquivo, não consigo enviar o dado para o struct.
Segue o código:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <locale.h>
#define TAM_VEICULOS 100
#define TAM_RESERVAS 100
#define TAM_DEVOLUCOES 100

const int TAM_BUFFER = 660;

//char    TAM_BUFFER[660];
char    url_veiculos[]   = "veiculos.csv";
FILE    *arq_veiculos;
char    url_reservas[]   = "reservas.csv";
FILE    *arq_reservas;
//char  url_devolucoes[] = "devolucoes.csv";

int opc;

void menu();

int     tam_arquivo_veiculos = 0, tam_arquivo_reservas = 0, tam_arquivo_devolucoes = 0, count = 0;

char    linha_veiculos[660];
char    linha_resevas[660];
char    linha_devolucoes[660];

char    marca_disponivel[15];
char    modelo_disponivel[15];
char    placa_disponivel[15];
char    valorDiaria_disponivel[8];

char    marca_nao_disponivel[15];
char    modelo_nao_disponivel[15];
char    placa_nao_disponivel[15];
char    valorDiaria_nao_disponivel[8];

// struct do arquivo veiculos.cvs
typedef struct {
    char    codigo[15];
    char    marca[15];
    char    modelo[15];
    char    placa[15];
    char    valorDiaria[8];
} Veiculos;

// array do arquivo de veicuos
Veiculos veiculos[TAM_VEICULOS];

// struct do arquivo reservas.cvs
typedef struct {
    char    reserva_ticket[10];
    char    reserva_cpf[12];
    char    reserva_bonus[2];
    char    reserva_placa[9];
    char    reserva_data_contrato[11];
    char    reserva_hora_contrato[6];
    char    reserva_data_devolucao[11];
    char    reserva_hora_devolucao[6];
    char    reserva_preco_contrato[7];
    char    reserva_preco_devolucao[7];
    char    reserva_desconto_um[7];
    char    reserva_desconto_dois[7];
} Reservas;

Reservas reservas[TAM_RESERVAS];

void preenche_array_veiculos() {
    arq_veiculos = fopen(url_veiculos, "r");
    if(arq_veiculos == NULL) {
        printf("Erro, nao foi possivel abrir o arquivo veiculos\n");
    } else {
        fflush(stdin);
        while (fgets(linha_veiculos, TAM_BUFFER, arq_veiculos)) {
            fscanf(arq_veiculos, "%[^;],%[^;],%[^;],%[^;]\n", veiculos[tam_arquivo_veiculos].codigo, veiculos[tam_arquivo_veiculos].marca,
            veiculos[tam_arquivo_veiculos].modelo, veiculos[tam_arquivo_veiculos].placa, veiculos[tam_arquivo_veiculos].valorDiaria);

            printf("Linha veículos: %s\n", linha_veiculos);

            ++tam_arquivo_veiculos;

            printf("Tamanho do arquivo veiculos: %d\n", tam_arquivo_veiculos);
        }
    }
}

void preenche_array_reservas () {
    arq_reservas   = fopen(url_reservas, "r");
    if(arq_reservas == NULL) { // etapa 2 - listar as reservas linha a linha
        printf("Erro, nao foi possivel abrir o arquivo reservas\n");
    } else {
        fflush(stdin);
        while (fgets(linha_resevas, TAM_BUFFER, arq_reservas)) {
            fscanf(arq_reservas, "%[^;],%[^;],%[^;],%[^;],[^;],%[^;],%[^;],%[^;],%[^;],%[^;]\n", reservas[tam_arquivo_reservas].reserva_ticket,
            reservas[tam_arquivo_reservas].reserva_cpf, reservas[tam_arquivo_reservas].reserva_bonus, reservas[tam_arquivo_reservas].reserva_placa,
            reservas[tam_arquivo_reservas].reserva_data_contrato, reservas[tam_arquivo_reservas].reserva_data_devolucao,
            reservas[tam_arquivo_reservas].reserva_preco_contrato, reservas[tam_arquivo_reservas].reserva_preco_devolucao,
            reservas[tam_arquivo_reservas].reserva_desconto_um, reservas[tam_arquivo_reservas].reserva_desconto_dois);

            ++tam_arquivo_reservas;

            printf("Tamanho do arquivo reservas: %d\n", tam_arquivo_reservas);
        }
    }
}

void fechar_arquivos () {
    //fclose(arq_devolucoes);
    fclose(arq_reservas);
    fclose(arq_veiculos);
}

void lista_veiculos () {
    printf("Tamanho do arquivo Veiculos: %d ", &tam_arquivo_veiculos);

    for (count = 0; count <= tam_arquivo_veiculos; count++) {
        printf("Marca: %s\n", veiculos[count].marca);
        printf("Placa: %s\n", veiculos[count].placa);
    }
}

executa(opc) {
    setlocale(LC_ALL, "Portuguese");
    switch(opc) {
        default:
        preenche_array_veiculos();
        preenche_array_reservas ();
        fechar_arquivos();
        lista_veiculos();
    }
}

Desde já agradeço.
Answer: Resolvido.
O problema estava na separação dos campos, onde foi utilizada vírgula, sendo correto o ponto e vírgula.
Isto
"%[^;],%[^;],%[^;],%[^;]\n"

Foi corrigido para isto:
"%[^;];%[^;];%[^;];%[^;]\n"

Obrigado a todos que tentaram ajudar.
Answer: Pessoas, quase consegui resolver.
No lugar de fazer isso
while (fgets(linha_veiculos, TAM_BUFFER, arq_veiculos)) {
            fscanf(arq_veiculos, ...

fiz isso:
while (fgets(linha_veiculos, TAM_BUFFER, arq_veiculos)) {
            sscanf(linha_veiculos, ...

O problema é que ele só atribui valor a variável no primeiro campo do arquivo, os demais campos não atribui.

Structs não alimentado


How does my host know that I own my domain name?

Question: I purchased my domain name from Namespace and am hosting my application on Digital Ocean. In order to point my domain name to my digital ocean droplet all I had to do is enter the digital ocean nameservers on Namespace then I was able to set my domain name on digital ocean. How does digital ocean know that I own that domain name?
Answer: The answer is in your own question: you have access to the domain(/zone) nameservers configuration, so you're the owner (or at least you have some privileges over that domain)l
Comment: the fact that the (real) domain name will not point to Digital Ocean, as only you (or the domain owner) can change records and nameservers for a domain/zone. So someone else *can* enter another domain in D.O., but it will be useless without the ability to change nameservers/records for that domain/zone.
Comment: what would stop someone from entering my domain name for their application on digital ocean ?


Move-Item cmdlet to move a folder using C#

Question: I want to move a folder containing 50GB of files to a Shared folder using C#.
Iterating through directories and copying each files using FileInfo CopyTo method doesn't seems to be best option for me. I tried XCOPY Windows Command to copy. But I personally don't like the idea to call an external application which Microsoft may withdraw any time in future.
My third option is to use Windows PowerShell cmdlet Move-Item.
Move-Item -Path D:\Files\Server-01 -Destination \\NAS-Storage-01\Backups\Server-01\ServerFiles

Can anybody tell me the pros and cons using this method using C# ?
Comment: If you want to move the file, why not FileInfo.MoveTo
Comment: @SirRufo It's showing File Exists Exception for large files (40Gb). It copied a 0Kb version of the file, and throwing exception.
Answer: xcopy.exe is a long-standing Windows console application that is not going anywhere.
These are a few options we have:

Directory.MoveTo: This does not work across different network paths.
Recursively move each files and subdirectories: This can take a long time if there are several files and subdirectories.
Use console application xcopy.exe; as the name suggests, however, only copying rather than moving is performed, so you'll need an additional step after successful copying that removes the source directory.

Here is sample code that invokes xcopy from C#, using Process.Start:
ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C xcopy D:\Files\Server-01 \\NAS-Storage-01\Backups\Server-01\ServerFiles";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);

Refer below links for more details on using xcopy in C#-

http://www.c-sharpcorner.com/UploadFile/jawedmd/xcopy-using-C-Sharp-to-copy-filesfolders/
https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true
Copy file(s) from one project to another using post build event...VS2010
Move a directory across a network using c#


Prove that if $f(x)=x^2$, $g(x)=-x^3+x^2+3x+2$ for $c∈(-1,2)$ the tangent line to f at $(c,f(c))$ is parallel to the tangent line of g at $(c,g(c))$

Question: Would have put this in the title but ran out of characters: The question also asks to find c, which is incidentally the thing I have most trouble with.
For the proof we know that by MVT: $$\frac{f(2)-f(-1)}{2-(-1)}=f'(c),\frac{g(2)-g(-1)}{2-(-1)}=g'(c)$$
When evaluating the functions at -1 and 2  we find that $f(-1)=g(-1)$ and $f(2)=g(2)$, thus $f'(c)=g'(c)$.
I'm not entirely sure about the validity of this proof, but I can't pinpoint why.
For finding c I'm stuck, and I think it's for some trivial reason, but I can't figure out why.
To find c I initially tried just solving the slope equation and got $f'(c)=1$ and $g'(c)=1$, good so far. But solving for 1 here gives different values of c, which makes me wonder about my proof. Then I decided to simply equate the derivatives:$$2x=-3x^2+2x+3 ⇒x=\sqrt{3}$$which also doesn't work! I don't know what I'm doing wrong here.
Answer: Note that $$2x=-3x^2+2x+3 ⇒x^2=1$$
Therefore $c=1$ makes the tangent line parallel and it is in the interval $(-1,2)$.
Comment: wow, I just realized my mistake. Algebra can be annoying sometimes


Measure Theory problem about rectangle cover.

Question: Show that if $A$ is a compact subset of $R^{n}$ and $A$ has measure zero in $R^{n}$, then given $\epsilon>0,$ there is a finite collection of rectangles of total volume less than $\epsilon$ covering $A$.
I know that countably finite collection of rectangle have total volume less than $\epsilon$  by definition of measure 0 set A. But how to prove finite collection of rectangle have measure 0.
Comment: Why the collection of rectangle should have measure $0$ ?
Answer: Like you said, by definition of $A$ having measure $0$, given $\epsilon > 0$, there's a countable collection of open rectangles $U_1, U_2, U_3, \dots$ which cover $A$ and have total volume $< \epsilon$.
Now, $A$ is compact, and $\{U_j\}_{j=1}^{\infty}$ is an open cover of $A$; so by compactness ... (I leave it to you to complete the argument)

Also, you're not trying to prove finitely many rectangles have measure $0$; in fact a non-trivial rectangle never has measure zero. You want to show the existence of a finite collection of rectangles with total volume $< \epsilon$.
Answer: There is an open set $U$ such that $A \subseteq U$ and $m(U) <\epsilon$. [$m(A)$ denotes the volume of $A$]. We can write $U$ as the union of  sequence of open rectangles $R_n$. $A$ is covered by a finite number of these rectangles and their total volume is less than $m(U) <\epsilon$.


Implementing cos(x) by its Taylor series in python

Question: I have to implement the cosine function in python by using its Taylor series. I have to print its values and the absolute and relative errors for all the values in listt from below. Here is what I tried:
import math

def expression(x, k):
   return (-1)**k/(math.factorial(2*k))*(x**(2*k))
pi=math.pi
listt=[0, pi/6, pi/4, pi/3, pi/2, (2*pi)/3, (3*pi)/4, (5*pi)/6, pi]
sum=0
for x in listt:
   k=0
   relative_error=1
   while relative_error>10**(-15):
       sum+=expression(x, k)
       absolute_error=abs(math.cos(x)-sum)
       relative_error=absolute_error/abs(math.cos(x))
       k+=1
    print("%.20f"%x, '\t', "%.20f"%sum, '\t', "%.20f"%math.cos(x), '\t', "%.20f"%absolute_error, '\t', "%.20f"%relative_error )

This, however, produces a huge error. The cause is probably that I perform all those subtractions. However, I don't know how to avoid them. I ran into the same problem when computing e^x for negative x, but there I just computed e^(-x) if x was negative and I could then just write that e^x=1/e^(-x). Is there some similar trick here?
Also, note that my while is infinite, because the relative error is always huge.
Comment: You don't specify what error you are getting. Can you edit your post and add the traceback?
Comment: It would be smarter to observe the magnitude of the errors as a function of the number of iterations (100 is complete overkill).
Comment: @AwesomeCronk By huge error I mean a huge computation error i.e. a huge error between my function and math.cos(x).
Comment: Bug apart, using the relative error might not be the best idea because the cosine goes through 0 and makes the relative error explode in this neighborhood.
Comment: @YvesDaoust Yes, when x=pi/2 the code just went nuts. I resorted to setting a number of iterations (something like 100) and using a for loop. I couldn't find a better approach.
Answer: Fatal error: You set sum=0 outside the loop over the test points. You need to reset it for every test point. This error could be easily avoided if you made the approximate cosine computation a separate function.

It is always a better idea to compute the terms of the series by multiplying with the quotient to the previous term. This avoids the computation of the factorial and all the difficulties that its growth may produce.
That said, the growth of terms is the same as those for the exponential series, so the largest term is where 2*k is about |x|. For the given points that should not be prohibitively large.
To be a little more precise, the error of a cosine partial sum is smaller than the next term, as the series is alternating. The term of degree 2*k for |x|<=4 has the approximate bound, using Stirling's formula for the factorial,
4^(4*k)/(4*k/e)^(4*k) = (e/k)^(4*k) < (3/k)^(4*k)

which for k=6 gives an upper bound of 2^(-24) ~ 10^(-7). Thus there should be no catastrophic errors for the test values.
See also Calculate maclaurin series for sin using C, Issue with program to approximate sin and cosine values, Sine calculation with Taylor series not working


Find matrix $A$ with real entries with minimal polynomial $t^4 + 1.$

Question: The title says it all.  This polynomial splits over $\mathbb{C}$ pretty obviously, $(t - \sqrt{i})(t + \sqrt{i})(t - i\sqrt{i})(t + i\sqrt{i}),$ but the matrix needs real entries, so I can't just make a diagonal matrix.
So my next idea is that $A^4 = -I,$ write $A^4 = B^2,$ where $B = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix}.$  Then all I need to do is find $A$ such that $A^2 = B.$  Not possible (I think), probably because I started working with $2 \times 2$ matrices whereas the question does not give a size to he matrix, it just says "find a matrix with minimal polynomial ..."
This leaves me with questioning my approach, and that is why I've posted this question, how does one go about constructing a matrix given that it needs to satisfy a minimal polynomial, restricted to having elements in some field (preferably $\mathbb{R}$ or $\mathbb{C}$)? Solutions would be appriciated, but I am mostly interested in the procedure for constructing such matrices given a general minimal polynomial.

For fun, the subquestion associated with the original question is,
"Show that the usual real linear map $v \to Av$ has no non-trivial subspace."
Comment: The degree of the minimal polynomial cannot be larger than the size of the matrix.
Comment: Look up "companion matrix".
Comment: Very cool, hadn't come across the companion matrix before, thanks for the help!
Answer: Hint to find such a matrix:

decompose $t^4+1$ into quadratic/linear factors. Here, we have two quadratic factors $p_1(t)$ and $p_2(t)$.
for each factor $p_i(t)$, find a $2\times 2$ matrix $A_i$ with minimal polynomial $p_i$.
$A=\left(\begin{array}{ll}A_1&0\\0&A_2\end{array}\right)$.

Note:

Since each $p_i$ is irreducible, $A_i$ can be taken in the form
$$\left(\begin{array}{rr} a& -b\\b&a\end{array}\right),$$
i.e, a rotation in $\mathbb{R}^2$. Like in Jack's answer, you should be able to find them both.
Clearly, $A$ has two stable subspaces :-).
$A$ should not have an invariant space, since each would yield an eigenvector hence an eigenvalue. But the minimal polynomial of $A$ has no real roots.
Answer: Figured it out, thanks to @Robert Israel's comment to look for companion matrices:
The answer to this specific question is $A = \begin{pmatrix}0&0&0&-1\\1&0&0&0\\0&1&0&0\\0&0&1&0 \end{pmatrix}$.
Thanks for the responses everybody.
Answer: Put $$A = \left(\begin{matrix}
0&1&0&0\\
0&0&1&0\\
0&0&0&1\\
-1&0&0&0
 \end{matrix} \right).$$ Then $$A^2 = \left(\begin{matrix}
0&0&1&0\\
0&0&0&1\\
-1&0&0&0\\
0&-1&0&0 \end{matrix} \right), \,\,\,\,\,
A^3 = \left(\begin{matrix}
0&0&0&1\\
-1&0&0&0\\
0&-1&0&0\\
0&0&-1&0 \end{matrix} \right), \,\,\,\,\,
A^4 = \left(\begin{matrix}
-1&0&0&0\\
0&-1&0&0\\
0&0&-1&0\\
0&0&0&-1 \end{matrix} \right).
$$
Thus $A^4 + I = 0$. Further, $A^3, A^2, A, I$ are linearly independent, so there is no third degree polynomial which annihilates $A$. Thus $t^4 + 1$ is the minimal polynomial of $A$.
I'm led to believe that if $A$ is $4\times 4$, the second part isn't necessarily true and we can only prove that $A$ has no $1$ or $3$ dimensional invariant subspaces while there are cases where $A$ has a $2$ dimensional invariant subspace. That being said, I'm struggling to find an example.
As an aside, did you find this on the UCLA Basic Exam? I remember this question came up on one of those.
EDIT: I had posted a counterexample to the fact that $A$ has no non-trivial invariant subspaces, but Quang Hoang pointed out in the comments that my counterexample was incorrect.
Comment: If you're coming in this fall as a first year, the boot camp is incredibly helpful in preparing for the Basic so I'd definitely advise you to attend. Good luck!
Comment: You counter example is not correct. That matrix has $(t^4+1)(t-1)$ as its minimal polynomial.
Comment: Oh you're right. I will edit. Thanks!
Comment: Ha yes, maybe 2014 spring exam? Been studying for September's qualifiers.


Ansible - ignore_errors WHEN

Question: Ansible 18.104.22.168
There are about three tasks which randomly fails. The output of the fail is:
OSError: [Errno 32]
Broken pipefatal: [machine1]: FAILED! => {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}

Is it possible to ignore the error, if Errno 32 is in the output of the error.
- name: This task sometimes fails
  shell: fail_me!
  ignore_errors: "{{ when_errno32 }}"

I"m aware this is a workaround.
Solving the 'real' problem could take up way more time.
Answer: You can use failed_when to control when a task should fail in Ansible, but you cannot use ignore_errors for a specific return code, it is a simple yes/no switch.
So in your case you can add an expression:
- name: This task sometimes fails
  shell: fail_me!
  register: fail_me
  failed_when: "fail_me.rc != 0 and fail_me.rc != 32"

Answer: You can also try with ignore_errors.

- name: This task sometimes fail & igonre that tasks and execute next task

  shell: fail_me!

  ignore_errors: true

Ansible - ignore_errors WHEN


Android & PHP Encryption / Decryption - Padding problems

Question: Used code on iOS fine and trying to translate code to Android we have the following however seem to have a padding issue, can anyone offer a hand.
Using a MD5 as key
Java (Android)
public class AES256Cipher {

    public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

    public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

        byte[] textBytes = str.getBytes("UTF-8");
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
             SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
             Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);

        return Base64.encodeToString(cipher.doFinal(textBytes), 0);
    }

    public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

        byte[] textBytes =Base64.decode(str,0);
        //byte[] textBytes = str.getBytes("UTF-8");
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return new String(cipher.doFinal(textBytes), "UTF-8");
    }
}

PHP
<?php
function encrypt ($key, $value)
{
    $padSize = 16 - (strlen ($value) % 16) ;
    $value = $value . str_repeat (chr ($padSize), $padSize) ;
    $output = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;
    return base64_encode ($output) ;
}

function decrypt ($key, $value)
{
    $value = base64_decode ($value) ;
    $output = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;

    $valueLen = strlen ($output) ;
    if ( $valueLen % 16 > 0 )
        $output = "";

    $padSize = ord ($output{$valueLen - 1}) ;
    if ( ($padSize < 1) or ($padSize > 16) )
        $output = "";                // Check padding.

    for ($i = 0; $i < $padSize; $i++)
    {
        if ( ord ($output{$valueLen - $i - 1}) != $padSize )
            $output = "";
    }
    $output = substr ($output, 0, $valueLen - $padSize) ;

    return $output;
}

?>

The output on Java side works fine however when the code is send to PHP you get an output with remainder which makes us think its a padding issue, any help would be great.
Comment: I don't understand why $output is being reset (`$output = "";`) on multiple situations?!?
Comment: This is where the padding fails
Answer: I know this is probably 4 years too late, but I wonder if my question/answer might help to solve this:
RSA Encryption disparity between Android and Java environments