Silhouette coefficients after deleting some data and re-clustering

Question: I was working on a dataset today on which I used K-means clustering algorithm and then calculated the Silhouette coefficients for each point. I then removed 5% of the data with worst silhouette coefficients and re-clustered again. The average silhouette coefficient for each cluster got worse after re-clustering and removal of those outliers (I expected opposite). Am I getting the right answer or have I made a blatant mistake? The results I got don't seem intuitive to me.
Comment: it's hard to say on a single instance because if you remove observations, even if you fix the seeds, the kmeans solution will not be the same. If you repeat the experiment 100 times (each time with a different seed), do you still get that the second clustering is worst?
Comment: Be careful of overfitting when using the same measure to evaluate and modify your result. It's data dredging / data snooping and not sound. Even worse, when you are using heuristics such as SSQ (k-means) and Silhouette.
Answer: That's a good question. The value of Silhouette index for an object shows how strongly is justified the decision to assign the object to its actual cluster over the decision to assign it to another cluster, closest to it. Value tending to 1 tells of hight justifiedness (well clustered object). Negative value tells that the object should better belong to that another cluster. Value close to zero is characteristic of a "borderline", between the two clusters, object.
In real data even optimal clusterization will leave some objects to be with low positive value because neighbour clusters usually "touch" each other by their borders. Unless the value isn't negative there is no reason to reassign the object (though you may do it, and sometimes it will enhance clusters). Nor there is reason to delete objects with low positive values. Deleting borderline objects may not help: re-clustering after the deletion will redefine clusters and make other points borderline in place of the deleted ones, so you are not guaranteed to better the overall cluster solution. In addition, deleting is a gross intervention in real data, and you must have strong reason to treat intermediate points like outliers.
Also, you should take into consideration that original Silhouette index which you probably use (Kaufman, L., Rousseeuw, P. Finding groups in data: an introduction to cluster analysis. New York, 1990) is based on averaged pairwise distances, whereas K-means clustering tries to minimize deviations from cluster centre. Thus, that index is not very good a judge for K-means. One should re-define terms of the Silhouette index formula to be about deviations from centres - then the index is more appropriate for K-means (if you use SPSS you may find a program to compute such modified Silhouette on my web-page).
Dependency of K-means on the choice of initial cluster centres should also be remembered here, as @user603 points in their comment.


Drupal 8: make Taxonomy terms translatable

Question: How to translate Taxonomy terms?
I have 2 languages in my site added here: /admin/config/regional/language
I have turned the Types here /admin/structure/types marked "Show language selector on create and edit pages" in "Language settings" of each type.
But I cannot really understand what to do in Vocabulary settings?
I have terms but I cannot see button "Translate" that it was in Drupal 7.
Should I create 2 languages terms separately one from another?
Please give me manual.
Comment: Have you activated Content Translation module ?
Comment: no. I had not activated it before your advice. I activated and after settings on admin/config/regional/content-language I have "Translations" button in every term. Thank you!
Answer: To translate terms of taxonomies, you need to activate the Content Translation module.


iOS 15 Safari CSS

Question: I have the iOS 15 beta installed and looking at my website on the new Safari update, I see that the top header is showing a grey header instead of being transparent to flow under the notch etc.
The whole site is plain white and black text, so I'd like the status bar to be transparent and black text so the site blends in perfectly.
I have tried:
<meta name="apple-mobile-web-app-status-bar-style" content="default" /> as well as
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
Also used:
<meta name="theme-color" content="#ffffff">
None of that seem to make a difference, I checked other websites where the header color is pretty much merging with the header, if you check:
cnn.com or hillarys.co.uk you will see that the header affects the color of the Safari's nav bar on iPad, on iPhone it will just take over the notch area so it becomes the header. For me, no matter what I do, I cannot get that white header/notch to blend in with my white site.
Hopefully it makes sense and thanks in advance.
Answer: If your phone is in Light Appearance mode (Settings -> Display & Brightness), it seems that there is a max darkness that you can set with <meta name="theme-color" content="foo">. For example:

<meta name="theme-color" content="blue"> affects the header in both light and dark mode.
<meta name="theme-color" content="black"> affects the header in both light and dark mode.
<meta name="theme-color" content="#ffffff"> affects the header only in light mode.

iOS 15 Safari CSS


Dynamic Table with custom validation

Question: First, I show you want I want to do.
I need something like form with a lot of lists. One list is the structure row1, row2, ... with the "+" button.
Every item from list (row1, row2) has setRequired(true) but I want enable validation only after save click. I suppouse that icon "+"  is AjaxButton wich adds another row but not validate previous rows.
How to achieve this?
Answer: You can define whether a Button validates a form or not by using setDefaultFormProcessing setting it to true will have the button validate the form while setting it to false will hav the button skip validation.
See the JavaDoc for Button for more information.

Dynamic Table with custom validation


Últimas postagens blog wordpress em outro site em PHP

Question: Estou precisando colocar em uma landingpage que ta em HTML os últimos posts de um blog que está em Wordpress, consegui um código na internet que tras os posts mais não consigo definir quantos posts vão aparecer e nem pegar a imagem do post. Alguém consegue me ajudar?
Se tiver algum outro código que faça isso também.
Obrigado.
<?php
            $url = 'http://blog.empresa.com.br/category/empresa/feed/';
            $xml = simplexml_load_file($url);
            $item = '1';

            if($xml !== false){
            echo '
';
            foreach($xml->channel->item as $node){
            printf('
%s
', $node->link, $node->title);
            printf($node->description);
            }
            echo '
';
}?>

Comment: nesse exemplo você esta carregando o feed gerado pelo worpress, uma opção é configurar isso no wordpress. Outra opção é manipular melhor esse xml pra controlar nesse loop a quantidade.
Answer: Como mencionei, há varias formas de resolver isso usando PHP
Ou mesmo usando componentes prontos para wordpres ou outros CMS's
Como não foi especificado se o site destino foi construído usando usando algum CMS, segue um exemplo usando DOMDocument no PHP
<?php
    $rss = new DOMDocument();
    $rss->load('http://blog.empresa.com.br/category/empresa/feed/');
    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array (
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
            'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
            );
        array_push($feed, $item);
    }
    $limit = 5; //Quantidade que deseja exibir
    for($x=0;$x<$limit;$x++) {
        $title = str_replace(' & ', ' & ', $feed[$x]['title']);
        $link = $feed[$x]['link'];
        $description = $feed[$x]['desc'];
        $date = date('l F d, Y', strtotime($feed[$x]['date']));
        echo '
'.$title.'
';
        echo 'Postado em '.$date.'
';
        echo '
'.$description.'
';
    }
?>

Comment: a LandingPage não está utilizando nenhum CMS, apenas HTML e CSS, coloquei o PHP que postei apenas pra puxar os últimos posts do blog que está em wordpress
Comment: caso você queira exibir sem a necessidade do PHP, é possível fazer isso usando apenas JS tbm https://gist.github.com/juanbrujo/3a71489572e5677fcec7e14676aa66e2
Comment: conseguei com esse código php que vc postou acima, só fiz alguamas alterações para limitar o número de caracteres da descrição, por exemplo. Obrigado.


Data Matrices Definiteness In Semidefinite Programming

Question: I'm little bit confused about the data matrices associated with an SDP program. Consider the following SDP program:

I know that the Matrix $X$ must be positive semidefinite i.e. $X \succeq 0$ as the last constraint implies. My question is about the data matrices $C$ and $A_i \forall i \in \{1, \cdots, m\}$. Do they have to be positive semidefinite ? In other words, can we have a matrix $C$ for example  that is either negative definite or indefinite ?
Comment: Yes, positive semidefiniteness is only enforced on $X$, not $C$
Comment: Due to the symmetry of $X$ one can always make $C$ and $A$ symmetric.
Comment: @user1936752 thank you for your answer. Do they have to be symmetrical (matrices $C$ and $A$)?
Answer: We do not need $C$ to be positive semidefinite.  It is an extension of linear programming.
$C\cdot X=\sum_{i=1}^n \sum_{j=1}^n C_{ij}X_{ij}$
Note that due to $X$ is symmetric we have $$C_{ij}X_{ij}+C_{ji}X_{ji}=(C_{ij}+C_{ji})X_{ij},$$
we can obtain the same expression using symmetric matrix by using $\frac12(C+C^T)$ instead. Hence, usually for simplicity, we just states that we want $C$ and $A_i$ to be symmetric.


Counting ways for $12$ card-hands to contain $4$ cards in each of three suits

Question: In a card deck of $52$, I want to count the ways for $12$ card-hands to contain 4 cards in each of three suits.
I thought that it'd be:
The ways of picking first suit $\to 4$
The ways of having 4 cards with this suit $\to \binom{12}4$
The ways of picking first suit $\to 3$
The ways of having 4 cards with this suit  $\to \binom{12}4$
The ways of picking first suit $\to 2$
The ways of having 4 cards with this suit $\to \binom{12}4$
So total ways is: $4\cdot 3\cdot 2 \cdot \binom{13}4 ^3$.
My notes say this is incorrect but do not say why.
Answer: You should divide your result by $3!$ otherwise you count each acceptable hand more than one time. The total number of ways is
$$\binom{4}{3} \binom{13}4 ^3=4\binom{13}4^3.$$
Comment: @Natash1 No because we have to distinguish the set of $7$ cards from the set of $6$ cards (their cardinalities are different).
Comment: @Natash1 Any further doubt?
Comment: Is it because doing $4\times 3\times 2$ means I "arrange" the suits?
Comment: Yes, basically you choose the set of suits in $\binom{4}{3}=4$ ways (or you exclude one of the 4 suits),
Comment: I see. There was another problem that was: "how many consist of seven cards in one suit,a nd six in another, in a 13 card hand"?
The solution was $4\times 3\times \binom{13}{7}\times\binom{13}{6}$.
Shouldn't I also divide by $2!$ here?
Comment: No I think I understand now: highly appreciate it.


