specific column filter with data tables

Question:

I am new to jquery programming. when I viwew the table in browsers I see the error:

Data Tables warning (table id = 'example'): can not reinitialise Data
  Table. To retrieve the data table object for this table, pass no
  arguments or see the  docs for bRetrieve and bDestroy

how to solve this  problem??
Answer: You are trying to initialize the same table twice.  First you are running
 $(document).ready(function() {
    $('#example').dataTable( {
         "sPaginationType": "full_numbers",

    } );
} );

Which is trying to initialize datatables on the table with the ID of example.  Then you try to initialize it again here:
var oTable = $('.exam').dataTable( {
        "oLanguage": {
            "sSearch": "Search all columns:"
        },
        "bStateSave": true,
        "fnInitComplete": function() {
            var oSettings = $('.exam').dataTable().fnSettings();
            for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
                if(oSettings.aoPreSearchCols[i].sSearch.length>0){
                    $("tfoot input")[i].value = oSettings.aoPreSearchCols[i].sSearch;
                    $("tfoot input")[i].className = "";
                }
            }
        }
    } );

Here you are initializing a table with the class of exam.  The table with the class exam, and the ID of example are the same table in this case.  The error is basically saying, hey I already initialized this table once, I cant do it again.
Remove the first block of code and it should solve your problem.

specific column filter with data tables


How many ways are there to select a collection of 10 coins chosen from very large bags of coins with face values 100, 200, 500 and 1000?

Question: How many ways are there to select a collection of 10 coins chosen from very large bags of coins with face values 100, 200, 500 and 1000?

If you consider your equation $+++=10$, with $x\geq 0$, $y\geq 0$, $z\geq 0$, $w\geq 0$b but I don't know if  this is the right way to find the solution
Comment: Why? I don't understand
Comment: https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)
Answer: By "stars and bars" the number is
$$N=\binom{10+4-1}{10}=286.$$
Answer: I would first simplify this problem by saying we are picking 14 coins, with at least one of each denomination; this has the same number of possibilities, but I think can more easily be calculated.
Imagine we are deciding which of each type of coin we will choose by visualising the 14 coins lined up; we then need to place three separators in the gaps between them, the separators themselves being identical, but the number of coins counted from the left to the first seperator gives the number of say 100 valued coins, then between the second and third the number of 200, etc., and from the last seperator to the end of the coins, the number of 1000 valued coins.
So this is $\binom{13}{3}$, since there are 13 gaps and 3 separators. Note that two separators can't be in the same gap (which would correspond to not picking any of one of the denominations). Sorry if I didn't explain that very well, it's late!


Consistent cluster labels after several runs of algorithm

Question: When running a clustering algorithm several times (e.g. k-means) I get different assignment of labels for the same clusters (that is understandable since labels are just symbolic). Is it possible to get all the time the same labels for the same data points after running clustering algorithm again and again?
Answer: Compare each cluster with each other cluster.
Reassign the same label by best match.
There is no better way to do this.
However, do not expect k-means results to be too similar. In particular on difficult data sets, results tend to vary a lot. At some point, there is no use in trying to make labels "consistent" when the clusters are 90% different on the "best" match. In the end k-means is a randomized algorithm, so expect it to return very different results (that is a strength, not a bug).
Answer: In most statisticals softwares/programming languages (R,Python,C#...), you can set the seed to a fixed number so that the random number generator of your program produces the same sequence of random numbers at each run. In R, this looks like set.seed(12), where 12 is your seed.
Random number generator are not that random, what they usually do is take DateTime.Now.Milliseconds as a seed, and start generating random number from there, explaining the non reproducible results.
Comment: Thanks for the answer! I was more interested not in a technical solution but rather in the method of association. I know that there are some methods that allow to associate cluster labels, but unfortunately dont know which of them are effective.


More shallow network outperformed a deeper one in accuracy?

Question: While trying to train different architectures of Convolutional Neural Networks (CNN) for a binary classification task (part of my undergraduate research, the statistical methods gives only 56% accuracy so I gave CNNs a try), there was a very strange thing: a relatively shallow network outperformed a deeper one!
The "shallow" network that I am talking about is the following:
32conv3x3 - mp2x2 - 32conv3x3 - mp2x2 - 64conv5x5 - mp2x2 - fc32 - fc32 - o

where conv denotes a convolutional layer, mp is max-pooling layer, fc is fully-connected layer, o is a one-neuron output (0 is one class, 1 is another class).
The one above resulted an accuracy of 66% on my task, while the "deeper" ones like VGG-11 and VGG-13 (actually I reduced the number of filters/neurons for each layer. Sorry, can't go deeper and wider on my no GPU core-i7 laptop) seems to get stuck on 55% accuracy already after 50 epochs (which is equal to the accuracy achieved by using statistical methods), I trained them for 300 epochs a few times.
Of course, I made sure that the samples from two classes used for training is balanced (so the network is not biased/overfitted towards one class). I am using ReLU as activation function and RMSProp as an optimizer. I am also using Dropout for regularization.
My guess is:

The learning rate for deeper networks are so small that it got stuck at a local minimum (the weight space in "deeper" architecture is smoother and has very vast "valleys" with local minimas), but doesn't Dropout intended to solve such problems?
300 epochs is too small for such a deep network, and it needs to be trained longer to converge. But again, the objects that I am classifying are cell's nuclei images, so I don't think that it needs super deep networks with a super long time to train (such as those that are used to classify 1000+ different objects like cats, dogs, donkeys, etc.).
Maybe I need to take a better look on the data for any corruptions. But again, I have checked them for any obvious biases, and normalized the nuclei images (after filtering out the background using computer vision methods and assigning background pixels to 0) to the range [0-255].

Can anyone with more expertise in this field give me a hint on what really is going on? Any guess (not nessesary sure answers) is appreciated! Thank you in advance!
Answer: This is a well known phenomenon. A good discussion can be found in the Deep Residual Learning for Image Recognition, especially Figure 1. The short summary is that when a neural network is very deep for a given problem, it tends to try and recreate the identity. This is because the first portion of the network has found an effective set of weights that optimize the objective, and now the latter portion of the neural network is essentially adding noise. So the latter portion will attempt to create an identity function, which is terrible because you're trying to make an identity function from a nonlinear set of activations. As an analogy, it's like approximating a line with polynomials of degree >1: you get a wavy mess. The above paper proposes ResNet, which is a deep neural network that allows you to skip over activations, which significantly improves the quality of deeper neural nets.
Comment: Thank you for your hint for this problem. There is a common stereotype that "deeper is better", but according to your answer, the reality is otherwise? (Btw If there will be no better answers in few days, I will mark yours as "correct" one).
Comment: Not quite. Deep neural networks are harder to train using naive techniques, and the above paper shows how to make it tractable. Note that resnet is huge, well over 50 layers, compared to VGG!
Comment: Also see this now classical paper: Understanding the difficulty of training deep feed forward neural networks - Bengio, Xavier:
http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf
Comment: Do the "first" and "latter" portion refer to earlier and deeper layer, respectively?


Proving $\mathbb{R}^\mathbb{N}$ ~ $\mathbb{R}$

Question: I am trying to show $\mathbb{R}^\mathbb{N}$ ~ $\mathbb{R}$ using the Cantor Bernstein method. Here is my proof so far:
Let $f: \mathbb{R}\to\mathbb{R}^\mathbb{N}$ be defined as for each $r_n\in\mathbb{R}$ where $n\in\mathbb{N}$, $f(r_n)=(r_n,0,0,...)$. Thus, we have an injection from $\mathbb{R}$ to $\mathbb{R}^\mathbb{N}$. (For me, $0$ is in the natural numbers.)
Now, for the other direction, let $g:\mathbb{R}^\mathbb{N}\to\mathbb{R}$ be defined as follows. Let $(r_0,r_1,...,r_n,...)\in\mathbb{R}^\mathbb{N}$ where $r_n\in\mathbb{R}$ and let $r_n=Z_n.a_{0,n}a_{1,n}a_{2,n}...$ be the unique corresponding decimal expansion where $n\in\mathbb{N}$,  $Z\in\mathbb{Z}$, $0\leq a_{n,n}\leq 9$, and the sequence does not end in infinitely many 9's.
Consider the list:
$r_0=r_n=Z_0.a_{0,0}a_{1,0}a_{2,0}...$
$r_1=r_n=Z_1.a_{0,1}a_{1,1}a_{2,1}...$
$r_2=r_n=Z_2.a_{0,2}a_{1,2}a_{2,2}...$
Then, let $r=0.a_{0,0}a_{1,0}a_{0,1}a_{0,2}a_{1,1}a_{2,0}...\in\mathbb{R}$.
So, $g((r_0,r_1,...,r_n,...))= r$.
Then, we have an injection from $\mathbb{R}^\mathbb{N}$ to $\mathbb{R}$. By Cantor Bernstein Theorem, $\mathbb{R}^\mathbb{N}$ ~ $\mathbb{R}$.
Does this proof work or how can I modify/improve it?
Comment: Hi, what you mean by $r_n$?
Comment: @sti9111 Okay, I defined it.
Comment: If you look around, you can probably find a more general proof of the fact, that if $X$ is an infinite set and $n$ is a natural number, then $X^n \simeq X$, and then adapt the proof to this situation.
Comment: @DuncanRamage Okay, but does what I have here not work then?
Comment: A nit:  you need to biject $\Bbb R$ with $(0,1)$ because you have not dealt with numbers before the decimal point.
Comment: @RossMillikan I am not sure what you mean? Would it be best then to do an injection from $(0,1)^\mathbb{N}$ to $\mathbb{R}$ instead since we know $\mathbb{R}$~$(0,1)$?
Comment: Just that your work only deals with numbers to the right of the decimal point.  There are lots of numbers in $\Bbb R$ that have digits to the left of the point.  We know $\Bbb R$ is equinumerous with $(0,1)$ so that is not a problem.  You can just chain your favorite bijection to get to $(0,1)$, then go to $(0,1)^{\Bbb N}$, then use the inverse bijection to get $\Bbb {R^N}$
Comment: @RossMillikan Okay, I think I see the issue but I am not clear on how to fix this. Why do we need the bijection in this case if we just chose to use $(0,1)$ instead?
Answer: Maybe, for the first direction you want to express the following, given $r\in\mathbb{R},$ this have the form $a_0,a_1a_2\dots$ where every $a_i$ is a digit, then we can define $f(r)=(a_0,a_1,\dots,a_n,\dots)$
the second part is o.k
Comment: I see, so you are turning an element in $\mathbb{R}$ into a sequence of its decimal expansion?
Comment: Yes!!! that´s the idea.
Comment: Okay, but then does what I have not work for that direction?
Comment: But we have to take care with numbers as 0.99999999.... and 1.0000000...,
Comment: I said it does not end in infinitely many 9s.
Comment: the firts direction works, I only want to give a proof using an idea to build both functions. The second direction I don´t understand what you did.
Comment: Not, your o.k, that´s the cantor diagonal idea. is. ok
Comment: Okay, then the second part works? What do you not understand so I can clarify.
Comment: I only was confused with the notation, but is o.k.
Comment: Oh okay, but yes I basically did the Cantor Diagonalization to create an element in $\mathbb{R}$.


Looking for simple, continuous differentiable decreasing function example that satisfies several conditions

Question: Is there some simple function of $c(s)$
  defined on $s\in[0,1]$
 , which is continuous, differentiable and decreasing in s
  such that $$-\frac{\frac{d\left(c(s)\right)}{ds}}{\frac{c(s)}{s}}>1+\frac{sc(s)}{\int_{s}^{1}c(s)ds}$$
 satisfied at some $s_{0}$
  in [0,1]
 ?
I studied the question again and find that the above question can be simplified as the following:
Is there a continuous, decreasing and differentiable function $c(x)\geq0$
  defined on $x\in[0,1]$
 , such that $$\omega(x)=\frac{x\,c(x)}{\int_{x}^{1}c(t)dt}$$
 is decreasing in $x$ at some $x_{0}\in[0,1]$
 ?
This way, we can view $xc(x)$ as a rectangle area below the curve of $c(x)$ and $\int_{x}^{1}c(t)dt$ another area below $c(x)$ curve. The question is exactly when $x$ increase, the rectangle area decrease faster than the integral area. Is there such a curve?
Comment: what is $\bar s?$
Answer: Yes.  We get:
$$ \omega'(x) = \frac{\left(\int_x^1 c(t)dt\right)[c(x) + xc'(x)] + xc(x)^2}{\left(\int_x^1c(t)dt\right)^2} $$
Suppose we want $\omega'(1/2)<0$.  So we want:
$$ \left(\int_{1/2}^1 c(t)dt\right)[c(1/2) + (1/2)c'(1/2)] + (1/2)c(1/2)^2 < 0 \quad (Eq *)$$
So just define $c(x)$ to have a very large (negative) derivative at 1/2, but that lasts for a short time only, so the integral $\int_{1/2}^1 c(t)dt$ is still significant. For example fix a small $\delta>0$ and define $c(x)$ so its derivative is:
$$ c'(x) = \left\{\begin{array}{cc}
-1 & \mbox{if $x \in [0, 1/2-\delta]$}\\
\mbox{tent(x)} & \mbox{if $x \in [1/2-\delta, 1/2+\delta]$} \\
-1 & \mbox{if $x \in [1/2+\delta, 1]$}
\end{array}\right. $$
where $tent(x)$ is a "tent" function such that $tent(1/2-\delta)=tent(1/2+\delta) = -1$ and $tent(1/2) = -M$ for some large value of $M$. You can choose $\delta$ much smaller than $1/M$ so the affect of the tent does not dramatically change the $c$ values for any of the terms in (Eq *) except for $c'(1/2)$.
For example if $c(0)=10$ and $\delta$ is very small, then $c(x) \approx 10-x$ for all $x \in [0,1]$, whereas $c'(x)=-M$, which is as negative as we like, so (Eq *) is easy to satisfy.
Comment: Thanks a lot. This is very close to my intuition. So basically we need a sharp drop of $c(x)$ at the point $x$, like a almost kink point, right? This is very helpful. Nonetheless, is it possible that we can find one such function which satisfies the conditions not only at one kind of kink point but at a larger range of $x$?
Comment: Since the functions and their derivatives are defined to be continuous, if the condition of (Eq *) holds at $x^*=1/2$, it will also hold for an interval about 1/2. You can play with $M$ and $\delta$ to make the interval bigger or smaller. The @nayrb answer is another possible approach, provided the $\omega(t)$ can be chosen so the solution gives $c(x)\geq 0$ and $c'(x)<0$ for $x \in [0,1]$.
Comment: That sounds right. The property should hold at the small interval around the picked $x^{*}$. If the @nayrb approach can deliver a more common (or simpler) solution of $c(x)$ without constructing the sharp drop part of the function, that would be much better.
Answer: You can pick your $w(x)$ and get your $c(x)$ by solving a differential equation.
Rewrite your expression as
$$\int_x^1 c(t) dt = \frac{1}{w(x)} x c(x)$$
and take a derivative to get
$$-c(x)=(x/w(x)) c'(x) + (x/w(x))' c(x)$$
which can be rewritten as
$$c'(x) + \frac{(x/w(x))'+1}{x/w(x)} c(x) = 0.$$
This is a 1st order linear differential equation and can be solved with an integrating factor.
Comment: Well, you would need to be careful that the resulting ODE solution $c(x)$ satisfies the nonnegative and decreasing properties for all $x$.
Comment: Thank you so much. I can further write the equation as: $$ c^{'}(x)+\left(w(x)/x+1/x-\frac{w^{'}(x)}{w(x)}\right)c(x)=0.$$ You mean that I can pick any value of $x$, $w(x)$ and $w^{'}(x)<0$ and then solve the ODE? In that case, the inequality will only be satisfied at the picked values, right? Can this be solved without picking specific numbers of  $x$, $w(x)$ and $w^{'}(x)<0$ so that the inequality is satisfied for a range of $x$, or even the entire $x\in[0,1]$? Sorry that I should know this, but my ODE knowledge is like zero. Thanks for your help!


