Is it possible to set an Image in Button with view?

Question: I'm currently developing a simple tic-tac-toe game. Here's the screenshot of the game.
The grid acts as a Button. So if I clicked the button, it would set the views to X's or O's according to the player's turn.
I used ((Button) v).setText("X"); and ((Button) v).setText("O"); to set the "views", but now I want to replace them with my own images of them.
As an information, I already tried ((Button) v).setBackgroundResources(R.drawable.x_icons); but it just turns the button to the image!
So is it possible to add custom images/icons in or above the button with custom measurements of them?
Comment: Why not use an ```ImageButton``` ?
Comment: It failed to run
Comment: Can you be more specific? What failed to run?
Comment: Update: I have to hardcode the size in `ImageButton`, which is not good for the layout because it's not flexible. So, using a regular `Button` is a must.
Answer: I think if you want to set an image on your button is better to use image button instead of button but if you have to use button i think you should change your image pixels because i think showing black background is because of your big image and because there is no 'scale type' for buttons it becomes black.
Comment: Tried it and then it failed too. I tried resizing the image before, but it keeps making the button black. I have no idea how to set the ```scaleType``` in the vector's XML
Comment: so how about 'image button' ?
Comment: Update: I have to hardcode the size in `ImageButton`, which is not good for the layout because it's not flexible. So, using a regular `Button` is a must.


Localization $(R_{\mathfrak p})_{\mathfrak q}$ for an Artinian ring.

Question:
Let $R$ be an Artinian ring, and let $\mathfrak p$ and $\mathfrak q$ be distinct prime ideals of $R$. I have to prove that $(R_{\mathfrak p})_{\mathfrak q}=0$.

What I have done is the following: Since $R$ is Artinian we have $\dim R=0$, so every prime ideal of $R$ is maximal, so $\mathfrak p\not\subset\mathfrak q$ and vice versa. If we localize at $\mathfrak p$ we invert all elements outside of $\mathfrak p$, so we invert at least one element of $\mathfrak q$. Then $\mathfrak qR_{\mathfrak p}$ contains a unit and thus equals $R_{\mathfrak p}$, so if we localize at $\mathfrak qR_{\mathfrak p}$ we invert everything outside $\mathfrak qR_{\mathfrak p}=R_{\mathfrak p}$, so we invert seemingly invert..nothing. This doesn't make sense.
Can somebody offer some help? It is much appreciated.
Comment: @Whoever was here just now with a comment, I have added a screenshot.
Comment: So as the answer shows, the notation $(R_p)_q$ is localization of the $R$-module $R_p$ at the prime ideal $q$. That makes a lot of sense of course.
Comment: @Manos Well yes, he has been using that notation for a while now. Do you have any suggestion for what else it might be? Of course it's actually localization at $qR_p$, but I'm sure that's what you mean.
Comment: @Manos And this makes it the zero ring? Is there a nicer way out here?
Comment: Ah! In his definition he demands that $1\in S$, which is certainly not fulfilled here. He never explicitly defines $R_{\emptyset}=0$, but I have no idea how to work around this in another way.
Comment: I agree. Thanks.
Comment: @Manos Also of the *ring* $R_p$ at the prime ideal $q$.
Answer:
Let $f:R\to R_{\mathfrak p}$ be the canonical homomorphism and $S=f(R\setminus\mathfrak q)\subset R_{\mathfrak p}$. Then $S$ is a multiplicative set, and $S^{-1}R_{\mathfrak p}=0$. (By definition, $(R_{\mathfrak p})_{\mathfrak q}=S^{-1}R_{\mathfrak p}$.)

In order to prove this we want to show that $\frac01\in S$, that is, there is $a\in R\setminus\mathfrak q$ and $b\in R\setminus\mathfrak p$ such that $ab=0$.
Denote by $\mathfrak m_1,\dots,\mathfrak m_t$ the maximal ideals of $R$ others that $\mathfrak p$ and $\mathfrak q$. Now we can pick $x\in\mathfrak p\setminus\mathfrak q$ and $y\in(\mathfrak q\cap\mathfrak m_1\cap\cdots\cap\mathfrak m_t)\setminus\mathfrak p$. Then $xy\in\mathfrak p\cap\mathfrak q\cap\mathfrak m_1\cap\cdots\cap\mathfrak m_t$, so it is nilpotent, that is, there is $k\ge1$ such that $x^ky^k=0$. Now set $a=x^k$ and $b=y^k$.
Comment: This is nice. Thanks.
Answer: I realize that this answer comes some 2 years too late, but I thought I'd post it nontheless for completeness sake now that I've stumbled upon this question. Here is an alternative way to see what is going on.
One can decompose Artinian rings as finite products of local Artinian rings, whose localizations are trivial, and taking localization commutes with taking the product. One possible explicit realization of this is as follows.
First suppose that $R=(R,\mathfrak{m})$ is local Artinian. Then $\mathfrak{m}$ is the only prime of $R$ and $R\setminus\mathfrak{m} = R^{\times}$, hence $R_\mathfrak{m}\cong R$. Next, for a general Artinian ring $R$, let $R=\prod_{i=1}^n R_i$ be its decomposition into Artin local rings $(R_i,\mathfrak{m}_i)$. The primes of $R$ have the form $\mathfrak{p}_i:=R_1\times\dots\times R_{i-1}\times\mathfrak{m}_i\times R_{i+1}\times\dots\times R_n$, $1\leq i\leq n$. Hence $R_{\mathfrak{p}_i}\cong R_i$ and if you take a different prime $\mathfrak{p_j}$, $j\neq i$, then $(R_{\mathfrak{p}_i})_{\mathfrak{p}_j} \cong R_i^{-1}R_i=0$ because $R_i\ni 0$.


Translate not working for some strings

Question: I am using Drupal commons. I am using I18n and other related modules for my website as it is created in English but is being used in French also. I am using translations provided. My issue is that I have string translations but for some strings, text is not being translated, although the translations are available in the drupal.

UPDATE
After going through code, I found that this "Request Message" field is not a normal form field, but it is being rendered using
     field_attach_form('og_membership', $og_membership, $form['membership_fields'], $form_state);

The issue is with this "field_attach_form()". Do ANYONE have any idea what can be done for this??
Comment: Which strings?  The first step is to isolate where the strings that are not being translated are being provided from (are they hard-coded into a module?  added through the Views UI? etc.)
Comment: those strings are mostly hardcoded in modules.. those are mostly GUI options, like I am using Organic Groups and there is registration for the groups. In add-user page of group I have fields, some are getting translated while some are not, like request message field label and description is not getting translated
Comment: I hope you getting what I mean or I will attach a screenshot soon
Comment: Try refreshing strings and clearing caches.
Comment: yes I tried that too but nothing worked
Comment: I have added the screenshot how some fields are translated but some not, although translations of non-translated fields are available
Comment: i18n issues can be difficult to trace, but there are probably multiple problems here.  I would start by searching drupal.org for Organic Groups i18n issues, and see how good/bad the situation is.  If some types of fields are translated but not others, than I would run a google search for the field that is not being translated correctly.
Comment: After going through code, I found that this "Request Message" field is not a normal form field, but it is being rendered using  field_attach_form('og_membership', $og_membership, $form['membership_fields'], $form_state);. The issue is with this "field_attach_form()". Do you have any idea what can be done for this??
Comment: try to change it to field_attach_form('og_membership', $og_membership, $form['membership_fields'], $form_state, 'fr');
Answer: Although I know this solution is not best and structural method and is better solve this issue but sometimes we just need a solution and want save the time(maybe it be some issue with commons distributes.
Sometimes I do this trick in some projects
if you want translate all keystring  in every where use
 $('body').html( $('body').html().replace(/keystring /g, "TranslateString"));

and also if you want only some specified(with specified class and page class) string use
$('.checkout-review .field-name-phone-mobile .field-label').html($('.checkout-review .field-name-phone-mobile .field-label').html().replace(/keystring /g, "TranslateString"));

You just need put one of them in JS file.
Comment: Yes, this solution is not best, but din't get any other solution, so have to use this only. Thanks, it was quick trick, accepting your answer.
Comment: @Drupaler your welcome, I know this is not best solution but sometimes we should save our times ;)
Answer: Drupal's language translation can be hit or miss sometimes. Often times its silly little pieces like the part that you mentioned that dont get translated while 95% of the rest of the page translate without issues. Google to the rescue!! I recommend the Gtranslate module to get you started and of course you can place the google translate api directly into a tpl or module file to get the full monty!!

Translate not working for some strings


How can I record the sound that a javasound application is currently playing?

Question: I have two wav files that I'd like to simulate generating at different points in 3D space, as heard from a rectangular 4 channel mic array.  That is, the ideal output will be either a single 4 channel wav file or 4 single channel wav files that are known to be synchronized.
My current approach isn't all that great, but it could in principle work.  I have the two sounds playing from their positions in a jReality simulation (chosen merely because I already had a jReality simulation handy).  There are two problems with this:  A) jReality only supports a single microphone location and B) it goes directly from jReality to javasound and from there out my speakers.  To solve A, I should be able to position the mic, take a recording, move the mic and repeat.  Unfortunately I don't know how to solve B, I do know that the recording has to be from within my java code because that's the only way to synchronize it.
So the question is twofold, first, is there a better way to simulate the audio mixing and attenuation?  And secondly, is there a way to intercept things that have been sent to javasound and store them to files?
Comment: I have no idea if this would work, but could you run two instances of jReality? One for each mic?
Comment: I could spin up 4 jRealitys (1 for each mic) within the same process, but if they all pipe into javasound the output would end up being stereo instead of 4 channel.
Answer: It is fully possible to read from four sources (AudioInputLines) and work on them at the "per frame" level. Usually coders have a while loop for reading incoming audio data. With each buffer read (for four sources, you would have four buffers) you would decode the incoming bytes into sound data, apply your mixing algorithm, and then reconvert the result back to bytes as per your audio format.
If you wrap the above in a TargetDataLine, it will be possible to record it.
The Java Sound Tutorials cover this in a sort of "big picture" manner, but if you haven't come across the main concepts before (on using javax.sound.sampled library) it will be worth a look.
Comment: That's the reverse of the data flow I'm looking for.  I'm not trying to read from 4 channels, I'm trying to _create_ 4 channels.  It's not my code that does the mixing, it's jReality that does the mixing.  I'm not trying to read from input lines, the audio I want is sent into output lines and I don't know how to get at it.  Am I missing something in your response?
Comment: Sorry for the mixup! I don't know about jReality. I would read the two stereo inputs via two AudioInputLines, both read in the same while loop described above, and converting to sound frames. Then, do your distance/power computations for the 4 mike locations, and convert back to bytes using a format with 4 channels. Do you know how to make your own format? To store the resulting 4-channel wav, again, wrap everything in a TargetDataLine. HTH!
Comment: Ah, so just do the whole thing myself?  That's an option I suppose, I tend to prefer using libraries if at all possible (when I look at http://www3.math.tu-berlin.de/jreality/mediawiki/index.php/The_jReality_audio_rendering_pipeline I see a lot of places I could screw up)... but I'm happy to switch which library I use if you have/can-find a better suggestion.
Comment: I don't know of a library where exactly what you want is prebuilt. But that doesn't mean there isn't one, only that I'm been very DIY on this technology. "TinySound" https://github.com/finnkuusisto/TinySound has source code and does per-frame mixing, but on a very simple level: blending multiple sources for a stereo output. You might check out JAudioLibs, Neil really knows his stuff. http://code.google.com/p/java-audio-utils/ I haven't fully explored his library but he's given me great advice while I've been building my own. Good luck! Maybe someone else will provide a library link.


