prove this inequality by $abc=1$

Question: Let $a,b,c>0$ and $abc=1$,show that
$$(a^{10}+b^{10}+c^{10})^2\ge 3(a^{14}+b^{14}+c^{14})$$
since
$$LHS=\sum \left(a^{20}+\dfrac{2}{a^{10}}\right)$$
it is prove
$$\sum_{cyc}\left(a^{20}+\dfrac{2}{a^{10}}-3a^{14}\right)\ge 0$$ not easy,and I found $x^{20}+2x^{-10}-3x^{14}$http://www.wolframalpha.com/input/?i=x%5E(20)%2B2x%5E(-10)-3x%5E(14)
Comment: This is problem 12024 from the *American Mathematical Monthly*. It is still current: http://www.mat.uniroma2.it/~tauraso/AMM/amm.html
Comment: A [closer look](http://www.wolframalpha.com/input/?i=plot+x%5E20%2B2x%5E(-10)-3x%5E14,+x%3D+0.9+to+1.1) reveals that $x^{20}+\dfrac2{x^{10}}-3x^{14}\geqslant0$ is false.
Comment: @LordSharktheUnknown Your version has an exponent $13$ rather than $14$ in the right-hand side.
Comment: I very much doubt that the problem has exponent 14 on the right side. With the following substitution: $a=\sqrt{x}, b=\sqrt{y}, c=\sqrt{z}$ the problem becomes simpler: $(x^5+y^5+z^5)^2 \ge 3 (x^7+y^7+z^7)$ with the same condition ($xyz=1$)
Comment: Shouldn't there be a $3$ in front of the term $a^{14}$ in the last sum?
Comment: @LordSharktheUnknown,it's different it
Answer: We can use the Vasc's EV-Method, Corollary 1.8 (b):
https://www.emis.de/journals/JIPAM/images/059_06_JIPAM/059_06.pdf
Indeed, we need to prove that:
$$(x^5+y^5+z^5)^2\geq3xyz(x^7+y^7+z^7),$$ where $x$, $y$ and $z$ they are positives.
Now, let $x^5+y^5+z^5=constant$ and $x^7+y^7+z^7=constant.$
Thus, $xyz$ gets a maximal value for equality case of two variables
and since the last inequality is homogeneous, it's enough to assume $y=z=1$, which gives
$$(x-1)^2(x^8+2x^7-2x^5-4x^4-2x^3+2x+4)\geq0$$ or
$$(x-1)^2((x^4-2)^2+2x(x^2-1)(x^4-1))\geq0.$$
Done!
Also, the BW helps (https://math.stackexchange.com/tags/buffalo-way/info), but it's a very complicated solution:
Let $x=\min\{x,y,z\}$, $y=x+u$ and $z=x+v$.
Hence, $$(x^5+y^5+z^5)^2-3xyz(x^7+y^7+z^7)=(u^2-uv+v^2)x^8-8(u^3-2u^2v-2uv^2+v^3)x^7+$$
$$+4(5u^4-17u^3v+50u^2v^2-17uv^3+5v^4)x^6+$$
$$+8(11u^5-20u^4v+25u^3v^2+25u^2v^3-20uv^4+11v^5)x^5+$$
$$+2(63u^6-79u^5v+50u^4v^2+100u^3v^3+50u^2v^4-79uv^5+63v^6)x^4+$$
$$+4(24u^7-21u^6v+5u^5v^2+25u^4v^3+25u^3v^4+5u^2v^5-21uv^6+24v^7)x^3+$$
$$+(42u^8-24u^7v+20u^5v^3+50u^4v^4+20u^3v^5-24uv^7+42v^8)x^2+$$
$$+(10u^9-3u^8v+10u^5v^4+10u^4v^5-3uv^8+10v^9)x+(u^5+v^5)^2\geq0$$
because for this it's enough to prove that $$4(u^3-2u^2v-2uv^2+v^3)^2-(u^2-uv+v^2)(5u^4-17u^3v+50u^2v^2-17uv^3+5v^4)\leq0,$$
which is true.
Indeed, let $u^2+v^2=2kuv$.
Thus, $k\geq1$ and we need to prove that
$$4(u^2+2uv+v^2)(u^2-3uv+v^2)^2\leq(u^2-uv+v^2)(5(u^4+v^4)-17uv(u^2+v^2)+50u^2v^2)$$ or
$$8(k+1)(2k-3)^2\leq(2k-1)(5(4k^2-2)-34k+50)$$ or
$$4k^3-12k^2+69k-56\geq0,$$ which is obvious for $k\geq1$.
Also, we can use SOS here.
Indeed, $$(x^5+y^5+z^5)^2-3xyz(x^7+y^7+z^7)=\sum_{cyc}(x^{10}+2x^5y^5-3x^8yz)=$$
$$=\sum_{cyc}\left(x^{10}+x^7y^3+x^7z^3-3x^8yz+2x^5y^5-x^7y^3-x^7z^3\right)=$$
$$=(x^7+y^7+z^7)(x^3+y^3+z^3-3xyz)-\sum_{cyc}x^3y^3(x^2-y^2)^2=$$
$$=\sum_{cyc}(x-y)^2\left(\frac{1}{2}(x+y+z)(x^7+y^7+z^7)-x^3y^3(x+y)^2\right).$$
Now, let $x\geq y\geq z$.
Thus, $$\frac{1}{2}(x+y+z)(x^7+y^7+z^7)\geq\frac{1}{2}(2y+z)(2y^7+z^7)\geq y^3z^3(y+z)^2,$$
$$\frac{1}{2}(x+y+z)(x^7+y^7+z^7)\geq\frac{1}{2}(x+2z)(x^7+2z^7)\geq x^3z^3(x+z)^2$$ and by Muirhead
$$\sum_{cyc}(x-y)^2\left(\frac{1}{2}(x+y+z)(x^7+y^7+z^7)-x^3y^3(x+y)^2\right)\geq$$
$$\geq(x-y)^2\left(\frac{1}{2}(x+y+z)(x^7+y^7+z^7)-x^3y^3(x+y)^2\right)+$$
$$+(x-z)^2\left(\frac{1}{2}(x+y+z)(x^7+y^7+z^7)-x^3z^3(x+z)^2\right)\geq$$
$$=(x-y)^2\left((x+y+z)(x^7+y^7+z^7)-x^3y^3(x+y)^2-x^3z^3(x+z)^2\right)\geq$$
$$\geq(x-y)^2\left((x^3+y^3+z^3)(x^5+y^5+z^5)-x^3y^3(x+y)^2-x^3z^3(x+z)^2\right)=$$
$$=(x-y)^2\left((x^4+y^4+z^4)^2+\sum_{cyc}x^3y^3(x-y)^3-x^3y^3(x+y)^2-x^3z^3(x+z)^2\right)=$$
$$=(x-y)^2((x^4+y^4+z^4)^2+y^3z^3(y-z)^2-4(y^4+z^4)x^4)\geq$$
$$\geq(x-y)^2((x^4+y^4+z^4)^2-4(y^4+z^4)x^4)=(x-y)^2(x^4-y^4-z^4)^2\geq0.$$
Done!
Comment: I think this equality without EV?
Comment: There is also BW if you wish.
Answer: Let us prove the equivalent inequality
$$f(x,y)= \left(x^5y^5+\dfrac1{x^5}+\dfrac1{y^5}\right)^2 -3\left(x^7y^7+\dfrac1{x^7}+\dfrac1{y^7}\right) \ge 0,\quad (x,y)\in\mathbb R_+^2,\tag1$$
the stationary points of which can be defined from the system
$f'_x=0,\ f'_y = 0,$ or
$$\begin{cases}
10\left(x^4y^5-\dfrac1{x^6}\right) \left(x^5y^5+\dfrac1{x^5}+\dfrac1{y^5}\right) -21\left(x^6y^7-\dfrac1{x^8}\right)=0\\
10\left(x^5y^4-\dfrac1{y^6}\right) \left(x^5y^5+\dfrac1{x^5}+\dfrac1{y^5}\right) -21\left(x^7y^6-\dfrac1{y^8}\right)=0,\\
\end{cases}\tag2$$
\begin{align}
&\left(x^4y^5-\dfrac1{x^6}\right)\left(x^7y^6-\dfrac1{y^8}\right) =
\left(x^5y^4-\dfrac1{y^6}\right)\left(x^6y^7-\dfrac1{x^8}\right),\\[4pt]
&x^2(x^{10}y^5-1)(x^7y^{14}-1) = y^2(x^5y^{10}-1)(x^{14}y^7-1),\\[4pt]
&x^4y^2(1-x^{10}y^5-x^7y^{14}) = y^4x^2(1-x^5y^{10}-x^{14}y^7).\\[4pt]
\end{align}
Let
$$u=x^2y,\quad v=xy^2,$$
then
\begin{align}
&u^2(1-u^5-v^7) = v^2(1-u^7-v^5),\\
&(u-1)(v-1)(v-u)(u^5v+u^5+u^4v^2+2u^4v+u^4\\
&+u^3v^3+2u^3v^2+2u^3v+u^3+u^2v^4+2u^2v^3+2u^2v^2+2u^2v+u^2\\
&+uv^5+2uv^4+2uv^3+2uv^2+2uv+u+v^5+v^4+v^3+v^2+v) = 0
\end{align}
(see also Wolfram Alpha),
\begin{align}
&(u=1)\vee(v=1)\vee(u=v),\\
&(x^2y=1)\vee(xy^2=1)\vee(x^2y=xy^2),\\
\end{align}
$$\left(y=\dfrac1{x^2}\right)\vee\left(x=\dfrac1{y^2}\right)\vee(x=y).\tag3$$
$\mathbf{\text{Case }y=\dfrac1{x^2}}$
Using the second equation of $(2)$ factor $x^8:$
\begin{align}
&10(1-x^{15})(x^{15}+2)-21(x^3-x^{24})=0,\tag4\\
&10(u^{10}+u^5-2)-21(u^8-u) = 0,\quad\text{where}\quad u=x^3,\\
&(u-1)P_9(u)=0,\\
&\text{where the polynomial}\\
&P_9(u) = 10u^9+10u^8-11u^7-11u^6-11u^5-u^4-u^3-u^2-u+20\\
\end{align}
has the single real root $u\approx -1.57861$ and is positive if $u>0$ (see also Wolfram Alpha).
So the single staionary point in this case is
$$\{x,\ y\ ,f(x,y)\}=\{1,\ 1,\ 0\}.\tag5$$
$\mathbf{\text{Case }x=\dfrac1{y^2}}$
This case leads to the solution $(5),$ because the task is symmetric on the variables $x,y.$
$\mathbf{\text{Case }y=x}$
The second equation of $(2)$ factor $x^{11}$ leads to the equation $(4),$
with the same solution $(5).$
$\mathbf{\text{Bounds}}$
Note that
$$\lim\limits_{x\to+0}f(x,y) = \lim\limits_{x\to+infty}f(x,y) = \lim\limits_{y\to+0}f(x,y) = \lim\limits_{y\to+\infty}f(x,y) = +\infty\ge0.$$
Therefore,
$$\boxed{\mathbf{(a^5+b^5+c^5)^2\ge3(a^7+b^7+c^7).}}$$
Comment: @AlexFrancisco Thank you. Another way is used.
Answer: We start with two identities that we can call Lamé-type identites:
$$(x+y+z)^5 - (x^5+y^5+z^5) = 5(x+y)(x+z)(y+z)(x^2+y^2+z^2+xy+xz+yz)=P$$
$$(x+y+z)^7 - (x^7+y^7+z^7) = 7(x+y)(x+z)(y+z)((x^2+y^2+z^2+xy+xz+yz)^2+xyz(x+y+z))=Q$$
Furthermore we have :
$$(a+b)(b+c)(c+a)=\frac{(a+b+c)^3-a^3-b^3-c^3}{3}$$
Or
With the identity of Gauss we have :
$$a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-bc-ca)$$
So we deduce this :
$$(x+y+z)^5 - (x^5+y^5+z^5) = 5(\frac{(x+y+z)^3+(x+y+z)(xz+yz+yz-x^2-y^2-z^2)-3}{3})(x^2+y^2+z^2+xy+xz+yz)$$
And
$$(x+y+z)^7 - (x^7+y^7+z^7)=7(\frac{(x+y+z)^3+(x+y+z)(xz+yz+yz-x^2-y^2-z^2)-3}{3})((x^2+y^2+z^2+xy+xz+yz)^2+xyz(x+y+z))$$
your inequality is equivalent to with ($xyz=1$) :
$$(x^5+y^5+z^5)^2\ge 3(x^7+y^7+z^7)$$
Or :
$$(x^5+y^5+z^5-(x+y+z)^5+(x+y+z)^5)^2\ge 3(x^7+y^7+z^7-(x+y+z)^7+(x+y+z)^7)$$
Or :
$$(-P+(x+y+z)^5)^2\geq 3(-Q+(x+y+z)^7)$$
Or :
$$-P\geq (3(-Q+(x+y+z)^7))^{0.5}-(x+y+z)^5$$
But :
$$-P=-(x+y+z)^5 + (x^5+y^5+z^5) = 5(\frac{-(x+y+z)^3+(x+y+z)(-xz-yz-yz+x^2+y^2+z^2)+3}{3})((x+y+z)^2-(xy+xz+yz))$$
$$-Q=-(x+y+z)^7 + (x^7+y^7+z^7)=7(\frac{(x+y+z)^3+(x+y+z)(xz+yz+yz-x^2-y^2-z^2)-3}{3})(-(-(x+y+z)^2+xy+zx+yz)^2-xyz(x+y+z))$$
Now we remark that if we put $x+y+z=\alpha$$\quad$ so $xy+yz+zx$ is maximal for $x=y=z=\frac{\alpha}{3}$
Furthermore in $-Q$ all the $xy+yz+zx$ are positive and in $-P$ there are negative so we can minimizing and maximazing the LHS and the RHS respectively
So we can reduce the problem to a one variable problem wich is easily solvable if we remark that :
$$xyz=1 \implies x+y+z\geq 3$$
Comment: I think it's nothing. Can someone, which up voted this "solution",  explain your step?
Comment: Why we need that $xy+xz+yz$ should be maximal? Explain please this point?

prove this inequality by $abc=1$


Nested fields and strong parameters

Question: I am having a complex issue in Rails 4, which I will try to describe below. I am using simple form and awesome_nested_fields gems.
I have a bunch of events with some fields in my app
Here's my working event_controller params before the implementation of accepts_nested_attributes:
private

  def event_params
    params.require(:event).permit(:title, :description, :type_id, :price, :program,
                                  :start_date, :end_date, :image, category_ids: [])
  end

Now I would like to add some speakers to my events, and make the user decide, how many speakers he wants per event. So I'm adding the nested fields gem and making speakers a nested field, as per their documentation.
Event.rb
class Event < ActiveRecord::Base
  has_many :speakers
  accepts_nested_attributes_for :speakers, allow_destroy: true
end

Speaker.rb
class Speaker < ActiveRecord::Base
  belongs_to :event
end

Adding speakers (inside my add event simple_form_for):
  <%= f.nested_fields_for :speakers do |f| %>
      <fieldset class="item">
        <%= f.label :name %>
        <%= f.text_field :name %>

        remove

        <%= f.hidden_field :id %>
        <%= f.hidden_field :_destroy %>
    </fieldset>
  <% end %>

Update controller for strong parameters:
private

  def event_params
    params.require(:event).permit(:title, :description, :type_id, :price, :program,
                                  :start_date, :end_date, :image, category_ids: [],
                                  speakers_attributes: [ :name ])
  end

Now when I launch my app, upon creation of the new event I'm getting:
can't write unknown attribute `event_id'

If I remove the
speakers_attributes: [ :name ]

from the strong parameters I will be able to create my event, however when trying to view or edit it I will get
SQLite3::SQLException: no such column: speakers.event_id: SELECT "speakers".* FROM "speakers"  WHERE "speakers"."event_id" = ?

And of course there are no speakers created in the database.
>> s = Speaker.first
=> nil

I will appreciate any help or advice. Thank you!
=====
UPDATED for the duplications issue
Events controller
  def update
    @event = Event.find(params[:id])

    if @event.update(event_params)
      flash[:success] = "Event updated"
      redirect_to @event
    else
      render @event
    end
  end

event.rb
class Event < ActiveRecord::Base

  belongs_to :type

  has_many :categorizations
  has_many :categories, through: :categorizations
  has_many :speakers
  accepts_nested_attributes_for :speakers, allow_destroy: true

  @today = Date.today

  def self.future_events
    order('start_date ASC').where('start_date >= ?', @today)
  end

  scope :current_events,  lambda { where('start_date < ? and end_date > ?', @today, @today) }
  scope :past_events,     lambda { order('end_date DESC').where('end_date < ?', @today) }

  scope :future_by_type,   lambda { |type| order('start_date ASC').where('type_id = ? and start_date >= ?', type, @today) }
  scope :current_by_type,  lambda { |type| order('start_date ASC').where('type_id = ? and start_date < ? and end_date > ?', type, @today, @today) }
  scope :past_by_type,     lambda { |type| order('start_date ASC').where('type_id = ? and end_date < ?', type, @today) }

  validates :title, presence: true

  mount_uploader :image, ImageUploader

  before_save :define_end_date
  before_save :zero_price

    private

      def define_end_date
        self.end_date ||= self.start_date
      end

      def zero_price
        if self.price.empty?
          self.price = 0
        end
      end
end

Comment: Things to check: Does your speakers table have `event_id` column? Did you run the migration?
Comment: If it was a strong params problem, you'd more likely see an error saying 'unpermitted params -> name of params'. I'd look at the db table as vinodadhika suggests.
Comment: @simonmorley adding event_id to speakers table worked. I can't understand why this was not mentioned in the documentation for the plugin. Now however I'm facing a new problem: when editing and saving an event with nested speakers, it duplicates them. Without any possibility of deleting. Strong parameters again?
Comment: @vinodadhikary adding event_id to speakers table worked. I can't understand why this was not mentioned in the documentation for the plugin. Now however I'm facing a new problem: when editing and saving an event with nested speakers, it duplicates them. Without any possibility of deleting. Strong parameters?
Comment: @DenisG, No I don't think that's strong parameters issue, please post your controller's update action and your model code.  The reason for model is to make sure you don't have any any filters that might cause this issue.
Comment: @DenisG, I don't see anything doing that duplication here.  When you say duplicates them, what is duplicated, speakers?
Comment: @vinodadhikary yes, I push update and all the speakers fields get duplicated
Comment: @DenisG, I wanted to post a comment but added an answer for you try because of the code.
Answer: Now that I think about it, it might be related to strong parameters.  For update to work you need to allow id attributes also.  In your permit params add id for speakers and any other nested nested resources in use that will be updated.
Please give this a try:
def event_params
  params.require(:event).permit(:title, :description, :type_id, :price, :program,
                              :start_date, :end_date, :image, category_ids: [],
                              speakers_attributes: [ :id, :name ])
end

Comment: It works! However I do not have the event :id permission. I have also added '_destroy' to the speaker_attributes array, so now it looks like this: speakers_attributes: [ :id, :name, '_destroy' ] Thank you so much
Comment: please join the fun then http://stackoverflow.com/questions/18316566/nesting-carrierwave-images-in-rails-4
Comment: I will add the :id to event just in case though
Comment: @DenisG, You're welcome.  Don't need to add :id on event for just in case.  I'll update my answer.
Comment: sorry to bother you again, but any idea on how can I remove the nested image I upload for every speaker? I tried nesting even further but failed miserably
Comment: @DenisG, You are not bothering me.  I suggest asking this as a new question for it as the topic is different.

Nested fields and strong parameters


AttributeError: 'str' object has no attribute 'confidence'

Question: Estou desenvolvendo um chatbot e gostaria que ele só respondesse se tivesse determinado nível de confiança na resposta.
# -*- codding: utf-8 -*-
import os
import telebot
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

bot = telebot.TeleBot("TEM UM CÓDIGO DO TELEGRAM AQUI")

#Futaba original
def bot_convencional(message):
    chatbot = ChatBot("Futaba")
    trainer = ListTrainer(chatbot)
    for arquivos in os.listdir('arquivos'):
        chats = open('arquivos/' + arquivos, 'r').readlines()
        trainer.train(chats)

    resposta = chatbot.get_response(message) #ESSE GET DENTRO DO IF DA ÚLTIMA FUNÇÃO
    resposta = str(resposta)

    mensagem = open("arquivos/teste", "w")
    mensagem.write(resposta)
    mensagem.close()

#Recebe e envia uma resposta inicial
@bot.message_handler(commands = ["help", "start"])
def enviar_mensagem(message):
    bot.reply_to(message, "Hey")

#Recebe qualquer outra mensagem
@bot.message_handler(func=lambda message:True)
def mensagem(message):
    bot_convencional(message.text)
    resposta = open("arquivos/teste", "r")
    resposta = resposta.read()

    if float(resposta.confidence) > 0.5:
        bot.reply_to(message, resposta)
    else:
        bot.reply_to(message, "Como você está se sentindo?")
bot.polling()

O problema é que quando eu tento usar o confidence dá o erro

if float(resposta.confidence) > 0.5:
  AttributeError: 'str' object has no attribute 'confidence'

Já usei confidence em outro chatbot e não entendo porque está dando esse problema dessa vez. Alguém pode me ajudar?
Eu queria colocar o get.response da função bot_convencional dentro do if do mensagem.
Comment: Porque `resposta` será o conteúdo do arquivo `arquivo/teste` e isso sempre será uma string. No Python a string não possui o campo `confidence` como está tentando acessar. Se o conteúdo do arquivo for um JSON ou qualquer outro formato estruturado você precisa primeiro avaliá-lo antes de utilizá-lo, com a biblioteca `json`, por exemplo.
Comment: Ah, meu confidence tá tentando pegar a última declaração do usuário e não o corpus dentro da pasta arquivos. Vou colocar o código todo na pergunta: Tem como me dizer como eu colocaria o get.response no if do confidence?
Answer: O problema consiste em você armazenar um objeto Python em forma de string no arquivo, posteriormente lê-lo também como string e utilizá-lo como se fosse o mesmo objeto inicial. NO momento que você grava o objeto como string no arquivo você deixa de tê-lo como um objeto do tipo original; o mesmo passará a ser um objeto instância de string, com os campos de string. Não existe o campo confidence na string, talvez apenas no tipo inicial do seu objeto.
Você grava um objeto como string no arquivo:
#Futaba original
def bot_convencional(message):
    ...
    resposta = chatbot.get_response(message) #ESSE GET DENTRO DO IF DA ÚLTIMA FUNÇÃO
    resposta = str(resposta)

    mensagem = open("arquivos/teste", "w")
    mensagem.write(resposta)
    mensagem.close()

Você lê o arquivo e acessa o campo confidence de uma string, gerando o erro citado na pergunta:
#Recebe qualquer outra mensagem
@bot.message_handler(func=lambda message:True)
def mensagem(message):
    ...
    resposta = open("arquivos/teste", "r")
    resposta = resposta.read()

    if float(resposta.confidence) > 0.5:
        bot.reply_to(message, resposta)
    else:
        bot.reply_to(message, "Como você está se sentindo?")

Se você precisa persistir um objeto em arquivo para utilizá-lo posteriormente, você precisará utilizar alguma técnica de serialização. No Python existe a biblioteca nativa pickle que faz isso.
Grava um objeto serializado em arquivo:
obj = {'foo': 'bar'}

with open('arquivo.pickle', 'wb') as stream:
    pickle.dump(obj, stream)

Lê um objeto serializado a partir do arquivo:
with open('arquivo.pickle', 'rb') as stream:
    obj = pickle.load(stream)

print(obj['foo'])  # 'bar'

Veja funcionando no Repl.it
Answer: Para o confidence eu precisava a acessar o chatbot.get_response(message). Para isso, criei uma variável chamada corpus pra armazenar esse corpus = chatbot.get_response(message), tornei ela global e acessei pelo if do confidence.
FUNÇÃO QUE ARMAZENA O CHATBOT
def bot_convencional(message):
    chatbot = ChatBot("Futaba")
    trainer = ListTrainer(chatbot)
    for arquivos in os.listdir('arquivos'):
        chats = open('arquivos/' + arquivos, 'r').readlines()
        trainer.train(chats)

    resposta = chatbot.get_response(message)
    resposta = str(resposta)
    global corpus
    corpus = chatbot.get_response(message)

    mensagem = open("arquivos/teste", "w")
    mensagem.write(resposta)
    mensagem.close()

FUNÇÃO QUE RESPONDE AS MENSAGENS
#Recebe qualquer outra mensagem
@bot.message_handler(func=lambda message:True)
def mensagem(message):
    bot_convencional(message.text)
    resposta = open("arquivos/teste", "r")
    resposta = resposta.read()

    if float(corpus.confidence) > 0.5:
        bot.reply_to(message, resposta)
    else:
        bot.reply_to(message, "Como você está se sentindo?")
bot.polling()

Eu não sei se isso é certo, mas funcionou.


multiple click open multiple share screens while loading first share screen

Question: I applied share package to share some data  I want to show a loader while opening share screen in android and IoS. if user click multiple times before showing share screen it open multiple share screen.
<code>ListTile(
                title: Row(
                  children: <Widget>[
                    Icon(
                      Icons.thumbs_up_down,
                      color: DrawerIconsText,
                      size: 24.0,
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text('Share App'),
                  ],
                ),
                onTap: () =>
                    Share.share('Share this data'),
              ),
</code>
Comment: You want to stop opening multiple screens when continuous click of view right ?
Comment: You can add a manual throttle for this as @AnkitMahadik suggested.
But better also write a ticket in the library GitHub
Comment: Yes Ankit Mahadik
Answer: Hy,
you should use Statefulwidget extendtion to get solve this problem.
As example:
<code>// change your class extends to Statefulwidget

bool _isShare = false;

@override
didupdatewidget(){
  // change duration time up to you
  if (_isShare)
    new Timer(const Duration(milliseconds: 400), () {
      setState(()=> _isShare = false);
    });
}

ListTile(
                title: Row(
                  children: <Widget>[
                    Icon(
                      Icons.thumbs_up_down,
                      color: DrawerIconsText,
                      size: 24.0,
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text('Share App'),
                  ],
                ),
                onTap: () {
                  if (!_isShare) Share.share('Share this data');
                  setState(() = _isShare = true)
                },
              ),
</code>
Comment: in such a way user will be able to multiple clicks on button I actually want to show a loader for the time while loading the screen.


Absolute value of a complex number (can't uderstand notes)

Question: I am taking a MOOC and in handouts there is the following expression:
$\left\lvert\alpha\right\rvert = \left\lvert\alpha_r + \alpha_c\right\rvert = \sqrt{\alpha^2_r+\alpha_c^2} = \sqrt{(\alpha_r+i\alpha_c)(\alpha_r-i\alpha_c)} = \sqrt{\alpha\bar\alpha} = \left\lvert\bar\alpha\right\rvert$
My question is how did they got from
$\sqrt{\alpha^2_r+\alpha_c^2}$
to
$\sqrt{(\alpha_r+i\alpha_c)(\alpha_r-i\alpha_c)}$? I am pretty sure that it should be $\sqrt{(\alpha_r\pm\alpha_c)^2 \pm 2\alpha_r\alpha_c}$.
Also in the handouts expression is missing some parentheses, so it looks like this: $\sqrt{\alpha_r+\alpha_c)(\alpha_r-\alpha_c}$
Can anyone clarify this for me?
Comment: @DietrichBurde Massive Open Online Course
Comment: Thank you. I found it [here](https://en.wikipedia.org/wiki/Massive_open_online_course). Hope it was not too massive, this course.
Comment: What is a MOOC?
Comment: Massive open online course
Comment: looks like there is a typo
Answer: When dealing with complex numbers $s=x+iy$ we can factor expressions such as $x^2+y^2=(x-iy)(x+iy)$ Due to $(i)(-i)=1$. It is essentially like a difference of 2 squares.
Answer: $\alpha$=$\alpha_r+i\alpha_c$ so the i was left out by mistake .Put it back in and you are fine.
Comment: I'd say this was a massive mistake.
Comment: Sure was but when you get used to a subject ,sometimes you can suspect that it was their mistake .However you should in my opinion always find out when you don't see why some technical detail holds ,so you are to be commended for pursuing it .Good luck
Comment: that was actually my mistake.


How P.test(V value) in Titan graph traversal query works?

Question: Came across a scenario where I need to write a titan query using GraphTraversal api which has various clauses like in, contains, within etc.
To form the required clauses I am utilising P.within(..), P.inside(..), P.test(..) etc. predicates. Following is an illustration of traversal instance
traversal.has("field1", P.within(new String[]{"value1", "value2"})).
            has("field2", P.test((r1, r2) -> {
                    return ((String)r1)).contains((String)r2));
                }, "someVal"));

I want to understand how Titan internally evaluates this query?
Does it evaluates all predicates after loading all vertices in memory?
Answer: Standard predicates like P.within will be optimized whenever possible (in your example, if you would have an index over field1, Titan would use it). Custom predicates on the other hand can't be optimized; as you say, Titan will load all vertices into memory and then apply the filter predicate.


iOS Unexpected platform condition (expected 'os', 'arch', or 'swift') - Reachability

Question: I just update my pods. after update Reachability causing an error

Unexpected platform condition (expected 'os', 'arch', or 'swift')

I tried to build and clean but it does not work. what's the solution?

Please help me to fix this. Thanks in advance.
Comment: `#if targetEnvironment` is a new feature of Swift 4.1/Xcode 9.4(?). Probably you are using an older version.
Comment: I am using Xcode 9, swift 4.0
Comment: ... that explains it.
Comment: But I can't update to it Xcode 10, what the solution?
Comment: use this instead of the 1 u r trying.

#if (arch(i386) || arch(x86_64)) && os(iOS)

#endif
Comment: Use a previous release - v4.1.0 should work for you
Answer: use this 1
#if (arch(i386) || arch(x86_64)) && os(iOS)

#endif

Comment: Hello, to help others understand your answer, consider including a short description of your code and how it solves the posted question.
Answer: You can try as Muhammad says.
I suggest the following code which is very easy to maintain. Copy paste the following code to a file and try yourself.
import Foundation
import SystemConfiguration

class Network {

    // Declarations
    static let shared = Network()

    // Check has Network
    func isConnected() -> Bool  {

        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }

}

Create a swift file and put the above code on that file.
Whenever you want to check the network status just use the following code
if Network.shared.isConnected() {

   print("Network available")
} else {

   print("Not connected")
}


iptables + TEE doesn't work correctly

Question: On my server, I want to duplicate all the traffic to an other host.  I use iptables with TEE module:
iptables -t mangle -A PREROUTING -i eth0 -j TEE --gateway IP_SERVER2

I check the rule: iptables -t mangle -L
=> The rule is here but it doesn't work... The other server receive nothing.
When I do a tcpdump: tcpdump dst IP_SERVER2
=> 0 packets received by filter
I tried to enable /proc/sys/net/ipv4/ip_forward, /proc/sys/net/ipv4/conf/all/accept_redirects, and /proc/sys/net/ipv4/conf/all/send_redirects.  I changed to 1 the net.ipv4.ip_forward option in /etc/sysctl.conf, it still doesn't work.
Have you got an idea what's wrong?
Comment: would this help? http://serverfault.com/questions/179968/how-to-tee-udp-packets-onto-a-different-host
Answer: IP_SERVER2 needs to be on your local network according to iptables manpages.
Comment: Really? Ok I understand better now...
Comment: Have you an idea how to duplicate packets on another network?
Comment: I am not sure why iptables has such a limitation, but the only way I can think of is to log the packets (probably just tcpdump - see `-G` option) and ship them in files to your external network.
Comment: I've done a vpn connection between the two servers (in order to be in the same private network) and now the duplication works great.
Thanks you.

iptables + TEE doesn't work correctly


Can I treat a categorical variable (such as income categories) as a numeric predictor?

Question: Suppose that I have a survey question about income level, with options like:
Less than 10,000
 10,001 - 20,000
 Greater than 20.000
Then could I assume a numeric value of 5,000, 15,000, and 20,000 for each of my options above when I run a regression? Are there any references that talk about this issue?
Answer: That would not be very appropriate.  If it is a dependent variable it should be treated as ordinal.  If an independent variable then represent it as categorical with three levels, requiring 2 indicator variables.  I'm surprised so few categories were used.


Qual a função dos descritores em Python?

Question: Em Python existe o protocolo dos descritores que é, basicamente, definir uma classe para controlar o acesso aos atributos de outra, mas minha dúvida é, seria essa a real funcionalidade de um descritor, somente retirar da classe o trabalho de definir a lógica de acesso a seus atributos?
Aqui segue um script:
class Descriptor(object):

    def __init__(self, name = None):
        self.name = name

    def __get__(self, instance = None, owner = None):
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if len(value) < 3:
            raise ValueError
        instance.__dict__[self.name] = value

    def __delete__(self, instance):
        del instance.__dict__[self.name]

class Person(object):

    name = Descriptor('name')

Answer: A resposta a seguir foi baseada no artigo Descriptor HowTo Guide, escrito por Raymond Hettinger¹, na documentação oficial do Python.
Definição e introdução
Em geral, um descritor é um atributo de objeto com comportamento de ligação cujo o acesso aos campos é sobrescrito por métodos do próprio descritor. Estes métodos são __get__(), __set__() e __delete__(). Se qualquer um desses métodos for definido pelo objeto, este pode ser chamado de descritor.
O comportamento padrão do Python para retornar um campo (get), atribuir a um campo (set) e excluir um campo (delete) é retorná-lo, atribuí-lo ou excluí-lo de um dicionário no objeto. Por exemplo, a.x buscará primeiro o valor de x em a com a.__dict__['x'], após buscará no tipo de a com type(a).__dict__['x'] e assim por diante, através das classes bases de a, até chegar em object, excluindo as metaclasses. Se o valor encontrado para o campo x nesse processo for um objecto que implementa o protocolo de descrição (ser um descritor), o comportamento padrão será alterado para a invocação do método no descritor.
Descritor é um protocolo poderoso de uso geral. Ele é o mecanismo por traz das propriedades, métodos, métodos estáticos e super(), utilizado pela linguagem desde a versão 2.2 para definir as classes no novo estilo.
Protocolo descritor
Como citado, o descritor é composto de três métodos, que possuem as seguintes estruturas:

descr.__get__(self, obj, type=None) -> value
descr.__set__(self, obj, value) -> None
descr.__delete__(self, obj) --> None

E somente isso. Um objeto que define qualquer um desses métodos será considerado um descritor e poderá ser utilizado para sobrescrever o comportamento padrão do Python descrito acima.
Se um objeto define ambos os métodos __get__() e __set__() ele será considerado um descritor de dados (data descriptors). Por sua vez, descritores que definirem apenas __get__() serão chamados de descritores de não-dados² (non-data descriptors) - esse último geralmente utilizado para métodos, mas há outras possibilidades.
A diferença entre um descritor de dados e um descritor de não-dados é como será considerada a sobrescrita com respeito a uma entrada do dicionário da instância. Se o dicionário da instância possuir uma entrada com o mesmo nome que um descritor de dados, o descritor de dados terá precedência. Porém, se o dicionário possuir uma entrada com mesmo nome que um descritor de não-dados, o dicionário terá precedência.
Para definir um descritor de apenas leitura, basta definir ambos os métodos __get__() e __set__() levantando uma exceção AttributeError em __set__().
Invocando um descritor
Um descritor pode ser chamado diretamente através do método. Por exemplo, d.__get__(obj), onde d é o descritor e obj o objeto descrito.
Alternativamente, é muito mais comum um descritor ser chamado através do acesso a campos. Por exemplo, obj.d buscará por d no dicionário de obj; se for um descritor, definindo o método __get__(), então o Python chamará d.__get__(obj), considerando as regras de precedência, obviamente.
Detalhes da invocação dependem se obj é uma instância ou uma classe.
Para instâncias, a lógica se encontra em object.__getattribute__(), que transforma a chamada b.x em type(b).__dict__['x'].__get__(b, type(b)). A implementação trabalha sobre a cadeia de precedência que define que descritores de dados possuem precedência sobre variáveis de instâncias, mas estas possuem precedência sobre descritores de não-dados. Para mais detalhes, ver o código fonte de PyObject_GenericGetAttr() em Objects/object.c.
Para classes, a lógica se encontra em type.__getattribute__(), que transforma a  chamada B.x em B.__dict__['x'].__get__(None, B). Em Python puro, se assemelha a:
def __getattribute__(self, key):
    "Emulate type_getattro() in Objects/typeobject.c"
    v = object.__getattribute__(self, key)
    if hasattr(v, '__get__'):
        return v.__get__(None, self)
    return v

Os pontos importantes para lembrar são:

Descritores são chamados através do método __getattribute__();
Sobrescrever o método __getattribute__() previne chamadas automáticas de descritores;
object.__getattribute__() e type.__getattribute__() fazem chamadas diferentes a __get__();
Descritores de dados sempre sobrescreve o comportamento do dicionário da instância;
Descritores de não-dados podem ser sobrescritos pelo dicionário da instância;

O objeto super() possui uma implementação personalizada de __getattribute__() para chamar descritores. A chamada super(B, obj) buscará em obj.__class__.__mro__ a classe base A que imediatamente segue B e então retorna A.__dict__['m'].__get__(obj, B). Se não for um descritor, m será retornado sem modificações; se não estiver no dicionário, m será revertido para uma busca em object.__getattribute__().
Exemplo
O código a seguir define uma classe cujos objetos serão descritores de dados que exibem uma mensagem quando vosso valor é retornado ou definido. Sobrescrever o método __getattribute__ seria uma abordagem interessante para implementar a mesma lógica para todos os campos, porém, com o descritor, será possível definir quais os campos que serão monitorados.
class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print('Retrieving', self.name)
        return self.val

    def __set__(self, obj, val):
        print('Updating', self.name)
        self.val = val

class MyClass(object):
    x = RevealAccess(10, 'var "x"')
    y = 5

Assim, fazemos:
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5

Veja funcionando no Repl.it | Ideone | GitHub GIST
Propriedades
A forma mais fácil de se implementar o descritor no Python é utilizando uma propriedade.
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

A própria documentação dá um exemplo de como fazer:
class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I'm the 'x' property.")

Inclusive, a implementação equivalente da propriedade em Python puro é exatamente a implementação de um descritor de dados:
class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

Funções e métodos
Dicionários de classes armazenam as referências aos métodos como funções. Na definição de uma classe, métodos são definidos usando def ou lambda, que são as ferramentas de criação de funções. Métodos só se diferenciam de funções normais por causa de seu primeiro argumento, que é exclusivo para o objeto instância da classe.
Para suportar a chamada de métodos, funções definem o método __get__() para ligar o método à instância durante a chamada. Isto significa que todas as funções são descritores de não-dados que retornam um método ligado quando chamadas de um objeto.
Em Python puro, a função seria algo como:
class Function(object):
    . . .
    def __get__(self, obj, objtype=None):
        "Simulate func_descr_get() in Objects/funcobject.c"
        if obj is None:
            return self
        return types.MethodType(self, obj)

Métodos estáticos e de classe
Descritores de não-dados definem um mecanismo simples para variações nos padrões usuais que fazem a ligação de funções para métodos. Por exemplo, descritores de não-dados convertem a chamada obj.f(*args) em f(obj, *args) e klass.f(*args) em f(*args).
O quadro abaixo apresenta todas as transformações para os diversos casos:

Quadro: exemplifica as transformações de uma função, um método estático e um método de classe quando invocados de um objeto e uma classe.
Métodos estáticos retornam a própria função, sem modificações. Chamando tanto c.f ou C.f o equivalente será object.__getattribute__(c, 'f') ou object.__getattribute__(C, 'f'). Como resultado, não faz diferença invocar um método estático de um objeto ou de uma classe.
A implementação equivalente em Python puro seria:
class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f

A diferença para um método de classe é que este refere a referência da classe como parâmetro, mas igualmente não faz diferença ao invocá-lo de um objeto ou de uma classe. A implementação equivalente em Python puro seria:
class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args):
            return self.f(klass, *args)
        return newfunc

Considerações finais

O protocolo dos descritores consiste basicamente em definir uma classe para controlar o acesso aos atributos de outra, mas minha dúvida é, seria essa a real funcionalidade de um descritor?

Sim, com o protocolo de descritor, você transfere a responsabilidade de regras de negócio sobre um campo para outra classe. Desta forma, você mantém a classe original focada na sua própria responsabilidade e deixa detalhes sobre os seus campos para uma classe específica.
Mas, perceba que, como é um protocolo de uso geral, seu uso não possui limitação. A linguagem Python define todas as funções como sendo descritores; métodos são descritores, métodos estáticos e de classe são descritores; propriedades são descritores; e vai além.
Uma aplicação, por exemplo, seria para um campo idade, que não faz sentido possuir valores negativos, então pode-se definir um descritor para este campo:
class Pessoa:
    @property
    def idade(self):
        return self._idade

    @idade.setter
    def idade(self, value):
        if value < 0:
            raise ValueError('Idade não pode ser negativa')
        self._idade = value

Veja funcionando no Repl.it | Ideone | GitHub GIST
Basicamente criamos um descritor de dados que validará o valor antes de atribuí-lo ao campo. Seria o mesmo que fazer:
class Idade(object):
    def __init__(self, value=None):
        self.value = value

    def __get__(self, obj, objtype):
        return self.value

    def __set__(self, obj, val):
        if val < 0:
            raise ValueError
        self.value = val

class Pessoa(object):
    idade = Idade(30)

Veja funcionando no Repl.it | Ideone | GitHub GIST
Mas qual seria a vantagem de implementar uma classe ao invés de apenas definir uma propriedade? Reutilização de código. Ao invés de definir o descritor Idade, poderia ser definido o descritor Positive, que faz a validação de números negativos e utilizá-lo, por exemplo, em dados de uma data, dia, mês e ano, que também não são negativos (geralmente).

1: Se há uma pessoa que você precisa seguir (não fisicamente) para aprender Python, Raymond Hettinger é essa pessoa.
2: Não achei uma tradução fiel para non-data, então deixei não-dados.


Using ioreg -l with awk to display the last 6 characters of the serialnumber on a mac

Question: I wish to use a script to grab a certain part of the serial number on a macbook air and use it in combination with another variable to create a Computer name based on the last 6 characters of the computers serial number.
system_profiler SPHardwareDataType | grep 'Serial Number (system)' |  awk '{print substr( $0, length($0) - 5 )}'
This code did just that but it doesn't work in single user mode. system_profiler returns a x86PlatformPlugin error and so i tried:
ioreg -l | grep IOPlatformSerialNumber | awk '{print substr( $0, length($0) - 6 )}'

with good result except for the serial ending in a double quote ".
How can i modify the output to get rid of that last character and leave me with the last 6 characters of the Serial Number?
Answer: You're very close; just tell awk to take the string of the right length:
ioreg -l | grep IOPlatformSerialNumber | awk '{print substr( $0, length($0) - 6, 6 )}'

From the documentation:

substr(string, start, length)
This returns a length-character-long substring of string, starting at character number start. The first character of a string is character number one.
For example, substr("washington", 5, 3) returns "ing". If length is not present, this function returns the whole suffix of string that begins at character number start. For example, substr("washington", 5) returns "ington". This is also the case if length is greater than the number of characters remaining in the string, counting from character number start.


Debussy's 'sneaky Tristan' in his own performance of 'Golliwogg's Cakewalk'?

Question: I don't understand this comment under the piano ROLL recording on Youtube :

User [Henry Baxter]:
Sneaky bit of tristan at 1:10

Am I right that 'tristan' refers to the Tristan chord?
Even if so, what's sneaky in Debussy's performance?
Answer: It's a little sneakier than that. Here's the score; look for yourself. The passage in question starts at m. 61. Debussy quotes the melody at pitch of the opening measure-and-a-half of the Prelude to Tristan, but he never quite lands on the Tristan chord - there's always something a little off. He repeats it several times, landing a couple of times each on A♭ minor with added fourth and a minor seventh chord on E♭ (plus a few more, none of which is the Tristan chord) before dissolving the quotation into cakewalk figuration.


How to update the value of DatetimeIndex of a single row in a pandas DataFrame?

Question: In a python pandas DataFrame, I would like to update the value of the index in a single row (preferably in-place as the DataFrame is quite large).
The index is DatetimeIndex and the DataFrame may contain several columns.
For instance:
In [1]: import pandas as pd
In [2]: pd.DataFrame({'DATA': [1,2,3]},
                      index=[pd.Timestamp(2011,10,01,00,00,00),
                             pd.Timestamp(2011,10,01,02,00,00),
                             pd.Timestamp(2011,10,01,03,00,00)])
Out[5]:
                     DATA
2011-10-01 00:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

The desired output is:
                     DATA
2011-10-01 01:00:00     1   <---- Index changed !!!
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Is there a simple (and cheap) way to do this for large DataFrames ?
Assuming the location of the sample is known (for instance it is the nth row the needs to be changed) !
Answer: One possible solution with Series.replace, but first need convert Index.to_series:
df.index = df.index
             .to_series()
             .replace({pd.Timestamp('2011-10-01'): pd.Timestamp('2011-10-01 01:00:00')})
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Another solution with Index.where (new in 0.19.0):
df.index = df.index.where(df.index != pd.Timestamp('2011-10-01'),
                          [pd.Timestamp('2011-10-01 01:00:00')])

print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Solution with appending new row and remove old one by drop, last sort_index:
df.loc[pd.Timestamp('2011-10-01 01:00:00')] = df.loc['2011-10-01 00:00:00', 'DATA']
df.drop(pd.Timestamp('2011-10-01 00:00:00'), inplace=True)
df.sort_index(inplace=True)
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Another solution if need replace by value not by position:
df.index.set_value(df.index, pd.Timestamp(2011,10,1,0,0,0), pd.Timestamp(2011,10,1,1,0,0))
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Last solution with converting index to numpy array from comment:
i = 0
df.index.values[i] = pd.Timestamp('2011-10-01 01:00:00')
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Comment: These are working indeed but they seem to perform some kind of search and they re-assign the whole index. I know the index of the row to be changed, so can I use this information to avoid searching through a really big index vector ?
Comment: I add another solution, please check it.
Comment: How about this one ? df.index.values[i] = pd.Timestamp('2011-10-01 01:00:00') ? It works for me but I don't know if it has any side effects. If you don't think so, please add it to your answer.
Comment: I test it, please give me a time.
Comment: It is indeed faster but it still includes a search somehow. A search is redundant if I know the exact position. (this is about the  df.set_value() method).
Comment: thank you for accepting! I add your solution to answer, it is really interesting.
Answer: A Fast way would be a direct lookup if you already are aware of the index to be operated upon and then you can set it's value accordingly with the help of Index.set_value:
df.index.set_value(df.index, df.index[0], pd.Timestamp(2011,10,1,1,0,0))
#                  <-index-> <-row num->  <---value to be inserted--->

This is an inplace operation, so you don't need to assign back the result to itself.
Comment: Is there a better documentation for this method "Index.set_value" than the one on the pandas docs page ? All what is says: use this if you know what you're doing !!! Is it performing a binary search so it needs a sorted array for example ?
Comment: I've commented to provide further explanation. I Know the doc-page lacks an illustration regarding it's usage. But if you go through answers regarding `DF.set_value`, you would fairly get an idea as it works very similar to that.


Recuperar carrinho de compras após fechar e abrir o navegador

Question: Estou montando um carrinho de compras com JSF ele está funcionando, mas não da forma que acredito ser o correto.
Exemplo:
Quando entro em sites de vendas, mesmo não estando logada, consigo adicionar itens no carrinho, e mesmo fechando e abrindo o navegador esses itens permanecem lá. No meu caso, quando saio do navegador e entro novamente os itens não permanecem, pois a sessão muda quando o navegador é fechado, nesse caso, é inútil gravar a sessão em itens para recuperá-la quando o usuário retorna ao site. Já pesquisei o uso de cookies para esse caso, mas em nada me ajudou. Alguém poderia me ajudar informando como poderia implementar essa situação? Se é implementado usando cookies e sessão mesmo?
Estou usando JSF, JPA. Qualquer ajuda ficarei muito grata!
Comment: Sim, salva no cookie alguma informação para você recupere o carrinho de compras.. claro que você deve salvá-lo do lado server também
Comment: Tentei fazer um exemplo usando JSESSIONID, se não saio do navegador ele funciona bem, olha a saída:  Session Id = D5913F3F699B66B8AFEDD32E108F9C92 //nova
JSESSIONID cookie = F688E7A616018963013062251D16A805 //sessão anterior, mas quando fecho o navegador e abro novamente ele ignora a sessão anterior olha o que sai: Session Id = 944D48C7F4BE1F807B207CC9694A629E
JSESSIONID cookie = 944D48C7F4BE1F807B207CC9694A629E Nesse caso é um teste que estou fazendo, será se o problema é porque nesse caso, ainda não salvei essa sessão no servidor?
Comment: Você não vai voltar a sessão anterior, fechou o navegador ela se perdeu, você vai iniciar uma nova sessão. Seu cookie pode ter alguma informação que identifique o usuário, um token, id, etc, dai você inicia uma nova sessão... claro que o carrinho precisa estar salvo do lado server pra poder recuperar. Você pode usar um banco *nosql* como MongoDB para salvar o carrinho, e quando efetivar salvar no seu banco transacional
Comment: Quando o usuário esta logado não tenho esse problema, pois salvo o item com a identificação do usuário, o problema é quando o usuário não esta logado. Seria correto fazer essa identificação por ip?
Comment: Nesse caso você poderia gerar um identificador temporário enquanto não está logado. IP não é uma boa ideia porque se ele estiver atrás de um proxy, você pode acabar lendo somente o IP do proxy da empresa por exemplo, e se mais de um usuário da mesma empresa acessar o site, vai ter o mesmo IP, o que vai ser um problema (todos vão ver o mesmo carrinho)
Comment: Pensei a mesma coisa, realmente ip não é uma boa idéia
Answer: A sessão só pode guardar atributos enquanto o cliente estiver interagindo com sua aplicação, dentro do período de validade daquela sessão. Em caso de inatividade por um período maior do que a validade ou se o usuário fechar o navegador, a sessão é perdida. Você mesma já constatou isso, verificando 2 JSESSIONIDs diferentes ao fechar e abrir novamente o navegador.
Portanto, se você usar apenas a sessão para manter o estado, não conseguirá resolver o seu problema.
Para identificar unicamente o cliente, uma boa opção seria usar um cookie mesmo. O cookie é persistido no próprio navegador do cliente, geralmente em um arquivo texto, durante a validade que você especificar.
Nesse caso, você precisaria definir um cookie específico para sua finalidade. O seu código teria que salvar os itens do carrinho em um banco de dados e atribuir um ID único a esse conjunto de itens salvos. Você poderia aproveitar o próprio JSESSIONID, se você não quiser gerar uma String aleatória. Lembre-se de atualizar o banco de dados cada vez que o usuário modificar algo no carrinho, colocando ou retirando algum produto.
O cookie seria criado e enviado ao navegador, tendo como conteúdo aquele ID único. Ajuste a validade do cookie de acordo com seu requisito de negócio. Ficaria parecido com isso:
String valorCookieCarrinho = ID; //O que você quiser definir, basta ser único
Cookie cookieCarrinho = new Cookie("cookieCarrinho_br.com.seusite", valorCookieCarrinho);
cookieCarrinho.setMaxAge(60*60*24*7); //Defina a validade - 1 semana?
response.addCookie(cookieCarrinho);

Em cada visita ao site, para a qual ainda não exista um carrinho ativo você procura o cookie, obtém o ID e busca os itens correspondentes no banco de dados. Caso eles existam, você coloca eles no carrinho que está na sessão. É importante verificar primeiro, para não correr o risco de sobrescrever um carrinho atualizado.
Cookie[] cookies = request.getCookies();

if (cookies != null) {
 for (Cookie cookie : cookies) {
   if (cookie.getName().equals("cookieCarrinho_br.com.seusite")) {
     //pegar o valor do ID com cookie.getValue() e buscar no bd
    }
  }
}

Não se esqueça de fazer o banco de dados expurgar os registros abandonados. Para isso, guarde a data em cada registro de carrinho.
Comment: Olá Guilherme, estudei mais um pouco a situação e implementei com cookie, segui a sua ideia mas implementei usando a biblioteca do Ominifaces. Muito obrigada!
Comment: Olá Guilherme, muito obrigada pela resposta e pelo seus exemplos. Então meu problema é que mesmo criando um cookie com uma identificação eu não tenho como saber se um usuário não logado é o mesmo que entrou no sistema adicionou itens no carrinho e por algum motivo, perdeu a sessão retornou ao site e perdeu tudo que já tinha inserido. Fiz de um jeito que não sei se é correto, mas foi a forma que encontrei, estou identificando o usuário não logado pelo ip "externo" e estou salvando essa informação como id, na hora que qualquer pessoal entra no carrinho busco se possui dados por IP.
Comment: Dessa forma, fiz alguns teste e esta respondendo bem, um problema é que o IP sofre alterações de vez em quando, de ontem pra hoje o meu já mudou duas vezes, mas por os itens ficar no carrinho por um determinado tempo, o risco não é tão ruim.
Comment: Pelo IP realmente não é a melhor maneira. Principalmente porque vários clientes podem ter o mesmo IP. No caso da rede de uma empresa, por exemplo, geralmente há um proxy que fica na saída para a internet com o chamado "IP de borda".
Comment: O cookie deveria funcionar, usando um ID único, como expliquei. Edite a resposta e descreva melhor o que você fez. Em que momento está *setando* o cookie? Em que momento está recuperando seu valor? Lembre-se que a sessão nunca será a mesma. Não adianta tentar buscar dados na nova sessão.


Somar linhas iguais de diferentes tabelas no R

Question: Estou tendo como saída diversas tabelas com três colunas, como por exemplo:
Inicial            Final        Mudanca
       1                 1              200
       1                 3              500
       3                 1               250
       3                 3               175
Tabela 2
   Inicial         Final        Mudanca
       1                 3              180
       1                 5              265
       3                 3               147
       3                  7              155

Preciso somar a última coluna das tabelas (Mudanca) de maneira que as linhas da coluna Inicial e Final da Tabela 1 seja igual a cada linha da Inicial e Final da Tabela 2, gerando uma tabela desse tipo
Inicial            Final        Mudanca
       1                 1          200
       1                 3           680
       1                 5           265
       3                 1            250
       3                 3            322
       3                 7           155

Estou tentando dessa forma, mas está dando erro:
for (row in 1:nrow(t1) {
  t2[t2$Inicial == row$Inicial && t2$Final == row$Final,t2$Mudanca] <- row$Mudanca + t2[t2$Inicial == row$Inicial && t2$Final == row$Final,t2$Mudanca]
}

Alguém pode me ajudar, por gentileza?
Answer: Através de duas maneiras consegui resolver isso:
A) usando aggregate e rbind
aggregate(Changes ~ ., rbind(t1, t2), sum)
B) ou criando uma nova coluna com as somas:
joined = merge(t1,t2,by = c("Initial","Final"),all=T)
    joined["Changes.final"] <- apply(joined[,c("Changes.x","Changes.y")],
                                 FUN = function(x)sum(x,na.rm=T), MARGIN = 1)


como ligar a um servidor ftp

Question: Tenho este código queria ligar me ao ftp. Pelo browser eu consigo, mas pelo código diz-me que não consegue fazer login.
Segue o código,escondi os dados:
$ftp_server = "" ;
$ftp_user_name = "" ;
$ftp_user_pass = "" ;
$depth = 10;

$conn_id = ftp_connect($ftp_server) ;
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (!$login_result) { die("Couldn't log in to FTP account."); }

$dir = array(".");
$a = count($dir);
$i = 0;
while (($a != $b) && ($i < $depth)) {
  $i++;
  $a = count($dir) ;
  foreach ($dir as $d) {
    $ftp_dir = $d."/" ;
    $newdir = ftp_nlist($conn_id, $ftp_dir);
    foreach ($newdir as $key => $x) {
      if ((strpos($x,".")) || (strpos($x,".") === 0)) { unset($newdir[$key]); }
      elseif (!in_array($x,$dir)) { $dir[] = $x ; }
    }
  }
  $b = count($dir) ;
}

print_r($dir) ;

ftp_close($conn_id);

?>

Answer: Viva,
Eu normalmente uso esta class que encontras no github: https://github.com/Nicolab/php-ftp-client
$ftp = new \FtpClient\FtpClient();
$ftp->connect($host, true, 22);
$ftp->login($login, $password);
$ftp->putAll($source_directory, $target_directory);

É muito fácil de usar, e tem um controlo de erros magnifico ;)
Podes fazer login também por ssl.
Comment: boas a questao é que tenho varias directorias...queria listar e fazer o download...nunca usei essa classe

