Nginx downloads PHP instead of executing

Question: PHP files are downloading instead of executing, and the mydomain.com root gives a HTTP 403 Forbidden, suggesting the index directive is not set up correctly.
(Sorry I know this has been asked a million times but I feel like I've tried every combination of articles I could get my hands on.)
Ubuntu 16.04, PHP FPM 7.2 installed
Here are the basic configs I'm using. I've stripped out everything else I've tried for clarity:
/etc/nginx/sites-available/default
# Default server configuration

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        index index.php index.html index.htm;

        location / {
            try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }

        location ~ /\.ht {
               deny all;
        }
}

/etc/nginx/sites-available/mydomain.com.conf
server {
    server_name .mydomain.com;
    listen 80;
    listen [::]:80 ipv6only=on;
    listen 443 default_server ssl;
    listen [::]:443 ipv6only=on;

    location / {
        root /var/www/html/mydomain.com;
    }
}

One thing I've noticed is that /run/php/php7.2-fpm.sock has a file size of zero even on a fresh install.
Answer: When is nginx downloading the php file? If it happens when you are accessing your main site mydomain.com/foo.php, it's because your php configuration should be inside your main site's server block, not in the default server block.
So this should work :
/etc/nginx/sites-available/mydomain.com.conf
server {
    server_name .mydomain.com;
    listen 80;
    listen [::]:80 ipv6only=on;
    listen 443 default_server ssl;
    listen [::]:443 ipv6only=on;

    # You need to add your SSL certs here
    ssl_certificate /path/to/mydomain.com.crt;
    ssl_certificate_key /path/to/mydomain.com.key;
    ssl_dhparam /path/to/dhparam.pem;

    root /var/www/html/mydomain.com;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }

    location ~ /\.ht {
           deny all;
    }
}

# Default server
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    return 401;
}

