If $\operatorname{E}(Y\mid X_i)=0$, the $\operatorname{Cov}(X,Y)=0$?

Question: Suppose we have two random variables $X$ and $Y$, where $X$ can take values of $X_1,X_2\cdots$. Now suppose $E(Y\mid X=X_i)=0$ holds for every $X_i$, does it mean that $X$ and $Y$ are not correlated?
Intuitively I think this is true, since no matter what value $X$ takes, the expectation of $Y$ is unchanged, therefore the two must be uncorrelated. However I don't know how to prove this mathematically.
Comment: Try to evaluate $E(XY)$, and do it like this - $E(XY) = E(E(XY|X))$. Its obviously 0. Then Writing $Cov(X,Y) = E(XY) - E(X)E(Y)$, is remains to show that $E(X)E(Y) =0$, which is also so. Just again take $E(Y) = E(E(Y|X))$. (I supposed that you know $E(E(Z|U)) = E(Z)$, for any $U$).
Answer: $\mathbb{E}(Y) = \mathbb{E}(\mathbb{E}(Y|X)) =  \mathbb{E}(0) = 0$
$\mathbb{E}(XY) = \mathbb{E}(\mathbb{E}(XY|X)) = \mathbb{E}(X\mathbb{E}(Y|X)) = \mathbb{E}(X \times 0) = 0$
Therefore, $\mathbb{C}(X, Y) = \mathbb{E}(XY) - \mathbb{E}(X)\mathbb{E}(Y) = 0$.
Answer: $E(XY)=E_X[\sum_{i≥1 } E(X_i Y| X=X_i)]=E_X[0] =0$
Similarly $E(Y)=0$ Thus we have $Cov(X,Y)=0$
Comment: I think you mean $E[XY] = \sum_{i=1}^{\infty} E[XY|X=X_i]P[X=X_i]$ (which is the law of total expectation, assuming $X \in \{X_1, X_2, ...\}$).   The notation $E_X[\cdot]$ that you use does not quite make sense.  You could alternatively say $E[XY] = E_X[E[XY|X]]$.
Comment: Yes in ur notation $ E[XY]=E_X [E[XY|X]]  $ and then u evaluate the inner expectation to get what I wrote directly
Comment: No, the inner expectation $E[XY|X]$ is a function of $X$, i.e., it is a random variable that can be written as $g(X)$, it is certainly not $\sum_{i \geq 1} E[X_iY|X=X_i]$, which is not a function of $X$ and is not even random.
Comment: I guess my notation is a bit sloppy but this is what I mean


Rails 3.2.15 migration fails: undefined method `create_join_table'

Question: I'm trying to create a has-and-belongs-to-many rich join between two models in Rails 3.2.15. What am I doing wrong here?
Here's my migration code:
class CreateTopicInterest < ActiveRecord::Migration
  def change
    create_join_table :users, :topics, table_name: :topic_interest do |t|
      t.index :user_id
      t.index :topic_id
      t.integer :interest_type

      t.timestamps
    end
  end
end

And here is the terminal output after running "rake db:migrate":
==  CreateTopicInterest: migrating ============================================
-- create_join_table(:users, :topics, {:table_name=>:topic_interest})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `create_join_table' for #<CreateTopicInterest:0x007fe7ac8d86a0>/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:465:in `block in method_missing'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:438:in `block in say_with_time'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:438:in `say_with_time'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:458:in `method_missing'
/Users/duncanmalashock/rails_projects/diver/db/migrate/20140801151401_create_topic_interest.rb:3:in `change'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:407:in `block (2 levels) in migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:407:in `block in migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:129:in `with_connection'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:389:in `migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:528:in `migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:720:in `block (2 levels) in migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:775:in `call'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:775:in `block in ddl_transaction'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/database_statements.rb:192:in `transaction'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/transactions.rb:208:in `transaction'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:775:in `ddl_transaction'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:719:in `block in migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:700:in `each'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:700:in `migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:570:in `up'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/migration.rb:551:in `migrate'
/Users/duncanmalashock/.rvm/gems/ruby-1.9.3-p448@diver/gems/activerecord-3.2.15/lib/active_record/railties/databases.rake:193:in `block (2 levels) in <top (required)>'

Answer: create_join_table has been added in rails 4.0.2. You need to use create_table instead.
create_table :topic_interest, id: false do
  t.integer :user_id
  t.integer :topic_id

  t.index :user_id
  t.index :topic_id
end

Note however, that using habtm association will not allow you to use any extra fields on the association (like interest_type you want to add). Instead use has_many :through association.


If $0<p\leq|a_n|\leq q$ for all $n\in\mathbb N$, find the radius of convergence f $\sum a_nx^n$.

Question: If $0<p\leq|a_n|\leq q$ for all $n\in\mathbb N$, find the radius of convergence f $$\sum a_nx^n$$.
For this one thing i could conclude that the series is bounded in a compact domain but convergence made me confused. what is the answer?
Comment: Have you heard of the Cauchy-Hadamard formula for the radius of convergence?
Comment: @DanielFischer No.
Comment: Okay. Then apply the root test.
Comment: For the unknown $a_n$ how can we? but i will try.
Answer: If $x>1$:
$|a_n|x^n \ge px^n\to\infty$: $R\le 1$.
if $x<1$:
$|a_n|x^n \le qx^n, \sum qx^n < \infty$ hence $R\ge 1$.
Comment: How you are predicting this. Is this true when the nth term goes to infinity $R\leq 1$?
Comment: I do not really understand what you are intended to convey... :O
Comment: i use the definition: $R = \sup \{ x \in \Bbb R^+ : \sum |a_n|x^n<\infty\}$
Answer: As you are not aware of Cauchy-Hadamard formula for the radius of convergence let us see this as some geometric series...
See $\sum a_nx^n$ as $\sum (\sqrt[n]{|a_n|}x)^n$. For this to converge,  you need

$|\sqrt[n]{|a_n|}x|<1\forall n\in \mathbb{N}$ i.e., $|x|<\dfrac{1}{\sqrt[n]{|a_n|}}$

You have :
$$0<p\leq|a_n|\leq q\Rightarrow 0<\sqrt[n]{p}\leq \sqrt[n]{|a_n|}\leq \sqrt[n]{q}\Rightarrow \dfrac{1}{\sqrt[n]{|a_n|}}<???$$
Can you conclude now?


Angular 2 - Multiple components in any layout on different static pages

Question: I have a bunch of static pages that use various components that are placed wherever a HTML designer likes. e.g. within any page on a WordPress site.

Though the sample components shown here are simple Panels, but in
  reality there are all sorts of components, e.g. Search, Lists,
  Editors, Views etc...
Currently they have been done on lots of Wordpress Sites where each and
  every page can have totally different layouts. In the past we used
  Angular 1.5 where the WP developer you could just put our app tag up near the body and then any widget (we have about 30) could be placed 1 or more times in any page.

Components can be re-used so making the components root components via the bootstrap[] property does not make sense as you can only use a root component once on a page. As seen in my second example.
Technique 1
Here is a screenshot and Plunker for the first setup. Notice that I have 4 area's in which I place 3 components with component 1 being reused.
This Example is done by laying out the components inside a single root component, which is impractical for my use case where Wordpress Pages will have totally different layout and composition requirements.
.
Plunkr

Technique 2
I have tried using a technique where each widget is bootstrapped as a root component, based on this post Bootstrapping Multiple Applications Sprinkling Angular 2 components inside a non-angular page.
But when I use this technique the 2nd instance of a widget does not load. AKA widget 1.
Plunkr
See example with bootstrapping

Technique 2 - Has further problems
If you have bootstrapped 3 root components, you MUST use all of them otherwise Angular throws up an error about the root component that you did not use.
Plunker

Technique 3
The use of <ng-content></ng-content> does not seem to work root components.
See: Angular2 Root Component with ng-content
Comment: What did you end up doing? I have a similar requirement.
Answer: For this kind of widgets the better is to have an ng2 application instantiated per each widget like Bootstrap multiples applications. I did post a possible solution there.
I do implement an ApplicationFactory which create a dynamic selector like:
moduleFactory(selector: string, childModule : ModuleWithProviders) {

  @Component({
    selector, // dynamic selector
   ...
  })
  export class AppComponent implements AfterViewInit{
    constructor(resolver: ComponentFactoryResolver){}
    ngAfterViewInit() {
      // Cretate a Child components dynamic
      // mapping from childModule::[bootstrap] components decoration
    }
 }

 @NgModule({
   declarations: [
     AppComponent
   ],
   imports: [
     BrowserModule,
     FormsModule,
     HttpModule
   ],
   bootstrap: [AppComponent]
 })
 class AppModule { }

  platformBrowserDynamic()
      .bootstrapModule(AppModule, {providers: childModule.providers});
}

In then in ngAfterViewInit you may create a dynamic component using a ComponentFactoryResolver
This is not an ideal solutions but it works
Answer: You can create a bunch of wrapper components with different selectors, each wrapping the same component, and then bootstrap these wrapper components instead.
Comment: I agree it's dirty but it could get you going until the unerlying issue is fixed. You might also be able to create the components dynamically at runtime to reduce the pain, but I'm not sure, never played with this approach http://stackoverflow.com/questions/34784778/equivalent-of-compile-in-angular-2/37044960#37044960
Comment: FYI: Just found that this technique can't be used anyway, because if you define multiple root components, you must use ALL of them. They are not optional. I commented in my original post in the area titled "Technique 2 - Has further problems"
Comment: I have expanded my original post to show how bootstrapping a component to a root component, means that you can only use each component ONCE.
Comment: That's what I explain in my answer. Create **multiple** wrapper components only for the purpose of wrapping your actual component. Only the selector of the outer-most component matters, you can reuse another component in each of the wrapper components as often as you want.
Comment: I don't really understand what your suggesting, I'm wondering if you could alter one of my plunkrs to demonstrate what you mean?. But for your clarity, the static pages I'm talking about are inside WordPress where each and every page can have totally different layouts. In the past we used Angular 1.5 where you could just put your app tag up near the body and then any widget (we have about 30) can be used 1 or more times on any page.
Comment: If you want bootstrap component A 5 times, you can create component B, C, D, E, F, where each of these 5 components only contains component A. Then bootstrap each B, C, D, E, F. I got the impression the Angular team plans to support bootstrapping a component multiple times eventually.
Comment: So your suggestion is that if I have component (A, B, C), I could create wraper (A1, A2, A3, A4, A5) + (B1, B2, B3, B4, B5) + (C1, C2, C3, C4, C5) and in so doing I could give my wordpress guy up to 5 instaces of each of my components (being A,B & C). I guess that would work, but its a pretty dirty solution.
Answer: Could you explain better what you want to achieve? I don't understand you...
you don't need to create 4 different components to do what you're doing, you can just do it like this:
https://plnkr.co/pvvlD7O2gXZBjVkY16po?p=preview

Area 1

          <my-widget></my-widget>

Area 2

          <my-widget [title]="'custom title'"></my-widget>

Area 3

          <my-widget [background]="'yellow'"></my-widget>

Area 4

          <my-widget [title]="'Last one'" [background]="'blue'"></my-widget>

Comment: I'm not trying to paramaterize a simple widget, I've added a not above, that explains. "Even though the sample components shown here are simple Panels, in reality there are all sorts of components, e.g. Search, Lists, Editors, Views etc..."
Answer: Okay, with you update I got you.
I'm not user if there is any way to make work what you're trying but what I'd do is something like this:
`

  <my-app>
    your table code
    </my-app>