como ligar a um servidor ftp


How to solve the issue in array search

Question: I am doing a site for publishing ads, in a section of adding the campaign (ads) I need to prevent certain badwords from the campaign title. So I have checked those title when the advertiser adds the campaign. These badwords are stored in a file in txt format. I have used this code.
$string = $description;

$badwords = file( "badwords.txt" );
if ( $badwords ) {
  foreach ( $badwords as $line ) {
    if ( preg_match("/$line/", $string) ) {
      echo $string; die();
      return array ( 0, $language['bad_words_error'] );
    }
  }
}

I have tried in_array() but i can't match the content in $string.
if ( in_array($string, $badwords) ) {
  echo "The word ".$string ." is a bad keyword";
}

Comment: Have you tried debugging? (Echoing both lines and seeing if it really matches?) Also, try `trim()`ming your lines.
Comment: @Truth Thanks it works. I used the trim() before checking.
Answer: Usually, the problem comes from trailing spaces left in the file.
To solve this, use trim() on individual $lines.
Answer: foreach ($badwords as $word) {
  if (preg_match("/\b$word\b/", $string)) {
    echo $string . ' contains bad word ' . $value;
  }
}

I am assuming your txt file contains one bad word per line. Also be careful your badwords don't include characters which may corrupt regular expression pattern.