As with best practices, the default server block should only be used as dummy to drop any request that has does not have a valid destination (i.e. domain name, e.g. mydomain.com). Which means when someone requests myexample.com and points that DNS to your nginx server, the person will hit a 401.
Comment: what should we name the file if we only have ip address and not DNS?
Comment: Thank you! That worked. So when should the sites-available/default config be used? I was thinking of that file as a catch-all of general settings that should apply to all sites I'll host, then have specific site configs in the relevant files, no?
Comment: To the best of my knowledge `nginx` allows 'global' settings for only some directives. Best practices recommend dedicated `server` blocks. Even dynamically configured load balancers with service discovery generate full `server` blocks, based on an `nginx` template. See: [`nginx-proxy`](https://github.com/jwilder/nginx-proxy) used with a template generator [`docker-gen`](https://github.com/jwilder/docker-gen) using an nginx template [`nginx.tmpl`](https://github.com/jwilder/nginx-proxy/blob/master/nginx.tmpl). If you scan the template you see dedicated `server` blocks and some 'global' settings
Comment: Some 'global' settings you see in that template are `map`, `ssl_dhparam`, `server_names_hash_bucket_size`, `gzip_types`, `log_format`, `access_log`, `proxy_*`... Basically anything that is allowed in the `http` context. See [`map`](https://nginx.org/en/docs/http/ngx_http_map_module.html#map) in the `nginx` docs as an example. But these directives should not go into the `default_server` `server` block.


Is DocumentBuilder thread safe?

Question: The current code base that I am looking at uses the DOM parser. The following code fragment is duplicated in 5 methods :
 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();

If a method that contains the above code is called in a loop or the method is called multiple times in the application, we are bearing the overhead of creating a new DocumentBuilderFactory instance and a new DocumentBuilder instance for each call to such a method.
Would it be a good idea to create a singleton wrapper around the DocumentBuilder factory and DocumentBuilder instances as shown below :
public final class DOMParser {
   private DocumentBuilderFactory = new DocumentBuilderFactory();
   private DocumentBuilder builder;

   private static DOMParser instance = new DOMParser();

   private DOMParser() {
      builder = factory.newDocumentBuilder();
   }

   public Document parse(InputSource xml) {
       return builder.parser(xml);
   }
}

Are there any problems that can arise if the above singleton is shared across multiple threads? If not, will there be any performance gain by using the above approach of creating the DocumentBuilderFactory and the DocumentBuilder instances only once throughout the lifetime of the application?
Edit :
The only time we can face a problem is if DocumentBuilder saves some state information while parsing an XML file which can affect the parsing of the next XML file.
Comment: I suggest you only optimise your code when you know you have a problem i.e. you have used a cpu or memory profiler.  The rest of the time you should make your code as simple and easy to understand as possible and this will often perform well.
Comment: possible duplicate of [Is DocumentBuilderFactory thread-safe in Java 5+?](http://stackoverflow.com/questions/9828254/is-documentbuilderfactory-thread-safe-in-java-5)
Comment: @PeterLawrey I understand what your getting at but once glance at the code and I can clearly see that the DocumentBuilderFactory and DocumentBuilder are getting created multiple times in loops from methods that uses them!
Comment: possible duplicate: http://stackoverflow.com/questions/56737/is-documentbuilder-parse-thread-safe
Comment: another possible duplicate: http://stackoverflow.com/questions/3439485/java-and-xml-jaxp-what-about-caching-and-thread-safety
Comment: @bot so they are not singletons currently. Do you know that creating them multiple times makes a significant difference to your performance?
Comment: That's right. They are not Singletons right now. I am planning to make them a part of my DOMParser Singleton as shown in my question. I am not sure whether creating a new DocumentBuilderFactory and a new DocumentBuilder is expensive or not. Regardless of this fact,don't you think we will still be reducing the amount of time spent on creating these objects for every iteration of a loop or for every method call in which they are used? We will also be reducing the number of objects created!
Answer: See the comments section for other questions about the same matter. Short answer for your question: no, it's not ok to put these classes in a singleton. Neither DocumentBuilderFactory nor DocumentBuilder are guaranteed to be thread safe. If you have several threads parsing XML, make sure each thread has its own version of DoumentBuilder. You only need one of them per thread since you can reuse a DocumentBuilder after you reset it.
EDIT A small snippet to show that using same DocumentBuilder is bad. With java 1.6_u32 and 1.7_u05 this code fails with org.xml.sax.SAXException: FWK005 parse may not be called while parsing. Uncomment synchronization on builder, and it works fine:
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();

        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            exec.submit(new Runnable() {
                public void run() {
                    try {
//                        synchronized (builder) {
                            InputSource is = new InputSource(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><俄语>данные</俄语>"));
                            builder.parse(is);
                            builder.reset();
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        exec.shutdown();

So here's your answer - do not call DocumentBuilder.parse() from multiple threads. Yes, this behavior might be JRE specific, if you're using IBM java or JRockit or give it a different DocumentBuilderImpl, it might work fine, but for default xerces implementation - it does not.
Comment: @bot: it means that parse method is *not* thread safe. there shouldn't be a problem with DocumentBuilderFactory, but since you want some singleton that parses your files, I'd suggest you to create a pool of DocumentBuilders and use them from it. See http://commons.apache.org/pool/ for a simple implemetation.
Comment: @bot: yeah, but parse might not be thread safe either. The fact that there's a `reset()` method on `DocumentBuilder` might suggest that parsing changes something and it is not a good idea to call it from multiple threads.
Comment: FYI - I hit this one even with making my own `Builder` on-the-fly before parsing so the static state must be somewhere deeper.
Comment: I understand that DocumentBuilderFactory and DocumentBuilder are not Thread safe. But if you take a closer look at my implementation of the DOMParser Singleton class, you will notice that there are no methods in this class to modify the DocumentBuilderFactory and DocumentBuilder instances. If N threads are going to call the only public method named parse from DOMParser which simply parses the input XML, I don't see why this would be a problem!
Comment: We are making an assumption that parsing an XML file using the DocumentBuilder changes some state in DocumentBuilder. If this assumption is correct, then yes, we will fall into trouble while parsing the next XML file. But this is an assumption we are making. Do you or does anyone know for sure whether DocumentBuilder relies on some state while parsing an XML?
Comment: Now that's what I am talking about. If only I had access to a computer  to try this out myself! Thanks a tonne! Does this mean that the parse method is thread safe?
Comment: One more question, does this mean that there won't be any problem while sharing a single instance of DocumentBuilderFactory across multiple threads?
Comment: synchronized (builder) {}does not solved my problem, so I decided to create new DocumentBuilder builder = factory.newDocumentBuilder(); for every parsing. It works fine and it's not much slower.
Comment: I'd like to point out that some Xerces versions, including those built into JDK/JRE, [contain a bug](https://bugs.openjdk.java.net/browse/JDK-8047329), which may cause the `FWK005` exception, even if each thread calls `DocumentBuilderFactory.newInstance()` respectively. That bug report is for `XPathExpression.evaluate(InputSource)`, but internally the same thing happens, even if you instantiate all required factories in each thread.
Answer: The JAXP Specification (V 1.4) says:

It is expected that the newSAXParser method of a SAXParserFactory implementation, the newDocumentBuilder method of a DocumentBuilderFactory and the newTransformer method of a TransformerFactory will be thread safe without side effects. This means that an application programmer should expect to be able to create transformer instances in multiple threads at once from a shared factory without side effects or problems.

https://jaxp.java.net/docs/spec/html/#plugabililty-thread-safety
So, for example, you should be able to create a single DocumentBuilderFactory instance via DocumentBuilderFactory.newInstance and then use that single factory to create a DocumentBuilder per thread via DocumentBuilderFactory.newDocumentBuilder. You could also create a pool of DocumentBuilders.
I can't find anywhere that says that, for example, the static method DocumentBuilderFactory.newInstance is thread-safe. The implementation appears thread-safe in that there is some method synchronization being done, but the spec specifically says that DocumentBuilderFactory.newDocumentBuilder is thread safe.
Answer: Primarily to answer your question no, Document Builder isn't thread-safe. But we can make it thread-safe in two ways:

Synchronized
ThreadLocal

For Synchronized what we can do is just make a synchronised block, this will work for us we should use synchronize on small blocks since it is very expensive and sometimes can make things very slow.
   DocumentBuilder documentBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
   synchronized(documentBuilder)
   {
      documentBuilder.parse(xmlFile.getInputStream());
   }

The other and better approach we can follow is using ThreadLocal.
    public class XmlParser {

    private static ThreadLocal<DocumentBuilder> documentBuilder;

    public XmlParser() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        documentBuilder = ThreadLocal.withInitial(() -> documentBuilder(factory));
    }
    private DocumentBuilder documentBuilder(DocumentBuilderFactory factory) {
        try {
            return factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new Exception("file is not valid");
        }
    }
    public Document parse(MultipartFile xmlFile) {
        try {
            Document parse = documentBuilder.get().parse(xmlFile.getInputStream());
            documentBuilder.remove();
            parse.normalizeDocument();
            return parse;

        } catch (IOException | SAXException e) {
            throw new Exception(e);
        }
    }

Comment: Cool idea. Just one thing: This implementation overwrites the static field `documentBuilder` with every new instance of `XmlParser `. If  `XmlParser ` is a singleton, `documentBuilder` does not have to be static. If `XmlParser ` is not a singleton, `documentBuilder` should be initialized in a static manner, like `private static final ThreadLocal documentBuilderThreadLocal = ThreadLocal.withInitial(XmlParser ::createBuilder);`
Answer: You need to know three things:

What is the cost of creating the factory? If the cost is low, your performance gain might be close to zero.
What is the cost of creating the builder?  If the cost is low, your performance gain might be close to zero.
Is the factory and/or builder thread safe? If not, you need to make sure the method accessing them is made thread safe using the synchronized keyword.

I'm not familiar with the DocumentBuilder classes you are using, but all this information should be available in its javadoc or other documentation. If the creation of certain objects is costly, they usually throw this information at you.
Comment: The cost of creating the factory is huge.  Unless you have defined a system property to specifiy your implementation, DocumentBuilderFactory will perform a full classpath scan every time you retrieve an instance. See the FactoryFinder at [link](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/javax/xml/parsers)/DocumentBuilderFactory.java#DocumentBuilderFactory.newInstance%28%29[link]
Comment: OK with #1 and #2 answers. This is the real question to ask, before having to think about synchronization and any risky and costly noisy/boiler plate technical code.
Answer: can we re-use DocumentBuilder  instance and not create it everytime, for us new object creation is taking up 3% of CPU utilization.
Sample:-
class level variable:-
private static volatile DocumentBuilder builder = null;
    if (Common.builder == null) {
        synchronized (DocumentBuilder.class) {
            if (Common.builder == null) {
                SplunkLogger.info("DocBuilderInstance=New_Instance");
                Common.builder =
                        XMLUtil.getDocumentBuilderFactory()
                        .newDocumentBuilder(); // DocumentBuilderFactory.newInstance().newDocumentBuilder();
            } else {
                SplunkLogger.info("DocBuilderInstance=Re-Use_Existing_Instance_InnerIf");
            }
        }
    } else {
        SplunkLogger.info("DocBuilderInstance=Re-Use_Existing_Instance");
}
    final InputSource source = new InputSource();
    source.setCharacterStream(new StringReader(responseString));
    final Document doc = Common.builder.parse(source);
    return doc.getElementsByTagName(firstKey);
}

Is DocumentBuilder thread safe?


Exclude first row (it is row #1 in my sheet) from USEDRANGE method?

Question: I have some input data from my broker.
I've written some code to automate calculations, adding columns and inserting some formulas.
In the end, I want to do some conditional formatting (affecting whole rows) to determine transactions that are profitable (green font whole row) and transactions that are lost (red font whole row).
To do this I've used USEDRANGE method - I know it's a tricky one, by my data are consistent - there's no empty rows, only few empty columns, so I think USEDRANGE will handle it. I need to use USEDRANGE because I'll have more rows next time I'll run this report.
But I have in my data the first row, where I keep headers 4 my columns.
I want my headers to stay black (font), but I still want to use USEDRANGE method.

How do I execute my conditional formatting using USEDRANGE method, excluding the first row (so it stays black font).
Option Explicit
Dim RowNumber As Long
Dim LastRow As Long
Dim ColumnNumber As Integer
Dim LastColumn As Integer
Dim VBA As Worksheet
Dim TotalRange As Range

Sub CondicionalFormating_WholeRows()
    Set VBA = Workbooks("lista transakcji Dukascopy od October 2015.xlsm").Worksheets("VBA")
    Set TotalRange = VBA.UsedRange
    LastRow = VBA.Cells(Rows.Count, 1).End(xlUp).Row
    LastColumn = VBA.Cells(1, Columns.Count).End(xlToLeft).Column

TotalRange.FormatConditions.Add Type:=xlExpression, Formula1:="=$H1<0"
TotalRange.FormatConditions(TotalRange.FormatConditions.Count).SetFirstPriority
    With TotalRange.FormatConditions(1).Font
        .Bold = False
        .Italic = False
        .Strikethrough = False
        .Color = -16777024
        .TintAndShade = 0
    End With
    TotalRange.FormatConditions(1).StopIfTrue = False

TotalRange.FormatConditions.Add Type:=xlExpression, Formula1:="=$H1>0"
TotalRange.FormatConditions(TotalRange.FormatConditions.Count).SetFirstPriority
    With TotalRange.FormatConditions(1).Font
        .Bold = False
        .Italic = False
        .Strikethrough = False
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.499984740745262
    End With
    TotalRange.FormatConditions(1).StopIfTrue = False

    '   VBA.Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
End Sub

Comment: I suggest you don't use `.UsedRange` and explicitly set `TotalRange`. `.UsedRange` can cause headaches.
Comment: First, I would do Resize. And only then Offset. Otherwise, error 1004 is possible.
Answer: Set TotalRange = VBA.UsedRange '<<< your existing line

'Add this line right after
Set TotalRange = TotalRange.Offset(1,0).Resize(TotalRange.Rows.Count-1, _
                                               TotalRange.Columns.Count)

Comment: should I just add this second line 2 my code?
can U comment a little on that part:

... ...Resize(TotalRange.Rows.Count-1, TotalRange.Columns.Count)
Answer: Use .offset(1) to move the entire range reference down 1 row. This will leave an empty row at the end of the range.  .Resize(VBA.UsedRange.Rows.Count - 1) will trim off the last rows.

Set TotalRange = VBA.UsedRange.Offset(1).Resize(VBA.UsedRange.Rows.Count - 1)


How to prove if something is a linear transformation?

Question: (I think) My textbook says something is a linear transformation if

$L(ax) = aL(x)$
$L(x+y) = L(x) + L(y)$
$L(x) = A(x)$

But a lot of sites I've been on haven't proved these 3 things, so I just wanted to make sure that this is the proper way to prove it.
For example, if $L(x) = (x_1, x_2, x_1 + 2x_2)^T$, then is it a linear transformation from $R^2$ to $R^3$? I know that it is, but I'm not sure if what I have above is how I'm supposed to prove it.
Comment: What is $A(x)$?
Comment: Oh, I was looking at an example where A was [0,1,1]^T, [1,0,1]^T. Then the book said L(x) = [x2,x1,x1+x2] = Ax. But I think that may have been just a note now that I look at it again.
Comment: I think that he's referring to the fact that $A$ is a matrix, and he meant to write $Ax$, as all matrix transformations are linear transformations
Answer: This is almost right, but that third condition shouldn't be there (in fact, I don't know what it means in general--what is "$A$"?).  That is, a map $L$ between two vector spaces is a linear transformation if and only if it satisfies $L(ax)=aL(x)$ and $L(x+y)=L(x)+L(y)$ (for any scalar $a$ and any elements $x,y$ in the domain of $L$).
You can check this directly for your example $L(x)=(x_1,x_2,x_1+2x_2)$ (for $x=(x_1,x_2)$).  For any scalar $a$, we have $ax=(ax_1,ax_2)$, so $$L(ax)=L(ax_1,ax_2)=(ax_1,ax_2,ax_1+2ax_2)=a(x_1,x_2,x_1+2x_2)=aL(x).$$
If $x=(x_1,x_2)$ and $y=(y_1,y_2)$, then $x+y=(x_1+y_1,x_2+y_2)$, so $$\begin{align}
L(x+y)=L(x_1+y_1,x_2+y_2)={} &(x_1+y_1,x_2+y_2,x_1+y_1+2x_2+2y_2)\\={}&(x_1,x_2,x_1+2x_2)+(y_1,y_2,y_1+2y_2)\\={}&L(x)+L(y).
\end{align}$$
As you can see, checking something like this can be a kind of lengthy computation sometimes!  But it's not hard--you just plug in the definitions and rearrange the terms appropriately.
Answer: Yes your textbook is right, basically a function is a linear transformation if and only if scalar multiplicity is reserved meaning that letting $a $ be a real number then
$L(a*x)=a*L(x)$
In your example if you wanted to show this property holds you show that
$2L(x)=2(x_1,x_2,x_1+2x_2)=(2x_1,2x_2,2x_1+4x_2)$
The second property that linear transformations must satisfy is preservation or distribution over vector addition. Let's say $v$ and $u$ are vectors then
$L(x+v)=L(x)+L(v)$
Meaning you can add the vectors and then transform them or you can transform them individually and the sum should be the same. If in any case it isn't, then it isn't a linear transformation.
The third property you mentioned basically says that linear transformation are the same as matrix transformations. So every linear transformation has a matrix corresponding to it called the standard matrix. Hope this helps.
Comment: @Chris no that doesn't need to be proven. But its useful. Usually you are asked to find the standard matrix a LT.
Comment: The final part of your answer is slightly confusingly worded. It would be more correct to say that the linear transformation can be represented by different matrices depending on the choice of basis (you can even choose a different basis for the domain than for the codomain), but that in some (not all) vector spaces you have a standard basis that you can use which makes things simpler and more standard.
Comment: So do I really only need to prove the first two properties? The last one seems more like a note to me.
Comment: @Chris Yes you must prove both. There are cases where only the first one will hold and the other will not.
Comment: I was referring to the last one, where it said L(x) = Ax
Comment: Sure thing, thank you!


Como enviar registro só uma vez no INSERT

Question: Olá, eu tenho um INSERT, envia, tudo ótimo, mas quando clica várias vezes no botão de submit, envia vários, registros, como posso evitar isso?
Código:
<?php
    $id_noticia  = $edit["id"];
$autor = $_SESSION["username"];
$texto = $_POST["texto"];
$coment = "INSERT INTO `10cms_noticias_resp` ( `id_noticia` , `autor` , `texto`, `data` , `id`, `num` ) VALUES ('$id_noticia', '$autor', '$texto', now(), '', '')";

mysql_query($coment);
?>

Botão:
 <button type="submit" id="comentar" onclick="this.disabled = true;" style="width: 76px;height: 30px;color: white;font-size: 15px;line-height: 20px;border-radius: 50px;border: none;position: absolute;right: 0;background-image: linear-gradient(0deg, #FFA141, #FFB366 100%);margin-right: 10px;">enviar</button>

Comment: Coloque um redirecionador no OK do insert... Ai ele volta pra página de ADD, ou para qual você direcionar.
Comment: Olá, já tem redirecionamento, o problema é que demora um tempo para carregar e enviar os registros. Sendo assim se a pessoa clicar várias vezes no botão submit vai enviar vários registros.
Answer: A fim de evitar envios múltiplos de um mesmo formulário, segue abaixo recomendações básicas:
1. Desativar a submissão do formulário
Uma vez feito a ação de "submit", desative-o. Exemplo de técnica usando JavaScript:

<form id="frm1" onsubmit="return AvoidMultiSubmit(this);">
...
<form>

Por quê não poderia apenas desativar o botão na ação de click (onclick) ?
O motivo é que um formulário pode ser submetido por outros meios que não a ação de click. Por isso, o mais seguro é verificar no evento "OnSubmit".
2. Reforçando a segurança com cookie
Impedir o envio múltiplo de um formulário não é o suficiente pois, num simples "refresh", o usuário ainda terá o formulário "limpo" para enviar novamente.
A fim de reforçar a segurança, precisamos implementar uma verificação por cookies. O exemplo abaixo deve ser encaixado dentro da função "AvoidMultiSubmit", na condicional que envia o formulário:
    var name = "cookie_frm1"; // nome do cookie
    var value = "submited"; // um valor qualquer
    var days = 1; // quantidade de dias de expiração

    /**
    Formata os parâmetros
    */
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires=""+date.toGMTString();

    /**
    Cria o cookie
    */
    document.cookie = name+"="+value+expires+"; path=/";

No script PHP que recebe os dados, verifique se o cookie existe:
if( isset( $_COOKIE['cookie_frm1'] ) )
{
    echo 'Ação negada';
    exit;
}

Obs: O bloqueio no PHP pode ser um redirecionamento ou conter outro tipo de mensagem mais amigável ao usuário. O exemplo acima é meramente didático.
Ao completar as execuções no PHP, caso não necessite retornar ao formulário, remova o cookie:
unset( $_COOKIE['cookie_frm1'] )

Comment: Seu código bugou minha cabeça. Eu coloquei ele certinho, mas continua enviando sozinho quando entra na página.
Comment: se vc apenas copiou e colou o código acima pensando que fosse funcionar como mágica, aí sim, vc tem problema, que está na sua cabeça.
Answer: Adicione um listener em Javascript no botão pra que assim que ele for clicado, ele seja desabilitado - não recebendo mais cliques:
Via script (recomendado):
document.getElementById('idDoBotao').addEventListener('click', function(event) {
    // event.target = quem acionou o evento
    event.target.disabled = true;
});

jQuery
var btn = $('#idDoBotao');
btn.on('click', function(event) {
    btn.disable(true);
});

Direto no botão:
<input type="submit" onclick="this.disabled = true;">

Comment: Funcionou tudo certinho, mas o problema é que quando eu abro a página é como se ele já tivesse apertado sozinho o submit.
Comment: Já fica desabilitado na primeira vez que você carrega a página? Ou depois de ter clicado uma vez? Qual das opções você usou?
Comment: O que você me passou foi depois de clicar. Só que quando eu carrego a página, automaticamente ele dá submit.
Comment: Estranho. Tem como você colocar o código HTML do seu botão na pergunta? Você está usando jQuery?
Comment: Não, não estou utilizando jquery.
Comment: Testei aqui e roda normal: http://jsfiddle.net/nqoddff3/. Tenta clicar na barra de endereço do browser e dar enter ao invés de dar F5, pois o browser pode estar reenviando o form. De qualquer maneira, acho que a resposta do @DanielOmine é melhor, pois como ele disse, um form pode ser submetido por diversas maneiras diferentes, então ouvir o evento de `click` não é a melhor solução.
Comment: Quando eu entro na página o submit envia o dado sozinho, queria que enviasse só quando eu clicasse no botão.


cx_freeze executable crashes with "Program Has Stopped Working" and "No Module Named Codec"

Question: I wrote a Python script that requires a few modules, these being:
PyQt5,
plotly,
pandas,
datetime,
xlsxwriter
I am trying to turn these into a .exe using cx_freeze. I have done this once before with a simpler program that relied primarily on PyQt5.
The line:
python setup.py build

completes without errors on the command prompt.
My setup.py file looks like:
  import sys

kwargs = {"name": "x",
          "version": "1.2",
          "author": "x",
          "author_email": "x",
          "description": "x",
          "zip_safe": False
          }

try:
    if sys.argv[1] == "build":
        import os
        from setuptools import find_packages
        from cx_Freeze import setup, Executable

        kwargs["options"] = {
            "build_exe": {
                "packages": find_packages() + ["os", "numpy", "plotly", "xlsxwriter", "sys", "datetime"],
                "includes": ["numpy", "plotly", "pkg_resources", "PyQt5", "xlsxwriter", "sys", "datetime","codecs"],
        }
    }
    kwargs["executables"] = [Executable(r"MyScript.py",
base="console")]

    setup(**kwargs)
except Exception as e:
    print(e)

The line with [username] has my username in it.
When I run it, the command line reads:
Fatal Python error: Py_Initialize: unable to load the file system codec
Traceback (most recent call last):
  File "C:\Users\[Username]\AppData\Local\Programs\Python\Python36\lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'

UPDATE
After reading more on the internet, it seemed like it might be an install issue. So I've uninstalled and re-installed Python and all the modules I needed after uninstalling Anaconda (just in case it was something to do with the Anaconda distribution). However, I'm still seeing the above error. There is a module named codecs, and the Python script (not the .exe) works fine. I've tried changing my path variable to make sure it points to the correct version of Python (though I've uninstalled all other versions).
Also, I'm running:
OS: Windows 7
Python: Python 3.6.3 64 bit
Answer: So it turned out that the issue was cx_freeze. If you use pip to install it, it doesn't install the latest version. Instead, I Googled "cx_freeze download", downloaded the latest .whl for my version of windows, then ran:
pip install [name of file here].whl

After that there were other issues, but the codec issue was resolved.


Congregational involvement in Protestant and Catholic services during the time of Luther

Question: How involved was the congregation in the performance of music in a Protestant service of Martin Luther and a Catholic service in the Counter-Reformation?
Comment: This is specific and answerable, as indicated by the answers, unlike this user's other questions.  Please vote based on content and not the user or their presumed intent.  Reopening
Comment: While I believe that the question should indeed be answerable here, you might look to http://history.stackexchange.com/ for a different perspective.
Answer: Martin Luther, long before he broke with the Catholic Church, believed that music was a form of prayer, through which the people spoke to God and God spoke back. History states that he didn't actively encourage his congregation to sing along until after his publishing of the 95 Theses and his excommunication, but some sources say he encouraged it at Wittenburg while he and the Wittenburg church were still Catholic. According to most sources it caught on fairly quickly, though I'd imagine the first few weeks of Mass were a bit timid on the part of the congregation.
In the Catholic Church at the time, a decree dating all the way back to the 4th Century and the Nicene councils that only the clergy should sing was still in effect. Therefore, with Protestant congregations singing hymns and the Catholic Church continuing to condemn practically everything Luther said or did (Catholic figures at the time lamented, "the German people are singing themselves into Luther's doctrines, and his hymns destroy more souls than all of his writings and sermons"), the Counter-Reformation would only have strengthened enforcement of a clergy-only liturgy. It would not be until 1964 that the edicts from Vatican II would take effect and the "New Mass", celebrated in the vernacular of each community, would formally lift this ban on Catholic congregational singing.
However, in certain locations (especially in newly Protestant countries like England and Germany), Catholics found themselves having to do their own singing. They didn't have much choice, as performing the Mass at all was an act of treason, so anyone still considering themselves in the Holy Orders wouldn't be quick to answer calls for Catholic liturgists. William Byrd, a reclusent Catholic in the employ of the Tudor royal family, wrote masses in three, four and five parts specifically for use in private chapels, where there may only have been half a dozen people in attendance, and it would be naive to assume they'd all be in Holy Orders of any kind. Byrd himself wrote in a preface to his "Psalmes, Sonnets & Songs", "Because it is so good a thing, I wish all men would learn to sing... the better the voice, the more fitting it is to honor and serve God therewith; and the voice of man is chiefly to be employed to that end". So, Holy Orders or not, there were Catholics who agreed with the Protestants on this one point even during the Counter-Reformation.
For a little bit more history as well as a primer in the sacred music of the time, I'd point you to the excellent BBC docuseries, "Sacred Music". Episodes are available on YouTube, and I have a playlist here which will take you through them in roughly chronological order. Of particular interest to you will be episodes 3 and 4, which deal most directly with the events of the Reformation in England and in Germany. Episode 2, and the special episode covering T.L. de Victoria, also have some information about how the Reformation and Counter-Reformation impacted still-Catholic nations like Italy and Spain.
Answer: I believe in those centuries (16th and 17th), going to church was a very important day each week in most European communities.  With that in mind, I believe in both cases, the congregation was as involved as they could be.  However, Lutheran hymns are written in the local language, which had been done in order to more greatly involve the congregation.  Catholic hymns, on the other hand, were in Latin (until much later), which made it much harder for the layman to participate in singing the hymns.


Find all values of K so that A is not invertible & Find all values of K so that AA^T is symmetric

Question: Given
$$A=\begin{bmatrix}
1 &  0 &  0 & 0 \\
3 &  k-2 &  0 &  0 \\
k-1 &  -1 &   k+1 &  0 \\
2 &  0 &   1 &  3
\end{bmatrix}$$
1 . Find all values of $K$ so $A$ is not invertible.
2. Find all values of $K$ so $AA^T$ is symmetric
My answer so far:
QUESTION 1
$det(A) = 0$
$0 = (1)(k-2)(k+1)(3)$
$0 = (k-2)(k+1)(3)$
$0 = (k-2)(3k+3)$
$0 = 3k^2 + 3k - 6k -6$
$6 = 3k(k-1)$
$6/3k = k-1$
$2k = k - 1$
$k = -1$
QUESTION 2:
I'm confused on how to even figure this question out, where exactly would I begin?
I'm not sure if I did this the correct way, any advice would be greatly appreciated.
Comment: $0=(k-2)(k+1)(3)\implies k-2=0$ or $k+1=0\implies k=2$ or $-1$
Comment: $A A^T$ is always symmetric, because $(A A^T)^T = (A^T)^T A^T = A A^T$.
Comment: Note:  after answers were given, the question was edited to add a second question
Comment: also, $6/(3k)=2/k,$ not $2k$, though for $k=-1$ they happen to be the same
Comment: You made an error in the next-to-last step, likely because of the way you wrote the left-hand side of the previous equation: it's $\frac6{3k}$, not $\frac63k$. However, as @J.W.Tanner pointed out, you could have stopped immediately after writing down an expression for the determinant since its already factored.
Answer: For a triangular matrix the determinant is the product of the diagonal elements.
By consequence the determinant is null each time a diagonal element is null.
In your case this happens for $k=2$ and $k=-1$.
Answer: Dividing by your variable is always a bad idea
for example if you divide
$0=x*(x-5)$
by $x$ you get $x=5$ as a solution but not $x=0$
Now to your problem:
The idea is right but
$$0 = (k-2)(k+1)$$
gives you two solutions: $x=2,x=-1$ since for each one of this values one of your factors becomes 0 and therfore your whole product.
Answer: You had the right idea,
but when you got to $0=(k-2)(k+1)(3)$,
you should have concluded that $k-2=0$ or $k+1=0$; i.e., $k=2$ or $-1$.
Comment: The mistake actually is that he claims that $6/(3k)=2k$.
Comment: @DietrichBurde:  yes, I commented about that above before I saw your comment here
Answer: I believe any k satisfies the second question.
Multipling $A*A^T$ gives the matrix:
$$
\begin{bmatrix}
1 & 3 & k-1 & 2\\
3 & k^2-4*k+13 & 2*k-1 & 6 \\
k-1 & 2*k-1 & 2*k^2-3 & 3*k-1\\
2 & 6 & 3*k-1 & 14 \\
\end{bmatrix}
$$
Which will be symmetric regardless of the value of k.


An issue when using trunc function

Question: i have an issue when i using this function in R. I don't know why trunc(z) is 637 instead of 638 as x = 51/80*100.
x <- 51/80*100
x
#[1] 63.75

z = abs(x)*10^1
z = z + 0.5
z
#[1] 638
z = trunc(z)
z
#[1] 637
z = z/10^1
z
#[1] 63.7

Answer: As @d.b already pointed out that z is numeric and with numerics you don't necessarily have what you see.
Check
formatC(z, digits = 14, format = "f")
#[1] "637.99999999999989"

(You might have to change digits argument on your system)
Also if you convert it to integer, you get
as.integer(z)
#[1] 637

You can round the numeric before using them
trunc(round(z))
#[1] 638

An issue when using trunc function


What are good warm-up exercises for guitarists?

Question: I do not generally warm up, but then I don't really stretch my playing as much as my ear when I practice. But I know I should.
What are some good exercises to do before I start getting into the details of working for speed, developing scales, etc.?
Answer: I usually warm-up with a slow-blues I found in a magazine years ago. Here's a video. Can't really notate more, because it's never the same after this.

It's pretty easy to change the drone to A for the second verse and then pop a B7 and do a lick to turn it around. It's really hard to make your fingers slow down for this. But it really sounds nice slow and sweet, too. But it's so simple that the temptation to jazz it up can be irresistible.
Illustration made with MuseScore. (Haven't figured out how to make the title smaller, yet.)
Comment: [meta help question](http://meta.music.stackexchange.com/q/487/1344) on the jTab formatting conundrum.
Answer: My favourite one because it really helps to warm up fingers. Play the first bar and then simply go one string down. Do this until you reach the last string.
Answer: Beginner here, I also warm up with blues, I am not sure about how to name what I play but it looks like that (I copied the notes from a 12 bar progression):

    E|----------------
    B|----------------
    G|---------25---47
    D|----25-26---48--
    A|--26--2----4----
    E|-3--------------

I do it because my left hand needs to move vertically and horizontally (which is the hardest for me right now).
Answer: This is a good warm-up exercise to improve your finger dexterity on one string. The jumps from the 4th finger to your 1st are particularly tough.
Follow the fingering guide above:

    1 2 3 2 3 4   1 2 3 2 3 4
E|--1-2-3-2-3-4-|-3-4-5-4-5-6-| ...
Answer: Thats my warmups (first similar to Craig Curtis's). But they're little harder, and can be used also as an exercise, not only as warmup.
Second one is about right-hand picking, and holding barre-chords.
Answer: I usually warm up playing scales. Sometimes I play a single major scale form in a cycle of fifths. Other times I will just play through major and pentatonic scale forms in one key up and down the neck. Then I usually just noodle around on some phrase or song with which I'm familiar. Caveat: I'm an amateur and have no sound reason for why this is good. It just works for me.
Answer: In addition to the examples shown here, I would advise you to warmup without the guitar, stretching your hands, wrist and shoulders, but also and in my opinion more importantly, to warm DOWN after a big session of playing. I used to hurt myself when I was a beginner, as my left wrist would go from "inside" flexion during hours to a sudden outside flexion.
The content of the exercise itself is not that important, and chromatisms are quite boring and frankly quasi-useless as a guitarist. What is important is to start slow, simple, with some are of your guitar playing which is mastered. It might be simple chords, it might be polyphonic tapping or tremolo, it depends on your personnal practice.
A good video description of hand stretching
Answer: I use arpeggios: major 7, minor 7, and dominant 7 in 5 positions (essentially CAGED).  Go through the circle of fifths, playing major 7ths in one of the 5 positions; repeat for other positions; repeat for minor 7 and dominant 7.  Practice with a metronome, and gradually increase speed (over weeks/months/years).
At the moment, I'm also working on tremolo picking, playing a scale using 4 sixteenth notes per degree of the scale (also, of course, with a metronome).
Answer: I saw some really good answers and I agree with some of them.
My favorite warm up practice helps strengthen all my fret hand fingers, as well as providing coordination with pick hand and fret hand.
Starting on the
low E string 2 - 3 - 4 - 5
then the A 2 - 3 - 4 - 5
then the D 2 - 3 - 4 - 5
continue through all six strings and back up again.
Next move up one fret, so... 3 - 4 - 5 - 6 , then another fret 4 - 5 - 6 - 7 , all the way to 12 - 13 - 14 - 15 and back down 15 - 14 - 13 - 12. This can be boring for your picking hand, so try all down strokes, or all up strokes, or alternate picking ( down - up - down - up ).
When I first learned this technique, I had a hard time getting clean sounding notes out of my pinkie ( since I used it so little ). Then speeding up was tricky, but this exercise pays off!
One last thing I can recommend, is alternate the order your four fret fingers ascend and descend. For example:
......2 - 3 - 4 - 5
then 3 - 4 - 5 - 2
then 4 - 5 - 2 - 3
last 5 - 4 - 3 - 2
This helps train each of your fret fingers to work independently and quickly. Try it and you may find a fun new exercise.
Answer: This warm up exercise helps stretch your fretting hand. I found a picture that explains http://www.fretjam.com/image-files/hand-stretch3.jpg Push as far as you can and use all three crooks of fingers.
Answer: Play violin and flute music: Paganini 24th and 5th caprice, Vivaldi G minor summer storm, B minor flute Bach, for tapping and stretch play EVH, Satriani (Midnight and Forgotten part 2) for arpp-s --- YJM, for developing strong thumb --- Hendrix, SRV. All dull and dumb chromatic exercises are better substituted with an outstanding R-K flight of a bumble bee, perform your own cover variant to fit your hand. This music will be with you through all the life and will impress people around.
 And play the other instruments to teach the ear and hands.
Comment: Hi Vassia - if you read the other answers to this question, you will see the sort of thing that is expected. Your post doesn't really give the OP anything useful.


how to a translatable string in drupal theme?

Question: I want to put a string as a signature in drupal theme I am working on. the website is multilingual and the string should be translated based on the current language of the website. I don't know how to do it.
my drupal version is 6.
Would you help me?
Answer: The first step to translate a string used from a module, or a theme is using t() for every string that needs to be translated. Remember that the first argument given to the function is a literal string containing a phrase in English. This means that the following calls to t() are not correct.
// The string is a concatenation of literal strings.
$error = t('This example, ' . "doesn't work.");

// Also in this case there is a concatenation of literal strings.
$errno = 15;
$error = t("Error number $errno received while translating a string.");

// This could work, provided that another function calls t() using a
// literal string that is equal to the string returned from the function.
$error = t(mymodule_get_error());

The second step is providing the translation of the string passed to t(). If the theme is hosted on Drupal.org, then the translation will be provided from translators on http://localize.drupal.org.
Otherwise, you need to translate the string on admin/build/translate/search.
You can look for the string to translate searching for untranslated strings, or entering a string.
Comment: The problem with this approach is that it doesn't filter by strings in your theme. It bundles those strings with Drupal core strings so that you're stuck with a bloated list of strings that you would normally want to export to a translator.
Answer: you should use something like t('your string');


Function from useState is usable if using props drilling but not from useContext

Question: Good morning,
I am converting an application over from props drilling to useContext and am encountering a strange issue.  A function I have assigned to a prop is seen as a function as a drilled prop but not when pulled out of a created context.  I have other functions in that same context that work just fine.  Below you will find the portions of my components that are relevant to the question:
root component:
import UserContext from '../context/userContext';
/*...imports
*/

const wageTrak = (props) => {
const [userState, setUserState] = useState({});
const [jobState, setJobState] = useState({});

                                //this is usable as a function
const contextArr = [ userState, setUserState,
                               //this is not
                     jobState, setJobState ];

/* ...more code
 *
 */

let userData = "Loading...";

if (userState) {
    userData = <User
        //I am trying to eliminate this but I can't seem to
        setJob={setJobState}
    />
}

return (
    <React.Fragment>
        <UserContext.Provider value={[...contextArr]}>
             ....
            <Route
                    path="/wagetrak/"
                    render={() => userData}
                />
             . . .
        </UserContext.Provider>

User component:
import UserContext from '../../context/userContext';
//imports

const user = (props) => {
const [ showModal, setShowModal ] = useState({});
const [ userState ] = useContext(UserContext);

/*
 * functions
 */

return (
    <React.Fragment>

             clickedNameHandler()}>

{userState.name}

                {window.location.pathname === "/wagetrak" &&

 toggleModal()}>
}

Your tax rate: {userState.taxRate * 100}%

 addJobHandler()}>
                    Add Job

                <Jobs setJob={props.setJob} />

</React.Fragment>
);
}

Jobs component:
import UserContext from '../../context/userContext';
//imports
                                 //When I attempt to use this as a function I get a compilation error
const [ userState, setUserState, setJobState ] = useContext(UserContext);

/*The change I'm trying to make
 *const selectJob = setJobState;
 */

const jobClickedHandler = (j) => {
    //I'm trying to use it here
    props.setJob(j);
    //selectJob(j);  <---this instead of props.setJob(j);
    props.history.push("wagetrak/job");
}

//...

const deleteJob = (name) => {
    fetch(
        "http://localhost:8080/wageTrak/" + userState.id + "/" + name,
        {
            method: 'DELETE',
            headers: {
                'Content-type': 'application/json',
                'Access-Control-Allow-Origin': 'localhost:3000/',
                'Access-Control-Allow-Methods': 'DELETE'
            },
        }
                                          //this works as intended
    ).then(res => res.json()).then(res => setUserState(res));
}

//...

return (

            {userState.jobs && userState.jobs.map(j => (

                            jobClickedHandler(j)
                        }>{j.name}

 deleteClickedHandler(j.name)}>

            )
            )}

);
}

Context file:
import React from 'react';

const userContext = React.createContext({});

export default userContext;

Changing the code to what you see commented out above results in the following error:

TypeError: selectJob is not a function
at jobClickedHandler (Jobs.js:14)
at onClick (Jobs.js:44)...

What am I doing resulting in setJobState not being recognized as a function but setUserState is?
If I need to include more code please let me know.
Thanks in advance.
Answer: Change array destructuring from
const [ userState, setUserState, setJobState ] = useContext(UserContext);
to
const [ userState, setUserState, jobState, setJobState ] = useContext(UserContext);
And even you can directly give your variable name e.g
const [ userState, setUserState, jobState, selectJob ] = useContext(UserContext);
Since array destructuring works on index rather than property name.


SQL Server: remove list entry from the string of another list

Question: I am sure that title is a bit confusing. Basically I have one table that has a column containing formation like "xx 123 Rg 43" and one that contains information like "Rg".. and if an entry from table 2's column is contained in the string contained in Table 1 then I need just  that entry removed.. leaving us with "xx 123  43"
Currently I am using:
update [Table1]
set [Col1] = case
                when (select * from [Table2]
                      where charindex(' ' + [Col2] + ' ', [Col1]) > 0) is not null
                   then replace([Col1], (select * from [Table2]
                                         where charindex(' ' + [Col2] + ' ', [Col1]) > 0), '')
                   else [Col1]
             end

And this works fine, but fails if this query
select *
from [Table2]
where charindex(' ' + [Col2] + ' ', [Col1]) > 0

returns more than 1 row with this error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

But I do need every match removed. Help!
Comment: Your fundamental problem is with your data structure.  Do not use strings to store lists of items.  SQL has a great data structure for lists.  It is called a table.
Answer: You seems want :
update t1
     set col1 = (case when exists (select 1
                                   from t2
                                   where charindex(t2.col2, t1.col1) > 0)
                                   )
                      then stuff
                      else t1.col1
                  end)

Answer: Have you tried something like this?
update actual
set column1 = replace(column1, valueToReplace, '')
from TableWithActualData actual
inner join TableWithValuesToFind find
on actual.column1 like '%' + find.valueToReplace + '%';

See SQL Fiddle Example.
That said; this could have unpredictable behaviour... Suppose you have a value catamaran and you have logic to replace the words cat and tamara.  If you replace cat first you're left with amaran, which doesn't contain tamara.  If you replaced tamara first you're left with can, which doesn't contain cat.  What should the behaviour be in such scenarios?
The above code sort of avoids this; by only acting on the first match... However this means that even in scenarios where there are multiple valid replacements (e.g. replacing cat and ran in catamaran) you still won't get your expected result (ama), but rather the result will depend on which of cat or ran were found first (giving amaran or catama accordingly).
There's no way for you to specif icy this order either; the database will just operate on whichever results are returned first.
To avoid that, you're best off replacing one value at a time, in a predefined order... e.g. SQL Fiddle.
declare @valueToReplace nvarchar(256)

declare replaceValueCuror cursor for
select valueToReplace
from TableWithValuesToFind
order by priority

open replaceValueCuror

fetch next from replaceValueCuror
into @valueToReplace

while @@fetch_status = 0
begin

    update TableWithActualData
    set column1 = replace(column1, @valueToReplace, '')
    where column1 like '%' + @valueToReplace + '%'

    fetch next from replaceValueCuror
    into @valueToReplace

end

close replaceValueCuror

deallocate replaceValueCuror


omega 4 sprites css

Question: I am using omega 4 theme. To generate css sprites I have used following in my layout sass file
<code>@import "social-icons/*.png";
@include all-social-icons-sprites;
</code>
It generated this file social-icons-s8394565a36.png in generated folder in my images folder, but I cant find the css for my icons.
Is it suppose to generate the CSS also if so where can I find that ?? I have checked almost all directories in my SASS\LAYOUT\MY-LAYOUT directory but it seems that no css is generated for sprites
Answer: Don't be confused by the fact that you're using Omega 4, which doesn't have much to do with the spriting aside from the fact that it allows you to use Compass to compile its styles.
You can find great write-ups on Compass spriting here and here.
Once you've created the spritesheet with:
<code>@import "social-icons/*.png";
</code>
You can use the sprites like this, where you have a file at "social-icons/facebook.png":
<code>.facebook-icon {
  @include social-icons-sprite(facebook);
}
</code>
Alternatively (my preference), you can use spritesheets like this:
<code>$social: sprite-map("social-icons/*.png");

.facebook-icon {
  background: sprite($social, facebook);
}
</code>
And you can get even more hands-on:
<code>.facebook-icon {
  background-image: sprite-url($social);
  // Offset the facebook sprite x-position by 2px and y-position by -6px.
  background-position: sprite-position($social, facebook, 2px, -6px);
}
</code>

omega 4 sprites css


How to find limit of a sequence of functions $f_n(x)=\frac{x^n e^x} {n+1}$?

Question: How to find limit of a sequence of functions $f_n(x)=\frac{x^n e^x} {n+1}$?  $$\lim_{n\to \infty} \frac{x^n e^x}{n+1}$$
I have no idea how to evaluate this limit. I thought maybe I should rewrite $e^x$ using $\sum_{n=0}^{\infty} \frac{x^n}{n!}$ but I am not sure whether I can do that or whether it would even help. If it is possible to evaluate the limit without L'Hospital's rule that would be the prefered way but I actually cannot see how L'Hospital would help with this problem.
Comment: Is it a typo in the question? $e^x$ does not depend on $n$, so that you can just pull it out of the limit.
Comment: That's a different question than the one posed.
Comment: Most things in that limit are constant (even $x$).  LHop works here.
Comment: No typo. I know I can pull it out but that's the task so I thought I was there for a reason so I kept it there.
Comment: Is $x$ supposed to be positive?
Comment: Well the the task is to find a limit of a sequence of functions $f_n(x)=\frac{x^n e^x}{n+1}$
Comment: Thanks. I edited the question.
Answer: We get the same result if we compute
$$e^x\lim_{n\to+\infty}\frac{x^n}{n}$$
If $|x|\le 1$, it gives zero.
If $ x>1$, we write it as
$$\lim_{n\to+\infty}e^{n(\ln(x)-\frac{\ln(n)}{n})}=+\infty$$
If $x<-1,$ the limite doesn't exist,
since for even indices, we find $+\infty$ ,and for odd ones, it gives $-\infty$.


Escrever em um arquivo .txt com laço 'for' no Python

Question: Preciso que um arquivo .txt guarde o último serial gerado, para das próximas vezes que for executado esse arquivo ser lido e continuar a sequencia. Ou seja, se o ultimo serial(serial2) gerado for o número 6 quero que seja guardado o número 6 no txt para que na proxima execução do código ele inicie no 6. Estou usando o txt como um "Banco de Dados".
def GerarSerial(start_at=int(open('ultimaos.txt', 'r').readlines(0)[0])+1):
    serial = f'{start_at:0>5}'
    serial2 = f'{start_at+1:0>5}'
    with open('ultimaos.txt', 'w') as ultimaosarquivo:
        ultimaosarquivo.write(serial2)
    with open('ultimaos.txt', 'r') as ultimaosarquivo:
        ultima_os = ultimaosarquivo.readlines(0)[0]
    return f'{ultima_os:0>5}'

if __name__ == '__main__':
    for x in range(3):
        GerarSerial()
        print(GerarSerial())

ultimaos.txt:
00006

Porém ao executar o código ele apenas repete o valor 3 vezes.
Comment: Artur a pergunta não está muito clara, da para melhorar? Vlw!
Answer: O problema é que você definiu um valor default para o parâmetro start_at. E segundo a documentação, esse valor só é avaliado uma vez, quando a função é criada, e depois não muda mais:

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call.

Ou seja, quando você cria a função, o start_at terá o valor default com base no conteúdo atual do arquivo, somado com 1. E para todas as chamadas feitas sem nenhum argumento, será usado o valor inicial que ele tinha. Por isso que, não importa quantas vezes você chame a função, o mesmo valor está sendo usado.
Sendo assim, retire este parâmetro. Dentro da função você tem que sempre ler o valor atual e somar 1:
def GerarSerial(arquivo='ultimaos.txt'): # acho que faz mais sentido o nome do arquivo ser um parâmetro
    try:
        # tenta ler o arquivo
        with open(arquivo, 'r') as arq:
            atual = int(arq.read()) # como o arquivo só tem uma linha, lê tudo
    except OSError:
        # se o arquivo não existe, começa um novo serial
        # mas também poderia dar erro, você decide o que faz mais sentido para o seu caso
        atual = 0

    # calcula o novo serial (no caso, soma 1 com o atual)
    serial = f'{atual + 1:0>5}'
    with open(arquivo, 'w') as arq: # atualiza o arquivo
        arq.write(serial)
    return serial

for _ in range(3):
    print(GerarSerial())

Como o arquivo sempre tem apenas uma linha, não precisa de readlines para ler todas as linhas e depois pegar a primeira. Basta usar read para ler tudo (mas também poderia ser readline() - no singular - para ler a primeira linha).
Claro que faltou verificar se o conteúdo é um número mesmo, mas a ideia geral é essa: se o arquivo não existe, começa um novo serial (mas poderia dar erro, você decide o que faz mais sentido para o seu caso), e se existe, lê o conteúdo dele.
Depois basta somar 1 e gravar o novo serial no arquivo, e retornar este serial. E veja que não precisa abrir de novo o arquivo para ler o que você acabou de gravar, pois isso já está na variável serial.


iphone prevent autorotation but only when keyboard is showing

Question: Is there a way to prevent auto-rotation from a view controller when the keyboard is showing?
I don't want to capture the notifications and handle all drawing by hand if possible.
Edit:I found that the root view controller in the chain was preventing the shouldAutorotateToInterfaceOrientation: message from coming down the pipe. Once it was taken away at the root view controller level and left to the sub-view controllers to handle it worked quite well.
Answer: Does the editing use a UITextField? If so, have you tried using the UITextFieldDelegate method textFieldShouldBeginEditing: as a place to modify a flag referenced by shouldAutorotateToInterfaceOrientation: ?


How to stream KML into ac-layer in angular-cesium

Question: I have an angular-cesium application, and I'm trying to stream kml data into the globe layer. I can't find any tutorials or help in the angular-cesium docs.
here is what I have so far:
app.ts
import { KmlService } from './kml.service';
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { CesiumService, MapsManagerService } from 'angular-cesium';

import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
  cesiumViewer;
  kml$;

  constructor(private Cesium: CesiumService,
              private viewersManager: MapsManagerService,
              private kmlService: KmlService) {}

  ngOnInit() {
    // console.log(this.cesiumViewer);
  }

  ngAfterViewInit() {
    this.kml$ = this.kmlService.getKml()
      .map((data) => data);
  }
}

app.html
<ac-map id="main-map">
  <ac-layer acFor="let kml of kml$">
  </ac-layer>
</ac-map>

kml.service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'

@Injectable()
export class KmlService {

  constructor(private http: HttpClient) { }

  getKml() {
    return this.http.get('http://172.16.1.254:8080/rest/kml/accept/all', { observe : 'body', responseType : 'text'});
  }

}

the kml output is like so:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>

</Pair>
<Pair><key>highlight</key></Pair>
</StyleMap>

...etc...

this error, which I assume means I'm just doing this totally wrong:
ERROR Error: ac-layer: must initialize [context]
    at AcLayerComponent.webpackJsonp.../../../../angular-cesium/bundles/angular-cesium.umd.js.AcLayerComponent.initValidParams (angular-cesium.umd.js:2670)

Comment: I wanted to add the tag angular-cesium to the post but I don't have enough reputation. angular-cesium is an npm package the helps the integration of cesium.js and angular, and I believe it deserves it's own tag because it has a fairly large documentation, specialized usage within angular, and differs from the questions tagged with just 'cesium'
Answer: currently angular-cesium doesnt support KML as angular component. but you can use pure cesium API.
class YourComponent {
 constructor(private mapsManagerService: MapsManagerService) {
   const viewer = mapsManagerService.getMap().getCesiumViewer()
   viewer.dataSources.add(
     Cesium.KmlDataSource.load(
       '../../SampleData/kml/bikeRide.kml',options
     )
   )
  }
}

answered here:
https://github.com/TGFTech/angular-cesium/issues/123


Structure within a Class

Question: I have a class with a structure under private.
How do I access the data members of that structure?
  class ClassStruct
  {
  private:
     struct Struct
     {
        std::string time;
        int temp;
     };
  public:
     ClassStruct();
  };

Here is what I tried:
struct Struct o;
ClassStruct object;
cout << "Enter time (hh:mm): ";
cin >> object.o.time;

But it shows an error on "o".
Comment: "I tried to declare a variable of structure but I guess that's wrong" - nope, that's correct. Show us.
Comment: @hakuna12 important tip when asking for help: When you say you got "an error", give the details. Error messages are very precise and technical and they reveal the problem.
Comment: Struct object; object.temp; this shows an error...
Comment: @hakuna12: So what's the error? Is the declaration in a member or friend of `ClassStruct`? If not, then you can't access the `Struct` name, since it's private.
Comment: struct Struct o;
 ClassStruct object;
 cout << "Enter time (hh:mm): ";
 cin >> object.o.time;
i tried this. but it shows an error on "o"
Comment: And post a minimal test case with which the error can be reproduced.
Answer: You can only access this struct from within the declaring class implementation. In your example the only place you can access it is in the constructor for ClassStruct.
EDIT to try and explain what people are asking you:
In ClassStruct.h:
class ClassStruct
{
private:
   struct Struct
   {
      std::string time;
      int temp;
   };
public:
   ClassStruct();
   void test(){
     Struct good; // This will work.
     good.temp = 5;
   }
};

In ClassStruct.cpp
ClassStruct::ClassStruct(){
   Struct alsoGood;
   std::cout << "Also Good Here" << std::endl;
}

void nonClassFunction(){
  ClassStruct::Struct bad; // compiler error
}

In AnyOther.cpp
void wontWork(){
  ClassStruct::Struct alsoBad; // compiler error.
}

Comment: And see Vlad's answer below on creating a field of your struct.
Answer: To access data members of the structure you need to define an object of this structure. You can define an object of this structure as a data member of the enclosing class or as an object created in methods of the class.
For example
  class ClassStruct
  {
  private:
     struct Struct
     {
        std::string time;
        int temp;
     } obj1;
  public:
     ClassStruct();
     void SomeMethod()
     {
        Struct obj2;
        // some operations with obj2
     }

  };

Structure within a Class


Script para desligar o computador ao fechar um determinado programa

Question: Como faço para criar um script para que quando a janela do rdesktop for fechada o computador seja desligado?
Answer: André Cabral
Seria fechar um programa ou uma janela?
Considerando um programa qualquer:
Crie um arquivo com o nome que você quiser, os exemplos abaixo referem-se ao ubuntu:
touch desliga_automatico

Coloque a permissão para executar:
sudo chmod +x desliga_automatico

Coloque o código abaixo:
#!/bin/sh
PROGRAMA='rdesktop' #nome do programa que deseja monitorar

while [ TRUE ]
do
    if ps ax | grep -v grep | grep $PROGRAMA > /dev/null
    then
        #echo "$PROGRAMA está rodando"
    else
        #echo "$PROGRAMA não está rodando"
        sudo reboot
    fi
    # colocamos o sleep para o processador ter tempo para realizar outras tarefas
    # você pode colocar o tempo que achar melhor (em segundos)
    sleep 120
done

No caso de ser uma janela e não um programa:
#!/bin/sh
PROGRAMA='rdesktop'

while [ TRUE ]
do

    if xlsclients | grep -v grep | grep $PROGRAMA > /dev/null
    then
        #echo "$PROGRAMA está rodando"
    else
        echo "$PROGRAMA não está rodando"
        sudo reboot
    fi
    # colocamos o sleep para o processador ter tempo para realizar outras tarefas
    # você pode colocar o tempo que achar melhor (em segundos)
    sleep 120
done

Se isso atender sua necessidade você pode coloca-lo em:
sudo mv desliga_automatico /etc/init.d/

para ele iniciar toda a vez que o computador for iniciado
Espero ter ajudado.
Comment: Edita a resposta. Ela está boa, mas colocar em `/etc/init.d/` não basta pra rodar a aplicação no *boot*. Além de dar permissão, tem que atualizar os *runlevels* E pra rodar no *boot* tb tem que alterar o cabeçalho da aplicação citando os *runlevels*, etc.
Answer: #!/bin/sh
PROGRAMA='rdesktop'

while [ TRUE ]
do

    if xlsclients | grep -v grep | grep $PROGRAMA > /dev/null
    then
        echo "$PROGRAMA está rodando"
    else
        echo "$PROGRAMA não está rodando"
        sudo reboot
    fi
    # colocamos o sleep para o processador ter tempo para realizar outras tarefas
    # você pode colocar o tempo que achar melhor (em segundos)
    sleep 120
done

PS: Tinha uma linha comentada antes do Else por isso o codigo da erro, agora ta certo!


Issues when installing th json framework on xcode4

Question: Hello
I am trying to install json framework. According to installation instructions I have to copy all the classes from json-framwork/classes in my project! I did that and I am getting this error:

ld: duplicate symbol
  _OBJC_METACLASS_$_SBJsonParser in /Users/user/Library/Developer/Xcode/DerivedData/testhttp-eavsbuatbfoagsgbqfnevfpjxxfc/Build/Intermediates/testhttp.build/Debug-iphonesimulator/testhttp.build/Objects-normal/i386/SBJsonParser-4254E5B76E32172.o
  and
  /Users/user/Library/Developer/Xcode/DerivedData/testhttp-eavsbuatbfoagsgbqfnevfpjxxfc/Build/Intermediates/testhttp.build/Debug-iphonesimulator/testhttp.build/Objects-normal/i386/SBJsonParser-46310C881BFA9776.o
  for architecture i386 collect2: ld
  returned 1 exit status Command
  /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2
  failed with exit code 1

What I am doing wrong here?
Answer: Please have a look at:
iPhone: Duplicate Symbol Error?
Select the project navigator in the right sidebar. Double click your project(top element).
Now open the build phases tab. There is a section which is called Compile Sources. Open it an check if there is a duplice entry of the file which the error refers to.
My Installation of the json-framework
Just added these files to my project

Each .m file is here only once

In the class I need JSON parsing I'll just import:
<code>#import "JSON.h"
</code>
Comment: The issue is when I have facebook sdk and json in the same project
Comment: I have duplicates but not in the same folder. I am using fb sdk which has "json" folder and there are 5 classes with the same name. If i try to delete these classes from the original json framework I am getting other error.What are you suggest me?
Comment: @It doesn't matter if you have the same class in many places, for compilation it'll only accept one unique class. What other errors are you getting?
Comment: @user622203 I some pictures to illustrate how I installed the framework.
Comment: this is the error:ld: duplicate symbol _OBJC_METACLASS_$_SBJsonParser in /Users/mixalismavris/Library/Developer/Xcode/DerivedData/testhttp-eavsbuatbfoagsgbqfnevfpjxxfc/Build/Intermediates/testhttp.build/Debug-iphonesimulator/testhttp.build/Objects-normal/i386/SBJsonParser-106FA3F38C16E67D.o and /Users/mixalismavris/Library/Developer/Xcode/DerivedData/testhttp-eavsbuatbfoagsgbqfnevfpjxxfc/Build/Intermediates/testhttp.build/Debug-iphonesimulator/testhttp.build/Objects-normal/i386/SBJsonParser-46310C881BFA9776.o for architecture i386
Comment: @user622203 could it be that you already have the json framework installed with the facebook sdk you've installed? You should remove the json framework you added recently and see if you can still use it.
Comment: I found the compiled sources in the targets group (icon looks like a bullseye), there were duplicates in there which I removed.
Comment: I have nearly the same problem, but I have got 2 Subprojects which both use SBJson. So I have no duplicates in the build phases, but still the same linking issue. Any ideas?
Answer: I just erase the .m and .h files from JSON Framework wich the compilator was giving me errors, at the end I just keep from the JSON Framework:  NSObject+SBJSON, NSSTring+SBJSON .h and m.
This worked for me, I hope it helps :D


Ovechkin's +/- in his recent hat trick game

Question: Alex Ovechkin had 3 goals and 1 assist in Saturday's 5-1 win over the New Jersey Devils. The Devils only scored 1 goal so I'd assume his minimum +/-, assuming he was on the ice when the Devils scored, is +3 (4 points for - 1 against). But he is listed as +2. Is this a mistake, me being stupid, or missing something about +/-?
Comment: See http://sports.stackexchange.com/questions/2215/in-ice-hockey-how-is-plus-minus-calculated for more details about how +/- is calculated.
Answer: Power play goals don't count towards the scoring team players' +. One of Ovechkin's goals and his assist were both on power play.


How find empty input value in jquery

Question: I have two checkboxes the one checkbox value is 1 and the second one is 0.
One checkbox is for enabling and other for disabling. Now I want to identify when a user clicks on Disable checkbox How I will get Disable checkbox value and if a user clicks on Enable box then how I will get Enable Checkbox value
<input type="radio" name="forgot_pass" class="forgot_pass_enable" value="1" checked>

<input type="radio" name="forgot_pass" class="forgot_pass_disable" value="0">

I have tried This code but it's not working for me any help
$("body").on('change', '.forgot_pass_enable', function(event)
{
  event.preventDefault();
  /* Act on the event */

  if($('.forgot_pass_enable').val().length > 0)
  {
    var status = 1;

    console.log(status);
  }

  if($('.forgot_pass_disable').val().length > 0)
  {
    var status  = 0;

    console.log(statusasdad);
  }
});

Answer: Neither of the elements you've shown are checkboxes - they are radio inputs.
To get the selected value apply the same class to both elements, then hook the change event to that class. Then you can simply read the value from it, like this:

$("body").on('change', '.forgot_pass', function(e) {
  e.preventDefault();
  var status = this.value;
  console.log(this.value === '1' ? 'enabled' : 'disabled', status);
});

<input type="radio" name="forgot_pass" class="forgot_pass" value="1" checked="checked">

<input type="radio" name="forgot_pass" class="forgot_pass" value="0">

If you did want to use a checkbox for this, which would be more applicable for an enable/disable switch, then the method is the same except you look for the checked property instead:

$("body").on('change', '.forgot_pass', function(e) {
  e.preventDefault();
  var status = this.checked ? '1' : '0'
  console.log(status);
});

<input type="checkbox" name="forgot_pass" class="forgot_pass" value="1" checked="checked">

How find empty input value in jquery


Como escrever uma agenda em ordem alfabética de Nomes, se a estrutura dicionário não tem ordem?

Question: Escreva um programa que receba quantas entradas o usuário desejar e depois
crie um novo contato para cada entrada (Nome, Telefone, Endereço, Email), e
por fim imprima, em ordem alfabética, a agenda de contatos :
Nomes = []
Telefones = []
Endereços = []
Emails = []
Agenda = {"Nome": Nomes,"Telefone":Telefones,"Endereço":Endereços, "Email": Emails}
entrada = ""
while entrada != "s":
    print("Bem-vindo a nossa Agenda!!!!!")
    nome = input("Digite o nome: ")
    Nomes.append(nome)
    telefone = input("Digite o telefone: ")
    Telefones.append(telefone)
    endereço = input("Digite o endereço: ")
    Endereços.append(endereço)
    email = input("Digite o email: ")
    Emails.append(email)
    print(Agenda)
    entrada = input("Deseja sair? ")
    if entrada.lower() == "s":
        print(Agenda)
        break

A agenda é um dicionário e ele não tem ordenação! Como posso imprimir a agenda em ordem alfabética de nomes, seguida das repectivas outras informações (Telefone, Endereço, Email) ?
Answer: nomes = []
telefones = []
endereços = []
emails = []

Agenda = {"Nome": nomes,
          "Telefone": telefones,
          "Endereço": endereços,
          "Email": emails
          }

entrada = ""
while entrada.lower() != "s":
    print("Bem-vindo a nossa Agenda!!!!!")

nome = input("Digite o nome: ")
nomes.append(nome)

telefone = input("Digite o telefone: ")
telefones.append(telefone)

endereço = input("Digite o endereço: ")
endereços.append(endereço)

email = input("Digite o email: ")
emails.append(email)

entrada = input("Deseja sair? ")
if entrada.lower() == "s":

    ordenada = sorted(Agenda['Nome'])

    for nome in ordenada:
        i = Nomes.index(nome)
        for chave, valor in Agenda.items():
            if chave == 'Email':
                print('{}: {}.\n'.format(chave, valor[i]))
            else:
                print('{}: {}.'.format(chave, valor[i].title()))

Comment: O que faz o zip? Não entendi
Comment: A agenda não está em ordem alfabética de nomes!
Comment: O zip serve para agregar os elementos de um iterador. Nesse caso ele pega uma posição das suas listas, por exemplo, a posição 0,  e  os reúne numa lista de tuplas, onde cada tupla é um contato. O laço for percorre cada tupla e exibe seu conteúdo.
Answer: Nomes = []
Telefones = []
Endereços = []
Emails = []
Agenda = {"Nome": Nomes,"Telefone":Telefones,"Endereço":Endereços,
          "Email": Emails}
entrada = ""

print("Bem-vindo a nossa Agenda!!!!!")
while entrada != "s":

    nome = input("Digite o nome: ")
    Nomes.append(nome)
    telefone = input("Digite o telefone: ")
    Telefones.append(telefone)
    endereço = input("Digite o endereço: ")
    Endereços.append(endereço)
    email = input("Digite o email: ")
    Emails.append(email)
    #print(Agenda)
    entrada = input("Deseja sair? ")
    print()
    if entrada.lower() == "s":
        ordenada = sorted(Agenda['Nome'])
        for nome in ordenada:
            print()
            print("Nome: ",Agenda['Nome'][Nomes.index(nome)])
            print("Telefone: ",Agenda['Telefone'][Nomes.index(nome)])
            print("Endereço: ",Agenda['Endereço'][Nomes.index(nome)])
            print("Email: ",Agenda['Email'][Nomes.index(nome)])
            print()
        break

Answer: Nomes = []
Telefones = []
Endereços = []
Emails = []
Agenda = [] # Agenda Agora é uma lista que recebe dicionários
entrada = ""
count = 0 #Contador

# Condição para funcionamento
while True:
    print("Bem-vindo a nossa Agenda!!!!!")
    nome = input("Digite o nome: ")
    telefone = input("Digite o telefone: ")
    endereço = input("Digite o endereço: ")
    email = input("Digite o email: ")

    # Lista
    Agenda.append({"Nome": nome,"Telefone":telefone,"Endereço":endereço, "Email": email})

    # Contador conta quantos contatos foram adicionados na agenda
    count+= 1
    print(f'Foram adicionados {count} itens na Agenda!')

    # Verifica se quer sair
    entrada = input("Deseja sair? ")
    if entrada.lower() in ('s', 'y'): # Você pode digitar sim, s, Sim, sim, y, Yes, etc
        break

# Ordena a lista Agenda por Nomes
Agenda.sort(key=lambda Agenda: Agenda["Nome"])
for i in Agenda:
    print(i)


Move from Activity class to AppCompatActivity class

Question: I'm trying to develop an Android Application that will play through a video and then transition to another activity.
The issue I'm having is that the video needs to be played FullScreen and in order to do so I had to switch the extends from "AppCompatActivity" to "Activity" otherwise the program would crash when trying to run full screen.
So when I transition to the next activity I had to call that class with extends Activity as well.
Now when I try to implement a drawer sidebar I'm running into issues because the class doesn't extend AppCompat, and is having explicit issues with "getSupportActionBar"
(The video plays, and transitions to the second screen without issue it's just proceeding from there that I'm caught on)
Is there any way to have my second activity extend AppCompat, without it crashing? Or if anyone is aware of a more effective way of implementing this?
public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.act_main);

    VideoView splash = (VideoView) findViewById(R.id.SplashView);

    Uri splashPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.phsplash);

    splash.setVideoURI(splashPath);
    splash.start();

    final int interval = 7000;
    Handler handler = new Handler();
    Runnable runnable = new Runnable(){
        public void run(){

            Intent goHome = new Intent(Main.this, HomeView.class);
            startActivity(goHome);

        }
    };

    handler.postAtTime(runnable, System.currentTimeMillis()+interval);
    handler.postDelayed(runnable, interval);

}
}