Rails language persistent? Locale always routing to default_locale

Question: I recently started to work with Rails and I18n.
It seems that, in my app, when I send an Http request to move from one endpoint to another the selected I18n param is not persistent.
I.e.
I land on the homepage http://localhost:4000
I get redirected to the default language http://localhost:4000/en
I click a button "Español" to switch language preference
I got sent to http://localhost:4000/es
The text on the page is in Spanish
(So far behaves as expected)
I click on a button to get to another page of the app i.e. "video"
I got redirected to http://localhost:4000/en/video
The text on the page is in English
As can be seen, the language preference "es" is gone and now I got redirected back to the default one "en". My Rails version is 5.1.
Here is my routes.rb
Rails.application.routes.draw do
  scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
    root 'pages#home'
    get 'accommodation' => 'pages#accommodation'
    get 'afterparty' => 'pages#afterparty'
    post 'afterparty' => 'pages#create_afterparty'
    get 'afterparty/index' => 'pages#afterparty_index'
    get 'registry' => 'pages#registry'
    get 'rsvp' => 'pages#rsvp'
    post 'rsvp' => 'pages#create'
    get 'rsvp/index' => 'pages#rsvp_index'
    get 'video' => 'pages#video'
  end
  match '*path', to: redirect("/#{I18n.locale}/%{path}"), :via => [:get, :post]
  match '', to: redirect("/#{I18n.locale}"), :via => [:get, :post]
end

Here is my application_controller.rb:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :set_locale

  private

  def set_locale
    I18n.locale = params[:locale] if params[:locale].present?
  end

  def default_url_options(options = {})
    {locale: I18n.locale}
  end

end

Here is my locale.rb defined in the initializers directory:
# Where the I18n library should search for translation files
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]

# Permitted locales available for the application
I18n.available_locales = [:en, :es]

# Set default locale to something other than :en
# I18n.default_locale = :es

Here is an extract of application.html that shows the locale param assignation:
            <%= t('.language') %>
            <%= link_to_unless_current "English", locale: "en" %> |
            <%= link_to_unless_current "Español", locale: "es" %>

Here is an extract of application.html that exemplifies 2 of the anchor tags that redirect you to different pages:

Christina & Alex

            VIDEO

I tried several things unsuccessfully. Please help to clarify where I am wrong. Thanks.
Answer: The links and buttons in your application do not appear to carry the locale from default_url_options in them.
For instance, your link:
VIDEO

Does not use the locale param.
If you used the rails helpers, it will:
<%= link_to 'VIDEO', video_path, class: 'section' %>

Because the *_path and *_url helpers will merge the default_url_options,
and the final HTML will look like this:
VIDEO

Of course, you could add the locale param yourself, too.
Comment: Thanks Unixmonkey!
That was really useful. It makes sense and works.


Receiving json data from a server to display a chart.js graph not working

Question: I am working on displaying weather data received from a weather station as a graph using charts.js. The weather data i.e. 'temperature' and 'humidity' is to be received from the weather station server as json data.
I am using XMLHttpRequest method to receive the json data from the server. But when I store the json response in a variable and use it in charts.js' Charts() method, it doesn't display anything.
I have followed few tutorials and I can't figure out a problem at least how I am using XmlHttpRequat method to receive json data from the weather station sever. Perhaps problem may be with using stored jason value in a variable and then how to use it Charts method's 'data'.
Here is my code:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Weather Update</title>

    <link rel="stylesheet" href="style.css">

Weather Update

    <canvas id="myChart"></canvas>

EDITED CODE:
<!DOCTYPE html>

    <meta charset="utf-8">

    <title>Weather Update</title>

    <link rel="stylesheet" href="style.css">

Weather Update

    <canvas id="myChart"></canvas>

Comment: Have you tested that the JSON coming back isn't null/an expected structure? At least then you'll know if it's the data that's the problem or the graph rendering it.
Comment: `request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200){
        var wData = JSON.parse(this.responseText);
        var hum = wData.humidity;
    }
}` try like this. [https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp ]. And by the way, create the onreadystatechange function before opening and sending the request.
Comment: what is the object type of the humidity property of the return object?
Comment: it's a real or float value.
Comment: @Jay Gould: I haven't tested it but I am also thinking about it. And finding some way to test it before using. Though in some tutorials, this is the way used to get value from a json object after parsing.
Comment: @JayGould: in console.log, it showing all the values of json object in Wdata and Humidity value in hum, though not populating graph with hum data.
Answer: Use onreadystatechange instead of onload, don't use request.responseType = 'json'; and call open() and send() after declaring the onreadystatechange.
w3schools example
var requestURL = 'http://api.holfuy.com/live/?s=101&m=JSON&tu=C&su=m/s'; //URL of the JSON data
var wData, hum;

var request = new XMLHttpRequest(); // create http request

request.onreadystatechange = function() {
  if (request.readyState == 4 && request.status == 200) {
    wData = JSON.parse(request.responseText);
    hum = wData.humidity;

    console.log(wData);
    console.log(hum);
  }
}

request.open('GET', requestURL);
request.send(); // send the request

And by the way, you create the hum variable to store the data you received inside the callback function scope, so the variable hum does not exist when you are trying to create the chart. Create the variable before the ajax request and then populate it inside the callback, that way the variable will have value when you create your chart.
Comment: @Nikko it is not populating the graph with data because you initialize your graph **before** the data has been received. You have to put the graph initialization inside a function and call that function inside the `request.onreadystatechange`
Comment: it raises this error on console: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.holfuy.com/live/?s=101&m=JSON&tu=C&su=m/s. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Comment: I utilized this method from a SO post 'Alternatively, to try things out, you can prefix the URL with https://cors.io :'
https://stackoverflow.com/questions/46785318/the-cors-header-access-control-allow-origin-is-missing
Its removed the error but no value is shown for hum
Comment: in console.log, it showing all the values of json object in Wdata and Humidity value in hum, though not populating graph with hum data.
Comment: I kept graph code in this function and declared another function containing request.onreadystatechange to call the graph display function. But it's raising this error: TypeError: 48.6 is not a non-null object[Learn More] Chart.min.js:12:2901 TypeError: l._view is undefined[Learn More] Where 48.6 is current hum value. I put edited code in EDITED CODE in OP. Please see this
Comment: This worked for me! I thought you could just call `mychart.update()` but you have to make sure you setup the chart in a callback.


How to Install Cudatoolkit in python environment in dockerfile

Question: I need to Install the Cudatoolkit in Docker file which is Python environment but cudatoolkit can only install by conda parameter.
We cant use conda in python.
Or can I create a anaconda environment in docker file  and use python in anaconda?
Any solution !!
thanks in advance
Answer: In my case, I installed  pytorch  and  torchvision  through  pip  (from within the  conda  environment) and rest of the dependencies through  conda
The final  Dockerfile:
# Use nvidia/cuda image
FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04

# set bash as current shell
RUN chsh -s /bin/bash
SHELL ["/bin/bash", "-c"]