error on line 1 at column 6: XML declaration allowed only at the start of the document

Question: I was trying to build an XML file. But stuck with an error. I am including the code and error. Thanks in advance.
    <?php
    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("comrade") or die(mysql_error());
    $data = mysql_query("SELECT * FROM support WHERE DATE(`date`) = CURDATE()")
    or die(mysql_error());
    $xml = new SimpleXMLElement('<xml/>');
    while($info = mysql_fetch_array( $data ))
     {
      $support = $xml->addChild('support');
      $support->addChild('cus_name',$info['com_name']);
      $support->addChild('ser_type',$info['ser_type']);
     }

     Header('Content-type: text/xml');
     print($xml->asXML());
     ?>

It showing the following error
     Below is a rendering of the page up to the first error.

Comment: Remove the spaces in the beginning of the file. `<?php` must start on the first position
Comment: PHP starts with `<?php` and not just `?php`
Comment: @MonkeyZeus it happened when I pasted the code here. The syntax is correct in the php file. Still it remain unsolved. :(
Comment: Did you try @AleksG comment?
Comment: Yes, I do. There is no spaces in the beginning of the file
Comment: i tried your code, you have a space before <?php please remove that. oops am late, @AleksG is right.
Answer: In short, you should do:
ob_clean(); //Clean (erase) the output buffer
print($xml->asXML());

explain: if any of the included files print a new line you will get

error on line 2 at column 6: XML declaration allowed only at the start
  of the document

it could be because in some file the <?php tag start after an empty line.
so instead of searching the file that cause the error, simply clean the output buffer.
Comment: After tens of hours looking for an empty line and not finding it, I have to say that this solution temporarily saves my life!
Comment: Basically, perform a ob_clean() before any output of any kind (json, xml, html ...) in order to prevent headers problems.
Answer: Your issue is the placement of Header('Content-type: text/xml');
Try this and make sure NOTHING comes before the header() call:
<?php
header('Content-type: text/xml');

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("comrade") or die(mysql_error());
$data = mysql_query("SELECT * FROM support WHERE DATE(`date`) = CURDATE()")
or die(mysql_error());

$xml = new SimpleXMLElement('<xml/>');
while($info = mysql_fetch_array( $data ))
{
    $support = $xml->addChild('support');
    $support->addChild('cus_name',$info['com_name']);
    $support->addChild('ser_type',$info['ser_type']);
}

print($xml->asXML());
?>

Answer: Sometimes saving UTF-8 with/without BOM could solve this (and similar) issues. Some special byte could exist in the very beginning of file in case of wrong saving method.


Intersections of saturated locally free sheaves

Question: I've been thinking about vector bundles recently and came up against the following problem. I'm hoping someone can help me with the intution here.
Background: In this question, we're working over a base scheme (or variety, if you like) $X$. All sheaves I work with are sheaves of $\mathcal O_X$-modules.
Let $\cal E$ and $\cal E'$ be locally free sheaves on $\mathcal O_X$ and suppose that $\cal E'\subseteq\cal E$. Say that $\mathcal E'$ is a saturated subsheaf of $\mathcal E$ if the quotient sheaf $\mathcal E/\mathcal E'$ is again a locally free sheaf.

Question: If the locally free sheaves $\mathcal E'$ and $\mathcal E''$ are saturated subsheaves of the locally free sheaf $\mathcal E$, then is their intersection $\mathcal E'\cap\mathcal E''\subseteq\mathcal E$ locally free? Assuming $\mathcal E'\cap\mathcal E''$ is locally free, is it a saturated subsheaf of $\mathcal E$?
(For both questions, give either a proof or counterexample.)

Thoughts:
By taking stalks, you can reduce this question to a problem in commutative algebra. Here $X$ would be a local ring and the locally free sheaves would just be free modules. This reduction might help in the proof, but it hasn't given me much intuition.
If $X$ is a point or a curve then any subsheaf of a locally free sheaf is locally free, meaning that if the first assertion fails, it can only fail in dimension $>2$. This obstruction has made it hard for me to think of examples.
It's tempting to come up with examples just by intersecting the total spaces of the sheaves; then we would be in the situation of this Math Overflow question. Unfortunately, intersection does not commute with formation of the total space of a vector bundle, so I don't know how to use geometric intuition about vector bundles for this problem.
Terminological Warning: Mohan pointed out that my usage of the word "saturated" is nonstandard: the usual definition states that a subsheaf is saturated if its cokernel is torsion-free, which is weaker than locally free. However, I'm not going to go back through my question and replace all instances of "saturated".
Sasha proposed that we say $\mathcal E'\to\mathcal E$ is a fiberwise monomorphism if its cokernel is locally free. This terminology makes sense, and I should have used it instead of "saturated".
Comment: There is already a notion of saturated, where the quotient is only assumed to be torsion-free, not locally free, so may be you should use another word.
Comment: Ah, I see; thank you for the terminological clarification.
Comment: I would say $\mathcal{E}' \to \mathcal{E}$ is a fiberwise monomorphism.
Answer: Under your assumptions the sheaf $\mathcal{E}' \cap \mathcal{E}''$ is necessarily reflexive, bot not necessarily locally free, as the next example shows.
Let $X = \mathbb{P}^3$, $\mathcal{E} = \mathcal{O}^{\oplus 4}$, with
$$
\mathcal{E}' = \Omega^1(1) := \mathrm{Ker}(\mathcal{O}^{\oplus 4} \stackrel{(x_0,x_1,x_2,x_3)}\longrightarrow \mathcal{O}(1)),
$$
and
$$
\mathcal{E}'' = \mathcal{O}^{\oplus 3} := \mathrm{Ker}(\mathcal{O}^{\oplus 4} \stackrel{(1,0,0,0)}\longrightarrow \mathcal{O}(1)).
$$
Then
$$
\mathcal{E}' \cap \mathcal{E}'' \cong
\mathrm{Ker}(\mathcal{O}^{\oplus 3} \stackrel{(x_1,x_2,x_3)}\longrightarrow \mathcal{O}(1)),
$$
which is a standard example of a reflexive, but not locally free sheaf.


Is there another way to refactor after adding new column: Sinatra Web App

Question: I am still new to using the Sinatra Framework. I was asked to add a new column :description, and to refactor this current line of code in my  POST request for editing a new list to include the :description column:           @list.update(params.select{|k|k== "name"})
I am unsure of not only refactoring it to include the :description but to make it shorter.
Here is the full POST request block
post "/lists/:id" do
  redirect_if_not_logged_in
  @list = List.find(params[:id])
  unless List.valid_params?(params)
    redirect "/email@example.com}/edit?error=invalid list"
  end
  @list.update(params.select{|k|k== "name"})
  redirect "/firstname.lastname@example.com}"
end

I did add the new column without issue and have an idea of what to put in my Edit & New forms, the controller action is where I am stuck.
Comment: I'm a little hazy on the aim. Do you mean you want to update 2 fields, `name` and `description` when posting to this route?
Comment: Hi iain! Yes, sorry. I tend to make things sound and be more complicated than they need to be. After much screen-staring, and help from a friend, I realized I just need to change my current line to @list.update(params). I ended up refactoring the whole Post request to be less complicated and much shorter.
Comment: I thought so but I didn't want to provide an answer in case it caused more problems, I shall be more bold in future! *Do* make sure to check that params hash before passing it on. [There are a few here](https://rubygems.org/search?utf8=%E2%9C%93&query=sinatra+parameter) (there's even one by me:)
Answer: Update:
I found the answer to my own question.
I refactored my original post request to reflect this change:
post "/lists/:id" do
   @list = List.find(params[:id])
if @list.update(params)
  redirect "/firstname.lastname@example.com}"
else
  redirect "/lists/edit"

end
  end


Rudin 3.6 - convergence of subsequences in compact metric spaces.