`
and then make you root element 'my-app' template looks like this:
''
'' will bind the html that you put inside 'my-app' so it'll work, and you can use a different content for each static page as you want.
Comment: The problem with that techique is the area where "your table code" is written, The HTML totally disappears after  is parsed by Angular 2. I have looked at using the  directive as a potential solution, but I can't seem to get that to work.
Comment: you're right, I dunno why it's not working in plkr... but I'm using it and works perfectly, here is a test project, which I've public and where I'm using ng-content to create a modal window component:
https://bitbucket.org/albertomartineztomas/angular2_test/src/1a54e7ced75fe5b1b00c40b73cf0a04554275c59/src/app/components/containers/modal/modal.html?at=master&fileviewer=file-view-default
Comment: I found out why it does not work,  cannot be used for root components, I've listed a link in my original question


Show View Pane in Node Template based on Taxonomy Term

Question: I am trying to add a view pane to a node template. The node and the content type shown in the view panel both have a taxonomy term field, so it should be a simple matter to link them, but I can't figure it out.
My node template has the relationship  Taxonomy term from Node. The view pane has context "has taxonomy term id" and has Argument Input from context. Unfortunately, I can't figure out what combination of selections I need to make in context and argument input to make it all work.
Under Argument Input, do I pick the field that contains the term or do I pick one of the choices under Taxonomy Terms?
Under Context filter value type, do I pick Term Name, Term from ID or something else (or nothing at all)?
I think I've tried all possible combinations, but I have the view showing up on nodes whether they contain the context or not. Any help would be greatly appreciated.
Drupal 7.37, Panels 7.x-3.5 and Views 7.x-3.11.
Answer: Ok, I finally figured it out!
To show a view in a panel where the view and panel are related by a taxonomy term (in my case Team Term (field_team_term), do the following:

Use the view content panes module to create a view content pane (How can I show a view in panel with argument in Drupal 7).
In the view content pane use contextual filter "Has Taxonomy Term ID". When Filter Value is not available: Hide View. When Filter Value is available - specify validation criteria - choose taxonomy vocabulary - Filter Value Type: Term Name converted to Term ID. (Some writers suggested checking the "Allow Multiple Values" box at the bottom of the window under More; I found that unnecessary.)
In the Pane Settings - Argument Input, select "From Context".
Under Required Context, select Name under Taxonomy Term.

That completes the views setup.
In the panel settings,

Set up a relationship"Taxonomy term from Node (on Node: Team Term [field_team_term])" in the case of my taxonomy term field.
In content, add the view pane, and select the taxonomy term relationship as the argument.

As near as I can tell, that is only combination of panel context and view arguments that will get the job done. I hope this helps someone.
Comment: Glad you figured it out your own way. In Views still don't see the Pane Settings that you speak of. You mention "create a view content pane" I just create a regular view of unformatted list and fields that shows content.
Comment: To create a views content pane, you need to turn on Views Content Panes (views_content) in the chaos tools suite. See link in my answer, above.


RAILS: how to pass JSON API data to hash in controller

Question: when I place this in my helper file in works and I can read this API info into the hash. But this doesn't work in my controller. I need it to work in my controller in order to paginate.
def object
    JSON.parse open(end_point).read
end

def feed            # <- feedjust a naming function for object
    file = object   #
    return file     #
end

def photo_object(object, record_number) # <- should take a feed or object
output = Hash.new
    output = {
        "pict" => file["data"][record_number]["images"]["standard_resolution"]["url"],
        "height" => file["data"][record_number]["images"]["standard_resolution"]["height"],
        "width" => file["data"][record_number]["images"]["standard_resolution"]["width"],
        "name" => file["data"][record_number]["user"]["full_name"],
        "profile_pict_Instagram" => file["data"][record_number]["user"]["profile_picture"],
        "likes" => file["data"][record_number]["likes"]["count"],
        "film_look" => file["data"][record_number]["filter"],
        "post_date" => Time.at((file["data"][record_number]["created_time"]).to_i),
        "rights" => file["data"][record_number]["attribution"],
        "tags" => file["data"][record_number]["tags"]
        }
    return output
end

^^ I'm getting the error:
output = Hash.new
    output = {
        "pict" => file["data"][record_number]["images"]["standard_resolution"]["url"],
        "height" => file["data"][record_number]["images"]["standard_resolution"]["height"],
        "width" => file["data"][record_number]["images"]["standard_resolution"]["width"],
        "name" => file["data"][record_number]["user"]["full_name"],

I get the Error
NoMethodError in InstagramSessionsController#index
undefined method `[]' for nil:NilClass on the             "pict" => file["data"][record_number]["images"]["standard_resolution"]["url"],
def show
end

def new
@instagram_session = InstagramSession.new
end

def edit
end

# POST /instagram_sessions
# POST /instagram_sessions.json
def create
@instagram_session = InstagramSession.new(instagram_session_params)

respond_to do |format|
  if @instagram_session.save
    format.html { redirect_to @instagram_session, notice: 'Instagram session was successfully created.' }
    format.json { render :show, status: :created, location: @instagram_session }
  else
    format.html { render :new }
    format.json { render json: @instagram_session.errors, status: :unprocessable_entity }
    end
  end
end

# PATCH/PUT /instagram_sessions/1
# PATCH/PUT /instagram_sessions/1.json
def update
 respond_to do |format|
  if @instagram_session.update(instagram_session_params)
    format.html { redirect_to @instagram_session, notice: 'Instagram session was successfully updated.' }
    format.json { render :show, status: :ok, location: @instagram_session }
  else
    format.html { render :edit }
    format.json { render json: @instagram_session.errors, status: :unprocessable_entity }
  end
end
end

# DELETE /instagram_sessions/1
# DELETE /instagram_sessions/1.json
def destroy
@instagram_session.destroy
respond_to do |format|
  format.html { redirect_to instagram_sessions_url, notice: 'Instagram session was successfully destroyed.' }
  format.json { head :no_content }
end
end

private
  # Use callbacks to share common setup or constraints between actions.
   def set_instagram_session
   @instagram_session = InstagramSession.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def instagram_session_params
  params.require(:instagram_session).permit(:layout)
 end
end

Answer: "pict" => file["data"][record_number]["images"]["standard_resolution"]["url"],

Some value in this chain is nil which is causing

NoMethodError in InstagramSessionsController#index undefined method `[]' for nil:NilClass on the "pict" => file["data"][record_number]["images"]["standard_resolution"]["url"]

To avoid this much chaining you can change the method slightly which will avoid such errors
def photo_object(object, record_number) # <- should take a feed or object
  data = file["data"] && file["data"][record_number]
  return {} unless data.present?
  images = data["images"] && data["images"]["standard_resolution"]
  user = data["user"]
  output = {
    "pict" => images && images["url"],
    "height" => images && images["height"],
    "width" => images && images["width"],
    "name" => user && user["full_name"],
    "profile_pict_Instagram" => user && user["profile_picture"],
    "likes" => data["likes"] && data["likes"]["count"],
    "film_look" => data["filter"],
    "post_date" => Time.at((data["created_time"]).to_i),
    "rights" => data["attribution"],
    "tags" => data["tags"]
  }
end

Comment: Thank broham wil chekc it our.
Comment: Worked like a charm bro.


Criar muitas classes estáticas impacta na performance do sistema?

Question: Eu ando criando muitas classes estáticas para facilitar e limpar o código, como por exemplo uma chamada de API do Google Translate.
public static class GoogleTranslate
{
    public static string Translate(string word){
        //código de chamada
    }
}

Fazendo assim fica muito mais fácil pois é só chamar:
GoogleTranslate.Translate("StackOverflow é a melhor universidade do mundo");

Eu tenho bastante classes assim para chamar APIS, como isso é visto diante dos profissionais?
Comment: Já que estamos falando de api e métodos estáticos, vou lhe sugerir que venha a ler este artigo.: [`YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE`](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/), não responde a sua pergunta, mas pode vir a lhe ajudar.
Comment: +1 ótimo questionamento. Se não for pedir muito, quem responder levar mais em consideração o conceito, seria legal pra quem é de outras linguagens entender melhor tambem.
Comment: @TobiasMesquita vou dar uma lida Valeuu
Comment: Relacionada: https://pt.stackoverflow.com/a/287792/101
Answer: Sim, fica mais rápido, classes estáticas não precisam instanciar, que tem um custo nada trivial.
Métodos estáticos são como funções normais de qualquer linguagem, está lá pronto para uso. A vantagem é que ela tem um sobrenome (é praticamente um namespace), então organiza melhor o código. Não precisa alocar nada (classe normal há alocação mesmo sem ter estado), não tem mecanismos sofisticados (exceto quando tem estado, mas em geral não deve usar estado global). Em classes estáticas todos os métodos devem ser estáticos.
Parece algo muito diferente, mas todas as linguagens que não tentaram se vender como 100% orientada a objeto, que é uma falácia, sempre tiveram, sempre foi útil e deu certo.
O ganho é mais pelo método estático do que pela classe. Vale também para os métodos estáticos de classes quem podem ser instanciadas.
Existem outras características de classes estáticas, mas não são relevantes e muitas vezes até ruins.
Uma delas é a sua construção. Ela ocorre em algum momento antes de ser necessária (pode não ser na carga, mas pode ser, por isso uma técnica de lazy loading pode ser interessante). Precisa certificar-se que a forma codificada atende tudo de forma boa, que não exagera na carga do sistema (raramente ocorre), é preciso entender todas as implicações para usar corretamente. Idealmente não deve ter uma construção, mas pode se for necessário, útil e souber o que está fazendo.
Quem gosta de OOP diz que não deve usar, eu venho de uma escola mais pragmática que faz o que deve fazer.
É mais difícil testar, mas não impossível. Eu prefiro dificultar o teste do que dificultar o código principal para facilitar o teste.
Se um dia precisar mudar a estratégia dinamicamente pode se tornar um problema, que é a mesma questão do teste. Se não é algo universal e único a instância pode ser uma opção melhor.
Cuidado com estado global variável na classe estática ou normal. Isso funciona bem em raros casos e precisa saber o que está fazendo. Não crie uma classe estática quando o adequado é uma instância. Se tem estado que potencialmente varia a cada execução, crie uma instância.
Eu e o Stack Overflow abusamos de classes estáticas :) Muitos dizem que isso é um erro terrível, mesmo eles não sabendo do nosso contexto. Quando tem que ser uma instância, eu o faço. Na maior parte das vezes se um dia eu precisar mudar, eu refatoro (eu posso fazer isso, nem todo mundo pode), mesmo nos casos que dão trabalho refatorar, costuma compensar pelo ganho porque em quase todos os casos eu nunca precisei refatorar.
Coloquei no GitHub para referência futura.
Comment: Simples assim? Sem nenhuma desvantagem? :o
Comment: Imaginei que seria mais prejudicial do que benéfico :o.
Comment: @Maniero como sempre trazendo respostas fodas e demonstrando um pouco de sua experiência. Valeu ! (sei que é contra as regras agradecer, mas não consigo não fazer).
Comment: Nem por o exemplo o facto de que as classes estáticas sao instanciadas pelo *runtime* e que possuam construtores estáticos que podem ter código não trivial neles, criando assim uma inialização mais lenta do sistema?
Comment: @Omni respondido agora?
Comment: @LeonardoBonetti não é contra as regras, não é necessário, não é positivo, mas também não é negativo demais.
Comment: sempre achei que tivesse sérias desvantagens..obrigado @Maniero por esclarecer vários pontos.
Comment: Um ponto muito interessante é o que você falou do teste... as vezes vemos códigos muito difíceis de entender e dar manutenção.. porém os testes são muito simples.. ou seja.. gasta-se mais tempo com testes ou desenvolvimento? bom ponto.
Comment: @ThiagoLoureiro é o que eu falo e muita gente não entende. E pior, muitas vezes o teste é feito burocraticamente, não testa nada útil e deixa de testar o que precisa. Aí a pessoa acha que sou contra testes. Sou contra testes sem sentido. Sou contra piorar o código para facilitar o teste. Nem é questão de tempo gasto, é de complexidade. Claro que qualquer coisa é ruim se feita do jeito errado.
Comment: @Maniero perfeito, entendo que temos que seguir padrões, prinícios(SOLID) por exemplo, e por aí vai.. mas vai exatamente no ponto que você disse.. a partir do ponto que você começa a complicar seu código pra testar algo.. e no fim é algo que não faz sentido, for what? :)
Comment: @Maniero É diferente do Java, né? Que tem o `ClassLoader` que instancia a classe estática do mesmo jeito (só muda o momento de alocação, que é mais no início da execução da aplicação). Então presumo que no Java não é tão vantagem assim usar classes estáticas.
Comment: @Piovezan imagino que sim. C# 9 deve ter uma forma de configurar quando acontece o processo, porque perceberam que há custos em deixar para acontecer mais tarde e a maioria das pessoas não precisa disso, então obrigando inicializar no *startup*, ficaria mais barato.