Fitting nonlinear curves and getting parameters

Question: I have the following data $(s_i, t_i)$:
$s_i:$     -337.6  202.1 341 387 397.2
$t_i:$   0.1  1.28  2.418 3.54  4.628
And also have the equation: $s_i= x - y*\exp(-t_i/z)$
How can I get those 3 parameters ($x,y$ and $z$) and fit the curve?
Answer: You don't get the parameters from the data, you get estimates of them.
Once you have them, to my mind you have already "fitted the curve". Do you mean something else, such as calculating the fitted values of $s_i$ ($\hat{s}_i$), or perhaps even displaying them?
How you get parameter estimates for a nonlinear equation depends on what you think about the conditional distribution of $s_i|t_i$, and on the dependence between the values.
If you felt that the variance of $s_i$ would be constant as $t_i$ changed*, and the values were independent, you could perhaps perform nonlinear least squares.
* However, with a function that asymptotes it's not uncommon for the variance to change, for example, in some cases getting smaller as asymptotes are approached, and in other cases growing when the mean grows. If you know something about how the distribution changes -- or at least how the spread changes -- with changing $t$, then that may suggest more suitable approaches. You might know this from theoretical considerations (such as the main ways noise/errors enter into the measurements) or from having seen similar studies with more data.
I agree with Mark's nonlinear least squares fit for your data. The fit looks like this:

(The tiny variation about the curve suggests that in this case it probably won't make much difference what approach you use to fit the curve, but with so few points some caution would be in order; you only have two df for error)
Comment: @Mark Thanks, I spotted it myself and corrected for it about 40 seconds before you posted the comment; since with the correction I had your answers I simply removed my fit -- there's no need to give it twice.
Comment: The reason for the apparent discrepancy between our solutions for z is that you have actually solved for the reciprocal of z as defined in the question.  I solved for z as defined.
Answer: You can apply nonlinear least squares, among other possibilities.  Here are the results I obtained, which correspond to a local optimum, which I think, but am not sure, is also the global optimum. The residuals are the LHS - RHS values for the 5 data points when using the fitted x, y, z.
<code>fitted x = 401.8423
fitted y = 825.4560
fitted z = 0.9068
residuals = -0.1753    1.4766   -3.4767    1.8032    0.3722
</code>
I leave it to your determination whether this is a good fit, and whether these parameter values make sense.  If there are constraints on the possible values of the parameters, you should have indicated so, and if these parameter values don't meet those constraints, then the constraints would need to be incorporated into a revised computation.
Comment: See Glen_b's answer, posted just after mine, which in effect is a useful expansion of my first sentence.  Also, to be clear, I performed unweighted, i.e., equally weighted, nonlinear least squares.


What are the benefits of using Nginx in front of a webserver for Go?

Question: I am writing some webservices returning JSON data, which have lots of users.
What are the benefits of using Nginx in front my server compared to just using the go http server?
Comment: THIS IS NOT NECESSARILY OPINION BASED. Closing it as such shows a severe lack of understanding of the considerations and caveats that an answer to such a question can fill in and provide. The selected answer is a great example. In fact, I see relevant new considerations in all provided answers.
Comment: fyi, had a lot of tcp errors like connection reset by peer, and i/o timeouts using Go http server for service handling 100s of large POST requests a minute. Put nginx in front of it - no more problems.
Comment: Eventually I decided to use Go http server, without NGINX, and it works very well. I haven't been running in any problem. But my service is not running large POST requests as in your case.
Comment: Yes this is not opinion based.
Answer: It depends.
Out of the box, putting nginx in front as a reverse proxy is going to give you:

Access logs
Error logs
Easy SSL termination
SPDY support
gzip support
Easy ways to set HTTP headers for certain routes in a couple of lines
Very fast static asset serving (if you're serving off S3/etc. though, this isn't that relevant)

The Go HTTP server is very good, but you will need to reinvent the wheel to do some of these things (which is fine: it's not meant to be everything to everyone).
I've always found it easier to put nginx in front—which is what it is good at—and let it do the "web server" stuff. My Go application does the application stuff, and only the bare minimum of headers/etc. that it needs to. Don't look at putting nginx in front as a "bad" thing.
Comment: One more big feature: How will you upgrade/maintain your app (without dropping packets while it's down)? Nginx will let you steer traffic around without loosing packets.
Comment: On my Raspberry Pi, putting Nginx in front of Go significantly increased page load speed.
Comment: @DanieleB The Go HTTP server produces only the logs you want it to (i.e. using the `log` package). If you want to log IP address, resource access, etc, you'll need to write that. Same goes for setting headers, beyond the basics.

Although I don't have any concrete data, nginx in front of Go should really be no slower than Go: in fact it may be faster thanks to gzip and its own optimisations. The "cost" will be more memory/CPU utilisation, but nginx is very efficient on that front too.
Comment: thanks for your reply! - 1) does Go HTTP produce some kind of logs? - 2) does nginx reduce somehow the request/response throughput?
Comment: you can load balance with nginx - you cannot with Go built-in. Therefore I recommend using nginx in front
Answer: The standard http server of Go is fine. If your application mostly/only are "dynamic" requests/responses, then it's really the best way.
You could use nginx to serve static assets, but most likely the standard Go one is fine for that, too. If you need higher performance you should just use a CDN or cache as much as you can with Varnish (for example).
If you need to serve different applications off the same IP address, nginx is a fine choice for a proxy to distribute requests between the different applications; though I'd more often get Varnish or HAProxy out of the toolbox for that sort of thing.
Comment: yes, I am actually only using it for serving dynamic data. So, I guess I don't need NGINX then! Thank for your reply
Comment: Varnish/HAProxy are not required, Nginx has similar toolset for caching and load balancing.
Comment: @mikhailov isn't that what I said? nginx works well for it; though personally I often prefer Varnish or HAproxy. I find them easier to configure and operate.
Answer: The Gorilla web toolkit gives you:

Advanced routing (domain/subdomain restriction, regex path matching).
gzip support (via middleware handlers.)
Logging middleware handler that outputs in Apache Common Log Format.
Secure encrypted cookies.
Sessions.
schema package converts form values to a struct.

This fills much gap between Go's net/http and HTTP servers like NGINX.
Personally, I'd avoid installing and configuring another HTTP server on top of net/http if I know I can plug in a CDN instead.
I think net/http has the most powerful HTTP server in any standard library.
Answer: From https://blog.gopheracademy.com/caddy-a-look-inside/ it looks like Go can handle gzip, errors, static files, routing and http headers using Middleware.
The line below, from the blog, show how you would handle such a request.
logHandler(gzipHandler(fileServer))

They handle error logging in a really interesting way. As long as your middleware returns an error code (int), the error-handling middleware automatically handles it. They've even gone as far as configuring the whole site in Go like Nginx would. "The nginx.conf file for all the Gopher Academy websites was over 115 lines long. The equivalent Caddyfile is only 50 lines."


Otimização de ferramenta de busca personalizada

Question: Galera, estou criando uma página de busca que recebe, via POST, as informações de um formulário contendo vários checkbox. Vejam abaixo que há várias sequências de resultados e está marcado em laranja uma delas como exemplo:

Quando eu clicar em procurar, as informações são enviadas para uma página onde conterá uma sequencia de if e case para organizar as informações:
    if(!isset($_POST['residencial']) &&
        isset($_POST['comercial']) &&
        isset($_POST['mecanico']) &&
        !isset($_POST['eletronico']) &&
        isset($_POST['chave']) &&
        isset($_POST['segredo']) &&
        !isset($_POST['display']) &&
        !isset($_POST['led'])){

        $var1 = $_POST['residencial'].'+'.
        $_POST['mecanico'].'+'.
        $_POST['display'];

    }

echo $var1;

RESULTADO: comercial + mecanico + chave + segredo
Depois que trato essas informações, eu as trato em um switch:
switch ($var1){

        case 'comercial + mecanico + chave + segredo ':
            $data = array(
            '1'  => $_POST['chave'],
            '2'  => $_POST['segredo']
        );
break;

Por fim, utilizo o $data para filtrar meu loop:
   $args = array(
        'posts_per_page' => -1,
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                // 'terms' => 'white-wines'
                'terms' => array(
                    $data['1'],
                    $data['2']
                    )
                )
        ),
        'post_type' => 'product',
        'orderby' => 'title,'
    );

MINHA DÚVIDA:
Como posso otimizar isto? Tudo funciona bem, mas como os checkbox tem muitas possibilidades, o código está ficando imenso!
Combinações:
(comercial+residencial+mecanico+eletronico+chave+segredo+display+led)
(comercial e/ou residencial + mecanico e/ou eletronico + chave e/ou segredo e/ou display e/ou led)

UPDATE:

O problema é que há uma combinação de check! Exemplo: existe o chave para comercial e chave para residencial e alem disso a chave pode ou não ser mecânico ou elétrico! Como faço nesse caso?

Há uma hierarquia entre os check:

Comercial(categoria)
-Mecânico(sub categoria)
--Chave(sub)
--Segredo(sub)
--Display(sub)
--Led (sub)

-Eletrônico(sub categoria)
--Chave(sub)
--Segredo(sub)
--Display(sub)
--Led (sub)

Residencial(categoria)
-Mecânico
--Chave
--Segredo
--Display
--Led

-Eletrônico
--Chave
--Segredo
--Display
--Led

Comment: Porque que quando isso aqui ocorre:
`case 'comercial + mecanico + chave + segredo ':
            $data = array(
            '1'  => $_POST['chave'],
            '2'  => $_POST['segredo']
        );
break;`

você só joga dois posts na array?
Comment: É um exemplo para o caso da imagem acima, pois perceba que `chave` e `segredo` estão selecionados!
Comment: Olha, pode não ter considerado o que o Dudu disse, mas daqueles ifs ele já te salvou, o que sugiro é usar array_push () para aqueles dados dentro do switch.

E tua pergunta tá meio confusa, se a gente te responder, provavelmente vai ter mais uma excessão no seu código que não está claro.
Comment: O problema é que vocês não estão entendendo que estou utilizando o resquest post para formar um valor para `$var1`. Só quero saber como faço a soma  `comercial + mecanico + chave + segredo`, sem utilizar muitos códigos. Essa soma vai determinar lá no **switch ($var1)**. Como diferencio quem é quem quando se tem subcategoria? Veja o update que fiz! Está claro.
Comment: @Lollipop Seria algo assim: http://pastebin.com/6kB56ksg ? Acho que entendi +- o que você quer fazer..
Answer: E se você fizer algo assim não te ajuda?
<?php
function ohGogWhy($postData) {
    //query categories
    $categories = array(
        'comercial' => array(
            'eletronico',
            'mecanico'
        ),

        'residencial' => array(
            'eletronico',
            'mecanico'
        )
    );

    $slug = array(
        'comercial' => 'co',
        'eletronico' => 'ele',
        'residencial' => 're',
        'mecanico' => 'mec'
    );

    $mainArr = isset($postData['main'])? $postData['main'] : array_keys($categories);
    $subArr = isset($postData['sub']) ? $postData['sub'] : $categories;

    $dataArr = array();

    //main
    if (isset($postData['subsub'])) {

        foreach($postData['subsub'] as $subsub) {

            foreach($mainArr as $main) {

                $tsub = (isset($subArr[$main])) ? $subArr[$main] : $subArr;

                foreach($tsub as $sub)
                    $data[] = $subsub . '-' . str_replace(array_keys($slug), array_values($slug), $main . '-' . $sub);
            }
        }
    }
    elseif (isset($postData['sub'])) {
        foreach($mainArr as $main) {

                $tsub = (isset($subArr[$main])) ? $subArr[$main] : $subArr;

                foreach($tsub as $sub)
                    $data[] = $sub . '-' . str_replace(array_keys($slug), array_values($slug), $main);
            }
    }
    else {
        $data = $mainArr;
    }

    return $data;
}