Question: I'm reading through Baby Rudin and I'm slightly confused about Theorem 3.6 (a).
The theorem is as follows:
$\textbf{ If $\{ p_n\}$ is a sequence in a compact metric space $X$,}$$\textbf{ then some subsequence of $\{ p_n\}$ converges to a point of $X$}$.
The main point of confusion for me is I'm not seeing how this is different than Theorem 2.37, stated in the previous chapter, which reads as follows:
$\textbf{If $E$ is an infinite subset of a compact set $K$, then $E$ has a limit point in $K$. }$
My thinking on it is that any subsequence in a compact metric space, or a compact set (which I believe may be regarded as the same), is by definition an infinite subset of a compact metric space. Indeed, even in the proof of Theorem 3.6 (a), where Rudin considers the case that the range of $\{ p_n\}$ is infinite, he refers back to Theorem 2.37.
However, I feel as if I'm missing something because if I've learned anything, is that Rudin is not one to write anything superfluous, so if it was the same, it certainly wouldn't be restated.
But ya, why is it even necessary to consider the separate cases of the range of $\{ p_n\}$ being finite and infinite, and what exactly is the difference between these two statements?
Thank you in advance for any help.
Comment: Limit point of set and subsequential limit of a sequence is not the same concept. Consider a constant sequence. Its range is a singleton, hence has no limit point. But the sequence converges, and in particular a subsequence converges to the limit. Also, a set may be uncountable, in which case the set cannot be written as a range of some sequence.
Comment: Ohh ok! I understand your first point. However for the 2nd, wouldn't any compact set by definition be countable, as there is some finite open covering which contains it? So a limit point of the set should be able to be written as a range of some sequence no?
Comment: No. 'Finite subcovering' means there are finite sets $U_1, U_2, \cdots, U_n$ that covers whole space, but each $U_i$ may be uncountable(which is the case for classic examples such as closed interval $[a, b]$).
Comment: Sorry, just to clarify, I understand each U_i may be uncountable, but my point is simply that we can extract a countable subset from each U_i to construct a sequence that converges. So for [0,1], whatever the open cover may be, I can describe any limit point, say 0 for example, by taking the countable subset {1/n: n in Naturals}. So theoretically, any limit point in a compact set can be written as a countable subsequence. In that sense they are equivalent. Maybe I'm, misunderstanding the point about why the compact set being uncountable matters for describing limit points.
Comment: Yes. To prove their equivalence you can argue like that. But I am just pointing out that they are not `immediately' equivalent. Your argument can be used to prove Theorem 3.6(a) using Theorem 2.37.
Answer: Let's consider the case when $\{p_n\}$ is infinite, and let's call this set $E$. If this subset has a limit point in $K$, it means there is a point $y \in K$ and  a sequence of points $p_{i_1}, p_{i_2},p_{i_3},\cdots$ converging to $y$. However, this sequence may not be a subsequence of $\{p_n\}$ because we cannot assume that the indices are increasing, i.e. $i_1 < i_2 < i_3 < \cdots$. This explains the difference: Theorem 2.37 says that you can find some sequence in $E$ that converges, but a sequence in $E$ is not the same thing as a subsequence of $\{p_n\}$ due to the order of the indices.
Comment: Ahh I see so it's essentially just saying that if there is a limit point we can theoretically customly assign each $p_i$ that meets the criteria of being a lesser distance from the limit point an increasing index, and thus construct a subsequence?
Comment: If the set has a limit point, the sequence of points in $E$ you construct to reach it may have no relationship to the original order of $\{p_n\}$, and so won't give you a subsequence thereof. You need to use a different approach when trying to obtain a subsequence.


shouldoverrideurlloading not called Webview Android

Question: First of all , this post may ,look like a Possible Duplicate of other question, but I have go through many questions but found them not helpful.
Now My problem is that I am loading an URL in my Webview and then I want to Trace URL on each event on webview so I have set up WebviewClient for Webview and overridden shouldoverrideurlloading method, but after first Event , shouldoverrideurlloading not getting called. (worked first time)
Here is the Code I have used :
<code>    wvSecurity = (WebView) findViewById(R.id.wvSecurity);
    wvSecurity.getSettings().setJavaScriptEnabled(true);
    wvSecurity.getSettings().setAllowContentAccess(true);
    wvSecurity.getSettings().setAllowUniversalAccessFromFileURLs(true);
    wvSecurity.getSettings().setBuiltInZoomControls(false);
    wvSecurity.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    wvSecurity.getSettings().setLoadWithOverviewMode(true);
    wvSecurity.getSettings().setDomStorageEnabled(true);

    wvSecurity.loadUrl("URL");

    wvSecurity.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view,
                        final String urlStr) {
                    Log.i("URL", "::" + urlStr);
                    return false;
                }
    }
</code>
EDIT ::
Ok, The URL which I want to Trace uses POST method , Now my question is How can I trace POST URL and its data. And one thing , I dont have access to Webpage coming in so I simply cant go for GET method. Please Help !!!
Comment: Is there any to Catch the Post Url ? @RGraham
Comment: have you try after returning `true` from `shouldOverrideUrlLoading` ?
Comment: Yeah , I tried that did nothing
Comment: I have tried from 8-21 Every API
Comment: @GOLDEE Sorry, misred the docs for that last comment. What kind of request are you making? GET or POST or other? Also, can you put all this info in the question so we don't pollute the comments?
Comment: Actually I dont know much about the Request type @RGraham as this is a Third party Webpage
Comment: @ρяσѕρєяK I have tried that too
Comment: `shouldOverrideUrlLoading` is not called with POST requests - switch on remote debugging & use Chrome to inspect the Network tab to see what requests are going on.
Comment: ohk I will try this , but I dont have much knowledge of Remote Debugging @RGraham
Comment: Did you ever find an answer to this?
Answer: I guess this method gets called when a hyperlink is tapped from page or some redirection happens. So make sure this thing.
Answer: I think you need to pass the url in place on "URL" so this will solve your problem.
<code>        wvSecurity = (WebView) findViewById(R.id.wvSecurity);
        wvSecurity.getSettings().setJavaScriptEnabled(true);
        wvSecurity.getSettings().setAllowContentAccess(true);
        wvSecurity.getSettings().setAllowUniversalAccessFromFileURLs(true);
        wvSecurity.getSettings().setBuiltInZoomControls(false);
        wvSecurity.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wvSecurity.getSettings().setLoadWithOverviewMode(true);
        wvSecurity.getSettings().setDomStorageEnabled(true);
        wvSecurity.loadUrl("http://www.google.com");
        wvSecurity.setWebViewClient(new HelloWebViewClient());

    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("URL :: " + url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, final String url) {
        }
    }
</code>
Comment: Please don't call loadUrl on the url you get from `shouldOverrideUrlLoading` as that callback is also called for subframes with non-https schemes. If you go to a a page like http://jsbin.com/gupug/1/quiet your code will end up calling view.loadUrl('tel:1234') and you will end up showing an error page, since the webview doesn't know how to load a tel: URL.
Instead of calling loadUrl(url) and returning true you should just return false from shouldOverrideUrlLoading.


Query and import range only returning header row

Question: I'm trying to import a selection of columns if the text in a row is "Week 2." I'm having the issue that the query is only returning the header row. The formula I'm using is this:
=query(importrange("https://docs.google.com/spreadsheets/d/1Eu5dJ5dOgFsG7jeIB1umoDOamt5r3BzYYoTWA1Rxyh0/edit#gid=0", "Sheet1!A:Z"),"select Col5,Col7,Col8 where Col6='Week 2'",1)
I have some test sheets here:
Original where I'm importing info from: https://docs.google.com/spreadsheets/d/1Eu5dJ5dOgFsG7jeIB1umoDOamt5r3BzYYoTWA1Rxyh0/edit#gid=0
Final destination (formula in A2): https://docs.google.com/spreadsheets/d/19IC36izklxgId5zjtzr9HP71JYTrt_ReHBgxbAwBEpg/edit#gid=0
Comment: I'm open to using a filter formula or anything else. I just couldn't get that to work either.
Answer: Your query is fine, but you have the wrong column no.
<code>=query(importrange("https://docs.google.com/spreadsheets/d/1Eu5dJ5dOgFsG7jeIB1umoDOamt5r3BzYYoTWA1Rxyh0/edit#gid=0", "Sheet1!A:Z"),"select Col5,Col7,Col8 where Col6='Week 2'",1)
</code>
should be
<code>=query(importrange("https://docs.google.com/spreadsheets/d/1Eu5dJ5dOgFsG7jeIB1umoDOamt5r3BzYYoTWA1Rxyh0/edit#gid=0", "Sheet1!A:Z"),"select Col5,Col7,Col8 where Col5='Week 2'",1)
</code>
Comment: Check this reply if not already solved. I tested and seemed to work ok...


PHP - file handle instead of path

Question: I have a 3rd party function that receives a file path only.
I have no file path but I have a file handle.
Is it possible to pass the handle in such a way it would be treated as path?
In particular:
I am using PHPMailer library for sending emails.
I want to attach files to emails and using <code>$mail->addAttachment()</code> which accepts file paths only.
The files I am going to send are generated on the fly.
I would like to generate such a file and pass it to this function without being actually created on the server. There are to many files and it becomes problematically to clean the trails.
Thoughts?
Answer: You can use the addStringAttachment() method:
<code>$mail->addStringAttachment($fileContent,$fileNameToDisplay,$encoding,$type).
</code>

PHP - file handle instead of path


How to make jquery fadeTo() animate on behind when showing confirm() popup

Question: I wanted to ask how to make fadeout when showing confirm()
When I clicked delete The box will fadeOut to 0.5 opacity slowly, when on confirmation to delete or not to delete.
But the slowly fading not occuring.
Here is the code

$(document).ready(function(){
  $(".animate-fade").click(function(e){
        $("#div1").fadeTo("slow", 0.15);
    e.stopImmediatePropagation();
    });
    $("button").click(function(){
        $("#div1").fadeTo("slow", 0.15);
var answer = confirm('Are you sure you want to delete this?');
    });

});
<!DOCTYPE html>

The box didnt animate the fade effect when confirm() popup shown how to make it animated?

<button>Delete Boxes</button>
  <button class='animate-fade'>Animate fade</button>

Thanks !
Answer: fadeTo() animation is async while  window.confirm is modal, it freezes any running javascript code.  Depending your exact expected behaviour, you should set your confirm box when the animation completes:
$("#div1").fadeTo("slow", 0.15, function() {
   var answer = confirm('Are you sure you want to delete this?');
   /* do whatever with answer variable*/
 });

An other way if you want the effect to be simultanous would be to use CSS transition/animation and just put the confirm() in event queue using a timeout.
Here are an example
Comment: Thx for the second example sir :D
Answer: Use of callback :
$("button").click(function(){

    $("#div1").fadeTo("slow", 0.15,function() {

        var answer = confirm('Are you sure you want to delete this?');
    })
})

Final code :

<!DOCTYPE html>

The box didnt animate the fade effect when confirm() popup shown how to make it animated?

<button>Delete Boxes</button>
  <button class='animate-fade'>Animate fade</button>


Lotka Volterra equations - Proving solutions are positive without solving the system.

Question: So I have a system describing two species:
$$y'_1=a_1y_1\left(1-\frac{y_1}{N_1}\right)-b_1y_1y_2 \\ y'_2=a_2y_2\left(1-\frac{y_2}{N_2}\right)-b_2y_2y_1$$
where $a_i,N_i,b_i>0.$
Carrying out stability analysis is straightforward. But I want to show that the solutionvector $[y_1(t) \ \ \ y_2(t)]$ is always positive if I start with $y_1(0),y_2(0)>0$.
Also, how can I prove that $[y_1(t) \ \ \ y_2(t)]<\infty?$
Comment: Ok, I was thinking of it as a Predator-prey system... Regarding the positivity, I think that solution uniqueness may do the trick. There are solutions "living" in the axis ($y_1=0$ with $y_2$ following a logistic equation and vice versa) so, if you can use uniqueness, a solution starting in the first quadrant that crosses the axis would have to coincide with a solution that never leaves the axis.
Comment: Are you sure about your system? Both "species" decrease after interaction? One of the minus signs after the logistic term should probably be a plus sign.
Comment: This is a competitive system, so I don't think it needs to be a positive sign. Look here https://www.kristakingmath.com/blog/predator-prey-systems.
Comment: Are you referring to the Picard-Lagerlöf theorem? I don't understand your last sentence. Why would it have to coincide with a solution that never leaves the axis?
Comment: And if a solution crosses an axis, its not in the first quadrant so I don't understand.
Comment: I am reasoning by contradiction. Imagine that a solution starts in the first quadrant and at some point reaches the axis. At that point it will cross another solution (one of the form $(y_1,0)$ or $(0,y_2)$, that always exists and can even by explicitly computed). Uniqueness of solution implies those two solution are actually the same, meaning that you must have started on the axis and contradicts the fact that you were starting in the interior of the first quadrant.
Comment: What do you mean by $[y_1(t)\ \ y_2(t)]<\infty$?
Comment: @Parseval Yes I was thinking of Picard's theorem, but sime extra work is needed in order to show that the solution are global in time.
Comment: @PierreCarre - Ok, I'll make an attempt to show this in a edit then maybe you can see if I'm doing it correctly.
Comment: @user539887 - I mean that the solutions can never go off to infinity.
Comment: A hint: compare the $i$-th coordinate, $i = 1, 2$, of a solution of the system with a solution of $y'_i=a_iy_i(1-\frac{y_i}{N_i})$.
Comment: What is "the $i$-th coordinate?" You mean like $(y_1,y_2)$? And in your last part, why have you only chosen $y_1$ and $N_1$?
Comment: The first coordinate of $[y_1\ \ y_2]$ is $y_1$, the second coordinate is $y_2$. I say: compare a function satisfying $y'_1=a_1y_1(1-\frac{y_1}{N_1})-b_1y_1y_2$ with (an appropriately chosen) function satisfying $y'_1=a_1y_1(1-\frac{y_1}{N_1})$ (and similarly for the second coordinate).
Answer: If we search solutions of the form $(y_1, 0)$ or $(0,y_2)$ we see that they are of the form $(y_1^*,0)$ or $(0,y_2^*)$, where $y_i^*$ is a solution of the logistic equation $y_i'=a_i y_i (1- \frac{y_i}{N_i})$. In phase space these solutions are straight lines on the axis, starting at some point in the axis and approaching $(0,0)$, $(0,N_2)$ or $(N_1,0)$. Assuming that the system has one an only one solution for each given initial condition $y_1(0)=u_0>0$, $y_2(0)=v_0>0$, defined for all $t>0$ (this needs to be proven), we can show by contradiction that $(y_1(t),y_2(t))$ will remain in the interior of the first quadrant.
In  fact, if we admit that a solution starting in the interior of the first quadrant  reaches the axis, the uniqueness of solution tells us that this solution must coincide with a solution of the form $(y_1^* ,0)$ or $(0,y_2^*)$, which is obviously a contradiction. Therefore the solution will not reach the axis and both components will remain positive.


stacked bar plot returns errors

Question: using the data below, I would like to create a stacked bar plot as described here. However, I got errors like
Error in `geom_col()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `tapply()`:
! argument "X" is missing, with no default
Run `rlang::last_trace()` to see where the error occurred.

