Working with Devise Login / Session Validation Error Messages in Rails 5.0

Question: This is my first stack overflow post so I apologize in advance if i ask the question poorly or leave anything out that could help answer the question. But please let me know if any other information would help and i'll respond right away!
Also, i'm working with a front-end css library called Semantic so i apologize for any clunkiness you might see in the erb files!
The issue: I am trying to validate the user login process and the errors are not showing for missing email and password fields. (app/views/devise/sessions/new.html.erb)

What's strange: I have studied many other stack overflow articles and other blogs and successfully displayed validation errors for the registration process (app/views/devise/registrations/new.html.erb)

What I've done:

require the validations in the User model:

`
class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :courses
  has_many :completions
  has_many :htmls, through: :completions

  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :email, presence: true
  validates :password, presence: true
  validates :country, presence: true
  validates :gender, presence: true
  validates :goal, presence: true, length: { in: 10..100 }
end

`

modified my config/locales/en.yml file to include the following:

'
en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            first_name:
              blank: "Your First Name is Required"
            last_name:
              blank: "Your Last Name is Required"
            email:
              blank: "Please enter an email address"
              taken: "That email is already taken"
              invalid: "Please enter a valid email address"
            password:
              blank: "Please Specify a Password"
              too_short: "Password must be at least %{count} characters long"
            country:
              blank: "Please Select Your Country of Residence"
            gender:
              blank: "Please Select Your Gender"
            goal:
              blank: "Please describe a goal you would like to achieve"
              too_long: "Your goal must be shorter than %{count} characters long"
              too_short: "Your goal must be longer than %{count} characters long"

'

write my app/views/devise/sessions/new.html.erb file

# log in

        <%= simple_form_for(resource, as: resource_name, url: session_path(resource_name), html: { class: "ui form" }) do |f| %>

              <%= f.input :email, autofocus: true %>

              <%= f.input :password %>

                <%= link_to 'register', new_user_registration_path, { class: "ui left floated huge register button" }%>
                <%= link_to "forgot password", new_password_path(resource_name), class: "ui left floated huge register button" %>

                <%= f.button :submit, "log in", class: "ui right floated huge login button" %>

         <% end %>

The view page above for devise/sessions/new does not display the messages i customized in config/locales/en.yml, but here is app/views/devise/registrations/new/html.erb that's pretty much identical to the previous snippet and displays the messages correctly.

# welcome to the community

      <%= simple_form_for( resource, as: resource_name, url: user_registration_path, html: { class: 'ui registration form' }) do |f| %>

            <%= f.input :first_name, autofocus: true %>

            <%= f.input :last_name %>

            <%= f.input :email%>

            <%= f.input :password%>

            <%= render "countries_dropdown" %>

<%= @user.errors[:country][0] %>

             <%= render "gender_dropdown" %>

<%= @user.errors[:gender][0] %>

          <%= f.input :goal, wrapper_html: { id: "goal_input" },
            label_html: { id: "varchar_count" },
            input_html: { id: "goal_input_field" } %>

          <%= f.button :submit, "register", class: "huge ui right floated register button" %>
          <%= link_to "log in", new_session_path(resource), { class: "ui huge login button" } %>

      <% end %>

I also created my own registrations controller that inherits from Devise::RegistrationsController:

'
class RegistrationsController < Devise::RegistrationsController
    #prepend_before_action :require_no_authentication, only: [:new, :create, :cancel]
  #prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy]
  #prepend_before_action :set_minimum_password_length, only: [:new, :edit]

  # GET /resource/sign_up
  def new
    build_resource({})
    yield resource if block_given?
    respond_with resource
  end

  # POST /resource
  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

  # GET /resource/edit
  def edit
    render :edit
  end

  # PUT /resource
  # We need to use a copy of the resource because we don't want to change
  # the current user in place.
  def update
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)

    resource_updated = update_resource(resource, account_update_params)
    yield resource if block_given?
    if resource_updated
      if is_flashing_format?
        flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
          :update_needs_confirmation : :updated
        set_flash_message :notice, flash_key
      end
      bypass_sign_in resource, scope: resource_name
      respond_with resource, location: after_update_path_for(resource)
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

  # DELETE /resource
  def destroy
    resource.destroy
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    set_flash_message! :notice, :destroyed
    yield resource if block_given?
    respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
  end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  def cancel
    expire_data_after_sign_in!
    redirect_to new_registration_path(resource_name)
  end

  protected

  def update_needs_confirmation?(resource, previous)
    resource.respond_to?(:pending_reconfirmation?) &&
      resource.pending_reconfirmation? &&
      previous != resource.unconfirmed_email
  end

  # By default we want to require a password checks on update.
  # You can overwrite this method in your own RegistrationsController.
  def update_resource(resource, params)
    resource.update_with_password(params)
  end

  # Build a devise resource passing in the session. Useful to move
  # temporary session data to the newly created user.
  def build_resource(hash=nil)
    self.resource = resource_class.new_with_session(hash || {}, session)
  end

  # Signs in a user on sign up. You can overwrite this method in your own
  # RegistrationsController.
  def sign_up(resource_name, resource)
    sign_in(resource_name, resource)
  end

  # The path used after sign up. You need to overwrite this method
  # in your own RegistrationsController.
  def after_sign_up_path_for(resource)
    after_sign_in_path_for(resource)
  end

  # The path used after sign up for inactive accounts. You need to overwrite
  # this method in your own RegistrationsController.
  def after_inactive_sign_up_path_for(resource)
    scope = Devise::Mapping.find_scope!(resource)
    router_name = Devise.mappings[scope].router_name
    context = router_name ? send(router_name) : self
    context.respond_to?(:root_path) ? context.root_path : "/"
  end

  # The default url to be used after updating a resource. You need to overwrite
  # this method in your own RegistrationsController.
  def after_update_path_for(resource)
    signed_in_root_path(resource)
  end

  # Authenticates the current scope and gets the current resource from the session.
  def authenticate_scope!
    send(:"authenticate_#{resource_name}!", force: true)
    self.resource = send(:"current_#{resource_name}")
  end

  def sign_up_params
    params.require(:user).permit(:first_name, :last_name, :email, :password, :country, :gender, :goal)
  end

  def account_update_params
    params.require(:user).permit(:first_name, :last_name, :email, :current_password, :password, :country, :gender, :goal)
  end

  def translation_scope
    'devise.registrations'
  end
  #def update_resource(resource, params)
    #resource.update_without_password(params)
  #end
end

'

As a result, i've changed the routes file to include:

'
Rails.application.routes.draw do
  devise_for :users, :controllers => { registrations: 'registrations' }

  devise_scope :user do
    authenticated :user do
        root 'users#index', as: :authenticated_root
    end
    unauthenticated do
        root 'devise/sessions#new', as: :unauthenticated_root
    end
end

'

And here is my rake routes:
My Rake Routes
And here is my app/views/layouts/application.html.erb upon request!

'
    1
    2
~   3     <title><%= content_for?(:title) ? yield(:title) : 'KodoTechnologies' %></title>
    4     <%= csrf_meta_tags %>
    5
    6     <%= stylesheet_link_tag "application", params[:controller], :media => "all" %>
    7     <%= javascript_include_tag "application", params[:controller] %>
    8
    9
   10
~  11
+  12     <% if current_user && current_user.admin? %>
+  13

+  14         <%= render "customs/admin_menubar" %>
+  15

+  16     <% end %>
+  17
+  18     <% if current_user && !current_user.admin? %>
+  19

+  20         <%= render "customs/student_menubar" %>
+  21

+  22     <% end %>
+  23
+  24

+  25       <%= content_for?(:content) ? yield(:content) : yield %>
+  26

+  27
   28
+  29
+  30   <%= content_for(:page_scripts) %>
+  31
   32

'

Summary:

As i mentioned before, the same error displaying method that works for the registration process does not work for the login process
I feel like my limit comes from my limited understanding of how the Devise SessionsController works under the hood. I've created my own RegistrationsController that inherits from Devise::RegistrationsController and had moderate success but I have no idea how to use the SessionsController and therefore couldnt debug or even implement my own validation process for sessions#create with flash error messages

Question:
Can anyone tell me what i might be doing wrong that's allowing validation messages being shown in the registration but not in the log in forms?
Let me know if i've left anything out, i'd love to provide everything you guys need. Thank you in advance!
Comment: Can you add your `app/views/layouts/application.html.erb` file too? The Devise help advises using that for flash messages - I'm wondering if there's an issue there.
Comment: Hello ArtOfCode! i just went and added it as the 8th item on the list. I'm not sure how helpful it would be because it yields to other layouts (nested layouts) and there's a whole bunch of partials and yielding from there as well.