# install anaconda
RUN apt-get update
RUN apt-get install -y wget bzip2 ca-certificates libglib2.0-0 libxext6 libsm6 libxrender1 git mercurial subversion && \
        apt-get clean
RUN wget --quiet https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh -O ~/anaconda.sh && \
        /bin/bash ~/anaconda.sh -b -p /opt/conda && \
        rm ~/anaconda.sh && \
        ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \
        echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc && \
        find /opt/conda/ -follow -type f -name '*.a' -delete && \
        find /opt/conda/ -follow -type f -name '*.js.map' -delete && \
        /opt/conda/bin/conda clean -afy

# set path to conda
ENV PATH /opt/conda/bin:$PATH

# setup conda virtual environment
COPY ./requirements.yaml /tmp/requirements.yaml
RUN conda update conda \
    && conda env create --name camera-seg -f /tmp/requirements.yaml

RUN echo "conda activate camera-seg" >> ~/.bashrc
ENV PATH /opt/conda/envs/camera-seg/bin:$PATH
ENV CONDA_DEFAULT_ENV $camera-seg

The  requirements.yaml :
name: camera-seg
channels:
  - defaults
  - conda-forge
dependencies:
  - python=3.6
  - pip
  - numpy
  - pillow
  - yaml
  - pyyaml
  - matplotlib
  - jupyter
  - notebook
  - tensorboardx
  - tensorboard
  - protobuf
  - tqdm
  - pip:
    - torch
    - torchvision

Then I used the command  docker build -t camera-seg . to build the container  and PyTorch now recognises CUDA.


How to make setState with nested object

Question: How do I use setState if am having nested object. I have a json list using that I update this state. but Suppose if I want to update only a Phone Number field in this state then how  do I make it. Below code gives me error
this.setState(prevState => ({
   myData: {
             ...prevState.myData,
             user: { ...prevState.myData.user, PhoneNumber: value }
            }
}));

interface IData  {
    ID:number,
    usage:string,
    user:IUser
}

interface IUser{
    name:string,
    PhoneNumber:number
}

Comment: What's the error you're getting?
Comment: https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react
Comment: Possible duplicate of [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react)
Answer: The simplest way of doing this is to create a clone of the object that you want to update, then update that clone using javascript as you desire, then set the state using that clone object.
Like this:
let clone = {...objectInStateToUpdate};
  // Do operations on clone as desired
this.setState({objectInStateToUpdate: clone});
  // or if you named the cloned same as your object
this.setState({clone});

Hope it helps!

How to make setState with nested object


Closed form expression of $ \sum_{k=0}^n (3k^3 +2k^2 -3k +2) r^k {n \choose k} $