Here is my data:
    graph_data <- structure(list(
  age = structure(c(52, 52, 52, 52, 52, 52), format.stata = "%8.0g"),
  race = structure(c(1L, 1L, 2L, 2L, 3L, 3L), levels = c("0.White", "1.Black", "2.Hispanic"), class = "factor"),
  TLE = structure(c(27.6, 27.6, 29.7, 29.7, 31, 31), label = "r(mean)", format.stata = "%10.0g"),
  var = structure(c(2L, 1L, 2L, 1L, 2L, 1L), levels = c("Unhealthy Life Expectancy", "Healthy Life Expectancy"), class = "factor"),
  value = c(17, 7.3, 17.7, 10.6, 22.3, 13.3),
  label_pos = c(8.5, 20.65, 8.85, 23, 11.15, 28.95),
  label_text = c("17.0", " 7.3", "17.7", "10.6", "22.3", "13.3"),
  tle_pos = c(26.3, 26.3, 30.3, 30.3, 37.6, 37.6),
  tle_label = c("27.6", "27.6", "29.7", "29.7", "31.0", "31.0")
), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))

Comment: It's great that you provided data, but the code would help us too.
Answer: library(tidyverse)

graph_data %>%
ggplot(aes(fill=var, y=value, x=race)) +
    geom_bar(position="stack", stat="identity")

It depends specifically what you want to do, but you can modify the code above and get what you want

stacked bar plot returns errors


Std dev should be less than 0.289 (help in understanding)

Question: In Kruschke's book (Doing Bayesian Analysis), he talks about using mean and standard deviation as one way to establish the beta priors for Binomial Bayesian model. He advises that the std dev should be less than 0.289, "which is the standard deviation of uniform density." That is a = 1, b = 1.
My confusion is that lower std dev indicates tighter distribution. But we should be cautious about being overconfident in the prior.
Can I request help in understanding this? How does larger alpha and beta values change standard deviation?
Thanks!
Comment: $\sqrt{1/12} = 0.28867\ldots\approx 0.289.$
Comment: Please give us direct quote and/or more context.
Comment: Hi Tim, check this link. It's above equation 5.6. https://books.google.com/books?id=ZRMJ-CebFm4C&pg=PA83&dq="0.289"+bayesian+analysis+beta&hl=en&sa=X&ved=0ahUKEwjOmePX5Y3fAhUGP6wKHXaJDpgQ6AEIJjAA#v=onepage&q="0.289"%20bayesian%20analysis%20beta&f=true
Comment: Hi Whuber, Thank you. But I don't think that answered the question. Should we not try to be cautious with our confidence in priors? Doesn't smaller std dev indicate that we have higher confidence in the prior distribution? Thus should we not try to have a wider std dev for the prior distribution?
Answer: The reason you find the behaviour of the beta distribution a bit confusing here is probably that your intuition is based on distributions such as the normal, which are supported on the entire real line. The beta distribution, on the other hand, is bounded on both sides ($0 \leq x \leq 1$), and it is for this reason that the variance (and therefore the standard deviation) has a maximum possible value.
Specifically, the variance of a distribution is the average squared deviation from the mean. For the beta distribution there is an upper limit to how much any value can deviate from the mean (with maximal deviation at $x=0$ or $x=1$), and there is therefore also an upper limit for the variance (and consequently for the standard deviation, which is the square root of the variance).
In the case of the beta (a=1, b=1) distribution, where values are distributed uniformly between 0 and 1 and the mean is 0.5, it turns out that the average squared deviation from the mean is $\frac{1}{12}$. The standard deviation corresponding to this distribution is therefore $\sigma = \sqrt{\frac{1}{12}} \approx 0.289$. Beta distributions with larger parameter values ($a>1,b>1$) will have a single peak between 0 and 1 (specifically the mode is at $\frac{a-1}{a+b-2}$; see example below). Since values in these distributions are more highly concentrated around the mean, the variance and standard deviation will be smaller than for the uniform distribution.

It should be noted that you can actually have beta distributions with standard deviation larger than 0.289: In cases where $a<1, b<1$ the beta distribution will be U-shaped, with values concentrating near 0 and 1 (see example below). The upper limit of the standard deviation is 0.5 (corresponding to an upper limit of 0.25 for the variance), which only occurs approaching the limit at $a = b = 0$. (Intuitively, at the limit, one can think of all values as being evenly distributed between 0 and 1, meaning they all have a deviation of 0.5 from the mean, and therefore an average squared deviation of 0.25).

