Como remover propriedade herdada pelo componente?

Question: Ao colocar um ícone de navegação lateral, percebi que um pedaço dele "vazou" para fora do esperado, o que fez ele se comportar  de forma visualmente estranha na animação. Coloquei um background-color: red para facilitar a visualização:

Mas, ao inspecionar o elemento da página, percebi que se eu removesse uma propriedade do CSS da tag  ele se comporta da forma desejada:

mas se eu coloco height: 0 no meu CSS a animação ocorre de outra forma estranha, além do elemento, aparentemente, não ter mais "fundo":

Como eu posso anular o comportamento de uma única propriedade herdado de tags e classes superiores no CSS sem perder os demais, que podem ser úteis?
Estrutura do DOM:

Comment: Talvez sobrescrever a classe CSS. Suponha que haja uma classe chamada `.a { height: 100px; }`, declare em um outro arquivo CSS a mesma classe alterando suas propriedades, ex.: `.a { heigth: unset }`. O importante é que sua alteração seja carregada depois da classe original.
Comment: Pode colocar um exemplo, com código?
Comment: coloquei a estrutura do DOM, mas não sei o que mais poderia botar pra ajudar
Comment: basicamente, o `materialize-css` tem um CSS pronto para todos os elementos `` situados de dentro de uma tag ``, mas eu quero remover uma das propriedades definidas e usar a padrão da página inteira
Comment: @MarceloVismari era isso mesmo. Coloca em uma resposta pra eu poder fechar o tópico ;)
Comment: @ArthurSiqueira mete também o código daquele css na pergunta. Para poder criar um trecho de código executável.
Answer: Você pode sobrescrever as classes CSS para alterar as propriedades desejadas. Suponha que haja uma classe chamada .a { height: 100px; }, declare em um outro arquivo CSS a mesma classe alterando suas propriedades, ex.: .a { heigth: unset }. O importante é que sua alteração seja carregada depois da classe original.


Inflection and relative extrema of a function with multiple unknowns

Question: I can't solve the following exercise:

Determine a, b and c so that the function $f(x)=ax^3+bx^2+cx+2$ reaches a relative maximum for $x=0$ and so that $(1,0)$ is an inflection point of the graph of f.

I do know that the function can reach a relative max. in the root of the derivative of the function and that the function has an inflection point in the root of the seconds derivative. But I don't understand how I could find a, b and c.
Answer: Placing
$f^{′}(x) = 3ax^2+2bx+c$
$f^{′′}(x) = 6ax+2b$
Now put these equations to $0$ with respect of $x = 0$ for first equation and $x = 1$ for the second equation (based on conditions of exercise).
$$3ax^2+2bx+c = 0 \implies c = 0$$
and
$$6ax+2b = 0 \implies 6a+2b = 0$$
In order to ensure, that point $(0, 0)$ is indeed a maximum, we have to make sure that a slope before $(0, 0)$ is negative and after $(0, 0)$ positive.
That means, with respect to our exercise, choosing $x$ smaller than $0$ and bigger than $0$.
In our example, let's choose $x = -1$ and $x = 1$.
Therefore
$$3a-2b+c > 0$$
$$3a+2b+c < 0$$
The same principle applies to inflexion point, so with respect to $(1, 0)$ let's choose $x = 0$ and $x = 2$, therefore
$$2b < 0$$
$$12a+2b > 0$$
What we have is the system of linear equation
$$c = 0$$
$$6a+2b = 0$$
$$3a-2b+c > 0$$
$$3a+2b+c < 0$$
$$2b < 0$$
$$12a+2b > 0$$
That gives us
$$b = -3a \land c = 0 \land a > 0$$
Let's choose $a = 1$, therefore $b = -3$.
That is $f(x) = x^3 -3x^2+2$.
Comment: I realized that in order to ensure that the point is global maximum, we have to constraint slopes before and after critical point (the same logic applies to inflexion point). The answer has been modified but the result is same :), sorry about that. @tomcajot
Comment: Thanks that's it!


Given four edge-lengths of a quadrangle $a,b,c,d$ so that $a\leq b\leq c\leq d$. Prove that $a^{2}+b^{2}+c^{2}+d^{2}<2\left(ab+ac+ad+bc+bd+cd\right).$

Question:
Given four edge-lengths of a quadrangle $a, b, c, d$ so that $a\leq b\leq c\leq d$. Prove that
$$a^{2}+ b^{2}+ c^{2}+ d^{2}< 2\left ( ab+ ac+ ad+ bc+ bd+ cd \right )$$

My solution
$$a+ b+ c> d$$
$$\begin{align}\Rightarrow \left ( 2a+ 2b+ 2c \right )d+ \left ( 2a+ 2b \right )c+ 2ab & > 2\left ( a+ b+ c \right )d+ ac+ bc\\
 & > 2d^{2}+ a^{2}+ b^{2}\\
 & \geq c^{2}+ d^{2}+ a^{2}+ b^{2}
\end{align}$$
How about you ?
Comment: OK ! Why do you down-vote me ?
Answer: \begin{align}\Rightarrow 2\left ( ab+ ac+ ad+ bc+ bd+ cd \right ) & = 2\left ( a+ b+ c \right )d+ ab+bc+bc+ca+ca+ab\\
 & \gt 2d^{2}+ \left (c+ a \right)b + \left (a+ b \right)c + \left (b+ c \right)a\\
 & \gt 2d^{2} + b^{2} + \left (a + b \right)c + a^{2} \\
 & \gt c^2 + d^{2} + b^{2} + \left (a + b \right)c + a^{2} \\
& \gt a^2 + b^{2} + c^{2} + d^{2}
\end{align}


Overriding one class with another using JS

Question: I have a navigation with three links. What I want to do is to show one of three boxes paired on these links if a specific link is clicked. I have these
 elements with data-nav set:

Prerender

Prefetch

Preconnect

I also have these three boxes, which should be visible only if paired
 element is clicked

 Prerendered page:

 Page2:

This is what I have in my .css file
.box1, .box2, .box3{display: none;}
        .expanded{display: block !important;}

This is where I set the expanded class on the box which is paired with the
 element clicked:
for (var i = 0; i < menu_items.length; i++) {
  menu_items[i].onclick = function() {

  var navId = this.getAttribute('data-nav');
  document.getElementByClassName('box' + navId).classList.add('expanded');

    }
  }
}

The problem is that display: none is still set even when I add the expanded class. If I look into console, the display: block rule is here but is erased. How to rewrite It?
Comment: `document.getElementByClassName` is not a function. It should be getElement**s**byClassName
Comment: that didn't fix it @chazsolo
Comment: well "Elements" returns an html Collection....
Comment: I hope that didn't fix it, otherwise I'd be answering in a comment! :) Just pointing out a syntax issue that hopefully should point you in the right direction of _why_ it isn't working. As epascarello said, it's a collection... so you can't just call `classList` directly on it. (and when this is done right, you won't need !important. I'd recommend dropping that now)
Answer: I think you can  set display none in first load with JavaScript or  (hide element)  then in function set display block or  (show the element)
And don't use !important for the class if you want to replace or you should remove class then add other class


Formulário de Contato 2017

Question: Minha dúvida é simples e direta: Atualmente, em 2017, com o avanço do Javascript... Existe alguma forma de eu fazer um formulário de contato 100% via javascript sem uso de um PHP por exemplo?
Se não der, existe alguma ferramenta tão simples quanto o PHP para este serviço?
Eu não entendo nada de PHP, e queria fazer um formulário de contato.
Quais saídas eu tenho?
Obrigado!
Comment: 100% via javascript não, você precisa do html.
Comment: Bom, você vai precisar obviamente enviar os dados do formulário para algum tipo de servidor, então se você não quer utilizar outra linguagem além do Javascript, uma saída é utilizar NodeJS no servidor.
Comment: [Como enviar emails utilizando JavaScript?](https://pt.stackoverflow.com/q/8701/91) e [Como enviar e-mails somente com o básico de HTML5](https://pt.stackoverflow.com/q/213/91)
Answer: Você sempre vai precisar de um back-end que ira fazer o envio de email, isso é indispensavel (mas usando NodeJS, você faz o envio, o que torno só JS).
Um exemplo disso usando JS + NodejS
<input type="email" id="email">
<textarea id="msg"></textarea>
<button id="btn">Entrar em Contato</button>

// Do lado do servidor com Node

'use strict';
const nodemailer = require('nodemailer');

// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
nodemailer.createTestAccount((err, account) => {

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: account.user, // generated ethereal user
            pass: account.pass  // generated ethereal password
        }
    });

    // setup email data with unicode symbols
    let mailOptions = {
        from: '"Fred Foo " <email@example.com>', // sender address
        to: 'firstname.lastname@example.com, email@example.com', // list of receivers
        subject: 'Hello ✔', // Subject line
        text: 'Hello world?', // plain text body
        html: 'Hello world?' // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        // Preview only available when sending through an Ethereal account
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

        // Message sent: <email@example.com>
        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    });
});

FONTE: https://nodemailer.com/about/
Comment: @Jackson isso depende muito, eu comecei com `PHP`, e quando comecei a estudar `Node` achei muito mais facil, pois já trabalhava com `Javascript`
Comment: Show @Rafael! Só complementando miha pergunta... Você acha que a curva de aprendizado de NodeJS como server side mais fácil do que PHP?
Comment: Entendi! Muito obrigado pela dica, Rafael =)

Formulário de Contato 2017


Upgrading to spring-3.1 seems to break my CustomWebArgumentResolver

Question: I'm trying to upgrade a spring MVC app from 3.0.6 to 3.1.2 and some controllers that used to work don't seem to work anymore.  I've read the spring docs, but I'm confused about what's compatible with what.
We've got a CustomWebArgumentResolver that looks for any request parameter named "asOf" and coverts its value to a date.  We call it, unimaginatively, the "AsOfDateConverter."  When upgrading to spring-3.1.2, I took advantage of the new namespace functionality and added this to my applicationContext:
<mvc:annotation-driven conversion-service="conversionService">
    <mvc:argument-resolvers>
        <bean id="customWebArgumentResolver" class="my.converters.CustomWebArgumentResolver">
        </bean>
    </mvc:argument-resolvers>
</mvc:annotation-driven>

The CustomWebArgumentResolver is straightforward:
public class CustomWebArgumentResolver implements WebArgumentResolver {
    private AsOfDateConverter asOfDateConverter;

    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
        if (isAsOfDateParameter(methodParameter)) {
            return asOfDateConverter.convert(webRequest.getParameter("asOf"));
        }

        return UNRESOLVED;
    }

Then an example controller might look something like this:
@Controller
@Secured({BaseController.ROLE_LOGGED_IN})
@org.springframework.transaction.annotation.Transactional
public class DashboardController extends BaseController {
    public static final String URL = "/dashboard";