Como obter penúltimo registro de uma data no Oracle usando consulta SQL

Question: Preciso puxar as informações de acordo com a penúltima data, atualmente, esse MAX(S2.DTMUDANCA) está trazendo o último, porém não é necessário para mim, somente o último. Tentei algumas questões, mas ainda estou com dúvidas, tentei comparar com um novo select, sem sucesso.
Segue abaixo o select:
SELECT A.CODCOLIGADA, A.CHAPA, A.CODSITUACAO, A.CODTIPO, A.NOME AS COLABORADOR, F.NOME AS FUNÇÃO, S.DESCRICAO AS SETOR,
       (SELECT MAX(S2.DTMUDANCA) FROM RM.PFHSTSEC S2 WHERE S2.CODCOLIGADA = HS.CODCOLIGADA AND S2.CHAPA = HS.CHAPA) AS DATA_SEÇÃO_ATUAL,
       To_Char(A.DATAADMISSAO,'DD/MM/YYYY') AS DATA_ADMISSÃO, To_Char(A.DATADEMISSAO,'DD/MM/YYYY') AS DATA_DEMISSÃO,
       TO_CHAR(HS.DTMUDANCA,'DD/MM/YYYY') AS DATA, (SELECT sa.descricao FROM rm.psecao sa WHERE sa.codcoligada = hs.codcoligada AND sa.codigo = hs.codsecao)
  FROM RM.PFHSTSEC HS, RM.PFUNC A, RM.PFUNCAO F, RM.PSECAO S
  WHERE
    HS.CODCOLIGADA = A.CODCOLIGADA
    AND A.CHAPA = HS.CHAPA
    AND HS.CODCOLIGADA IN (1,5,7,8)
    AND A.CODCOLIGADA = F.CODCOLIGADA
    AND A.CODFUNCAO = F.CODIGO
    AND A.CODCOLIGADA = S.CODCOLIGADA
    AND A.CODSECAO = S.CODIGO

  AND HS.DTMUDANCA >= '01/11/2019'
  ORDER BY A.CODCOLIGADA, A.NOME, hs.dtmudanca

Retorno do select

Select
Answer: A função de agregação MAX() vai retornar apenas a maior data, para trazer "as duas, três, etc maiores" é preciso "rankear" as datas. Isso é possível usando ROW_NUMBER() e OVER.
ROW_NUMBER() retorna o número de uma linhas, mas se usada em combinação com OVER, vai retornar o número da linha de acordo com o critério dentro de OVER.
Imagine por exemplo que tem as datas:
10/11/2022
15/11/2022
01/12/2022
Se fizer um select assim: SELECT DATA, ROW_NUMBER() OVER (ORDER BY DATA) NUMERO, vai retornar:
DATA        NUMERO
==================
10/11/2022  1
15/11/2022  2
01/12/2022  3

Da mesma forma que, se usar ORDER BY DATA DESC, vai interter a ordem, 1 será a maior, no exemplo a última, e assim por diante. Logo, se fizer um WHERE NUMERO < 3 vai trazer as 2 maiores datas, e se quiser só a penúltima basta fazer WHERE NUMERO = 2 :)
Veja aqui um exemplo funcionando: http://sqlfiddle.com/
E a query:
SELECT *
  FROM (
     SELECT COD, DTMUDANCA,
            ROW_NUMBER()
            OVER (ORDER BY DTMUDANCA DESC) ORDEM
      FROM Teste
      )
WHERE ORDEM < 3;


Sylvester-like criterion for semidefiniteness

Question: In Zhou's A Practical Guide To Quantitative Finance Interviews I see the following:

A symmetric matrix is positive semidefinite  if and only if all its upper left (or lower right) submatrices have nonnegative determinants.

I know that looking only at upper left submatrices (i.e, leading principal minors) is not enough to guarantee semidefinitess (see, e.g., this question).
I'm confused by Zhou's wording. I think it should read "all its upper left and lower right submatrices have nonnegative determinants". Is this a correct statement for semidefiniteness ?
I'm not good enough at linear algebra to come up with a proof.
Comment: *'I think it should read "all its upper left and lower right submatrices have nonnegative determinants". Is this a correct statement for semidefiniteness ?'*  No.  The correct statement of Sylvester's generalized criterion for semi-definiteness (for real symmetric or hermitian matrixes) is that *all principal minors are* $\geq 0$.  I gave a proof here:  https://math.stackexchange.com/questions/4145638/a-is-positive-semidefinite-iff-textdet-b-k-geq-0/
Answer: The statement is false. As a simple counterexample, consider the matrix
$$
\pmatrix{0&0&0\\0&-1&0\\0&0&0}.
$$
It should be clear that all "leading" and "trailing" principal minors are zero and therefore non-negative. However, this matrix fails to be positive semidefinite.
For an arguably more interesting example, you can consider
$$
\pmatrix{
1&1&1&2\\
1&1&1&1\\
1&1&1&1\\
2&1&1&1
}.
$$
Comment: Nice counterexample !


Filter a List of Objects Based on A Different List of Objects with Linq

Question: I currently have two types of Lists: List (named LintMessages) and List (named FilterList).
PCMessages Properties:
    public string filename { get; set; }
    public int linenumber { get; set; }
    public string messagetype { get; set; }
    public int messagecode { get; set; }
    public string description { get; set; }
    public string evaluated { get; set; }
    public string comment { get; set; }

Filter Properties:
    public bool applied { get; set; }
    public string messagetype { get; set; }
    public int messagecode { get; set; }
    public string evaluated { get; set; }
    public string filename { get; set; }

The goal is to exclude PCMessages from LintMessages that fit the criteria of any applied Filter and store them in List FiltLintMessages.  For example, if FilterList contains two filters:
Filter1 Properties:
    applied = true;
    messagetype = Warning;
Filter2 Properties:
    applied = true;
    messagecode = 12;
    evaluated = "WIP";

Then I wish to create a List FiltLintMessages from LintMessages that excludes any entries where messagetype contains "Warning" or where messagecode=12 or where evaluated contains "WIP".
Code at time of writing:
FiltLintMessages = (from mess in LintMessages
                    from filt in FilterList
                    where !mess.evaluated.Contains(filt.evaluated)
                         && !mess.filename.Contains(filt.filename)
                         && mess.messagecode != filt.messagecode
                         && !mess.messagetype.Contains(filt.messagetype)
                    select mess).ToList();

Any help would be appreciated.
/* Edited to work off of gaearon's suggested solution. Stepping through with debugger shows that this is the only relevant code to the problem. The correct items are in each list coming up to this block and on the assignment to FiltLintMessages, two separate filters (exclude messagetype "Warning" and messagecode = 10, both applied) only excludes messagecode=10 PCMessages as it is the last applied filter in the list (tested with several instances of multiple filters).  However, the code works with a single applied filter excluding both messagetype = "Warning" and messagecode = 10.  Uploading any more of the code would not help and would bog down the post even more (the program is getting quite large). */
IEnumerable<PCMessage> messages = LintMessages;

foreach (LintMessageFilter filter in FilterList.Where(f => f.applied))
{
    messages = messages.Where(
               m => !m.evaluated.Contains(filter.evaluated)
                       && !m.filename.Contains(filter.filename)
                       && m.messagecode != filter.messagecode
                       && !m.messagetype.Contains(filter.messagetype)
                );
}

FiltLintMessages = messages.ToList(); //FiltLintMessages already initialized

Comment: I think your `messagetype` and `messagecode` should be nullable, because otherwise there's no way to tell if they are initialized or just set to the default values.
Comment: Edited default properties of PCMessages so that default values of Filters will never overlap and provide a false positive.
Comment: You should use nullable types instead of non-trivial default values. Such as `int?` and `MessageType?` (if `MessageType` is enum). Then, in filtering code, check for nullity.
Comment: @Bandoth: instead of writing `(something == false)` you should write `(!something)` ("not something"). This is C# idiom and it's hard to read code otherwise.
Comment: @gaearon: Haha, I have a couple friends who would beg to differ.  I'll evaluate the rest of my code to see if nullable types would be worth adding all the checks for values before using them, but it seems like it would make things quite a bit more explicit.  Thanks for the help.
Comment: @Bandoth: I posted this as a question in case your friends don't mind :-) http://stackoverflow.com/questions/6336735/if-condition-vs-if-condition-false-in-c
Answer: This would apply each applied filter to the sequence in order.
IEnumerable<PCMessages> messages = LintMessages;

foreach (var filterIter in FilterList.Where(f => f.applied)) {
    var filter = filterIter; // capture current filter
    messages = messages.Where (m =>
                   !m.evaluated.Contains (filter.evaluated)
                   && !m.filename.Contains (filter.filename)
                   && m.messagecode != filter.messagecode
                   && !m.messagetype.Contains (filter.messagetype)
    );
}

var FiltLintMessages = messages.ToList ();

Comment: Strange.  Using this method seems to work with any single applied filter, but applying multiple filters seems to only use the last applied one in the FilterList.
Comment: @Bandoth: all right, you got me. Because `Where` is evaluated only on its enumeration, apparently `filter` was always the last filter used. You need to capture current filter inside of `foreach` and use it for filtering.
Comment: @gaearon: Thank you very much.  Works beautifully.
Comment: @Bandoth: if the answer helped you, please don't hesitate to upvote it. You can do so by pressing the up button next to it. Thanks.


Can I edit the properties of System Spacers in LilyPond and double it on the other side of the page?

Question: I can't find any information about system spacers more than:
\paper {
   system-separator-markup = \slashSeparator
}