Coming back to the specific Bayesian modeling context, where you want to use a beta distribution as a prior on some parameter: Here you can in principle directly specify the a and b parameters according to your prior beliefs, but it might be more intuitive to instead specify the expected mean and standard deviation of the prior distribution. Based on these you can then compute the corresponding values for a and b using Kruschke's equations 5.6 in the book also linked above. If you think the parameter you are modeling has a value somewhere between 0 and 1, then a unimodal prior with $a>1, b>1$ is a reasonable choice, and here the standard deviation will always be less than 0.289. If you think the parameter is either close to 0 or to 1, but you don't know which, then a bimodal prior with $a<1, b<1$ could be a good description, and here you will have $0.289 \leq \sigma \leq 0.5$. If you use Krusckhe's equation and try to enter $m = 0.5$ and  $s > 0.5$ you will get negative (impossible) values for a and b. If you keep the standard deviation below 0.289 (as suggested by Kruschke) then you can choose any value in $[0,1]$ for m and get valid values for a and b. If you set the standard deviation to be between 0.289 and 0.5 then only some values of m are possible (you can only achieve high standard deviation if the mean is near the middle of the interval).
Comment: +1 Thank you for this thoughtful discussion of an unanswered question.
Comment: Thank you, Anders. Lot to digest. I appreciate you taking time to detail the answer.


Diferença entre DTO e ViewModel?

Question: Nessa pergunta podemos vero que é ViewModel: Pra que serve uma ViewModel no ASP.NET MVC?
Nessa outra pergunta podemos ver o que é DTO: O que é um DTO?
Mas afinal de contas:

Qual a diferença entre DTO e ViewModel?
Quando devemos usar um ou outro ou até mesmo os dois?

E ainda tem essa aqui Utilização de DTO e ViewModel em projeto ASP.Net MVC que eu acredito não ser duplicada
Comment: Boa +1, eu andei pesquisando sobre, mas pra mim não fez muito sentido quando utilizar um e outro, vou aguardar uma resposta aqui!
Comment: Eu já havia pesquisado há um tempo, mas também não havia entendido. Normalmente uso ViewModel em Web e DTO em apis. mas porque apreendi assim, sem um porquê(o que é péssimo)
Answer: Lá na pergunta sobre DTO já tem uma boa resposta sobre o que ele é, exceto pelo fato de falar em campos como se fossem atributos, mas é um erro que 99,99% das pessoas cometem mesmo :).
Vamos esquecer um pouco, e só por um momento inicial, a terminologia usada no MVC para não confundir. Vamos usar a terminologia do banco de dados que é mais comum as pessoas entenderem.
O DTO é uma forma de organizar informações na aplicação que vem de alguma(s) fonte(s), geralmente um banco de dados, mas pode ser outro mecanismo. Podemos entender o DTO como uma view que você já deve conhecer do banco de dados. Não que seja exatamente isto, mas só para entender. O DTO pega dados da fonte de dados e monta um objeto fácil de usar usado pela aplicação. Em geral o DTO faz um mapeamento simples e não tem comportamento. Ele tem relação direta com a fonte de dados, e pode ser usado em diversas partes da aplicação apenas para consumo.
Geralmente quando este tipo de objeto tem comportamento ele passa ser um padrão chamado de Active Record. Em alguns casos usa-se o Domain Object ou outra terminologia com pequenas sutis diferenças.
O DTO pega os dados de uma fonte, provavelmente uma tabela de um banco de dados, e monta um objeto simples. O AR permite ter uma lógica de como a transferência será feita, e até mesmo lógica de negócios nela, ainda que alguns autores indicam que aí já seja outra coisa.
O DTO é um mecanismo que pode ser usado como parte do modelo do model do MVC, mas geralmente é o AR que é usado.
Não gosto da pergunta sobre DTO e view model, acho que está confuso, provavelmente errado e segue uma linha específica de desenvolvimento que eu não gosto. Vou ignorá-la.
Continuando na analogia com banco de dados o view model, é como se fosse uma view de um banco de dados que você já conhece, porém apenas dentro da sua aplicação. Ele é um modelo para a view do MVC. Ele não é um modelo para a base de dados. Claro que ele terá que se comunicar com o modelo da base de dados para pegar dados, mas o consumo é da view do MVC.
Há muitos casos simples que usar um objeto via DTO, AR, DO, ou o que seja adequado e simples, há uma relação fácil entre esse objeto e o que vai usar na view do MVC. Mas há casos que não é tão simples, você precisa de objeto que será consumido pela view que é mais complexo que é composto por um subconjunto de campos desses objetos que se ligam à base de dados, ou de campos criados só nesses objetos porque a base de dados ou objetos da aplicação não os provê, ou ainda precisa de dados que estão em diversos objetos e fica complicado usá-los separadamente, então compila-se (no sentido de juntar, não de analisar um código fonte :) ) tudo isto em um objeto que se encaixe na demanda da view do MVC. Ou seja o view model mapeia para a view do MVC, enquanto que o model mapeia com a base de dados.
Então o view model é como se fosse um SELECT pré-estabelecido que gera um objeto pronto e fácil de usar na view.
Não há qualquer relação entre os dois. Achar que o DTO é um mecanismo do view model, na minha concepção, é errado, mas é possível fazer essa analogia como um DTO entre o modelo do MVC e a visão do MVC.
Se não tem uma view na jogada, não tem porque usar um view model. E view pode ser de um padrão de projeto conhecido como o MVC, MVP, ou MVVM, e provavelmente em RUI (que eu ainda estou estudando, e parece bom), mas podem ser views fora desses padrões conhecidos, tem gente que usa um M(odel)V(iew) e um model view pode ser útil mesmo em casos assim.
DTO é um mecanismo primitivo. Sozinho, em sua essência, ele é útil em aplicações simples e diretas. É quase impossível ter uma aplicação com base de dados que não tenha alguma forma de DTO ou suas derivação, geralmente um AR, mesmo que não pareça, já que há linguagens e frameworks que abstraem isso para você. O viewmodel não é necessário a não ser que o mecanismo que se comunica com a view exija, o que é comum nos frameworks MVC por aí, mas é mais por deficiência deles.
Pra fica claro, o model do MVC é sempre uma forma, quase sempre mais sofisticada, de DTO, em geral até mais sofisticada do que um AR. Muitas vezes o model é representado por um repositório, que é cheio de ARs e outros mecanismos.
Coloquei no GitHub para referência futura.
Comment: Não sei dizer com propriedade, eu acho que não, pelo que eu entendo, e se estamos falando da mesma coisa, é tranquilo, desde que o objweto resultado deste DTO seja simples, ou seja, voc|ê quer o nome do cliente, mas ele não está na tabela base para o DTO que só tem um ID do cliente, acho ok pegar o nome lá ter no objeto diretamente, porque toda aplicação vai precisa disto, o que é diferente de uma *view* específica precisar dele. Mas não tenho certeza, posso pesquisar. Porque o que eu acho certo é fazer o que precisa, que nome vai dar é secundário, embora eu goste de dar o nome certo, ajuda...
Comment: Compreendi a diferença, minha visão(posso ter entendido algo errado) eles são parecidos, mas tem finalidades totalmente diferentes. Pelo que entendi eu já usava da forma correta, só não sabia o porquê. Só me ficou uma pequena dúvida(para deixar mais claro o que já está claro), aqui você diz `O DTO pega os dados de uma fonte, provavelmente uma tabela` seria errado ter um *select* "customizado" que traga dados de 2 ou 3 tabelas e passado para um DTO  com esses campos ou nesse caso seria AR?
Comment: ...entender melhor, comunicar melhor.
Comment: Concordo plenamente ;) Para finalizar, sem querer folgar, mas já folgando. estou pesquisando mas não estou achando sobre `MVVP e RUI` que você citou. alguma indicação de artigo sobre?
Comment: O certo era MVVM :D o RUI é novo mesmo não tem muita coisa
Comment: kkk eu suspeitava, mas como tem tanta coisa, vai que rsrs. Vou pesquisar mais, logo menos pergunto aqui sobre. xD
Answer: TL;DR
Use DTO para modelar a API do seu sistema ou componente (backend), ou seja, como o "mundo externo" vê o modelo de dados.
Use ViewModel para modelar os dados expostos na interface com o usuário (frontend).
Compreendendo abstrações no backend
Quando comecei a programar, eu tentava pesar num sistema como um todo, desde o banco até a "telinha" como uma coisa só. Tentava refletir, tanto quando possível, o banco de dados na tela e vice-versa.
Pulando uma década, cada vez fica mais claro que isto não funciona, por várias razões.
Num mundo de micro-serviços - ou mesmo num sistema grande bem organizado - é importante que cada peça da engrenagem funcione com uma responsabilidade e um modelo bem definido. Entretanto, um endpoint pode ser bem diferente da forma como os dados são realmente armazenados, se é que um banco de dados existe mesmo. Detalhes de implementação não importam para quem usa o sistema.
Portanto, o projeto de um sistema moderno começa com a definição da API. Os desenvolvedores podem usar qualquer tipo de bancos de dados e então, na hora de representar ou receber os dados do mundo externo, o padrão DTO é aplicado.
Um sistema complexo pode agregar dados de diversas fontes diferentes e criar um DTO como um valor de retorno. Ou o contrário: ele recebe uma requisição com um corpo em JSON, por exemplo, que algum framework pode automaticamente mapear para um DTO, e no final o sistema pode destrinchar aquela informação e tomar diferentes ações.
Compreendendo abstrações no frontend
Um processo muito semelhante acontece nos frontends modernos, principalmente quando falamos de Apps escritos em React.js, Android e muitos outros.
O frontend moderno deixou de ser um simples formulário baseado numa tecnologia de templates, onde você preenche alguns valores e renderiza para o usuário.
Os SPAs (Single Page Applications) e mesmo Mobile Apps podem consumir informações de uma miríade de sistemas.
Portanto, é comum em designs modernos você projetar o frontend de forma completamente independente do(s) backend(s) por traz do sistema.
Assim, você precisa definir models das views ou View Model. Os dados podem vir de diferentes requisições a diferentes servidores, de interações com o usuário, do ambiente ou navegador, etc.
Considerações
Os dois padrões são usados para a representação de dados, porém geralmente em camadas completamente diferentes e isoladas de um sistema ou conjunto de sistemas.
É importante entender os conceitos na prática, já que tecnologias e frameworks podem, de uma forma ou de outra, apropriar-se dos conceitos e tornar confusa a aplicação deles.