    @RequestMapping(value=URL, method=RequestMethod.GET)
    public ModelAndView get(@RequestParam(required=false) String requestedMeterType, @AsOf Date asOf) {
        debug(log, "Rendering dashboard asOf %s", asOf);
etc etc

The "asOf" parameter is coming in null, and I'm sure I'm missing something obvious.  If anyone out there neck deep in the latest MVC 3.1 stuff could point me in the right direction I'd be grateful.
Thanks!
Tom
EDIT:
The AsOf annotation:
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface AsOf {
}

More of my applicationContext:
<mvc:annotation-driven conversion-service="conversionService">
    <mvc:argument-resolvers>
        <bean class="[blah].AsOfDateHandlerMethodArgumentResolver">
            <property name="asOfDateConverter">
                <bean class="[blah].AsOfDateConverter"/>
            </property>
        </bean>
    </mvc:argument-resolvers>
</mvc:annotation-driven>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="[blah].converters.CustomerConverter"/>
            <bean class="[blah].converters.AccountConverter"/>
            <bean class="[blah].converters.DateConverter"/>
            <bean class="[blah].converters.CustomerCommunicationInstanceConverter"/>
            <bean class="[blah].converters.MeterTypeConverter"/>
            <bean class="[blah].converters.AreaAmountConverter" p:precision="0"/>
            <bean class="[blah].converters.LengthAmountConverter" p:precision="1"/>
        </set>
    </property>
</bean>

Answer: The API has changed with Spring 3.1 - the interface to implement to resolve a controller argument is HandlerMethodArgumentResolver. You can continue to use CustomWebArgumentResolver, by adapting it to a HandlerMethodArgumentResolver
However changing the code to use HandlerMethodArgumentResolver also will be easy:
public class CustomWebArgumentResolver implements HandlerMethodArgumentResolver {
    private AsOfDateConverter asOfDateConverter;

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        if (isAsOfDateParameter(methodParameter)) {
            return asOfDateConverter.convert(webRequest.getParameter("asOf"));
        }

        return UNRESOLVED;

    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (methodParameter.getParameterAnnotation(AsOf.class)!=null)
    }

Edit
After looking through your comments, I think I have an idea about what could be going wrong. Can you please check your @AsOf annotation, you probably have not declared the retention of Runtime, which could be the reason why the the WebArgumentResolver is not taking effect:
@Retention(RetentionPolicy.RUNTIME)
public @interface AsOf {

}

Anyway here is a gist with a full working test along the same lines:
https://gist.github.com/3703430
Comment: Thanks for pointing out the API change.  I've converted my CustomWebArgumentResolver from an implementation of the WebArgumentResolver to be an implementation (like yours) of the HandlerMethodArgumentResolver.

After adding lots of logging, it seems like it is doing its job right, but the Controller is still getting set with a null Date (!).  It's like the param is being mapped correctly to the Handler, but isn't being set back on the controller.

So something about this still isn't working...
Comment: Actually, on further thought the CustomWebArgumentResolver isn't getting passed any date strings at all... just nulls.
Do I need ParamMappings on my Controller's get() method, just before the AsOf annotation?
Comment: But you are grabbing the `asOf` from the request parameter right, so the issue you are having is that the asOf parameter is present and seems to come into the the resolveArgument method also, but in the method itself it is null is it
Comment: Logging statements are telling me that (1) the resolveArgument method is getting a null, (2) the resolveArgument method sees the null and decides to return a "new Date()", (3) the controller is injected with null.  So somehow the input/output pipeline between the Controller and the HandlerMethodArgumentResolver is nulling out data.
Comment: I have added a gist with a full test which works for me - https://gist.github.com/3703430, can you check. Can you also check if you have runtime retention on your annotation
Comment: The AsOf annotation is @Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface AsOf {
}
Comment: I'm starting to wonder if the  might be the issue.  As shown in the original description, I've also got a conversionService defined in it, and some of the latest tests I ran make it seem like a TypeConverter is attempted to be run before the HandlerMethodArgumentResolver.  I'll add additional snippets of my applicationContext.xml in case that reveals some clues.
Comment: The `AnnotationMethodHandlerAdapter` is not required above right - any reason to have it, not likely to be the reason for the issue though. Is AsOfConverter not part of the list of converters in `ConversionServiceFactoryBean`


Drupal-to-Drupal data migration Taxonomy issues

Question: I'm wondering if there is something special I need to do within the UI when using Drupal-to-Drupal data migration to actually get taxonomy terms to port over with all my nodes. I get an error that reads

No matching taxonomy term found for source value '144' in vocabulary Topics.

I've created first level terms and ported over each term correctly, but what is the special thing I need to do to actually map the terms with the nodes? I've mapped the TID and yet it still doesn't work. Is there something special Im missing?
Comment: How did you map them over? did you create a separate migration job for the taxonomy terms?
Comment: Correct. I used the d2d module to port over all of the terms first then then ported the nodes over and mapped them to those terms.  This was all done via the UI in d2d's new wizard
Comment: If it's a bug in d2d, you should post it in their issue queue, not here. Unless you are willing to fix it yourself, then we may help, but at leas try to find responsible part of code and show us the excerpt of it, describing what about editing it is problematic.
Comment: Would you want to try this module as a different approach to migration as it retains original ids for various things - [data_export_import](https://drupal.org/project/data_export_import)
Comment: Thanks @Mołot.  I did post in the issue queue before coming here to let them know, but I wasn't 100% sure it was a bug or just my own user error.  In terms of code, this all comes out of D2D's UI so I'm not sure if or what code to post.
Comment: Here's a link to how I have it mapped currently.  Im mapping the terms from the old site to the same term ID on the new site. [link](http://i.imgur.com/lHUsMEm.png)
Comment: Can anyone tell if the link ive shown for mappings is incorrect?
Comment: I am having the same problem as you, @doodirock and a similar mapping and approach. Did you succeed with it? How?
Answer: Well, this is a couple years' old now, but thank you doodirock for tickling my memory on this. You need to configure that field's source_type value to 'tid'. I'm doing so in code, but I believe that you can set this in the UI. The code you need is this:
<code>$this->addFieldMapping('field_news_categories:source_type')
  ->defaultValue('tid');
</code>
In my UI view, this row appears like this:

Where 'tid' is the value input.
As the documentation points out:

source_type: If the option value is 'tid', then the incoming value is assumed to be a valid term ID in the destination Drupal instance. Otherwise, it is assumed to be a term name (the default behavior). Note that you'll want to set this to 'tid' if the mapping has a source migration (the sourceMigration() method is used on the mapping).


Drupal Settings for PHPStorm

Question: I want to try to work with PHPStorm Debug.
I already installed debug on my Mac and changed the php.ini File. Furthermore, I installed the Debug Helper for Chrome and created a Projekt on PHPStorm.
If I start Debug, my PHPStorm will find a connection, but I had the Problem that PHPStorm always jumps into my "index.php" file no matter where I set my breakpoint.
I always have to push the "play" button, but again, it runs always through the "index.php" file and my site (I work with VM) will not load before I push "play".
What do I have to do so PHPStorm only jumps to my breakpoint?
Updated
Attached my PHPStorm Settings:
Comment: Sounds good to me @mradcliffe, re-opening
Comment: I vote to close as this question relates to PHP debugging with a particular IDE and server setup which can be asked on http://stackexchange.com. It really has nothing to do with Drupal.
Comment: I disagree. The question is very specific to using PHPStorm to develop a Drupal module, which is different than using PHPStorm to develop a generic web application. The latter is much easier to setup, while the former requires Drupal-specific settings changes to PHPStorm. I think it is more likely to find an answer on Drupal Answers rather than StackExchange.
Comment: @mradcliffe I use PHPStorm exclusively for PHP development and that's not my experience - you need the same settings for any application that dispatches everything through index.php don't you? What's the Drupal-specific bit? (will gladly re-open this BTW, but like the others I didn't know there were Drupal-specific debug settings)
Comment: I guess I thought it was a bit more specific to Drupal than most projects because the project is the module and core isn't in the project root. I see the question SE probably having to delve into Drupal web root specifics in order to be solved (my answer below is generic, but isn't working for the user atm). But I guess if it's off-topic, it's off-topic. *shrug*
Answer: Relevant for PHPStorm 10:
Disable the Force break at the first line when a script is outside the project setting. This is accessible under Settings:

Languages & Frameworks > PHP > Debug > Xdebug

I also disable Force break at the first line when no path mappings specified.
Comment: It's 99% this. I always have to set the path mapping when using a VM so it doesn't pop open index.php.
Comment: i already try but my index.php still popup.. what do you mean with "path mapping"?
Comment: Does PHP Storm run on the host or the VM guest machine? If on the host then you will need to do path mapping. If on the VM guest itself then there is no need for that.
Answer: In addition to @mradcliffe's answer above, and as you work in a VM I guess you may have your browser open in the host OS, hence you need to enable these settings in php.ini (and assuming you use xdebug):
zend_extension="..path to xdebug extension/ext/php_xdebug.dll"

xdebug.remote_enable=1

xdebug.remote_port="9000"

You furthermore need to set the IDE key to PHPStorm in your chosen debug extension in the browser. You can also consult the PHP Storm documentation to set it up as an environment variable if you wish, or you can add a bookmarklet.
And just to cover all the bases, you need to listen for incoming connections in PHP Storm here:

Drupal Settings for PHPStorm


Quando inserido conteúdo dentro da div, a página não rola certo

Question: Quando inserido conteúdo dentro da div, a página não rola certo, mas sem o conteúdo ela estava normal.

    var _AlturaDocumento = $(window).height();
    function AlturaSecao(){
    $('.secao').height(_AlturaDocumento);
    }

    function ScrollSecao(){
    console.log('entrou');
    var body = $('html, body');
    if($(this).parent('.secao').is('#secao01')){
    body.animate({scrollTop: _AlturaDocumento}, '500');
    } else if($(this).parent('.secao').is('#secao02')){
    body.animate({scrollTop: _AlturaDocumento*2}, '500');
    }else if($(this).parent('.secao').is('#secao03')){
    body.animate({scrollTop: _AlturaDocumento*3}, '500');
    }
    else if($(this).parent('.secao').is('#secao04')){
    body.animate({scrollTop: _AlturaDocumento*4}, '500');
    }else {
     body.animate({scrollTop: 0}, '800');
    }
    }

    $('.icone-scroll').click(ScrollSecao);

    $(AlturaSecao);

    <!DOCTYPE html>

      <meta charset="utf-8">
      <title>CURRICULUM</title>

    Nome Completo

     RUA, Numero - Bairro
 Cidade/Estado, Cep

    CELULAR: 11980******

    E-MAIL: email@example.com

EDUCAÇÃO E FORMAÇÃO

      ANÁLISE E DESENVOLVIMENTO DE SISTEMAS - ANHANGUERA
             INÍCIO: JAN/2019 - TÉRMINO: JUN/2021

    TÉCNICO EM INFORMÁTICA (PROGRAMAÇÃO) - INSTITUTO TÉCNICO DE BARUERI
              INÍCIO: JUL/2015 - TÉRMINO: JUL/2017

    ENSINO MÉDIO COMPLETO (EJA) - E.E. MARIA ALICE CRISSIUMA MESQUITA
              TÉRMINO: DEZ/2014

EXPERIÊNCIA PROFISSIONAL

      HIBERO EXTINTORES, CARAPICUÍBA - SP

     CARGO: PINTOR