I find the defaults too small, and I would like to put a second separator aligned to the right (so both sides have one)
Is this possible?
Comment: Have you looked at the tilting-init.ly file itself?
Comment: I didn't know about that file, let me check it out.
Comment: @Aaron Okay, I looked at it. I didn't expect it to be a `\markup` , but that seems useful. Should I just copy the `\markup` lines and edit that? or edit the titling-init.ly file itself?
Comment: I'm afraid I can't answer that. I found the file mentioned in the LilyPond manual [entry for system-separator-markup](https://lilypond.org/doc/v2.20/Documentation/notation/other-paper-variables#miscellaneous-paper-variables), and it seemed a promising lead. I think whether you copy the code locally or edit the file itself is probably more dependent on your personal coding preferences. Maybe make your own copy of the file for inclusion in your projects and edit that.
Comment: I'll try to make a copy and see if everything goes right then. Thank you!
Answer: Okay, what I did was to make a copy of the titling-init.ly in another folder (in my documents), edit some things (please change the name of the variable) and include it in my files with \include.
However, It's actually more useful to just copy the slashSeparator variable into a file instead of making a copy of the entire titling-init.ly and play around with the numbers and else so you can see what they mean.
What worked for me was doubling some of the numbers and adding some extra stuff, so this is my result:
NEW-NAME-OF-YOUR-OWN-VARIABLE = \markup {
  \left-column {
  \vcenter \combine
  \beam #4.0 #0.5 #0.96
  \raise #1.4 \beam #4.0 #0.5 #0.96
  }
  \hspace #100
  \right-column {
  \vcenter \combine
  \beam #4.0 #0.5 #0.96
  \raise #1.4 \beam #4.0 #0.5 #0.96
  }
}

You can just copy that into your working file or save it in another file and include it. And then add it to:
\paper {
   system-separator-markup = \NEW-NAME-OF-YOUR-OWN-VARIABLE
}


Incorrect syntax near the keyword 'where'

Question: Slightly confused about why I'm getting this error;
select *
from #test1
where basepolicystartdate < '20160701'
  and basepolicyenddate is not null
  and renewaldate is not null
where basepolicyid = 5294

I'm getting this error:

Msg 156, Level 15, State 1, Line 24
  Incorrect syntax near the keyword 'where'

If anyone can point me in the right direction.
Using SQL Server Management Studio 2017
Comment: `WHERE basepolicyid = 5294` did you mean to have another `and` ?
Comment: `WHERE basepolicyid = 5294` did you actually include this with your query?
Comment: Yes, well I think so. Been handed this and the person has left, figuring out his stuff is making me lose my hair!
Comment: I'd go out on a limb, and guess that the `where basepolicyid = 5294` was used for debugging, and the original author of the SQL accidentally left that in. I'm not suggesting that you blindly remove it without understanding what the query is meant to do, but it's likely not meant to be there.
Comment: Thank you, soon as I took it out and selected the bit I wanted to test run it was ok.
Answer: WHERE basepolicyid = 5294

You already have a WHERE clause in your query, did you mean to add another 'AND'?
EDIT: Added formatting to make it easier to read.
Comment: Fair enough, Thanks for letting me know, I'm kind of new to replying on StackOverflow.


Is manifold mapping degree equal to algebraic degree for polynomials?

Question: If $M$ and $N$ are oriented $n$-manifolds and $f: M \to N$ then the degree of $f$ is given by
$$
\deg f = \sum_{p \in f^{-1}(q)} sign_p f
$$
where $q$ is a regular value and the sign is $+1$ if $f$ is orientation preserving at $p$ and $-1$ if is orientation reversing at $p$. If we identify $\mathbb S^2$ with the one point compactification of the complex plane, then any polynomial in $\mathbb C[X]$ is a smooth map from $\mathbb S^2$ to itself. Does the degree of a polynomial as a map between manifolds coincide the algebraic degree? Equal up to a sign? Easily related?
It's easy to see that they coincide for $f(z)=z^n$. The fundamental theorem of algebra assures that a regular point has exactly the algebraic degree number of preimages, but can the signs of the preimages lower the mapping degree?
Comment: Related question that might interest you: http://math.stackexchange.com/questions/140123/how-do-different-definitions-of-degree-coincide
Answer: Yes, they coincide.  Any polynomial (or indeed any holomorphic function) on the complex plane is orientation-preserving, so all of the "signs" of the preimage are positive.
Note, however, that the maps $f(n)=z^{-n}$ do not have negative degree.  These maps are also holomorphic on the sphere, so the degrees are positive (with $z^{-n}$ having degree $n$).  To get negative degree, you have to compose with the complex conjugation map, which has degree $-1$.
Comment: @Bungmap Guillemin and Pollack consider the map $z\mapsto z^m$ on the unit cirlce, which indeed has degree $m$ for all integers $m$.  But on the Riemann sphere the map $z\mapsto z^m$ has degree $|m|$.
Comment: In Guillemin Pollack's book it says that $\operatorname{deg}(z^{m})=m$, where $m<0.$ Is correct that $\operatorname{deg}(z^{-n})=n?$
Comment: Why do we have the difference between Riemann's sphere and unit circle?
Comment: The difference is in how $S^1$ gets its orientation. If you want to use local degrees on $S^2$, you think of $S^1$ as getting a positive orientation as the boundary of a neighborhood of a point. The map $z \mapsto 1/z$ maps the positively oriented $S^1$ around $z=0$ to the positively oriented $S^1$ around $z=\infty$. So degree $+1$. But if you consider this is a map from that circle to itself, then it's a reflection with degree $-1$.


Cassandra session data corruption from multithreaded read

Question: I am having an issue with the cassandra api and select queries. In a single threaded context it works just fine. However, when multiple threads use the same object and call the function, even with just two threads, cassandra is returning it's futures with bad data(sometimes appears to be overwritten with data from other select queries, other times it is just garbage). I have a singleton object handling my calls to cassandra, and a byte buffer struct to hold the data returned. I have determined that, on a single thread, it all works as intended, but when  I have added more threads using the same object and calling the same function, erroneous data is introduced into the data returned from cassandra.
The values sizes are ~1kb in size, and the keys are 32 bytes.
You can see the 2 lines surrounded by commented out mutex locks. If uncommented, this prevents the incorrect data issue, but also negates any performance gains from increasing the number of threads.
Additionally, the percentage of corrupted queries is about ~33%.
The cassandra api is supposed to be able to handle multiple threads and connections to the session without any issues(as per http://datastax.github.io/cpp-driver/topics/), so why am I getting back bad data?
I am using Centos7, c++14 and cassandra api 2.15 with cassandra 3.11.4
#include <cassert>
#include "DataObj.h"//contains the rest of my includes

//byteBuf has two members: a const uint8_t pointer, and a uint32_t variable for declaring the size
DataObj::byteBuf  DataObj::threadGet(DataObj::byteBuf key)
{
  CassError rc = CASS_OK;
  CassStatement* statement = NULL;
  CassFuture* future = NULL;
  string temp = "SELECT value FROM "+ keyspace+"."+tablename+" WHERE id = ?";// variables defined elsewhere
  const char* query = (const char*)temp.c_str();
  statement = cass_statement_new(query, 1);
 //I am also having issues with prepared statements not working properly,
//but I believe it is not directly related to this question. This setup was working fine on 1 thread
  cass_statement_bind_bytes(statement, 0, key.data, key.size);
  //rw_mut.lock();
  future = cass_session_execute(m_session, statement);// m_session is the cassandra session of the object
  cass_future_wait(future);
  //rw_mut.unlock();
//The two statements above, when gated by the mutex, do not produce errors when multithreading,
// but also do not gain any performance.
// When not gated, works fine on a single thread, but corrupts the return data on 2 or more threads

  const  uint8_t* st=nullptr;
  size_t len=0;
  rc = cass_future_error_code(future);
  if (rc != CASS_OK)
  {
    //error handling...
  }
  else
  {
    const CassResult* result = cass_future_get_result(future);
    CassIterator* iterator = cass_iterator_from_result(result);
         if (cass_iterator_next(iterator))
          {
             const CassRow* row = cass_iterator_get_row(iterator);
             cass_value_get_bytes(cass_row_get_column_by_name(row, "value"), &st,&len);
          }
    cass_result_free(result);
    cass_iterator_free(iterator);
  }
  DataObj::byteBuf  res((uint8_t *) st, len);
  //was able to use gdb here and confirm that the data is corrupt

  cass_future_free(future);

  return res;
}

Answer: It looks like you're freeing the results before a copy is made from the value pointers into the byteBuf. In single-threaded version, you may be getting lucky that the dereferenced memory is still intact. Multithreaded, you're likely to overwrite.
Comment: Thanks for the assist! I had to copy the data over to a new pointer, and free that pointer elsewhere, but it still worked


Expressing σ as a binary shift map.

Question: Having shown that the only fixed point of $\sigma$ is $x=0$, I've now got the show that the fundamental period-$2$ points of σ are of the form
$x=0 . ababab \ldots$ where $a,b \in \{0,1\}$ and $a\neq b$
I've then got to express these points as fractions in lowest terms using the sum of infinite geometric series.
Would I need to use the definition of a Bernoulli shift map,
$σ(x)=2x \pmod 1$?
Please help!
Answer: If $x=0.\overline{ab}$ then consider $11x=100x-x$ (here I'm using binary notation). What can you deduce from this?

Expressing σ as a binary shift map.


SignatureDoesNotMatch on AWS signed v4 PUT request presigned url

Question: Currently, I have an issue by creating a valid signature v4 presigned url for a PUT request.
The urls are generated on the server side and are then provided to clients.
The clients should use the urls to upload a file over an API Gateway into an Amazon S3 bucket.
To authenticate the request API Gateway IAM authentication is used.
For my use case, a direct upload into an S3 bucket via "s3-presigned-url" is not possible.
The following code describes the generation of the presigned url and is written in Typescript. The generation of the signature v4 url is based on the AWS provided package @aws-sdk/signature-v4.
<code>import { SignatureV4 } from "@aws-sdk/signature-v4";
import { Sha256 } from "@aws-crypto/sha256-js";
import { formatUrl } from "@aws-sdk/util-format-url";

const createSignedUrl = async (credentials: {
  accessKeyId: string,
  secretAccessKey: string,
  sessionToken: string,
}, requestParams: {
  method: "GET" | "PUT",
  host: string,
  protocol: string,
  path: string,
}) => {
  const sigv4 = new SignatureV4({
    service: "execute-api",
    region: process.env.AWS_REGION!,
    credentials: {
      accessKeyId: credentials.accessKeyId,
      secretAccessKey: credentials.secretAccessKey,
      sessionToken: credentials.sessionToken,
    },
    sha256: Sha256,
    applyChecksum: false
  });

  const signedUrlRequest = await sigv4.presign({
    method: requestParams.method,
    hostname: requestParams.host,
    path: requestParams.path,
    protocol: requestParams.protocol,
    headers: {
      host: requestParams.host,
    },
  }, {
    expiresIn: EXPIRES_IN,
  });

  const signedUrl = formatUrl(signedUrlRequest);
  return signedUrl
};
</code>
I use Postman to test the presinged urls.
If I generate a presigned url for an GET request, everything works fine.
If I generate a presigned url for an PUT request and don't set a body in Postman for the PUT request, everything works fine. But I have an empty file in my bucket ;-(.
If I generate a presigned url for an PUT request and set a body in Postman (via Body -> binary -> [select file]), it fails!
Error message:

The request signature we calculated does not match the signature you provided. ...

The AWS documentation https://docs.aws.amazon.com/general/latest/gr/create-signed-request.html describes that the payload has to be hashed within the canonical request. But I don't have the payload at that time.
Is there also an UNSIGNED-PAYLOAD option if I want to generate an presigned url for a PUT request that is sent to an API Gateway, like described in the documentation for the AWS S3 service?
How do I configure the SignatureV4 object or the presign(...) method call to generate a valid PUT request url with UNSIGNED-PAYLOAD?
Comment: Try including `"X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD"` in the header of the request to be presigned.
Comment: @jellycsc
Unfortunately doesn't work. If I extend the headers section with *"X-Amz-Content-Sha256": "UNSIGNED-PAYLOAD"* than the PUT request with no body added also failed.
Answer: I was able to compare my generated canonical requests with the canonical request that is expected by the Amazon API Gateway.
The Amazon API Gateway always expects a hash of the payload no matter if I add the query param X-Amz-Content-Sha256=UNSIGNED-PAYLOAD to the url or not.
Thus the option "UNSIGNED-PAYLOAD" as canonical request hash value for API Gateway IAM Authentication is not possible, as would be possible with Amazon S3 service.
Answer: You can use unsigned payload with Single Chunk, Here is how (I built my own coldfusion based AWS4 signer, so you will have to figure out where to put it)
In the signer, I set:
X-Amz-Content-Sha256:UNSIGNED-PAYLOAD\n (DO NOT HASH!)
For the hashed payload: "UNSIGNED-PAYLOAD" (DO NOT HASH!)
in the header:
X-Amz-Content-Sha256 = UNSIGNED-PAYLOAD
Then the body can have what ever it needs to send up.


Can I do a scrollable calendar/events listing with a Drupal module?

Question: I have the FullCalendar module installed, and it's pretty easy to use that to put a little calendar display in a block (making it look good is another matter).
But can I use it to make an events display like the one on Metromix?
(Sorry, I guess I'm too new to post an image! Please see the link above)
I can make FullCalendar display a week's worth of events, but that's not really what's happening here.  As you can see in the example, the user can scroll left or right to get different days to display, have a particular day in the list selected, and have that selected day's events displayed below.  Those are the parts that aren't clear how to do with FullCalendar (if it's possible at all).
Can FullCalendar do this?  Is there another module that can do this?  Or do I have to do this kind of thing by hand?
Thanks in advance for any pointers!
Answer: Yes, I believe that you can do that with the full calendar module.
In the example link you posted when you click left or right though the months an ajax request is actually happening returning the next months set of events.
The full calendar module also has ajax support.
To turn ajax on on your calendar you need to look at a setting called Use AJAX under the advanced section:

There is a similar question, AJAX in a calendar view block, which may also be of interest.


Does issuing an SSL certificate at a new company immediately invalidate the certificates on our servers?

Question: We have a wildcard certificate issued by GoDaddy coming up for renewal, and I would like to use a different company (which is yet to be chosen). The wildcard certificate is on use at a dozen sites across a few servers. There will be a gap of a few hours between the certificate being issued at the new authority, and when we can install the certificate on all those sites & servers. During that gap, will our users notice anything, e.g.,

"Site is insecure" type of warning
Outright failure of the site to work (they are Windows/IIS sites).

I am wondering if, for instance, the new authority issue something to GoDaddy that makes GoDaddy revoke our certificate that they have on file. Or, will a web browser find the installed certificate mis-matching with the newly issued certificate, and cause a problem.
Answer: A certificate will be valid as long as the system date that verifies the domain is between its validity not-before and not-after date, all other certificates in the chain are valid, and the issuer has not taken action to revoke the certificate by means of CRL or OCSP options at their disposal (most commonly due to counterfeit or security issues such as a private key that becomes compromised). Obviously, the domain have to match. Issuing a new one will not affect that.
You can actually request the new certificate before the expiration date of the current and start changing certificates ahead of that point in time so that there is the smallest disruption possible in services. If you wait for expiration in order to proceed with the renewal, the services will show the insecure note if not blocked completely by security settings on browsers like HSTS or other security mechanisms.
Automation tools related to certificate renewal like acme.sh or the Let's Encrypt module in WHM do their job usually 1 month ahead of expiration so that caching and other functionality doesn't impact the renewal process either.
Comment: The first paragraph is incomplete. A certificate may also become invalid due to CRL or OCSP checks. Won't happen in this situation, though, so the conclusion remains correct that OP can go ahead and order the new certificate and the old one will remain valid.
Comment: Requesting a new certificate early is not only possible, it's the industry norm. There's a reason that you generally hear about it when a certificate lapses on a big site, and it's because sensible admins renew their certificates early whenever possible (aside from ensuring minimal downtime just for the renewal itself, you also minimize the possibility of downtime resulting from issues with renewing the certificate).
Comment: Accepting this answer because of the detailed explanation compared to the one from TomTom, but obviously appreciate that one as well, and the input from @jcaron here.
Comment: Of course, revocation is also a reason for invalidity. I just went with reasons that invalidate a certificate when no action is taken and time just pass by. I will add those two and have a much more complete source of information. Thanks, @jcaron
Answer: No, Getting a new certificate from another CA is absolutely unrelated to the old certificate.


Foot selection during shooting

Question: How does one determine the proper foot to use when taking a shot on goal in football? For this question assume the player is equally skilled with both the left and right foot. I'm assuming position on the field is a contributing factor.
Comment: I'm leaving this as a comment, as I don't think it's a complete answer. When playing, if the ball is on my right side, I'll tend to play it with the right foot. If it's on my left side, I'll play it with the left. That's what feels natural to me.
Answer: There are a number of factors in determining which foot to shoot with in football, including:
Position of the Ball
Due to the mechanics of dribbling (and naturally, passing), the ball is rarely directly under the player's centre of mass (and it is extremely difficult to strike the ball effectively from here.) The ball will often be on the left or right side of central to the player, and should be struck with that foot accordingly.
If a ball is being crossed to the striker, proper technique is to place your body in line with the path of the ball and strike across your body against the movement of the ball (rather than across the movement of the ball whilst facing the goal, which is a lot more difficult to control.) This will determine the foot you strike with for you; if the cross is coming from the left, natural body movement will dictate that you strike with your left foot.
Position of the Player Relative to the Goal
A player should strike the ball with the foot that affords the largest target area of the goal to aim at. If the player is on the left side of goal, this is the right foot and vice-versa. This is due to the action of striking the ball, which opens the body in the direction of the foot being used. If you strike the ball with your left foot on the left side of goal you are turning your body away from goal, which makes it more difficult to shoot towards the far post.
Position and Movement of the Goalkeeper (and/or Defensive Players)
A striker should always attempt to place the ball in a manner that makes it as difficult as possible for the defending team to stop the shot. If the goalkeeper is moving or shifting their body weight to your right, shooting with your right will allow you more control and power in striking it to your left. The mechanics of movement in defence will also often allow a striker to place a shot between a defender's legs with one foot but not the other.
Desired Movement of the Ball
If you want a shot to curl from right to left, it is easier to do so using the instep of your right foot. Whilst possible to do so with your left foot, it is mechanically harder to impart as much revolution on the ball whilst maintaining control. Similarly, it is easier to strike a placed curled shot from left to right using your left foot.
Personal Preference
Even in the hypothetically perfectly skilled two-footed player, a striker is going to have a preferred foot. If there is no mechanical reason for choosing which foot to strike with, the player will default to the most natural foot.
Notes
Of course, there are plenty of one-footed players who are quite capable of striking effectively against the preferred mechanical option. Sometimes taking the less conventional option will be more effective in catching the defence off-guard. Proper striking technique is more important that choice of foot.
[Source: 25 years of playing football, Junior coaching licenses.]

Foot selection during shooting


How can I get single data or specific data from the API in PHP?

Question: When I am using the below code then I am getting all the data printed
<?php
$url = "https://api.postalpincode.in/pincode/201301";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
$xmldata = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_r($xmldata);
?>

But I am not able to know that if only one of these data is to be printed then how will we do it?
for example, I want to print only the district in this
enter image description here
Comment: `json_decode` can help you
Answer: This works for me:
<?php

$url = "https://api.postalpincode.in/pincode/201301";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_TIMEOUT, 3600);

$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$json = json_decode($response, true);
$districts = [];
foreach($json as $item) {
    foreach($item['PostOffice'] as $office) {
        $districts[] = $office['District'];
    }
}

print_r($districts);

and the result is
Array
(
    [0] => Gautam Buddha Nagar
    [1] => Gautam Buddha Nagar
    [2] => Gautam Buddha Nagar
    [3] => Ghaziabad
)


Django multiple files in one field

Question: I am trying to make a database using sqlite3 with a field for multiple files so that i can have a file list on mt model info page. For example if the model is student and he needs to store an unspecified number of homework files and needs to be able to add, view, edit and delete them. Any help is much appreciated.
Comment: You don't need multiple files in one field, you need a separate Files table with a foreign key to the student.
Answer: You can make a homeworkfile model. In that model add a file_upload field.
And then relate student table to homeworkfile model using one-to-many relationship.
<code>class homeworkfile(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    file_upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
</code>
Comment: Thanks for the idea, is there anywhere I can find documentation for referencing and editing  these files?

Django multiple files in one field


Algebra Problem in Korean Mathematical Olympiad

Question:
Let $a_1=5, a_2=25, a_{n+2}=7a_{n+1}-a_n-6$. Prove that $\exists x, y \in \Bbb{Z} $ s.t. $a_{2023}=x^2+y^2.$

Doing some trials and errors, I found that $a_n=(2F_{2n-1})^2+F_{2n}^2$. ($F_n$: Fibonacci number) Then I tried to show this...
\begin{align}
n=1; \; & a_1=5=(2 \cdot 1)^2+1^2. \\
n=2; \; & a_2=25 = (2 \cdot 2)^2+3^2. \\
\text{Assume.} \; & a_k=(2F_{2k-1})^2+F_{2k}^2, a_{k-1}=(2F_{2k-3})^2+F_{2k-2}^2. \\
n=k+1; \; & a_{k+1}=7(2F_{2k-1})^2+7F_{2k}^2-(2F_{2k-3})^2-F_{2k-2}^2-6.
\end{align}
And I'm stuck...
The Fibonacci Lemmas I know with squares are those below, which I don't know where to use...
\begin{align}
& F_{k}^2=F_{k-1}F_{k+1} + (-1)^{k+1}. \\
& \sum_{i=1}^{k} F_i^2=F_kF_{k+1}.
\end{align}
Can I use these lemmas to this problem?
Comment: If your hunch is correct, you should be able to use Binet's formula to brute force this out.
Comment: Note: You can prove by induction that $F_{2n+3}^2 = 7 F_{2n+1}^2 - F_{2n-1}^2 - 2$, and a similar expression for $F_{2n+2}$. This is related to Binet's formula, because the roots of $ x^2 - 7x + 1 $ are $ [(1 \pm \sqrt{5}) /2 ] ^4$.
Answer: Inspired by @CalvinLin's comment.
\begin{align}
& F_1=F_2=1, F_{n+2}=F_{n+1}+F_{n}. \\
\ \\
& \text{Lemma 1. } F_n^2=F_{n-1}F_{n+1}+(-1)^{n+1}. (n \geq 2) \\
& \text{(i) } n=2: F_2^2=1^2=1\cdot2+(-1)^3=F_1F_3+(-1)^3. \\
& \ \quad n=3: F_3^2=2^2=1\cdot3+(-1)^4=F_2F_4+(-1)^4. \\
& \text{(ii) Assume that } F_k^2=F_{k-1}F_{k+1}+(-1)^{k+1}, F_{k-1}^2=F_{k-2}F_{k}+(-1)^k. (k\geq 3)\\
& \text{(iii) } F_{k+1}^2=F_k^2+2F_kF_{k-1}+F_{k-1}^2 = F_{k}(F_k+2F_{k-1})+F_kF_{k-2}+(-1)^k \\
& \quad \ = F_k(F_k+2F_{k-1}+F_{k-2})+(-1)^{k+2} = F_kF_{k+2}+(-1)^{k+2}. \\
&\quad \ F_{k+2}^2=F_{k+1}^2+2F_{k+1}F_k+F_k^2 = F_{k+1}(F_{k+1}+2F_{k})+F_{k+1}F_{k-1}+(-1)^{k+1} \\
& \quad \ = F_{k+1}(F_{k+1}+2F_{k}+F_{k-1})+(-1)^{k+3} = F_{k+1}F_{k+3}+(-1)^{k+3}. \ _\blacksquare \\
\ \\
& \text{Lemma 2. } F_{n+4}^2=7F_{n+2}^2-F_n^2+2(-1)^n. \\
& \text{By Lemma 1, } F_{n+1}^2=F_nF_{n+2}+(-1)^{n+2} \\
& \Rightarrow (F_{n+2}-F_n)^2-F_nF_{n+2}=(-1)^n, F_{n+2}^2-3F_nF_{n+2}+F_n^2=(-1)^n. \\
& \Rightarrow 2F_{n+2}^2-6F_nF_{n+2}+2F_n^2=2(-1)^n. \\
& \Rightarrow (9F_{n+2}^2-6F_nF_{n+2}+F_n^2)-(7F_{n+2}^2-F_n^2)=2(-1)^n. \\
& \Rightarrow (3F_{n+2}-F_n)^2=7F_{n+2}^2-F_n^2+2(-1)^n. \\
& \therefore F_{n+4}^2=7F_{n+2}^2-F_n^2+2(-1)^n. \ _\blacksquare \\
\ \\
& \text{Claim. } a_n=(2F_{2n-1})^2+F_{2n}^2. \\
& \text{(i) } n=1: a_1=5=(2\cdot1)^2+1^2=(2F_1)^2+F_2^2. \\
& \ \quad n=2: a_2=25=(2\cdot2)^2+3^2=(2F_3)^2+F_4^2. \\
& \text{(ii) Assume that } a_k=(2F_{2k-1})^2+F_{2k}^2, a_{k-1}=(2F_{2k-3})^2+F_{2k-2}^2. (k\geq 2)\\
& \text{(iii) } \\
& a_{k+1}=7a_k-a_{k-1}-6 \\
& = 28F_{2k-1}^2+7F_{2k}^2-4F_{2k-3}^2-F_{2k-2}^2-6 \\
& = 4\left\{7F_{2k-1}^2-F_{2k-1}^2+2(-1)^{2k-1}\right\}+\left\{7F_{2k}^2-F_{2k-2}^2+2(-1)^{2k-2}\right\} \\
& = 4F_{2k+1}^2+F_{2k+2}^2=(2F_{2k+1})^2+F_{2k+2}^2. \ _\blacksquare \\
\ \\
&\therefore x=2F_{4045}, y=F_{4046}. \ _\blacksquare
\end{align}


Erro em criar colunas no CSS

Question: Colegas.
Assumi um projeto agora com uma estrutura já pronta, porém estou levando uma surra com o css do site. Quando é incluído mais uma sala nesse projeto, as divs não ficam alinhadas em 3. Vejam:

O código HMTL/PHP:
while($jmSeg = mysqli_fetch_object($sqlSeg)){ ?>

SALA <?php  echo $jmSeg->sala; ?>

            <?php
                $sqlI = mysqli_query($conecta,"SELECT * FROM `horarios` WHERE dia = 'Segunda e Quarta' and sala = '".$jmSeg->sala."' and status = '1' ORDER BY hora");
                while ($horasI = mysqli_fetch_object($sqlI)) {
                    echo"

".utf8_encode($horasI->hora)."".$horasI->atividade."
Prof. ".$horasI->professor."

";
                 }
             ?>

<?php }  ?>

CSS:
.hr-corpo{
    width:30%; margin:0% 1.666666666666667% 4% 1.666666666666667%; background:rgba(0,0,0,0.0); min-height:10px; display:inline-block; padding:0%; float:left;}/*CORPO DA AGENDA*/

.hr-container-campos-sala{
    font-size:0.7em;}

Comment: Se bem entendi, você gostaria que as divs fiquem alinhadas em 3 colunas  e que por exemplo a div4 fique abaixo da div1 e assim por diante?
Comment: Olá Will Ramos. Exatamente. Me desculpe por não poder passar mais informações, pois como eu disse no post, esse projeto já estava pronto e quando assumi, percebi que isso ocorre quando a inclui mais salas.
Answer: O que você procura se chama masonry, e pode ser feito utilizando a propriedades "collumn" do css, segue abaixo um exemplo da propriedade com responsibilidade para mobile.
CSS:
body { font: 1em/1.67 'Open Sans', Arial, Sans-serif; margin: 0; background: #e9e9e9; }
.wrapper { width: 95%; margin: 50px auto; }
.masonry { margin: 10px 0; padding: 0; column-gap: 10px; column-rule:dashed #FF0000 5px}
.item { display: inline-block; background: #fff; padding: 20px; margin: 0 0 10px 0; width: 100%;-webkit-box-sizing: border-box; }

@media only screen and (min-width: 400px) {
.masonry { -moz-column-count: 2; -webkit-column-count: 2; column-count: 2; }
}

@media only screen and (min-width: 700px) {
.masonry { -moz-column-count: 3; -webkit-column-count: 3; column-count: 3; }
}

@media only screen and (min-width: 900px) {
.masonry { -moz-column-count: 10; -webkit-column-count: 5; column-count: 5; }
}

@media only screen and (min-width: 1280px) {
.wrapper { width: 1260px; }
}

HTML:

1asdasdasdadasd

2asdasdasdadasd

3asdasdasdadasd

4asdasdasdadasd

5asdasdasdadasd

6asdasdasdadasd

7asdasdasdadasd

8asdasdasdadasd

9asdasdasdadasd

10asdasdasdadasd

Comment: Olá Will. Obrigado.

Erro em criar colunas no CSS


Eclipse: How can I find all (public) classes/methods without Javadoc comments?

Question: In Eclipse, is there a way to find all (public) classes/methods which do not currently have any Javadoc comments?
Additionally, would it be possible to automatically add a basic Javadoc comment such as:
/**
 * TODO Javadoc
 * @param i
 * @return
 */

so that these methods without Javadoc would also be added to my TODO list?
Answer: See Window -> Preferences -> Java -> Compiler -> JavaDoc
Change the missing JavaDoc tags preference to Warning.
After all projects have been rebuilt, you can switch to the Problems View and all methods with missing JavaDoc are listed.
HTH Tom
Edit: Unfortunately there is no way to add a JavaDoc-template to all missing methods in one single step. The fastest way is to insert a JavaDoc is to set the cursor on the method-declaration and then using the shortcut Shift+Alt+J
Comment: Actually you can add JavaDoc to all missing methods in a class. From the package explorer view, expand the class that you wish to generate JavaDoc on. Select all of the methods and press Alt-Shift-J. This will generate Javadoc for all of the methods in that one class. If however you want to do it on a package or project level, I would point you at the responses to this question:
http://stackoverflow.com/questions/2530043/any-way-to-auto-generate-all-javadoc-comments-in-eclipse


Help me get a guitar amp for Mark Knopfler sound

Question: I play Mark's "clawhammer" fingerstyle and have a Les Paul R8, but don't have any amps.
I like Mark's solo career more than his Dire Straits era, and seek a sound close to that. Think about songs like "Speedway at Nazareth", "I dug up a diamond", "Song for Sonny Liston", etc.
To my knowing, Mark usually plays his Les Pauls with a Reinhardt Talyn, Talon or Commet, which are based around Marshall JTM and JCM.
I play for my leasure and seek a tube amp with an appropriate apartment volume, which can also sound good quiet. Here are some amps I thought about:
Marshall Astoria - Can go to 5w and reduce volume with the looper level. Has bass and treble boost for low volumes. Sounds like a mix of vintage and modern Marshall amps.
Marshall SV20/ SC20 - can go to 5w. Should be somewhere in the ballpark of Mark's amps.
Victory Sheriff/Duchess - should be voiced around Marshall, and have a super low wattage settings.
Morgan mvp23 - can to down up to 0.25w. A mix of British and American voicing. Not sure it'll get dirty enough.
Friedman Pink Taco/ Friedman Dirty Shirley - I liked their sound, but afraid the 20w will be too much.
Fender Bassbreaker 15 - sounds marshall-ish, and good at low volumes.
Mesa Boogie California - no Marshall voicing, but I liked its sound. It can also be reduced to 2w.
I wonder which of those you find mostly approprite for the task?
As for pedals - do I need one? I always had the impression that Mark is being plugged directly into the amp (volume pedal not included), without any overdrive/distortions. I read somewhere that Mark used a HotCake not extensivly.
P.S
Since I seek a relatively low volume, I wonfer if a clean fender amp + several stacked dirt pedals (like a Warthog with a Tube Screamer) will give me a similar results.
Answer: I don't have an exact answer to your question but I can share some thoughts:

I like Mark's solo career more than his Dire Straits era, and seek a sound close to that. Think about songs like "Speedway at Nazareth", "I dug up a diamond", "Song for Sonny Liston", etc.

AFAIK, "Speedway" is played with the Pensa, not with the Les Paul

Mesa Boogie California - no Marshall voicing, but I liked its sound. It can also be reduced to 2w.

In his 2019 tour, Knopfler has been using Kemper profiling amps, but in the past I've heard him mention the Mesa Boogies

Marshall SV20/ SC20 - can go to 5w. Should be somewhere in the ballpark of Mark's amps.

A 20W amp is still quite loud for bedroom tones. I own a Marshall Origin 20C, and I can't overdrive it without killing the neighbours (even when I bring the power down to 5W). On the other hand, I tried the SV5C and wasn't too impressed with the tone. Personally, I don't see much correlation between the Marshall sound and Knopfler's tone, but that's just me.

As for pedals - do I need one? I always had the impression that Mark is being plugged directly into the amp (volume pedal not included), without any overdrive/distortions. I read somewhere that Mark used a HotCake not extensivly.

Knopfler uses at least a volume pedal (you can see him using in "Song for Sonny Liston" in the Roadrunning Live DVD). It wouldn't suprise me if he also used at least a reverb and potentially a compressor. I suspect he uses a compressor when he plays clean (but he uses his strat for that). However, if you're talking exclusively about overdrives, I've never heard him talking about an O/D pedal. He seems to rely purely on his amps for the tone.

I wonfer if a clean fender amp + several stacked dirt pedals (like a Warthog with a Tube Screamer) will give me a similar results.

You might get "similar" results, but it would be hard to nail the exact tone.
This question is so specific that you might be better off asking in a forum for Mark Knopfler enthusiasts. I can point you to a couple ;)


In R, I cannot use the tidyr:fill function for some reason

Question: I have a dataframe as the following:
      Date Bond2 Bond3 Bond5 Bond6
3218 44492    NA    NA    NA    NA
3219 44493    NA    NA    NA    NA
3220 44494  0.13  0.41  0.73  1.05
3221 44495  0.13  0.41  0.74  1.07
3222 44496  0.14  0.56  0.95  1.22
3223 44497  0.16  0.83  1.22  1.44
3224 44498  0.15  0.82  1.25  1.54
3225 44499    NA    NA    NA    NA
3226 44500    NA    NA    NA    NA
3227 44501  0.15  0.71  1.09  1.38
3228 44502  0.15  0.73  1.09  1.39
3229 44503  0.09  0.59  0.93  1.27
3230 44504  0.13  0.65  1.01  1.31
3231 44505  0.10  0.58  0.97  1.29
3232 44506    NA    NA    NA    NA
3233 44507    NA    NA    NA    NA
3234 44508 -0.02  0.57  0.95  1.25

I want to use the following code: data <- fill(data) However nothing happens when I do this.
Then if I try for example data$Bond2 <- fill(data$Bond2), I get the error
Error in UseMethod("fill") :
  no applicable method for 'fill' applied to an object of class "c('double', 'numeric')"

I do not know how to fix this? I have tried converting to character, and again nothing. Thanks.
Comment: the syntax is `data <- fill(data, Bond2, ...)`
Comment: You can try: `data %>%
  fill(Bond2, Bond3, Bond5, Bond6, .direction = 'downup')`
Answer: No need to convert to char
df <- data.frame(Date = c(4492,44493,44494,44495,44496,44497,44498,44499),
                 Bond2 = c(NA,NA,0.13,0.13,0.14,0.16,0.15,NA),
                 Bond3 = c(NA,NA,0.41,0.41,0.56,0.83,0.82,NA))
df
 Date Bond2 Bond3
1  4492    NA    NA
2 44493    NA    NA
3 44494  0.13  0.41
4 44495  0.13  0.41
5 44496  0.14  0.56
6 44497  0.16  0.83
7 44498  0.15  0.82
8 44499    NA    NA

df %>% fill(Bond2,Bond3,.direction="downup")

Output:
   Date Bond2 Bond3
1  4492  0.13  0.41
2 44493  0.13  0.41
3 44494  0.13  0.41
4 44495  0.13  0.41
5 44496  0.14  0.56
6 44497  0.16  0.83
7 44498  0.15  0.82
8 44499  0.15  0.82

Comment: Thanks. This works. I have 200+ variables, though, is there an easy way to do it for basically variable 2 to 200+?
Comment: could do 2:200+ yeah
Comment: If you check `?tidyr::fill` you'll see that the dots `...`, which we feed `Bond2` and `Bond3` to, expect a "tidy selection", which basically is a very flexible way to select columns, so in the case above you can do `df %>% fill(2:3, .direction="downup")` , and in your real case you can do use `2:245` or select all columns that follow a given name pattern for instance.
Comment: Ah, there we go, GuedesBF answered as I was typing this :)
Answer: We can use a pipe to feed the data to fill, then a selection helper to select the desired columns (here starts_with), then use the .direction argument too.
The selection helper is very useful if we have many columns.
library(dplyr)
library(tidyr)

df %>% fill(starts_with('Bond'), .direction = 'downup')

Alternatives with other variable selections:
df %>% fill(-date, .direction = 'downup')

df %>% fill(2:200, .direction = 'downup')

df %>% fill(num_range('Bond', 1:6), .direction = 'downup')


I cannot get assets to work in Rails application

Question: I just fixed some problems with database in production mode of my Rails application and now I couldn't get any assets to work. Here is the part of production.log:
    I, [2016-06-11T10:26:14.368556 #4807]  INFO -- : Started GET "/assets/application-dcd31064dda15c4420c78914a108b57fe4a17ea71a20e180b4d51e1f12c45c7a.js" for 127.0.0.1 at 2016-06-11 10:26:14 +0200
F, [2016-06-11T10:26:14.375224 #4807] FATAL -- :
ActionController::RoutingError (No route matches [GET] "/assets/application-dcd31064dda15c4420c78914a108b57fe4a17ea71a20e180b4d51e1f12c45c7a.js"):
  actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.4) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.6) lib/rails/engine.rb:518:in `call'
  railties (4.2.6) lib/rails/application.rb:165:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  rack (1.6.4) lib/rack/content_length.rb:15:in `call'
  rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
  /home/nikola/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'
  /home/nikola/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'
  /home/nikola/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'

I have app/assets/javascript/application.js and app/assets/stylesheet/application.scss because of Bootstrap. I tried with precompiling assets for production environment and still nothing.
app/assets/stylesheet/aplication.scss
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
 *= require styles
 */

@import "bootstrap-sprockets";
@import "bootstrap";
@font-face{
font-family:'Glyphicons Halflings';
src: font-url("bootstrap/glyphicons-halflings-regular.eot");
src: font-url("bootstrap/glyphicons-halflings-regular.eot?#iefix") format("embedded-opentype"),
font-url("bootstrap/glyphicons-halflings-regular.woff") format("woff"),
font-url("bootstrap/glyphicons-halflings-regular.ttf") format("truetype"),
font-url("bootstrap/glyphicons-halflings-regular.svg#glyphicons_halflingsregular") format("svg")
}

Comment: Do you have precompiled assets in /public directory?
Comment: @kunashir Yes, they're precompiled.
Answer: Problem is solved - I just had to change this line:
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

To
config.serve_static_files = true

In config/environments/production.rb to serve static files from /public directory.


Instalando apk de um app a partir de outro app já instalado

Question: Após pesquisa não encontrei nada recente ou específico sobre isso, então resolvi perguntar aqui.
Na empresa em que trabalho temos algumas soluções móveis e diferentes clientes usam diferentes conjuntos de Apps. Assim, nos foi requerido que escrevêssemos uma aplicação que deve ser capaz de instalar os apks (e eventualmente atualizar) dos outros apps do nosso ecossistema no aparelho, tudo sem a interação do usuário. Bom, sei que nas configurações do device posso indicar o app com permissão para instalação, mas ainda assim, pelo que sei, o usuário precisa interagir.
Gostaria de saber se isso é possível de ser feito sem que o usuário participasse do processo e qual seria o caminho, caso possam indicar algum material mais detalhado.
Muito obrigado pela atenção!
Comment: Se não me engano, as versões mais recentes do Android não permitem a instalação de um APK sem confirmação, mesmo que você libere o aplicativo para realizar instalações.
Comment: @RafaelTavares muito obrigado pelo retorno.
Answer: Instalar apks por fora da store tem que ter permissão Developer liberada no sistema operacional Android (ao menos nas versões mais atuais do sistema creio que seja assim)
Se optar por colocar na play store você pode abrir "um activity" com a playstore, como descrito na documentação
https://developer.android.com/distribute/marketing-tools/linking-to-google-play
Por exemplo:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
        "https://play.google.com/store/apps/details?id=com.example.android"));
intent.setPackage("com.android.vending");
startActivity(intent);

E para evitar abrir esse Activity se o app já estiver instalado você pode usar o getApplicationInfo (que poderá checar se está habilitado também) ou usar simplesmente o getInstalledApplications e checar na lista
Ou seja, você induz o usuário a instalar via playstore o app se não tiver instalado ainda, assim facilitando e sem precisar de permissões root ou developer.
Eu estou um pouco enferrujado sobre Android, mas creio que com https://developer.android.com/reference/android/content/pm/PackageInstaller você consegue isso, pois desde a API 29 o ACTION_INSTALL_PACKAGE [e considerado obsoleto
Provavelmente usando installExistingPackage que vai necessitar da permissão Manifest.permission.INSTALL_PACKAGES (não deve usar com pacotes de terceiros)

Você também pode experimentar o Google play instant:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri.Builder uriBuilder = Uri.parse("https://play.google.com/store/apps/details")
    .buildUpon()
    .appendQueryParameter("id", "com.example.android")
    .appendQueryParameter("launch", "true");

uriBuilder.appendQueryParameter("referrer", "exampleCampaignId");

intent.setData(uriBuilder.build());
intent.setPackage("com.android.vending");
startActivity(intent);

Dessa forma ele nem vai instalar (https://developer.android.com/topic/google-play-instant), no entanto o app que vai usar esse serviço precisa seguir uma série de situações para ser disponibilizado como Instant: https://developer.android.com/topic/google-play-instant/guides/reduce-module-size
Comment: Obrigado pela riqueza de detalhes Guilherme. Vou experimentar as opções que deu e ver qual delas seria mais viável para o cliente. Grande abraço.


PHP e json como imprimir?

Question: Alguém poderia me ajudar a imprimir cada uma desses elementos deste Json usando php.

{"data":{"charges":[{"code":30013193,"dueDate":"05/09/2017","checkoutUrl":"https://sandbox.boletobancario.com/boletofacil/checkout/985FFB59969D9F117D47FD7D1881880E","link":"https://sandbox.boletobancario.com/boletofacil/charge/boleto.pdf?token=60370:m:9675cf45e010be056a06bdef6e0f478bd75f435ce9cda7d0cf5b9afdfc6fefc5","payNumber":"BOLETO TESTE"}]},"success":true}
Answer: Utilize a função json_decode:

json_decode( string $string, bool $assoc_array = false )

Exemplo minimo

$json = '{"data":{"charges":[{"code":30013193,"dueDate":"05/09/2017","checkoutUrl":"https://sandbox.boletobancario.com/boletofacil/checkout/985FFB59969D9F117D47FD7D1881880E",
  "link":"https://sandbox.boletobancario.com/boletofacil/charge/boleto.pdf?token=60370:m:9675cf45e010be056a06bdef6e0f478bd75f435ce9cda7d0cf5b9afdfc6fefc5","payNumber":"BOLETO TESTE"}]},"success":true}';