Diferença entre DTO e ViewModel?


Launching an external GUI application from Python via crontab

Question: Good afternoon!
I have a need in Raspbian to run a GUI application using a telegram bot (Python). Running the application works like this:
p = Popen (["/home/pi/Downloads/reaper_linux_armv7l/REAPER/reaper"], stdout = PIPE, stderr = STDOUT)

There is one problem. If the bot was launched from crontab at system boot (@reboot),
then the external application runs in the background. It works in the background, but I can't see its interface through realVNC.
If the bot was launched manually (without crontab), then everything is fine, in which case I can see the interface of the application being launched.
Can you please tell me how launching a Python bot through crontab affects whether the application is launched in the background or not, and how can this be controlled?
Comment: Crontab is meant for programs to run in the background. If you use GUI then you will have access to the terminal, so what is the need for crontab?
Comment: Crontab is used for autolaunching Python telegram bot at system startup. Bot peforms several tasks. One of the tasks is to launch GUI app when I need it.
Anyway problem is solved by using DISPLAY=:0 in crontab thanks to the advice below.
Answer: Cron run in a specific environment, without display manager. If you try to do a echo $DISPLAY return null.
You need to set DISPLAY in your command, like that:
* * * * * DISPLAY=:0 <YOUR-COMMAND>

if your display is not 0, you can find, in X server with ps aux | grep Xorg


Does a Class extended from a Base which uses an Interface ever need to also use the same Interface?

Question: This questions comes from my AS3 history, but I think the concept applies to all languages.  I can't go back to check the original code but it has been bothering me for a while and would appreciate some clarity.
I was tasked with writing a game, MyGame, that extended a GameBase class.  The template I had been told to follow required that the game use an IGame interface, but I found that that the GameBase class also used that same interface.
Lacking proper notation, I think about it like this:
<code>   MyGame : GameBase
     |          |
   IGame      IGame
</code>
This looks redundant to me and I want to know whether it was or whether I misunderstood inheritance in this context.
Answer: The sub class inherits all super types, that includes the interfaces. There's no need to implement that interface again, because it is already implemented.


Como fazer um INSERT no postgresql com valor default condicional?

Question: Temos a seguinte tabela simplificada para o exemplo:
create table teste(
        id serial not null
        );

Os comandos abaixo causam erro de sintaxe:
insert into teste(
        select (case when 1=1 then DEFAULT end)
        );

ou:
insert into teste(
        select coalesce(null::integer, DEFAULT)
        );

ERROR:  syntax error at or near "DEFAULT"
LINE 2:         select (case when 1=1 then DEFAULT end)
                                           ^
********** Error **********
ERROR: syntax error at or near "DEFAULT"
SQL state: 42601

Provisoriamente uso o seguinte:
   insert into teste(
    select coalesce(null::integer, nextval('teste_id_seq'::regclass))
    );

O Objetivo é informar o valor DEFAULT do campo, seja ele serial ou não, de forma condicional sem informar a função ou o valor da constante definida na tabela, pois esse valor pode mudar futuramente e irá causar uma inconsistência nos comandos que chamam o INSERT. Isso é possível?
Comment: A palavra DEFAULT deve ser informada na parte de VALUES do INSERT e não na lista de campos.
Comment: @anonimo Obrigado, mas, observe que o DEFAULT de exemplo acima não está na declaração dos campos, o INSERT é feito somente com o valor, que é uma das formas de se fazer isso sem obrigatoriamente informar o nomes do campos, desde os valores que estejam na mesma ordem de tipos aceita pelo tipo do registro da tabela.
Comment: Não entendi. Não tem sentido você querer especificar o termo DEFAULT se na criação da tabela você não informou qual é o valor DEFAULT.
Comment: @anonimo:"__...na criação da tabela você não informou qual é o valor DEFAULT__". Implicitamente defini sim. Observe que a declaração da tabela fica assim: `...id integer **default** nextval('teste_id_seq'::')`
Answer: O valor default do campo deve ser informado no momento da criação da tabela, conforme segue:
CREATE TABLE products (
    product_no integer DEFAULT nextval('products_product_no_seq'),
    price numeric DEFAULT 9.99,
    ...
);

Mais detalhes na documentação do PostgreSQL.
Comment: Obrigado, mas, isso não responde à pergunta. O valor DEFAULT também pode ser implicitamente informado usado a palavra reservada DEFAULT no comando INSERT.
[link] https://www.postgresql.org/docs/9.6/static/sql-insert.html [link]
Comment: Por que precisa passar no INSERT? Porque o DEFAULT muda? Se muda não é mais fácil controlar na aplicação? Não pode ajustar o DEFAULT alterando o que foi definido no create table?
Comment: O Código completo é chamado de uma trigger num "UPSERT" (ON CONFLICT no postgresql). Como o id é incrementado sob certa condição, se não for encontrado a id para entregar ao "ON CONFLICT UPDATE" ele deve inserir o DEFAULT.
Comment: Então se não for encontrado o ID, move NULL que ele utilizará o default, conforme definido no CREATE.
Comment: Desculpa, não entendi o que quis dizer com "move NULL".
Comment: Passa NULL ou não passa o campo no insert!
Comment: Passar NULL não chama o Default, visto que o campo é chamado explicitamente. O banco retornará "ERROR:  null value in column "codigo" violates not-null constraint".
Não passar o campo não atende ao requisito de informar o código explicitamente sob certa condição, informado acima.
Comment: Da documentação: "To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value. This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word.". https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-SERIAL


cURL falha ao enviar array

Question: Bom estou com um pequeno problema ao enviar os dados via cURL, quando envios os dados para a API me retorna que há um dos campos que não é uma array: {"errors":["items deveria ser um Array"]}
Código:
$user = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$pass = '';
$data = array(
        "email" => "firstname.lastname@example.com",
        "due_date" => "2018-10-08",
        "items" => array(
                "description"=>"carro",
                "quantity"=> 1,
                "price_cents"=>150000
                ),
        "payer"=>array(
                "cpf_cnpj"=>"644.620.920-74",
                "name"=>"Jeison",
                "phone_prefix"=>"31",
                "phone"=>"991872520",
                "address"=>array(
                        "zip_code"=>"30520240",
                        "number"=>"109",
                        "street"=>"blenda"
                        )
                 )
        );