     INÍCIO: SET/2011

              TÉRMINO: MAI/2019

 QUALIFICAÇÕES E ATIVIDADES PROFISSIONAIS

 C#, JAVA, HTML5, ASP.NET, ECLIPSE ANDROID, ORACLE SQL

OBJETIVO

 ESTÁGIO/TRAINEE EM DESENVOLVIMENTO DE SISTEMAS

Comment: Editei sua pergunta para o código ser executável e não vi problema nenhum. Pode Executá-lo e ser mais específico no seu problema?
Comment: Cara mas a forma como vc está calculando não é legal.... esses `_AlturaDocumento*1` ou `_AlturaDocumento*2`... quem te garante que realmente essa conta vai bater com o tamanho do conteúdo? A section 2 pode ter 3* a altura, ai sua lógica vai pro saco... Veja outras formas de fazer aqui https://pt.stackoverflow.com/questions/90119/efeito-deslizante-em-links-ancora
Comment: Peguei em um exemplo de site, então, achei que não teria esse problema do ajuste ao conteúdo.
Answer: Você não precisa pegar a altura do window para fazer isso. Basta colocar no CSS, na classe .secao, a propriedade height: 100vh; para que as divs tenham sempre a altura da janela.
.secao{
   position:relative;
   height: 100vh;
}

E remova todos os height dos id's #secao01 a #secao05.
Quanto ao código jQuery, está muito complicado quando você pode fazer de uma forma muito mais simples, movendo o scroll para a div posterior ao do ícone clicado, sem precisar fazer multiplicação. Veja no exemplo que não precisa de muita coisa que você colocou, basta um if...else:

$(function(){

   function ScrollSecao(){
     // console.log('entrou');
      var body = $('html, body');

      var secao = $(this).parent(".secao").next().offset().top;

      if($(this).parent('.secao').is('#secao05')){
         body.animate({scrollTop: 0}, '800');
      }else {
         body.animate({scrollTop: secao}, '500');
      }
   }

   $('.icone-scroll').click(ScrollSecao);

});
body{
margin:0;
padding:0;
}

p{
position:absolute;
top:80px;
left:5px;
}

h1{
position:absolute;
top:10px;
left:5px;
}

h2{
position:absolute;
top:10px;
left:5px;
}
.secao{
position:relative;
height: 100vh;
}

#secao01{
background-color:#0B77C5;
width: 100%;
margin: 0;
padding: 1px 0;
}

#secao02{
background-color:#fff;
width: 100%;
margin: 0;
padding: 1px 0;
}

#secao03{
background-color:#000;
color:#fff;
width: 100%;
margin: 0;
padding: 1px 0;
}

#secao04{
background-color:#ccc;
width: 100%;
margin: 0;
padding: 1px 0;
}
 #secao05{
background-color:#FFF;
width: 100%;
margin: 0;
padding: 1px 0;
}

.icone-scroll{
position:absolute;
bottom:3em;
width:50px;
height:50px;
background-color:#1a1a1a;
border-radius: 50%;
left:50%;
margin-left:-25px;
cursor:pointer;
}

.scroll{
width:15px;
height:15px;
border-right: 2px solid #fff;
border-bottom : 2px solid #fff;
display:inline-block;
position:relative;
}

.scroll-next{
transform:rotate(45deg);
margin:14px 0 0 16.5px;
}

.scroll-top{
transform:rotate(225deg);
margin:19px 0 0 17px;
}

.scroll-top + .scroll-top{
top:-15px;
margin-top:0;
}

    Nome Completo

     RUA, Numero - Bairro
 Cidade/Estado, Cep

    CELULAR: 11980******

    E-MAIL: email@example.com

EDUCAÇÃO E FORMAÇÃO

      ANÁLISE E DESENVOLVIMENTO DE SISTEMAS - ANHANGUERA
             INÍCIO: JAN/2019 - TÉRMINO: JUN/2021

    TÉCNICO EM INFORMÁTICA (PROGRAMAÇÃO) - INSTITUTO TÉCNICO DE BARUERI
              INÍCIO: JUL/2015 - TÉRMINO: JUL/2017

    ENSINO MÉDIO COMPLETO (EJA) - E.E. MARIA ALICE CRISSIUMA MESQUITA
              TÉRMINO: DEZ/2014

EXPERIÊNCIA PROFISSIONAL

      HIBERO EXTINTORES, CARAPICUÍBA - SP

     CARGO: PINTOR

     INÍCIO: SET/2011

              TÉRMINO: MAI/2019

 QUALIFICAÇÕES E ATIVIDADES PROFISSIONAIS

 C#, JAVA, HTML5, ASP.NET, ECLIPSE ANDROID, ORACLE SQL

OBJETIVO

 ESTÁGIO/TRAINEE EM DESENVOLVIMENTO DE SISTEMAS

Comment: Muito obrigado!!! Resolveu.


Ajuda no meu Formulário PHP