xml

<VideoView
    android:id="@+id/SplashView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true" />

</RelativeLayout>

There is then the Home view (Not finished writing due to AppCompat issue)
public class HomeView extends Activity {

private ListView theDrawer;
private ArrayAdapter<String> theAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);

    theDrawer = (ListView)findViewById(R.id.drawlayout);

    theOptions();
    setupDrawer();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
}
private void theOptions(){
    String[] panelarray = {"About PHam", "Upcoming Projects", "Idea Submit", "Locate PHam"};
    theAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, panelarray);
    theDrawer.setAdapter(theAdapter);

    theDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){
            Toast.makeText(HomeView.this, "WTF is Toast!", Toast.LENGTH_SHORT).show();
        }
    });
}
private void setupDrawer(){

}
}

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

<TextView
    android:text="This is the Home Screen!"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView" />

<ListView
    android:id="@+id/navlist"
    android:layout_width="200dp"
    android:layout_gravity="left|start"
    android:layout_height="match_parent"
    android:background="#ffeeeeee" />

</LinearLayout>

And then Finally the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phsplash.captain.pcketham">

<application
    android:allowBackup="true"
    android:icon="@mipmap/phico"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
    <activity android:name=".Main">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".HomeView"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Black" >
    </activity>

</application>

</manifest>