$value = (json_decode($json, true));

echo $value['data']['charges'][0]['code'];
echo PHP_EOL;
echo $value['data']['charges'][0]['dueDate'];
echo PHP_EOL;
echo $value['data']['charges'][0]['checkoutUrl'];
echo PHP_EOL;
echo $value['data']['charges'][0]['link'];
echo PHP_EOL;
echo $value['data']['charges'][0]['payNumber'];
echo PHP_EOL;
echo $value['success'];
echo PHP_EOL;

Exemplo ONLINE
Referencias

json_decode
JSON to PHP Using json_decode

PHP e json como imprimir?


if $f:(a,b) \rightarrow (c,d)$ is a differentiable surjection and $f'(x)$ is never zero then $f$ is a homeomorphism

Question: There is a theorem in our analysis book which says:
if $f:(a,b) \rightarrow (c,d)$ is a diffrentiable surjection and $f'(x)$ is never zero then $f$ is a homeomorphism.
This is the proof of the book:
if $f'$ is never zero then by the intermediate value property of derivatives, it is either always positive or always negative. We assume for all $x$ that $f'(x)>0$. If $a<s<t<b$ then by the Mean Value Theorem there exists $\theta \in (s,t)$ such that $f(t)-f(s)=f'(\theta)(t-s)>0$. Thus $f$ is strictly monotone. Differentiability implies continuity, so $f$ is a homeomorphism $(a,b) \rightarrow (c,d)$.
As I know for proving that $f$ is a homeomorphism, We should prove that $f$ is a continuous bijection and $f^{-1}$ is also continuous. But in this proof the book just proved that $f$ is a continuous bijection, what about continuity of $f^{-1}$? Am I Right? If not, what is my mistake then?
Comment: You are right. It's just that there is a theorem that states that a continuous bijective mapping defined on an interval has a continuous inverse.
Comment: @LeBtz Does this theorem any name or something that I can find it?
Comment: Actually Mark Joshi almost proved that. You just have to replace $f'>0$ with $f$ strictly increasing (or decreasing) which you always have for a bijective continuous function on an interval.
Answer: we have to show that the image of every open set is open. Take $f'>0$ everywhere WLOG. (work with -f otherwise)
 Consider an open set $U$ and $x \in U.$ Take $y < x< z$ all in $U.$ Then