Question: Problem: Find an expression without summation for the following sum: $ \sum_{k=0}^n  P(k) r^k {n \choose k} $ , where $ P(k) = 3k^3 +2k^2 -3k +2 $.
Attempt: I managed to show that $  \sum_{k=0}^n  k(k-1) r^k {n \choose k} = n(n-1)(r+1)^{n-2}r^2 $ in a previous exercise ( by using derivatives ). Now I think I'm supposed to use this identity, so I tried in a similar fashion to get an useful expression when taking the derivative of $ \sum_{k=0}^n  r^k {n \choose k} $ three times. But first I tried to get an useful expression from the coefficient that I'll get as a result, so I did  as follows:
Note $ k(k-1)(k-2) = k(k^2 -2k-k+2)=k(k^2 - 3k +2 ) = k(2k^2 -3k+2 -k^2) = k(2k^2 -3k +2 ) -k^3 $
Also, $ P(k) -3k^2 = 2k^2 -3k +2 \iff k \cdot ( P(k) - 3k^2 ) -k^3 = k(2k^2 -3k +2 )-k^3 = k(k-1)(k-2) $. But I realized I've reached a dead-end since I got nothing useful.
Do you have any ideas? any help would be appreciated.
Note:  I can't use generating functions ( if it's even needed here ).
Comment: related https://artofproblemsolving.com/community/c6h571981p3362051
Answer: Hint: $3k^3 +2k^2 -3k +2=k(3k^2+2k-3)+2=k(2k^2+(k+3)(k-1))+2.$
Now $2k^2=2k(k-1)+2k$ and so
$$P(k)=k(2k(k-1)+2k+(k+3)(k-1))+2=k((k-1)(2k+k+3)+2k)=k(3(k-1)(k+1)+2k)+2,$$
this means that $P(k)=18\cdot \binom{k+1}{3}+2k(k-1)+2k+2=18\binom{k+1}{3}+4\binom{k}{2}+2\binom{k+1}{1}=18\binom{k}{3}+22\binom{k}{2}+2\binom{k}{1}+2.$
Now, split the sum in the four terms and show that $\binom{a}{b}\binom{b}{c}=\binom{a}{c}\binom{a-c}{b-c}.$ Use binomial theorem afterwards.
Note: This is a general technique, you can always express a polynomial in the monomial basis in terms of the falling factorial basis(binomials are particular polynomials there).
Answer: When you face a problem like $$S_n=\sum_{k=0}^n P_m(k) {n \choose k}r^k $$ is to consider that it involves the $m^{\text{th}}$ derivative of something and then to consider that is is a linear combination of terms like $k$, $k(k-1)$, $k(k-1)$,$k(k-1)(k-2)$ and so on.
So, use
$$k^2=k(k-1)+k \qquad \text{and} \qquad k^3=k(k-1)(k-2)+3k(k-1)+k$$
So
$$3k^3 +2k^2 -3k +2=3 \Big[k(k-1)(k-2)+3k(k-1)+k \Big]+2\Big[k(k-1)+k\Big]-3k+2$$ that is to say
$$3k^3 +2k^2 -3k +2=3k(k-1)(k-2)+11k(k-1)+2k+2$$
So, we have
$$S_n=3r^3\left(\sum_{k=0}^n {n \choose k}r^k\right)^{'''}+11r^2\left(\sum_{k=0}^n {n \choose k}r^k\right)^{''}+2r\left(\sum_{k=0}^n {n \choose k}r^k\right)^{'}+2\left(\sum_{k=0}^n {n \choose k}r^k\right)$$
What we could have also done is to write
$$3k^3 +2k^2 -3k +2=a k(k-1)(k-2)+bk(k-1)+c k +d$$
$$3k^3 +2k^2 -3k +2=a k^3+ (b-3 a)k^2+ (2 a-b+c)k+d$$ and comparing coefficients
$$a=3 \qquad b=11 \qquad c=2 \qquad d=2$$


ATP/WTA ranking during Grand Slam tournaments

Question: As far as I know, the ATP and WTA rankings work approximately this way: Each week the points for the tournaments played that week are added. The points for tournaments more than 52 weeks old are dropped. (Of course, there are more complicated rules about which and how many tournaments are counted, but this should be the gist of it.)
My question is what happens during Grand Slams, which last two weeks. Some players do not play at GS tournaments, so they might play some tournament during the first week. However, if the new ranking would be issued after one week of GS tournaments, what should be done? Dropping the points for the last edition of the same GS tournament seems unfair, since the players did not finish the tournament yet?

Is the new edition of WTA/ATP rankings issued after the first week of the GS tournament? Are the points for Grand Slams dropped/counted only after the two-week period, in which the tournament is played?
Answer: During Grand Slam events - new rankings aren't calculated after the first week. New rankings are calculated after the Grand Slam event is over, so after the end of those 2 weeks.
As far as rankings points go - the points expire (like you said, after 52 weeks) whether they play the same event the following year or not.


Get the original URI in ExceptionMapper

Question: I am using an ExceptionMapper in JAX-RS.
 public class MyException implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        ...
    }
}

all works. However, is there anyway I can get a handle to the URL, or the HTTP request that generated the exception?
Thanks
Answer: Inject UriInfo using @Context:
@Context
private UriInfo uriInfo;

Then use the getRequestUri() method to get request URI:
URI uri = uriInfo.getRequestUri();

Refer to this answer for other types that can be injected with @Context.
Answer: Use @Context in class and use it to get original request:
@Context
private HttpServletRequest request;
@Override
public Response toResponse(ConstraintViolationException exception) {
   String requestURI = request.getRequestURI();

Get the original URI in ExceptionMapper


How to properly set TXT SPF record when separating A from MX records

Question: I have current TXT record for my domain:

v=spf1 a mx ip4:{ip-of-my-server} -all

Both email traffic and website goes to same machine. Now, I have to point website (A record) to other server. Will it broke Sender Policy Framework - note the "a" in TXT record?
If so, should I just strip "a" form current TXT record or reconfigure current record differently, and how?
Comment: That's not how it works. [Please read up on SPF](http://serverfault.com/questions/369460/what-are-spf-records-and-how-do-i-configure-them) then come back if you have any additional questions.
Answer: The SPF record you have allows at least three entities to send mail claiming to be from your domain.
Using example.com as your domain, these entities are:

The IP address obtained when you ask for the A record for example.com
The IP address(es) obtained when you ask for the MX records for example.com and then ask for the A records of those addresses.
The IP address listed after the ip4: string.

At the moment, all of these are the same IP address.  After your proposed change, the A record for example.com will be a different IP address and that IP address will also be allowed to send email claiming to be from your domain.  The IP addresses pointed to by your MX records and the raw ip4: entry will also still be able to send email claiming to be from your domain.
All other IP addresses will be forbidden from sending email claiming to be from your server. This is ensured by the -all at the end, which is a good thing.
TL;DR
In your case you don't need to change anything in your SPF when you change your web server's primary IP address.  You will still be able to send email and no one else will be able to pretend to be you.
Answer: You are mixing SPF with A and MX records.
Just create a new A reord for the hostname you want to point to the other server. Don't change the SPF record unless you have to (e.g. add a new IP etc.).
The snippet you posted is correct SPF syntax. In fact it contains the string A MX but this is not related to A and MX records nor does it have such an effect in means of DNS records.
I'll try to explain this using some dig snippets
Let this be the SPF record
;; ANSWER SECTION:
mydomain.tld.       14400   IN      TXT     "v=spf1 +a +mx +ip4:88.xxx.xxx.xxx ?all"

Then we usually got the following records that are independent from the above snippet. A SPF record can never replace missing A/MX records nor does it affect those record types in any way.
Let this be the A record of my example (webserver)
;; ANSWER SECTION:
mydomain.tld.       600     IN      A       109.xxx.xxx.xxx

This is redirecting clients requesting mydomain.tld to the host with the IP 109.xxx.xxx.xxx
And this is what makes mails arrive on the mailserver @ 88.xx.xx.xx
;; ANSWER SECTION:
mydomain.tld.       14400   IN      MX      10 mail.mydomain.tld.

;; ADDITIONAL SECTION:
mail.mydomain.tld.  600     IN      A       88.xxx.xxx.xxx

The MX for mydomain.tld is pointing at the A record mail.mydomain.tld.
As a result mail is being sent to the mailserver with the IP 88.xxx.xxx.xxx


Push notifications from Web server to android application

Question: Hello to everyone who is viewing this question. I think this question might be quite abstract, but I couldn't find the correct answer by googling.
I am trying to make an application like Starbucks Siren-Order.
Our android applications are made in Android-Java, and we are also developing a web-server which is also
written in Java, using Spring-MVC.
Once a customer makes an order using this application(which is for customers), I want to make push notifications appear in Store-Owner-Application. I was thinking about using WebSocket, but is Firebase a great alternative for websocket in this case? I never used neither WebSocket or Firebase before.
Just asking for some tips and advice. Thank you :)
Answer: in simple cases, Firebase is a much better alternative to implementing it yourself using WebSocket.
That's because Firebase already has a battery draining constantly open socket to handle its notifications, and since most apps use it rather than creating a new socket, it helps conserve battery and other resources.
There are a few exceptions though..
Firebase isn't perfect, it allows sending messages to the client most of the time, and in some cases, your notification will be delayed, or won't get delivered at all.
For example:

If the battery is low
if the device received many push notifications recently

If you need a simple 99% solution to sending push notifications that is easy to implement and won't waste battery - Go with Firebase.
If you have to have full control over your notifications and need them delivered all the time, as soon as possible, consider implementing it yourself.
Comment: of course. Firebase (or in this case, Firebase Cloud Messaging - FCM) is simply a tool that allows you to send messages from your server to your mobile clients.

You can send any String you want, in whatever format you want it, parse it in your client and do whatever you want with it there
Comment: I have to make contents of push notifications by parsing JSON string. Is it possible to do so using firebase? I've never used firebase before..


Javascript: Problemas ao executar uma função. Como melhorar o código feito?

Question: Olá, estou fazendo um curso introdutório de JavaScript e, embora eu consiga imprimir o resultado desejado pelo exercício, a plataforma não reconhece meu código. Gostaria que me ajudassem a melhorar o código ou me oferecessem alternativas em que eu pudesse continuar usando conceitos introdutórios sobre JavaScript.
A questão é: "Programe uma função buscarDivisivelPor que recebe dois parâmetros, um array de números e um número de teste, retornando como resposta o primeiro número do array que seja divisível pelo número dado e diferente de zero. Caso nenhum número do array passe no teste, retorne o texto "Nenhum número válido encontrado!"".
Os erros apontados pela plataforma são:
Para o array [0, 9, 4, 7, 128, 42, -1, 301, -5] e num = 2 a reposta deve ser 4
Para o array [0, 9, 4, 7, 128, 42, -1, 301, -5] e num = 7 a reposta deve ser 7
Para o array [0, 9, 4, 7, 128, 42, -1, 301, -5] e num = 8 a reposta deve ser 128
Meu código:
function buscarDivisivelPor(array, num)
{
  // Escreva abaixo o seu código:

  var invalido =[];

  for(var i=0; i<=array.length;i++){

     if (array[i] % num == 0 && array[i] != 0) {

        var valor = 0;
        valor = console.log(array[i]);

         break;

         return valor;

      } else {

         invalido.push(array[i]);
      }

      if (array.length == invalido.length){

         return "Nenhum número válido encontrado!";
      }
   }
}
console.log(buscarPorDivisivel([0, 9, 4, 7, 128, 42, -1, 301, -5],2));

Comment: Isto responde à sua pergunta? [Retornar divisível por número em um array](https://pt.stackoverflow.com/questions/461011/retornar-divis%c3%advel-por-n%c3%bamero-em-um-array)
Answer: Segue uma possível solução para o seu problema.
function buscarDivisivelPor(a, b) {
    for (let i = 0; i < a.length; i++){
        if (a[i] !== 0 && a[i] % b === 0) {
            return a[i]
        }
    }
    return "Nenhum número válido encontrado!"
}

Poderiamos implementar uma versão utilizando o método filter do tipo array, da seguinte maneira, a função find vai retonar o primeiro elemento que a cumpra a condição passada pela função auxiliar:
function buscarDivisivelPor(a,b){
    c = a.find(x => x !== 0 && x % b === 0)
    return c || "Nenhum número válido encontrado!"
}


If $a$ and $b$ are integers s.t. $2x^2 -ax + 2 > 0$ and $x^2 -b x + 8 \geq 0$ for all real numbers $x$, then the largest possible value of $2a−6b$ is

Question:
If a and b are integers such that $2x^2-ax+2>0$ and $x^2-bx+8≥0$ for all real numbers $x$, then the largest possible value of $2a−6b$ is
Answer: 36.
My attempt: Multiply the first inequality by 2 and second by 6. This gave $4x^2-2ax+2>0$ and $6x^2-6bx+48≥0$. Subtracting the second inequality from the first one, we get $-2ax+6bx≥2x^2+44$. This means $2a-6b≤(2x^2+44)/-x.$ Now how to move further. Am I going in the right direction?
Comment: You can't subtract inequalities at all...
Comment: Thanks for this. Could you explain as to why can't we subtract inequalities?
Comment: $2>1 \land 8>7 \not \implies -6 = 2-8 > 1-7 = -6$.
Comment: Ok. Got the idea. Thanks.
Comment: Actually you *can* subtract inequalities but you must subtract the *opposite* side.  If $a < b$ and $c < d$ then $a - d < b - c$.  You can do that because taking away a *LARGER* thing gives a smaller result.
Comment: In this case you'd get the probably useless $2x^2 - ax + 2 -0 > 0 - (x^2 -bx +8)$ or $2x^2 -ax + 2 > -x^2 +bx -8$.  .... which you already knew as $2x^2 -ax + 2 >0\ge  -x^2 +bx -8$
Answer: The discriminant for first must be $<0$ and for second $\leq 0$ so $$a^2-16<0\;\;\;\;{\rm and}\;\;\;\;b^2-32\leq 0$$
So $$ a\leq 3\;\;\;\;{\rm and}\;\;\;\;b\geq -5 \implies 2a-6b\leq 36$$
Comment: Because of >  in first and $\geq$ second inequality
Comment: That is in first case your parabole can not go below x-axsis, so it has no zeroes, that is if disciriminat is <.
Comment: In second case parabola can touch x-axsis so it can have at most one root
Comment: How do you determine that the discriminant has to be <0 and  ≤0 for the first and second respectively?
Comment: I understood this from this. https://www.quora.com/In-a-quadratic-inequality-why-is-the-discriminant-always-less-than-0#
Answer: Since these quadratic functions have a positive leading coefficient, they have a minimum on $\bf R$, and we know the extremum of a quadratic function $p(x)=Ax^2+Bx+C$ is attained at $x=-\dfrac B{2A}$, so the function  is positive (resp. non-negative) for all $x$ if and only if $A>0$ and $p\Bigl(-\dfrac B{2A}\Bigr)>0\:$ (resp. $\ge 0$).
Here the hypotheses yield
\begin{cases}2\Bigl(\dfrac a4\Bigr)^2-\dfrac{a^2}4+2>\iff2-\dfrac{a^2}8>0\iff a^2<16, \\[1ex]
\Bigl(\dfrac b2\Bigr)^2-\dfrac{b^2}2+8\ge 0\iff 8-\dfrac{b^2}4\ge 0\iff b^2\le 32,
\end{cases}
Therefore we have $-4<a<4\;$ and $\;-4\sqrt 2 \le b\le 4\sqrt 2$, so that
$$\left.\begin{matrix}-8<2a<8\\-24\sqrt 2\le -6b\le24\sqrt2\end{matrix}\right\}\Rightarrow -8(1+3\sqrt2)<2a-6b<8(1+3\sqrt 2).$$
Added:
This solution is for real $a$ and $b$.  If ˆ$a$ and $b$ are constrained to be integers, we have the same basic inequalities with $a^2$ and $b^2$, but now we have the equivalence
$$\begin{cases}
a^2<16\\b^2\le 32\end{cases}\iff \begin{cases}
|a|<4\\ |b|\le 5\end{cases}\iff \begin{cases}
-3\le a \le 3\\ -5\le b\le 5\end{cases}\iff \begin{cases}
-6\le 2a \le 6\\ -30\le -6b\le 30\end{cases}$$
so $\;2a-6b\le 36$.
Comment: That would be a good approach if $a,b$ being integers wasn't a condition. However in this case... stepping down to 36 from 41.94... won't be justified.
Comment: @Macavity: I've added the very simple  conclusion for integers.
Comment: Yes, of course that conclusion works.. +1
Answer: As pointed out in the comments, you cannot subtract inequalities since $a>0$ & $b>0$ does not imply $a-b>0$ (eg. $7>0$ & $8>0$ but $7-8<0$). You should go forward with such problems involving quadratic equations using discriminants as used in the solution above by @greedoid.


Prob. 9, Sec. 3.10 in Kreyszig's functional analysis book: The image of ann isometric non-unitary operator on a Hilbert space

Question: Let $H$ be a Hilbert space, let $T \colon H \to H$ be a linear operator such that $T$ is isometric but not unitary.
Then how to show that the image $T[H]$ is a proper closed subspace of $H$?
My effort:
Since $T$ is a linear operator, $T[H]$ is a (vector) subspace of $H$.
Since $T$ is isometric, for each $x \in H$, we have
$$ \langle Tx, Tx \rangle = \Vert Tx \Vert^2 = \Vert x \Vert^2 = \langle x, x \rangle.$$
If $H$ were complex, then $T$ would be unitary if and only if $T$ were isometric and surjective.
But $T$ is not unitary. So $T$ is not surjective. Thus $T[H]$ is a proper subspace of $H$. How to tackle the case when $H$ is real?
How to show that $T[H]$ is closed in $H$?
After reading @Braindead's comment:
Suppose that $y \in \mathrm{cl}(T[H])$. Let $y_n \colon= T x_n$ be a sequence in $T[H]$ such that $y_n$ converges to the point $y$. Then $y_n$ is a Cauchy sequence in $H$. And since $T$ is isometric, the sequence $x_n$ is also Cauchy in $H$, which is complete. So $x_n$ converges to some point $x \in H$. Again using the isometric property of $T$, we can conclude that $T$ is continuous, so that $T x_n$ converges to $T x$. But $Tx_n = y_n$. So $Tx = y$; that is, $y \in T[H]$, showing that $T[H]$ is closed.
Is the above proof correct?
Using th so-called polarisation identities, we obtain, for all $x, y \in H$,
\begin{align*}
\langle Tx, Ty \rangle & = \Re \langle Tx, Ty \rangle + \iota \Im \langle Tx, Ty \rangle \\
&= \frac{1}{4} \left( \Vert Tx + Ty \Vert^2 - \Vert Tx - Ty \Vert^2 \right) + \frac{\iota}4 \left( \Vert Tx + \iota Ty \Vert^2 - \Vert Tx - \iota Ty \Vert^2 \right) \\
&= \frac{1}{4} \left( \Vert T (x + y) \Vert^2 - \Vert T ( x - y) \Vert^2 \right) + \frac{\iota}{4} \left( \Vert T (x + \iota y) \Vert^2 - \Vert T ( x - \iota y) \Vert^2 \right) \\
& = \frac{1}{4} \left( \Vert x + y \Vert^2 - \Vert x - y \Vert^2 \right) + \frac{\iota}4 \left( \Vert x + \iota y \Vert^2 - \Vert x - \iota y \Vert^2 \right) \ \mbox{ [ since $T$ is isometric ]} \\
&= \Re \langle x, y \rangle + \iota \Im \langle x,y \rangle \\
&= \langle x, y \rangle.
\end{align*}
If $H$ is real, there would be no terms involving the $\iota$.
Thus, irrespective of whether $H$ is real or complex, using the definition of the Hilbert adjoint operator $T^*$ of $T$, we have
$$\langle T^* Tx, y \rangle = \langle Tx, T y \rangle = \langle x, y \rangle \ \mbox{ for all } \ x, y \in H.$$
This implies that $$T^* T x = x \ \mbox{ for all } \ x \in H,$$
and so $$T^*T = I. \ \tag{equation 1}$$
Now if $T$ were also surjective (i.e. if $T[H]$ were all of $H$), then $T$ would be bijective (and so $T^{-1}$ would also exist) and in that eventuality, we would obtain
$$TT^* = TT^*I = TT^* (TT^{-1}) = T(T^*T)T^{-1} = T I T^{-1} = I,$$
which together with equation (1) would imply $T^* = T^{-1}$ and hence $T$ would be unitary, contrary to our hypothesis.
Comment: Given a sequence in $T[H]$ that converges in $H$, can you show that the limit must belong to $T[H]$?
Comment: @Braindead, how to show that if $H$ is a real Hilbert space and if $T \colon H \to H$ is an isometric linear operator such that $T$ is not unitary, then $T[H]$ is a proper subspace of $H$?
Comment: That, I am not sure. How does the proof for the complex case go?
Comment: @Braindead, please have a look at my edit.
Comment: Looks fine to me. So it seems that the main thing you needed to prove non-surjectivity is $(Tx,Ty) = (x,y)$.
Answer: Your proof is correct.  Here is a slightly shorter way to do the last step (once you have $\langle Tx,Ty\rangle=\langle x,y\rangle$).  Suppose $T$ is surjective.  Then it is bijective, since any isometry is injective.  Now note that for any $x,y\in H$, $$\langle Tx,y\rangle=\langle Tx,T(T^{-1}y)\rangle=\langle x,T^{-1}y\rangle.$$
By definition of adjoints, this means $T^*=T^{-1}$.
Comment: which grad school have you dropped out from? Were you a PhD student?
Answer: In general, an isometric linear operator satisfies $T^*T = I$.
By polarization identity we have $\langle Tx , Ty \rangle = \langle x ,y \rangle$, then $\langle Tx,Ty \rangle = \langle x,T^*Ty \rangle $, ie., $\langle x,(T^*T-I)y\rangle = 0$ for all $x,y$. Then $T^*T = I$.
In your case, if $T$ is subjective, then $T^{-1}$ exists and
$$T^{-1} = I T^{-1} = (T^*T)T^{-1} = T^*$$


Hypergeometric distribution - the formula works, but WHY?

Question: While studying the hypergeometric distribution, I came up with this formula below that yields the same numerical result of the standard formula, but looks completely different!
Why are the two formulas equivalent? HELP!
I don't get the intuition why they are equivalent, probably I don't understand the hypergeometric enough yet :/
Definitions:
$\ N$=total marbles in the urne
$\ G$=green marbles in the urne, among the $\ N$ total in the urne
$\ n$=marbles drawn for the urne
$\ g$=green marbles, among the $\ n$ marbles drawn for the urne
Standard formula:
$\ P(X=g) = \frac{{G \choose g}  {N-G \choose n-g}}{{N \choose n}}$
Alternative formula:
$\ P(X=g) = \frac{{n \choose g}  {N-n \choose G-g}}{{N \choose G}}$
I derived it starting from:
$\ P(X=g) = \frac{D \times R}{A}$
where:
$\ A$=combinations of all $\ N$ marbles in the urne = $\ {N \choose G}$
$\ D$=combinations of $\ n$ drawn marbles, containing $\ g$ green marbles = $\ {n \choose g}$
$\ R$=combinations of $\ (N-n)$ remaining marbles, containing $\ (G-g)$ green marbles  = $\ {N-n \choose G-g}$
Answer: $$
\frac{\frac{\color{blue}{G!}}{\color{red}{g!}(G-g)!}\frac{\color{blue}{(N-G)!}}{\color{red}{(n-g)!}(N-G-n+g)!}}{\frac{\color{blue}{N!}}{\color{red}{n!}(N-n)!}}
=\frac{\color{red}{\frac{n!}{g!(n-g)!}}\frac{(N-n)!}{(G-g)!(N-n-G+g)!}}{\color{blue}{\frac{N!}{G!(N-G)!}}}.
$$
Comment: thanks! I had made a mistake in the expansion of the two formulas, that's why I couldn't find the equivalence. Your clear expansion helped me find that mistake :)


Changing Idle time for server 2003

Question: I have a user using quickbooks 2013 remotely from her house.  She logs in to our server and will be working but if she idles for too long the server makes her log back in. Normally this would be ok but not with quick books..
When she logs back in quick books tells her someone else is already in this file. I have to reset the user every time this happens.
Is there a way to fix the idle time with server 2003?
Also sometimes the user will go into quick book and buttons will be missing.. Again by me resetting her fixes the problem.
Thanks for the help
Comment: How are you "resetting" the user? Logging off her accounts?
Answer: Here's a TechNet article detailing how to adjust the timeout/disconnect settings:
http://technet.microsoft.com/en-us/library/cc758177(v=ws.10).aspx

Changing Idle time for server 2003


Drop down menu won't work with MasterPage

Question: So I am facing that problem for couple of days now and I really don't know where to start with this issue...
When I am trying to create the  hover DropDownMenu
It just won't work with the other stuff goes on my CSS file.
it shows the button itself (half of it) and when you hover. it does change his color but nothing really happends.
No list opened.
Picture of it
(The CSS copied from the w3s School code they offer)
Thanks for helping!
Hope to hear from you guys soon.
The MasterPage Code:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html>

    <title>Nua </title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="assets/css/main.css" />

    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>

    <form id="form1" runat="server">

        <% if (Session["Level"].ToString().Equals("-1"))
            { %>

                 Login
                   Register
                     About

    <%} %>
      <%--  This is the Drop down menu code--%>

             <%if (Session["Level"].ToString().Equals("1"))
               { %>

                                <button class="dropbtn">Here</button>

                                      Link 1
                                      Link 2

              <%} %>

        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>

    </form>

i hope I posted it right O-o
Comment: any html and css code?
Comment: The Css code is too long to upload it here :/
Comment: Please use then http://codepen.io/pen/
Comment: http://codepen.io/anon/pen/apmWBz (This is it? No clue about the Javascript. I am suppose to do a school project here and the teacher just wants us to copy things from her. Huge thanks for help tho)
Answer: Three things:

For .dropdown set display: inline-block - now it has full page width
For .dropdown .dropbtn set height: auto - now it gets 32px from styles for button
You lost below code, which shows menu on hover:
.dropdown:hover .dropdown-content {
    display: block;
}

Comment: Using your answer below: 1. It not exist, your `.dropdown` element is `div`, not `li`, so rule `li.dropdown` wouldn't work. 2. `.dropdown .dropbtn` is your button, I have no idea what you couldn't understand here. 3. You forgot to add this small piece of code I pasted here.
Comment: Hey!
Huge thanks!!!
I simply have no clue about these stuff and what they do. as I said earlier.
No one teaching me these and I am just trying to understand what I am doing while actually doing it (Lack of time a little bit)

Can you please explain me what's the difference between div and li?
Comment: `div` is a block element, let's say it is something like rectangle to keep content ;) `li` is a list element (like lists in MS office) - it should be inside list container like for example `` or ``
Answer: Lost you my friend.

.dropdown Display : inline-block - is already exist (?)
what .dropdown .dropbtn?
I lost code?
This is the DropdownMenu CSS code.

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-color: #555;
}

li {
    float: left;

}

li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
    background-color: red;
}

li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

You mean the code you just write down
.dropdown:hover .dropdown-content {
    display: block;
}

I need to add that to this code above ^^?
Thanks for help tho!
please explain.


How to calculate the trace and the determinant of a matrix given an annihilating polynomial?

Question:
Find the trace and determinant of the $5 \times 5$ matrix $A$ that satisfies the condition $$ \sum_{k=0}^{5} (k+1)A^k = 0 $$

My attempt relies on the fact that the given condition can be thought as its Cayley-Hamilton polynomial, since it can be written exactly as $P_5(A) = 0$. Considering this fact, I can also say that the characteristic polynomial of the matrix is $P_5(\lambda) = 0$. As check for my attempt, I tried to compute the roots of that polynomial with WolframAlpha, and discovered that the "sum of roots = $-\frac{5}{6}$" and "product of roots = $-\frac{1}{6}$". Those results are indeed the trace and determinant of $A$, as the book give me also the solution, but since I'm not able to find easily these roots (I was't able to find them at all!), I think that my attempt is wrong. Any suggestion?
Comment: Are you sure you wrote the sum correctly? What you wrote is equivalent to $A^5=0$.
Comment: @HappyDay you're right, I wrote wrong, the edit of ParclyTaxel is the correct one.. do you refer to this?
Comment: Use Vieta's formulas: https://en.wikipedia.org/wiki/Vieta%27s_formulas
The sum of the roots is: -(coefficient of A^4)/(coefficient of A^5)=-5/6
Comment: Wow that formula is a great tool! However.. can you review my attempt? I mean, beyond the brute search of all roots of the polynomial, is my reasonement for characteristic polynomial correct?
Comment: @giuliolib What makes you think you can find the roots of a quintic polynomial?
Comment: Unless your book has other constraints imposed on $A$, the trace/determinant need not be $-\frac56$ and $-\frac16$. This is because if $\lambda$ is any root of $P_5(\lambda) = 0$, then $A = \lambda I$ also satisfy $P_5(A) = 0$.
Answer: You need a bit more work to implement what you want. The fact that a polynomial of degree $5$ is zero on a $5\times5$ matrix is not enough to tell that it is the characteristic polynomial. For a simple example consider the $5\times5$ matrix $E_{11}$ (this is the matrix with $1$ at the $1,1$ entry and zero elsewhere). The characteristic polynomial of this matrix is $x^4(x-1)$. But since the minimal polynomial is $x(x-1)$, the polynomials $x^3(x-1)^2$,  $x^2(x-1)^3$, and $x(x-1)^4$ are also degree-five polynomials that annihilate $E_{11}$.
What works in this example to guarantee that your $P_5$ is indeed the characteristic polynomial of $A$ is that $P_5$ has five distinct roots. As mentioned by Macavity in the comments, one can do this by showing that the greatest common divisor between $P_5$ and $P_5'$ is $1$; that would show that $P_5$ has no common roots with its derivative, and thus guarantee that all roots are simple. When the five roots are distinct, you know that $P_5$ is the minimal polynomial, and being of degree $5$ it has to be the characteristic polynomial.
As for how to answer the question, over $\mathbb C$ the (monic version of) the characteristic polynomial is
$$
(x-\lambda_1)(x-\lambda_2)(x-\lambda_3)(x-\lambda_4)(x-\lambda_5).
$$
The independent term of this polynomial is $$(-1)^5\lambda_1\lambda_2\lambda_3\lambda_4\lambda_5=-\det A.$$ And the coefficient of $x^4$ is
$$
-(\lambda_1+\lambda_2+\lambda_3+\lambda_4+\lambda_5)=-\operatorname{Tr}(A).
$$
So, since the monic characteristici polynomial of $A$ is
$$
x^5 + \frac56x^4 + \frac46x^3 + \frac12x^2 + \frac13x + \frac16,
$$
it follows that
$$
\operatorname{Tr}(A)=-\frac56,\qquad\qquad\det A=-\frac16.
$$
Comment: Well one could always find  $\gcd(P_5, P_5')$ to check for multiple roots, say using the Euclidean algorithm...  +1 for bringing up the point though.
Comment: Good point, I should have noticed that but my algebra is fairly rusty.
Comment: Thus, I have some questions about these statements: 1) If the roots of any polynomial are all and only the eigenvalues of the matrix (with the correct multeplicity), I know for sure that is the characteristic polynomial (follows directly from the definition); 2) Special case: if all the roots of any "correct-degree" polynomial are distinct, then I know for sure that is the characteristic polynomial (how can I state that the roots are necessarly the eigenvalues?)
Comment: For example, in my specific case, how would I had say that $P_5(\lambda)$ have five distinct roots?
Comment: 1) Yes, that can be taken as the definition of the characteristic polynomial (usually, together with "monic" so that you have uniqueness). 2) Yes, but it depends on what "correct degree" means. The key facts are that the minimal polynomial divides any polynomial that is zero on the matrix, and that the roots of the minimal polynomial are simple and they are precisely the eigenvalues. Any polynomial $q$ with $q(A)=0$ will have the eigenvalues of $A$ as roots. Your particular $P_5$ has simple roots, so it has to be the minimal polynomial (the only way to reduce degree is to erase roots)
Comment: The reason it has to be the minimal (and characteristic, in this case) polynomial is that it is  of degree $5$ and divides the characteristic polynomial which is also of degree $5$.
Comment: As for how to say that it has distinct roots, either you find them somehow, or you show that it is coprime with its derivative.
Comment: Ok, I finally good with the concept itself.. but the practice remains difficult: in my example, I can't easily demonstrate that the polynomial is coprime with its derivative.. how can you show this?
Comment: It's not fun, but it is not too hard to do the Euclidean algorithm.
Comment: Yes, you're right, I was searching for an easy escape, but this way still seems to me as 'not much efficient/general'.. I mean let's suppose that the example asks for an $n \times n$ matrix with condition: $\sum_{k=0}^{5} (k+1)A^k = 0$ for every $n \in \mathbb{N}$.. or maybe with $n=2023$ (you know, those tricky tests). In those situations Euclidean algorithm still hold?
Comment: If it is a tricky test, there will be some smart way of finding out. If it is a natural question instead, writing software to perform the Euclidean algorithm is not hard (like [this](https://www.wolframalpha.com/widgets/view.jsp?id=18ca12c754852a11ca8ffbbeeee77b76)).
Comment: Ok, that's definitely a time-eater way to be doable in an exam, but I've convinced myself that this way is covering pretty general cases. Thank you for your time and dedication <3


What does this strange Jersey warning mean?

Question: What does this warning mean in Jersey 1.4:
<code>WARNING: A sub-resource method, public final java.lang.String com.XXX.render(),
with URI template, "/", is treated as a resource method
</code>
This is how the method looks:
<code>@GET
@Produces(MediaType.APPLICATION_XML)
@Path("/")
public final String render() {
  return "test";
}
</code>
Answer: Why do you need specify such path for method? @Get is enough to tell jersey that it is default method for entire class (I'm assuming that your class has some @Path("/MyRes") annotation).
Comment: @AlikElzin-kilaka the same thing, POST is handled by strictly specified URL, that can be formed by root + method
Comment: Great. So I conclude that just specifying '@POST' is enough and '@Path("/")'. Thanks.
Comment: @AlikElzin-kilaka depends on your task. If your class has only 1 method (or 1 method for each VERB) then it is ok
Comment: What's VERB? I have only one method that's defined as `@POST` without any `@Path`.
Comment: @AlikElzin-kilaka VERBs are: POST, PUT, GET, HEAD, DELETE
And then it is ok if you have only single method
Answer: Looks like you had the same problem last week with How to route JAX-RS request conditionally, depending on the suffix? - any luck fixing it there?
A look around on the net reveals you may have set-up your constructor incorrectly - have a read through http://jersey.576304.n2.nabble.com/Problem-using-the-JerseyTest-class-td3256608.html - someone who had a similar problem and was able to resolve it.
Comment: Yes, the problem is solved already, as suggested by Dewfy. Works perfect without this redundant `@Path("/")` annotation.


Do I need multithread in my program?

Question: My project is about fabricating a spin coater. Basically a machine that uses centrifugal for to cover a substrate  with micro thickness. Anyway, for this project, it requires me to key in time and speed of the motor uses to spin the substrate. Then read the rpm of motor, and the restart again for new session. My problem now is, how do I run the motor whilst the rpm is read using a sensor.   Let me go through the process of this machine,
Step 1: set speed of motor (using servo value of 103-180) and timing of motor in second( how long the motor need to spin).
In this step, there are 3 stages of speed and time setting. I need to key in the speed and timing of this stages using a keypad.
Step 2: spinning of the motor and rpm measurement reading
For this step, the  value of speed and time is turn into integer. This allow the motor to spin according to the time given. At the same time, as the motor spinning, the rpm measurement also start, reading the rpm of motor and display on the LCD screen.
Step 3:  motor stop and repeat step 1
Here is my problem, how do I make the motor to spin whilst rpm reading is taken?  Can i do it in single thread or multithread( hopefully won 't in multithread, still a beginner in arduino)
Comment: There is no threading on an Arduino.
Answer: Arduino doesn't have threads.  Threads are usually a feature of the operating system.  With Arduino, you don't have an operating system in the classic sense.
 Your code, including the libraries it uses, runs directly on the hardware.
The system is set up so that your loop function will be called over and over again.  The usual way of doing multiple things at once (like controlling the speed of the motor and reading a sensor and updating a display) is to do a little bit of each task during the loop.  In pseudocode it might look like this:
void loop() {
  int rpm = read_rpm_from_sensor();
  adjust_motor_timing(rpm, target_rpm);
  display_speed(rpm);
}

It seems like you also have phases: an initialization phase where the user enters values, a run phase, and a finished phase.  You can handle these by using a global "state" variable that keeps track of which phase your in.  You initialize your state in setup(), and then you read it in the loop() to decide what work you need to do.
enum { enter_values, run, finish } state;

void setup() {
  // your other initialization goes here
  state = enter_values;  // set up the starting state
}

void loop() {
  switch (state) {
    case enter_values:
      get_values_from_keyboard();
      state = run;
      break;
    case run:
      int rpm = read_rpm_from_sensor();
      adjust_motor_timing(rpm, target_rpm);
      display_speed(rpm);
      if (enough time has elapsed) {
        state = finish;
      }
      break;
    case finish:
      stop_motor();
      // go back to the initial state for the next run
      state = enter_values;
      break;
  }
}

That should give you an idea of the general structure.
For some types of sensors and peripheral devices that require very precise timing, you might use interrupts that deal directly with the hardware.  But that's a very similar idea:  you break the work you need to do into very small chunks that you can do over and over again.  The only thing that changes is that the interrupts may literally (briefly) interrupt whatever you were doing.  But the CPU is still doing just one thing at a time.
Comment: I understand your FSM  structure. In a big picture, I can see. So for all the functions, I have to write specific task for the function to work?
Comment: Yes, those were just placeholder functions to give you an idea of the specifics you would have to provide and where they fit into the structure.
When you implement them, make sure that you don't add any delay calls.  Each step has to finish in a reasonably short amount of time so that the other tasks that are happening "simultaneously" can do what they need to do.

Do I need multithread in my program?


Why does a header set via drupal_set_header() revert to text/html?

Question: I'm using the views_rss module in Drupal 6. Whenever I build out a View using this plugin, the following header is sent in a template_preprocess function:
drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');

This seems to be ignored, as the page is ultimately sent with a text/html header. It seems that my header is getting appended, but text/html is either sent first or last (whichever is ultimately interpreted by the browser) and thus has no effect.
How can I force a non-text/html header for a page output in Drupal 6?
Comment: Can you using curl -I and give me an output of list headers?

So i think in your site, you have other function output this header again, so the return headers have 2 'Content-Type' headers, that's the header come late will override the header come first.

I guess you will have 2 headers like this:

    Content-Type: application/rss+xml; charset=utf-8
    Content-Type: text/html; charset=UTF-8
Answer: I think you are too late in the template_preprocess hook. The views display will have set it's header already before your hook gets called.
To test my thought have a look at the return value of the function drupal_set_header. It shows you all headers sent before.
If I'm right: Try implementing a hook which is is called earlier (maybe even before execution of the view query). Then your header will have precedence.


Jquery Ajax não funcionando devidamente em Browser Mobile bem como em MacOS

Question: O Seguinte código funciona perfeitamente no Browser do Windows 10, mas não funciona no browser mobile Android/IOS completamente e no MacOS dá uma menssagem dizendo ao usuário de que não está funcionando bem. O problema parece estar em: success: function(result).
O resto do código funciona, a única coisa é que nao funciona é div $('#aviso'), por isso testei em partes isoladas. Quando executado em partes funciona, mas está dentro do código completo não.
$(function () {

    $("form[name='form-inscricao']").submit(function(e){
        e.preventDefault();

        var $form = $(this);

        var $inputs = $form.find("input, select, button, textarea");

        var serializedData = $form.serialize();

        $inputs.prop("disabled", true);

        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded; charset=UTF-8"
        });

        $.ajax({
            url:'https://www.example.com/wp-content/themes/example.com/enviar.php',
            type: 'post',
            dataType: 'html',
            data: serializedData,
            async: false,
            beforeSend: function(){
                $('.loader').show();
                $('#aviso').text('');
            },
            error: function() {
                console.log('Something went wrong');
            },
            success: function(result){
                $('#aviso').append(result).css({opacity:1.0}).delay(1000).animate({opacity : 0},500);
            },
            complete: function(){
                $('.loader').hide();
                $form.get(0).reset();
                $inputs.prop("disabled", false);

            }});

        });
});

Comment: Aqui é StackOverflow em Português, por favor, traduza sua pergunta, ou mova para o StackOverflow em Inglês.
Comment: Você editou a pergunta para que esteja em português, mas agora o problema não está claro. Defina "não funcionar".
Comment: Pode ser outros plugins ou scripts antes deste, dê detalhes por favor.
Answer: O problema estava relacionado ao protocolo HTTPS na URL, por alguma razão o Browser Mobile é redirecionado para a URL http sem o SSL enquanto o navegador não.
Desta forma o ajax não conseguia retornar a requisição para a URL correta. Tudo o que eu fiz foi deletar a parte da URL que incluia o http e deixar somente à partir da pasta raiz.
Obs: Este problema esta mais suscetível a acontecer quando se utiliza um framework PHP como o WordPress e não se escreve corretamente os Links e URLS do site, especialmente em scripts js como esse.
        $.ajax({
            url:'/wp-content/themes/example.com/enviar.php',


wordpress added unwanted margin below footer

Question: Nothing I found in the archives has worked for me, so hopefully you can help me find a solution.  I created my template in Dreamweaver, and have almost successfully transferred it all over to a wordpress theme, but now wordpress has added a small margin below the footer.
The margin doesn't appear on the original layout:
http://merrymeadowspagosa.com/post.html
But it IS on the template:
http://merrymeadowspagosa.com/
Any insight?
Answer: Nothing to do with wordpress. Pure css: your body element has a padding-bottom of 40px you need to remove. Inspect it with Chrome Dev Tools
Comment: oh jeez. Thank you!  Don't know where that came in to play!


fonts/glyphicons-halflings-regular.woff2 404 error

Question: Our drupal site uses fonts/glyphicons-halflings-regular.woff2 through bootstrap v3.3.2. But I am getting 404 for the file fonts/glyphicons-halflings-regular.woff2.
Is it some issue with the bootstrap? What is proper way to fix this?
Comment: What webserver and version?  Apache?  IIS?
Comment: we use Apache/2.2.15
Answer: wget https://github.com/metaskills/less-rails-bootstrap/raw/master/app/assets/fonts/twitter/bootstrap/glyphicons-halflings-regular.woff2
and move it to the openatrium/themes/oa_radix/assets/font directory.
Here: https://www.drupal.org/node/2625784


How to apply for loop in Django's views.py

Question: [research/models.py]
RECRUITING_CHOICES = [
    ('Recruiting', 'Recruiting'),
    ('Not yet recruiting', 'Not yet recruiting'),
    ('Completed', 'Completed'),
    ('Holding', 'Holding'),
]
RECRUITING_CHOICES_INV = {val: val for val, _ in RECRUITING_CHOICES}

class Research(models.Model):
    is_deleted = models.BooleanField(default=False)
    is_recruiting = models.CharField(choices=RECRUITING_CHOICES, null=True, max_length=50)
    research_name = models.CharField(max_length=2000, null=True)
    teacher= models.CharField(max_length=2000, null=True)

I'm using Django, and I'm trying to create a list for generating apexchart (graph) in views.py using a class model 'Research'.
I am trying to add each of the 4 values of the is_recruiting field to filtering , but adding Recruiting and Not yet Recruiting just takes multiple lines and makes the code look inefficient. Is there a workaround using the for statement?
[research/views.py]
counts = Research.objects.values('teacher') \
    .annotate(A=Count('id', filter=Q(type='A')),
              B=Count('id', filter=Q(type='B')),
              C=Count('id', filter=Q(type='C')),
              D=Count('id', filter=Q(type='D')),
              E=Count('id', filter=Q(type='E')),
              F=Count('id', filter=Q(type='F')),
              r_A=Count('id', filter=Q(type='A', is_recruiting='Recruiting')),
              r_B=Count('id', filter=Q(type='B', is_recruiting='Recruiting')),
              r_C=Count('id', filter=Q(type='C', is_recruiting='Recruiting')),
              r_D=Count('id', filter=Q(type='D', is_recruiting='Recruiting')),
              r_E=Count('id', filter=Q(type='E', is_recruiting='Recruiting')),
              r_F=Count('id', filter=Q(type='F', is_recruiting='Recruiting')),
              N_A=Count('id', filter=Q(type='A', is_recruiting='Not yet recruiting')),
              N_B=Count('id', filter=Q(type='B', is_recruiting='Not yet recruiting')),
              N_C=Count('id', filter=Q(type='C', is_recruiting='Not yet recruiting')),
              N_D=Count('id', filter=Q(type='D', is_recruiting='Not yet recruiting')),
              N_E=Count('id', filter=Q(type='E', is_recruiting='Not yet recruiting')),
              N_F=Count('id', filter=Q(type='F', is_recruiting='Not yet recruiting'))) \
    .values('teacher', 'A', 'B', 'C', 'D', 'E', 'F',
            'r_A', 'r_B', 'r_C', 'r_D', 'r_E', 'r_F',
            'N_A', 'N_B', 'N_C', 'N_D', 'N_E', 'N_F')

----------------------ADD---------------------------
[views.py - ADD]
teacher = [];
A= [];
B= [];
C= [];
D= [];
E= [];
F= [];
r_A = [];
r_B = [];
r_C = [];
r_D = [];
r_E = [];
r_F = [];
for count in counts:
    teacher.append(str(count['teacher']))
    A.append(str(count['A']))
    B.append(str(count['B']))
    C.append(str(count['C']))
    D.append(str(count['D']))
    E.append(str(count['E']))
    Ftc.append(str(count['F']))
    r_A.append(str(count['r_A']))
    r_B.append(str(count['r_B']))
    r_C.append(str(count['r_C']))
    r_D.append(str(count['r_D']))
    r_E.append(str(count['r_E']))
    r_F.append(str(count['r_F']))

is_recruiting = request.GET.get('is_recruiting')

[graph.html]

Do I have to list the if statements over and over in the JavaScript part?
Answer: You can build up dynamic keyword parameters to a function by creating a dictionary of the parameters and unpacking that dictionary as you pass it with **.
Loop over your types and for each one create keys and values for each annotation that you want for that type.
You can also unpack the dynamic annotations you created into field names to pass to values() using *
annotations = {}
types = ('A', 'B', 'C', 'D', 'E', 'F')
for type in types:
    annotations[type] = Count('id', filter=Q(type=type))
    annotations[f'r_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Recruiting'))
    annotations[f'N_{type}'] = Count('id', filter=Q(type=type, is_recruiting='Not yet recruiting'))
counts = Research.objects.values('teacher').annotate(**annotations).values('teacher', *annotations.keys())

Comment: Solved successfully. thank you very much ! I have one more question. I am outputting a list by returning the final extracted queryset with a for statement. This part is also inefficiently increasing the code, so I wonder how to shorten it.  (
Added a question.)
Comment: Do you require all the lists in separate variables, would a dict with all your lists as values similar to this do `{'A': [1, 2, 3], 'r_A': [4, 5, 6], ...}`?
Comment: Yes, that's right. Only 'is_recruiting' field is being applied differently.
Answer: Kwargs can be passed as dict, so all you need to do is to create a dict with these key: value pairs.
You could do sth like:
recruiting_values = (
    ("", dict()),
    ("r_", dict(is_recruting="Recruiting")),
    ("n_", dict(is_recruting="Not"),
)
types = ("A", "B", "C")

...

.annotate(**{
    f"{prefix}{type}": Count("id", filter=Q(type=type, **recruiting)) for prefix, recruiting in recruiting_value for type in types
})


Layout com largura 100% e/ou altura 10%

Question: Como  posso aplicar em minha aplicação para deixar a largura e/ou altura em 100% para iphone e Ipad?
tenho em minha aplicação navbar. textview, webview...
obrigado
Answer: Para criar um layout que seja compativel com Iphone e Ipads é necessario ter o conhecimento de Auto Layout.
Primeira coisa a ser definida na size class é a compatibilidade, nessa imagem ela seria para todos os dispositivos.

Na sua storyboard será necessario adicionar Constraints para cada componente pegar a sua altura e largura exemplo:

Selecionei as duas views green and yellow e adicionei uma constraint que fazem as duas possuirem a mesma largura, desta forma quando o dispositivo for Ipad ele se adaptará.
Aconselho dar uma estudada: Raywenderlich - Auto Layout
Comment: Ok amigo, mas preciso que seja ajustado pois quando coloco o tamanho no iphone não da certo, ele corta parte....
Comment: @AugustoFurlan leia esta parte "desta forma quando o dispositivo for Ipad ele se adaptará." isso serve para qualquer outro dispositivo, faça isso que funciona... valew

Layout com largura 100% e/ou altura 10%


Get rid of classes from views root container

Question: Looking for a way to clear all unnecessary in terms of semantic classes from top-level div for a view:

        ROWS

want to become:

        ROWS

I have tried Semantic Views and Fences but they all deal only with view content (field or rows) but not with the top-level div config.
I know that some bits can be changed with views-view.tpl.php however you can only clear all classes from it but I want to use css class from Views configuration.
Answer: You can use template_preprocess_views_view function and remove needles classes from  $vars['classes_array'] array.
function mymodule_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view') {
    $vars['classes_array'] = array('view', $vars['css_class']);
  }
}

Comment: In this case I wouldn't be able to set the class in a views setting (called CSS class).
Comment: You can add this class in array in template_preprocess_views_view
Comment: How do I find this class in an array? I want the class to be set from Views UI.
Comment: $css_class = $view->display_handler->get_option('css_class');
  if (!empty($css_class)) {
    $vars['css_class'] = preg_replace('/[^a-zA-Z0-9- ]/', '-', $css_class);
    $vars['classes_array'][] = $vars['css_class'];
  }
Comment: Sorry, I didn't get where I need to put this code. $view is undefined in the module.
Comment: $view = $vars['view'];
$css_class = $view->display_handler->get_option('css_class');
  if (!empty($css_class)) {
    $vars['css_class'] = preg_replace('/[^a-zA-Z0-9- ]/', '-', $css_class);
    $vars['classes_array'][] = $vars['css_class'];
  }
Comment: It is something I was looking for. Could you update your post with the following code so I can choose it as an answer:
  `$view = $vars['view'];

  $css_class = $view->display_handler->get_option('css_class');

  if (!empty($css_class)) {
   $vars['css_class'] = preg_replace('/[^a-zA-Z0-9- ]/', '-', $css_class);
   $vars['classes_array'] = array('view');
   $vars['classes_array'][] = $vars['css_class'];
  }`

Could you also tell why there is: `$css_class = $view->display_handler->get_option('css_class');`? Could we just use `$vars['css_class']`. It is there in $vars when hook is fired.
Comment: I have updated my answer. You are right we do not need to use $css_class = $view->display_handler->get_option('css_class'); because $vars['css_class'] is already added in https://api.drupal.org/api/views/theme!theme.inc/function/template_preprocess_views_view/7
Comment: Great! Sorry I brought you 666 points ;)
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/26107/discussion-between-andrew-and-valera-tumash).


Akaike Information Criterion I cannot interpret the result

Question: Maybe is a silly question, or maybe I'm doing something wrong.
I've tried to implement AIC criterion to estimate the optimum number of parameters using Auto Regressive (AR) linear models using white noise as input.
$$AIC(p) = N\log(RSS) + 2p,$$
where $N$ is the number of observations and $RSS$ the residuals sum of squares.
The results does not really make sense to me: since the predictors variables are completely indipendent, I would expect an increasing values of aic, so why do I see such a large oscillations?
<code>x = randn(100000,1);  % Generate white noise
for p = 1:30;
    Z = [];
    for z = 1:p;                            % Here I build the predictors variables
        Z = horzcat(Z, x(z:end-p-1+z));
    end
    [b,bint,r] = regress(x(p+1:end),Z);     % Linear Regression
    aic(p) = N*log(sum(r.^2)/N) + 2*(p+2);

end
</code>
Comment: By what measure are these oscillations "large"?  To me, they look consistent with purely random fluctuations attributable to the fact that the *data* will not be completely uncorrelated.
Comment: What I don't understand is that I expect the penalty term $2p$ should push the value upwards for high values of $p$. With "large oscillation" I mean deviation from the up trend which I expect. I repeat the simulation and every time it shows a similar pattern. I expect that AIC(p) should be minimized for very small values of $p$ with white noise.
Comment: @whuber data should be uncorrelated : they are generated from an autoregressive model of order 0 (i.e. they are just white noise). So adding parameters to the autoregressive models fitted on the data should not increase their likelihood.
Comment: @Camille Because the data are random, they are almost certain to exhibit a little bit of correlation: check it out yourself.
Comment: @whuber I agree, but we would expect the gain in likelihood to be small compared to the penalty due to adding an extra free parameter, since data are generated with p=0 and not p=1.
Answer: The most probable reason is that the AIC is not suited for this task. The Akaike Information Criterion and the Bayesian Information Criterion are two criteria for model comparison and selection, which are respectively defined as
$$
AIC  = -2\log( \hat{L} )+ 2p
$$
and
$$
BIC  = -2\log( \hat{L} )+ \log(N)p
$$
where $N$ is the number of data points. Although they differ in the way they are derived, we can consider, for this specific application, that they only differ in the way they penalize the number of free parameters $p$ in a model. A good reference on the differences between the AIC and the BIC is the following one :
Burnham, K. P., & Anderson, D. R. (2004). Multimodel inference: understanding AIC and BIC in model selection. Sociological methods & research, 33(2), 261-304.
In the tapering-effects context (that is to say when your family of models shows a continuous increase of complexity), which is illustrated in Fig. 1 of the paper, AIC will perform better than the BIC. On the other hand, when you only have a few big effects (i.e. when there is a big jump in complexity when you rank your models by increasing complexity), which is illustrated in Fig. 2, the BIC should be favored.
Here, you are clearly in the latter case. An autoregressive model with $p=0$ implies that your data are uncorrelated and corresponds to white noise. Any model with $p > 0$ implies a temporal correlation between your data. So there is a big jump in complexity between $p = 0$ and $p=1$, but not so much between $p=1$ and any other strictly positive value of $p$.
Using the BIC instead of the AIC thus allows to meaningfully compare your models :
Comment: thanks, also for the good reference, very helpful
Comment: Ok so maybe that happen because I am not testing the **real** model, which is $p=0$. I have come to the idea that the root of the problem is that AIC (as opposed to BIC) does not give enough penalty in the parameter term when there is very small or no information, and in this sense is not suited for the task.
Comment: Which is indeed what is stated in my answer ^^


Determine the parameters so that the function is continuous in R

Question: I got this problem i've tried to solve but i don't know how to proceed.
$$\begin{cases} 3\sin(4x)&&\text{if }x\leq 0 \\ mx+q&&\text{if }x>0 \end{cases}$$
Find the value of $m$ and $q$ so that the function is continuos in R.
I've tried this
$$\lim_{x\to 0^-} 3\sin(4x) = \lim_{x\to 0^+}mx+q$$
So that the $q$ value equals to $0$ but I don't know.
Comment: "the $q$ value equals $0$" looks like a good conclusion.  You might want to consider whether the function would then be continuous for any value of $m$
Comment: Hi! I've taken the step of editing your MathJax. Note that (as with regular LaTeX), MathJax treats any letters as variables, unless they are part of a control sequence (or are enclosed in a `\text{}` command)).
Comment: Further comments, if you want to make these changes: $1$. It is generally not considered obligatory to use parentheses in $\sin 4x$, even though it's technically less ambiguous that way. $2$. The reals are often denoted either $\mathbb{R}$ (`$\mathbb{R}$`) or, more traditionally, $\mathbf{R}$ (`$\mathbf{R}$`).
Comment: @BlobFish If my answer was satisfactory in resolving your question, can you please vote for it and/or click the checkmark to accept it?
Answer: You are correct in determining that $q = 0$.
Since we are taking the limit at $x = 0$, and anything times $0$ is still $0$, the coefficient of $x$ does not have any effect on the answer. Therefore, $m$ can be any real number, and $q = 0$ (as mentioned above). We can represent this answer as $\boxed{q = 0, m \in \mathbb{R}}$ or $\boxed{q = 0, m \in (-\infty, \infty)}$.


know the element you are over while dragging

Question: I am faced with a problem almost identical to this thread:
jQuery droppable - receiving events during drag over (not just on initial drag over)
The only difference is I need to know the element I'm over and it's NOT a "droppable" element.  It's just an element INSIDE my droppable.
So if I have a parent DIV (that is the droppable) that has 3 child DIVs, while I'm dragging my item over the 3 child DIVs, I want to know if, when dropped, the item should be dropped above or below one of the child elements.
The same problem exists as in the post above (mouseover, etc., events are not firing on the child elements of the droppable div).
Thoughts?
Comment: Is this just a UI feature?  Does it drop in the correct place, but you're not getting the style you want while dragging?
Comment: see: http://stackoverflow.com/questions/8810378/javascript-elementfrompoint-select-bottom-element
Comment: Yes, I know I can convert the non-droppables to droppables and use the method in the link above, but I'm trying to solve this without do that.  Thanks!
Comment: @Eli - I want to show an indicator as to where the item WILL be dropped when they release the mouse button.  I can't show them where it's going to go, though, unless I can tell what child DIV I'm over.
Comment: Ok so besides the UI giving the proper feedback of where it is going to drop, when you DO drop it, it DOES drop at the right spot?
Comment: Is this going in the right direction? http://jsfiddle.net/C5UnK/3/
Answer: You could get the mouse X & Y coordinates or the offset X & Y of the item when dropped - plus it's height & width etc. so you could calculate the boundaries of the object and get an accurate drop position.
<code>$(this).offset().top / $(this).offset().left

$(document).mousemove(function(event) {
    currentMousePos.x = event..pageX;
    currentMousePos.y = event.pageY;
});
</code>
Then iterate over the objects that sit below and compare their coordinates / boundaries with your object ones. You can have some logic that works out if more is above than below etc. if it's not a straightforward call.


Is it possible to have different frontpage page--front.tpl.php based on user´s device (mobile/desktop)?

Question: I am using the Detect_Mobile module in order to detect whether the user is coming from a mobile/tablet device or not. I would not like to use other modules as Mobile switch or Mobile tools because those are too big modules for my needs and also have cache bugs that appear when visiting again the frontpage, anyway that is not the point now.
I already detect the user´s device by using the Detect_Mobile library and module and I know it works because when I access the site by mobile I am redirecting the site to a different website so as testing I am using the next code in my template.php from my theme:
    <?php

    include 'sites/all/libraries/Mobile_Detect/Mobile_Detect.php';
    $detect = new Mobile_Detect();

    if (drupal_is_front_page()) {

     $GLOBALS['conf']['cache'] = FALSE; /*otherwise 2nd time shows desktop frontpage on mobile*/

        if ($detect->isMobile() or $detect->isTablet()) {
            header("Location: "); /*for testing goal*/
        exit;
       }
    }

    ?>

So the previous code works because the site gets redirected to another site address when the user´s access is by mobile/tablet but the point is that I don't want to redirect the site to another link like this: header("Location: /mobile.php");
What I want is to have 2 frontpages templates loaded based on user´s device:
page--front.tpl.php => normal(desktop) frontpage and loaded by default
page--frontmob.tpl.php => mobile/tablet frontpage and loaded when user´s device is mobile/tablet
Then I dont know if what I want is possible to do in Drupal but after reading some other examples like:
https://stackoverflow.com/questions/8840051/how-to-redirect-mobile-visitors-from-drupal-site-to-mobile-site-on-other-domain

Your best bet would be to write a small module and implement
  hook_init() which happens before the page is even built.
function MYMODULE_init() {   include("PATH/TO/Mobile_Detect.php");
$detect = new Mobile_Detect();   if ($detect->isMobile()) {
      header('Location: http://newdomain.com/');
      drupal_exit();   } }

And also this: http://example.com/serving-different-pagetplphp-different-browser-types-ie-ie6-your-drupal-theme
<?php
include('browser_detection.php');
if ((browser_detection('browser') == 'ie' ) &&
            (browser_detection('number') >= 5 ) &&
            (browser_detection('number') < 7  )) {
  include "page-ie.tpl.php";
  return;
} else {
  include "page-normal.tpl.php";
  return;
}
?>

Then I came out with the following code in my template.php of my theme:
<?php

        include 'sites/all/libraries/Mobile_Detect/Mobile_Detect.php';
        $detect = new Mobile_Detect();

        if (drupal_is_front_page()) {

         $GLOBALS['conf']['cache'] = FALSE; /*otherwise 2nd time shows desktop frontpage on mobile*/

            if ($detect->isMobile() or $detect->isTablet()) {
                include 'sites/all/themes/mytheme/page--frontmob.tpl.php';
            return;
        } else {
            include 'sites/all/themes/mytheme/page--front.tpl.php';
            return;
            }
        }

        ?>

But what the previous code does is calling both of the frontpages templates do both are showing on frontpage when loading the site: page--frontmob.tpl.php and page--front.tpl.php without caring the if statement about devices... so it feels like one page is embeding another page.... and still shows the next errors:
Notice: Undefined variable: logo in include() (line 14 of /sites/all/themes/mytheme/page--front.tpl.php).
Notice: Undefined variable: page in include() (line 26 of /sites/all/themes/myclassiclive/page--front.tpl.php).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in theme_get_registry() (line 277 of /includes/theme.inc).

So please help!!! I really have tried already many times to solve this problem but without success... I am new in Drupal.. so I guess the code I am using has something wrong...
I would appreciate so much for your soon help to fix that code or either use it in a different way... REMEMBER I am using Mobile_Detect(working fine) and REMEMBER I have not a different THEME for mobile that´s why I am not using Mobile switch or other similar modules but I have just 2 different frontpages templates on my theme based on user´s device... so:
mytheme/page--front.tpl.php
mytheme/page--frontmob.tpl.php

Rest of the sites pages works as desktop based on page.tpl.php.
Or should I do a small module(using hook_boot/hook_init) in order to be able to replace mytheme/page--front.tpl.php for mytheme/page--frontmob.tpl.php when detecting the mobile/tablet device? as here was suggested for somebody else with a little similar situation?
I there is NO a solution for this then I guess I have to use the redirection option with header("Location: http://www.example.com/mobile.php");
Answer: This is possible. You can use template_preprocess_page(). If you have the Devel module enabled you can dpm($variables) in the hook. Within the variables array is the theme_hook_suggestions element with a bunch of values which loads the template files upon output. So within template_preprocess_page you can add your device detection snippet and modify the element to load your template files. This article explains how to work with template suggestions and manipulate them to your needs.
Comment: I followed your instructions and it worked - thanks! It was all about reading documentation and some examples! :)
Answer: You can use the Theme Key module. You can achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, …
)
testing your redesign safely on a live server
...

ThemeKey should play well with internal and external page caches, like Boost or Varnish, even for anonymous users.
We use it in my company for a high-traffic site and works ok.
In your case, you can create a subtheme that is almost equal to the main theme and make your customizations there.
Comment: Thanks for your suggestion. it looks like I have to research around that because my theme is already a subtheme... but let´s see what I can do.. more sugestions are welcome! thanks to everyone! :)
Comment: Note that there's no problem with creating a theme that is a subtheme of another subtheme...
Comment: ok thank you! The only page that would be different for mobile/tablet devices would be the frontpage that means that the page.tpl.php should look and work same either user comes from a desktop or a mobile/tablet device... or should then I create the page.tpl.php for the subtheme from my subtheme even if both would be the same?
Comment: I'm not a frontend developer, so take mi words with cauton, but I guess you only have to override the tpl that is changes, not the ones thar are the same. May be the Theme Key is a littler overkill if you only ant to change one tpl, but as I said before I'm not a frontend developer.
Comment: Thanks tunic! Your sugestion is also ok but I wanted to avoid to install another module so in the end i used template_preprocess_page() + Mobile_detect module.


Remove link to terms page when printing taxonomy term on node--content_type.tpl.php?

Question: I have a node--content_type.tpl.php template where I want to print the taxonomy term associated with the current content as plain text so that I can surround it with a div class to print a special label for content with the selected term.
So for example I have chosen "Sold" as a taxonomy term and want to display the word with no link to the taxonomy terms page. It currently outputs as "Sold", so links to the taxonomy terms page.
I am currently using this code to print the term:
<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  $status = $node->field_p_status['und'][0]['value'];
}

?>

<?php if(isset($status)) { ?>

<?php print render(field_view_field('node', $node, 'field_p_status', array('label'=>'hidden'))); ?>

<?php } ?>

Any idea how to strip it down so it prints just "Sold"?
Comment: you got some advance?
Answer: To print the raw value you can use this code:
<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  print $node->field_p_status['und'][0]['value'];
}
?>

Comment: It didn't seem to print for some reason. Please see my answer below... (Thank you by the way).
Answer: I used a different solution which was better for me by printing the id of the taxonomy term (which I then wrapped in a div class). Obviously that didn't technically print the taxonomy term itself, but allowed me to have a class where I could style a background image unique to that class to show to the user (a Sold banner).
The code I used was:
                    <?php

                        if(!empty($node->field_p_status['und'][0]['value'])) {
                            $status = $node->field_p_status['und'][0]['value'];
                        }

                    ?>

                    <?php if(isset($status)) { ?>

                        <div class="status_<?php print $node->field_p_status[$node->language][0]['tid'] ?>">

                    <?php } ?>

Comment: It is good to have found the answer ;-)