Question: Tô tentando fazer um formulário, em que eu possa enviar arquivos e textos, porém eu quero que tenha apenas um botão enviar pra enviar tanto os arquivos como o texto. O que acontece é que consigo enviar, mas só envios ou o texto ou os arquivos, cada um de uma vez. Sou iniciante, tipo, to fazendo de CtrlC+CtrlV.
Segue meus códigos que fiz até agora:
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <?php
    date_default_timezone_set('America/Sao_Paulo');
    $ip = $_SERVER['REMOTE_ADDR'];
    $data = date("d/m/Y H:i:s");

    if($file = fopen("ips.txt","a+")){
        fputs($file,"O dia e hora da visita foi: ".$data." e o ip do
    visitante é: ".$ip. "\n");
        }else{
        $file = fopen("ips.txt","a+");
    }

    fclose($file);

    ?>

    <form method="post" action="recebe_upload.php" enctype="multipart/form-data">

    Arquivo
    <input type="file" name="arquivo" multiple />

    <input type="submit" value="Enviar" />

    </form>

  <form method="POST" action="recebe_upload.php">

  Caso queira escrever algo; Note que ENVIAR é para enviar
  arquivos(foto,video...), e enviar texto envia
  só o texto. Caso queira enviar um texto e arquivo, envie
  cada um de uma vez.
  Obrigado!

  <textarea name="" rows="100" cols="100">
  </textarea>

<input type="submit" value="Enviar texto" name="B1">

  </form>

Agora o arquivo recebe_upload.php
  <?php

  $_UP['pasta'] = 'uploads/';

  $_UP['tamanho'] = 1024 * 1024 * 100; //

  $_UP['extensoes'=['jpg','jpeg','png','gif','mp4','mp3','txt','apk','docx','doc'];

  $_UP['erros'][0] = 'Não houve erro';
  $_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do PHP';
  $_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
  $_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
  $_UP['erros'][4] = 'Não foi feito o upload do arquivo';

  if ($_FILES['arquivo']['error'] != 0) {
      die("Não foi possível fazer o upload, erro:" . $_UP['erros'][$_FILES['arquivo']['error']]);
  exit; }

  $nome_final = $_FILES['arquivo']['name'];

  if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta'] . $nome_final)) {
  echo "Upload efetuado com sucesso!";
  }     else {

  echo "Não foi possível enviar o arquivo, tente novamente";

  }

Agora o enviar.php
          <?php

          //Armazena os dados em strings

          $nome = $_POST['nome'];

          //Cria um Arquivo

          $arquivo = 'texto.txt';

          $criar = fopen($arquivo, "a+");

          //Define o conteudo do arquivo

          $conteudo = "O texto digitado foi: $nome \n ";

          //Escreve no arquivo que foi criado

          $escrever = fwrite($criar, $conteudo);

          if($escrever == true){ echo "Texto enviado com sucesso"; } else { echo "Erro ao salvar dados em $arquivo";
          } ?>

Edit1: Eu sei que estão em php's diferentes, mas não sei como uni-los.
Comment: Você está usando dois formulários distintos e estes enviam informações distantes.
Coloque ambas as informações em apenas um formulário e no arquivo receb_upload.php você altera para fazer a verificação acerca do envio dos textos.
Comment: Não sei fazer isso
Answer: Foi dado um nome para o atributo name do textarea:
<textarea name="MeuTextarea" rows="100" cols="100"></textarea>

Arquivo que envia - basta um formulário
<!DOCTYPE html>

<meta charset="UTF-8">
<title></title>

<?php
    date_default_timezone_set('America/Sao_Paulo');
    $ip = $_SERVER['REMOTE_ADDR'];
    $data = date("d/m/Y H:i:s");

    if($file = fopen("ips.txt","a+")){
        fputs($file,"O dia e hora da visita foi: ".$data." e o ip do
    visitante é: ".$ip. "\n");
        }else{
        $file = fopen("ips.txt","a+");
    }

    fclose($file);

    ?>

<form method="post" action="recebe_upload.php" enctype="multipart/form-data">

Arquivo
<input type="file" name="arquivo" multiple />

<input type="submit" value="Enviar" />

<textarea name="MeuTextarea" rows="100" cols="100"></textarea>

<input type="submit" value="Enviar" />

</form>

Arquivo que recebe

Foi corrigida essa linha $_UP['extensoes'=['jpg',...  a qual iria gerar um Parse error:  syntax error, unexpected '=', expecting ']' Falta de ] antes do sinal de =
Recupera o texto digitado no text area do formulário  $MeuTextarea = $_POST['MeuTextarea'];

Arquivo corrigido e unificado
$_UP['pasta'] = 'uploads/';

$_UP['tamanho'] = 1024 * 1024 * 100; //

$_UP['extensoes']=['jpg','jpeg','png','gif','mp4','mp3','txt','apk','docx','doc'];

$_UP['erros'][0] = 'Não houve erro';
$_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do PHP';
$_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
$_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
$_UP['erros'][4] = 'Não foi feito o upload do arquivo';

if ($_FILES['arquivo']['error'] != 0) {
  die("Não foi possível fazer o upload, erro:" . $_UP['erros'][$_FILES['arquivo']['error']]);
exit; }

$nome_final = $_FILES['arquivo']['name'];

if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta'] . $nome_final)) {
   echo "Upload efetuado com sucesso!";
}  else {
  echo "Não foi possível enviar o arquivo, tente novamente";
}

//Armazena os dados em strings

      $MeuTextarea = $_POST['MeuTextarea'];

      //Cria um Arquivo

      $arquivo = 'texto.txt';

      $criar = fopen($arquivo, "a+");

      //Define o conteudo do arquivo

      $conteudo = "O texto digitado foi: $MeuTextarea \n ";

      //Escreve no arquivo que foi criado

      $escrever = fwrite($criar, $conteudo);

      if($escrever == true){ echo "Texto enviado com sucesso"; } else { echo "Erro ao salvar dados em $arquivo";
      }

Comment: Muito obrigado!

Ajuda no meu Formulário PHP


Como fazer a mensagem ficar centralizada e piscar na tela em C++?

Question: Como fazer essa mensagem piscar na tela, ficar centralizada e como mudar a cor da mensagem?
<code>    #include <iostream>
    #include <cstdlib>
    #include <windows.h>

    using namespace std;
    string mensagem;
    int main(int argc, char *argv[]) {

    cout << "Digite um palavara: " ;
    cin >> mensagem;

        cout << "***************************" "\n";
        cout << "***************************" "\n";
        cout << "***                     ***" "\n";
        cout << "***                     ***" "\n";
        cout<< "***""\t"<<mensagem<<"\t***""\n";
        cout << "***                     ***" "\n";
        cout << "***                     ***" "\n";
        cout << "***************************" "\n";
        cout << "***************************" "\n";

    system("PAUSE");
    return EXIT_SUCCESS;
}
</code>
Comment: Se por acaso você está se referindo ao atributo `BLINK` de texto no console, isto é característica de código legado que fazia uso da lib `conio.h` da antiga Borland, agora embarcadero: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/textattr_xml.html.
Esta funcionalidade vem dos [antigamente difundidos modos VGA](http://en.wikipedia.org/wiki/VGA-compatible_text_mode).
Answer: Para centralizar é fácil. Estou vendo como fazer piscar, o que já vi que não é tão simples:
<code>#include <iostream>
#include <string>
using namespace std;

string Center(string str) {
   int espacos = (int)((21 - str.length())/2);
   return string(espacos, ' ') + str + string(espacos + (str.length() > espacos * 2 ? 1 : 0), ' ');
}

int main() {
    string mensagem;
    cout << "Digite um palavara: ";
    cin >> mensagem;

    cout << "***************************" "\n";
    cout << "***************************" "\n";
    cout << "***                     ***" "\n";
    cout << "***                     ***" "\n";
    cout<< "***" << Center(mensagem) << "***""\n";
    cout << "***                     ***" "\n";
    cout << "***                     ***" "\n";
    cout << "***************************" "\n";
    cout << "***************************" "\n";

    return 0;
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura. A cor não funciona nele.
Pelo que entendi para piscar tem que fazer um loop trocando a cor por um timer mas deve ter uma forma melhor.
Comment: Essa questão me levou a vidas passadas. O único contexto no qual piscar no console é trivial foi na época que aprendi C e C++ no Turbo C++ em Windows 95 quando ainda havia o modo MS-DOS real.

http://en.wikipedia.org/wiki/VGA-compatible_text_mode
Comment: @pepper_chico é, nesta época era mais fácil. Na verdade eu acho que deve existir um modo de console no Windows mais fácil de fazer isto. E provavelmente até o jeito antigo ainda funciona. Mas você tem razão que mandar algo ficar piscando assim não faz muito sentido. Bons tempos, tudo era mais fácil, agora a gente procura problemas para aplicar soluções que criaram :)
Comment: Uma resposta interessante seria uma aplicação exemplo no contexto do modo texto VGA, acho que vale uma pesquisada :)
Comment: Existem escolas que ainda estão neste ambiente pelo Brasil afora, não duvido.


Buying a harp, what to consider

Question: I'm considering the purchase of a harp for a first-time harpist with a high level of competency playing the piano and recorder, as well as composition. What factors should I consider?
A few more specific questions:

What's the principal difference between pedal harps, lever harps or Celtic harps? What is likely to be best for a competent musician who hasn't played one before.
Are there any buyer beware factors to avoid while buying a harp.
Can you recommend a buying guide which could provide some in-depth information about it?
Comment: @AricFowler While I completely agree with that advice (for any instrument), the context is that it's a surprise gift, so not entirely practical.
Comment: A pedal harp is going to be at least $25000. Good quality lever or Celtic harps are still going to be several thousand dollars. This seems impractical as a surprise gift. If you're spending that much money, you're gonna want to know what they want.
Comment: Consider learning on a borrowed harp for a while before buying one. It's an expensive investment to make, especially if you stop enjoying it
Comment: If a pedal harp (or a Welsh harp) is a serious option on your list given the cost, consider whether the recipient has any means of transporting it, or even enough house-room to keep it at all without permanently disrupting the rest of their lives. Full size harps are *big* - about 6ft x 4ft x 2ft deep - and weigh 80 pounds or more.
Comment: Just a thought - we are all assuming the OP actually means "a harp" (as in an instrument with plucked strings), and not "a harmonica" (which is often called a "blues harp").
Comment: @alephzero Yes, I meant a harp, which is named a harp. I don't know how I could make that any clearer.
Answer: Pedal harps are big and expensive.  You'll need a big enough vehicle if you ever want to take it anywhere, and the prices will be in the "if you have to ask, you can't afford it" range - perhaps US$10000 at the very bottom, and going up way beyond that for a concert harp.  On the plus side, they tend to have more strings, so more range at the bass end.  Pedal harps are the only ones allowing you to both sharp and flat strings.  That gives more flexibility to fit in with orchestras.  It also means you can do a better sounding glissando, by avoiding adjacent notes that don't sound good together.
Lever harps tend to be smaller (perhaps 26 to 34 strings), and priced a lot more affordably (say, US$2000 and up).  They are more portable, especially the smaller ones.  They are likely to be quieter.  The levers only allow you to sharp or flat a string.  A fully levered harp allows you to select all the common major keys, but clever stuff may (a) result in you having to flip levers mid-tune, (b) need you to re-tune the harp, or (c) be unplayable with that harp.
Celtic harps are generally just the same as lever harps, but without the levers.  This means you can only tune them to one key.  Anything else means getting the tuning key out, and re-tuning the thing.  They may be slightly cheaper.
Buying suggestions:

Avoid partly-levered harps.  There's no point, and you'll just keep finding things you can't play.
There are some good-looking but really cheap harps around.  It's real pot-luck what you will get.  You might get a good one, or you might get one that self-destructs after a few months under the strain of the strings.  If you want more certainty, go for a reputable European, US or Japanese manufacturer.
Answer: Since this is a huge purchase, with so many options for size, style, tone quality, etc., I am not sure it's something one person can choose for someone else.
But since people who want to buy harps for other people should never be discouraged (LOL), here are some suggestions:
1. Rental?: A six month rental would be a fabulous gift. Contact your local chapter of American Harp Society (if you are in the USA), or other harp institutions or harp university programs to find out who rents in your area.
2. Harp Column magazine (online or print) has harp ads, occasional articles about harp purchase. Makes a great gift too.
3. www.harpspectrum.org Has articles about harps.
While used harps are often a great option, you need to have an experienced harpist look at it. I and many harp teachers I know will evaluate a used harp with you to look for structural flaws, string condition, and other possible conditions affecting its value. Unlike most other instruments, harps sound better and better for about 70-100 years, then they explode or need costly "rebuild" services.
Don't buy the cheap "Pakistani" harps you see online; they are garbage.
Choose between lever and pedal depending on the preferred genre of music that will mostly be played.
With lever harps, get full levers and make sure you get one that takes the kind of strings you like (nylon vs. gut vs. synthetic). I know, this is one of those "how can you pick for someone else?" situations, but at least know that there are vastly different kinds of strings.
You are a very nice person!  Good luck!

Buying a harp, what to consider


Add a hyperlink underneath the table of a Page View?

Question: I have a Page View that is being displayed as a table. Underneath that table I want to add a simple hyperlink.
I was looking into hook_views_pre_render but I do not see any way to do add this. I also tried hook_preprocess_node. In order to add an anchor tag underneath the table, I really don't know if I should be looking at view hooks or page hooks, or ?
Question:
How do I add a hyperlink underneath the table of a Page View?
Answer: There's a few ways to do that.

Edit View
Click "Footer > Add"
Add your footer HTML as "Global: Text Area"

Another way is to add a block on that page under the view.

admin/structure/block/add
Set page visibility to only your View page path
Set region to "Content" below "Main page content"

If you want more control or placement, you can theme the View page

Edit the View
Click "Advanced > Theme > Information"
You would override the page level "views-view.tpl.php" template renamed to match your View (e.g views-view--my-view.tpl.php ) in your theme dir.
Comment: The block approach fit my situation. Thanks for taking the time David.


Campo para por URL de arquivo de legenda em Player

Question: Estou trabalhando em um WebPlayer e preciso criar um campo onde o User possa inserir a URL de sua legenda e a mesma vá pará no SRC da tag TRACK...
Penso em input mas não sei como prosseguir no JS...
Preciso de um INPUT onde ponha a URL...
Script que pegue essa URL e injete na tag TRACK.
Atual script:
var LEGENDA = "LINKDOINPUT";

(function() {
    'use strict';
    var URLactual = window.location;
    GM_setClipboard(URLactual);
    var html = "<video controls><source src='" + URLactual + "'><track src='" + LEGENDA + "' kind='subtitles' srclang='en' label='LEGENDA' default></video>Download VIDEO<form action=''>Link em .VTT:<input name='firstname' type='text'>

<input type='submit'></form>"
    document.documentElement.innerHTML = html;
})();

Comment: Inclua na pergunta o código que vc já tem.
Answer: Com base no seu código, fiz algumas modificações.

Código comentado

(function() {
  'use strict';
  const URLactual = window.location;
  GM_setClipboard(URLactual);

  const TEMPLATE = '<video controls>' +
        '<source src="' + URLactual + '">' +
        '</video>' +
        'Download VIDEO' +
        '<form>' +
        // Definido um id para o input
        'Link em .VTT:<input id="legenda" type="text">

' +
        // Alterado para tipo button e definido id
        '<input id="btn_inserir" type="button" value="INSERIR LEGENDA">' +
        '</form>';
  // Imprime no corpo do documento
  document.body.innerHTML = TEMPLATE;

  const BTN_INSERIR = document.querySelector('#btn_inserir');
  const VIDEO = document.querySelector('video');

  // Adiciona o evento Click no botão
  BTN_INSERIR.addEventListener('click', function(e) {
    const TRACKS = document.querySelectorAll('track');
    const LEGENDA = document.querySelector('#legenda');
    const TEMPLATE_TRACK = '<track src="' + LEGENDA.value + '" kind="subtitles" srclang="en" label="LEGENDA" default>';
    // Verifica se foi adicionado a legenda
    if (TRACKS.length > 0) {
      // Caso já tenha adicionado uma legenda, apenas atualiza
      // o endereço conforme o valor do input
      TRACKS[0].src = LEGENDA.value;
    } else {
      // Caso não tenha, adiciona com o valor passado no input
      VIDEO.insertAdjacentHTML( 'beforeend', TEMPLATE_TRACK );
    }
  });
})();

Código minificado

(function(){'use strict';const URLactual=window.location;GM_setClipboard(URLactual);const TEMPLATE='<video controls><source src="'+URLactual+'"></video>Download VIDEO<form>Link em .VTT:<input id="legenda" type="text">

<input id="btn_inserir" type="button" value="INSERIR LEGENDA"></form>';document.body.innerHTML=TEMPLATE;const BTN_INSERIR=document.querySelector('#btn_inserir');const VIDEO=document.querySelector('video');BTN_INSERIR.addEventListener('click',function(e){const TRACKS=document.querySelectorAll('track');const LEGENDA=document.querySelector('#legenda');const TEMPLATE_TRACK='<track src="'+LEGENDA.value+'" kind="subtitles" srclang="en" label="LEGENDA" default>';if(TRACKS.length>0){TRACKS[0].src=LEGENDA.value}else{VIDEO.insertAdjacentHTML('beforeend',TEMPLATE_TRACK)}})})()

Referências

insertAdjacentHTML
addEventListener
querySelector
querySelectorAll
Quais as vantagens e desvantagens de minificar scripts JS?
Comment: Funcionou perfeitamente obrigado...


Is it possible to receive rpc-websocket json request in angular from python?

Question: My client is based on angular and electron, the server is written in python language.
I am able to send json-rpc requests between python-python and angular-angular.
I want to send a json object to client using json-rpc websocket from python to angular.
I am a noob so not really sure if it is possible or if there's a library available as I cannot find anything cross platform. Any help will be appreciated :)
Answer: It is possible, there seems only python 3.x rpc websocket support.
Look for 'jsonrpcclient[websockets]'. There is a server available too.
On angular side, I can only suggest 'rpc-websockets'


Union of vector subspaces, sum of dimensions of vector subspaces and direct sum of vector subspaces

Question: I am currently reading Linear Algebra Done Right by Sheldon Axler, and I have stumbled upon some proposition that I have trouble verifying.
Excerpt from the book:

Proposition. Suppose $\boldsymbol V$ is finite dimensional and $U_1,...,U_m$ are
  subspaces of $\boldsymbol V$ such that: $\boldsymbol V = U_1 + ··· + U_m$
and
$\dim \boldsymbol V  = \dim U_1  +\cdots+ \dim U_m$.
Then $\boldsymbol V = U_1 \oplus \cdots \oplus U_m$.

So I tried to verify this with an actual example from the book itself that was given in a chapter before.
Say we use these three subspaces:
\begin{align}
U_1 =& \big\{(x,y,0) ∈ F^3 : x,y ∈ F\big\},\\
U_2 =& \big\{(0,0,z) ∈ F^3 : z ∈ F\big\},\\
U_3 =& \big\{(0,y,y) ∈ F^3 : y ∈ F\big\}.
\end{align}
Then:
$\boldsymbol V = U_1 + U_2 + U_3$ (ok),
$\dim \boldsymbol V  = \dim U_1  + \dim U_2  + \dim U_3 = 1 + 1 + 1 = 3$ (ok)
But:
$\boldsymbol V ≠ U_1 ⊕ U_2 ⊕ U_3$ (not ok)

Could somebody explain me what I am confusing here?
Comment: check the dimension of U1
Answer: The mistake is that $\dim U_1\ne 1$.
In particular,
$$
U_1=\{(x,y,0):x,y\in F\}=\mathrm{span}\,\{(1,0,0),(0,1,0)\},
$$
and hence
$$
\dim U_1=2.
$$
Comment: Thanks! Makes sense now :)


Movimentos no tkinter python

Question: Estou apendendo python, e quis fazer uma interface em que tenha uma bola que vá batendo nas paredes, só que queria saber como posso fazer pra bola ir batendo nas paredes.
from tkinter import *
import time
tela = Tk()
tela.geometry('500x500')
tela.resizable(False, False)

canvas = Canvas(tela, width=400, height=400, bg='black')
ball = canvas.create_oval(20,20,50,50, fill='red')
canvas.pack()
for x in range(60):
    y = x = 6
    canvas.move(ball, x, y)
    time.sleep(0.025)
    tela.update()
sair = Button(tela, text='Sair', bg='red', command=tela.destroy)
sair.pack()
tela.mainloop()

Answer: Não use time.sleep() pois sua interface fica irresponsiva.
Ao invés disso, crie uma função para atualizar a posição da bola, e use tela.after() para agendar a execução dessa função de tempos em tempos.
Dentro da função, use canvas.coords() para pegar as coordenadas da bola e ver se ela passou dos limites da tela (400x400 no seu caso). Se tiver passado, inverta a direção.
from tkinter import *
tela = Tk()
tela.geometry('500x500')
tela.resizable(False, False)

canvas = Canvas(tela, width=400, height=400, bg='black')
ball = canvas.create_oval(20,20,50,50, fill='red')
canvas.pack()
x = 6
y = 8

def atualiza_posicao_bola():
    global x, y
    canvas.move(ball, x, y)
    xb, yb, xs, ys = canvas.coords(ball)
    if xs > 400 or xb < 0:
        x = -x  # inverte a direcao eixo x
    if ys > 400 or yb < 0:
        y = -y  # inverte a direcao eixo y
    tela.after(25, atualiza_posicao_bola) # agenda pra daqui a pouco

tela.after(0, atualiza_posicao_bola) # agendamento inicial
sair = Button(tela, text='Sair', bg='red', command=tela.destroy)
sair.pack()
tela.mainloop()

Veja que optei por manter a estrutura do código similar à sua para facilitar o entendimento. Em uma futura evolução desse código, sugiro usar uma classe para a bola, e armazenar as variáveis de direção como atributos dessa classe, evitando dessa forma o uso de globais e possibilitando mais flexibilidade como a criação de múltiplas bolas e/ou outros elementos.

Movimentos no tkinter python


Closed and bounded does not mean compact in general

Question: Suppose in metric space $\Bbb Q$ I consider the subset $\{x\in\Bbb Q | 2<x^2<3\}$. I want to find a open cover for this set which does not have any finite subcover. How to do it ? Hint is enough.
Answer: Hint: Consider a cover consisting of $\Bbb{Q} \cap (-r, r)$ for rationals $r$ with $r < \sqrt{3}$.
Comment: In case one wants to avoid explicit reference to irrational numbers like $\sqrt 3$, a cover consisting of sets of the form $\{x\in\mathbb Q|2<x^2<r\}$ with $r$ rational and less than $3$ would do.
Comment: @JonasMeyer: yes, i also got this solution.


Get data from both table, where data isn't common for this tables

Question: I have 2 tables
TABLE  jt1
name
---
A
B
C

and TABLE  jt2
name
---
B
C
D

I need get names from both tables, which is not common for both tables, that is result must be
result
------
A
D

This is my query, but may be there is better solution for this?
    SELECT jt1.name  AS name  FROM jt1
    LEFT JOIN jt2
    ON jt1.name = jt2.name
    WHERE jt2.name IS NULL

    UNION

    SELECT jt2.name  AS name  FROM jt2
    LEFT JOIN jt1
    ON jt2.name = jt1.name
    WHERE jt1.name IS NULL

Comment: This is called **`MINUS`**.
Answer: SELECT    COALESCE(jt1.name,  jt2.name) AS zname
FROM      jt1
FULL JOIN jt2 ON jt1.name = jt2.name
WHERE     jt2.name IS NULL OR jt1.name IS NULL
  ;

BTW: the naive solution could probably be faster:
SELECT name
FROM a (WHERE NOT EXISTS SELECT 1
        FROM b WHERE b.name = a.name)
UNION ALL
SELECT name
FROM b (WHERE NOT EXISTS SELECT 1
        FROM a WHERE a.name = b.name)
   ;

BTW: I purposely use UNION ALL here, because I know that the two legs cannot have any overlap, and the removal of duplicates can be omitted.
Comment: That one's probably fastest and simplest.
Comment: My guess is that the `select n from a (where not exists select 1 from b where b.n = a.n) union all select n from b (where not exists select 1 from a where b.n = a.n)` will be faster (I 'll add it) . Results may depend on the distribution of the data, etc.
Answer: A combination of EXCEPT and UNION will do the trick as well.
I can't tell if that is more efficient that the other solutions though:
(
  SELECT name
  FROM jt1
  EXCEPT
  SELECT name
  FROM jt2
)
UNION
(
  SELECT name
  FROM jt2
  EXCEPT
  SELECT name
  FROM jt1
)
ORDER BY Name;

(The paranthesises are not really necessary, I just added them to visualize the approach)
Answer: you could do something along the lines of
select * from jt where jt.name not in (select name from jt2)
union
select * from jt2 where jt2.name not in (select name from jt)

or if the entries are only singular in each table you could do a count and a union all
or you could even setup something with a full outer join (probably not very fast)
or you could setup a cursor and temporary tables to do this
ultimately it will depend on how your indexes are set up and the amount of data involved and the architecture to determine which is best
probably worth trying a few and profiling them yourself to find out
Answer: You can use FULL JOIN for this:
SELECT    jt1.name
  FROM      jt1
  FULL JOIN jt2
         ON jt1.name = jt2.name
  WHERE     jt2.name IS NULL
UNION
SELECT jt2.name
  FROM jt1
  FULL JOIN jt2
         ON jt1.name = jt2.name
  WHERE jt1.name IS NULL
ORDER BY Name;

Output:
╔══════╗
║ NAME ║
╠══════╣
║ A    ║
║ D    ║
╚══════╝

See this SQLFiddle
Answer: Not very efficient, but you could use an exclude statement:
Select name from A
Union
Select name from B
Except
Select A.name from A join B on B.name = A.name

This full join should also do the trick:
Select coalesce(a.name, b.name) as name
From a full join b on a.name = b.name
Where a.name is null or b.name is null


Why doesn't memory get released to system after large queries (or series of queries) in django?

Question: First off, DEBUG = False in settings.py, so no, connections['default'].queries is not growing and growing until it uses up all of memory.
Lets start off with the fact that I've loaded the User table from django.contrib.auth.models.User with 10000 users (each named 'test#' where # is a number between 1 and 10000).
Here is the view:
from django.contrib.auth.models import User
from django.http import HttpResponse

import time

def leak(request):
    print "loading users"

    users = []
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())
    users += list(User.objects.all())

    print "sleeping"
    time.sleep(10)

    return HttpResponse('')

I've attached the view above to the /leak/ url and start the development server (with DEBUG=False, and I've tested and it has nothing to do with running a development server vs other instances).
After running:
% curl http://localhost:8000/leak/

The runserver process' memory grows to around the size seen from ps aux output below and then stays at that level.
USER       PID %CPU %MEM    VSZ    RSS TTY      STAT START   TIME COMMAND
dlamotte 25694 11.5 34.8 861384 705668 pts/3    Sl+  19:11   2:52 /home/dlamotte/tmp/django-mem-leak/env/bin/python ./manage.py runserver

Then running the above curl command above does not seem to grow the instance's memory usage (which I expected from a true memory leak?), it must be re-using the memory?  However, I feel that there is something wrong here that the memory does not get released to the system (however, I understand that it may be better performance that python does NOT release the memory).
Following this, I naively attempted to see if python would release large chunks of memory that it allocated.  So I attempt the following from a python session:
>>> a = ''
>>> a += 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' * 10000000
>>> del a

The memory is allocated on the a += ... line as expected, but when del a happens, the memory is released.  Why is the behavior different for django query sets?  Is it something that django is intending to do?  Is there a way to change this behavior?
I've literally spent 2 days debugging this behavior with no idea where to go next (I've learned to use guppy AND objgraph which seem to not point to anything interesting that I can figure out).
UPDATE: This could be simply python memory management at work and have nothing to do with Django (suggested on django-users mailing list), but I'd like confirmation by somehow replicating this in python outside of Django.
UPDATE: Using python version 2.6.5
Comment: +1. Very interested in answers of this question. I also recognized strange memory leaks with Django over some time on production (DEBUG=False as well and even with very simple apps/projects).
Comment: What happens if you `del users`?
Comment: What version of Python are you using (for both the server and the command line test)? Older versions don't release memory allocated for objects back to the system, so if your local version is 2.5 or later, but your server is running 2.4, that may be your problem. Single large allocations (like your big string) may also bypass the allocator - see what happens with something like `([[]] * 10**6)` instead.
Comment: With lots of small objects, you can also see memory fragmentation problems, so even the more recent allocators are unable to free up complete chunks to return to the OS. As an experimenting, using the big list from my previous comment, grab a reference to every 10th object `x = seq[::10]` or so, then kill the original list and see how much memory you give back to the OS (likely very little).
Comment: My example in the above comments is incorrect - I posted a corrected version as an answer.
Comment: @chris nothing actually, that's the problem (`del users` is the same as leaving the scope of the function
Answer: I decided to move my comments into an answer to make things clearer.
Since Python 2.5, the CPython memory allocation tracks internal memory usage by the small object allocator, and attempts to return completely free arenas to the underlying OS. This works most of the time, but the fact that objects can't be moved around in memory means that fragmentation can be a serious problem.
Try the following experiment (I used 3.2, but 2.5+ should be similar if you use xrange):
# Create the big lists in advance to avoid skewing the memory counts
seq1 = [None] * 10**6 # Big list of references to None
seq2 = seq1[::10]

# Create and reference a lot of smaller lists
seq1[:] = [[] for x in range(10**6)] # References all the new lists
seq2[:] = seq1[::10] # Grab a second reference to 10% of the new lists

# Memory fragmentation in action
seq1[:] = [None] * 10**6 # 90% of the lists are no longer referenced here
seq2[:] = seq1[::10] # But memory freed only after last 10% are dropped

Note, even if you drop the references to seq1 and seq2, the above sequence will likely leave your Python process holding a lot of extra memory.
When people talk about PyPy using less memory than CPython, this is a major part of what they're talking about. Because PyPy doesn't use direct pointer references under the hood, it is able to use a compacting GC, thus avoiding much of the fragmentation problem and more reliably returning memory to the OS.
Comment: The Dropbox team actually gave a really good description of this problem in their Pycon talk (first mentioned in slide shown at 18:00, more detail at ~26:00): http://pycon.blip.tv/file/4878722/
Comment: Could you link to the relevant parts of the source?
Comment: Development version of the object allocator: http://hg.python.org/cpython/file/default/Objects/obmalloc.c

Change the "default" segment in the URL to the relevant Python version to get the latest version of the allocator code on that branch.
Answer: Lots of applications, language runtimes, and perhaps even some system memory allocators will keep deallocated memory in place for as long as possible with a view to re-using it, purely for performance purposes. In a complex system like Django it could be any number of extensions, possibly implemented in C, which exhibit this behaviour, or it might be Python with some sort of memory pool, or lazy garbage collection.
It could even be the underlying malloc implementation doing this, or your operating system keeping a certain amount of memory space allocated to your process even though the process isn't explicitly using it. Don't quote me on this though - it's been a while since I looked into such things.
On the whole though, if repeating the allocation process after the initial alloc and dealloc does not double the amount of memory used, what you're seeing is not a memory leak but memory pooling. It's only likely to be a problem if you have a lot of processes that contend for a limited amount of memory on that machine.
Comment: Good answer, just not thrilled with a lot of the "hand waving" magically explanation...  I like that ncoghlan gave me an example of how to do repeat the problem, thanks for your input though
Comment: Sadly, a bit of handwaving is necessary, because it's very rare that you get a completely deterministic mapping between resource allocation in a high level language and process memory usage at the OS level these days - the various memory managers have too many optimisations for that. This is why you can't diagnose a memory leak from `ps` or Task Manager alone.
Comment: ncoghlan sees to have explained it in a way that makes sense.  Memory gets fragmented and therefore cannot be free'd by the interpreter.  I'm sure memory managers come into play at some point... but I think you've blown this out of proportion.  The fact is, the memory was fragmented and has nothing to do with anything deeper than that.
Comment: The only reason the memory is fragmented and can't be freed by the interpreter is -because- there's a special case memory manager at work here. And exactly the same issue applies in the system allocator too, depending on the implementation. My answer is just a more general version of what ncoghlan has specifically highlighted.
Comment: After a little more understanding of the problem and re-reading your answer, I up-voted your answer as I think its a good one.  However, you address the total underlying problem and did not specifically help me with mine, so I think ncoghlan helped me much better than you did.  But I do appreciate the answer.


Continuous RV: PDF/CDF (Geometric)

Question: Let vector $(X, Y)$ be distributed uniformly on a support of triangular shape $ABC$, where $A=(0;0), B=(2;0), C=(1,1)$. Find $PDF$ and $CDF$ of random variables $X$ and $Y$. Are those random variables independent?
Could you help me with this one? I do have some experience with the basic geometric probability, however I literally don't know what and how to apply here..
Answer: When they say $Z \sim U(\Omega), \Omega \subset \mathbb{R}^n$, this means that the PDF is the same in every point, if it is in the support $\Omega$ and zero otherwise:
$$ p(z) = \begin{cases}C, \text{ if } z \in \Omega \\ 0, \text{ if } z \notin \Omega \end{cases} $$,
where the constant C is chosen so that $\int_\Omega C \mathrm{d} z = 1$.
In your case $n = 2$, $z = (x,y)$ and $\Omega = \Delta ABC$.
For the integration purposes the support of $(X,Y)$ can be expressed as the following constraint on values of $Y$:
$$
\Delta ABC = \left\{(x,y) \in [0,2] \times \mathbf{R} \bigg| \begin{cases} y \in (0,x) &\text{ if } x \in [0,1],\\ y \in (0,2-x) &\text{ if } x \in (1,2] \end{cases}\right\}.
$$
So
$$ C = \left(\int_{\Delta ABC} 1 \mathrm{d}y\mathrm{d}x\right)^{-1} = \frac{1}{S_{\Delta ABC}} = 1,$$
therefore
$$ p(x,y) = 1 \text{ if } (x,y) \in \Delta ABC, \text{ and } 0 \text{ otherwise}.$$
To obtain PDF of $X$ in a certain point $X=x$, you must integrate the joint PDF over all values of $Y$ that are consistent with $x$:
$$ p(x) = \begin{cases} \int_0^x 1 \mathrm{d} y = x, \text{ if } x\in [0,1], \\
           \int_0^{2-x} 1 \mathrm{d} y = 2 - x, \text{ if } x \in (1,2],\\
0 \text{ otherwise}.
    \end{cases} $$
The CDF is computed from the PDF according to the definition:
$$ P(x) = \int_0^x p(\xi) \mathrm{d} \xi = \begin{cases} 0, \text{ if } x < 0, \\ \frac{x^2}{2}, \text{ if } x \in [0,1], \\ 2x - \frac{x^2}{2}, \text{ if } x \in (1,2], \\ 1, \text{ if } x > 2.   \end{cases}$$
By the same token, you can easily find the PDF and CDF of $Y$.
Comment: Got the same for X, will check what is with Y now, thanks a lot! I was not sure whether my solution flows the right path, now I see :)
Comment: Sure, no problem. Please upvote the the answer as well, it did take a bit of time to write it up.
Comment: However, looks like something odd is happening with $p(x)$ integral limits..
Comment: You should be more specific, if you want explanations.
Comment: Not really get it, why for $x \in (1,2]$ we integrate from 0 to (2-x), may you add some details with indicators manipulating, please?
Comment: The thing is, I was told to try avoiding geometry here, so I've used following technique: $\rho_X(a)=\int_{-\infty}^{+\infty} Ind(y0)dy$ from that point of view your sectioning $[0,1]; (1;2], etc$ is not that straightforward, unfortunately
Comment: $Ind(y1$. Then you have to get rid of $Ind$'s and adjust the integration boundaries.
Comment: Got it, thanks again!

Continuous RV: PDF/CDF (Geometric)


como passar muitas variáveis do controller para a view no laravel

Question: Quero passar estas variáveis, mas parece que a quantidade me impede, tem outro jeito?
<code>        return view('pontuacao')->with('somas', $somas[0]->p)->with('somas1', $somas1[0]->s)->with('palpites', $palpites)->with('confrontos', $confrontos)->with('ranking', $ranking)->with('somas2', $somas2[0]->s)->with('somas3', $somas3[0]->s)->with('somas4', $somas4[0]->s)->with('somas5', $somas5[0]->s)->with('somas6', $somas6[0]->s);
</code>
Answer: Você pode colocar todos os dados em 1 array e retornar o array:
$dados = array(
    'somas'  => $somas[0]->p,
    'somas1'   => $somas1[0]->s,
    '...' => '...'
);
return view('pontuacao')->with('dados', $dados);
ou, passa variável por variável fora do with():
return view('pontuacao',['somas'  => $somas[0]->p, 'somas1'   => $somas1[0]->s, '...' => '...']);
testa ai e retorna o que escolheu! :D
Salve do ZoyO!


strtotime always returns 01-1-1970

Question: I really tried everything, I get my date from date picker like this : 05/10/2016
then I replaced the / with -  . used strtotime but i always get 01-1-1970.
this is my code:
 if (isset($_POST['CampaignName']) && isset($_POST['CampaginBudget']) && isset($_POST['start_date']) && isset($_POST['end_date']) && $email  )
 {
   // receiving the post params
    $CampaignName= $_POST['CampaignName'];
    $CampaignBudget = $_POST['CampaginBudget'];
    $start_date= str_replace('/', '-', $_POST['start_date']);
    $end_date = explode('/', $end_date);
    $start_date = date('Y-m-d', strtotime($start_date));
    $end_date = date('Y-m-d', strtotime(implode('-', strtotime($end_date))));
    //$end_date = date('Y-m-d', strtotime($end_date2));
    echo $start_date;  echo $end_date;

edit : startdate works fine but end date has problem. even when they are exactly the same
html code:
Campaign Duration :<input type="text" name="start_date" class="form-control" id="datetimepicker" placeholder="mm/dd/yyyy"/  required>  TO   <input type="text" name="end_date" class="form-control" id="datetimepicker2" placeholder="mm/dd/yyyy"/   required>

Comment: yeah as stated `$end_date` that's undefined and we don't see how it's defined for the POST array for it `$_POST['end_date']` and you have a possible typo for `CampaginBudget`, so unclear there. and again; db schema, column type etc. etc. etc. The ***less*** the good people know, the ***more time*** it takes to provide you with a solution and comments will just continue to grow until we know exactly which animal(s) were dealing with here.
Comment: your question is rather short on code (html form), not to mention what the mysql is or the db schema.
Comment: from where `$end_date` is coming ?? `$end_date` is not declared in your code... you are directly exploding end date
Comment: `$end_date = explode('/', $_POST['end_date']);` probably will be better. but why you are doing `explode()` and `implode()` here? if it works for start_date, use same approach with `str_replace()`.
Comment: check here http://stackoverflow.com/questions/2891937/strtotime-doesnt-work-with-dd-mm-yyyy-format may it helps you
Comment: @mitkosoft I used $_POST in my code, but it is still the same
Comment: *gently walking out...*
Comment: @Neshat try my solution
Answer: Did you tried this?
$originalDate = $_POST['start_date'];
echo $newDate = date("Y-m-d", strtotime($originalDate));

Comment: glad to hear that :)
Answer: You are doint strtotime on end date double time, thats why issue is occuring:
for end date just do:
$end_date = explode('/', $end_date);
$end_date = date('Y-m-d', strtotime(implode('-', $end_date))); // remove strtotime from implode function

Full code:
if (isset($_POST['CampaignName']) && isset($_POST['CampaginBudget']) && isset($_POST['start_date']) && isset($_POST['end_date']) && $email  )
 {
   // receiving the post params
    $CampaignName= $_POST['CampaignName'];
    $CampaignBudget = $_POST['CampaginBudget'];
    $start_date= str_replace('/', '-', $_POST['start_date']);
    $start_date = date('Y-m-d', strtotime($start_date));
    $end_date = $_POST['end_date']; // add this line
    $end_date = explode('/', $end_date);
    $end_date = date('Y-m-d', strtotime(implode('-', $end_date))); // remove strtotime from implode function
    echo $start_date;  echo $end_date;

Comment: I did that but nothing changed
Comment: First recieve $_POST['enddate'] into $enddate
Comment: I knew that i haven't get the end_name from post, i copied your code., but still same problem

strtotime always returns 01-1-1970


Rails association makes undefined method error

Question: I have 2 models Airline and User. The problem is that when I try <%= @current_user.airline.name %> in a view I get undefined method 'airline' for nil:NilClass I have my models set up like this https://gist.github.com/4353169 Maybe I am doing something wrong, but this should work both ways.
Thank you,
Happy holidays (:
Comment: Post your models, please
Comment: @pduersteler they are in https://gist.github.com/4353169 this gist link.
Comment: Can you post the actual development logs? Like a snippet for where that error occurs? Is there a SQL that gets executed before that?
Answer: Try to define a foreign key more specified in the Airline class and Check the foreign key spelling is correct in the both table.
User model,
has_one :user, :foreign_key => "uid", primary_key: 'uid', class_name: 'Airline'

And in your Airline model,
belongs_to :airline, foreign_key: 'uid', class_name: 'Airline'

It's just the suggestion. Try it....


Cannot initialize context because there is already a root application context present

Question: My project uses tapestry 5.3.0,spring 3.0.6.RELEASE,hibernate 3.6.8.FINAL and maven.When
I intruct jetty to start the project with mvn jetty:run, I get the following:
2011-12-13 16:15:42.947:WARN::failed app: java.lang.RuntimeException: Exception     constructing service 'ApplicationContext': Cannot initialize context because there is  already a root application context present - check whether you have multiple ContextLoader*  definitions in your web.xml!
2011-12-13 16:15:42.948:WARN::Failed startup of context  org.mortbay.jetty.plugin.Jetty6PluginWebAppContext@98062f{/projektni,/home/borislav/eclipse_ workspace/web_apps/projektni/src/main/webapp}
java.lang.RuntimeException: Exception constructing service 'ApplicationContext': Cannot  initialize context because there is already a root application context present - check  whether you have multiple ContextLoader* definitions in your web.xml!
at  org.apache.tapestry5.ioc.internal.services.JustInTimeObjectCreator.obtainObjectFromCreator(J ustInTimeObjectCreator.java:78)
at   org.apache.tapestry5.ioc.internal.services.JustInTimeObjectCreator.createObject(JustInTimeOb jectCreator.java:56)
at $ConfigurableWebApplicationContext_10f23e440970.delegate(Unknown Source)
at $ConfigurableWebApplicationContext_10f23e440970.getBeanDefinitionCount(Unknown  Source)
at  org.apache.tapestry5.spring.SpringModule$1.initializeApplication(SpringModule.java:58)
at $ApplicationInitializer_10f23e440987.initializeApplication(Unknown Source)
at  org.apache.tapestry5.services.TapestryModule$39.initializeApplication(TapestryModule.java:25 55)
at $ApplicationInitializer_10f23e440987.initializeApplication(Unknown Source)
at $ApplicationInitializer_10f23e440983.initializeApplication(Unknown Source)
at  org.apache.tapestry5.services.TapestryModule$ServletApplicationInitializerTerminator.initial izeApplication(TapestryModule.java:411)
at $ServletApplicationInitializer_10f23e440969.initializeApplication(Unknown Source)
at org.apache.tapestry5.TapestryFilter.init(TapestryFilter.java:102)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:713)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499)
at  org.mortbay.jetty.plugin.Jetty6PluginWebAppContext.doStart(Jetty6PluginWebAppContext.java:11 5)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)
at  org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156 )
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.plugin.Jetty6PluginServer.start(Jetty6PluginServer.java:132)
at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:454)
at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:396)
at org.mortbay.jetty.plugin.AbstractJettyRunMojo.execute(AbstractJettyRunMojo.java:210)
at org.mortbay.jetty.plugin.Jetty6RunMojo.execute(Jetty6RunMojo.java:184)
at    org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java :107)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at  org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuild er.java:84)
at  org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuild er.java:59)
at  org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.ja va:183)
at  org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
2011-12-13 16:15:43.009:INFO::Started firstname.lastname@example.com:8080[INFO]
Started Jetty Server