How to solve the issue in array search


How to get data from json object with fetch in javascript?

Question: I'm trying to get values of an object in JSON file with javascript.
My JSON file looks like this;
<code>{
    "product":"gill",
    "body":
        {
        "name":"gill",
        "thumbnail":"https://www.example.com/gill.jpg"
    },
    "product":"folded",
    "body":
        {
        "name":"folded",
        "thumbnail":"https://www.example.com/folded.jpg"
    }
}
</code>
and my JS file looks like this:
<code>window.onload = function(){
 const apiUri ="../test.json";
 const product = document.getElementById("products").children[0].id;
    const data = { product : product };
        fetch(apiUri, {
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then((response) => response.json())
        .then((json) => {
            Image.setAttribute("src",json.body.thumbnail)

        })
        .catch((err) => console.log(err));
        console.log(data);
}
</code>
when page loads, the Image src gets always the last product in json file, which is folded.
I want to search for a product which has been get by element id, and set the image src of that product in JSON file.
Comment: Your JSON is invalid. You can't have (meaningful) duplicate keys.
Answer: See the JSON specification:

The names within an object SHOULD be unique.

and

When the names within an object are not    unique, the behavior of
software that receives such an object is    unpredictable.  Many
implementations report the last name/value pair    only.  Other
implementations report an error or fail to parse the    object, and
some implementations report all of the name/value pairs,    including
duplicates.

Change the design of your JSON.
If you want to have multiple products, use an array of products.


Irrationals in $[0,1]$ does not have measure zero

Question:
Show that the set of irrationals in $[0,1]$ does not have measure zero in $\mathbb{R}$

By definition of measure zero, we must show that there exists $\epsilon>0$ such that the set $A$ of irrationals in $[0,1]$ cannot be covered by a countable collection of intervals $[a_1,b_1],[a_2,b_2],\ldots$ with total length less than $\epsilon$.
So I take $\epsilon=1/2$, and suppose for contradiction that the countable collection of intervals $[a_1,b_1],[a_2,b_2],\ldots$ covers $A$ and $(b_1-a_1)+(b_2-a_2)+\ldots < 1/2$.  How can I continue?
EDIT: Thanks for all the responses. Actually I haven't learned any measure theory, only the definition of measure zero in real analysis. Is it possible to proceed using only that? (By the way, sure, I can show $\mathbb{Q}\cap[0,1]$ has measure zero.)
Comment: Why not use the fact that $m([0,1]) = m(\mathbb{Q}\cap[0,1]) + m(\mathbb{Q}^c\cap[0,1])$?
Comment: Can you show a countable set (in particular, $\Bbb Q\cap[0,1]$) has measure zero? If so, then the rest follows
Comment: Actually I haven't learned any measure theory, only the definition of measure zero in real analysis. Is it possible to proceed using only that? (By the way, sure, I can show $\mathbb{Q}\cap[0,1]$ has measure zero.)
Answer: Ok, you have a collection $[a_1, b_1],...,[a_n, b_n]$ that covers $A$ of total diameter less than $\frac{\epsilon}{2}$. You know that the rationals in $[0,1]$ are measure $0$, so you can find $[c_1, d_1], ..., [c_m, d_m]$ covering $\mathbb{Q} \cap [0,1]$ of diameter less than $\frac{\epsilon}{2}$. Then together, these intervals form a cover of $[0,1]$ of total diameter less than $\epsilon$ which is a contradiction.


Showing there is no neighborhood on which a mapping is stable

Question:
Define $G(x, y) = (x^2, y)$ for $(x, y) \in \mathbb{R^2}$. Show that
  there is no neighborhood $U$ of the point $(0, 0)$ such that the
  mapping $G : \mathbb{R}^{2} \rightarrow \mathbb{R}^{2}$ is stable.

Here's my definition of stability:

Let $\mathcal{O}$ be a subset of $\mathbb{R}^{n}$. Then the mapping $F
 : \mathcal{O} \rightarrow \mathbb{R}^{n}$ is stable provided that
  there is some positive number $c$ such that
$$||F(u) - F(v)|| \geq c||u - v|| $$
for all points $u, v$ in $\mathcal{O}$.

I'm not so sure about how to prove the mapping isn't stable. I have the following theorem:

Theorem 16.9: Let $\mathcal{O}$ be an open subset of $\mathbb{R}^{n}$ and suppose $F : \mathcal{O} \rightarrow
 \mathbb{R}^{n}$ be continuously differentiable. Suppose $x_{\star}$ is
  a point in $\mathcal{O}$ at which the derivative matrix
  $DF(x_{\star})$ is invertible. Then there is a neighborhood $U$ of
  $x_{\star}$ such that $F : U \rightarrow \mathbb{R}^{n}$ is stable.

I don't think I can conclude from this theorem alone, since it's not an "if and only if" statement, can I? I don't know if that's how the book wants me to solve it though. You can easily show $DF(0, 0)$ isn't invertible at $(0, 0)$ by calculating the determinant. But is this enough? If not, how can I solve this problem?
Comment: Just take x to be very small and consider the points (0,0) and (x,0). You'll see they don't satisfy your definition.
Comment: But I need to show that there is no neighborhood on which it's stable. Not just at a point
Comment: Any neighborhood of 0 must contain 0. It also must contain a point (x,0) for some x $\neq$ 0 because neighborhoods are open. Therfore to be stable on a neighborhood your criterion must hold for at least the points (0,0) and (x,0) for some arbitrarilly small x. Do you get it or do you need a full answer?
Comment: Thanks for your reply. I am still having trouble getting it. I would really appreciate a full explanation.
Answer: Let's assume theat there is a neighborhood of $0$, E say, such that your function is stable on E with constant c. As E is open there exists an r > 0 such that $B(0,r) \subseteq E$ therefore for any $0 < x < r$ then $(x,0) \in B(0,r) \subseteq E$
As the functions is stable on E we have that
$x^2  = |(x^2,0)| = |(x^2,0)-(0,0)|\geq c|(x,0)-(0,0)| = cx$
which implies
$x \geq c$ for all $0 < x < r$ which is our required contradiction.
Good luck :)
Comment: In my definition of stability, $||u||$ denotes the norm of a vector, not an absolute value. Does this matter? So here, I believe $||{(x^2, 0)}|| = 0$, which I think no longer gives the contradiction.
Comment: I am talking about the Norm as well I'm just using 1 line instead of 2 for brevity.
Comment: Isn't the norm of any vector with the zero vector equal to zero, though? How did we get $|(x^2, 0)| = x^2?$
Comment: I think you're a bit confused as to what a Norm is. The norm only takes in 1 argument so you can't take a norm of a vector with another vector? In my proof I'm subtracting (0,0) from (x,0) which is just (x,0) and taking the norm of (x,0) which is x. At no point do I take the norm of (0,0) on its own. The source of your confusion may be that |(0,0)| = 0.
Comment: Oops. You're right. Thanks.
Comment: $|(x,y)| = \sqrt{(x^2+y^2)}$
Comment: Sorry - why is there a contradiction if $x \geq c$ for all $0 < x < r?$
Comment: let $k$ be the minimium or $r$ and $c$. Then $k/2 < r$ but $k/2 \ngeq c$ so what we derived is not true. Therefore we have a contradiction.
Comment: In general though for things like this in real analysis try to think intuitively about the problems, not just follow the proofs. If you get the intuition first then the proof will follow easily. For example here, the reason we have a contradiction is that we derived that all numbers less than r are greater than c. If you think about a number line you will see this cannot be true.


How to get field values in rules condition from fetched entity

Question: I have a content type "Event" that's linked to a registration type.
Inside rules I want to trigger the action only if a field value from the host entity is "Open" (it's a checkbox field).
Under actions I'm able to fetch the host entity and access this field but i'm baffled how to access the same field under conditions. How can I go about this?
Thanks.
Comment: which type of rule you created?
Comment: Just a "normal" rule for now..
Comment: means which event ?
Comment: add in conditions data comparison select field and set equal to select your value. done.
Comment: The event is "After saving a new registration"
Comment: @VimalGoradiya I can't select field because it's not yet in context. That'd be a way to do it if the referenced entity was already loaded which is not the case right now
Answer: You have to first add conditions that allow the rule to know what fields are available.
To do this you can use combinations of the following conditions:

Entity exists by property
Entity has field
Entity is new
Entity is of bundle
Entity is of type

Those conditions help rules identify the entity and bundle so it can show the relevant fields.
You can then access those field tokens in subsequent conditions and actions.
For example, you might use Entity is of bundle "Event" to then get access to fields used on the event content type.
In your case where you only have access to he user/profile entity you would have to add a condition like above to determine the entity/bundle of the user/profile so that you could get access to the field that references the event.
Then have an action to load the event entity (you could use the action "Fetch entity by id") using the entity id in that field.
Then you could add an if condition in the actions (using the conditional rules module) and say if the fetched entity is of type "Event" then if the value of your field is "Open" then do your final action.
It's a bit complex but you should be able to achieve what you want using the conditional rules module.
I think though that this will only work if you have a field on the user that references the event.
If it is the other way around and you have a field on the event that references the user then it would work differently.
In that case I would use the "Fetch entity by property" action to fetch content where the checkbox field = "Open".
Comment: Thanks. I've tried to add those conditions but in the data selector for any of your listed conditions, I only have available "site information" and "created registration" no reference to anything else.
Comment: I updated my answer to add more detailed examples.


How do I exclude a bunch of nodes from being indexed by Solr?

Question: I want to remove unused nodes from indexing in solr and also I need to make sure that they are not indexed again. I will fetch the list of the unused node IDs using a query.
If any of the nodes is getting updated, then I need to index that node again.
How can I achieve this?
Answer: For d7 you are looking for the hook: hook_apachesolr_exclude
Example from the apachesolr.api.php
/**
 * This is the place to look for the replacement to hook_apachesolr_node_exclude
 * You should define a replacement for the status callback and return
 * FALSE for entities which you do not want to appear in the index and TRUE for
 * those that you want to include
 */

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  return FALSE;
}

See here: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.api.php/7
UPDATE
For deleting certain nodes (entities) you can use apachesolr_remove_entity.
Comment: Thanks for providing a Drupal 7 version. However I just want to point out again, as I said in my post, if nodes are supposed to be added and excluded from the queue as they are updated, this function alone will not suffice, since it does not remove already existing nodes from the index and that seems like it would be a constant need in Mathankumar's scenario. I think the explanation in my answer should make sense...
Comment: Hi Boriana, thanks for noticing this. I edited my answer to inculde this.
Comment: That's not a problem.  Would have been nice if you had given me a chance to update my own answer by leaving the Drupal 7 function modification in a comment, so we didn't end up having almost identical answers, but oh well!  I may delete my original answer to avoid confusion...
Comment: I would certainly do what you are saying if I were to make a suggestion or an improvement to an otherwise correct answer.
Answer: If you're comfortable writing your own modules, there's a hook that can help you exclude certain nodes from the index: hook_apachesolr_node_exclude($node, $namespace).
This is invoked by the apachesolr module for each node that qualifies to be added to the index. If the function returns TRUE, the node is skipped for indexing.  However, nodes which are already index will not just be removed because of the TRUE return value.  That only prevents nodes from being added.  You'll have to clean up your index by calling apachesolr_delete_node_from_index().
See the here for additional information: http://api.drupalhelp.net/api/apachesolr/apachesolr.api.php/function/hook_apachesolr_node_exclude/7
Hope this is enough to get you started!
There were some modules in Drupal 6 to help with this, such as http://drupal.org/project/apachesolr_exclude, but I don't know of any good ones for Drupal 7.
Comment: Your api reference is outdated. hook_apachesolr_node_exclude does not exist in the lates d7 version module
Answer: In Solr configuration at "admin/settings/apachesolr/content-bias" you can set the content types to exclude from the search index.
Comment: It looks like he's trying to avoid indexing specific nodes that he can pull up via a query rather than excluding entire content types....
Comment: in 7 it's set in admin/config/search/apachesolr/settings/solr/index


Make a beat machine in js

Question: I wanna make a beat machine to play sounds at a given time. I need to pass in a bpm number. My first attempt was just to use a setInterval function to get a constant beat, but Im not sure if thats the way to go.
let beat = (bpm) => {

  setInterval(()=> {

    // Run update beat machine

  }, (60 * 1000) / bpm)
}

I didnt find anything on the web. I appreciate articles as well.
thanks
Comment: what's the problem?
Comment: @DCR It's pretty clear from the question that they don't know if this is the correct approach or not.  (It isn't.)
Answer: No, that's not what you want.  setInterval is not precise.
The Web Audio API has an AudioBufferSourceNode which keeps the sample in memory.  It can be scheduled to start at a certain time.
bufferNode.start(0.5, startOffset);

In this example, we start playing 0.5 seconds from the offset.
Comment: @Fluqz Correct, and you can only start them once.  See the documentation:  https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode  "An AudioBufferSourceNode can only be played once; after each call to start(), you have to create a new node if you want to play the same sound again. Fortunately, these nodes are very inexpensive to create, and the actual AudioBuffers can be reused for multiple plays of the sound. Indeed, you can use these nodes in a "fire and forget" manner: create the node, call start() to begin playing the sound, and don't even bother to hold a reference to it."
Comment: The AudioBufferSourceNode is only for samples right? Because Im having a Oscillator and I found a Article about a little sequencer which starts the osc and then stops it at a given time again. osc.start(); osc.stop(context.currentTime + length);. But im getting the following error:  Failed to execute 'start' on 'AudioScheduledSourceNode': cannot call start more than once.

Make a beat machine in js


What does `* Mark bundle as not supporting multiuse` mean in my curl trace?

Question: When I do a curl -v to some docker container that I created, I get:
* Mark bundle as not supporting multiuse
What does it mean? Where is it documented?
Answer: From https://github.com/curl/curl/blob/curl-7_82_0/lib/http.c#L4226 :
if(conn->httpversion < 20) {
   conn->bundle->multiuse = BUNDLE_NO_MULTIUSE;
   infof(data, "Mark bundle as not supporting multiuse\n");
}

It is a feature of HTTP/2. See, e.g.,
https://web.archive.org/web/20200328114206/https://www.cloudflare.com/website-optimization/http2/what-is-http2/
Comment: Is that like a Microsoft 'feature'? The explanation provided is useless, and the documentation only puts this as #24 on a list of error messages with no explanation of where it comes from. Neophytes in cURL or whatever command brings up "Mark bundle as not supporting multiuse" will find no help here so far...
Comment: I completely agree. This answer is useless. Especially the generic link to what http2 is without any further information is really not useful.
Comment: "Oops, you appear to be lost"
Answer: If I understand correctly, multiuse == multiplexing?
If so, then this explanation is fine.

Multiplexing is perhaps the most significant benefit of HTTP/2. HTTP/1.1 requires each request to use its own TCP connection. Multiplexing, in contrast, allows a browser to include multiple requests in a single TCP connection.

Multiplexing Diagram 1

The problem is, a browser can only have a limited number of TCP connections open at any given time. For HTTP/1.1, this means a browser can only load a single resource at a time—every asset in a web page is sent back to the browser sequentially. Multiplexing allows a browser to request all these assets in parallel. This results in a dramatic performance gain.

Multiplexing Diagram 2

HTTP/1.1 is sort of like buying a single item at a grocery store, taking it back home, going back to the store for the next item you need, and repeating until your pantry is fully stocked. Multiplexing gives you a shopping cart so you can pick up everything you need in one trip.
Comment: Can you check your posting?   I think you typed `HTTP/1.1` where you did mean `HTTP/2`  in the last paragraph?
Comment: I copy/pasted the explanation word for word from https://www.cloudflare.com/en-in/website-optimization/http2/what-is-http2/
Comment: The link is dead. In trying to find something similar, I found the following. https://blog.cloudflare.com/http-2-for-web-developers  I see that the first diagram that is linked above shows up in this article.


Align content in center css

Question: How to align content in the center?
Currently the Header Text
and
the Login/Password Input fields
are not aligned in the center, and align seperately
Example:
"Header1"
"Header2"
...."login"
...."password"
...."buttons"
Header Fields:

            header1header1

            headerheader2

Login Input Fields:

    <form class="form-signin" method="Post">
        <input type="text" id="email" class="form-control"  placeholder="email">
        <input type="password" id="password" class="form-control" placeholder="pwd">

        <input type="checkbox" value="remember-me">
            Keep Login

        <button class="btn btn-lg btn-info btn-block" type="submit">
            로그인
        </button>

            Email Join

            Find Password

        </form>

Answer: Centering placeholder text alone isn't browser wide supported. For safari and mozilla (seems to work in chrome) you can use:
::-webkit-input-placeholder {
    text-align:center;
}
input:-moz-placeholder {
    text-align:center;
}

DEMO
If you are OK with the text that the user inputs be centered as well use:
input {
    text-align:center;
}

EDIT: I'm assuming you are using bootstrap.
Answer: try
 if that doesn't work putting it onto jsfiddle would be helpful.
Answer: if you are using bootstrap and by the looks of you code you are, you can center text by adding the class "text-center".

aligned center

And some other useful alignments available in bootstrap :

aligned left

aligned right

justified

Align content in center css


combining log likelihoods from different series of observations

Question: I have generated multiple log likelihood estimates for some parameters $\theta$ based on independent sets of observation. How can I combine these into one average?
Comment: What are you trying to do?
Answer: Because the data sets are independent, summing the likelihoods would give the total log likelihood of $\theta$ in the combined data set. This is because the joint density (or mass function) of independent random variables is the product of the individual densities (or mass functions). See wikipedia for more info.


When does SEM have little to no benefit over multiple regression, and there is a distinction without a difference between two approaches?

Question: I recently saw a case where someone fit a SEM with 20 latent variables (with many indicators each) predicting a single latent variable (of several indicators), and suggested it was evidence for some causal/theoretical model and called it a day.  There were no indirect paths and they did not have multiple outcomes/DVs (i.e., multivariate). They also did not test multiple possible SEMs. This seems not so useful to me and does not seem to reflect the usefulness of SEM over regression. My understanding of SEM and it's advantages over multiple regression is:

Model Comparison: Contraining paths, or fixing paths to other estimates, or specifying other possible models to see which is better fit to the data
Multivariate: SEM, unlike multiple regression, can simultaneously estimate multiple outcomes
Combining Measurement and Structural Model: You can simultaneously estimate latent variables and the causal relationships among them
Error-Free: SEM uses latent variable models to account for measurement error

This is my cursory understanding of some of the major advantages of SEM over multiple regression for specific applications. With that being said, if someone takes a set of 20 questionnaires, puts them in an SEM as 20 latent variables, predicting another questionnaire as a latent variable, and stops there, that strikes me as providing no advantages over multiple regression. It is involving no model comparison (no constraining of paths, no testing of alternative models) and it is not multivariate (i.e., it has a single outcome). I suppose you could argue there are advantages to estimating the latent variables in the same model as the causal/path model, but I suspect this will be almost identical to estimating the means for each of these questionnaires, and estimating a linear regression model predicting the DV from the 20 IVs. Further, if you decided in advance what each of the indicators for each latent variable will be based on questionnaire they belong, it doesn't seem that this measurement model provides all that many advantages.
I am aware of papers like this which suggest that calling multiple regression and SEM equivalent is a myth but I find this unconvincing for univariate regression cases with no model comparison. It seems like the inferences would and should be effectively identical in such a scenario.
My question broadly is-- When is there little to no advantage of SEM over multiple regression, and when is this a distinction without much of a difference? Further, when is the added obfuscation and complexity of SEM providing little benefit over a simpler, and easier to comprehend multiple regression model (e.g., the univariate case)?
References:
https://www.researchgate.net/post/What-is-the-difference-between-a-regression-analysis-and-SEM#:~:text=While%2C%20multiple%20regression%20is%20observed,based%20and%20variance%2Dbased%20methods.
http://faculty.cas.usf.edu/mbrannick/regression/SEM.html
Regression in SEM programs vs regression in statistical packages such as SPSS
https://www.quora.com/Which-is-better-regression-or-structural-equation-modeling-and-why
https://www.statisticssolutions.com/advantages-of-sem-over-regression/
https://www.youtube.com/watch?v=wHFrgp3SQMI&t=67s
Comment: "Multiple regression" is not well defined here. The overlaps include a lot of notable cases, possibly with multiple linear regressions, constraints, or derived values. For instance, the Baron Kenny test can be replicated in SEM as well as linear regression. In that way, SEM is a useful piece of software. Though latent variable models are seemingly unique to SEM, if we can call mixed effects regression "regression" even though we use EM to integrate over random effect distributions, why can't we use the same reasoning with a latent variable?
Answer: Relative to multiple regression (and assuming a single DV and only direct effects like you wrote), I see the main advantages of SEM in the possibility to test the model against the observed data (in particular: the measurement model) and that SEM corrects for measurement error. When you use regression with observed sum scores for each construct, you cannot test whether the measurement structure is adequate, and you do not correct for measurement error in the independent variables. One assumption of regression is that the independent variables are measured without error. This is probably an unrealistic assumption, at least for most social science constructs. When there is measurement error in the IVs, regression coefficients and their standard errors may be biased.
To answer your question, from this perspective, it would be OK to use regression with simple sum scores instead of SEM when you have a "proven" tau-equivalent (or Rasch/1-pl logistic IRT) measurement structure for each construct (so that a simple unweighted sum score is adequate for each construct), no cross-loadings between different constructs, and each scale's composite reliability was very close to perfect (1.0). Of course, there are other situations where you may have reasons to prefer regression (e.g., when your audience does not know or understand SEM).
Comment: Another reason to prefer regression in some cases may be sample size. Sometimes, the sample size may not be sufficient for a complex SEM with many measures and many predictors but it may be sufficient for regression.
Comment: Helpful-- Thank you!


Set font size to header's elements after applied a fomatter to multiple columns in formattable

Question: With code below, I'm able to customize column mpg and disp's format:
library(formattable)
data(mtcars)

df <- mtcars

f1 <- formatter("span", style = x ~ style(color = ifelse(x > 0, red, blue), "font-size:20px"))
f2 <- formatter("span", style = x ~ style("font-size:20px"))

formattable(df, list(
  `mpg` = f1,
  `disp` = f2
  ))

Based what I have done above, I would like to set font size for header's elements by applying f2 to header:
formattable(df, list(
  `mpg` = f1,
  `disp` = f2,
  names(df) <- f2(names(df))
  ))

But as you may notice, the effect for mpg and disp have disappeared, any ideas to deal with this issue? Thanks.
Answer: Problem solved by the code below:
library(formattable)
data(mtcars)

df <- mtcars

f1 <- formatter("span", style = x ~ style(color = ifelse(x > 0, red, blue), "font-size:20px"))
f2 <- formatter("span", style = x ~ style("font-size:20px"))

df$mpg <- f1(df$mpg)
df$disp <- f2(df$disp)
names(df) <- f2(names(df))
formattable(df)

Out:


How to use Rules to perform a simple anti-spam validation using specific keywords?

Question: My site is under repeated attacks by spammers who create accounts manually with nonsense email addresses and "fake" IP addresses (no way to block them).
I came up with the idea of blocking node creation with the Rules module, using data comparison, but it does not work. Here is a summary of the rule I have:

Event : Before saving content
Conditions: text comparison : Parameter: Text: [node:body:value], Matching text: lexapro, etc. [how to make the list of words/expression? One per line?]
Actions : page redirect

Update: starting from the rule in this answer, I created a rule which will redirect to a page and unpublish the node, but only if the words are both in the title and in the body. I've tried to put an OR in the rule, but it didn't work.
{ "rules_simple_antispam" :
  {
    "LABEL" : "Simple antispam",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "node:title" ], "match" : "lexapro" } },
      { "text_matches" : { "text" : [ "node:body:value" ], "match" : "lexapro" } }
    ],
    "DO" : [
      { "redirect" : { "url" : "death-spam" } },
      { "node_unpublish" : { "node" : [ "node" ] } }
    ]
  }
}