$data_string=json_encode($data);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, 'https://api.iugu.com/v1/invoices/' );
curl_setopt( $ch, CURLOPT_HEADER, 1 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode( $user . ':' . $pass ) ) );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$return=curl_exec( $ch );
curl_close( $ch );
header("Content-Type: text/json; charset=utf8");`

Answer: Segundo o manual, o problema ocorre, pois, você está enviando apenas um item à API. O correto seria enviar um array de itens, da seguinte forma:
//demais itens omitidos
$data = array(
    "items" => array(
        array(
            "description"=>"carro",
            "quantity"=> 1,
            "price_cents"=>150000
        )
    )
);

Ou simplificado:
//demais itens omitidos
$data = array(
    "items" => [
        [
            "description"=>"carro",
            "quantity"=> 1,
            "price_cents"=>150000
        ]
    ]
);

O que ocorre é o seguinte: quando um array associativo é convertido para JSON, ele é convertido como um objeto e não como um array. Por isso, mesmo o valor de items sendo um array, a interpretação dele é como um objeto.
Ao adicionar o objeto item dentro de um novo array, sem informar índice, por padrão, ele utilizará o índice zero (0), o que o tornará um array indexado. Arrays indexados, por sua vez, são mantidos como arrays no JSON.
Nota: O array foi simplificado para demonstrar apenas o problema
Update
Há mais uma questão no seu código. Você está convertendo o array para JSON, mas está enviando o array para a API:
$data_string = json_encode($data);

No código abaixo, deveria ser $data_string:
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Envie no cabeçalho, também, o tipo de dados e o tamanho:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic '. base64_encode($user.':'.$pass),
    'Content-Type: application/json',
    'Content-Length: '.strlen($data_string)
));

Comment: fiz aqui porém o erro continua, fiz dessa maneira:"items" => array(
                           array(
                               "description"=>"carro",
                               "quantity"=> 1,
                               "price_cents"=>150000

                                ),
                           array(
                               "description"=>"moto",
                               "quantity"=> 3,
                               "price_cents"=>150000

                           )

                )         converti para json e tbm não deu.
Comment: @user9806474 eu atualizei a resposta com outros pontos que você deve mudar
Comment: Deu certo, muito abrigado cara!! me salvou no estagio!!
Comment: @user9806474 marque a resposta como correta e, se possível, +1

cURL falha ao enviar array


Is there a way to determine at runtime if an object was created using Lambdaj.on() method?

Question: I want to write a method that takes as a parameter either result of Lambdaj.on() call or a string.
public static <T> void method(T arg) {
}

T can be String here.
Is it possible to determine if arg was created using Lambdaj.on() method?
Comment: Does `Lambdaj.on` ever return String?  If not, and `!(arg instanceof String)`, then it came from `Lambdaj.on` (or is null).
Comment: Yes, `Lambdaj.on` can return any type. This is really cool because you can write `on(SomeClass.class).getX().getY()`
Comment: Then you can't, because if you receive a String it might be a String the user passed in directly or a String returned by `getY()`, and any information about the source has been lost.  (On the other hand, if `getY` actually returns a type that subclasses String and adds some interfaces, you can test for the presence of those interfaces.  That seems impossible without a modified JVM, however, as String is final.)
Comment: If I recall correctly, Lambdaj remembers returned values internally. If it uses identity comparison for strings I could check if `arg` is stored in Lambdaj internals (most likely by trying to pass `arg` to some Lambdaj method). But I don't know if it's safe or correct or defined behavior.
Answer: After reading Lambdaj source code (ArgumentsFactory.java for the most part) I can conclude that this is impossible.
Lambdaj stores data in a WeakHashMap<Object, Argument<?>>, where key is what return things like on(SomeCLass.classs).getX().
WeakHashMap compares objects using .hashCode() and .equals().


Auto scaling button's width in RelativeLayout

Question: <?xml version="1.0" encoding="utf-8"?>

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

    <Button

        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/btn1"/>

     <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/btn1"/>

I put 7 buttons in its relativelayout. And I'd like to adjust their 'width' to the same size to fit the screen. What should I do
Comment: is it necessary to put relativeLayout as parent ?
Comment: android:layout_width="match_parent" doesn't work?
Comment: If I can do it without relativeLayout, I won't put relativeLayout as parent.
Answer: You can use LinearLayout as a parent and can give weight and weightsum to achieve that, Using Relative layout you can't fit the entire screen or it may exceed the screen based on the device.
You can achieve this using LinearLayout like below,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:weightSum="7"
              android:layout_height="match_parent">
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

</LinearLayout>

Comment: I got it! Thank you for your help.
Comment: Welcome, If you feel it solves your problem, You can mark as answer.
Answer: If you're thinking of displaying each button (height= match_parent), then use scrollview. I hope this helps


How to show online data for offline without database in Android

Question: I want show 3 fragments in my Activity and load data from json in any fragments! I show websites data into Recyclerview with OkHTTP v3 library.
I want show this datas for offline, my mean is if user turn off data/wifi show this datas for offline. but i do not want use SQLite Database!
Can i use OkHTTP cache?  i don't know how to use okhttp cache.
AsyncTask code:
public class freeDataInfo {
    private Context mContext;
    private String ServerAddress = freeServer_IP.getFreeIP();

    public void getFreeDataInfo(Context context) {
        mContext = context;
        //new getInfo().execute(ServerAddress + "limit=10");
        new getInfo().execute(ServerAddress);
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<DataModel> infoModels = new ArrayList<>();
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            //CustomProcessDialog.createAndShow(mContext);
            //infoModels = new ArrayList<>();

            // Initiate Progress
            dialog = new ProgressDialog(mContext);
            this.dialog.setMessage("شکیبا باشید...");
            this.dialog.show();

            infoModels.clear();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            //String url = (String) params[0];
            Request request = new Request.Builder()
                    //.url(ServerAddress + "limit=10")
                    .url(ServerAddress)
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("result");

                        for (int i = 0; i <= postsArray.length(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);

                            int id = postObject.getInt("id");
                            Log.d("id", String.valueOf(id));
                            String title = postObject.getString("title");
                            String description = postObject.getString("full_description");
                            String image = postObject.getString("image");
                            String category = postObject.getString("categoryName");
                            String date = postObject.getString("date");
                            String url = postObject.getString("url");

                            Log.d("Data", "Post ID: " + id);
                            Log.d("Data", "Post title: " + title);
                            Log.d("Data", "Post image: " + image);
                            Log.d("Data", "Post url: " + url);
                            Log.d("Data", "---------------------------------");

                            //Use the title and id as per your requirement
                            infoModels.add(new DataModel(id, title, description, category, date, url, image));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("error", String.valueOf(e));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("error2", String.valueOf(e));
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            //CustomProcessDialog.dissmis();

            //Stop Progress
            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (result != null) {
                bus.post(new MyEvent("forfragment1", infoModels));
            } else {
                Toast.makeText(mContext, "اتصال اینترنت خود را بررسی کنید", Toast.LENGTH_LONG).show();

            }
        }
    }
}

Adapter codes:
public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
    private List<DataModel> mDateSet;
    private Context context;

    // Provide a suitable constructor (depends on the kind of dataset)
    public free_recycler_adapter(Context context, List<DataModel> dataSet) {
        this.context = context;
        this.mDateSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_card_layout, parent, false);

        // create ViewHolder
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // - get data from your itemsData at this position
        // - replace the contents of the view with that itemsData

        viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));

        Glide.with(context)
                .load(mDateSet.get(position).getImage())
                .placeholder(R.drawable.ic_download_image)
                .crossFade()
                .into(viewHolder.free_avatarImage);

        viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));
        viewHolder.free_descText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.getContext().startActivity(new Intent(v.getContext(), ContentPage.class)
                        .putExtra("title", mDateSet.get(position).getTitle())
                        .putExtra("desc", mDateSet.get(position).getDescription())
                        .putExtra("image", mDateSet.get(position).getImage())
                        .putExtra("url", mDateSet.get(position).getUrl())
                        .putExtra("category", mDateSet.get(position).getCategory())
                        .putExtra("date", mDateSet.get(position).getDate()));
            }
        });

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDateSet.size();
    }

    public void remove(int position) {
        mDateSet.remove(position);
        notifyItemRemoved(position);
    }

    public void clear() {
        mDateSet.clear();
        notifyDataSetChanged();
    }

    public void add(List<DataModel> models) {
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public void update(List<DataModel> models) {
        mDateSet.clear();
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    // inner class to hold a reference to each item of RecyclerView
    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView free_titleText, free_descText;
        public ImageView free_avatarImage;

        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);

            free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
            free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
            free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);

        }
    }
}

Fragment codes:
public class free_fragment extends Fragment {

    private RecyclerView mRecyclerView;
    private free_recycler_adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<DataModel> dataModels = new ArrayList<DataModel>();

    private Context context;
    private boolean isDataFetched;
    private boolean mIsVisibleToUser;
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_free_layout, container, false);

        context = getContext();

        if (mIsVisibleToUser) {
            LoadData();
        }

        ///----- RecyclerView -----
        mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new free_recycler_adapter(context, dataModels);
        mRecyclerView.setAdapter(mAdapter);

        return view;
    }

    @Subscribe
    public void onEvent(MyEvent event) {
        List<DataModel> dataModels = event.getInfoModels();
/*        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdapter.notifyItemRemoved(dataModels.size());
            //mAdapter.setLoaded();
        }*/
        if (event.fragmentTag.equals("forfragment1")) {
            mAdapter.add(dataModels);
            isDataFetched = true;
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        mIsVisibleToUser = isVisibleToUser;
        if (isVisibleToUser && !isDataFetched && getContext() != null) {
            context = getContext();
            LoadData(); //Remove this call from onCreateView
        }
    }

    private void LoadData() {
        freeDataInfo dataInfo = new freeDataInfo();
        // here getMainDataInfo() should return the server response
        dataInfo.getFreeDataInfo(context);
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        EventBus.getDefault().unregister(this);
        super.onPause();
    }
}

How can i show data for offline without Sqlite DataBase? Thanks all <3
Answer: Every good network framework provides Response caching. So it's better to use caching instead of using mysql or shared presences to cache the Api response.
For more details how to cache response in okHttp - https://stackoverflow.com/a/31097050/1741586
Just use these methods in your Util class -
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
                .header("Cache-Control", String.format("max-age=%d, only-if-cached, max-stale=%d", 120, 0))
                .build();
    }
};

private static void createCacheForOkHTTP() {
    Cache cache = null;
    cache = new Cache(getDirectory(), 1024 * 1024 * 10);
    okHttpClient.setCache(cache);
}

// returns the file to store cached details
private File getDirectory() {
    return new File("location");
}

Add interceptor to the OkHttpClient instance:
okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);

And finally add OkHttpClient to the RestAdapter:
RestAdapter.setClient(new OkClient(okHttpClient));

These whole implementation is independent of your project. You need to just put in your Uitility class and start using it :)
Comment: @Updated my answer, kindly check :)
Answer: you can use sharepreference save data in /data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
Comment: can you send me true code with my above code? pleaseeeee . i really need this help


Como Disparar Pop Up depois de Copiado Texto

Question: Possuo um cupom de desconto para meu site, ao clicar no botão ele é copiado. Mas gostaria que após copiado mostrasse um pequeno balão em forma de pop-up dizendo "copiado".
Segue meu código:

        let copiarTexto = () => {
            //O texto que será copiado
            const texto = "10KITS239";
            //Cria um elemento input (pode ser um textarea)
            let inputTest = document.createElement("input");
            inputTest.value = texto;
            //Anexa o elemento ao body
            document.body.appendChild(inputTest);
            //seleciona todo o texto do elemento
            inputTest.select();
            //executa o comando copy
            //aqui é feito o ato de copiar para a area de trabalho com base na seleção
            document.execCommand('copy');
            //remove o elemento
            document.body.removeChild(inputTest);
        };
.banner-cupom img{

    display: block;
    padding: 10%;
    margin-top: -70%;

}

.text-coupon {

    font-size: 1.3em;
    margin-top: -30%;
    color: white;
    margin-bottom: 20%;
    text-align: center;
    font-weight: bold;

}

.button, button {
       display: -webkit-inline-box;
    color: #fff;
    border: 1px solid #72dafb;
    border-radius: 10px;
    margin-bottom: 10px;
    text-align: center;
    outline: 0;
    background: #72dafb;
    font-weight: bold;
    padding-left: 2em;
    padding-right: 2em;
}

.button:hover, button:hover {
    cursor: pointer;
    color: #fff;
    background-color: #f6bc70;
    border-color: #f6bc70;
    text-decoration: none;
}

 <button onclick="copiarTexto()">10KITS239</button>

Comment: Olá JVEUZEBIO, consegui ajudá-lo com seu problema?
Answer: É bem simples, você cria uma div que ficará escondida quando a página é carregada:

No script:
let copiarTexto = () => {
...

document.getElementById("div1").innerHTML = " Seu cupom é: "+texto+". ";
//carrega um valor dentro da div, e esse texto é a variavel com o valor
document.getElementById("div1").style.display = "block";
// faz a div aparecer
}

Answer: Como não deixou explicito como seria a exibição pop-up, vou lhe trazer algumas opções para atender sua proposta.

A primeira e mais simples é alertar o usuário utilizando o comando alert(); do Javascript nativo, passando como parâmetro o texto 'Copiado', como mencionou.
E o segundo seria utilizar a classe modal de alguma biblioteca(apenas para facilitar e agilizar o seu processo de implementação).
Utilizar Javascript Nativo, juntamente com CSS para seu objetivo.

Exemplos:
1: Adicionar ao final de sua função copiarTexto o código alert('Copiado'); para exibir um pop-up onde o usuário terá que clicar no botão OK para fechá-lo.
2: Utilizando a Biblíoteca BootStrap(lembre-se de importar os scripts obrigatórios para o seu funcionamento), você pode realizar a exibição de seu pop-up utilizando a classe modal, segue exemplo:
<!DOCTYPE html>

  <title>Modal com Bootstrap</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

  <button type="button" data-toggle="modal" data-target="#myModal" onClick="fecharModal()">10KITS239</button>

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

Copiado.

          <button type="button" class="btn btn-default" id="close" data-dismiss="modal">Close</button>

Note que criei uma função fecharModal() que aguarda 1 segundo(parâmetro 1000 em milisegundos) para fechar o modal, aproximando com um pop-up genérico, uma vez que você não deixou claro como gostaria de exibí-lo.
3: E por último e um pouco mais trabalhoso ao meu ver, seria utilizando JavaScript nativo, para adaptar o pop-up de acordo com suas necessidades. Não vou trazer códigos, pois nesse caso, isso seria mais expecífico à sua necessidade, mas trago dois links que o ajudaria à solucionar, caso deseje utilizar essa opção. segue os links: utilizando modal + JS Nativo, tutorial utilizando Modal com CSS/JS.


How to debug Observable values in Angular2 / Typescript?

Question: I have followed the tutorial for angular 2 and have a search functionality that renders a list of heroes asynchronously.

    {{hero.name}}

In the component I have observable heroes:
heroes: Observable<Hero[]>;

Now I have implemented similar functionality in my application by I don't see anything and I don't see any errors either. I opened the debugger in Chrome and tried to check the value of heroes, but it's just some Observable wrapper of course.
Is there any way to see the current/last or some value in the debugger or maybe there is some other technique to debug such issues?
Comment: Hopefully, some tools to aid debugging RxJS will be built. Until then, you might find this useful: http://staltz.com/how-to-debug-rxjs-code.html And maybe this answer: http://stackoverflow.com/a/38597548/6680611
Answer: In RxJS v6+, the tap() operator has replaced do(). So it will look more like this now:
someObservable$.pipe(
  map(x => x.whatever),
  tap(whatever => console.log(whatever)),
)

Answer: There're several article on this topic but most easily use do() operator to see what's going on in your operator chains.
Read more:

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/testing.md#debugging-your-rx-application
How to debug rxjs5?
http://staltz.com/how-to-debug-rxjs-code.html
https://react.rocks/example/rxvision
http://jaredforsyth.com/2015/03/06/visualizing-reactive-streams-hot-and-cold/
Comment: So there is no way to use the debugger for that purpose if I understood correctly?
Comment: @IlyaChernomordik Of course you can use debugger. The problem is that it's not very helpful because there're so many nested calls and so many anonymous Observables and function that it's very hard keep track of what's going on inside. This is described also in the doc https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/testing.md#long-stack-traces-support
Answer: First of all, if you're using typescript consider:
heroes: Observable<Array<Hero>>;

If you want to print it, you can simply add in your code:
heroes.subscribe((v) => console.log('got new heroes list: ', v));

Comment: So back to console logging and no debugging options? P.S. Why is Array better than Hero[]? This is directly from Angular2 tutorial.
Comment: No pain no gain :-) But even stalz relate to the hardship of debugging.

As for Array, I find it more readable and consistant with the typed approach. Imagine Array>, Item[][]? (Item[])[]? it gets messy.
Comment: The debugger (in Chrome at least) now allows fine-grained breakpoints. I was able to write a statement like in this answer, put a breakpoint directly on the log call, and then the Local Scope window showed the value of v as the materialized Observable.
Answer: You can use the do() operator EX :
this.http
        .get('someUrl', options)
        .map(res => res.json())
        .do(
            data => {
                console.log(data);
            },
            error => {
                console.log(error)
            }
        )

If nothing happens inside the do() functions it means you are not subscribed to that observable, remember that observables are waiting for a subscription to start doing something.
Answer: U can use  .pipe() to log as shown.
constructor(
    private variable: Variable<any>
  ) {
    this.field= this.variable.select<any>(state => state.field).pipe(
        tap(Value => console.log('Field: ', Value ))
    );
  }

Answer: If you want to do some console.log debugging, I wrote a little helper logValues() in s-rxjs-utils. You can use it like this (from the docs):
of(1, 2).pipe(logValues()).subscribe();
// prints using console.log:
// [value] 1
// [value] 2
// [complete]

You can also pass it a string to print along with the values, and specify the log level.


Show this set generates the Borel subset of the reals?

Question: This question is in a past paper I'm doing:
Let $\mathcal{I}$ be the collection of all intervals in $\mathbb{R}$ not containing zero. Show that $\mathcal{I}$ generates the $\sigma$-algebra of Borel subsets of $\mathbb{R}$.
I've been trying to write an arbitrary interval $(a,b)$ as some union or intersection of intervals in $\mathcal{I}$ but haven't had any luck.
Comment: Algebras contain complements, do they not?
Answer: If $I$ is an interval and  $0 \in I$ then $I^{c}=(I^{c}\cap (-\infty,0))\cup (I^{c}\cap (0,\infty)) $. Can you verify that $I^{c}\cap (-\infty,0)$ and $I^{c}\cap (0,\infty)$ are intervals not containing $0$?


How to prove that if $Z=Z(r\cos \theta, r\sin\theta)=F(r,\theta)$ then $F_{\theta}=0$ when $yZ_x=xZ_y$?

Question:
How to prove that if $Z=Z(r\cos \theta, r\sin\theta)=F(r,\theta)$ then $F_{\theta}=0$ when $yZ_x=xZ_y$?

I tried diffentiating $F_{\theta}$:
$$
F_{\theta}=\frac{\partial z}{\partial x}\cdot\frac{\partial x}{\partial \theta}+\frac{\partial z}{\partial y}\cdot\frac{\partial y}{\partial \theta}=\frac{\partial z}{\partial x}\cdot-r\sin\theta+\frac{\partial z}{\partial y}\cdot r\cos\theta
$$
How to I arrive to $F_{\theta}=0$?
Comment: You have it almost done:  What are $x$ and $y$ in polars? The derivatives "cross" the sine and the cosine. Rewrite the hypotesis.
Comment: Sine goes to cosine and viceversa. And yes, it is, but the proposition to prove is the converse one.
Comment: $F_\theta$ can be seen as the variation of $F$ along a direction always perpendicular to the position vector of the point at where we are evaluating $F$ (and having as modulus our $r$). This variation must be zero as the function only depends on $r$. Another way to see it is as $F$ being symmetric for rotations: you calculate $F$ for some values of $x_0$ and $y_0$, then, rotate the axes in an amount of $\theta$ and the value of $F$ for the same values of $x_0$ and $y_0$ it's the same too. The condition you asked to prove is a nice form to express this symmetry.
Comment: @RafaBudría what do you mean by "cross"? I guess because $x=r\cos\theta$ and $y=r\sin\theta$ this equation is just another form of $Z=f(r)$ from https://math.stackexchange.com/questions/2286401/given-r2-x2y2-and-function-z-fr-prove-that-the-function-fulfills-yz-x#2286432                         By the way the fact that $F_{\theta}=0$, does this tell us anything?
Comment: @RafaBudría but what follows from the fact that $F_{\theta}=0$? Is the function flat or something?
Answer: Just write
$$F_{\theta}=\frac{\partial Z}{\partial\theta} = \frac{\partial Z}{\partial x}\frac{\partial x}{\partial\theta} + \frac{\partial Z}{\partial y}\frac{\partial y}{\partial\theta}$$
$$=Z_x\cdot(-r\sin\theta)+Z_y\cdot(r\cos\theta)$$
$$=-yZ_x+xZ_y$$
which is zero by hypothesis.