Web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>projektni Tapestry 5 Application</display-name>

<context-param>

    <param-name>tapestry.app-package</param-name>
    <param-value>org.prikic.projektni</param-value>
</context-param>

<context-param>
    <param-name>tapestry.development-modules</param-name>
    <param-value>
        org.prikic.projektni.services.DevelopmentModule
    </param-value>
</context-param>
<context-param>
    <param-name>tapestry.qa-modules</param-name>
    <param-value>
        org.prikic.projektni.services.QaModule
    </param-value>
</context-param>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>

        classpath:application_context*.xml

    </param-value>
</context-param>

<filter>
    <filter-name>app</filter-name>

    <filter-class>org.apache.tapestry5.spring.TapestrySpringFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>app</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<welcome-file-list>
    <welcome-file>Index</welcome-file>
</welcome-file-list>

If you need anything else of the source code files,tell me and I'll post them
Ideas,anyone?
Answer: You should remove the ContextLoaderListener from the web.xml. The following is from the Tapestry Spring integration page.
Please omit the part about creating a ContextLoaderListener: this is now done automatically by Tapestry.
Comment: This saved my day when upgrading to spring 4.0.0.RELEASE +1
Comment: Thanky you, this also worked with a Spring-boot with JSF on an external Tomcat.


Which players won both FIFA U-20 World Cup and FIFA World Cup?