The thing is, i would totally use flash messages if i knew where the validations were actually taking place :(

I dont think i understand the Devise SessionsController enough to know where i need to write the appropriate code for the custom validations and flash messages to be stored :o Thank you for your interest!
Answer: The Devise help recommends that you include flash messages in your application layout file. Yours doesn't appear to have these; try including them. This will enable flash messages across the application, regardless of what route is being hit.
For a basic Rails project, you might use something like this:
<% if flash[:notice].present? %>

<%= flash[:notice] %>

<% end %>

<% if flash[:alert].present? %>

<%= flash[:alert] %>

<% end %>

If you're using Bootstrap with Glyphicons, I find the following template works quite well:
<% if flash[:notice].present? %>

    <%= flash[:notice] %>

<% end %>

<% if flash[:alert].present? %>

    <%= flash[:alert] %>

<% end %>

Comment: Hello ArtOfCode, OP here, thank you for your feedback!
Comment: I had some other questions that popped up but i think your answer was a great place for me to start and i figured most of them out, thank you very much!
Comment: It would be great if you or anyone else who might read this thread could elaborate on how i might be able to customize these messages, or ultimately, how to get access to the part of the code where the username/password comparisons are being made within devise so i can create custom flash session variables containing very specific flash messages. I think this could be helpful for unique inline validation error message displaying and a couple other situations. If anyone can help me understand the highlighted process above, i'd love to accept that as the answer, thanks again ArtOfCode!


What is the Probability of a Very Large Digit Constant Number to be Exactly Divided by 19?

Question: Let's just put the 40s and 8s side by side randomly to create a 4002 digit number. We have a chance to do this once. Is it possible to talk about the probability of dividing the created constant by 19 exactly? A number is either a multiple of 19 or it isn't. So I thought the answer to this question was 1/2. But such a large number probably won't be divisible by 19. Would it be more accurate to say that the probability of such a situation cannot be defined?
Comment: We create a 4002 digit number in the form of 4084084040404040408884040... This is a random operation and we only have one chance to generate a number.
Comment: What does it mean "Let's just put the $40$s and $8$s side by side randomly"? Are you talking about creating a number made only by $40$ and $8$? Like $40408$ or $884084040$ but of $4002$ digits?
Answer: You can define a sample space of all the $4002$ digit numbers that can be made by putting substrings of $40$ and $8$ together.  It is a finite collection.  You can then compute how many of them are divisible by $19$.  If you sample your space randomly the chance that the number you get is divisible by $19$ is just the second divided by the first.  I would guess it is not far from $1/19$


Series for $\text{Arg}( \zeta (z))$

Question: Though I don't know if the formula I've found is useful, I decided to publish it anyway.
$$
\text{Arg}( \zeta (z))
=
-\sum_ {k = 1}^{\infty}\sum _ {q = 1}^{\infty}\frac {1} {k P_q^{k x}}\text {Sin}( k y \text{ Log}(P_q ) ) \text{ , } |z|>1
$$
where $z=x+i y$ and $p_q$ is th $q^{th}$ prime number.
Here is an example with a plot of $\text{Arg}( \zeta (1+i y))$ in blue, and a plot of the sum in red:

My question is whether the formula is known, whether someone finds it helpful.
EDIT: this post was put 'on hold'. I don't know why. I'm a graphist and foreigner to the mathematics' community, thus it's very hard for me to check the results I got, and this is the reason of this post.
EDIT 2: If someone's interested, this other post shows at the end how the series was calculated simple tools to extract Re, Im, Abs... of any complex function
Comment: What is $P_q $?
Comment: I don't know what is Pq but this is superb, even better than the previous you posted ! How many terms did you sum for the red line ?
Comment: I am surprised that the sum is over the primes and not the von Mangoldt function. Wonderful result of yours.
Comment: @claude, only ten terms..
Comment: @mats, I will post
Comment: crosspost http://mathoverflow.net/questions/150563/serie-for-argzetaz
Comment: @mats, the way i calculated this serie is in this post: [simple tools...](http://math.stackexchange.com/questions/593830/simple-tools-to-extract-re-im-abs-of-any-complex-function)
Answer: I have never seen anything like this before. Here is some code for the plot, apparently with a different scale factor:
<code>(*Mathematica*)
Clear[a, k, q, y, x]
x = 1;
Monitor[a =
   N[Table[-Sum[
       Sum[1/(k*Prime[q]^(k*x))*Sin[k*y*Log[Prime[q]]], {q, 1,
         50}], {k, 1, 100}], {y, 1, 50, 1/4}]];, Floor[N[y]]]
g1 = ListLinePlot[a, DataRange -> {1, 50}, PlotStyle -> Red]
g2 = Plot[Arg[Zeta[1 + I*y]], {y, 1, 50}]
Show[g1, g2]
</code>

Series for $\text{Arg}( \zeta (z))$


Laravel - Ajax and preventdefault

Question: I have a problem with getting items in cart, after I add an item into the cart, Ajax works perfect, then when i try to remove it from the list, first time it wont work with Ajax, if I reload the page it will work.
Ajax generate response like this:
1x ItemTitle     X (remove)
When remove has /delete-from-cart/id/place_id
It only works when I reload the page, and also I have a button for coupons that is also managed to work with Ajax, but it only works after refresh.
$('.deletefromcart a').each(function(){
    $('#'+this.id).on('click',function(e) {
      e.preventDefault();
      var id = $(this).attr('data-del');
      var url = $(this).attr('href');
      var place = $(this).attr('data-place');
       $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $.ajax({
         url: '/delete-from-cart/'+id+'/'+place+'',
         method: 'get',
         data: $(this).serialize(),
         success: function(data){
           toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
             $(".korpa").load(location.href + " #cartAll");
         },
         error: function(data){
           console.log(data);
         }

         });
     });
});

It seems like this function cant find any object to run it from ajax after I add to cart, after refresh it finds.
If you need live preview, i can make you an account.
Comment: what does `$('#' + this.id)` refere to ?
Comment: This is the element:

`x`
Comment: `$(this)` will refer to element itself
Comment: no need for each, because it's going to be triggered one at a time so if you write the click function without the each and try it might work
Comment: shouldn't the method be `post`?
Comment: Yes it is POST, just i was editing and trying and left it GET..
Answer: You should bind the click event handler on each 'delete' element as,
$('body').on('click', '.deletefromcart a', function (e) {
    e.preventDefault();
    var id = $(this).attr('data-del');
    var url = $(this).attr('href');
    var place = $(this).attr('data-place');

    $.ajax({
        url: '/delete-from-cart/' + id + '/' + place + '',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        method: 'get',
        data: $(this).serialize(),
        success: function (data) {
            toastr.warning('Uspešno ste obrisali iz korpe!', 'Korpa');
            $(".korpa").load(location.href + " #cartAll");
        },
        error: function (data) {
            console.log(data);
        }
    });
});

Note 1: Your method of binding will attach the event handler to all .deletefromcart a elements. But the one I suggested will bind the event handler to only one element, body. This will also work on dynamically added .deletefromcart a elements.
Note 2: You can include the header values as above too.
Comment: Your methods works like a charm, but there is a delay, it tooks maybe 4-5 seconds to actually delete it from the cart.

But i will keep it this way, and many thanks for this explanation. God bless you !

Laravel - Ajax and preventdefault


ActiveViewModels in Catel

Question: currently I have a solution with multiple ViewModels - "normal" and "nested" ones.
Every time I create a new ViewModel instance, I can see the new instance in the ViewModelManager.ActiveViewModels. So far so good.
Unfortunately I also can see "old" ViewModel instances there, in fact, instances that are not in use but still remain in this "Cache".
My first question is now, what do I have to do for disposing this "old" ViewModels?
And an additional question (follow-up)...: which is the recommended usage of ViewModel instantiation to avoid this behavior?
Thanks in advance
Answer: Okay, seems like I found it.
Short description:
Since I cant use the Catel "DataWindow" because we use DevExpress WPF (DXWindow), the ViewModel seems not to be closed automatically on unloading the View.
I fixed the issue by closing the ViewModel myself when the View is unloaded. Snipped:
<code>private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs)
{
  var dc = DataContext as IViewModel;
  if (dc != null && !dc.IsClosed)
    dc.CloseViewModel(null);
}
</code>
Answer: Catel will automatically close (and remove) the viewmodels as soon as the view models are really out of scope. I recommend that you use the latest prerelease (v.4.0.0) because that is very stable and should solve several issues currently in 3.9.

ActiveViewModels in Catel


What does 7P mean?

Question: I'm trying to learn the song Ladye Nothynges Toye Puffe by John Renbourn and noticed the following symbol in the book (7P followed by a line).
I have tried googling but didn't find anything. Thank you very much for any help!
Answer: I believe this means to play in 7th position: so that the first (index) finger plays on the 7th fret during the part below the horizontal line. In particular the last two notes should be played with barré on the 7th fret.
This is a fingering suggestion, you may follow it or not, depending on what feels better to you.
Comment: I suggest this is close to the mark but not quite spot on. I think it means play in the seventh position, not necessarily with a barre (but in this case a barre makes sense for the last two notes). If I'm correct, this notation has fallen out of favor and the current practice for indicating position on the guitar is with capital Roman numerals. I suspect the "p" stands for "position".
Comment: What does the P mean? Does it stand for something?
Comment: @ToddWilcox right this makes sense, thanks! Going to update the answer.

What does 7P mean?


Execute .jar from windows form C#

Question: I have .jar to execute from windows from, so far I was able to lunch the program from my window form, but when I put information in my java file I get no result the java file does nothing.
If I go manualy double click and execute the .jar file and put the information I get the resul.
here is my code to execute java inside windows form :
 Process p = Process.Start(@"C:\convert\Convert.jar");
            Thread.Sleep(500);
            p.WaitForInputIdle();
            SetParent(p.MainWindowHandle, this.Handle);

.jar file is for to convert .csv to .txt with special data.
Comment: `java -jar C:\convert\Convert.jar`
Comment: @nater303 Have you tried setting working directory to C:\convert? http://stackoverflow.com/questions/114928/net-process-start-default-directory
Comment: Thanks Liberty but it is not working I have tried this before.
Comment: @nater303 what exactly happens when you run LibertyLocked's suggestion? It's definitely more correct than the original attempt. For testing purposes: try running ``java -version``.
Comment: I can execute the .jar file but no result for my conversion.
Comment: And for java version :

java version "1.8.0_73"
Java(TM) SE Runtime Environment (build 1.8.0_73-b02)
Java HotSpot(TM) Client VM (build 25.73-b02, mixed mode, sharing)

NOTE: csv.csv it is in the same folder as Convert.jar
Comment: BINGO!
It woks, I had to set up the working directory because the .jar looks for files in the same folder where it is.
Thanks Liberty Locked for the link.
Answer: To run a jar, you need to use
java -jar <FILENAME.jar>

In your case it would be
Process p = Process.Start(@"java -jar C:\convert\Convert.jar");
        Thread.Sleep(500);
        p.WaitForInputIdle();
        SetParent(p.MainWindowHandle, this.Handle);

Answer: Here is the solution :
System.Diagnostics; ... ProcessStartInfo _processStartInfo = new ProcessStartInfo();
_processStartInfo.WorkingDirectory = @"%ProgramFiles%";
_processStartInfo.FileName = @"Notepad.exe";
_processStartInfo.Arguments = "test.txt";
_processStartInfo.CreateNoWindow = true;
Process myProcess = Process.Start(_processStartInfo);

Execute .jar from windows form C#


Find the joint pdf of X and Y for two uniform distributions

Question: Let X have a uniform distribution on the interval $(0,1)$. Given that X = x, let Y have a uniform distribution on the interval $(0,x+1)$.
Find the joint pdf of X and Y. Sketch the region where $f(x,y) > 0$.
Find fY$(y)$, the marginal pdf of Y. Be sure to include the domain.
I'm not really sure where to start. Is fY$(y)$ just $\frac{1}{(x+1)-0}$ since that's the pdf of a uniform distribution? And I have no idea how to find the joint pdf of X and Y.
Answer: The conditional density of $Y$ given $X=x$ is $f_{Y|X}(y|x)=\frac{1}{x+1}1_{0<y<x+1}$, hence the joint density of $X$ and $Y$ is
$$ f(x,y)=f_{Y|X}(y|x)f_X(x)=\frac{1}{x+1}1_{0<x<1,0<y<x+1}$$
The marginal density can then be obtained by "integrating out" the $x$-variable:
$$ f_Y(y)=\int f(x,y)\;dx$$
Comment: Sorry, what do you mean by *fY|X(y|x)*=1/x+1 1 0?
Comment: This is the conditional density of $Y$ given $X=x$. See here for more info: https://en.wikipedia.org/wiki/Conditional_probability_distribution
Comment: I think I get that, but why is there a 1 between 1/x+1 and the bounds?
Comment: That is a shorthand notation for 1 if $0<y<x+1$, and 0 otherwise.
Comment: I'm a bit confused on the bounds to use on the integral to calculate the marginal density of y. I believe $y$ should be the lower bound, but what is the upper bound? It can't be $x+1$, right?
Comment: The lower bound is $0$ if $0<y<1$ and is $y-1$ if $1\leq y<2$. The upper bound is $1$.
Comment: Sorry, could you explain that to me? I just don't know how to get that if the bounds on $f(x,y)$ for $y$ are $0<y<x+1$
Comment: We know that $0y-1$. If $y<1$ then $y-1<0$, so use the lower bound $0$. Otherwise the lower bound for the integral is $y-1$.


Executando uma função em python tem como output "none"

Question: Eu estou com um problema, eu tenho o seguinte código em Python.
def teste(n):
    n = int(n)
    if (n > 0) and (n < 200000):
        for i in range (1, n+1):
            if ((i % 3 == 0) and (i % 5 == 0)):
                print('FizzBuzz')
            elif ((i % 3 == 0) and (i % 5 != 0)):
                print('Fizz')
            elif ((i % 5 == 0) and (i % 3 != 0)):
                print('Buzz')
            elif ((i % 3 != 0) and (i % 5 != 0)):
                print(i)
    else:
        print('São aceitos apenas números entre 1 e 200000')

usuario = int(input('Olá, por favor digite o número: '))
resultado = teste(usuario)
print(resultado)

E quando o input é 5 por exemplo, o output é:
1   2   Fizz   4   Buzz  None

Minha pergunta é: por que esse None está aparecendo? E como corrigir isso?
Comment: Você mandou imprimir o que a função retorna. E como ela retorna `None`, é isso que foi impresso. Imprimir não é o mesmo que retornar.
Comment: A função não tem nenhum `return`, ou seja, ela não retorna nenhum valor. E quando a função não retorna nada, o Python assume que este retorno é `None`. Como ela não retorna nada, não faz sentido pegar o resultado dela e imprimir, então basta retirar o último `print` e só chamar a função. Ou seja, faça apenas `teste(usuario)`
Comment: Ué, já foi explicado. Quando uma função não tem nenhum `return`, o Python faz com que o retorno dela seja `None`. No seu caso, a variável `resultado` recebe esse `None` que a função retorna, e o `print` mostra o valor dela, que é `None`. E como já dito, não faz sentido imprimir esse `resultado` se a função não retorna nada
Comment: Eu consegui corrigir, mas ainda não entendi porque quando eu uso o print tem como output none. Poderia me explicar melhor?
Answer: Aprece none pq o programa ta imprimindo as coisas de dentro da função e ao final do laço ele não tem nada para imprimir, por isso ele imprimi "nada", ou seja, none. Para resolver o problema eu sugiro fazer o seguinte.
Crie uma lista dentro da sua função e peça para adicionar os valores dentro da lista. ao final do laçor for peça para a função retornar a lista. Dessa forma o que será mostrado será a lista com todos os valores dentro.
def teste(num):
  n = num
  lista = []
  if (n > 0) and (n < 200000):
    for i in range(1, n+1):
      if ((i % 3 == 0) and (i % 5 == 0)):
        lista.append('FizzBuzz')
      elif ((i % 3 == 0) and (i % 5 != 0)):
        lista.append('Fizz')
      elif ((i % 5 == 0) and (i % 3 != 0)):
        lista.append('Buzz')
      elif ((i % 3 != 0) and (i % 5 != 0)):
        lista.append(i)
    return lista
  else:
    return 'São aceitos apenas números entre 1 e 200000'

usuario = int(input('Olá, por favor digite o número: '))
resultado = teste(usuario)
print(resultado)


Write a C program to find whether the given string is Lucky or not

Question: A string is said to be lucky if the sum of the ASCII values of the characters in the string is even. The function accepts a pointer to a string and returns an int.
The return value is 1 if the string is lucky and 0 otherwise.
I have tried with the following code, but on execution I am getting some errors.
#include<stdio.h>
#include<string.h>
int checklucky(char *a);
int main()
{
    int c;
    c=checklucky(char *a);

    if(c==1)
        printf("%s is lucky",a);
    else
        printf("%s is not lucky",a);

    return 0;
}

int checklucky(char *a)
{
    char name[100];
    int sum=0,len,i;
    a=name;

    printf("Enter the input string\n");
    scanf("%s",name);

    len=strlen(name);

    for(i=0;i<len;i++)
    {
        sum=sum+name[i];
    }

    if(sum%2==0)
        return (1);
    else
        return (0);
}

Sample Input and Output 1:
Enter the input string
anitha
anitha is not lucky

Comment: `but on execution i am getting some errors`.  What errors?  Did you step through with a debugger?
Comment: Your question was downvoted because you did not provide sufficient detail as to what the exact problem is (e.g. what errors you were getting).  Even though your question is already answered, you can edit it to improve the quality.  Some people that previously downvoted may undo the downvote, or you may even attract upvotes.  Leave a comment here if you edit your question so that others are notified.  See http://stackoverflow.com/help/how-to-ask
Comment: Declare `name` in `main` and pass it to the function.
Answer: This line is incorrect and should not compile
c=checklucky(char *a);

You declared checklucky to accept a pointer to the input string, but you are actually gathering that input string within checklucky.  Move that part into main, then pass in the string.
int main()
{
    int c;
    char name[100];
    scanf("%s",name);

    c=checklucky(name);

then
int checklucky(char *a)
{
    int sum=0,len,i;

    len=strlen(a);
    // etc.  Refer to a rather than name,
    // or change the method parameter's name to name.

Answer: Eric J. has already told what is your mistake.
You can take the input string in main() and pass the pointer to it to the called function. There are many ways you can modify your code to get it working.
Below is one way (it tries to keep code similar to the original code)
 #include<stdio.h>
 #include<string.h>
 int checklucky( char *);
 int main()
 {
    int c;
    char a[100];
    printf("Input string: ");
    scanf("%s",a);

    c=checklucky(a);

    if(c==1)
        printf("%s is lucky\n",a);
    else
        printf("%s is not lucky\n",a);

    return 0;
}

int checklucky(char *a)
{
    char *name;
    int sum=0,len,i;
    name=a;

    // printf("Enter the input string\n");
    // scanf("%s",name);

    len=strlen(name);

    for(i=0;i<len;i++)
   {
       sum=sum+name[i];
   }

   if(sum%2==0)
       return (1);
  else
       return (0);
}

Answer: #include<stdio.h>
#include<string.h>
int checkLucky(char *a);
int main()
{
char b[100];
int d;
printf("Enter the input string\n");
gets(b);
d=checkLucky(b);
if(d==1)
{
printf("%s is lucky\n",b);
}
else
printf("%s is not lucky\n",b);
return(0);
}
int checkLucky(char *a)
{
int sum=0;
while(*a!='\0')
{
sum+=*a;
a++;
}
if(sum%2==0)
{
return(1);
}
else
return(0);
}

Comment: Computation time is less and the memory space consumed is also low as relatively lesser number of variables are used.


How to prove that $ ¬∀x∈A, ¬P(x) \equiv \exists x\in A, P(x) $ using quantifier negation

Question: I'm not needing assistance proving this statement.
$ ¬∀x∈A, ¬P(x) \equiv \exists x\in A, P(x) $
My first approach was to use demorgans laws but I'm having trouble with determining what to do next.
$ ¬∀x(x \in A, ¬P(x)) \equiv ¬\forall x(x \in A \wedge ¬P(x)) $
Comment: $\forall x \in A, \lnot P(x)$ means $\forall x (x \in A \rightarrow \lnot P(x))$, not $\forall x (x \in A \land \lnot P(x))$.
Comment: Alright, How exactly do I show their equal though?
Comment: Just try for yourself first, but now with the correct statement.
Answer: Quantifier negation is typically stated as:
Quantifier Negation
For any formula $\varphi(x)$:
$\neg \forall x \ \varphi(x) \Leftrightarrow \exists x \ \neg \varphi(x)$
$\neg \exists x \ \varphi(x) \Leftrightarrow \forall x \ \neg \varphi(x)$
But in the case of qualified quantifiers, it would be:
Qualified Quantifier Negation
For any formula $\varphi(x)$ and set $S$:
$\neg \forall x \in S \  \varphi(x) \Leftrightarrow \exists x \in S \ \neg \varphi(x)$
$\neg \exists x \in S \ \varphi(x) \Leftrightarrow \forall x \in S \ \neg \varphi(x)$
If you were given the latter, then what you need to show is trivial:
$\neg \forall x \in A \ \neg P(x) \Leftrightarrow \text{ (Qualified Quantifier Negation)}$
$\exists x \in A \ \neg \neg P(x) \Leftrightarrow \text{ (Double Negation)}$
$\exists x \in A \ P(x)$
So, assuming you were not given the Qualified Quantifier Negation principle, but only the 'normal' one, you will indeed have to rewrite the qualified quantifier as an unqualified quantifier, but as indicated by @Magdiragdag, you didn't do this right.
In general, you have that:
Rewriting Qualified Quantifiers as Unqualified Quantifiers
For any formula $\varphi(x)$ and set $S$:
$\forall x \in S \ \varphi(x) \Leftrightarrow \forall x (x \in S \rightarrow \varphi(x))$
$\exists x \in S \ \varphi(x) \Leftrightarrow \exists x (x \in S \land \varphi(x))$
Applied to your problem, we thus get:
$\neg \forall x \in A \ \neg P(x) \Leftrightarrow \text{ (Rewrite Qualified Quantifier)}$
$\neg \forall x (x \in A \rightarrow \neg P(x) \Leftrightarrow \text{ (Quantifier Negation)}$
$\exists x \neg (x \in A \rightarrow \neg P(x)) \Leftrightarrow \text{ (Implication)}$
$\exists x \neg (\neg x \in A \lor \neg P(x)) \Leftrightarrow \text{ (De Morgan)}$
$\exists x (\neg \neg x \in A \land \neg \neg P(x)) \Leftrightarrow \text{ (Double Negation)}$
$\exists x (x \in A \land P(x)) \Leftrightarrow \text{ (Rewrite Qualified Quantifier)}$
$\exists x \in A \ P(x)$


Finding c for a joint pdf

Question: I'm given the following joint pdf:
$$
f(A,B)=
\begin{cases}
c(a^2+b) & \text{ for } 0 \leq b \leq 1-a^2\\
0 & \text{ else}
\end{cases}
$$
I'm supposed to find c but I'm not sure how to find the limits of integration. I thought that they were 0 and 1 for db and -1 and 1 for da, giving me 5/3 when I integrate, but that isn't correct. Could anyone help me understand what's going wrong?
Overall, I just having difficulty understand the limits of integration when the other variable is in the equation, for example Pr(B>X+1) or Pr(B=X^1/2).
Answer: If $|a| > 1$, then $1-a^2 < 0$, and so, there are no values of $b$ such that $0 \le b \le 1-a^2$.
If $|a| \le 1$, then $1-a^2 \ge 0$, and so, there are values of $b$ such that $0 \le b \le 1-a^2$.
Hence, the bounds are $-1 \le a \le 1$ and $0 \le b \le 1-a^2$.
Notice that the upper bound for $b$ isn't simply $1$, it actually depends on $a$. This is because the region you are integrating over isn't a simple rectangle, but rather a curved region.
So, you need to find the value of $c$ such that $\displaystyle\int_{-1}^{1}\int_{0}^{1-a^2}c(a^2+b)\,db\,da = 1$.
Comment: The bounds still happen to be a bit unclear for me. So, what if b<=a+.5 instead, how would the bounds change?

Finding c for a joint pdf


script used to extract data from pipe-delimited CSV file fails

Question: I created a shell script that takes a CSV file and uses a regex to match data and outputs that data to another CSV file. However, when I run the script I get an error saying:

file_processor.ps1
$input_path = 'c:\shell_scripting\input.csv'
$output_file = 'c:\shell_scripting\output.csv'
$regex = '^(?:[^|]*\|){2}([^|]*)'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

input.csv:
1|2|3|4|5|6||8|9|10

I have checked the regex and it works:
http://www.regexr.com/3bj9p
Comment: The error line in the message doesn't match the posted script.
Comment: Sorry I don't understand what you mean?
Comment: @mjolinor means that the regular expression in the error is not the same as the one in your script.
Comment: Why are you parsing the file manually? `Convertfrom-CSV`, `Import-CSV` & `Export-CSV` all accept the `Delimiter` parameter which will let you specify the `|` character instead of the default comma.
Answer: The error suggests an encoding issue. Most likely you have typographic quotes in your script (please avoid those) and saved it UTF-8 encoded without BOM. Because of that the opening typographic quote (which consist of 3 bytes in UTF-8) is read as 3 characters (â€~). Without the quotes PowerShell doesn't recognize the string as a string and throws a syntax error.
Comment: that's exactly what it was :)


Question on determining the validity of statements using the continuity of function

Question: I need to determine if the following statements are true or false:

If $f$ is a continuous function on the interval $[5,10)$ and $(x_n)$ is a convergent sequence in $[5,10)$ such that $\lim f(x_n) =
 10^6$ then $\lim x_n$ can be determined.
If $f$ is a continuous function on the interval $[5,10)$ and $(x_n)$ is a convergent sequence in $[5,10)$ such that $\lim f(x_n) =
 \infty$ then $\lim x_n$ can be determined.

Here are my arguments and questions:
If $x_n$ is convergent, then $\lim x_n \in [5,10]$ (the problem here is continuity at $x=10$). Is the author asking of the existence of limit of $(x_n)$ or if it can be uniquely determined? Because if $(x_n)$ is the sequence given by $x_n = 6-\frac{1}{n}$ and $f(x)= \frac{10^6}{6} x$ then $\lim f(x_n)= 10^6$. I could do the same for $x=7$ as well.
For the second question if $(x_n)$ converges to some point $c\in [5,10)$ then by the continuity of $f$, we must have $\lim f(x_n) = f(c) = \infty$. Thus, f is not continuous on $[5,10)$ and thus $\lim x_n$ cannot be determined. I'm not sure what to conclude when $c=10$.
I need some hints on this.
Answer: For the first part, you have exhibited two possible continuous functions of the form of
$$f_t(x) = \frac{10^6}{t}\cdot x$$ where $t \in \{ 6,7\}$ and a convergence sequence $x_{n,t}=t-\frac1n$ that shows that we can't determine the limit uniquely.
For the second part, note that for any $t \in [5, 10)$, $f(t) $ is finite. If $x_n$ converges to $t$, that is if $\lim_n x_n = t$, then we have $$\lim_{n \to \infty}f(x_n)= f(\lim_{n \to \infty} x_n ) = f(t)< \infty.$$
Hence, $\lim_{n \to \infty}x_n$ cannot be in $[5,10)$. It must converges to a limit point, the only limit point that is not in $[5,10)$ is $10$. Hence $\lim_{n \to \infty}x_n = 10$.
Comment: It seems I was almost correct.


Using MIDI with Serial Midi Converter using usb to ttl converter

Question: in market we have available usb to ttl converter. So can i use them to send midi signals to usb using
This circuit
https://irq5.files.wordpress.com/2011/03/midi-sch.png?w=640
connected to the pins of usb to ttl converter module
then using software "MIDI Yoke" and "serial to midi converter"
Please tell me if its possible because most of them do it by using the same pins on arduino uno r3
Answer: That circuit is horribly wrong:

The connections to pins 4 and 5 of the MIDI connector are exchanged (and that connector is labelled wrong).
RB must be 220 Ω.
The CNY17 optocoupler is often too slow; use a H11L1, or better a 6N137.
RD is too large unless you're using a really fast optocoupler.

But when you're using a correct circuit (see, for example, MIDI IN : many circuits or MIDI to Arduino with a 4N38 Optocoupler), this will work.
It might be a better idea to just buy a cheap USB/MIDI interface cable.


Interpreting results of K-means after PCA

Question: I have this dataset about an airline company customers with 22 explanatory variables. My goal is to perform some sort of customer segmentation with the k-means algorithm. One problem that I've found is that when applied on the whole dataset, I find it difficult to identify well-separated and balanced group. For this reason, finding some sources online to support this practice, I tried to first apply PCA on the dataset and then the k-means obtaining some good results in terms of clusters.
My question now is, would it be wrong to use this clusters that I found, to compare the differences in the original 22 variables between groups?
For example I have column 'satisfaction', which identify whether or not a customer is satisfied, and I've noticed that the percentage of satisfied customer in each group is very different. Can I try to analyze other variables, like age in each group, to try to explain this difference? Or would it be wrong since the clusters were created using transformed variables and not the original ones?
Comment: If all 22 variables are informative, I'd cluster all 22 variables. PCA reduces information, and there is no guarantee whatsoever that the information you lose is not valuable for clustering. How exactly did you arrive at the impression that the clusters with all 22 variables are no good and those based on PCA are better? Why do you need groups to be balanced and well separated? (Lack of separation on all relevant information is better than separation on information that is not so relevant.)
Comment: @ChristianHennig : There is an argument that says that in higher dimensions, everything is far from everything and thus KMeans will struggle...although 22 isn't very high so it's probably not an issue here

As regards the original question, I think it's totally legit to perform PCA first, then do KMeans, and then run some sort of explainability/interpretability algorithm which uses the labels as gathered by KMeans and the original 22 features to try to explain/gain intuition for the clusters

I don't necessarily recommend this approach for optimal clustering, but it's legitimate.
Comment: @gazza89 I don't know what "legit" is supposed to mean, I mean, true, you won't go to jail for it. However in an applied situation like this I'd try to find proper reasons why to do something and not something else. I suspect that the information reduction by PCA is not going to help the clustering, and I also think that "clusters look better separated" isn't a very good argument to use it. It is however all dependent on the situation and aim of clustering, so there may be situations where there are good reasons to do this. I'm not claiming it's outright wrong.
Answer: In brief, the protocol you are suggesting (PCA followed by k-means) is a manual application of a type of latent class analysis (LCA, also called latent cluster analysis).  Your idea of reducing the number of dimensions prior to forming (unsupervised) clusters is not unreasonable.  That said, there are far more advanced techniques available to do the process directly using latent variables.  (Happy to share more on this as needed.)
Furthermore, the use of the manifest variables (the observed variables you have as opposed to the latent variables imposed by a model or the cluster assignments) to elucidate the meaning/interpretation of the clusters is very common.  In fact, one might argue that this is essential.  The key is that this descriptive analysis of the clusters is not a statistical technique...it is a theoretical technique, and it must draw on the discipline knowledge in which the research question (and resulting data) are situated.
Answer: The whole idea of dimensionality reduction, then followed by a clustering algorithm (sometimes referred to as "tandem analysis" in the literature) is something that is commonly done but of course, the clustering problem is more generally seen as a question of whether there is an inherent structure in your data. If K-Means is actually producing some hardly interpretable results, this could be for several reasons; perhaps you might have got outliers in your data set? Especially K-Means is not the most robust clustering algorithm when it comes to outliers (K-Medians is a much better choice and there exist some more involved algorithms out there as well that you could go for). Also PCA is not fully robust to outliers, so I would be quite cautious about this.
Sticking to your original question, the clusters might be "nicely separated" (since that is what K-Means seeks to find) but this is true for the observations once these are projected in PCA space. Moreover, have you used a certain method for obtaining the number of clusters or is this something you know in advance? This can also affect things, since different intrinsic measures of cluster quality (e.g. the average silhouette width) seek to find the number of clusters which yields clusters that are as dense and well-separated as possible, but even then you would need to apply this in the transformed feature space. Of course, as long as you can get some nice interpretable results out of your clustering output, that's all you really need so you may ignore some of these if you feel like it.


How to use .startsWith with SASS

Question: I have a SASS condition like this it works as I expected but as you can see It is too long and I want to refactor it. How can I use something like JavaScript's startsWith() or includes() prototype?
<code>@if $styleName == margin or $styleName == margin-top or $styleName == margin-right or $styleName == margin-bottom or $styleName == margin-left {
//..something happens there
}
</code>
I'm looking for a solution like:
<code>@if $styleName.startsWith('margin'){
//..something happens there
}
</code>
Answer: <code>@if str-index($styleName, "margin") {}
</code>

How to use .startsWith with SASS


wpf CheckBox command parameter

Question: In my View I have 8 checkboxes all bound to a different property in the Model, lets say bool port1 ... port8. The property changes when the concerned checkbox is clicked.
When the user checks or unchecks one of these checkboxes, I also execute a binded command 'SetPortCommand'. The command executes a function like SetPort(uint numPort, bool set)
My view looks like this:
<CheckBox x:Name="cbPort1" Content="port1" Command="{Binding SetPortCommand}">
    <CheckBox.IsChecked>
        <Binding Path="MyModel.Port1"/>
    </CheckBox.IsChecked>
</CheckBox>

Behind the whole thing is quite slow hardware, so I would like to avoid calling the function SetPort() for each port. I could use 8 commands like SetPortCommand1 to SetPortCommand8, but that causes lots of duplicate code.
I had the following ideas, but I do not know how to implement it, neither which one wouldf be conform to MVVM.

idea would be to somehow pass a constant to the command, telling it which of the 8 ports it should check or uncheck. Is there a easy way to do this?
idea would be to somehow use the OnPropertyChanged()-Event to call the function in here.

Any help appreciated :-)
Comment: Can you please show your code (the VM - viewmodel), that will help. Also why not just do the binding for `IsChecked` just like you did for `Command`. It could be `IsChecked = "{Binding PropName}"`... If you want to pass a parameter, look at the `CommandParameter` property, [*here*](https://stackoverflow.com/a/20275938/1797425) is an example.
Answer: With a checkbox, the usual approach is to bind ischecked and to act in that setter. This uses text rather than a bool, but you can see there's a method called in the setter. https://social.technet.microsoft.com/wiki/contents/articles/30564.wpf-uneventful-mvvm.aspx#Change_of_Variable
You have a repeating group of functionality in this set of check boxes.
The usual approach is to bind a list or observablecollection of viewmodels to the itemssource of an itemscontrol. Template that data out into your ui. Here you'd have checkboxes. Each of your row viewmodels would hold data about a port. Name and whatnot.
If you particularly want a command you could have an ICommand such as delegatecommand or relaycommand bound from either:
The row viewmodel - in which case that "knows" which port is to be acted on. And your code that does stuff with that port is in the row viewmodel.
or
To the window viewmodel, in which case the row viewmodel is the datacontext of the button and this is passed as a parameter to the ICommand.
Both these are common scenarios working with buttons and you should be able to find code googling.
Binding IsChecked would be simpler and is hence more usual though.
Comment: Thanks for your answer. I did the function call in the isChecked-event in the MyView.xaml.cs before, which worked fine, but I wanted to seperate the view from the code, thats why I started using a command, which caused the problem of the command not knowing which of the checkboxes was set. Still I am interested in how to get a object or string from the view to the command. That topic often hit me before.
Answer: You could avoid exeucting the command and just call your method from each setter, e.g.:
private bool _port1;
public bool Port1
{
    get { return _port1; }
    set { _port1 = value; SetPort(); }
}

If the SetPort modifies the other properties, you could use a flag to determine whether it should be invoked:
private bool _setPort = true;

private bool _port1;
public bool Port1
{
    get { return _port1; }
    set
    {
        _port1 = value;
        if (_setPort)
        {
            _setPort = false;
             SetPort();
            _setPort = true;
        }
    }
}

You could do the same thing in the Execute method of your command if you still want to use a command for some reason.
The _setPort field prevents the method from getting called for each source property.
Alternatively, you could also avoid setting the property in the method and instead set the backing field and raise the PropertyChanged event:
_port2 = true;
OnPropertyChanged(nameof(Port2));
This will bypass the setter and avoid calling the method.
Comment: Thanks a lot, this solves my problem. I dont need a command, just call my function when set of the binded property is called. The easiest solution is always best one :-) But still I would really be interested in a way to give a object or string to a binded command ...

wpf CheckBox command parameter


How do I print main_menu?

Question: I try to render a main menu but it doesn't render. My old Drupal 6 template try to upgrade Drupal 7 template.
I've render in page.tpl.php.
<?php if (isset($main_menu)) : ?>
    <?php print phptemplate_primary($main_menu); ?>
  <?php endif; ?>

This is the code for phptemplate_primary().
function phptemplate_primary() {
  $output = '
';
  $element = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
  $output .= drupal_render($element);
  $output .= '
';
  return $output;
}

How do I resolve this problem?
Answer: You can do it both ways:

You can add menu block to your template - just like any other block (this method is the easiest).
If you need more customization, you can do it in template:

page.tpl.php
<?php if ($primary_nav): print $primary_nav; endif; ?>

template.php
if (isset($variables['main_menu'])) {
  $variables['primary_nav'] = theme('links__system_main_menu', array(
    'links' => $variables['main_menu'],
    'attributes' => array(
      'class' => array('links', 'inline', 'main-menu'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    )
  ));
}
else {
  $variables['primary_nav'] = FALSE;
}

How do I print main_menu?


Using jq to extract information about dependencies from package.json

Question: So I am trying to run a jq command inside a makefile to link some dependencies, and I do not understand what the line inside the do-done does. If using only echo "$$dep" I understand what's going on, but when using the full line of code ([ -f "$$dep/package.json" ] && echo "$$dep";) I seem to be lost.  Does anyone have any idea? Thanks.
jq -r '.dependencies,.devDependencies|keys[]' $< | while read -r dep; do \
    [ -f "$$dep/package.json" ] && echo "$$dep"; \
done | (piping forward)

Answer: Since this is in a makefile, there are two things that need to be understood.  First, to understand the "$$" variable ($$dep), see this stackoverflow question:
Makefile and use of $$
Second, to understand the ... in do ... done, remember that this is essentially equivalent to a shell conditional of the form:
if [ -f _ ] ; then echo _ ; fi

For details about the test, see e.g. http://wiki.bash-hackers.org/commands/classictest
Comment: So here the `[ -f "$$dep/package. part]` is checking if that file exists ?


Pages don't seem to see my css file

Question: I am new to this, and have created a Twitter Bootstrap page, based on an MVC4 application.
In my layout, I start with this:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="@Url.Content("~/scripts/jquery-1.9.1.min.js")" rel=""/>
    <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet"/>
    <link href="@Url.Content("~/Content/Site.css")" />
    <title>@ViewBag.Title</title>

And then the rest of the page.
Within my Site.css, which is where I put my custom css, I have the following:
body {
    margin-bottom: 80px;
}
.field-validation-error {
    color: #f00;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00;
    background-color: #fee;
}

.validation-summary-errors {
    font-weight: bold;
    color: #f00;
}

.validation-summary-valid {
    display: none;
}

.page-header {
    margin-top: 0;
}

.panel-body {
    padding-top: 0;
}

.featuredImg {
    margin-bottom: 15px;
}

It seems none of my pages are using this CSS though. The body doesn't seem to add the margin...
If I used Firebug, and select the CSS tab, I see no reference to Site.css. Only to 'bootstrap.min.css'.
In design time, the path to my CSS file seems right, as I can click it in the designer, and it takes me to the css file.
It just seems not to load it at runtime.
Is there a fault I am doing?
Answer: Try adding rel to your link tag
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" />

Pages don't seem to see my css file


Programa em python quesoma o fatorial de números impares até o digitado pelo usuário

Question: Devo pedir para o usuário digitar um número ímpar e retornar na tela a soma do fatorial de todos os ímpares até o digitado pelo usuário.
Fiz a parte que valida se o número digitado é ímpar e a função que calcula o fatorial do número digitado. Mas não sei como fazer o resto. Não consegui nem pensar na lógica da outra função. Fiz esse código:
def fatorial(x):
    result=1
    for i in range(x):
        result=result*(x-i)
    return result

'''def fatorial(x):
    x=x-2
    while x>1:
        fat=fat*a
        a-=1 - Não deu certo'''
a=int(input("Digite o número: "))
while a%2!=1:
    a=int(input("Número não impar, digite outro número: "))
    while a<0:
        a=int(input("Número menor que zero, digite outro número: "))
else:
    b=fatorial(a)
print(b)

Answer: Tendo a função que calcula o fatorial e o número digitado N, basta fazer um for pelos números ímpares de 1 a N, e ir somando o fatorial deles:
def fatorial(x):
    result = 1
    for i in range(2, x + 1):
        result *= i
    return result

while True:
    n = int(input('digite o número'))
    if n % 2 == 0 or n <= 0:
        print('número deve ser impar e maior que zero, digite outro')
    else: break

soma = 0
for i in range(1, n + 1, 2):
    soma += fatorial(i)

print(soma)

Repare que para verificar se o número digitado é ímpar eu fiz um loop infinito (while True), que só é interrompido se o número for ímpar (se for par, imprime a mensagem e pede que digite novamente). Também incluí a verificação se é negativo, pois parece só poder aceitar positivos.
Depois fiz um for usando um range, que começa em 1 e vai até n, pulando de 2 em 2 (assim eu sei que vai percorrer somente os ímpares até n). Tive que colocar n + 1 porque o valor final não é incluso no range.
Entendo que por ser um exercício, pode ser que queiram que você itere de 1 em 1 e teste se o número é impar, algo assim:
for i in range(1, n + 1):
    if i % 2 != 0:
        soma += fatorial(i)

Mas sinceramente, a menos que seja exigência do exercício iterar de 1 em 1 e usar o operador %, isso é desnecessário, pois se eu começo de um número ímpar e só quero iterar pelos ímpares, basta pular de 2 em 2.
Veja também que mudei a função que calcula o fatorial, para começar o range com 2 (começar com 1 é desnecessário  porque multiplicar por 1 é redundante). Da forma que você fez até funciona, mas em um range é possível controlar o valor inicial e final, então acho que fica melhor assim. Se n for 1, ele nem entra no for e o resultado é 1.
Ah sim, você disse que estava tentando fazer uma função para calcular a soma. Neste caso ficaria:
def soma_fat(n):
    soma = 0
    for i in range(1, n + 1, 2):
        soma += fatorial(i)
    return soma

n = # ler valor do n
print(soma_fat(n))

Se quiser, você também pode calcular a soma usando sum juntamente com uma generator expression, bem mais sucinta e pythônica:
soma = sum(fatorial(i) for i in range(1, n + 1, 2))

Também é possível dar uma pequena "otimizada". Ao calcular o fatorial de 3, por exemplo, multiplicamos 1 * 2 * 3, e depois temos que calcular o fatorial de 5, fazendo 1 * 2 * 3 * 4 * 5 (ou seja, as primeiras multiplicações serão feitas novamente).
Dá para evitar esse retrabalho guardando o fatorial do último número calculado, e só fazer as multiplicações que faltam:
# ler n usando o while True acima

soma = 1
fat = 1
for i in range(3, n + 1, 2):
    fat *= i * (i - 1)
    soma += fat
print(soma)

Se n for menor que 3 (ou seja, se for 1), ele nem entra no for e o resultado é 1. Se for maior ou igual a 3, o loop vai atualizando o fatorial (multiplicando os valores que faltam) e somando ao total.
Comment: Cara, muito bom. Obrigada pelas explicações e pelo detalhamemto.


Script for pulling daily water characteristic data does not save file

Question: I am a new python user and I need some help. I am trying to download data from here for characteristic zeta, salt, temp, u, and v.
My code is below and is largely modeled from a code used for downloading HYCOM data, which has a data library with a similar structure. This code will run and does not produce any errors, but it doesn't bring any .nc files into my folder... Can anyone help me figure out what is wrong? I know this is really specific and I appreciate any help you can offer.

#!/usr/bin/env python3
#automatically download HYCOM data
from pylib import *
close("all")

#--------------------------------------------------------------------
#input
#--------------------------------------------------------------------
StartT,EndT=datenum(2021,6,1),datenum(2021,10,1)
xm=[-100,0]; ym=[0,80]
sdir='.'

#database
url_1='https://tds.marine.rutgers.edu/thredds/roms/doppio/ncss/grid/roms/doppio/'
database=['DopAnV3R3-ini2007_da/his',]

#download hycom data
if not os.path.exists(sdir): os.mkdir(sdir)
for ti in arange(StartT,EndT):
    url='{}/{}?'.format(url_1,database)

    #add variables
    for i in ['zeta','salt','temp','u','v']: url=url+'var={}&'.format(i)

    #add domain
    for i,k in zip(['south','north','west','east'],[*ym,*xm]): url=url+'{}={}&'.format(i,k)

    #horizontal stride and time
    for n in arange(0,24,3):
        fname='{}/hycom_{}_{:02}.nc'.format(sdir,num2date(ti).strftime('%Y_%m_%d'),n)
        furl=url+'horizStride=1&time={}T{:02}%%3A00%3A00Z&timeStride=1&vertCoord=&accept=netcdf4'.format(num2date(ti).strftime('%Y-%m-%d'),n)

        #download doppio data
        if os.path.exists(fname): continue
        try:
           urllib.request.urlretrieve(furl,fname)
           print(fname)
        except:
           pass

print('Done-----------')

I expect to see .nc files output into my folder location for the time range indicated, but nothing ends up outputting and I don't get any error messages.
Comment: Because you basically never downloaded nor saved as file any content of any url in your code
Comment: I really appreciate your response, could you help me with what to add to save? I basically want to file to save as what I have called fname....
Answer: The problem seems to be in the URL.
When I look at the Rutgers website you've linked, I find a different URL to request data files.
After correcting the URL, it works for me and files are being saved and downloaded.
The reason why you see no error messages is that the crucial part of the code is within try-except and the error message is discarded.
This should be avoided.
A better way is to write the except statement as follows:
except Exception as e:
    print("Error:", e)

This way, you will at least have an idea what went wrong.
In my case, it gives HTTP Error 500, indicating that the request was not well-posed.
Using the information on the linked Rutgers website, I attempted to correct the URL and arrived at the following code, which downloads the files as requested:
from urllib.request import urlretrieve

url = "https://tds.marine.rutgers.edu/thredds/ncss/roms/doppio/DopAnV3R3-ini2007_da/his?"

# Add variables of interest to the URL
for var in ["zeta", "salt", "temp", "u", "v"]:
    url += "var={}&".format(var)

url += "disableLLSubset=on&disableProjSubset=on&horizStride=1&vertStride=1&"

date = "2021-06-01"
for n in range(0, 24, 3):
    fname = "out/hycom_{}_{:02}.nc".format(date, n)
    furl = url + "time={}T{:02}%3A00%3A00Z&accept=netcdf4".format(date, n)
    print("Downloading from:", furl)
    print("Saving to:", fname)
    urlretrieve(furl, fname)

This is for only a single date, because I don't know this pylib module and the datenum function, but I believe it will work the same when you add the for-loop over all dates again.
Also, I removed the specified lat/lon range, because the given domain seems to be outside the area covered by the dataset.
Some further suggestions:

Using from pylib import * should be avoided, because it makes it unclear where a name (e.g., a function) comes from.  It is better to only import that is really needed.  In my code, this is only the urlretrieve function, and one can easily see from which library this function comes from.
The close("all") does not seem to be useful here.  It is probably there to close previously opened figures, but this code does not produce any figures, so no need to close anything.
The brackets and the comma in database=['DopAnV3R3-ini2007_da/his',] are not needed here, and are presumably part of the problem with the wrong domain.


How to exclude certain IP for AWS WAF rate limit?

Question: I am new to AWS WAF, I set up the AWS WAF for the api gateway to limit the 5k requests in 5 minutes window. However, the internal IPs would exceed the 5k limit and get blocked, so is there a way to exclude internal IPs from this rate limit (let them request unlimited times)?
Comment: Am I going to create an IP set and change the rate limit rule to count requests that are not from the IP set?
Answer: I understand that you would like to know if there is a way to exclude certain IPs from a WAF rate limit rule inspection.
This can be done by using a Scope Down statement on the rate limit rule.
There is an excellent article on the AWS Knowledge Center about this.
Section 2 of the article above contains the necessary steps. I've also written them out below. The most important steps to review are 8, 9, and 10.
Use the following steps to exclude an IP set from a rate-based-rule:

Open the AWS WAF console.
Select Web ACLs.
Select the web ACL and then select the Rules tab.
Select Add rules.
Select Add my own rules and rule groups.
Select Rule builder for the Rule type.
Enter a Name and select Rate-based rule as the Type.
Enter the following parameters for the Request rate details:

Rate limit: Enter a number between 100 and 20,000,000. This is the maximum number of requests allowed for every IP in a 5-min period.
IP address to use for rate limiting: If you want the rate limit based on the client IP field, select Source IP address. Or, if you want the rate limit based on the IP address in the header, select IP address in header. For example, X-Forwarder-for.
Criteria to count request towards rate limit: Select Only consider requests that match the criteria in a rule statement.

In the If a request dropdown list, select Doesn't match the statement (NOT).
Complete the following fields in the Statement details section:

Inspect: Originates from an IP address in.
IP set: Select the IP set from the dropdown list.
IP address to use as the originating address: If you want the rate limit based on the client IP field, then select Source IP address . Or, if you want the rate limit based on the IP address in the header, select IP address in header. For example, X-Forwarder-for.

In the Action section, select Block.
Select Add rule. Move the rule to the correct priority for your use case and then select Save.

Here are some additional resources for working with rate based rules.

AWS WAF Docs - Rate-based rule statement
AWS WAF Docs - Listing IP addresses that are being rate limited by rate-based rules

I hope this helps!


#default_value for select form elements does not work

Question: <code><?php
namespace Drupal\dishes_dropdown\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Component\Utility\UrlHelper;

/**
 * Desarrollo de un formulario en drupal 8
 *
 */
class DishesDropdownForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'dishes_dropdown_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $maxlength = 250;

        $tax_terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('dish_type', $parent=0, $max_depth=NULL, $load_entities=FALSE);
        $taxs = array();
        foreach ($tax_terms as $tax_term) {
            $taxs[$tax_term->tid] = $tax_term->name;
        }

        $form['dish_dropdown'] = array(
            '#type' => 'select',
            '#options' => $taxs,
            '#chosen' => true,
            '#multiple' => false,
            '#maxlength' => $maxlength,
            '#default_value' => $form_state->hasValue('dish_dropdown') ? $form_state->getValue('dish_dropdown') : '' ,

        $form['submit'] = [
            '#type'  => 'submit',
            '#value' => $this->t('Ir al tipo de plato'),
            '#weight' => 50,
        ];
        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Display result.
        $id = reset($form_state-> getValues('dish_dropdown'));
        $aliasManager = \Drupal::service('path.alias_manager');
        // The second argument to getAliasByPath is a language code such as "en" or LanguageInterface::DEFAULT_LANGUAGE.
        $alias = $aliasManager->getAliasByPath('/taxonomy/term/' . $id);

        $url = new TrustedRedirectResponse($alias);
        if (isset($url)) {
            $form_state-> setResponse($url);
        }

        return;

    }
}
</code>

I do not load the "default_value" in select. I have tried a thousand ways in the "build" but there is no way. I want a blank default value but without forcing it load it. It's like if you read the "default_value".
Answer:
The #default_value for a select element should be an integer value matching an array key in the #options array.

In your case, lets say
<code>$taxs = [5 => 'blue dish', 9 => 'red dish', 15 => 'green dish'];
</code>
Then an option for the value for *#default_value will be one of 5,9 or 15.
In your case the function $form_state->hasValue('dish_dropdown') will return one of "blue dish", "red dish" or "green dish" which is not an array key in your $taxs array.
So what do you do?

Either select one of your dish types as the default OR
Add a default value - None -

For example:
<code>$taxs[0] = '-- None --';
$reverseTaxs = array_flip($taxs);
$form['dish_dropdown'] = array(
        '#type' => 'select',
        '#options' => $taxs,
        '#chosen' => true,
        '#multiple' => false,
        '#maxlength' => $maxlength,
        '#default_value' => $form_state->hasValue('dish_dropdown') ? $reverseTaxs[$form_state->getValue('dish_dropdown')] : 0 ,

    $form['submit'] = [
        '#type'  => 'submit',
        '#value' => $this->t('Ir al tipo de plato'),
        '#weight' => 50,
    ];
    return $form;
</code>


Are baseball game-winning hits off the bench becoming more common?

Question: It seems that every day a player comes off the bench with runners in scoring position for a game-winning hit. Are these walkoffs in baseball becoming more statistically common? They are usually followed by an energy drink shower or celebratory pie in the face.
Looking at numbers for the current season. The pinch hitter has always been part of the game but now we see offensive substitutions in almost every game that is tied or goes into extra innings. It could be a reaction to relievers being chosen out of the bullpen to counter expected lineups.
Comment: What's your time frame on this? When do you *think* they started to trend upwards?
Comment: As mentioned above, viewing numbers for the current season.
Comment: Pinch hitters are put in because they match up with the current pitcher well.  But historically guys pinch hitting hit below the league average.  You might notice pinch hitters hitting bigger hits because a manager often wouldn't use a pinch hitter when the situation doesn't matter.
Answer: This query pulls up approximately the desired specifics - Walk-off win, RBI>=1, PA=1, PH position, finished game, didn't play any other position than PH.  That's almost always going to be the exact specifics - occasionally you might have a PH in the final inning with a non-winning RBI of course, but usually it's
not, and the distribution for that particular should be approximately consistent.
I'm going to just list what year is on every 250 rows:
2014: 0
2003: 250
1992: 500
1983: 750
1976: 1000
1968: 1250
1958: 1500
So 11,11,9,7,8,10 years between each 250 rows.  Sounds like it's slightly less common nowadays, if anything, assuming this query is correct; you'd have to be a Baseball Reference PI subscriber probably to verify this with any reasonable degree of certainty.  Overall this is a pretty reasonably random distribution.
Answer: I don't exactly when such things became more common, but I have the sense that they are more common than in the 1970s, when I was growing up.
That's because baseball management has become more "scientific" in the past 40 years, with the monitoring of things like pitch counts for pitchers, innings counts for fielders, left-right and right-left batter-pitcher match-ups, and even "splits" of individual batters versus individual pitchers.
Comment: Some numbers to prop this up would be amazing.
Comment: @waxeagle: Unfortunately, I don't have numbers going back 40 years. So I have to argue, "Today's management is more scientific, and IF your observation (and my recollection) is correct, this would be the reason why."


Some content is not displaying on one of my Drupal 7 pages

Question: I inherited a development theme and I am a Drupal newbie. I don't seem to be able to print out any new fields that I add to my content types. I put this code in node.tpl.php:
<code><?php echo render($content['field_my_text']);?>
</code>
I have the corresponding name in my content type. Any ideas on what could be going wrong?
Thanks!
Comment: I figured it out. The new field was initially set to hidden inside the manage display tab of the "full content" (instead of the default).
Answer: I figured it out. The new field was initially set to hidden inside the manage display tab of the "full content" (instead of the default).


Can bagatelles be in Sonata Form?

Question: I am composing a bagatelle and it is turning out to be sort of a hybrid between your typical bagatelle and a sonata. However, even once the piece is finished, it would be too short for me to put Sonata in the title(5 minutes at most, that isn't long enough for an entire sonata). I mean, I guess I could call it the Sonata Bagatelle but then the title would be confusing.
Here is how I was planning things out.
I was planning to do it in rondo form. At first I thought of sticking to ABACA such as in Fur Elise. But the rondo form quickly expanded to be ABACABA, the typical form of a rondo in a sonata. But I was still planning on having 2 sections in the tonic. That is, until my melodic improvisation lead me somewhere else. This is really when the hybridization of the typical bagatelle and the sonata started happening. And it is why I am asking this question relating to bagatelles and sonata form.
I will show both the general terms and the Sonata Form terms here.
Here is the First Theme/A section of my bagatelle:

And here is its motive division:

As you can see, I have a lot of motives here. This means that I can have an extensive development without it being boring or completely unrelated sounding. Here are the motives:

Red - Starting motive and its inversion
Green - Second motive
Blue - Triplet motive
Purple - Dominant motive
Orange - Scale motive
Dark red - Cadential motive

Here is my Second Theme/B section:

And here is its motive division:

As you can see, I have a single motive here, a scale step that descends through the theme. This means that the Second Theme/B section can't contribute as much to the Development/C section as the First Theme/A section can, but it is pretty typical for 1 theme to have more motives than another theme in a sonata form piece.
With this, my bagatelle "Exposition" is in this form:

ABA

The C section, I am planning on having be in the parallel minor. So since I am in C major here, the C section would be in C minor. Here is my question.
Can bagatelles be in Sonata Form? Because that seems to be what my bagatelle is heading towards is Sonata Form.
Comment: Possible duplicate of [What makes a piece a bagatelle?](https://music.stackexchange.com/questions/86254/what-makes-a-piece-a-bagatelle)
Comment: How is it a duplicate? Here I'm asking whether or not it can be in Sonata Form. That is a specific question about a specific form, whereas the other question is where I talk about similarities I have found in bagatelles, more specifically, Beethoven bagatelles that are in minor keys, and whether or not any of them make a piece a bagatelle. I never mentioned Sonata Form in the linked question. I mentioned Sonata-Rondo Form which is different because it's a combination of Rondo Form and Sonata Form. I only mentioned it briefly, when I talked about why Mozart's Rondo Alla Turka is not a bagatelle
Answer: If well over a century ago Liszt wrote a bagatelle that was atonal, and also something that he called a sonata (for piano, b minor) that is in four symphonic movements by any reasonable analysis, then your thematic structure can be much wilder yet before anyone complains that it wasn't both bagatelle and sonata.
If that's where it's headed, that's where it's headed.  Don't look over your shoulder at the theorists too much.
If you're self-conscious about its length, just call it a bagatelle.  Many shorter things (Bach WTC) have been analyzed as sonata form, never mind the title.
Comment: @Caters, a bagatelle is simply a light, short piece. It can have whatever form you want it. I know composers who made up their own terms, too, for short piano pieces to avoid connotations that might create expectations in the listener for a specific sound or form. In short, do what you want, call it what you want. There are plenty of pieces out there that are called "sonata" that don't follow sonata form. And even more that supposedly have a sonata form that, when analyzed, make you scratch your head and say "huh?"
Comment: So, I don't have to worry that the Sonata Form that my piece is heading towards will make the piece not a bagatelle.
Answer: You can call your piece whatever you want. If you are not happy with either "Bagatelle" or "Sonata" then other possibilities might be:

"Sonatina" (a piece that is in basic sonata form, but is shorter and lighter in character).
"Piano Piece No.x"
a fantasy or descriptive name
a dedication ("Für Elise")

Can bagatelles be in Sonata Form?


How to show full processlist in mysql with state higher than x?

Question: I'm writing a "systems check" bash script and for one of the items, I want to check all running processes in MySQL, but I only care if they have a state higher than 30.
In MySQL, is there a way to show a list of processes only that have a state higher than x, such as over 30?
I tried show processlist where state>=30;
I have version 5.5.58-0+deb8u1.
Answer: As @Hariraman Radhakrishnan answered, the SHOW PROCESSLIST command cannot be modified.
However, from reading his link, the SHOW PROCESSLIST actually reads from information_schema.processlist
This means you can perform a normal query against information_schema.processlist like this:
SELECT *
FROM information_schema.processlist
WHERE TIME > 30

If you look at https://dev.mysql.com/doc/refman/8.0/en/processlist-table.html, you can see what each column means.
I have written the query to select all processes that have been running for more than 30 seconds, but that might also just be a sleeping connection, for example a program that connects at the beginning, and then keeps the connection alive until you close the program again.
This would mean that the process can run for minutes, hours or days, but will have COMMAND = 'Sleep' most of the time.
If you only want to see long running queries, you should update your queries to:
SELECT * FROM information_schema.processlist WHERE COMMAND != 'Sleep' AND TIME > 30;
TIME is reset when the state changes
From the docs: "The time in seconds that the thread has been in its current state.")
Answer: Unfortunately, SHOW PROCESSLIST does not allow filtering. When you are on MySQL ≥ 5.1.7, do this instead:
SELECT * FROM information_schema.processlist WHERE command != 'Sleep' ORDER BY id;
That also allows you to only show some values or order differently, like so:
SELECT user, time, state, info FROM information_schema.processlist WHERE command != 'Sleep' ORDER BY time DESC, id;
One more example -- see all non-sleeping queries that take some time, for example at least 2 seconds:
SELECT user, time, state, info FROM information_schema.processlist WHERE command != 'Sleep' AND time >= 2 ORDER BY time DESC, id;
Comment: For my sake and anyone else this is helpful to, can you improve your answer by listing the command I should use here and also explain how sleeping relates to state? Thanks.


Gmail rejecting IMAP calls from AWS EC2 hosted James server

Question: I have James server (SMTP server) hosted on AWS EC2. I have small application running on this AWS instance which fetches certain emails from my Gmail account.
Gmail rejecting any IMAP request from my AWS EC2 with message suspicious activity.
When I did login (RDP) to EC2 instance and open gmail in a browser (in which case it prompted me to valid few other details apart from regular password), it worked fine and all subsequent requests from my small application working fine.
It doesn't make sense to ask all users to do RDP to server first, then only use this application.
Does any one have any suggestions on how can I overcome this issue and make sure Gmail server trusts my AWS EC2 instance as valid instance?
Thanks for your time.
Comment: Gmail has likely blacklisted EC2's IP range due to abuse. Use Amazon SES, Mandrill, Postmark, or another similar e-mail provider.
Comment: Another method: go to http://www.google.com/accounts/DisplayUnlockCaptcha then have your EC2 instance initiate an IMAP connection. See https://support.google.com/mail/answer/14257?p=client_login&rd=1
Comment: @Nambari I'm having a hard time imagining custom functionality that would forbid you from using a service like SES. Can you elaborate?
Comment: @ceejayoz: I can't use SES because of custom functionality I have (that is one of the reason why I ended up with Apache James). Is there way I can put in requests to unblock my IP?
Comment: @ceejayoz: (Please note that I have high level info SES, so correct me if I am wrong). I need capability to create email account on server for every user registered from my application 2) need to have a capability to read emails from SES (I think this can be achieved)
Comment: I'm confused. How is your server creating accounts in Gmail? That's pretty hard to automate.
Comment: @ceejayoz: No, accounts are on James (SMTP) server on EC2, I need to download emails from Gmail to this James server, which is where Gmail rejecting my requests.
Answer: In fact, the problem is simple: your JAMES server is running in an instance that's probably geographically far from where you usually are when you log in to your Gmail account, so it appears to Google like someone is trying to break into your account (after all, how can you be logging in from California and Virginia within a couple of hours of each other?). So to be safe, they block the connection and send a warning. The warning is usually accompanied by an "Is this you?" link and if you say "yes", you'll be able to log in with JAMES in a few hours.
Recently, Google has implemented a setting that lets you connect using what Google refers to as "less secure mail clients", so the dreaded "Suspicious signin detected" message should become a thing of the past.


Função do R retorna valor errado

Question: a função Log.lik abaixo retorna o valor -INFquando deveria retornar o valor -5836.219. Não consigo descobrir o erro, alguém tem alguma sugestão?
rm(list=ls())
library(ssmrob)
data(MEPS2001)
attach(MEPS2001)
n<-nrow(MEPS2001)
Log.lik <- function(par,X,W,y){
  n <- length(y)
  beta <- par[1:(ncol(X)+1)]
  gamma <- par[(ncol(X)+2):(ncol(X)+ncol(W)+2)]
  mu1 <- model.matrix(~X)%*%beta
  mu2 <- model.matrix(~W)%*%gamma
  sigma <- par[(ncol(X)+ncol(W)+3)]
  rho <- par[(ncol(X)+ncol(W)+4)]
  term0 <- (y-mu1)/sigma
  term1 <- ((rho*(term0))+mu2)/sqrt(1-rho^2)
  Phi_mu2 <- pnorm(mu2)
  phi_t0 <- dnorm(term0)
  phi_t1 <- dnorm(term1)
  Phi_t0 <- pnorm(term0)
  Phi_t1 <- pnorm(term1)
  f <- (phi_t0*Phi_t1)/(sigma*Phi_mu2)
  #Função log de verossimilhança
  return(sum(ifelse(Y2>0,log(phi_t0)+log(Phi_t1)+log(1/sigma),log(1-Phi_mu2))))
}
y <- lnambx
Y2 <- dambexp
X <- cbind(age,female,educ,blhisp,totchr,ins)
W <- cbind(age,female,educ,blhisp,totchr,ins,income)

gamma0=-0.6760544
gamma1=0.0879359
gamma2=0.6626647
gamma3=0.0619485
gamma4=-0.3639377
gamma5=0.7969515
gamma6=0.1701366
gamma7=0.0027078
beta0=5.0440623
beta1=0.2119747
beta2=0.3481427
beta3=0.0187158
beta4=-0.2185706
beta5=0.5399190
beta6=-0.0299875
sigma=1.2710176
rho=-0.1306012
beta=c(beta0,beta1,beta2,beta3,beta4,beta5,beta6)
gamma=c(gamma0,gamma1,gamma2,gamma3,gamma4,gamma5,gamma6,gamma7)
start=c(gamma0,gamma1,gamma2,gamma3,gamma4,gamma5,gamma6,gamma7,beta0,beta1,beta2,beta3,beta4,beta5,beta6,sigma,rho)
Log.lik(start,X=X,W=W,y)

Se rodar os códigos abaixo que estão dentro da programação da função Log.lik os mesmos compilam corretamente!
mu1 <- model.matrix(~X)%*%beta
mu2 <- model.matrix(~W)%*%gamma

term0 <- (y-mu1)/sigma
term1 <- ((rho*(term0))+mu2)/sqrt(1-rho^2)
Phi_mu2 <- pnorm(mu2)
phi_t0 <- dnorm(term0)
phi_t1 <- dnorm(term1)
Phi_t0 <- pnorm(term0)
Phi_t1 <- pnorm(term1)
f <- (phi_t0*Phi_t1)/(sigma*Phi_mu2)
#Função log de verossimilhança
sum(ifelse(Y2>0,log(phi_t0)+log(Phi_t1)+log(1/sigma),log(1-Phi_mu2)))

Answer: Ao substituir as linhas abaixo no código da verossimilhança, a mesma compila!
Phi_mu2 <- pnorm(-mu2,log.p = TRUE)
 phi_t0 <- dnorm(term0,log = TRUE)
 phi_t1 <- dnorm(term1)
 Phi_t0 <- pnorm(term0,log.p = TRUE)
 Phi_t1 <- pnorm(term1,log.p = TRUE)
return(sum(ifelse(Y2>0,(phi_t0)+(Phi_t1)+log(1/sigma),(Phi_mu2))))

Função do R retorna valor errado


Predictive Density for Dirichlet Multinomial

Question: I am wondering what the predictive distribution of a Dirichlet-Multinomial distribution is.
In this tutorial (page 24), the predictive density is simple and something like "pseudo samples."

However, in this writeup, the predictive density is rather complicated.

I can walk through the latter formula, but do not come to the former one. (It does work from my side for multinoulli/categorical distributions, but not multinomial with N>2).
Can anyone give some references? Thanks a lot.
Answer: The first slide applies the general result of the second slide to a case when $$y=\overbrace{(0,\ldots,0,1,0,\ldots,0)}^{1\text{ at }\kappa\text{th position}}$$ with different notations, since [in the second slide] $\alpha'_j=\alpha_j+n_j$ and $y^{(j)}=n_j\in\{0,1\}$. Then
\begin{align*}
\dfrac{\Gamma(n+1)}{\prod_{j=1}^K \Gamma(y^{(j)}+1)}&=\dfrac{\Gamma(n+1)}{\Gamma(y^{(\kappa)}+1)}=\dfrac{n!}{1}\\
\dfrac{\prod_{j=1}^K \Gamma(y^{(j)}+\alpha_j')}{\prod_{j=1}^K\Gamma(\alpha_j')}&=\dfrac{\Gamma(1+\alpha_\kappa')}{\Gamma(\alpha_\kappa')}=\alpha_\kappa+n_\kappa\\
\end{align*}
and the middle ratio does not depend on $y$.
Hence $$\mathbb{P}(y=(0,\ldots,0,1,0,\ldots,0))\propto \alpha_\kappa+n_\kappa$$which normalises as
$$\mathbb{P}(y_\kappa=1)=\dfrac{\mathbb{P}(y_\kappa=1)}{\sum_{k=1}^K \mathbb{P}(y_k=1)}=\dfrac{ \alpha_\kappa+n_\kappa}{\sum_{k=1}^K \{\alpha_k+n_k\}}=\dfrac{ \alpha_\kappa+n_\kappa}{\sum_{k=1}^K \alpha_k+n}$$
Comment: Thank you very much for answering. If I am understanding correctly, the first slide works with multinomial distributions where N=1, i.e., a categorical distributions. Am I right?
Comment: May I make it more clear? The first slide, which I was confused about, predicts the density for a **single** (N=1) next draw (although the training samples are multinomial distributions with N which can be greater than 2.) Am I right now?
Comment: Hi Xi'an, I am currently having trouble in thinking about conjugate prior for Dirichlet processes. Could you please, perhaps, share some quick sort on [this](https://stats.stackexchange.com/questions/310886/conjugacy-of-dirichlet-process)? It would be much appreciated.
Comment: Well, I'm mainly in engineering background, so if that's too complicated for me, I may feel like skipping that.


Most well-known set-similarity measures?

Question: I know of the Jaccard index and the Sørensen-Dice coefficient for computing set similarity, but have been unable to find any other algorithms related to set similarity. This site contains quite a few resources for vector similarity, but that's not what I want.
What other set-similarity measures exist?
Comment: You can treat being in a set as an variable (or being in the first set as a classifier and being in the second as the concept). Using this reduction you can apply all the supervised learning metrics - accuracy, mutual information, etc.
Answer: Other measures are:

Overlap Coefficient: $\frac{|A \cap B|}{min(|A|,|B|)}$
Tversky index: $|A\cap B| + \alpha|A\setminus B| + \beta|B \setminus A|$ where $\alpha$ and $\beta$ are positive numbers.
Comment: Tversky is the generalization of Jaccard and DIce


Book page appears in one language (of four) only

Question: I run a Drupal 7 site with 4 languages installed: English (for me as admin) and 3 balkan languages (I don't speak them actually): Serbian, Croatian, Slovenian.
I have added a book there (url shortcut should be: help) and have added 3 book pages: Imprint (in German, url shortcut imprint), Privacy and Terms of Services (both pages have English content and url shortcuts privacy and tos).
All 3 book pages should be visible in all languages - i.e. in English, Serbian, Croatian, Slovenian.
However for some reason they are only visible in the Croatian view of my web site and also only /hr/shortcuts work.
And when I look at http://balkan-preferans.de/en/node/1#overlay=en/admin/content they have Croatian as language:

Can I somehow change the language to be All?
Answer: Ok, found that setting under
Home » Administration » Configuration » Search and metadata » URL aliases

Or go to Modules and configure Path module settings
Setting the language to All languages has solved my problem


Show that for every interval $(a,b)$, the intersection of C (Cantor set) with $(a,b)$ is empty or uncountable

Question: My try:
Case I
Let $(a,b)$ such that for any subinterval of $C = \bigcap_{m=0}^{\infty}F_m$, $[\frac{n}{3m},\frac{n+1}{3m}]<(a,b)<[\frac{n+2}{3m},\frac{n+3}{3m}]$ for some $n \in \mathbb{N}$
then $C\bigcap(a,b)=\emptyset$
Case II
If $C \bigcap (a,b)\neq \emptyset$ then because we know that for any open interval $(a,b)$ that intersects $C$ contains some subinterval of some $F_m$, the subinterval $[\frac{n}{3m},\frac{n+1}{3m}]⊆(a,b)$.
Suppose that two binary functions in base three $f,g \in[\frac{n}{3m},\frac{n+1}{3m}]$ such that $f(p)=h(p) \; \; \;  \forall n≤p≤1$ exists. And because we know that the set of binary sequences having the same initial $n$-segment is uncountable, $C \bigcap (a,b)$ must be uncountable.
I don't know if my analysis is correct (especially Case II). Any hints would be great!
Comment: Hi, here's a typesetting resource https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference, it would help making your question more readable.
Comment: A better title would be: "Show that for every interval $(a,b)$, the intersection of $C$ (Cantor set) with $(a,b)$ is empty or uncountable." By definition, if the intersection is the empty set, we say the two sets don't intersect.
Answer: Consider the two halves of Cantor set $C^1_1=[0,1/2]\cap C$ and $C_2^1=C\cap [1/2,1]$. Each of these is uncountable, and they "look the same" (they're homeomorphic, but that's not important) as $C$. So, we can repeat the process and split each half into halves. In general, for each $n\in\mathbb{N}$ you can find uncountable sets $C_i^n$ for $i=1,2,\dots,2^n$ such that each $C_i^n$ has diameter $\le 2^{-n}$ and $C=\bigcup_{i=1}^n C_i^n$.
Granted this, let $I$ be an open interval with $I\cap C\neq \emptyset$. Pick a point $x\in I\cap C$. Let $\varepsilon>0$ be such that $(x-\varepsilon,x+\varepsilon)\subset I$. Pick $n$ with $2^{-n}<\varepsilon$. There exists an $i\le 2^{n}$ with $x\in C^n_i$. Then we have that $C^n_i\subset I$, so that $C\cap I\supset C^n_i$, which is uncountable (in fact of size continuum, but eh).


Cayley graph is normal

Question: We had an exercise on the lecture to show that Q = $Cay(Z_{2} ^n; e_1,e_2,...e_n)$ is a normal Cayley graph. And also to calculate |Aut(Q)|. Also before we had a theorem that states that :
If G ia abelian,finite group , S- inverse closed generating set of G, not containing identity. If S satisfies the condition $\forall s_1,s_2,s_3,s_4 \in S$ such that $s_1 + s_2 = s_3 + s_4 $ implies {$s_1$,$s_2$} = {$s_3$,$s_4$}.
I have a question, firstly what mean {$s_1$,$s_2$} = {$s_3$,$s_4$} ? Just that this two sets are equal?  And what if there does not exist elements such that $s_1 + s_2 = s_3 + s_4 $ ? Can we conclude that the theorem holds?
Also could someone please help, and give a hint on how to show that Q = $Cay(Z_{2} ^n; e_1,e_2,...e_n)$ is normal Cayley graph?
Answer: $Q$ is the $n$-dimensional cube. It's well known that $\mathrm{Aut}(Q)=\mathbb{Z}_2^n\rtimes S_n$, where $\mathbb{Z}_2^n$ is the copy you started with, and $S_n$ permutes the generators (this is also called the hyperoctahedral group). It follows that it's a normal Cayley graph.
It's quite obvious that at least $\mathrm{Aut}(Q)\leq\mathbb{Z}_2^n\rtimes S_n$. I'm not sure what the easiest way to prove the other inequality is, but the way I usually think about/remember it is that it's the Cartesian product of $n$ copies of $K_2$, and there are results giving the automorphism groups of Cartesian products.

Cayley graph is normal


Unknown format error when trying to respond_to format.xml

Question: I'm trying to parse a simple XML POST request and send back a 200 status in response but I'm receiving an unknown format error, but I do not understand why. The action says processing as / not as xml.  Any help would be great!
ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/locations_controller.rb:171:in `vz_api'

Started POST "/vz_api" for 127.0.0.1 at 2014-06-25 19:52:27 -0400
Processing by LocationsController#vz_api as */*

  def vz_api
    require 'nokogiri'
    xml_doc = Nokogiri::XML(request.body.read)
    vin = xml_doc.xpath("//VIN").inner_text
    @truck = Truck.find_by(vin: vin)
    @location = @truck.location
    lat = xml_doc.xpath("//Latitude").inner_text
    lng = xml_doc.xpath("//Longitude").inner_text
    heading = xml_doc.xpath("//Heading").inner_text
    speed = xml_doc.xpath("//Speed")[0].inner_text
    @location.update_attributes(longitude: lng, latitude: lat, speed: speed, direction: heading)
    respond_to do |format|
      format.xml do # format.json
        render :nothing => true, :status => :ok
        # return true
      end
    end
  end

Answer: Rails is processing as / not XML or JSON, so why don't you try the following instead
Remove respond_to block and just have:
render :nothing => true, status: :ok
Comment: I really don't understand what you mean here: `Rails is processing as / not XML or JSON`. What do you mean by this?


Combining two join queries into one

Question: I have two queries that I want to combine into one.
First query is
select
   a.desc  as desc
   ,sum(bdd.amount) as amount
from
   t_main c
left outer join
   t_direct bds on (bds.mainId = c.id)
left outer join
   tm_defination a on (a.id = bds.defId)
where
   c.descId = 1000000134
group by
   a.desc;

It returns following result
              desc       amount
              NW         12.00
              SW         10

Second query I have
select
    a.desc as desc
    ,sum(bdd.newAmt) as amount1
from
    t_main c
left outer join
    t_newBox b on (b.mainId = c.id)
left outer join
    t_transition c on (c.id = b.tranId)
left outer join
    tm_defination def a on (a.id = c.defId)
where
    c.descId = 1000000134
group by
    a.desc;

This query returns this result:
           desc   amount
           NW       4.00

I want to combine these two queries so that I get out put like this..
               desc   amount amount1
               NW      l2.00  4.00
               SW      10.00

I tried UNION between query 1 and query 2 but the result came out as
            desc    amountamount1
             NW      16.00
             SW      10.00

Which is not what I wanted.
Please let me know how I can create a query or expression to achieve this.
Thanks
Comment: @jeroen please see what I had tried and what came up as result.
Comment: Please update your question. What is the specific problem? What have you tried so far and why didn't it work?
Comment: please post you table structures and sample data to help you out..
Answer: Instead of union you can use the join.
In this case your code will be like the following:
select coalesce(q1.desc, q2.desc) as desc,
       q1.amount as amount, q2.amount1 as amount1
from
(
   select
   a.desc  as desc
   ,sum(bdd.amount) as amount
   from t_main c
   left outer join t_direct bds on (bds.mainId=c.id)
   left outer join tm_defination a on (a.id =bds.defId)
   where c.descId=1000000134
   group by a.desc
) q1
full join
(
    select
    a.desc as desc
    ,sum(bdd.newAmt) as amount1
    from t_main c
    left outer join t_newBox b on (b.mainId=c.id)
    left outer join t_transition c (c.id=b.tranId)
    left outer join tm_defination def a on (a.id =c.defId)
    where c.descId=1000000134
    group by a.desc
) q2
  on q1.desc = q2.desc
order by 1

Because of the same table usage for the desc column source, coalesce function can be used. The result query will be ordered by the result desc column.

Combining two join queries into one


Why I estimate huge RR?

Question: I am trying to do an excercise about temperature related mortality. I want to plot exposure-response curve, identify the temperature threshold and estimate Relative Risk of mortlaity above this threshold. I work with daily data. I use GLM model(packages:nlme,splines) and DLNM package to build a crossbasis matrix for temperature and lags:

<code>model<-glm(daily_mortality~cb+ ns(time,df=7)+dow, family=quasipoisson, data)
time=1:length(data$date) #to control for long-term and seasonal trends
dow<-as.factor(weekdays(data$date))
cb<-crossbasis(data$Temp,lag=21,argvar=list(knots= equalknots(data$Temp, df=5)), arglag=list(knots=logknots(21,3,df=4)))

pred<- crosspred(cb, model, cen=median(data$AvgTemp), cumul=TRUE)

plot()
plot(pred, "overall", ylab="cumulative RR", xlab="Temp", ylim=c(0.5,4),col=2,lwd=2)

pred$cumRRfit
pred$allRRfit
</code>
One of my problems is that I estimate huge allRRfit and cumRRfit which I think is wrong.
Can anyone guess why or suggest me a paper/book to read (I have read everything of Gasparrini)?
Answer: It is unclear if your data is intended to be actual data or a generated sample data to test your problem solving program.
If the units are intended to be Celsius, the temperature columns still appear to be very low, all near freezing. You state this is daily data, so I infer the min and max temp are intended to be the weather on those days, but the difference between high and low is only 3 or 4 degrees, so that seems like a very unusually low span of temperature for typical weather. Normally one would expect a range of maybe 15 degrees? Is it possible the min column should actually be negative (below freezing)?
In any case, I would start by looking if the data has been loaded correctly from this sample.
Comment: It is sample data.. Now I also noticed that Average Temperature is not equal to (MaxTemp+MinTemp)/2.  But I estimate huge RR either I use Average Temp or Max or Min.. I am not sure that the parameters I take are correct..

Why I estimate huge RR?