$$
f(y) < f(x) < f(z)
$$
since $f'$ is never zero. So the image set contains $(f(y),f(z))$ that is an open interval containing $f(x)$ so the image of $U$ is open as claimed and we are done.
Comment: No, the proof is correct. If you want to prove that preimages of $f^{-1}$ are open you can aswell prove that images of $f$ are open (of open sets) which he did in this case.
Comment: I know that $f$ is continuous. what I want to prove is continuity of $f^{-1}$. So, I think for proving by your approach we need to prove that the **preimage** of every open set is open. (I'm not sure but I think proving that the image of every open set is open will prove the continuity of $f$ ).
Comment: @LeBtz Thank you so much
Answer: The continiuity of $f^{-1}$ follows from the equality $(f^{-1} )' (y) =\frac{1}{f'(f^{-1} (y))}$ which shows that $f^{-1}$ is differentiable and hence continuous.


finger picking vs pick tone

Question: I've been writing with my band and when we play live, I switch off between picked parts and finger picking parts throughout the songs. I don't notice much difference in the tone playing live together (both methods sound great to everyone). However, when I record my own tracks at home, the difference between picked and finger-picked parts is drastic.
As you can imagine, the finger picked stuff sounds much fatter and less bright. I'm not using fingernails and don't mess with banjo-style finger picks. What can I do to help get the tones to be as similar as possible?
My current clean channel is:
guitar => Compresser => EQ => Reverb => amp
I'm currently playing a strat and tele with humbuckers and I use a 0.75mm pick*
Answer: Why would you want them to be as similar as possible? Each one has its unique characteristic which is desirable in its own way.
It can be done to an extent though, a few tips would be first in the way you play. You can fingerpick a little closer to the bridge or you can pick closer to the neck. You can also grow your right hand nails out just a bit so you catch some nail along with the skin when you pluck.
The other option is EQ. Experiment with cutting low mids and adding high frequencies a bit for fingerpicking, vice versa for the pick.
Comment: In addition to playing closer to the bridge or neck, using the bridge pickup alone for finger picking, and blending pickups or using neck pickup for flat picking might also help.
Comment: @wabisabied I like the idea of using the pickups in different combinations, it's a good one.
Comment: Thanks, John. Easy enough to at least give it a try!