Question: Which players won both FIFA U-20 World Cup (until 2005 known as the FIFA World Youth Championship) and FIFA World Cup?
This would show players who excelled both in the young age and in their later career.
I guess that there will not be too many such players but, of course, I might be wrong.
I did not find any source where I could systematically search for statistics like this. By some more-or-less random searching I was able to find Maradona, Dunga and Xavi.
Answer: If this source (Internet Archive) is correct, then the following list includes all players who won both U-20 World Cup and senior World Cup until 2013. There are some later additions too (based on other sources).

Diego Maradona. Maradona won the FIFA World Youth Championship in 1979, and also received the Golden Ball. In 1986 he won the FIFA World Cup, again receiving the Golden Ball.
Iker Casillas won the FIFA World Youth Championship in 1999, and the FIFA World Cup in 2010, where he was voted a member of the all-star team and also won the Golden Glove award for best goalkeeper.
Xavi Hernandez won the FIFA World Youth Championship in 1999. He was a member of the victorious Spanish team at 2010 World Cup, where he was also voted a member of the all-star team of the tournament.
Dunga helped Brazil to win the World Youth Championship in 1983 and the World Cup in 1994, where he also became a member of the all-star team.
Bebeto was a member of the winning Brazilian teams at the same tournaments as Dunga.
Jorginho won the gold medal at the same tournaments as Dunga and Bebeto. He was in the all-star team of the 1994 World Cup.
Cláudio Taffarel won the World Youth Championship in 1985 and the World Cup in 1994.
Müller won at the same tournaments as Taffarel.
Dida won the World Youth Championship in 1993 and was a member of the winning Brazil team at the 2002 World Cup, although he did not play a game there.
Carlos Marchena won the World Youth Championship in 1999 and the World Cup in 2010.
Lionel Messi won the FIFA World Youth Championship in 2005, winning both the Golden Ball and Golden Boot, then won the FIFA World Cup in 2022, where he again won the Golden Ball.
Papu Gómez and Ángel Di María won U-20 World Cup in 2007 and FIFA World Cup in 2022.
Alphonse Areola,
Paul Pogba,
Florian Thauvin and
Samuel Umtiti
won U-20 World Cup in 2013 and FIFA World Cup in 2018.