$data = array();
if (isset($_POST)) {
    $data = ohGogWhy($_POST);
    echo '
'; print_r($data); echo '
';
}

?>

    <title>lol</title>

        <form method="POST">
            main:
            <input type="checkbox" name="main[]" value="comercial" multiple="false" />Comercial
            <input type="checkbox" name="main[]" value="residencial" multiple="false" />Residencial

            sub:
            <input type="checkbox" name="sub[]" value="mecanico" />Mecanico
            <input type="checkbox" name="sub[]" value="eletrico" />Eletronico

            subsub:
            <input type="checkbox" name="subsub[]" value="chave" />Chave
            <input type="checkbox" name="subsub[]" value="segredo" />Segredo
            <input type="checkbox" name="subsub[]" value="display" />Display
            <input type="checkbox" name="subsub[]" value="led" />Led

            <input type="submit">
        </form>

As validações pra selecionar apenas um elemento tu faz por JS
Answer: Para facilitar você pode montar um vetor de checkboxes no HTML onde o valor do campo é o termo a se buscar, assim seu formulário ficaria dessa forma:
<input name="termos[]" type="checkbox" value="comercial">
<input name="termos[]" type="checkbox" value="residencial">
<input name="termos[]" type="checkbox" value="mecanico">
<input name="termos[]" type="checkbox" value="eletronico">
<input name="termos[]" type="checkbox" value="chave">
<input name="termos[]" type="checkbox" value="segredo">
<input name="termos[]" type="checkbox" value="display">
<input name="termos[]" type="checkbox" value="led">

Quando esse formulário é recebido no PHP você terá um vetor de termos $_POST['termos'] que pode ser inserido diretamente na sua busca e assim dispensa o tratamento que você está fazendo na primeira parte do código:
$args = array(
    'posts_per_page' => -1,
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => $_POST['termos']
        )
    ),
    'post_type' => 'product',
    'orderby' => 'title,'
);

Comment: Aí funciona igual, é só você trocar o checkbox por radios.


How to handle 204 errow from window.location = 'URL'

Question: I'm trying to export file in such way:
<code>exportReportFile: function exportReportFile(url) {
    window.location = url;
}
</code>
But sometimes I have 204 error. How can I handle it?
Comment: Can you please provide more context to the question please.
Comment: Hello. I'm working on functionality for downloading exports from back-end.
I'm downloading files in such way window.location = url;
Some of methods are returning 204 error and I must handle it.
 window.location = url; is not common http request with success and fail callbacks. I don't know how to handle this error.
Answer: This means that the URL that you pass to the function is returning a 204 error.
Comment: That's not an answer. You just said obvious. I asked how to handle this error.


webrequest implementation in .net core

Question:         WebRequest request = WebRequest.Create(Url);
        request.Method = "POST";

        string postData = "XML=" + System.Net.WebUtility.UrlEncode(req);
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        WebResponse response = request.GetResponse();
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(responseFromServer);
        XmlNodeList HotelDetailsResponse = xmldoc.SelectNodes("/Details");
        XmlNodeList Hotels = xmldoc.GetElementsByTagName("School");
        foreach (XmlNode node in Hotels)
        {

        }

i am facing problem with the above code while working in .net core
can you please convert the code according to .net core
Comment: This is not a free coding service, it's a Q/A site. If you do not put any efforts in trying to solve it yourself and tell us your efforts and where exactly you are having an issue, you shouldn't expect people to help you
Answer: You can split your code into two parts - (1) HTTP response retrieval, and (2) parsing.
To get your XML response you can use such method.
    private async Task<string> GetXmlResponse(Uri uri, string postData)
    {
        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.PostAsync(uri, new StringContent(postData));
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Error: {response.StatusCode}"); // TODO use specific exception
            }

            return await response.Content.ReadAsStringAsync();
        }
    }

And your main parsing method could call the GetXmlResponse() method first, then parse response using XDocument class. Next you can query for the School node using Linq and loop through the result.
    // Mocked API returns "<xml><hotels><School>s1</School><School>s2</School></hotels></xml>"
    var uri = new Uri("http://demo7162366.mockable.io/"); // TODO change to your URL
    var postData = "XML=" + System.Net.WebUtility.UrlEncode("<xml></xml>"); // TODO change to your content

    var xml = await GetXmlResponse(uri, postData);

    var doc = XDocument.Parse(xml);
    var hotelNodes = (from d in doc.Descendants()
            where d.Name.LocalName == "School"
            select d).ToList();

    foreach (var hotelNode in hotelNodes)
    {
            // TODO your logic
    }

I used https://www.mockable.io to mock API XML response.

webrequest implementation in .net core