finger picking vs pick tone


Python code getting stuck while trying to handle an exception

Question: Code:
def ScanNetwork():
        nmScan = nmap.PortScanner()
        s = nmScan.scan("192.168.1.1/24", '0-4444', arguments="-O")

        for host in nmScan.all_hosts():
            if nmScan[host].state() == "up":
                print("Host : %s (%s)" % (host, nmScan[host].hostname()))
                try:
                    print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
                except:
                    print("An Error occured while scanning this host!\nNo extra info was collected!")
                    continue
                for proto in nmScan[host].all_protocols():
                    print("---------------------------")
                    print("\nProtocol : %s" % proto)
                    lport = nmScan[host][proto].keys()
                    lport = sorted(lport)
                    for port in lport:
                        print("\nport: " + f'{port}' + "\tstate: " + nmScan[host][proto][port]['state'])
                print("---------------------------\n")
        print("\n\nScan Completed!")
ScanNetwork()

Sometimes an exception occurs when the nmap fails to identify the Version or the Os running in a host. (It's a KeyError exception)
The part which is supposed to handle that exception is this:
try:
   print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\nType: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except:
    print("An Error occured while scanning this host!\nNo extra info was collected!")
    continue

I of course assume that there's nothing wrong with nmap's output and I've again made a huge beginner mistake and that's the reason my code is getting stuck..
Notes:

I've left the script running over night incase it returned some useful info but nothing happened!
Please do not tell me that I need to quit using the nmap module and turn to nmap3

Having tired you with all the above, does anyone know a way to still handle that exception without the code getting stuck?
Answer: You have forgotten to add the type of the exception to excpect while running the code inside the try-except block.
This should fix it:
try:
   print("Version: " + s['scan'][host]['osmatch'][0]['name'] + "\n" + "Type: " + s['scan'][host]['osmatch'][0]['osclass'][0]['type'])
except KeyError:
    print("An Error occured while scanning this host!\nNo extra info was collected!")
    continue

In case you want to catch any possible exception that could occur (and yes custom ones included) then you should use the following code:
try:
   <some critical code with possible exceptions to catch>
except Exception:
   print("An exception occured")

Comment: Oh my god I am a complete idiot.. I will accept the answer as soon as it lets me.. I even wrote that it was a 'KeyError' exception and somehow didn't think to check if I had added it after the except! Thank you very much for the quick answer sir!


Let $X$ a non-Hausdorff topological space and let $\sim$ denote an equivalence relation on $X$. Is it possible that $X/\sim$ be Hausdorff?

Question: Let $X$ a non-Hausdorff topological space and let $\sim$ denote an equivalence relation on $X$. Is it possible that $X/\sim$ be Hausdorff? Show an example.
I would like to know also if there is a sufficient condition for $X/\sim$ to be an non-Hausdorff space.
Comment: Take any non-Hausdorff space $X$ and let $x \sim y$ for all $x,y \in X$.
Comment: If $x\sim y\iff x=y$ then $X/\sim$ is homeomorphic to $X.$
Comment: Another example. Let $Y$ be Hausdorff and $q\in Y$ and $X=Y\cup \{p\}$ with  $p\not \in  Y. $ Let $S\subset X$ be open in $X$ iff $[\,( p,q\not \in S$ and $S$ is open in $Y) \lor ( p,q \in S$ and $S$ \ $\{p\}$ is open in $Y)\,].$ Let $u\sim v$ iff $(\,u=v \lor \{u,v\}=\{p,q\}\,).$ Then $X/\sim$ is homeomorphic to $Y.$ The idea is to add a point $p$ to $Y$ such that $p$ and $q$ have the same nbhds in $X, $ and such that $Y$ (with its given topology) is a subspace of $X.$
Answer: For your first question, yes, this is possible. Take, for example, the topological space
$$(X, \tau) = (\{1, 2, 3\}, \{\emptyset, \{1, 2\}, \{3\}, \{1, 2, 3\}\})$$
with equivalence relation
$$\sim \; = \{(1, 1), (2, 2), (3, 3), (1, 2), (2, 1) \}.$$
Then, if $\tau'$ is the quotient topology on $X / \sim$, then
$$(X / \sim, \tau') = (\{\{1, 2\}, \{3\}\}, \{\emptyset, \{\{1, 2\}\}, \{\{3\}\}, \{\{1, 2\}, \{3\}\}\}),$$
i.e. the discrete topology, which is definitely Hausdorff. However, $(X, \tau)$ is not Hausdorff, as $1$ and $2$ cannot be separated with open sets.
Comment: Thanks it already helped a lot! :D
Answer: Let $X=\mathbb{N} \cup \{p,q\}$ ($p,q$ distinct points not in the set $\mathbb{N}$) with the topology that $O$ is open iff $O \cap \{p,q\}=\emptyset$ or $\mathbb{N} \setminus O$ is finite. The points $p$ and $q$ cannot be separated by open sets so $X$ is not Hausdorff. $X$ is compact and $T_1$, though.
But the equivalence relation $\sim$ on $X$ that has one non-singleton class $\{p,q\}$ has the property that $X/{\sim}$ is homeomorphic to a convergent sequence and thus compact and Hausdorff (also metrisable).


By default which selector is set to Checkbox

Question: I want to modify the default selector to use same drawable for enabled and disabled checkboxes.
  For that i think i need to override selector for checkbox.
  I need to use same device specific drawables.(No custom drawables).
  Thanks.
Comment: If you want to device specific drawables then what is need of selector here?
Answer: Following is default selector for Checkbox
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:state_window_focused="false"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_off_selected" />

    <item android:state_checked="false"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_off" />
    <item android:state_checked="true"
          android:state_enabled="true"
          android:drawable="@drawable/btn_check_on" />

    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_check_on_disable" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_check_off_disable" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_check_on_disable_focused" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_check_off_disable_focused" />

    <item android:state_checked="false" android:drawable="@drawable/btn_check_off_disable" />
    <item android:state_checked="true" android:drawable="@drawable/btn_check_on_disable" />

</selector>

this is defined as btn_check.xml in to sdk -> platforms -> API_VERSION -> data -> res -> drawable


How restrictive is the markov assumption?

Question: Forgive me if this is a basic question.
The markov assumption is generally taken to be restrictive in the texts that I've read.
But intuitively it seems to me that we can turn any dynamic process into a markov process, simply by adding new variables at every time $t$ that record the "non-markov nature" of the relationships between time steps, so that we end up with a markov process in the end.
Is this right?
Answer: Let ${(X_n)}_{n \geq 0}$ be a stochastic process. It is not Markov in general. Define the random variables $Y_n = (X_0, X_1, \ldots, X_n)$. Then ${(Y_n)}_{n \geq 0}$ is a Markov process. Now, note that ${(X_n)}_{n \geq 0}$ and ${(Y_n)}_{n \geq 0}$ generate the same filtration. Thus, we can say that the filtration of any stochastic process is the filtration of a Markov process. I hope this illuminates your idea. I don't see what else can be said.
Comment: It is not clear to me how this explains whether having Markov property (the current state dending solely on the previous state) is a strong assumption or not.


Proving a set has measure zero

Question: Let $f\colon (0,1) \to \mathbb{R}$ be a measurable function. Suppose there exists a $C>0$ such that for all $0<a<b<1$, we have $\int_a^b f \geq C(b-a)$. I want to show that $f \neq 0$ almost everywhere on $(0,1).$
I think I have a proof of this, but it's rather long and complicated. I'm hoping there is a much simpler proof. Any help is appreciated!
Comment: Yeah you're right. I'll make an edit.
Comment: Did you mean $$ \begin{align} & \text{For all } 0<a<b<1,\, \left( \int_a^b f \ge C(b-a) \text{ for some } C \right) \\ \text{or} \\ & \left( \text{For all } 0<a<b<1,\, \int_a^b f \ge C(b-a) \right) \text{ for some } C \text{ ?} \end{align}$$ I suppose only the second one makes sense, but even so I'd rather see it made explicit, e.g. by putting "for some $C$" before "for all $0<a<b<1$".
Answer: This would be trivial if $f$ was assumed to be continuous but without continuity the best way to prove this is to use Lebesgue's Theorem. This theorem says $\frac 1 {b-a} \int_a^{b} f(x)\,dx \to f(a)$ as $b \to a$ almost everywhere so we get $f \geq C$ almost everywhere.
I have assumed integrability of $f$ but I will let you explain why there is no loss of generality in assuming this.
Comment: By "almost everywhere" do you mean "for almost all values of $a$?"
Comment: @MichaelHardy Yes, that is what 'almost everywhere' means.
Comment: "Almost everywhere" means for almost all values of some particular variable. Sometimes it's nice to see the variable identified explicitly.
Comment: Yeah this helps. Thanks!

Proving a set has measure zero