What do I need to change in my rule to make it work?
PS: I'm not a coder.
Comment: Which version of Drupal are you using?
Comment: I'm using Drupal 7 and looking forward to move to D8 eventually.
Answer: IMO you should use a captcha, such as:
reCAPTCHA

Uses the Google reCAPTCHA web service to improve the CAPTCHA system
and protect email addresses.

OR
Draggable Captcha

Here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam
If spam still happening, which means they are indeed human and not bots, you could implement a point system. Where users need to gain points by doing something (login x amount of days or comment x amount of times etc..)
To create nodes, users need to have x amount of points.
In addition, you could also implement spam flags, where users can flag content as spam and have the content be auto deleted if x amount of flags are raised.
Comment: thanks, but I have honeypot that works 100%. As for asking people to flag content, people don't really care and they prefer to go away than doing your job. There must be a simple way of using Rules to redirect on specific words.
Answer: Have a look at this rule (in Rules export format):
{ "rules_block_specific_words_in_node_body" : {
    "LABEL" : "Block specific words in node body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "text_matches" : { "text" : [ "node:title" ], "match" : "lexapro" } },
          { "text_matches" : { "text" : [ "node:body:value" ], "match" : "lexapro" } },
          { "text_matches" : {
              "text" : [ "node:title" ],
              "match" : "ANotAllowedTextStringInTitle",
              "operation" : "regex"
            }
          },
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "ANotAllowedTextStringInBody",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_spammers_allowed" } },
      { "node_unpublish" : { "node" : [ "node" ] } }
    ]
  }
}