Sources:

Maradona and other youth and senior world champions (Internet Archive)
Coupe du monde U20 : Que vont-ils devenir? (Internet Archive)
Wikipedia articles of individual world cups


How to add expose View filter for a derived field

Question: I have a Drupal View looking at User profiles. One of the fields is derived, or calculated, which is done using Views PHP.
I'm trying to add an exposed filter for this View, but the expose option isn't visible.
Is there another module I use to add this?
Answer: Sadly I needed to filter the results myself in the Views alter hook.
Results Alter,
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7
Query Alter
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
Comment: This does not answer the question, can you elaborate the answer with steps.
Comment: I've added the hyperlinks.


Card dealing probability question

Question: My text says the following:

Probability that when dealing two cards, if the first card is an ace, then the second card is also an ace. Let B be the event that the first card is an ace, and let A be the event that the second card is an ace. Note that P(A)= P(B) = 1/13

Where did 1/13 come from? I know that there are 13 ranks for each of the 4 suits, but I would've guessed something like 1/52 and 1/51...
We need to figure out P(A and B) for which there are 52*51 sample points since we care about order with no replacement of cards. They say that the sample point where both cards are aces can happen 4*3=12 ways. I know the 4 comes from the 4 suits the Ace could be but where does 3 come from?
Comment: $\frac{4}{52} = \frac {1}{13}$  the probabilites that they have told you are only true if you don't have any information as to whether or not the other card is an ace.  Additionally the word 'then' in the first sentence is used in a confusing manner.
Answer: The original $1/13$ comes because there are $4$ aces among the $52$ cards, so the chance of a given card being an ace is $4/52=1/13$.  For getting the first two cards aces, the probability that the first one is an ace is $4/52$ as before.  Given that the first is an ace, the chance the second is an ace is $3/51$ as there are $51$ cards left and $3$ of them are aces.
Comment: There are four choices for the first ace and for each one there are three choices remaining.  You can write out the twelve possibilities.  Just start with drawing the spade first, then you have ??? as choices for the second, and so on.
Comment: If you just say $P(A)$ it is the probability the second card is an ace regardless of the first card.
Comment: Thank you that's very clear. I want to understand the 4*3 in terms of points in a sample space. If there are 52*51 possible card pairs, how can I deduce that 4*3 of those pairs are both aces?
Comment: Also, How can we say that $P(A) = P(B) = \frac{4}{52} = \frac{1}{13}$ ? Wouldn't the probability of event $A$, that the second card is an ace, be reduced to $\frac{3}{51}$ ?
Comment: Oh okay thanks - still getting used to the language!