Prove the Wallis formula form $\left(4^{\zeta{(0)}} \cdot e^{-\zeta'{(0)}}\right)^2=\frac{\pi}{2}$

Question: How would you prove the following Wallis formula form
$$ \left(4^{\zeta{(0)}} \cdot e^{-\zeta'{(0)}}\right)^2=\frac{\pi}{2}?$$
Thanks in advance!
Comment: We know the value of $\zeta(0)$ and $\zeta'(0)$. So just plug them in...
Answer: In this answer, I show that $\zeta(0)=-\frac{1}{2}$, and that $$\zeta^{'}(0)=-\frac{1}{2}\log(2\pi ).$$
Plugging these in yields $$\left(4^{\zeta(0)}e^{-\zeta^{'}(0)}\right)^{2}=4^{-1}e^{\log(2\pi)}=4^{-1}\cdot2\pi=\frac{\pi}{2}.$$  Also of interest is part $4$ of my answer regarding the evaluation of $\Gamma\left(\frac{1}{2}\right).$

Proving that $\zeta(0)=-\frac{1}{2}.$
The Riemann zeta function is defined as $\zeta(s)=\sum_{n=1}^{\infty}n^{-s}.$ Writing this as a Riemann Stieltjies integral and applying integration by parts we have that $$\zeta(s)=\int_{1}^{\infty}x^{-s}d\left[x\right]=\int_{1}^{\infty}x^{-s}dx-\int_{1}^{\infty}x^{-s}d\left\{ x\right\}$$
$$=\frac{s}{s-1}-s\int_{1}^{\infty}\left\{ x\right\} x^{-s-1}dx,$$ and this holds for all $\text{Re}(s)>0.$ Notice that taking the limit as $s\rightarrow0$ and being careful with the canceling singularities  yields $$\zeta(0)=-\frac{1}{2}.$$
Proving that $\zeta^{'}(0)=-\frac{1}{2}\log(2\pi).$
Recall the functional equation for the zeta function, $$\zeta(z)=2^{z}\pi^{z-1}\sin\left(\frac{\pi z}{2}\right)\Gamma\left(1-z\right)\zeta\left(1-z\right).$$ Taking the logarithmic derivative, we have that $$\frac{\zeta^{'}(z)}{\zeta(z)}=\log2+\log\pi-\frac{\Gamma^{'}\left(1-z\right)}{\Gamma\left(1-z\right)}+\frac{d}{dz}\log\left(\sin\left(\frac{\pi z}{2}\right)\zeta\left(1-z\right)\right).$$ Since $\zeta(1-z)=-\frac{1}{z}+\gamma+O(z),$ and $\sin\left(\frac{\pi z}{2}\right)=\frac{\pi z}{2}+O\left(z^{3}\right),$ we have that $$\sin\left(\frac{\pi z}{2}\right)\zeta\left(1-z\right)=\frac{\pi}{2}-\frac{\pi\gamma}{2}z+O\left(z^{2}\right),$$
and so $$\frac{d}{dz}\log\left(\sin\left(\frac{\pi z}{2}\right)\zeta\left(1-z\right)\right)=\frac{-\frac{\pi\gamma}{2}+O\left(z\right)}{\frac{\pi}{2}+O\left(z\right)}=-\gamma+O(z).$$ Thus $$\frac{\zeta^{'}(0)}{\zeta(0)}=\log2\pi-\Gamma^{'}\left(1\right)-\gamma.$$ As $\Gamma^{'}(1)=-\gamma,$ and $\zeta(0)=-\frac{1}{2},$ we conclude that $$\zeta^{'}(0)=-\frac{1}{2}\log2\pi.$$
Comment: A very beautiful answer one should know! (+1)


Async using WCF

Question: I have a Windows forms application  that depends on oneway WCF service ; which simply returns data from (Oracle) Database.
Some of client calls to wcf are long running, now we need to implement a way to asynchronously capture and send Oracle's DBMS_output to the client.
How can such be implemented using SignalR or similar that can be hooked to WCF ?
We are using .NET framework 4.5.
Comment: i would think doing the usual async method in the service, and the client using a callback, would work.  you probably want a sufficient connection pool also.  A simple example [here](http://msdn.microsoft.com/en-us/library/ms730059%28v=vs.110%29.aspx)
Answer: @kims answer is correct, but to explain further I will add a sample of the controller.
Just showing that work can start and then later a message will be published...
<code>/// <summary>
/// A realtime controller
/// </summary>
public class ZooController : XSocketController
{
    /// <summary>
    /// This method will be hit both from JavaScript, WCF and MVC examples
    /// Could have sent a custom object as well, but settled for a string in this case.
    /// </summary>
    /// <param name="message"></param>
    public void Say(string message)
    {

        //Just send it out to all subscribers
        this.SendToAll(new {message = "Longrunning process started"}, "say");

        Thread.Sleep(10000);

        this.SendToAll(new {message}, "say");
        //You can also use
        //this.Send, this.SendTo<T> etc...
    }
}
</code>
EDIT: I do not know your scenario, but maybe you can use the longrunning controller options described here
Answer: Since XSockets was tagged in the question...
I would subscribe to a topic in the client and let a realtime framework publish the result when the long running task is completed.
A simple sample on how to boost a WCF to realtime can be found here: XSockets WCF
That sample just publish a result instantly, but if the method called in XSockets starts a long running task and publish the result upon completion the client will be notified when the work is done.
It is only two lines of code to call a XSockets controller from a WCF (or another half duplex process)
<code>//Get a connection (if it exists already that one will be used)
var conn = ClientPool.GetInstance("ws://127.0.0.1:4502/Zoo", "*");

//We send an anonymous message here, but any object will work.
conn.Send(new { message = "I was sent over WebSockets: " + message },"Say");
</code>

Async using WCF


Queria a ajuda de como criar um link público do meu perfil com php (meusite.com/usuario) como no linkedin e instagram

Question: Um link similar ao do linkedin com url personalizada com o nome do usuario (meusite.com/usuario), ele seria visível para todos e o usuário poderia compartilhar esse link com qualquer pessoa. Tenho criado o perfil e as informações do usuário mas não estou sabendo como criar esse link personalizado.
Answer: Para criação de Urls personalizadas / amigáveis, você vai precisar utilizar algum sistema de rotas no seu projeto. Basicamente é uma um lugar aonde você especifíca as Urls que seu site/api possui e qual arquivo será executado quando cada url for acessada.
Se você estiver utilizando algum framework web, provavelmente ele já tenha algo tipo integrado e que você possa utilizar. Caso esteja fazendo tudo usando só PHP, Html, etc... você pode procurar por alguma classe pronta para PHP que te ajude nisso, vou deixar uma de exemplo abaixo, mas recomendo dar uma olhada em outras e para ver qual te atende melhor:
https://github.com/dannyvankooten/PHP-Router
Você também criar seu próprio esquema de rotas ou urls utilizando/configurando o .htaccess para fazer o redirecinamento das urls para os scripts correspondentes, mas pode ser que acabe dando mais trabalho. Vou deixar aqui um tutorial sobre como criar o seu próprio:
https://alexandrebbarbosa.wordpress.com/2019/04/17/phpconstruir-um-sistema-de-rotas-para-mvc-primeira-parte/
Se tiver a opção de utilizar algum framework no projeto, recomendo fortemente, pois ele provavelmente já terá toda essa parte de rotas e muitas outras funcionalidades prontas e bem organizadas. Se não quiser sair do PHP, o Laravel é uma excelente opção.


items.map is not a function react

Question: I'm having a problem with fetching data from my api, and displaying it on a web page. I am getting this error : "items.map is not a function". Im not sure whether this is a problem with this code or maybe my code for my get request in the api, I'll post both codes just in case.
I'll paste my code below without the link to my api.
Thanks,
import React from "react";

class App extends React.Component {

  constructor(props) {

    super(props);

    this.state = {
        items: [],
        isLoaded: false
    }

}

componentDidMount() {

  fetch(" api link ")
      .then(res => res.json())
      .then(json => {
        this.setState({ isLoaded: true, items: json });
      }).catch((err) => {
          console.log(err);
      });

}

render() {

  const { isLoaded, items } = this.state;

  if (!isLoaded)
      return
Loading...
;

  return (

              {items.map(item => (

                      Name: {item.rows.productName} | Condition: {item.rows.productCondition}

              ))}

  );

}

}

export default App;

Api code:
async function getComments(req) {
   let status = 500, data = null;
   try {

         const sql = 'SELECT * FROM products';
         const rows = await db.query(sql);

         if (rows) {
            status = 200;
            data = {
                rows,

            };
         } else {
            status = 204;
         }

   } catch (e) {
      console.error(e);
   }
   return { status, data };
}

app.get('/demo/api_project', async (req, res) => {
   const { status, data } = await getComments(req);
   res.status(status);
   if (data) res.json(data);
   else res.end();
})

Comment: what is the response from your api? post a sample response
Comment: your API response is an object, not an array. It looks like you should set the `items` state to `json.rows` rather than just `json`
Comment: @Vineesh as in what comes up when i open the api link?
Comment: Yes, If it is not an array you may have to use it or format it accordingly @JakubK
Comment: @RobinZigmond Thanks, oh dear i've been trying for so long. I thought it would of worked when i had the .rows in the item.productName etc
Comment: try ```items?.map```
Answer: try console.log() your response from the api, you may find that is your array is nested inside the response object.
Comment: This could have been a comment

items.map is not a function react


Update sem where

Question: Como fazer um incremento apenas no child periodo de todos os alunos cadastrados no Firebase?
Ex.: no SQL, eu usaria:
UPDATE alunos
SET periodo = periodo + 1

Atualizando todos os alunos para seu período posterior. Como posso fazer no Firebase?
Comment: @Ismael pronto. Obrigado pela sugestão! Sou novo como usuário no stack.
Comment: @Henrique pronto. Obrigado pela sugestão! Sou novo como usuário no stack.
Comment: Tiago, edite sua pergunta e a sua edição, que foi a solução, adicione como resposta à esta pergunta.
Answer: Consegui realizar o que precisava adaptando o código abaixo
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String true = "true";
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            ds.child("SubmitCheck").getRef().setValue(true);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);

Fonte: https://stackoverflow.com/questions/45162528/how-to-set-value-to-all-childs-data-in-firebase-database

Update sem where


What is the probability that if six letters are selected from the alphabet with replacement that the chosen letters can be used to spell ASSESS?

Question: In an arrangement of 6 letters where each letter is selected at random from the alphabet (letters can be selected repeatedly).
What is the probability of getting the word 'ASSESS' if after selecting 6 letters you have the option to have the ordering of the selected letters to be randomly rearranged once?
Solution
To tackle this question my initial thought is to work out the probability of the following points (edited after incorporating Peter's response)

Probability of picking correct letters with correct ordering

(1/26)x(1/26)x(1/26)x(1/26)x(1/26)x(1/26)

Probability of picking the correct letters with incorrect ordering

Total outcomes = 26^6
Desired outcomes (including the outcome of correct ordering of letters) = (6!)/(4!x1!x1!) = 30
Desired outcomes probability (including the outcome of correct ordering of letters) = 30 / (26^6)
Desired outcomes probability minus probability of correct ordering of letters (point 1)
= Probability of picking the correct letters with incorrect ordering
= 29 / (26^6)

Given point 2, the probability of rearranging the correct letters with incorrect order into correct ordering

Total permutations (discounting 'S' is repeated 4 times)
(6!/4!)
Therefore probability of the random rearrangement arranging the letters into correct ordering = 1/30
Final answer:
After working out all 3 points above, the final answer will be:
Probability of point 1 + (Probability of point 2 x Probability of point 3):
=[ 1/26^6 ] + [ (29/26^6) x (1/30) ]
= 59 / (26^6 x 30)
Comment: Hi and welcome to the site! Since this is a site that encourages and helps with learning, it is best if you show your own ideas and efforts in solving the question. Can you edit your question to add your thoughts and ideas about it?
Comment: Also, don't get discouraged by the downvote. I downvoted the question and voted to close it because at the moment, it is not up to site standards (you have shown no work you did on your own). If you edit your question so that you show what you tried and how far you got, I will not only remove the downvote, I will add an upvote.
Comment: As a way to get started:  try a smaller collection.  Try, say, $BOB$ with the same sort of rules.
Answer: There are $$26^6$$ possibilities to draw $6$ letters. The number of ways to draw $4$ times $S$ , once $E$ and once $A$ is $$\frac{6!}{4!\cdot 1!\cdot 1!}=\frac{6!}{4!}=30$$
Since drawing the word exactly (including the order) does not count as a success, we have $29$ possibilities to be successful.
Hence, the probability of a success is $$\frac{29}{26^6}\approx 9.4\cdot 10^{-8}$$
Comment: Drawing ASSESS including order do count as success. That is why I have added the probability of achieving point 1 into the final probability.  Whereas based on the question, drawing the correct characters but incorrect order, you will have an opportunity to randomly rearrange these letters once. Therefore probability of point 2 and 3 is required
Comment: Thanks Peter, I am not sure if I have over complicated the question but it seems this answer only address the probability of achieving ASSESS by selecting the right characters and the right order of characters only?
Comment: @jacdam333 I considered that the order doesn't matter. The $30$ is the number of draws leading to the combination $SSSSAE$ without considering the order. We are successful, if we draw one of the $30$ draws. Successfull draws are, for example $ASSESS$ or $ESASSS$
Comment: If we were not allowed to rearrange the letters, the probability of a success would be $$\frac{1}{26^6}$$ because then only one draw would be successful.
Comment: Thanks Peter, I have incorporated your working into my answer above. Please feel free to comment if I have made any mistakes.
Comment: @jacdam333 Does drawing exactly "ASSESS" (including the order) NOT count as a success, or do I misunderstand something ? If so, the probability would, of course, be $$\frac{29}{26^6}$$
Comment: @jacdam333 OK, then I edit my answer


Fundamental theorem of line integral over parabola

Question: Let $C$ represent the parabolic path $y = x^2 - 1$ from the $(0,-1)$ to $(1,0)$. Using the fundamental theorem of line integrals, evaluate
$$
\int_C(ye^x-\sin x)dx+(e^x+2)dy
$$
I know that the fundamental theorem of line integrals states that
$$
\int_C\boldsymbol{\nabla} f \cdot dr=f(r(b))-f(r(a))
$$
but how do you apply it to this problem?
Comment: can you try to find a function f such that the gradient is given by what you have written down? (forget about the parabola for now)
Answer: You want to find a scalar function $f$ such that
$$\nabla f = (ye^x-\sin x, e^x+2).$$
For that, we can take
$$f(x,y) = ye^x + \cos x + 2y.$$
Then,
$$\int_C (ye^x - \sin x) \ dx + (e^x + 2) \ dy = \int_C \nabla f \cdot dr = f(1,0) - f(0,-1) = \cos 1 + 2.$$
You can check this by just parametrizing the curve ($r(t) = (t,t^2-1)$ for $0\leq t\leq1$) and computing the integral:
$$\int_C (ye^x - \sin x) \ dx + (e^x + 2) \ dy = \int_0^1 (t^2-1)e^t - \sin t + 2t(e^t + 2) \ dt.$$
This is obviously more involved, but a few applications of integration by parts should take care of non-trivial parts.
Comment: https://math.meta.stackexchange.com/q/33508/9003


Decide if the given endomorphism $F:V\rightarrow V$ is normal

Question:
Decide if the given endomorphism $F:V\rightarrow V$ is normal
Let $V := \mathbb{C}[x]_{\leq 2}$ with $ \langle g,h\rangle := \int_{-1}^{1}g(x)\overline{h(x)}dx$ and $F$ given by the derivative $F(g):=g'$

I would love to get some tipps on how to solve this one.
Any help is appreciated
Answer: Tip: Your operator satisfies $F^3 = 0$ so $F$ is nilpotent. When can a nilpotent operator be normal?
Comment: when it satisfies f* x f = f x f* right? But how do u apply this here? Would you just create the matrix corresponding to the endomorphism with the basis 1,x,x^2 and then take the conjugate transpose of it and check the criteria?


How to express $\ln\left(\frac{1}{1+j}\right)$ in rectangular form?

Question: Trying to understand how to express this complex number $\ln\left(\frac{1}{1+j}\right)$ into rectangular form.
I thought to use $x = r\cos(\theta)$ and  $ y = r\sin(\theta)$, but I am pretty sure that is wrong.
Comment: There was absolutely no reason to edit the question, it is my preference to decide if I want parenthesis around theta. So irrelevant and trivial to edit the question.
Comment: Can you calculate the magnitude and the argument of $1/(1+j)$ (that is, can you express $1/(1+j)$ in polar form)? If so, do you know how to compute the complex logarithm of a number in that form?
Comment: @GenoC The edited version corrected typesetting.
Comment: @GregMartin, I am so stupid, I am sorry I see what you mean now.
Comment: You're not stupid—you're simply learning!
Answer: If by $\ln$, you mean the main branch of the complex logarithm (remember, the complex logarithm is a fairly complicated topic), then use the fact that $$\log z = \log|z| + i\cdot \mathrm{Arg}(z).$$
Answer: $$\ln\frac1{1+i}=-\ln(1+i)=-\ln\sqrt2e^{i\pi/4}=-(\ln\sqrt2+i\pi/4)=\ln\frac1{\sqrt2}-i\pi/4$$
with the usual caveat about $\ln$'s multivaluedness.
Comment: Eh, thank you for the answer but I want to make sure I know how to do this for future questions for my Linear systems class. Could you explain in more detail?
Comment: @GenoC What I did is essentially what Greg Martin outlined in the comment on the main question.
Comment: I am confused where $\frac{\pi}{4}$ comes from?
Comment: @GenoC It is the _argument_ of $1+i$.
Answer: $$\ln\Bigl(\frac{1}{1+i}\Bigr)=-\ln\Bigl(1+i\Bigr)= -\ln\Bigl(\sqrt{2}\Bigl(\frac{1}{\sqrt{2}}+\frac{i}{\sqrt{2}}\Bigr)\Bigr)$$
$$-\ln\Bigl(\sqrt{2}\Bigl(\frac{1}{\sqrt{2}}+\frac{i}{\sqrt{2}}\Bigr)\Bigr)=-\ln\Bigl(\sqrt{2}\Bigl(\cos\frac{\pi}{4}+{i}\sin\frac{\pi}{4}\Bigr)\Bigr)$$
$r(\cos\theta +i\sin\theta)$ can be written as $re^{i\theta}$
$$-\ln\Bigl(\sqrt{2}\Bigl(\cos\frac{\pi}{4}+{i}\sin\frac{\pi}{4}\Bigr)\Bigr)=-\ln\Bigl(\sqrt{2}\Bigl(e^{i\frac{\pi}{4}}\Bigr)\Bigr)=-\ln\sqrt{2} -\ln{e^{i\frac{\pi}{4}}}$$
$$= \ln\frac{1}{\sqrt{2}} -i\frac{\pi}{4}$$


What does training correlation coefficient means in ANN prediction

Question: I'm a beginner in statistics with limited knowledge.
I'm reading up on neural networks to predict outputs using inputs.
I understand that a neural network has to be trained to produce the Least mean squared error from the desired output.
What does it mean by training correlation coefficient?
Answer: The question is not very clear to me but if I have understood correctly than this is the answer:
The neural network have to be trained in order to minimize a cost function.
Usually the cost function is the MSE. In other cases the cost function can be 1 - correlation coefficient.
Comment: Does it means that, for the cost function (MSE) to be minimum, it will need a suitable correlation coefficient to meet that objective?
Comment: No it means that different cost functions can be used. So you can decide if to minimize the MSE error or the 1-correlation function. There are also other kind of cost functions but these are probably the most common for regression problems


Android: map view doesn't work

Question: in my Android App I have add a map activity whit the Android Studio procedure (add-> new activity -> Google -> Map). I have followed this example: https://developers.google.com/maps/documentation/android-api/start#step_2_install_the_google_play_services_sdk.
But if I open the map activity, it's strange, I see only a map whit the Google logo but completely empty (I attach a screenshot). And I don't see any connection or key error message. Why?
PS I have only added the "import com.mycompany.myapp.R" row in the activity java file, because in the original file create with the automatic procedure, I see all "R" in that file in red as an error.
Summarizing:
1) I have add a map activity whit the Android Studio automatic procedure
2) I have followed the procedure and copied the key in my app (I don't see any key or certificate error message)
3) I have only add the row about import com.mycompany.myapp.R
4) If I test on my real device, I see a blank map.
Thank!
Code of activity:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mycompany.myapp.Views.myFragmentMap" />

Code of java file related to the activity:

package com.mycompany.myapp.Views;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

//I have added only this one!
import com.mycompany.myapp.R;

public class myFragmentMap extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_myapp_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

Google maps api file, in which I have copied my key:

<resources>

    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">
        AIza.... (and the correct code imported from Google)
    </string>
</resources>

And this is the screen of the activity
Comment: Check your logs, there will be an error regarding the API key.
Comment: just launch after sometime it may be downloading playstore update
Answer: Did you run the application right after installing the Google Play services SDK?
Daniel is right, you can check the logs for error that might be related to API key.

Get a Google Maps API key
Your application needs an API key to access the Google Maps servers. The type of key you need is a Key for Android applications. The key is free. You can use it with any of your applications that call the Google Maps Android API, and it supports an unlimited number of users.
Use the credentials provided in the google_maps_api.xml file that Android Studio created for you:

Copy the credentials provided in the google_maps_api.xml file.
Go to the Google Developers Console in your browser.
Use the copied credentials to add your app to an existing API key or to create a new API key. For more details, see the complete process.

Following all steps from 1-7 will give you the basic working google maps app. I hope it helps. Also here a previous Google Map on Android do not load SO that you may relate your experience
Answer: I got similar issue. Try delete your app and reinstall again.

Android: map view doesn't work


Propriedade componente não grava

Question: Estou criando um componente baseado em TDBGrid, incrementando algumas funcionalidades, por exemplo, para zebrar, porém, mesmo eu ativando TRUE na propriedade ZEBRAR, ele aparece FALSE quando passa pelo código debugando, e a opção escolhida para a propriedade não fica salvo no projeto também, como se não estivesse indo para o ".dfm", sendo assim, ao abrir o projeto, a propriedade esta FALSE novamente. (ao fechar o projeto o delphi trava também). Alguém pode me dar uma dica onde estou errando? Já procurei na internet e não consigo encontrar a solução. Grato.
Segue a implementação:
unit MZDBGrid;

interface

uses
  System.SysUtils, System.Classes, Vcl.Controls, Vcl.Grids, Vcl.DBGrids, Vcl.Graphics, System.Types;

type
  TBloqueios = (blqInsert, blqDelete);
  TBloqueio = set of TBloqueios;

  TCorZebra = class
  private
    FZebrar: Boolean;
    FCorPrimaria: TColor;
    FCorSecundaria: TColor;
  public
    constructor Create;
  published
    property Zebrar: Boolean read FZebrar write FZebrar default False;
    property CorPrimaria: TColor read FCorPrimaria write FCorPrimaria default clWindow;
    property CorSecundaria: TColor read FCorSecundaria write FCorSecundaria default clSilver;
  end;

  TMZDBGrid = class(Vcl.DBGrids.TDBGrid)
  private
    FCorZebra: TCorZebra;
    FBloqueio: TBloqueio;
    procedure SetCorZebra(Value: TCorZebra);
  protected
    procedure DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property CorZebra: TCorZebra read FCorZebra write SetCorZebra stored True; // NAO FICA GRAVADO NO PROJETO
    property Bloqueio: TBloqueio read FBloqueio write FBloqueio stored True; // NAO FICA GRAVADO NO PROJETO
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('MZComponents', [TMZDBGrid]);
end;

{ TMZDBGrid }

constructor TMZDBGrid.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FCorZebra := TCorZebra.Create;
  FCorZebra.CorPrimaria := clWindow;
  FCorZebra.CorSecundaria := clSilver;
  Include(FBloqueio, blqInsert);
  Include(FBloqueio, blqDelete);
end;

destructor TMZDBGrid.Destroy;
begin
  FCorZebra.DisposeOf;
  inherited Destroy;
end;

procedure TMZDBGrid.DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  inherited;
  if FCorZebra.Zebrar then // MESMO COLOCANDO TRUE NO PROJETO, AO DEBUGAR CHEGA AQUI FALSE
  begin
    if Odd(Self.DataSource.DataSet.RecNo) then
      Self.Canvas.Brush.Color := FCorZebra.CorPrimaria
    else
      Self.Canvas.Brush.Color := FCorZebra.CorSecundaria;

    Self.Canvas.FillRect(Rect);
    Self.DefaultDrawColumnCell(Rect, DataCol, Column, State);
  end;
end;

procedure TMZDBGrid.SetCorZebra(Value: TCorZebra);
begin
  if Assigned(FCorZebra) then
    FCorZebra := Value;
end;

{ TCorZebra }

constructor TCorZebra.Create;
begin
  FZebrar := False;
  FCorPrimaria := clWindow;
  FCorSecundaria := clSilver;
end;

end.

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Comment: Será que ele está chegando como false porque o default value que você passou para property na classe que ela pertence é false hence `Zebrar: Boolean read FZebrar write FZebrar default False`?
Comment: @Diego_F obrigado pela sugestão.
Answer: Consegui resolver com as seguintes alterações:
unit MZDBGrid;

interface

uses
  System.SysUtils, System.Classes, Vcl.Controls, Vcl.Grids, Vcl.DBGrids, Vcl.Graphics, System.Types;

type
  TBloqueios = (blqInsert, blqDelete);
  TBloqueio = set of TBloqueios;

{$M+}

  TCorZebra = class(TPersistent)
  private
    FZebrar: Boolean;
    FCorPrimaria: TColor;
    FCorSecundaria: TColor;
  public
    constructor Create;
  published
    property Zebrar: Boolean read FZebrar write FZebrar;
    property CorPrimaria: TColor read FCorPrimaria write FCorPrimaria;
    property CorSecundaria: TColor read FCorSecundaria write FCorSecundaria;
  end;

  TMZDBGrid = class(Vcl.DBGrids.TDBGrid)
  private
    FCorZebra: TCorZebra;
    FBloqueio: TBloqueio;
    procedure SetCorZebra(Value: TCorZebra);
    procedure SetBloqueio(const Value: TBloqueio);
  protected
    procedure DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property CorZebra: TCorZebra read FCorZebra write SetCorZebra;
    property Bloqueio: TBloqueio read FBloqueio write SetBloqueio;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('MZComponents', [TMZDBGrid]);
end;

{ TMZDBGrid }

constructor TMZDBGrid.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  FCorZebra := TCorZebra.Create;
  Include(FBloqueio, blqInsert);
  Include(FBloqueio, blqDelete);
end;

destructor TMZDBGrid.Destroy;
begin
  FCorZebra.DisposeOf;
  inherited Destroy;
end;

procedure TMZDBGrid.DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  inherited;
  if FCorZebra.Zebrar then // MESMO COLOCANDO TRUE NO PROJETO, AO DEBUGAR CHEGA AQUI FALSE
  begin
    if Odd(Self.DataSource.DataSet.RecNo) then
      Self.Canvas.Brush.Color := FCorZebra.CorPrimaria
    else
      Self.Canvas.Brush.Color := FCorZebra.CorSecundaria;

    Self.Canvas.FillRect(Rect);
    Self.DefaultDrawColumnCell(Rect, DataCol, Column, State);
  end;
end;

procedure TMZDBGrid.SetBloqueio(const Value: TBloqueio);
begin
  FBloqueio := Value;
end;

procedure TMZDBGrid.SetCorZebra(Value: TCorZebra);
begin
  if Assigned(FCorZebra) then
    FCorZebra := Value;
end;

{ TCorZebra }

constructor TCorZebra.Create;
begin
  FZebrar := False;
  FCorPrimaria := clWindow;
  FCorSecundaria := clSilver;

  inherited;
end;

end.

Propriedade componente não grava


Unexpected results when using dynamic input in QueryBuilder

Question: I wrote a SQL query to interact with an MS Access database. Here's the query:
SELECT COUNT(*) AS Expr1
FROM employee
WHERE ([M-ID] = ?) AND (pnumber NOT IN (
    SELECT pnumber
    FROM evaluation
    WHERE ([year] = ?) AND ([month] = ?)
))

The query meant to count the number records that are present within employee table and not present in the evaluation with the given conditions.
Problem is when I replace the placeholders with actual input it works correctly. But when placeholders are present (?) in the query and VisualStudio prompts for the input it returns different results. I enter the very same input in the prompt dialogue as I did previously in the query but results are different. When parameters are provided statically within the query the result of COUNT is correct but not when provided dynamically via ? placeholders.
Below are a few screenshots to illustrate the issue.
Dynamic Input:

Dynamic Input Results:

Static Input Results:

Any ideas?
Comment: Did you also try the combinations of 2 placeholders and 1 static value? Sorry, all I can do is to think along and at this moment I would guess that the query builder does not map the fields of the pop up to the correct placeholder (since they are all called ? you have no way to know which is the first/second/third in your query.)
Comment: I'm not that familiar with the visual studio query-builder but is it possible to replace the 3 static values one by one with a question mark to see if the problem is due to one specific placeholder?
Comment: I did that. As far as I see the problem is with the combination of all three placeholders. If I remove one of them, no matter which the query will correctly result in 3. Thank you for your comment.
Comment: I just reread your last comment and realize you actually already answered my previous question, sorry for missing that.
Answer: wild guess, but based on Access experience back to 2.0: take the hyphen out of the field name.
Comment: Thank you very much Delmer, you saved me a hell of time!


Is there a way to run drush updb without going to maintenance mode

Question: I have a live site which runs on drupal 8. I am using drush 8.5.3 with the installation. Whenever I run drush updb the site automatically goes to maintenance mode. Is there a way to do this without going to maintenance mode. In simple words, can I use drush updb with my site running?
Comment: Consider the answer found here: https://drupal.stackexchange.com/questions/270793/is-it-normal-that-drupal-enters-maintenance-mode-during-a-module-update
Comment: Possible duplicate of [Should a site be in maintenance mode when running the Drush Up command?](https://drupal.stackexchange.com/questions/134087/should-a-site-be-in-maintenance-mode-when-running-the-drush-up-command)
Comment: I have experienced issues with this causing which is possibly an edge case. In a containerized infrastructure sometime the container terminates (or there is a system failure) . This makes the site stuck in maintenance mode even after  subsequent successful updbs. The onlyway to get out of it manually via the UI or drush.
Answer: Actually, if you take a look at the drush code for updatedb command, you can find this piece of code in updateBatch() function:
$original_maint_mode = \Drupal::service('state')->get('system.maintenance_mode');
if (!$original_maint_mode) {
    \Drupal::service('state')->set('system.maintenance_mode', true);
    $operations[] = ['\Drush\Commands\core\UpdateDBCommands::restoreMaintMode', [false]];
}

For safety reasons, the drush command puts your site in maintenance mode during the update and then set it back online once it is completed. It prevents your users from accessing the website and generate possible conflicts within the database while it is updating.
There is a pretty clear explanation of this here
If you really wish to avoid the maintenance mode, though, you could run update.php directly from your website.
Answer: No. The critical path for drush updb is through:

update_main()
drush_update_batch()

Where drush_update_batch() toggles the maintenance mode state prior to processing the updates needed to be processed.
Theoretically, you could modify Drush itself or create your own Drush command that mimics the drush_update_batch() code without toggling maintenance mode. But a better question would be why? Maintenance mode is being set to prevent any problems while DB schema is being altered.


Integer part of a sum (floor)

Question: Let $\left(\, x_{n}\,\right)_{\,n\ \geq\ 1}$ be a sequence defined as follows:
$$
x_{1}={1 \over 2014}\quad\mbox{and}\quad x_{n + 1}=x_{n} + x_{n}^{2}\,,
\qquad\forall\ n\ \geq\ 1
$$
Compute the integer part of the sum:
$$
S=\frac{x_1}{x_2} + \frac{x_2}{x_3} + \cdots +\frac{x_{2014}}{x_{2015}}\,,\qquad
\left(\,\mbox{i. e.}\  \left\lfloor\, S\,\right\rfloor\,\right)$$
Any nice idea to approach this? How can one find a formula for $x_{n}$?
Thank you!
Comment: Recurrence relations aren't solvable in general. Are you sure that there is a solution?
Comment: It is clearly that not all recurrences have a closed form. This is from a youth magazine.
Comment: Alright, so there should be an answer, thanks. And yes, I meant a closed form solution in terms of $n$.
Comment: You are welcome! Maybe there is a mistske, but I'm interested in solving the problem as it is! At first sight I thought it is easy, but I have never been so wrong.
Comment: Deceptively simple, isn't it? I've taken a few stabs at it, but nothing seems to be working. Unfortunately, I have to get back to studying for my exams.
Comment: Yes, simple but complicated. I wish you good luck with your exams!
Comment: @CFG: What exact magazine is this? Did you change any part of the problem? Are calculators allowed or is a mathematical proof required?
Comment: A mathematical proof is required. I think there is something wrong with the problem, but I like it!
Comment: @CFG: Please don't deface the posts like that.
Comment: It was one of my friends who did this. I appologize!
Answer: Your sum is telescoping since
$$S={\displaystyle \sum_{k=1}^{2014}\frac{x_{k}}{x_{k+1}}=\sum_{k=1}^{2014}\frac{x_{k}^{2}}{x_{k}x_{k+1}}=\sum_{k=1}^{2014}\frac{x_{k+1}-x_{k}}{x_{k}x_{k+1}}=\sum_{k=1}^{2014}(\frac{1}{x_{k}}-\frac{1}{x_{k+1}})}
$$
$$
{\displaystyle =\frac{1}{x_{1}}-\frac{1}{x_{2015}}=2014-\frac{1}{x_{2015}}.}$$
Hence it's a matter of evaluating $x_{2015}$.
It seems that $.17<x_{2015}<.18$ and $S=2008.22$.
Some identities that might help
$$ x_{2015}=x_1+\sum_{k=1}^{2014} x_k^2;\ x_{2015}=x_1(1+x_1)(1+x_2)\cdot\ldots\cdot(1+x_{2014})$$probably with some inequalities involving sums and products.
Comment: @CFG Would you be so kind and edit your problem so that it reflects the things you knew like the fact that the sum is telescoping and that it reduces to $x_{2015}$?
Comment: I knew that the sum is telescoping. My problem is with $x_{2015}$. How do you get that inequality, @Silencer?
Comment: I made mistake. Sorry.
Comment: Look also [here](http://pastebin.com/RMtxWNnV). You can take bigger precision, and (if I didn't make mistake) receive the answer should be 2008.
Comment: @Silencer If the answer 2008 is correct then it makes the mathematical proof of this problem even more interesting!
Comment: @NeutralElement it looks like it is. Everything seems correct. But I don't have idea, how to prove it using pen and paper.
Answer: To get a bound on $\dfrac{1}{x_{2015}}$, let $y_n = \dfrac{1}{x_n}$. Then, $\dfrac{1}{y_{n+1}} = \dfrac{1}{y_n}+\dfrac{1}{y_n^2} = \dfrac{y_n+1}{y_n^2}$.
Hence, $y_{n+1} = \dfrac{y_n^2}{y_n+1} = y_n-\dfrac{y_n}{y_n+1}$. Rearrange to get $\left(1+\dfrac{1}{y_n}\right)(y_n-y_{n+1}) = 1$.
Since $y_n$ is a decreasing sequence and $1+\dfrac{1}{y}$ is a decreasing function, we have:
$2014 = \displaystyle\sum_{n = 1}^{2014}\left(1+\dfrac{1}{y_n}\right)(y_n-y_{n+1}) = \sum_{n = 1}^{2014}\int_{y_{n+1}}^{y_n}\left(1+\dfrac{1}{y_n}\right)\,dy \le \sum_{n = 1}^{2014}\int_{y_{n+1}}^{y_n}\left(1+\dfrac{1}{y}\right)\,dy = \int_{y_{2015}}^{y_1}\left(1+\dfrac{1}{y}\right)\,dy = \left[y + \ln y\right]_{y_{2015}}^{y_1} = (2014+\ln 2014)-(y_{2015}+\ln y_{2015})$
Therefore, $y_{2015}+\ln y_{2015} \le \ln 2014$. Exponentiation yields $y_{2015}e^{y_{2015}} \le 2014$.
If you can convince yourself that $6e^6 > 2014$, then we have $y_{2015} \le 6$ (because $ye^y$ is increasing).
Therefore, $S = 2014 - y_{2015} \ge 2008$. It remains to show that $S \le 2009$, i.e. $y_{2015} \ge 5$.
Answer: JimmyK has ignored the request (in now deleted comments) to add the lower bound proof to his answer, so I will add an answer with the lower bound proof which will resolve the question completely.
Just like Jimmy's excellent upper bound proof we use
$$ 2014 = \sum_{n=1}^{2014}\left(1 + \frac{1}{y_n}\right)(y_n - y_{n+1}) = \sum_{n=1}^{2014} \int_{y_{n+1}}^{y_n} \left(1 + \frac{1}{y_n}\right) dy$$
Now we can easily show by induction that $y_k \gt -1$ and thus
$$y_{n+1} + 1 \gt y_{n+1} + \frac{y_n}{1+y_n} = y_n$$
Thus we have that
$$\left(1 + \frac{1}{y_n}\right) \ge \left(1 + \frac{1}{y_{n+1} +1}\right)$$
Now for $-1 \lt y_{n+1} \le y$ we have that
$$\left(1 + \frac{1}{y_{n+1} +1}\right) \ge \left(1 + \frac{1}{y +1}\right)$$
Thus
$$\left(1 + \frac{1}{y_n}\right) \ge \left(1 + \frac{1}{y +1}\right)$$
Let $a = y_{2015}$
We thus have
$$ 2014 = \sum_{n=1}^{2014} \int_{y_{n+1}}^{y_n} \left(1 + \frac{1}{y_n}\right)dy \ge \sum_{n=1}^{2014} \int_{y_{n+1}}^{y_n} \left(1 + \frac{1}{y +1}\right) dy = \int_{a}^{2014} \left(1 + \frac{1}{y +1}\right) dy =$$
$$ 2014-a + \log(2015) - \log(a+1)$$
Thus
$$ 2014 \ge 2014-a + \log(2015) - \log(a+1)$$
which means
$$ a + \log(a+1) \ge \log (2015)$$
giving us
$$ (a+1)e^{a} \ge 2015$$
Now $6e^5 \lt 6 \times3^5 = 1458$ and since $(x+1)e^x$ is increasing, we have $$a \gt 5$$
This coupled with the other two answers gives the answer of $$2008$$

An observation:
$$y_{n+1} = y_n - \frac{f(y_n)}{f'(y_n)}$$
where  $f(y) = ye^y$.
This is a Newton Raphson recurrence and techniques used there should be applicable here.
Comment: @CFG: You are welcome. Can you please tell us the name of the youth magazine? Sounds like a very interesting one...
Comment: @CFG: I don't understand. What is wrong with mentioning the source? Someone who has physical access can take a look.
Comment: @CFG: Thanks...!
Comment: Interesting. CFG deleted his comment. The magazine is apparently Gazetta Mathematica. I was unable to find it in there though (didn't look too hard).
Comment: Please delete your comment. It's from an additional collection of this magazine (for fun), which can't be found on the internet.

Integer part of a sum (floor)


Can any one tell whats wrong with this query?

Question:     $sql    =   "select * from instalmentsdetails_ where studentFeeId='$savestudentfees' AND instalmentName='$instlnamefdtls'";
    $query  =   $this->db->query($sql);
    if($query->num_rows() > 0){
        echo($id);
        $this->db->where('instalmentsDetailsId',$id);
        $this->db->update('instalmentsdetails_',$instldata);
    }else{
        echo($id);
        $id='';
        echo($id);
        $sql=   "INSERT INTO instalmentsdetails_` (`instalmentsDetailsId`, `studentFeeId`, `instalmentName`, `amount`, `dueDate`, `status`) VALUES ('$id', '$savestudentfees', '$instlnamefdtls', '$amtfdtls', '2011-10-06', '1')";
        $id=$this->db->insert_id();
        $query  =   $this->db->query($sql);
        return $query;
    }
    return $id;

This query first checks if there are any rows present, if there is, it is going to update the old record, otherwise it is going to create a new record, but for some reason it does not work as expected even when the query returns num_row() > 0.It's a model in codeigniter
Comment: if condition in `if` is true - then `if` body isn't executed. By definition. You have `num_rows <= 0` or insert the data somewhere else in your code.
Answer: Have you checked the output of $query->num_rows()?, eg echo $query->num_rows()
You could do this instead and save the bother in PHP
ALTER TABLE teami_db ADD UNIQUE INDEX(studentFeeId, instalmentName);

Then you can perform an ON DUPLICATE KEY UPDATE query like so.
INSERT INTO `instalmentsdetails_teami` (
  `instalmentsDetailsId`,
  `studentFeeId`,
  `instalmentName`,
  `amount`,
  `dueDate`,
  `status`
) VALUES (
  '$id',
  '$savestudentfees',
  '$instlnamefdtls',
  '$amtfdtls',
  '2011-10-06',
  '1'
) ON DUPLICATE KEY UPDATE
  `instalmentsDetailsId` = VALUES(`instalmentsDetailsId`),
  `studentFeeId`         = VALUES(`studentFeeId`),
  `instalmentName`       = VALUES(`instalmentName`),
  `amount`               = VALUES(`amount`),
  `dueDate`              = VALUES(`dueDate`),
  `status`               = VALUES(`status`)

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Comment: bro the prob is that its not updating rather creating a new row or inserting a new row
Comment: It will only create a new row if a duplicate key doesn't exist in the database, otherwise it will update. You must have the UNIQUE index on the two columns.This saves 1 extra query as the duplicate key check is doing what your first query did, and its saving duplicated code, making it more efficient also.
Comment: sure Geoffrey.. wil check it out and let u know.. Thanks again for ur help
Comment: THANKS Geoffrey .. its working ... Accepted ur answer and upvoted it
Comment: No problems :) Thanks for the rep.


selinux mls ssh getting denied dyntransition - login failure

Question: I am trying to learn SELinux and going though the Red Hat documentation for RHEL 7. I came upon the documentation for Multi Layer Security (MLS) and wanted to try it, so I set SELINUXTYPE=mls and SELINUX=permissive , touched /.autorelabel (echoed an -F into it) and rebooted.
I was able to log in, but wanted to check the audit log to make sure no failure or denials happen that would prevent me from logging in using enforcing mode. I found the following:
type=AVC msg=audit(1457127380.826:208): avc:  denied  { dyntransition } for      pid=2109 comm="sshd" scontext=system_u:system_r:sshd_t:s0-s15:c0.c1023 tcontext=root:sysadm_r:sysadm_t:s0 tclass=process

So, I figured that was nothing to worry about (Still learning), so i set SELINUX to enforcing and rebooted. Locked myself out!
I was able to get back in with some hacking and set SELINUX back to permissive, but I am not sure why its not working...
I have tried to restorecon /usr/sbin/sshd and it does have the correct context:
ls -Z /usr/sbin/sshd
-rwxr-xr-x. root root system_u:object_r:sshd_exec_t:s0 /usr/sbin/sshd

But if you look at the tcontect in the error its strange:
 tcontext=root:sysadm_r:sysadm_t:s0

Anyway, as I stated, I am still learning, so any advice would be helpful... Documentation to explain any examples or solutions would be greatly appreciated - "Teach a man to fish..."
Thanks so much!
Joe
Comment: Nobody uses MLS and half your issue is the policies dont really support it. Nobody really uses it enough for it to gain enough attention to its policies. Its an interesting security model based on bell-la-puda, but in production and in reality -- whereever I've used SELinux before its never been considered.
Comment: @MatthewIfe My understanding is that DoD uses it pretty extensively, but MLS is not something that "works out of the box". It needs to be heavily customized for the security needs of the environment. And that generally requires an SELinux expert or two. Being part of an IPA domain is also a good idea, as it helps ease some of the administrative burden.
Comment: Hi Mathew, yeah, I didn't get the feeling that it was widely used when I was trying to search for the issue, but it does look powerful and as Michael pointed out, the DOD and DOE does seem to use it allot so I would like to learn more about it.
Answer: It looks like root is not allowed to login directly via ssh on an MLS system.
You will need to ssh in as a staff_t user and then sudo to root.
Comment: Hi Michael, Oh, ok. Let me try that and see what happens. It does make since that root would not be allowed to log in, so making another user and sudoing should work. I will play with that and see how it works out.


Verificar se uma div está visivel

Question: Preciso saber qual id da div visível, estou procurando sobre isVisible() porem não está dando certo, o que devo fazer ?
Problema:

Tenho varias divs que tomam contam da tela toda, porém so deixo visivel a tela que está em questão na tela, porém preciso saber qual id desta dela. As telas restantes ficam com propriedade display: none;

Tenho por padrão as divs da seguinte forma:

e o que estou fazendo é o seguinte:
if($('.upage').is(':visible') == 'home'){
}else{}

Comment: Sim, a resposta do @Sergio é muito boa.
Comment: `.is(':visible');`?
Comment: @RenanRodrigues A sugestão do Sergio está correta, é assim que você determina se uma div está visível. Mas se você quer buscar por uma div visível entre um conjunto de divs, basta usar `$(":visible")` (mas provavelmente você vai querer filtrar mais pra não retornar tudo quanto é elemento visível na página inteira, tipo `$(".upage:visible")`).
Comment: Para pegar o Id faça assim: `$("div:visible").attr("id");`
Comment: não sei se é assim mesmo.
Comment: E para pegar o ID da div visivel ?
Comment: o que você está considerando como visible?
Comment: @durtto Utilizo o que não está com hidden, a dica dos nossos amigos resolveram meu problema e sanaram minha duvida. Obrigado a todos.
Answer: O jQuery tem um pseudo seletor para isso. O :visible que pode ser usado em combinação com o .is(). Desse modo recebes um Booleano.
Podes usar assim:
var visivel  = $('#minhaDiv').is(':visible');
if (visivel) alert('Sim!');
else alert('Não :( ...');

jsFiddle: http://jsfiddle.net/jLk6ot27/
ou dentro do próprio seletor assim:
var elementos = $('div:visible');

neste caso só vai selecionar elementos que estejam visiveis.
Se quiseres saber o ID de vários podes fazer $('div:visible').get().map(function(el){ return this.id; });. Se fôr só um podes fazer o mesmo ou usar jQuery assim: $('div:visible').attr('id')
jsFiddle: http://jsfiddle.net/jLk6ot27/2/

Verificar se uma div está visivel


python bdist_rpm not using install_requires?

Question: I've created a new RPM using python bdist_rpm . Normally python setup.py install would install python dependencies like websocket-client or any other package. But the RPM just refuses to install anything.
Apparently the suggestion from various other posts seem to be in the line of just requiring them in setup.cfg as rpm packages. This doesn't make sense to me since most of the rpm packages seem to be on really old version and I can't possibly create rpms for all the python packages i require. I need a much recent version and it doesn't make sense that the yum installs don't actually install the packages.
What is the right (clean and easiest) way to do it ? I believe if a setup.py has something like
install_requires=[
    "validictory",
    "requests",
    "netlogger>=4.3.0",
    "netifaces",
    "pyzmq",
    "psutil",
    "docopt"
],

Then it should try to either include them in the rpm or try to install it.
I am trying on a clean centos vm using vagrant which I keep destroying and then install the rpm.
Answer: Well the super hack way i used was to just add a post install script with all the requirements as easy_install installation (instead of pip because older versions may not have pip and even after installing pip, the approach failed on systems with python 2.6)
#Adding this in setup.py
options = {'bdist_rpm':{'post_install' : 'scripts/rpm_postinstall.sh'}},

Then the script is as follows:
easy_install -U <pkgnames>

Of course a post_uninstall can also be added if you want to clean up which I wouldn't because you have no clue what is using the packages installed apart from this app.
The logic of the rpm approach seems to be for this but its honestly over engineering and I'd rather package all the modules with the rpm to ensure it always works. ** Screaming out for a cleaner solution **


How do I change (upgrade) my Elastic Beanstalk instance type?

Question: My current Elastic Beanstalk environment is using the "t2.micro" instance. Recently, my website is getting a lot of traffic and it is not been able to handle CRON jobs. The instance is getting overloaded with high memory usage.
I want to change my instance to better RAM (at least 4GB). I can't find the option to change the instance type in Elastic Beanstalk settings.
Can you please guide me on how to upgrade the instance without any downtime? Thank you
Answer: AWS documentation tells you how to do this.

Open the Elastic Beanstalk console, and in the Regions list, select your AWS Region.

In the navigation pane, choose Environments.

Choose Create a new environment to start creating your environment.

On the wizard's main page, before choosing Create environment, choose Configure more options.

In the Instances configuration category, choose Edit. Make changes to settings in this category, and then choose Apply. For setting descriptions, see the section Instances category settings on this page.

In the Capacity configuration category, choose Edit. Make changes to settings in this category, and then choose Continue. For setting descriptions, see the section Capacity category settings on this page.


Grouping data across midnight and performing an operation using pandas

Question: I have the following data contained in a DataFrame which is part of a custom Class, and I want to compute stats on it for night-time periods.
                     LAeq,T  LAFmax,T  LA90,T
Start date & time
2021-08-18 22:00:00    71.5      90.4    49.5
2021-08-18 22:15:00    70.6      94.0    45.7
2021-08-18 22:30:00    69.3      82.2    48.3
2021-08-18 22:45:00    70.1      89.9    46.4
2021-08-18 23:00:00    68.9      82.4    46.0
                     ...       ...     ...
2021-08-24 08:30:00    72.3      85.0    61.3
2021-08-24 08:45:00    72.9      84.6    62.2
2021-08-24 09:00:00    73.1      86.1    62.6
2021-08-24 09:15:00    72.8      86.4    61.6
2021-08-24 09:30:00    73.2      93.5    61.5

For example, I want to find the nth highest LAFmax, T for each given night-time period.
The night-time period typically spans 23:00 to 07:00, and I have managed to accomplish my goal using the resample() method as follows.
def compute_nth_lmax(self, n):
    nth_lmax = self.df["LAFmax,T"].between_time(self._night_start, self._day_start,
                                                                     include_start=True, include_end=False).resample(
        rule=self._night_length, offset=pd.Timedelta(self._night_start)).apply(
        lambda x: (np.sort(x))[-n] if x.size > 0 else np.nan).dropna()

    return nth_lmax

The problem is that resample() assumes a regular resampling, and this works fine when the night-time period is 8 hours and therefore subdivides 24 equally (as in the default case of 23:00 to 07:00), but not for an irregular night-time period (say, if I extended it to 22:00 to 07:00).
I have tried to accomplish this using groupby(), but had no luck.
The only thing I can think of is adding another column to label each of the rows as "Night-time 1", "Night-time 2" etc., and grouping by these, but that feels rather messy.
Answer: I decided to go with what I consider a slightly inelegant approach and create a separate column which flags the night-time periods, before processing them. Still, I managed to achieve my goal in 2 lines of code.
self.df["Night-time indices"] = (self.df.index - pd.Timedelta(self._day_start)).date
nth_event = self.df.sort_values(by=[col], ascending=False).between_time(self._night_start, self._day_start)[
            [col, period]].groupby(by=period).nth(n)
Out[43]:
Night-time indices
2021-08-18    100.0
2021-08-19     96.9
2021-08-20     97.7
2021-08-21     95.5
2021-08-22    101.7
2021-08-23     92.7
2021-08-24     85.8
Name: LAFmax,T, dtype: float64


JSAngular Múltiplos ng-repeat

Question: Estou com uma dificuldade para criar um loop's com ng-repeat, no angular. Seguinte...Eu queria criar tags para cada projeto que eu adicionar, exemplo:

Veja que é possível adicionar mais tags e há também, no final, um texto, que ao clicado adciona um novo projeto, chamado Add Projeto, ficando assim:

O PROBLEMA: Quando eu digito um texto para a tag do projeto1 é inscrito, ao mesmo tempo, na tag do projeto2! Eu imagino que isso seja por conta do {{tag.taagscliente}}, que está sendo o mesmo pra cada projeto. Como eu faço esse loop, sem haver esse conflito, digo, separar as tags para cada projeto? Código do projeto abaixo:

       <form action="">

                        Pasta Projeto

                            <input type="text" name="projetos_cliente[]" ng-model="projeto.projetoscliente">

                            Tags

                                    <input type="text" name="tag_cliente[]" ng-model="tag.taagscliente">

-

+

Add Projeto

                </form>

ANGULAR:
var app = angular.module('app', ['ngTagsInput']);

app.controller('dash', function($scope, $http){

    $scope.clientes = [{'text': 'Digite o projeto'}];
    $scope.add = function () {
            $scope.clientes.push({
                projetoscliente:""
            });
      };

      $scope.del = function (index) {
            $scope.clientes.splice(index, 1);
      };

      $scope.taags = [{'text': 'Digite o projeto'}];
      $scope.addTag = function () {
            $scope.taags.push({
                tagscliente:""
            });
      };

      $scope.delTag = function (index) {
            $scope.taags.splice(index, 1);
      };

});

Comment: **Ofereço 100 pontos de reputação para a sua próxima pergunta no http://pt.stackoverflow.com.**
Comment: Alguém??????????
Answer: Você pode definir uma coleção de tags pra cada projeto. Algo assim:

Projetos

              Projeto:
                  <input class="form-control" ng-model="project.name">
                {{ project.tags.length }}
              <input class="form-control" ng-model="tag">  +

{{ tag }}  -

          Add Projeto

E o código js angular:
function TagsCtrl($scope) {
  $scope.projects = [
      { name: 'Projeto 1', tags: ['tag1', 'tag2'] },
      { name: 'Projeto 2', tags: [] }
  ];

  $scope.addProject = function() {
      $scope.projects.push({ name: '', tags: [] });
  };

  $scope.addTag = function(project, tag) {
      project.tags.push(tag);
      console.log(project);
  };

    $scope.delTag = function(project, index) {
      project.tags.splice(index, 1);
  };
}

Demo.
Comment: Iuri, meu amigo, tem como implementar um autocompletar com valores predefinidos para o input das tags? Não estou conseguindo nessa versão do angular. Abraço.

JSAngular Múltiplos ng-repeat


SQL Fulltext Search Index or custom query to searching app database?

Question: I have a .NET, SQL2005, C# website which will be open to public in June 2011
Site has video albums containing videos. Video albums and Videos has title, tags, description and other fields.
Video albums and videos are stored in different tables. Video albums can be public and private. I want to exclude the private albums and videos from search
I have stored procedure that searches just the tag field of albums and videos tables.
Will this stored proc scale with the number of rows in the tables?
I don't have full text search on title or tag field.
I would prefer searching the Title field. But the query requires '%keys%' format which slow.
What do you recommend to go with as search solution and prevent redesign later on?
EDIT: My original question was longer and nobody cared. So shorted.
Answer: You might look into Google Site Search. It's easy, customizable, and recognizable.


Unique validator in Symfony2

Question: I have a user sign-up form. One of the things this form must do is enforce the uniqueness of the new user's email address. In other words, the new user's email address must not be an email address already used by someone else.
I haven't yet been able to find an acceptable solution to this problem, which is somewhat surprising given how simple and common this need is (and how simple and easy the solution is in Rails!).
I've seen this question/answer, but the problem with that solution is that it seems to validate "uniqueness" not only on the creation of a record, but every time you try to update the record as well. So once a record is saved, you can't update it ever again because it tells you the email address is already being used. (Perhaps I'm implementing their solution wrong, but it doesn't seem like I am.)
Does anyone have a working example (not just a link to the docs, please, which I've already read) of a uniqueness validator on an entity/form?
Comment: Are your trying to use the exact same form for both creating and updating?  I think you might want to look at validation groups (http://symfony.com/doc/current/book/validation.html) which allows you to control which constraints are applied for a given use case.
Comment: Also, I followed the instructions here (http://symfony.com/doc/current/reference/constraints/UniqueEntity.html) and same thing: it validates uniqueness, but I get an error when I try to update existing records.
Comment: No, I'm using two different forms. I'll look at validation groups. Thanks.
Comment: Validation groups were the ticket. Thanks.
Answer: Okay, I have it working. The problem I had been having with email uniqueness being "validated" on all user forms, regardless of whether or not I wanted it to be checked there, was something I was able to solve with validation groups. Here's the relevant part of my User entity. Notice the groups={"registration"} part of the @UniqueEntity annotations:
/**
 * VNN\PressboxBundle\Entity\User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity
 * @UniqueEntity(fields="email", message="Sorry, this email address is already in use.", groups={"registration"})
 * @UniqueEntity(fields="username", message="Sorry, this username is already taken.", groups={"registration"})
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $email
     * @Assert\NotBlank()
     * @Assert\Email()
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     */
    private $email;

    /**
     * @var string $username
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="username", type="string", length=255, unique=true)
     */
    private $username;

And my form class (note the last function):
<?php

namespace VNN\PressboxBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UserType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('first_name')
            ->add('last_name')
            ->add('email')
            ->add('username')
            ->add('password', 'password')
            ->add('athletic_director_email')
            ->add('school')
            ->add('active', 'hidden')
            ->add('transition_key', 'hidden')
        ;
    }

    public function getName()
    {
        return 'vnn_pressboxbundle_usertype';
    }

    // The following function is what's important here.
    // This tells this form to use the "registration" validation group.
    public function getDefaultOptions(array $options)
    {
        return array(
            'validation_groups' => array('registration')
        );
    }
}

And I believe that's it. I don't think I had to do anything special anywhere else.
Comment: The only additional thing you might need to consider is the case where a user wants to change their email.
Comment: This only works when you do a persist + flush and catch the DoctrineException, the $form->handleRequest() can return isValid() as true even if the username of the user already exists in the database.
Answer: You can hardcode it, like
$form->handleRequest($request);

if ($form->isSubmitted()) {
    if ($existingUser = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(['email' => trim($form->getData()->getEmail())])) {
          $form->get('email')->addError(new FormError('Email already used'));
     }
}

Answer: If you are using Doctrine, could tou try to set the unique flag in the Entity directly?
/**
 * @ORM\Column(type="string", unique="true")
 */
protected $email;

Comment: this flag is only for the database. it creates a unique key but no validation. if you save an entry you will get the following error:
Integrity constraint violation: 1062 Duplicate entry

Unique validator in Symfony2


Garageband with UVI Grand Piano

Question: I'm trying to play a software instrument track on GarageBand and I want to use the excellent UVI Grand Piano for that. The problem is I could not get GaragaBand to recognize it as an external instrument, and there doesn't seem to be any helpful information online.
How can I connect these two? Am I missing anything or is there some intermediary software required?
Comment: What is a Daw?.
Comment: Does any Daw see it?
Comment: [Digital Audio Workstation](https://www.musicmatter.co.uk/buying-guides/daw-software)
Comment: Garageband on Mac supports VST and AU plug-ins as does the UVI Grand Piano collection. Try this video for clues to making the UVI piano set visible in the Garageband interface: https://www.youtube.com/watch?v=Hv2fOlHhmQk Let us know if this works for you.
Answer: GarageBand is very limited, and should only be used either because you don't have money, don't have a computer, or don't want to pursue music production.
EDIT:
What I am saying is that GarageBand is probably just not capable of recognizing all external instruments. You will probably have to invest in a better DAW, or find a free one that works.
P.S.: Don't use soundflower, use iShowU Audio Capture. soundflower doesn't work anymore.
Comment: Ethan, that's ok. To make this a good answer, consider suggesting an alternative to GarageBand that works with UVI GP, and is in a similar budget range with GB.
Comment: I don't want to pursue music production. I just want to enjoy what I'm doing. And unfortunately, this does not address the question.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://music.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://music.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/35647)
Comment: @edgerunner. Sorry, I got distracted. I was meaning to write a longer answer and accidentally posted this before I was finished writing it. I have edited it for clarification.
Comment: @Richard. Sorry about that. I edited it to provide an answer.
Comment: @EthanCannoy, there's a reason why I don't think this answers the question. Whether or not GarageBand is limited or incapable of recognizing *all* external instruments isn't being asked. The question is much more specific: can GarageBand recognize the UVI Grand Piano? It's possible for the answer to be "yes" *and* for GarageBand simultaneously to be limited in the ways you say. So your statements about GarageBand in general don't shed any light on the specific question being asked. You've said edgerunner "probably" needs a better DAW, which suggests uncertainty regarding this specific issue.
Comment: @jdjazz, sorry if I'm "necro-ing" this. I whole-heartedly agree with you. I am sure it is _possible_ to use GarageBand with a UVI Grand Piano. But it may be _improbable_. My answer was simply suggesting to get a better DAW than GarageBand. For instance, Logic Pro, FL Studio, or Audacity.

Garageband with UVI Grand Piano


Only show comments in view where the comment author has a specific role

Question: I am trying to make a Drupal View which only shows the comments of users with a certain role. For example I have a node with content_author who has Role Y. The same user (with Role Y) placed a comment, another user with Role X posted a comment too.
I want to have a view which only displays comments from users with Role X. This does not depend on the user who is logged in, so I cannot use a contextual filter I suppose.
Did anyone manage to do something like this?
Answer: I figured out how to do it.

Create a view displaying items of type Node.
Create a relationship Comment:User
Create a filter User: Roles and require Relationship with User (which was created in 2.
Specify the roles

You can style the view (and add fields) as you like.