Just import it in your own site (using the Rules UI) to experiment with it, and make it fit your needs.
Some more details about the logic included in the above sample:

It only applies to authenticated users (adapt and/or remove that Rules condition as needed).
It includes 4 verifications about the title or the actual body text (at least 1 one of these 4 Rules Conditions must be satisfied, as per the "OR" in these Rules conditions), ie:

an exact match (equal to) of either the title or the content of the body which is (just) "lexapro".
using a regular expression (regex) related to the string (in the title) ANotAllowedTextStringInTitle or (in the body) ANotAllowedTextStringInBody (use any regex that may fit your needs).

If the combination of Rules conditions is satisfied (ie the role matches AND at least 1 of the 4 of the text comparisons are satisfied), then these 2 Rules Actions are triggered:

issue a redirect "before saving the content" (which is the Rules Event) to a page with a path like no_spammers_allowed.
the node is unpublished.

Note: to make a list of words, the most straight forward way to do so is via the RegEx expressions (in which you could also use the "lexapro" word of course, which would make the first 2 Rules Conditions obsolete).
Comment: Thanks for tour time. I just cannot make it work. The node is saved. And how do I put more than one expression? I've tried comma separated and one per line. But didn't see any difference; doesnt work more. Thanks again for your time.
Comment: So... I need an action for each word? I'm not shure to follow. Maybe someone else will take a look at this rule. I'm not the first one to come up with this. Its like if the saving process could not be stopped. And I will switch on debug... Thanks again.
Comment: @user54770 : have a look at my refined answer. Curious to hear your feedback about it.