Card dealing probability question


Non-convergence of Cauchy Random Variables

Question: Suppose $X_1,X_2,\ldots$ is a sequence of Cauchy random variables with density $$f(x)=\frac{1}{\pi(1+x^2)}, \hspace{3mm}x\in \mathbb{R}$$
and let $S_n=X_1+\ldots+X_n$.
It's easy to show that $\frac{S_n}{n}$ converges in distribution using characteristic functions (in fact, $S_n/n$ has the same distribution as $X$ for every $n$).
On the other hand, $S_n/n$ does not converge in probability. Does this follow from the fact that these random variables are not integrable (if they were, we could apply WLLN)? Or do we need to use the definition of convergence in probability directly?
Answer: Define $Z_n:=\frac{S_{2n}}{2n}-\frac{S_n}n$. Then
$$A_n:=\frac{S_{2n}}{2n}+Z_n$$ is independent of $B_n:=\frac{S_n}n$. We assume that $B_n\to Y$ in probability. Then $A_n-B_n\to 0$ in probability, and denoting $\varphi$ the characteristic function of $Y$, we should have $\varphi(t)\varphi(-t)=1$ for each real number $t$. Since $Y$ is necessarily a Cauchy random variable, we get a contradiction.
There is a necessary and sufficient condition for the weak law of large numbers for independent sequences, namely, if $(X_n,n\geqslant 1)$ is an i.i.d. sequence and $\varphi$ is the characteristic function of $X_1$, the NSC is $\varphi'(0)$ exists.
Here, we can't use the law of large numbers because we know in advance that the limit would not be constant, but Cauchy.
Comment: Got it. Thanks! Do you have a reference where I can read a little on the NSC for WLLN?
Comment: It's exercise 3.17 in Durett's book. I remember it has been solved in this site by Nate Eldredge.
Comment: Great, I'll look into that. Thanks again.


Non-orientable cover of a non-orientable surface

Question: I was quite puzzled by the request of classifying all the $4$-covers of the connected sum of $5$ copies of $\Bbb R P^2$. For oriented covering space, the answer is well known: it's enough to consider the $2$-cover of the orientable cover. But I was quite surprised I wasn't able to find the non-orientable covering (or rule it out).

In general, what can we say about non-orientable finite coverings spaces of non-orientable surfaces?
Answer: If $M$ is a connected manifold, let $nM$ denote the connected sum of $n$ copies of $M$.
First note that if $X \to Y$ is a $k$-sheeted covering, then $\chi(X) = k\chi(Y)$. So if $X$ is a four-sheeted covering of $5\mathbb{RP}^2$, $\chi(X) = 4\chi(5\mathbb{RP}^2)$. Now recall that $\chi(n\mathbb{RP}^2) = n - 2$, so $\chi(X) = 4(5 - 2) = 12$. If $X$ is non-orientable and connected, then $X = n\mathbb{RP}^2$ for some $n$. But $\chi(X) = 12$ and $\chi(X) = \chi(n\mathbb{RP}^2) = n - 2$, therefore $n = 14$. That is, the only connected non-orientable surface which can be a four-sheeted cover of $5\mathbb{RP}^2$ is $14\mathbb{RP}^2$. Note, we still need to check whether $14\mathbb{RP}^2$ does cover $5\mathbb{RP}^2$ or not.
Here's a useful trick: if $\pi: X' \to X$ is a $k$-sheeted covering, then there is a $k$-sheeted covering $p: X'\# kY \to X\# Y$.
To see this, let $U$ be an evenly covered open disc in $X$, then $X'\setminus\pi^{-1}(U)$ is $X'$ with $k$ disjoint open discs removed. Let $V$ be an open disc in $Y$. Gluing a copy of $Y\setminus V$ to each boundary sphere of $X'\setminus\pi^{-1}(U)$, and a copy of $Y\setminus V$ to the boundary sphere of $X\setminus U$, the $k$-sheeted covering $X'\setminus\pi^{-1}(U) \to X\setminus U$ extends to a $k$-sheeted covering $X'\# kY \to X\# Y$.
Returning to the problem at hand, recall that $3\mathbb{RP}^2 = T^2\#\mathbb{RP}^2$, so $5\mathbb{RP}^2 = T^2\# 3\mathbb{RP}^2$. There is a four-sheeted covering $T^2 \to T^2$ (for example, $(z, w) \mapsto (z^4, w)$), so by the above construction, there is a four-sheeted covering $T^2\# 12\mathbb{RP}^2 \to T^2\# 3\mathbb{RP}^2$, i.e. $14\mathbb{RP}^2 \to 5\mathbb{RP}^2$.
If the deck transformations of the four-sheeted covering map $T^2 \to T^2$ are generated by a $90$ degree rotation (which is the case for the example I gave), you can visualise the construction of the four-sheeted covering of $T^2\# 3\mathbb{RP}^2$ as follows:
$$3\mathbb{RP}^2 \\
\# \\
3\mathbb{RP}^2\ \#\ \ T^2\ \#3\ \mathbb{RP}^2 \\
\# \\
3\mathbb{RP}^2$$

These arguments can be used to show the following:

Let $X$ and $Y$ be two closed, connected surfaces, either both orientable or both non-orientable. Then there is a $k$-sheeted covering $X \to Y$ if and only if $\chi(X) = k\chi(Y)$.

As every covering of an orientable space is orientable, the only case left to consider is orientable coverings of non-orientable surfaces.

Let $X$ and $Y$ be two closed, connected surfaces, with $X$ orientable and $Y$ non-orientable. Then there is a $k$-sheeted covering $X \to Y$ if and only if $\chi(X) = k\chi(Y)$ and $k$ is even.

The reason we need $k$ to be even in this statement is that every orientable covering of a non-orientable manifold factors through the orientation double cover.
Comment: I will come back later and address the general case.
Comment: Dear Michael, wow this answer is impressive! That trick is really something! Looking forward to see the general case addressed!
Answer: There certainly exist some: here, for example, is a non-orientable map of 110 pentagons, which is a 2-fold cover of this map. There seem to be plenty of other examples of non-orientable covering maps.
Comment: Dear Michael, thanks for the examples (even though they seems hard to understand at a first glance). I was looking for some insight of how to build them, (or at least prove existence), do you know anything about that?


Redeclare issue user_has_role following upgrade from Drupal 7.34 to Drupal 7.36

Question: Precise error is "Fatal error: Cannot redeclare user_has_role() (previously declared in /usr/home/adpca/public_html/adpca.org.736/modules/user/user.module:863) in /usr/home/adpca/public_html/adpca.org.736/modules/php/php.module(80) : eval()'d code on line 23"
This is in an eval statement I've been through through code base looking for any duplication of the function user_has_role and can't find any. Also been through the databases looking for anything that might trigger the duplicate eval but no joy so far. Anybody got any pointers on what to look for?
Comment: Update. I've traced the issue to the cron.php. This was set to automatically tag itself onto the user page.  Poor man's cron telling it to never do this removes the error from all the pages.  However, when I run cron manually or using curl from the linux command prompt I get the error above.
Answer: The user_has_role() function has been introduced with Drupal 7.36, as stated here, and detailed here.
Following information given by the error message you received we see that:

the function is primarily declared in modules/user/user.module:863: looking at the code of the user module confirm this, ok
the new declaration is said to happen through modules/php/php.module(80): again, looking at the code of the php module confirms that line 80 executes eval('?> . $code);, ok
so the culpry supplemental declaration should be found at line 23 of the PHP content of a field which uses a format where the (not so usual) PHP evaluator filter has been enabled

IMO you should:

review all of your defined text formats, in order to select which of them have PHP evaluator filter enabled
from this reduced list, look for any node or block using these text formats (should not be as many)
then review the corresponding contents, where you'll probably find that somebody had created its own user_has_role() function for its needs, since it didn't exist yet before 7.36

HTH


Mkdir() set permission 777

Question: How do I set permissions for folders below 777?
 mkdir(getcwd() . '/public/profile/usr'.$user->getId(), 0777, true);
 mkdir(getcwd() . '/public/profile/usr'.$user->getId() . '/patients', 0777, true);
 mkdir(getcwd() . '/public/profile/usr'.$user->getId() . '/picture', 0777, true);

Folder permissions for these are the type below:
drwxr-xr-x

And I want it set to:
drwxrwxrwx

Can you tell me please how to solve this problem?
Answer: First off, there is never a good reason to set folder or file permissions to 777. People that feel the need to do this usually either are blindly following a (bad) online tutorial or have an underlying security/permissions problem that they are unable to fix. Usually any uploading/writing problems can be fixed by setting the proper owner/group on the folder (usually the www-data or apache user), 777 means that anybody can write or execute anything in those folders. You're basically leaving your back door open and unlocked in a bad neighbourhood. Also see How will a server become vulnerable with chmod 777? for further details.
That being said, I've seen problems like this with mkdir() before, it is usually because of a certain umask on the system being set, forcing newly created folders to have 755 permissions. Doing a specific chmod() call will do the trick though:
mkdir(getcwd() . '/public/profile/usr'.$user->getId(), 0777, true);
chmod(getcwd() . '/public/profile/usr'.$user->getId(), 777);
// And so on...

But, the better solution: fix your permissions/security issue. Just set the proper owner (the process that PHP is running under), this will avoid having to set 777 permissions, but will allow proper upload handling. This should already be the default, but you can force it with:
// This will get the user the PHP process is running under on Linux machines:
$user = `whoami`;

mkdir(getcwd() . '/public/profile/usr'.$user->getId(), 0755, true);
chown(getcwd() . '/public/profile/usr'.$user->getId(), $user);
// And so on

This will set 755 permissions on the folder and set ownership to the PHP process, meaning that PHP has full permissions on the folder, but any other users do not. This is more secure, yet no less convenient.
The problem might also be caused by SELinux, in which case chmod 777 is not going to help you much anyway. Usually the httpd_public_content_rw_t context is required on upload folders.
Answer: Check this post: http://php.net/manual/de/function.mkdir.php
Answer from there...
When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:
<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1/test2', 0777);
?>

May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do:
<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1', 0777);
chmod('/test1/test2', 0777);
?>

Answer: Here is one of the many possible ways of doing it:
    <?php
        $baseDir    = getcwd() . '/public/profile/usr'. $user->getId();
        $arrFolders = array('/patients', '/picture');

        // FIRST chmod THE BASE DIRECTORY TO HAVE THE PERMISSIONS YOU WANT:
        chmod($baseDir, 0777);

        // LOOP THROUGH THE ARRAY OF FOLDERS YOU WANT TO CREATE & CREATE THEM WITH APPROPRIATE PERMISSIONS:
        foreach($arrFolders as $folder){
            try{
                mkdir($baseDir . $folder, 0777, true);
            }catch(Exception $e){
                // HANDLE ANY EXCEPTION SHOULD ONE OCCUR...
            }
        }

Mkdir() set permission 777