Log Cat Error Files when implementing Public class HomeView extends AppCompatActivity:
11-15 21:05:54.857 13627-13627/? E/Typeface: SANS_LOC file not found.
11-15 21:05:54.867 13627-13627/? E/Typeface: SANS_LOC file not found.
11-15 21:06:02.107 13627-13627/com.phsplash.captain.pcketham E/VdcInflateDelegate: Exception while inflating <vector>
                                                                                java.lang.RuntimeException: Failed to resolve attribute at index 1
                                                                                at android.content.res.TypedArray.getColorStateList(TypedArray.java:425)
                                                                                at android.support.graphics.drawable.VectorDrawableCompat.updateStateFromTypedArray(VectorDrawableCompat.java:518)
                                                                                at android.support.graphics.drawable.VectorDrawableCompat.inflate(VectorDrawableCompat.java:472)
                                                                                at android.support.graphics.drawable.VectorDrawableCompat.createFromXmlInner(VectorDrawableCompat.java:436)
                                                                                at android.support.v7.widget.AppCompatDrawableManager$VdcInflateDelegate.createFromXmlInner(AppCompatDrawableManager.java:708)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:348)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:181)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:689)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:186)
                                                                                at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:77)
                                                                                at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:83)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:146)
                                                                                at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
                                                                                at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
                                                                                at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:193)
                                                                                at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:173)
                                                                                at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:511)
                                                                                at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
                                                                                at com.phsplash.captain.pcketham.HomeView.onCreate(HomeView.java:22)
                                                                                at android.app.Activity.performCreate(Activity.java:5958)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:155)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5696)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