Find the turning point of $y=x^2(2-x^2)$ and determine if it it is a max or min point.

Question: After differentiating I got $4x-4x^3$ ....how are we supposed to get the answer when the its $x^3$??? I'm kinda lost here! >.<
EDIT: Sorry Kasper, I googled that Math app you told me to it's not free however. I tried my best to get the $x^2$ and the $x^3$ symbol. I truly apologize for the inconvenience but I'm not good in typing maths formula out in the computer.
If anyone can help, please suggest me an online website that can do the math equation easily to avoid confusion.
Comment: Wow gee! Though I'm not supposed to say the word "thank you" here but please let me say it... Thank you! At least I can now improve myself in maths equation
Comment: It should give you a quadratic equation with the $b$ term equal to 0 after factoring; i.e., $4x(1-x^2)$. As the answer posted mentions, you will have three points to check.
Comment: Well, we would have the equation $4x(1-x^2)=0$. Personally, I don't think a calculator is needed in this case because we have three possibilities: $4x=0 \Rightarrow x=0$, or $1-x^2=0 \Rightarrow x= \pm 1$. These in turn are your critical points which can help you determine the max/mix of the function.
Comment: @YamadaYousuke You're welcome!
Comment: I was talking about MathJax, that is absolutely free, and you can use it on the website by placing dollars \$...\$ around the math. I've edited your post.
Comment: @Kasper let me give it a try... $y=x^2(2-x^2)$
Comment: But is the (money symbol) .... (money symbol) code applicable to only this website?
Comment: Consider factoring out an $4x$ from your derivative calculation; that should simplify to a much simpler quadratic.
Comment: @Jamil_V but that doesn't make me get the $ax^2+bx+c=0$ ! >.< I mean by that equation, you will get two $x$ answers...
Comment: @Jamil_V .okay so how are we supposed to type these numbers ( 4x−4x3=0 ) in the calculator? I mean the equation part. Are we using the let x be 1,2,3 method???
Comment: @Jamil_V Oh gee! I never noticed! Thank you so much!!
Answer: You're almost there, keep going. To find turning points, set $y'$ equal to zero, factor the differential equation ($4x-4x^3$) and you should be able to determine the turning points (there are three of them). Check each case to see if they are a maximum or minimum.
Comment: Sorry, I should have been more explicit. Setting $y'=0$ we find

$4x-4x^3=0$

which implies

$4x(1-x^2)=0$

Can you solve for $x$ now?
Comment: In order to determine the 3 points, are we using the "Let $x=1,2,3$ ??
Comment: It doesn't matter sir...okay so how are we supposed to type these numbers ( $4x−4x^3=0$ ) in the calculator? I mean the equation part


Android Emulator hang up and impossible to quit

Question: I've installed the Android plugin on Eclipse 3.6 in a regular way (aka i followed step by step the google installation page).
When I launch any sample application, everything works fine, but if I try to quit the emulator (by clicking the exit cross button of the emulator), the emulator seems to hang completly.
What is very bothering is that I can't even kill the process, launch another emulator or even reboot my pc, since the process seems to be impossible to stop or kill.
Does anyone have similar problem, and a solution to give?
Comment: How much size did you allot to SD card of AVM?
Answer: I have seen this issue with the emulator when running Linux on some machines. That problem was related to the audio and could be helped by setting the -noaudio option when launching the emulator.
You can add emulator options in preferences-Android-Launch in eclipse. Just add -noaudio to the "default emulator options" field.
Comment: Thanks a lot! it does the trick (by the way, i'm running on a Windows XP SP2 computer).
Answer: Hang on quit due to audio handling thread is a known bug:
http://code.google.com/p/android/issues/detail?id=17294
To work around this issue, disable audio input in the AVD manager with "Audio recording support" set to "no", which sets "hw.audioInput=no" in the qemu ini file.
Answer: First, I was able to confirm on my system (Win7 x64, Eclipse Helios SR2) the eclipse hanging situation was due to the audio defect noted. (I did this by starting an emulator from the command line and using the -noaudio option.  Eclipse will use the existing emulator and it no longer hangs.)
However, I cannot get Eclipse to use the "-noaudio" value I put in the "default emulator options" field.  I also tried "noaudio" but it didn't work.  Checking the command-line of the process, the "-noaudio" option is not present; just the rest of the standard options.
Answer: I still had this problem with WXP SP3 and ADT-Bundle-Windows-X86 (which is an pre-bundled Eclipse with ADT; SDK r21).
I tried some of the tips above, but none worked when starting the emulator from eclipse. The emulator hangs after quitting and prevents Windows shutdown.

setting hw.adioInput=no: after trying several config files, the file <user dir>\.android\avd\<emulator name>.avd\hardware-qemu.ini seemed to be the right one. To my disappointment, this file is rewritten every time eclipse starts the emulator.
setting -noaudio in Preferences\Android\Launch\Default emulator options did not work, as @RodBarnes mentioned

What finally worked (for me), is one of those two options:

Either create a batch file to start the emulator, using a command line of emulator @<emulator name> -noaudio, assuming emulator.exe is on your path. Else prefix it with the complete path to emulator.exe. Eclipse will recognize the running emulator and use it.
Or set a command line option for every single run configuration. You find it under Run\Run configurations...\<Your configuration>\Target\Additional Emulator Commandline Options. Enter -noaudio here. You may need to scroll the Target panel down a bit to see the option. Some other comments i found mentioned that in some Eclipse versions the scrollbar is missing, so try to increase the window size.

I for myself prefer the first option as you need a single batch file for each emulator only, and do not need to change every single run configuration.
Answer: If you are using linux, tap command xkill, then be careful, click in something you want to kill. In this case after command you should click on emulator and then it will be killed.