11-15 21:06:02.117 13627-13627/com.phsplash.captain.pcketham E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.phsplash.captain.pcketham, PID: 13627
                                                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.phsplash.captain.pcketham/com.phsplash.captain.pcketham.HomeView}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:155)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5696)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
                                                                                Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:343)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:312)
                                                                                at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:277)
                                                                                at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at com.phsplash.captain.pcketham.HomeView.onCreate(HomeView.java:23)
                                                                                at android.app.Activity.performCreate(Activity.java:5958)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:155)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5696)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

Updated LogCat with

Then add the theme to your Activity or Application in AndroidManifest.xml with android:theme="@style/AppTheme" something like this:
<application
    android:allowBackup="true"
    android:icon="@mipmap/phico"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Comment: my dependencies currently have:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:support-v4:24.2.0'
}

it still crashes once the video fails
Comment: Please add the stacktrace/error log to your question.
Comment: Please see the logcat error files placed in the original question
Comment: That means, you need to change the style to AppCompat
Comment: Added updated LogCat, updated styles as indicated, app still crashing when loading the startactivity for HomeView
Comment: Have you applied it to your Activity in `AndroidManifest.xml` ?. like this `android:theme="@style/AppTheme"`
Comment: First try to add to your `<application .. `
Comment: You sir, are a magician. Thank you for your support it's greatly appreciated!
Comment: AppCompat v7 is the only library needed, by the way
Comment: @cricket_007, I read from [Support Library Features](https://developer.android.com/topic/libraries/support-library/features.html)  on `v7 Support Libraries` section that says **Note: This library depends on the v4 Support Library.**, so we need to add v4 Support library. I'll stand corrected.
Comment: It's a transitive dependency. By compiling v7, you get v4. Same with the design library, that includes v7 and recyclerview on its own. You can run the gradle dependencies task to see the dependency tree


How to code having in mind the screen resolution of each user?

Question: I made my web design in Figma setting it to 1440px x 1024px.
(here is the link if that helps to see what I mean https://www.figma.com/file/IlSDcBbvr4nFp83p0jtndR/Bohhi-Portfolio?node-id=2%3A2)
Now that I want to code and style it I'm confused about it.
How can I position my objects in relation to the design and screen resolution of my PC and every other user?
Can I make it so that the code fits the design?
Thank you!
Comment: The [responsive design page at MDN](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design) might be a good place to start.  The gist-- use a combination of relative units (such as percentages and rems), media queries, and other responsive techniques to guide the browser as to how to alter the layout and the viewport grows/shrinks.  Web is not print-- there are myriad different screen and window sizes on which your site may be rendered.  Your best bet is not to fight this, but to embrace.
Answer: Try checking out @media query for creating responsive layouts:
https://www.w3schools.com/css/css_rwd_mediaqueries.asp
Explanation Edit:
@media only screen and (max-width: 768px) {

width: 100%;

}

For example, you can use it to ajust your preferred lyaout on devices with different screen widths (Example: Phone).
When a condition is true (Example: device screen is maximally 768px width) the following css property will be used (Example: width: 100%;). In this way you can create different content layouts and properties for PC users and Phone users.
Comment: Hello! Thanks for the answer. I don't understand it.  I cant code it to the initial size of the design and then @media it to the 100% or auto resolution?
Comment: @bohhi you can use `max-width` and `min-width`. By using this, you're looking at the dimensions of the screen a user is viewing your website from. You can use your current design for the dimensions you designed on and something like chrome dev tools to test other screen viewports/resolutions. https://anexia.com/blog/en/chrome-dev-tools-explained/
Comment: @bohhi applied explanation in the edit


How to display nodes in order on a daily base

Question: I would like to display node of a specific content type with views.
I want one node to be display every day in order based on node id and the node to change every day.
Comment: Can't you add a date field to a node, to indicate on what dates it will be shown? It would make things easier, both from code POV, and from redactor's POV.
Answer: You can use the views random seed module and on the sort criteria use Global: Random seed
and set the reset seed to everyday

Adds a random order handler with seed. If a constant integer argument
  N is specified in the sql RAND() function, it is used as the seed
  value, which produces a repeatable sequence of column values. This
  makes it possible to have paging and not having items show up twice.
  It's also possible to compute a custom seed using PHP, allowing you to
  create pseudo randoms numbers based on variables such as the date of
  the day.
Comment: This does not meet "order based on node id" criteria.


Diminished Triad + Major 7th =?

Question: i wanted to ask something related to the 5 types of seventh chords. Specifically in what category would a diminished triad topped with a major seventh fall? Can it be considered a half-diminished 7th? All music theory sources i've checked clearly indicate that half-diminished 7th chords can only be topped with a minor. So what type of chord do you get by laying down a major 7th over a diminished triad?
Thank you
Comment: 5 types? Maj7, m7, dom7, dim7, m7b5, mM7,
Comment: It won't be a 'half-diminished' chord. Those have a diminished triad (e.g. C Eb Gb) with m7 (Bb) added. AKA 'm7b5'. Yours would be 'mM7b5'.
Answer: dimMaj7. It's quite uncommon. But its component notes are enharmonics of tones in a different, more common chord.
The tones in CdimMaj7 (C, E-flat, G-flat, B) are enharmonic equivalents of four fifths of a B7flat9 chord (B, D#, F#, A, C).
Comment: Also, I believe, the first chords of a personal favorite: https://www.youtube.com/watch?v=kokbJvSEMUY&t=27s
Answer: Just to add a bit to this post, another way of conceptualizing this chord is a triad with a b2 in the bass (i.e. B/C). This diminished chord along with the maj7th melody note is a defining part of the song "Spring is Here" by Rogers and Hart.

Diminished Triad + Major 7th =?