consumindo JSON

Question: Estou com problema em pegar um arquivo da internet por JSON.
Tenho uns dados neste link http://www.sinestandar.com.br/maker/categorias.txt e quero pegar para usar na minha aplicação, o link retorna algo como:
{
   "Categorias":[
      {
         "nome":"Black",
         descricao:"Cortes de cabelo estilo Black",
         "icone":"http://mundomulheres.com/fotos/2013/10/dois-tipos-de-cortes-cacheados.jpg"
      },
      {
         "nome":"Casamento",
         descricao:"Cortes de cabelo para casamento",
         "icone":"http://www.belasdicas.com/wp-content/uploads/2012/07/penteados-para-casamento.jpg"
      }
   ]
}

Tentei fazer assim
class DownloadJsonAsyncTask extends AsyncTask<String, Void, List<Trend>> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(ConsumirJsonTwitterActivity.this, "Aguarde", "Baixando JSON, Por Favor Aguarde...");
    }

    @Override
    protected List<Trend> doInBackground(String... params) {
        String urlString = params[0];
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(urlString);
        try {
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String json = toString(instream);
                instream.close();
                List<Trend> trends = getTrends(json);
                return trends;
            }
        } catch (Exception e) {
            Log.e("DEVMEDIA", "Falha ao acessar Web service", e);
        }
        return null;
    }

    private List<Trend> getTrends(String jsonString) {
        List<Trend> trends = new ArrayList<Trend>();
        try {
            JSONArray trendLists = new JSONArray(jsonString);
            JSONObject trendList = trendLists.getJSONObject(0);
            JSONArray trendsArray = trendList.getJSONArray("trends");
            JSONObject trend;
            for (int i = 0; i < trendsArray.length(); i++) {
                trend = new JSONObject(trendsArray.getString(i));
                Log.i("DEVMEDIA", "nome=" + trend.getString("name"));
                Trend objetoTrend = new Trend();
                objetoTrend.name = trend.getString("name");
                objetoTrend.descricao = trend.getString("descricao");
                objetoTrend.icone = trend.getString("icone");
                trends.add(objetoTrend);
            }
        } catch (JSONException e) {
            Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
        }
        return trends;
    }

    @Override
    protected void onPostExecute(List<Trend> result) {
        super.onPostExecute(result);
        dialog.dismiss();
        if (result.size() > 0) {
            ArrayAdapter<Trend> adapter = new ArrayAdapter<Trend>(ConsumirJsonTwitterActivity.this, android.R.layout.simple_list_item_1, result);
            setListAdapter(adapter);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(ConsumirJsonTwitterActivity.this).setTitle("Atenção").setMessage("Não foi possivel acessar essas informções...").setPositiveButton("OK", null);
            builder.create().show();
        }
    }

Mas está dando este erro:
12-16 15:33:47.229  14947-14955/json.exemplo.com.testejson E/DEVMEDIA﹕ Erro no parsing do JSON
org.json.JSONException: Value {"Categorias":[{"icone":"http:\/\/mundomulheres.com\/fotos\/2013\/10\/dois-tipos-de-cortes-cacheados.jpg","descricao":"Cortes de cabelo estilo Black","nome":"Black"},{"icone":"http:\/\/www.belasdicas.com\/wp-content\/uploads\/2012\/07\/penteados-para-casamento.jpg","descricao":"Cortes de cabelo para casamento","nome":"Casamento"}]} of type org.json.JSONObject cannot be converted to JSONArray
        at org.json.JSON.typeMismatch(JSON.java:107)
        at org.json.JSONArray.<init>(JSONArray.java:91)
        at org.json.JSONArray.<init>(JSONArray.java:103)
        at json.exemplo.com.testejson.ConsumirJsonTwitterActivity$DownloadJsonAsyncTask.getTrends(ConsumirJsonTwitterActivity.java:76)

estranho que parece que está pegando os dados mais ta dando erro na hora de passar para o JSONArray trendLists;
Para Ajudar quem estiver com o mesmo problema estou colocando como resolvi
private List<Categoria> getTrends(String jsonString) {
        List<Categoria> categorias = new ArrayList<Categoria>();
        try {
            JSONObject trendLists = new JSONObject(jsonString);
            JSONArray jArray = trendLists.getJSONArray("Categorias");

            for(int i=0; i<jArray.length(); i++){
                Categoria categoria = new Categoria();
                JSONObject json_data = jArray.getJSONObject(i);
                categoria.nome=json_data.getString("nome");
                categoria.descricao=json_data.getString("descricao");
                categoria.icone=json_data.getString("icone");
                categorias.add(categoria);
            }

        } catch (JSONException e) {
            Log.e("DEVMEDIA", "Erro no parsing do JSON", e);
        }
        return categorias;
    }

Comment: `JSONArray trendLists` não deveria ser um `JSONObject`?
Comment: @LucasNunes você foi mais rápido do que eu +1
Comment: tava olhando de um site , não sei nada to tentando aprender :/ , to bem perdido
Comment: @IlgnerdeOliveira eu adicionei um exemplo também.
Answer: O "level root" do seu "json" usa { ou seja é um Object e não um Array, o correto é você usar JSONObject ao invés de JSONArray.
Veja aqui você tenta converter algo como {...} em Array:
JSONArray trendLists = new JSONArray(jsonString);
O certo neste caso é usar assim:
JSONObject trendLists = new JSONObject(jsonString);
Nota:
Para pegar a descrição separadamente do nome, você deve pegar primeiro Categorias usando JSONObject.getJSONArray e depois nome e descricao (sem acento) usando um loop e JSONObject.getString.
Veja um exemplo:
JSONObject trendLists = new JSONObject(jsonString);
JSONArray arr = trendLists.getJSONArray("Categorias");
for (int i = 0; i < arr.length(); i++)
{
    String nome = arr.getJSONObject(i).getString("nome");
    String desc = arr.getJSONObject(i).getString("descricao");
    System.out.print(nome);
    System.out.print(":");
    System.out.println(desc);
}

Nota: No seu código notei que você tentou capturar name ao invés de nome, nesta linha objetoTrend.name = trend.getString("name");
Comment: usei assim JSONObject trendLists = new JSONObject(jsonString);
 Log.d("teste",trendLists.getString("Categorias"));
ai consegui imprimir a categoria toda
mais nao to conseguindo pegar o nome, descrição separados.
tentei assim , JSONObject categorias = trendLists.getJSONObject("Categorias");
Answer: Notei outro problema ao passar sua url no jsonlint (http://jsonlint.com/): O campo descricao não está formatado corretamente; ele deveria estar entre aspas.
Parse error on line 4:
...Black",            descricao: "Cortes d
----------------------^
Expecting 'STRING'

Comment: Verdade. Deve ser "descricao" : "conteúdo..."
Comment: obrigado nem tinha percebido isto, vou alterar agora mesmo
Answer: A resposta do Guilherme resolve seu problema.
Mas, uma sugestão: você poderia usar o volley para facilitar essa parte.
Ficaria algo assim:
// lista de requisições
RequestQueue queue = Volley.newRequestQueue(this);

// não seria melhor chamar de `categorias.json`?
String url = "http://www.sinestandar.com.br/maker/categorias.txt";

// depois, para pegar o arquivo json:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>()
    {
        @Override
        public void onResponse(JSONObject response)
        {
            // ocorreu como esperado:
            JSONArray trendLists = response.getJSONArray("Categorias");

            // continuação do seu código.
        }
    },
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            // deu algo errado
        }
    });

queue.add(request);

Comment: Quando coloca RequestQueue queue = Volley.newRequestQueue(this); fica pedindo para criar classe
Comment: Tem que baixar umas classes mesmo. No da resposta indica onde baixar.

consumindo JSON


rudin theorem 1.20 (b) proof

Question:
(a) If x ∈ R, y ∈ R and $x > 0$, then there is a positive integer n such that $nx > y$.
(b) If x ∈ R, y ∈ R and $x < y$, then there exists a p ∈ Q such that $x<p<y$ $x<p<y$.
Since x < y, we have $y−x > 0$, and (a) furnishes a positive integer $n$ such that $n(y−x) > 1$.

In (b) we have that $x < y$ which can be expressed as $y-x > 0$.
How does (a) provide that $n(y-x) > 1$ ?
Thank you for any help.
Answer: Part a) provides the archemedian property, that an integer times any positive real number can be made larger than any real number. As such, the statement $n(x-y) \ge 1$ is valid for positive $x-y$.
Answer: $x$ and $y$ stand for different things in the two statements. Read (a) as saying:

if $a \in \mathbb R$, $b \in \mathbb R$, and $a > 0$, then there is a positive integer $n$ such that $na > b$.

If $x < y$ then setting $a = y-x > 0$ and $b = 1$ there exists a positive integer $n$ with $na > b$. That is, $n(y-x) > 1$.

rudin theorem 1.20 (b) proof


How to use Django paginator in a query-performance purpose?

Question: I just read the doc about Django pagination.
From the example, it seems to need to be used like this:

Load all the objects
Create Paginator object to split objects across pages.

Now, let's say I wan't to use pagination with a very long query that returns 100000 entries.
I takes a very long time to load all 100000 objects at once.
What I'd like to do is to load only 10 objects per page. Is there a way to do this using Django paginator, and maybe some limit/offset queries?
Thanks.
Answer: No, Paginator doesn't load all objects to memory.  If you pass a queryset to Paginator then it uses <code>.count()</code> to get number of objects.
Comment: Ahhh! Just read [this too](https://docs.djangoproject.com/en/1.7/ref/models/querysets/#when-querysets-are-evaluated) that helped me to understand why. Thanks.


Probability statistics - probability that 10 or more of the donors are Rh-negative?

Question: In a certain population, 18% of the people have Rh-negative blood. A blood bank serving this population receives 95 blood donors on a particular day.
So my teacher posted a solution to a problem below which solves the probability of getting 10 or less donors that are Rh-negative. I was wondering if I wanted to instead find the probability of 10 or MORE donors that are Rh-negative, how would I do so?
This was my attempt from following the teacher's logic
p(x≥10) = p(x>9.5) = 1 - p(Z>((9.5-17.1)/3.745)) = 1 - (Z>-2.03) = 1 - 0.2118 = 0.7882
Can someone confirm if I did this right, and if not, teach me how? I'm still a little lost.
Comment: First, pay attention that 18% $\ne$ 15%, and 95 $\ne$ 100.
Comment: p(x≥10) = p(x>9.5) $\approx$ p(Z>((9.5-17.1)/3.745)) = p(Z>-2.03) =0.9788
Answer: Let $X \sim \mathsf{Binom}(n = 95, p = .18).$ Then you
seek $P(X \ge 10) = 1 - P(X \le 9) = 0.9841.$
Directly in R, where pbinom is a binomial CDF, we have
1 - pbinom(9, 95, .18)
[1] 0.9840775

Using a normal approximation with continuity correction, you should
begin with $P(X \ge 10) = P(X > 9.5) = \cdots .$
You have the right idea, except I guess you got mixed up using normal tables.
In particular, $P(Z>-2.03) = 0.9788 \ne 0.2218.$
1 - pnorm(-2.03)
[1] 0.9788217

Below is a plot of the relevant part of the PDF of $\mathsf{Binom}(95,0.18)$
along with the normal distribution that matches the binomial mean and standard deviation.

x = 0:35;  PDF = dbinom(x, 95, .18)
plot(x, PDF, type = "h", lwd=2)
  abline(h=0, col="green2")
  abline(v = 9.5, col="red", lty="dotted")
mu = 95*.18;  sg = sqrt(mu*(1-.18))
  curve(dnorm(x, mu, sg), add=T, lwd=2, col="blue")


Why cannot a kernel be launched with the reason of too many register use when there is a register spilling mechanism?

Question: 1) When does a kernel start to spill registers to local memory?
2) When there is not enough registers, how does the CUDA runtime decide to not launch a kernel and throws too many resources requested error? How many registers are enough to launch a kernel?
3) Since there is a register spilling mechanism, shouldn't all CUDA kernels be launched even if there are not enough registers?
Comment: 1 and (2 and 3) are completely unrelated. Register spilling is a static operation performed by the compiler.
Answer:
1) When does a kernel start to spill registers to local memory?

This is entirely under control of the compiler.  It is not performed by the runtime, and there are no dynamic runtime decisions about it.  When your code reaches the point of a spill, it means that the compiler has inserted an instruction like:
STL  [R0], R1

In this case, R1 is being stored to local memory, the local memory address given in R0.  This would be  a spill store.  (After that instruction, R1 could be used for/loaded with something else.)  The compiler knows when it has done this, of course, and so it can report the number of spill loads and spill stores it has chosen to use/make.  You can get this information (along with register usage, and other information) using the -Xptxas=-v compiler switch.
The compiler (unless you restrict it, see below) makes decisions about register usage primarily focused on performance, paying otherwise less attention to how many registers are actually used.  The first priority is performance.

2) When there is not enough registers, how does the CUDA runtime decide to not launch a kernel and throws too many resources requested error? How many registers are enough to launch a kernel?

At compile-time, when your kernel code is being compiled, the compiler has no idea how it will be launched.  It has no idea what your launch configuration will be like (number of blocks, number of threads per block, amount of dynamically allocated shared memory, etc)  In fact the compilation process mostly proceeds as if the thing being compiled is a single thread.
During compilation, the compiler makes a bunch of static decisions about register assignments (how and where registers will be used).  CUDA has binary utilities that can help with understanding this.  Register assignments don't change at runtime, are not in any way dynamic, and therefore are entirely determined at compile time.  Therefore, at the completion of compilation for a given device code function, it is generally possible to determine how many registers are needed.  The compiler includes this information in the binary compiled object.
At runtime, at the point of kernel launch, the CUDA runtime now knows:

How many registers (per thread) are needed for a given kernel
What device we are running on, and therefore what the aggregate limits are
What the launch configuration is (blocks, threads)

Assembling these 3 pieces of information means the runtime can immediately know if there is or will be enough "register space" for the launch.  Roughly speaking, the pass/fail arithmetic is if the launch would satisfy this inequality:
 registers_per_thread*threads_per_block <= max_registers_per_multiprocessor

There is granularity to be considered in this equation as well. Registers are often allocated in groups of 2 or 4 at runtime, i.e. the registers_per_thread quantity may need to be rounded up to the next whole-number multiple of something like 2 or 4, before the inequality test is applied.  The registers_per_thread quantity is ascertained by the compiler as already described.  The threads_per_block quantity comes from your kernel launch configuration.  The max_registers_per_multiprocessor quantity is machine-readable (i.e. it is a function of the GPU you are running on).  You can see how to retrieve that quantity yourself if you wish by studying the deviceQuery CUDA sample code.

3) Since there is a register spilling mechanism, shouldn't all CUDA kernels be launched even if there are not enough registers?

I reiterate that the register assignment (and register spill decisions) is/are entirely a static compile-time process.  No runtime decisions or alterations are made.  The register assignment is entirely inspectable from the compiled code.  Therefore, since no adjustments can be made at runtime, no changes could be made to allow an arbitrary launch.  Any such change would require recompilation of the code.  While this might be theoretically possible, it is not currently implemented in CUDA.  Furthermore, it has the possibility to lead to both variable and perhaps unpredictable behavior (in performance) so there might be reasons not to do it.
Its possible to make all kernels "launchable" (with respect to register limitations) by suitably restricting the compiler's choices about register assignment.  __launch_bounds__ and the compiler switch -maxrregcount are a couple ways to achieve this.  CUDA provides both an occupancy calculator as well as an occupancy API to help with this process.
Comment: Thanks a lot for the answers. Exactly the answers I was looking for.


The requested PHP extension ext-mcrypt * is missing from your system

Question: I have updated my php to version 5.4.13 etc and well in the terminal my version of php states this
   PHP 5.4.12 (cli) (built: Mar 16 2013 21:46:23)

But running a composer install io get the following error.
  The requested PHP extension ext-mcrypt * is missing from your system

Anyway i have tried several emthods to get this to work etc and nothing:
I have used the following: Solution One and Solution Two, they both use a similar approach but i stil ge the errors.
I then did a php info test and this shows that the version is 5.3.15 and that mycrypt says mcrypt support is enabled
So is my server using this php and the one in my terminal using another as this what it seems
Any ideas how to fix this?
I am using a MAC Mountain Lion with Mountain Lion Sever (latest), xcode and all operations are up to date and i have restarted the server.
Answer: Got the same error in Linux(Ubuntu 14.04)
Check that ini exists
/etc/php5/mods-available/mcrypt.ini

If it is so, check that you have symlink to ini.
Something like in directory /etc/php5/cli/conf.d
05-mcrypt.ini -> ../../mods-available/mcrypt.ini

If there is no symlink create it. After installing the php5-mcrypt extension I have no symlink, only ini file. That is why create the symlink manualy.
You can use sudo php5enmod mcrypt to enable the mod. It will create the symlink for you.
Comment: Thanks a lot, this worked in Ubuntu 14.04. May I ask a couple questions: 1. How did you guess there was no .ini file? 2. Why does the php5-mcrypt package not do this automatically? Should I report a bug?
Comment: thanks for the reply on this but in the time i have moved over to Virtual servers mainly using Vagrant and a file call Vaprobash. thanks again
Comment: Also, how did you know it had to be 05-filename, and not some other int at the start?
Answer: Try the following solution:
sudo apt-get install php5-mcrypt
sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available
sudo php5enmod mcrypt
sudo service apache2 restart

Good luck,
-Iulian
Comment: Can you explain how you might do this without `php5enmod`? Most of us don't have that on our systems.
Answer: I had the same issue - mcrypt showed as installed for CLI but missing via command line. To fix, I ran
#php -i

to find the location of the command line version's php.ini file and then added
extension=mcrypt.so

After that, running #php -m will show you what modules are installed for the command line version and mcrypt should be there. If not, your "Solution 1" and "Solution 2" options should help you build the module - then just make sure the module is installed (or gets copied) to your php installation's module (extension) directory (something like /usr/lib/php/extensions/no-debug-non-zts-20100525/ or check where extensions_dir value in php.ini points to).
Answer: Well I simply went back to basics and uninstalled Mac Server and went back to MAMP, this performed all the latest updates and installs required, as my system was conflicting with two separate installs etc


Repeated measures and random effects in R

Question: I have an issue I cannot solve myself and hope I can get some pointers here:
I have a RCB design with 10 tree species each replicated 5 times in 5 blocks. I classified all species according to their height and assigned them to 3 groups (A, B and C). Then, I chose 2 species from each group and take my measurements on 8 individuals of that species, making sure to get at least one individual from each block. That gives me sample size of 48. In the end I want compare the groups with each other. Then I take a measurement for each individual in autumn, winter and spring and call this variable 'season'.
My hypothesis is that the groups are different with respect to the measurement I took, as well as the season will change the outcome of the measurement, e.g. the measures will be 'ideal' in autumn, ' very low' in winter and 'high' in spring.
My data looks similar to this made up example:
mydat<-data.frame(species=rep(1:6, 3, each=8),
                        block=rep(sample(1:5,replace=T,8), 18),
                        individual=rep(1:8,18),
                        group=rep(as.factor(sample(LETTERS[1:3],48, replace=T)),3),
                        season=rep(as.factor(c('autumn','winter','spring')),each=48),
                        outcome=rep(rnorm(144,10,1)))

Here is the model I fit:
fit<-aov(outcome~group*season+Error(season),data=mydat)
summary(fit)

But I guess this is not 100% correct, since I  cannot treat block as a random factor in aov(), can I? How can I proceed here? I tried to do it with lmer but I don't really understand what I am doing there. I know how do add the random term but how can treat the season now as a repeated measures, so that I get the right total degrees of freedom of 47? Also can I run TukeyHSD() on a lmer model afterwards since I'd like to compare the means.
Thanks for any help!!
Answer: You may find the following links helpful
Repeated Measures ANOVA using R
and
Repeated Measures Analysis with R


How to fetch HTTP response body with lua?

Question: I need to parse retreived text from HTTP GET request. I am using Lua on NodeMCU and I am not very familiar with it.
I am using script to fetch response and to split it one row at a time using this script
local nStart, nEnd = string.find(c, "\n\n")
if (nEnde == nil) then
    nStart, nEnd = string.find(c, "\r\n\r\n")
end
c = string.sub(c,nEnd+1)
print("length: "..string.len(c))
data = mysplit(c, "\n") -- fill the field with filenames

HTTP GET request looks like this
GET /lua/node.php?id=4022029&list HTTP/1.1
Host: mydomain.com
Accept: */*
User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)

When I print HTTP response, it looks like this
HTTP/1.1 200 OK
Date: Tue, 28 Nov 2017 01:05:12 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=23p8rtds43pd1662ncm5cjhrl3; path=/
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8

When I type mydomain.com/lua/node.php?id=4022029&list, I get a list of files as a text one bellow other, but this script is not fetching anything. It looks like there is no body. What am I missing here?
Update,
My script is working when fetching data from HTTP which is not encoding data chunked, but I am not able to fetch it from chunked encoding.
Answer:
Transfer-Encoding: chunked

The server you are connecting to is using chunked encoding, which means the header should be followed by one or more chunks that consist of chunk length and the content. It looks like either you haven't finished reading the content or the library you are using doesn't handle the chunked content for some reason.
Comment: I managed to get it working on localhost where HTTP is not encoded chunked. I can't change the encoding on that server, so it will remain chunked. I need to figure it out how to parse that data.


Find the variance of p-hat

Question: We have not discussed $\hat p$ in my probability and statistics course and a problem involving it is on our hw this week after learning about discrete distributions. The problem states "Let the random variable $Y\sim \text{Binomial}(n,p)$ and let $\hat p = \frac{Y}{n}$.
a. Find the mean of $\hat p$.
b. Find the variance of $\hat p$.
c. Use this and Chebyshevs theorem limit as $n$ goes to infinity of $Pr(\vert\hat p-p\vert < a)$ for any $a>0$.
I was able to find the mean of $\hat p$ as $p$ and I know that the variance of $\hat p$ should be $p(1-p)/n$ but I have been unable to prove that or do part c.
Comment: I was able to prove the variance of p-hat but am struggling with where to start with part c.
Comment: Can you update your question showing what you have tried so far? Also you should add the self-study tag while you're at it.
Comment: You need the self study tag
Answer: a.
$$ \mathbb{E}(\hat{p}) = \mathbb{E}\left(\dfrac{Y}{n}\right)= \dfrac{np}{n}= p$$
b.
$$ \operatorname{Var}(\hat{p}) = \dfrac{\operatorname{Var}(Y)}{n^2} = \dfrac{p(1-p)}{n} $$
Note here that
$$\lim_{n\rightarrow \infty} \operatorname{Var}(\hat{p}) =\lim_{n\rightarrow \infty} \sigma^2 =  0$$
c. I'll assume you mean Chebyshev's inequality
The inequality says
$$ \operatorname{Pr}(\vert \hat{p} - p| > k\sigma) \leq \dfrac{1}{k^2} $$
In your case $\alpha = k\sigma$ so $1/k = \sigma/\alpha$.  Since $\alpha$ is non -zero, we have no problems thus far.  Substituting, we have
$$ \operatorname{Pr}(\vert \hat{p} - p| >a) \leq \dfrac{\sigma^2}{\alpha^2} $$
If $\alpha$ does not vary with $n$, what can you conclude about
$$\lim_{n\rightarrow \infty} \operatorname{Pr}(\vert \hat{p} - p| >a)$$
Hint: See the law of large numbers
Comment: @EBusch does this answer your question?

Find the variance of p-hat


How to capture image with different resolution using Multi camera android?

Question: I'm trying to capture an image using Android Multi Camera API. The problem I'm facing now is that I can not get supported resolutions and prepare output configuration for a specific physical camera.
Google official docs suggests to use MultiResoultionImageReader, here's the link, but MultiResolutionImageReader should be used for a camera device only if the camera device supports multi-resolution output stream by advertising the specified output format in android.hardware.camera2.CameraCharacteristics#SCALER_MULTI_RESOLUTION_STREAM_CONFIGURATION_MAP.
However it's returning null and i'm testing it with Pixel 5 and 6.
val multipleStreamConfigurationMap = mCameraCharacteristics.get(CameraCharacteristics.SCALER_MULTI_RESOLUTION_STREAM_CONFIGURATION_MAP)
How can I set a resolution for physical camera?
Answer: Most of the physical camera are not exposed directly to app developer.
it is exposed via some logical cameraID. You need to check if the device that you are using support logical cameraID or not before using MultiResolutionImageReader
Comment: Yes, I'm checking the existence of physical camera ids, and opening a wide and optical zoom camera, if they're provided. Unfortunately, most of the devices don't support it, for now I've only tested with Pixel phones.@Wasim Ansari Have you tried setting multi-resolution?
Answer: I'm not sure if this is exactly what you were after, but on my Pixel 6 Pro, I can get the StreamConfigurationMap of a particular physical camera by first using getCameraCharacteristics on the physical Id; for instance, the telephoto lens on the P6 pro has id "4". Then use .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) just like you would for a normal camera Id. This worked for a Pixel 4 XL as well.
You can also use the characteristics of the physical id to get the ISO range, focal lengths, and anything you can get for a normal Id.
I also tried MultiResoultionImageReader and found, like you, that it returned null on the Pixel 6.
Hopefully this little example is helpful:
try {
    physicalCharacteristics = manager.getCameraCharacteristics(physicalId);
}catch (CameraAccessException e){
    throw new RuntimeException(e);
}
StreamConfigurationMap tempMap = physicalCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Range<Integer> isoRange = physicalCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);

And for anyone reading who doesn't know, you can find the physical ids of a given logical camera by calling .getPhysicalCameraIds() on the CameraCharacteristics of that logical camera.


Rate of NHL playoffs going to the overtime

Question: It feels like over the last few years and specially this season (16-17) more games are going to overtime. So I'm wondering what has been the trend of Stanley Cup playoffs games that go to overtime in the past 20 years? I'd like to see how the rate has fluctuated over many seasons.
I chose 20 years as it seems to be long enough to have a meaningful sample size. If you can find data for more seasons that'd be great.
Answer: Playoff games have gone into overtime 376 times from the 1996-1997 NHL season to the 2015-2016 NHL season (ie, "in the past 20 years")(1).
Using Hockey Reference's Team Game finder, I specified the following criteria: "For single games, from 1996-97 to 2015-16, in the playoffs, in overtime games, sorted by descending Game Date."

Rate of NHL playoffs going to the overtime

In the past 20 years, from the 1996-1997 NHL season to the 2015-2016 NHL season, there have been 1646 playoff games played(2).
Thus, the 20-year average (376/1646) is around 22.8%.

I'd like to see how the rate has fluctuated over many seasons.

2015-2016: 20 overtime games / 91 total games = 22.0%
2014-2015: 19 overtime games / 89 total games = 21.3%
2013-2014: 26 overtime games / 93 total games = 28.0%
2012-2013: 27 overtime games / 86 total games = 31.4%
2011-2012: 25 overtime games / 86 total games = 29.1%
2010-2011: 22 overtime games / 89 total games = 24.7%
2009-2010: 18 overtime games / 89 total games = 20.2%
2008-2009: 16 overtime games / 87 total games = 18.4%
2007-2008: 16 overtime games / 85 total games = 18.8%
2006-2007: 17 overtime games / 81 total games = 21.0%
2005-2006: 20 overtime games / 83 total games = 24.1%
2004-2005: lockout, no playoff games played
2003-2004: 19 overtime games / 89 total games = 21.3%
2002-2003: 22 overtime games / 89 total games = 24.7%
2001-2002: 18 overtime games / 90 total games = 20.0%
2000-2001: 26 overtime games / 86 total games = 30.2%
1999-2000: 9 overtime games / 83 total games = 10.8%
1998-1999: 21 overtime games / 86 total games = 24.4%
1997-1998: 19 overtime games / 82 total games = 23.2%
1996-1997: 16 overtime games / 82 total games = 19.5%

 Note: results are divided by two to account for each team being represented per game.

It feels like over the last few years ... more games are going to overtime.

Not entirely true. Although there was an higher than average trend from 2012-2014, the average in 2015 and 2016 was behind the 20-year average.
Other seasons of note include 2001 (~5% higher than the next highest percentage outside of 2012-2014) and 2000 (~8% lower than the next lowest percentage and 12% lower than the 20-year average).
Comment: Ah I should've been more specific with my question. I'm wondering about the trend. As in what the rate has been in each of these years, or a bar graph showing that to see how the rate has been changing over the years. I'll modify my question
Comment: @alamoot Done. I left the "20-year average" for comparison to yearly trends and removed 2016-2017 from my dataset as it is incomplete (until a Stanley Cup winner emerges).
Comment: Interesting. I could remember there weren't too many overtime games last year, but not the year before that. Guess I had biased view. specially with all the OT games this year. Thanks for the answer


Is Unique build rule to check uniqueness on year only not whole datetime field ?

Question: I want to validate combination of email and created using build rules such that created field's year is considered only for uniqueness.
<code>$rules->add($rules->isUnique(['email', 'created'], 'invalid entry'));
</code>
Answer: Seems like you need to do custom validation


Why did Japan stop to play just before the game ends on a match vs Poland?

Question: Japan seems to stop to play the game on the additional time on a World Cup match vs Poland, for about 2 minutes.
But the score was 0-1 and Japan was going to be defeat if they cannot score before the game ends.
So why did they seem to stop the game, by lazily sending pass to each other?
Answer: I didn't watch the game, but from what I've heard, the result of the Colombia-Senegal game meant that Japan were still set to qualify from the group even though they were losing 1-0. However, as they were tied with Senegal on points and goal difference, conceding another goal would knock Japan out and send Senegal through instead.
If Japan pushed forward in search of an equaliser, they risked being caught out by a counter-attack and conceding a second goal that would have eliminated them. All they needed to do for those final two minutes in order to qualify, was keep Poland from getting hold of the ball. And that's exactly what they did. A disappointing end to the game, perhaps, but they were thinking in the long-term.
Comment: 1) I believe time-wasting only applies to dead-ball situations (goal kicks, free kicks etc). There are no rules against just passing the ball around while it's in open play. 2) I don't know about the players on the pitch, but it's certainly okay for the coaches to bring their phones and keep an eye on what's happening in the other matches.
Comment: Thanks and that is reasonable. But then I have two wonders - (1) Is it OK to keep the ball that way? In game 1 vs Columbia the Japanese goal keeper got a yellow card as he kept the ball for a while (if I understand it correctly) so why is it OK to keep the ball that way? Is it because they are losing or other reasons? (2) In soccer is it OK to bring an electronic device or otherwise how can they know the result of other games?
Answer: The Japan vs Poland game was happening at the same time as the Senegal vs Colombia game. At the end of the games Poland and Colombia were winning their games by one goal. Given the standings Colombia would go through as first seed with 6 points, while Japan and Senegal were tied with 4 points.
Japan and Senegal had the same number of points, goals, goal differential. But Japan held the tie breaker by having 2 less yellow cards than Senegal.
So instead of attacking in the stoppage time and push for a goal Japan took the safer way by keeping the ball. Had they pushed for a goal they would've been vulnerable to counter attacks, which could lead into goals for Poland or more yellow cards for Japan which would've reduce from their tie breaker over Senegal. Also Poland was already eliminated and were winning the game so they didn't need to push Japan to get the ball back. So Japan made sure to keep control of the ball without trying to score and hoped that on the other game Senegal wouldn't score a goal.
At the end the score of both games remained at 1-0. Japan made it to the round of 16 for having 2 less yellow cards based on fair play performance.
Answer: Poland was eliminated regardless, they wanted to go out with a win.
The match between Senegal vs Colombia was happening at the same time with Senegal losing 0-1 as well and if result had stayed (0-1 in both match; Sengal vs Colombia and Poland vs Japan) Japan & Colombia would win the tie breakers and advance to the next stage.
If Senegal had scored a goal, Japan would've been eliminated. So it'd be better for Japan to at least draw with Poland as well in case Senegal also draw with Colombia in the other match but Japan didn't want to risk losing more and gambled that Colombia could hold the result.
In short, Japan gambled on the other match, not their own.


How to import St library in gjs

Question: Answer to a similar question suggests that I cannot import Shell stuff in a standalone mode. However, as I understand it, St is a separate library written in C. Yet I still cannot import it in gjs...
I.e.
<code>$ gjs -c "imports.gi.Gtk"
</code>
works (i.e. no output). But
<code>$ gjs -c "imports.gi.St"
</code>
fails with
<code>Error: Requiring St, version none: Typelib file for namespace 'St' (any version) not found
</code>
Is there any way to import St library from a standalone (not GNOME Shell extension) gjs?
Answer: Some of them are not there (e.g. Meta, Shell, St) because they are considered "private".
Read more here on how to import them:
http://mathematicalcoffee.blogspot.ca/2012/09/developing-gnome-shell-extensions_6.html?m=1
St Lib would really (!!!) help in writing apps with custom interfaces due to the use of CSS. If we could use the library with Clutter and gjs it would really attract developers due the easy of use of St and Shell libraries.
Comment: But I don't see how to import them in that post. As I understand it, it mostly covers documentation.
Comment: Hmm, yes I tried to copy the St-1.0.typelib to  /usr/lib64/girepository-1.0, after that I can do: imports.gi.St but after creating any St objects I get an error
Comment: I'm accepting the answer on the basis of "because they are considered 'private'".
Answer: Please try:
<code>#!/usr/bin/gjs

const res = imports.gi.GIRepository.Repository

res.prepend_search_path('/usr/lib/x86_64-linux-gnu/mutter-11')
res.prepend_search_path('/usr/lib/gnome-shell')

const St = imports.gi.St;
</code>
Depending on your setup, the libraries can be on different location. Please also check https://gist.github.com/buzztaiki/1492431 and Could not find Meta, Shell & St in Python's GTK bindings which gjs has

How to import St library in gjs


*nix live CD to recover Vista host?

Question: A friend of mine got his Vista PC infected by a virus. Before I tell him to just reboot with the maker-provided recovery DVD and lose all his data, is there a recommended Linux/*BSD live CD that he could try to clean up the mess?
Thank you.
Answer: Either the Ultimate Boot CD or the Windows version.  I would recommend the windows PE based disk for cleaning windows systems.
Comment: i can vouch for the Windows Ultimate BootCD. got me out of many holes especially with viruses. I would recommend that you add/enable the malwarebytes anti-malware plugin which I have found finds a lot of things that most anti-virus doesnt.
Comment: Yes, definitely.  I forgot this isn't default.
Answer: I've used SystemRescueCD successfully in the past. Also there is SLAX with the NTFS-3G module. Both allowed be to transfer data from one HD to another. Make sure you scan the files before putting them on another system.
Answer: I highly recommend doing a backup followed by a clean reinstall, it's much more secure, as you are never sure that there isn't something left even after the scanners didn't find anything anymore.
Answer: Once a virus is detected, I take the approach that the whole installation is now suspect and should not be trusted.  I don't think there's anything to be gained by trying to "clean up the mess."  Cut your losses and re-install.
When a virus damages your system, there's only one way you can be certain that you've removed all traces of the virus, and that's to do a complete re-installation, including re-formatting of your drive(s).
Hopefully, your friend has been performing regular backups of their system.  It is now too late to do a backup as others have suggested.  If you perform a backup now, you're potentially creating a virus infected backup because you cannot be sure which files have been affected by the virus.  If you were to restore data from a virus infected backup, you could end up back in the same situation your friend is in now.  :-(
I'd suggest a slightly different approach:

Locate the newest backup prior to the machine becoming infected.  If your friend has not been making regular backups, this will be the lesson that will teach them to start making regular backups.  :-)
Re-install the OS from scratch, including re-formatting the drive(s).
Restore from the clean backup.
Answer: You can do it with Knoppix and ClamAV.  There's tools (sorry, I forget the name) you can use on Knoppix to access the registry, but it's pretty tricky to clean out the registry.  ClamAV will do fine at finding viruses in the filesystem, however.  But some spyware (and viruses, I assume) will put itself all sorts of places in the registry so that it reinstalls itself.
Better option: back up the system, do a clean install, scan the files (documents, movies, music) that are still needed and copy those over.  Reinstall any software from scratch and don't copy any of the registry over.
Here's some useful links:

http://www.extremetech.com/article2/0,1697,1918306,00.asp
http://books.google.com/books?id=YaSWlOOxshsC&lpg=PA272&ots=rGcqfUi-Ol&dq=knoppix%20clamav%20registry&pg=PA269
http://www.greenfly.org/talks/knoppix/rescue.html
Answer: If you work with Windows I highly recommend Bart PE. There are a number of antivirus plug-ins available for it, as well as just about every disaster recovery tool you might need.

*nix live CD to recover Vista host?


Get toolbar in Xamarin.Forms if the first page is not a navigation page

Question: I tried to intercept the software back button in Android. I follow several samples that  adds these:`
protected override void OnPostCreate(Bundle savedInstanceState)
{
    var toolBar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
    SetSupportActionBar(toolBar);
    base.OnPostCreate(savedInstanceState);
}

protected override void OnResume()
{
    Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
    if (toolbar != null)
        SetSupportActionBar(toolbar);

    base.OnResume();
}

Then use the OnOptionItemSelected to get the software back button event.
But this didn't work because, for me the first page of the app is login page that does not belong to NavigationPage. After the successful login, I change the Application.Current.MainPage to the root application page that is a NavigationPage. But it is too late, the OnPostCreate or OnResume already been called and the FindViewById(Resource.Id.toolbar) return null.
Any suggestion?
Comment: Are you currently working with xamarin forms ?
Comment: Yes, I actually get the "hardware" back button functionning ok, but I can't intercep the soft one.
Comment: Is this Xamarin.forms? Or xamarin.android?
Answer: I dont understand whether you are asking xamarin.forms or xamarin.android.
For xamarin.forms
You can navigate from Login Page to Mainpage like this
Navigation.InsertPageBefore(new MainPage(), this);
 Navigation.PopAsync();

And In your App.xaml.cs
 MainPage = new NavigationPage(new Login());


Proper organ glissando technique?

Question: I am playing an organ patch on an electric keyboard with a low-ish trigger point, so I have to depress the key fairly deeply to be able to trigger sound. Generally, I am finding it hard to get quick, good sounding swipes out of it, especially ones that change direction. In fact, last time I tried I smashed my finger between two keys.
My question has two parts to it:
1) Should I be swiping using the tips of my fingers, or somewhere lower, or is there a best practice technique to swiping?
2) Are there recommendations on what to wear to protect my fingers from getting jammed between keys again, especially if I'm playing on a keyboard with a low trigger point?
Edit: By swiping, I do mean glissandos - basically sliding your hand down (or up) every white key on the keyboard (or possibly every black key), and possibly changing direction as well in the middle of a glissando.
Comment: One thing to consider is the difference in design.  A lot of organs are designed with keys that have rounded edges, making it significantly easier to accomplish this sort of gliss.  I don't think this consideration will help with your issue but it is something that I have heard plenty of keyboardists have to deal with when playing organ music.
Comment: Please qualify exactly what you mean by 'swipe'. Sounds like a gliss, but only you know.
Comment: Clarified. For some reason I thought organ players called these swipes - possibly not.
Answer: If you mean a glissando, I'd recomend using the back of your fingers; hitting the keys with your fingernails. With certain keyboards it has helped me a lot, since you can pressure the keys easier this way, and your fingers will be angled so you probably wont get them stuck.
Answer: If this is what I have heard described as a palm smear - though I believe it is technically a glissando - I have a couple of strategies to try.
If you are playing more informal music (blues, rock and roll, etc.), consider using the palm of your right hand, sweeping across your body ready to hit your destination note with your left, then quickly switching back to your right to continue the solo line.
Or you can use your left to smear to your destination - but still be ready to attack the solo line with your right.
It is a pretty thrilling effect, even on a Clonewheel board. I am sure some genuine B3 players will have great tips, which I will eagerly monitor.
Answer: Achieving smooth glissandos is maybe the main reason why waterfall key beds are used in most console organs and related "clones". Thanks to them, you can confortably perform glissandos through the palms of your hands, without scratches and undesired mechanical stresses both on yourself and your instrument.
Viceversa, if you have a "spinet" organ or an instrument with "synth" keys or a digital piano (regardless of being weighted or a semi-weighted action keyboard), the toe nail works great.
Last but not least, in the latter case do not use your palms to preserve both your hands and the keys!
Here follows some links to provide you with some examples and, if needed, clarification:
1) a magnificent example of the glissando technique:

2) synth-shaped keys:
https://images.google.it/imgres?imgurl=http%3A%2F%2Fwww.nonlinear-labs.de%2Fdev_blog%2Fuser_interface%2Fimages%2Fkeybeds.jpg&imgrefurl=http%3A%2F%2Fwww.nonlinear-labs.de%2Fdev_blog%2Fuser_interface%2Fuser_interface.html&docid=44VVibRUdT12ZM&tbnid=sO0aJ6dIDJkAGM%3A&vet=1&w=1350&h=882&source=sh%2Fx%2Fim#h=882&imgrc=sO0aJ6dIDJkAGM:&vet=1&w=1350
3) waterfal-shaped keys (perfectly rounded):
https://images.google.it/imgres?imgurl=http%3A%2F%2Fwww.nordkeyboards.com%2Fsites%2Fdefault%2Ffiles%2Ffiles%2Fproducts%2Fnord-stage-2-ex%2Fimages%2FSW-keybed.jpg&imgrefurl=http%3A%2F%2Fwww.nordkeyboards.com%2Fproducts%2Fnord-stage-2-ex&docid=GxTe9gLWpYJjtM&tbnid=imI0odl2xaKjFM%3A&vet=1&w=320&h=148&source=sh%2Fx%2Fim#h=148&imgrc=imI0odl2xaKjFM:&vet=1&w=320
4) piano-like keys:
https://images.google.it/imgres?imgurl=http%3A%2F%2Ffatar.com%2Fpart_grandi%2FTP_10-MDR_PartGRANDE.jpg&imgrefurl=http%3A%2F%2Fforums.musicplayer.com%2Fubbthreads.php%2Ftopics%2F2115663%2Fall%2FIs_there_a_brilliant_action_co&docid=mTY_MeNZn-3bsM&tbnid=ydFEzjfaUVPqlM%3A&vet=1&w=350&h=250&source=sh%2Fx%2Fim#h=250&imgrc=ydFEzjfaUVPqlM:&vet=1&w=350
Answer: My tip on learning glissando's is to use a finger glove or soft thin glove, to have a smooth slide that you feel comfortable with. As the technique develops, drop the glove. It comes naturally. Same with playing glissando's on the bass pedals. I love those and my audience is more interested in my feet! Take your shoe off and wear a soft woolen sock.
Answer: If your keyboard has a low action, you probably need to use piano gliss technique rather than an organ technique, otherwise you will end up injured one way or another. On piano, the basic idea is to you the back of a finger or thumb so that the nail protects you from injury, not the flat part of your fingertips or your palm. For the safest results, you need strong nails cut to the right length. See here:

Proper organ glissando technique?


Use Open Query with quoted items

Question: I am trying to use openquery to access a linked server. However, it appears to be impossible because, you cannot have the correct number of Single quotes. I need to pass a variable Start and End date, so I cannot use the basic openquery method, but instead must use the EXEC(@OPENQUERY+ @SQL) method. The problem is, to pass the date through the @SQL variable I must use ''' so it has 1 quote, but then when it gets passed to the EXEC(OPENQUERY+@SQL) the open query which introduces another level of quotes, causes the dates to now be not be quoted and I get an error. If I add another layer of quotes it then causes them to be double quotes causing that error. Is it not possible to use quotes in an open query? I have the same issue even passing things like Where Username = 'Jack'. I can never have the correct number of quotes.
DECLARE @STARTDT NVARCHAR(10) = '2019-01-01'
        ,@ENDDT NVARCHAR(10) = '2019-03-01'

DECLARE @SQL NVARCHAR(4000)
DECLARE @OPENQUERY nvarchar(4000)
        , @LinkedServer nvarchar(4000)

SET @LinkedServer = 'ProductionSvr'

SET @SQL =
'select  *
from SalesData a
where a.Sale_date between ''' + @StartDt + ''' and ''' + @ENDDT + ''')
'''

print @SQL

SET @OPENQUERY = 'SELECT * FROM OPENQUERY('+ @LinkedServer + ','''

EXEC (@OPENQUERY+@SQL)

Answer: How about this:
DECLARE @STARTDT NVARCHAR(10) = '2019-01-01'
        ,@ENDDT NVARCHAR(10) = '2019-03-01'

DECLARE @SQL NVARCHAR(4000)
DECLARE @OPENQUERY nvarchar(4000)
        , @LinkedServer nvarchar(4000)

SET @LinkedServer = 'ProductionSvr'

SET @SQL =
'SELECT * FROM OPENQUERY(' + @LinkedServer + ',''select  *
from SalesData a
where a.Sale_date between ''' + @StartDt + ''' and ''' + @ENDDT + ''')'

print @SQL

All you have to remember is within quotes, double single quotes means 1 single quote. So, ''')' essentially translates to "')". Hope this helps.
Comment: I just figured it out, the trick was 4 quotes around constants and 5 quotes around variables. If you update your answer I will make it as correct :)
Comment: I didn't quite get what you are trying to say, but I am good if you got the answer you are looking for. You may want to give the query I have put in the answer a try as well, as I believe it's a simpler version and should give the correct result.
Answer: Within a quoted string, you have to escape a single quote with an additional single quote, which is where you start to see the four and five single quotes in a row. In order to help simplify things, I would make a couple of suggestions.
First, keep your strings more segregated in their duties. Your @SQL variable includes the necessary ending punctuation for your OPENQUERY, but the beginning punctuation is in the @OPENQUERY variable. (This might be clearer in the code below.)
Also, I'd recommend using proper data types (such as your dates), and then use the CONCAT function, which conveniently handles all of the data type conversions for you.
So, the modified version of what you started with would look like this:
DECLARE @OPENQUERY nvarchar(4000)
      , @LinkedServer nvarchar(256)
      , @SQL NVARCHAR(4000);

--Set your dates. Use the right data type to avoid sending
--invalid dates into your query. Easier to debug them here.
DECLARE @STARTDT DATE = '2019-01-01'
        ,@ENDDT DATE = '2019-03-01';

--Set your server.
SET @LinkedServer = 'ProductionSvr';

--Then set up the inner query.
SET @SQL =
CONCAT(
'select  *
from SalesData a
where a.Sale_date between ''', @StartDt, ''' and ''', @ENDDT,'''');

--Set up the OPENQUERY variable with all of the punctuation that it needs,
--so you just need to drop in your LinkedServer name and your SQL statment.
--Use CONCAT because it handles the data type conversions for you.
SET @OPENQUERY = CONCAT('SELECT * FROM OPENQUERY(',@LinkedServer,',''(',@SQL,')'')');

PRINT @OPENQUERY;

Result:
SELECT * FROM OPENQUERY(ProductionSvr,'(select  *
from SalesData a
where a.Sale_date between '2019-01-01' and '2019-03-01')')

Use Open Query with quoted items


Tecnologia, Plataforma e Linguagem, o que são e como se relacionam?

Question: Tecnologia, Plataforma e Linguagem são termos usados para caracterizar vários "aspectos" do "mundo da programação".
A quê cada um deles se refere exactamente?
O que os une e/ou os separa?
Comment: Relacionada: [Afinal, Java é uma tecnologia ou uma linguagem de programação?](https://pt.stackoverflow.com/questions/266489/afinal-java-é-uma-tecnologia-ou-uma-linguagem-de-programação)
Comment: @vnbrs Foi essa pergunta que me levou a fazer esta.
Comment: Plataforma é bem ambíguo, mas com certeza é respondível :)
Answer: Linguagem
Vou falar mais da linguagem de programação, mas há outras linguagens que usamos na computação.
A linguagem em si é apenas uma especificação. Normalmente só podendo ser usada quando tem uma implementação feita, tipicamente com um compilador e um código de runtime, que pode incluir uma biblioteca básica específica. Veja Como é desenvolvida uma linguagem de programação?.
A linguagem é o que permite expressar algoritmos e estruturas de dados para que o computador depois saiba o que fazer. Ela é uma formalização de sintaxe (ortografia e gramática) e semântica de instruções que determinarão a execução de um algoritmo.
A linguagem é abstrata demais. Você não instala a linguagem, você simplesmente a usa. Imagino que algumas pessoas devem achar, erroneamente, que o compilador é a linguagem. Além de ser só a implementação, ele sozinho não pode ser considerado a linguagem, precisando de outras partes, por isso imagino também que no contexto o termo esteja sendo usado quase como plataforma.
Tecnologia
A linguagem é uma tecnologia, o compilador é uma tecnologia, vários outros componentes usados em conjunto são tecnologias. Enfim, quase tudo o que o ser humano criou para resolver problemas é tecnologia. É um conjunto de técnicas, habilidades, métodos e processos para produzir algo com algum objetivo. É conhecimento. Tecnologia é o que te dá capacidade fazer algo.
É um termo bastante amplo e abstrato, que significa pouca coisa ou nada na nossa área. Em geral falamos de ferramentas em geral, softwares ou hardwares que executam alguma tarefa específica, mas tecnologia é muito mais que isso. Usamos o termo para referenciarmos produtos que foram criados para ajudar na criação dos nossos softwares.
Uma linguagem é uma tecnologia, uma plataforma é uma tecnologia, um compilador é uma tecnologia, um *runtime é uma tecnologia. Cada um deles está cheio de tecnologias específicas isoladas ou em conjunto.
Tecnologias específicas vão recebendo outros nomes mais específicos.
Taxonomia é hierárquica, tudo tem vários nomes dependendo do grau de especificidade que deseja designar aquilo. Quando chamamos algo de objeto é uma taxonomia em nível alto.
Plataforma
Plataforma é algo que sustenta uma série de coisas para alcançar um objetivo. Qualquer coisa que seja usado como base para executar um software dentro de determinadas regras que o software precisa se conformar é uma plataforma. Pode ser um hardware ou software (geralmente são máquinas virtuais ou mesmo sistemas ou ambientes operacionais ou até uma biblioteca, ou ainda navegadores web ou de outro padrão com objetivos semelhantes).
Nenhum software roda se conformando com várias plataformas de forma direta. Ou precisa de outra camada, que acaba sendo outra plataforma em um nível mais alto ou ele precisa ficar verificando a plataforma e tomando decisões sobre o que executar para se conformar como o que está rodando em cima (tem diversas técnicas para isto, todas com penalização de desempenho).
Mas também usamos o termo em um nível mais alto, mais "administrativo", que eu acho que não é o foco. Mas algumas plataformas desse tipo acabam também sendo plataformas de execução também.
É possível ter alguns níveis de plataforma (do mais concreto ao mais abstrato). Em geral só precisa se preocupar mais com o nível mais alto que está mais próximo do seu software. Você não usa a plataforma web tendo que saber como resolver o o acesso a um arquivo, a plataforma abstrai isso. Você não faz um código nativo se preocupando como acessa o teclado.
Não confundir com um framework. Um framework é uma tecnologia que roda em cima de uma plataforma e geralmente em conjunto com uma linguagem. É uma forma concreta de acessar a plataforma.

Como exemplo temos a Common Language Infrastructure (CLI). É uma plataforma, e geralmente apelidamos ela de .NET. Mas essa é apenas uma das implementações dessa plataforma. Pode ser útil.
Outro exemplo.
Conclusão
Não considere esta como resposta absoluta, não conheço definição formal dos termos para nossas áreas. Cada pessoa pode classificar as coisas de forma diferente.
Além disso não dá para passar toda a complexidade de classificação disto aqui, a pessoa tem que ir obtendo diversas informações para ir formando uma base que lhe permita entender corretamente.
É frequente que até os criadores de certos produtos chamem uma coisa de forma errada, seja porque ele desconhece ou usa outra definição, seja por puro marketing. O que frequentemente gera confusão.
Coloquei no GitHub para referência futura.
Comment: Pretendo alterado o título da pergunta para "Tecnologia, Plataforma e Linguagem, o que são e como se relacionam?". A alteração expressa melhor o que pretendo perguntar. Apesar de considerar que a sua resposta vai nesse sentido não queria fazer a alteração sem que se manifeste a favor.
Comment: Pode fazer sim, espero já já dar uma melhorada ou finalizá-la, aí com a mudança já acerto alguma coisa pra adequar.


Generate $r_i$ following condition $\sum_{i=1}^n \left|\frac{r_i}{\sigma_i}\right|^2\leq\chi^2_{n,\alpha}$

Question: How can I generate $r_i$ for $1 \leq i \leq n$, such that $\sum_{i=1}^n \left|\frac{r_i}{\sigma_i}\right|^2\leq\chi^2_{n,\alpha}$, where  $\sigma_i^2$ is the variance of $r_i$ and $\chi^2_{n,\alpha}$ is a chi-squared value for $n$ degree of freedom and an $\alpha$ confidence level.
I truly appreciate your insights.
Comment: In general, as $n \rightarrow \infty$, then $(\chi_n ^2 -n)/2n \rightarrow N(0,1) $ for $ \chi^2$.
Comment: Two questions: are _n_ and _\alpha_ known or unknown? Are you asking a programming question or a math question?
Comment: @akash87, thanks for your comment. $\alpha$ and $n$ are both known. However, I am also keen on the relationships. I am looking more into the theory and mathematics, but any insights are certainly appreciated.
Comment: Are you sure $r_i$ is not normal?
Comment: Not necessarily.
Comment: If it is normally distributed then this becomes an noncentralized $\chi^2$ function.
Comment: akash can you please give a detailed answer under the normal distribution assumption, and give an example how you generate $r_i$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/41777/discussion-between-jolfaei-and-akash87).
Comment: @akash87 You forgot a square root in the denominator.
Answer: Chi-squared distribution is defined in terms of normally distributed random variables. If $Z_1,\dots,Z_k$ are i.i.d. standard normal variables, then $ \sum_{i=1}^k Z_i^2 \sim \chi^2_k $. So to draw from chi-squared distribution with $k$ degrees of freedom, can use $k$ values drawn from standard normal. Alternatively, as in your case, you can draw $X_1,\dots,X_k$ from normal distribution with mean $0$ and standard deviation $\sigma^2$ and then take $Z_i = X_i / \sigma^2$ (so are you sure that you want to divide by variance..?).
<code>set.seed(123)

f <- function() {
  n <- 20
  sigma <- 5
  r <- rnorm(n, 0, sigma)
  sum((r/sigma)^2)
}

x <- replicate(5000, f())
xx <- seq(0, 75, by = 0.01)

hist(x, 100, freq = FALSE)
lines(xx, dchisq(xx, df = n), col = "red")
</code>

If you need $100\alpha \% $ middle values, and $\alpha$ is big (say $0.95$), than the easiest way to go is to make multiple draws and then discard the draws that fall beyond the $100\alpha \% $ interval.
Comment: (+1) for your insight but the question still remains. I'm looking for a method to create $r_i$ that maintain the condition with probability 1. Your method seems like a trial and error. What is the best distribution and method of generation to ensure the condition?
Comment: @Jolfaei if your alpha is big, e.g. $0.95$ then this means that your would have to reject only only 5% of the cases, that is not much. No better method comes to my mind.
Comment: I also have another concern, why did you use normal distribution? Can't this work with poison distribution (if you write the gof test then this might cross your mind) or even uniform distribution or ... . Why normal?
Comment: @Jolfaei because, by definition, this is a distribution of sum of squared normals (check https://en.wikipedia.org/wiki/Chi-squared_distribution or statistics handbook). This is *the* distribution that is taken by sum of squared normals, not just squared things.
Comment: That's correct but $\chi^2$ is a constant, let's say $ C$, in here that defines an upper bound for the sum. Given this constant bound, can't we generate $r_i$ following any other distributions?
Comment: @Jolfaei chi-squared distribution is the distribution of sum of squared normals...
Answer: In general, as $n \rightarrow \infty$, then $(\chi_n ^2 -n)/2n \rightarrow N(0,1) $ for $ \chi^2$. Now we can establish the function $\Sigma_{i=1} ^n (\frac {r_i}{\sigma_i})^2 \leq \chi^2 _{n,\alpha} $ is true for the normal distribution $R$ for $r_i$. This is kind of actually a normal to chi-square transformation, and what you can do to generate the $r_i$ is usually select $\sigma_i^2 = 1$ for all $i$ and then you can find the $r_i^2$ values that correspond to the $\chi^2_n$ distribution.
To consider $\alpha$ in this problem is really to determine if the value samples falls within the $1-\alpha$ confidence interval of $\chi^2_n$.
@Jolfaei The $r_i$  distribution is sampled from a normal distribution of mean $E(r_i)$ and variance $Var(r_i)$. It should come from $N(E(r_i), Var(r_i))$. If you know $n$, then you can sample from any normal distribution for a defined $E(r_i)$ and $Var(r_i)$. So lets say for example, you want to find the $\chi^2 _5$. You can actually pick the normal distribution parameters for each iteration. It should work because the tail end $\chi^2$ p-value increases as $n\rightarrow infty$ and by definition the $chi^2$ distribution is the sum of normal distributions.
Comment: I think the answer is somehow vague and not complete. It is still not clear to me how you generate $r_i$. What is the $E(r_i)$? My other concern is that I think $\chi^2$ is constant not a variable.
Comment: @Jolfaei The $r_i$  distribution is sampled from a normal distribution of mean $E(r_i)$ and variance $Var(r_i)$. It should come from $N(E(r_i), Var(r_i))$


Limitar ocorrências de registros para cada tipo

Question: Estou precisando limitar o número de ocorrências de cada tipo de material que tenho no meu banco de dados.
Segue a query abaixo com o que quero fazer:
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 1
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 2
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 3
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 4

Como podem ver, eu quero as 10 primeiras ocorrências de cada tipo de material na minha consulta.
Mas estou precisando fazer com que isso vire uma query só. No caso, preciso que venham as 10 primeiras ocorrências de cada tipo na mesma query.
Como posso fazer isso? Com CASE WHEN é possível fazer um contador para cada tipo de material? Até fiz uns teste, mas sem sucesso. Acho que minha lógica não está dando certo nessa questão.
Infelizmente não consegui extrair uma resposta da pergunta abaixo
Limitar número de ocorrências do Group By
Comment: a solução do Sorack, deve solucionar o seu problema obrigado.
Comment: os tipos são fixo?
Comment: sim, só existem esses 4.
Answer: Utilize UNION ALL, que vai combinar os resultados sem a execução no final de um distinct trazendo os dados mesmo se houver repetição, acredito que no seu caso isso já resolva. Se por ventura não quiser repetição utilize somente UNION

Como ficaria então sua SQL?

SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 1
UNION ALL
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 2
UNION ALL
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 3
UNION ALL
SELECT TOP 10 ID, NOME, TIPO FROM TB_MATERIAIS WHERE TIPO = 4

Oservação: a resposta @Sorack é justa para SQLServer e perfeita, mas, a minha server para diversos bancos, acredito que a diversidade de respostas corretas e que solucionam o problema são válidas.
Referencias:

UNION (Transact-SQL)
SQL: Utilizando o Operador UNION e UNION ALL
Comment: Opa Virgilio, acho que é algo desse tipo mesmo. O TOP já faz o limite para mim e o union all junta todos os resultados para mim, certo?
Comment: Nesta solução a tabela TB_MATERIAIS terá que ser lida 4 vezes; isto não é eficiente. Além disso, se um novo tipo de material for registrado, o código ficará obsoleto.
Comment: O `row_number()` é para SqlServer e a minha resposta serve para diversos bancos é um padrão universal, se o código do tipo vai ficar obsoleto pode acontecer é um fato, mas, se for diferente de `SQLServer` o que você disse também não vale. Lembro que respostas universal também tem sua valia, inclusive vou editar esse comentario, obrigado.
Comment: @DiChrist sim ... !!! é da forma que descreveu
Answer: Você pode usar o ROW_NUMBER com agrupamento da seguinte forma:
SELECT x.*
  FROM(SELECT ROW_NUMBER() OVER(PARTITION BY m.TIPO  ORDER BY m.ID) as sequencia,
              m.*
         FROM TB_MATERIAIS m) x
 WHERE x.sequencia <= 10;

Comment: Não pude comentar antes, meu problema foi resolvido! Deu certinho!
Comment: Já foi nas duas :)
Comment: Opa beleza, valeu :)
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/48654/discussion-on-answer-by-sorack-limitar-ocorrencias-de-registros-para-cada-tipo)


HOUR_OF_DAY sets the same hour for value 0 and 1

Question: I have a tricky (at least for me) question with java time zones. I will start with an example that works as expected:
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.setTimeZone(tz);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(tz);

calendar.set(Calendar.HOUR_OF_DAY, 0);
System.out.println("0: " + simpleDateFormat.format(calendar.getTime()));

calendar.set(Calendar.HOUR_OF_DAY, 1);
System.out.println("1: " + simpleDateFormat.format(calendar.getTime()));

calendar.set(Calendar.HOUR_OF_DAY, 2);
System.out.println("2: " + simpleDateFormat.format(calendar.getTime()));

output:
0 4/28/17 12:27 AM
1: 4/28/17 1:27 AM
2: 4/28/17 2:27 AM

And now a little of magic:
TimeZone tz = TimeZone.getTimeZone("Africa/Cairo");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.setTimeZone(tz);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(tz);

calendar.set(Calendar.HOUR_OF_DAY, 0);
System.out.println("0: " + simpleDateFormat.format(calendar.getTime()));

calendar.set(Calendar.HOUR_OF_DAY, 1);
System.out.println("1: " + simpleDateFormat.format(calendar.getTime()));

calendar.set(Calendar.HOUR_OF_DAY, 2);
System.out.println("2: " + simpleDateFormat.format(calendar.getTime()));

output:
0: 4/28/17 1:31 AM
1: 4/28/17 1:31 AM
2: 4/28/17 2:31 AM

Could someone explain me why HOUR_OF_DAY for values 0 and 1 set hour on the same value for specific TimeZone's?
Comment: Old enough to be at least 7 time zone data versions out of date :)
Comment: Might be related to Daylight Saving Time (DST). I don't know how DST are handled in Java for such TimeZones which seem to have very irregular DST policies.
Comment: I can't reproduce this. It works fine for me. I wonder whether you have an old version of time zone data, where maybe April 28th 2017 was a "skip forward" day...
Comment: I'm using jdk1.8.0_25. Not very fresh but not too old also
Answer: Your machine has an old version of time zone data, in which Egypt would have put the clocks forward at midnight local time at the start of April 28th 2017. Therefore 12:31am wouldn't have existed, and Java is skipping forward by an hour instead1.
On July 5th 2016, IANA time zone data 2016f was released with the change to the Africa/Cairo time zone to not observe DST from that point onwards. (This was a very late announcement, as the next change would have been July 8th 2016.)
You can see all the transitions for every IANA time zone, across different versions of the IANA data, at http://nodatime.github.io/tzvalidate/. (Disclaimer: I build that page. I started the tzvalidate project to validate that different date/time libraries understand the time zone data in the same way.)

1 I would argue that the API should force you to state what you want to happen in that case, but I won't go into everything that's wrong with java.util.Calendar here...
Answer: A few years ago, that timezone was planned to have a DST transition the night of the 28th of April 2017: at 00:00am, clocks would have been moved forward by one hour. So a time between midnight and 1am would have been invalid due to the transition.
However that transition did not occur in practice because it was cancelled (Egypt seem to have cancelled and reinstated DST a few times over the past few years).
In conclusion, you are probably using an older version of Java which has an outdated timezone database.
Comment: Looks like timezoneconverter.com has out-of-date data - but probably the same data that the OP has. Ah, the joys of time zone data changing.
Comment: That would make sense *if* Cairo actually had that transition. It doesn't according to current data. https://www.timeanddate.com/time/zone/egypt/cairo I'll see whether I can find an old version where that actually happened.
Comment: @JonSkeet I checked there: http://www.timezoneconverter.com/cgi-bin/zoneinfo?tz=Africa/Cairo - not sure which is right.
Comment: @JonSkeet I found that Cairo had such DST on the 30 of April in 2010. I would be interested to know what is the reference for DSTs in Java's `Date` class.
Comment: @ArnaudDenoyelle: I believe most Java implementations use the IANA data: https://www.iana.org/time-zones
Answer: You were right. Problem was with time transition at 28th. Today everything works fine :)


How to prevent an execution timeout error message to appear?

Question: I've got a piece of PHP code retrieving my last tweet :
<code>$twitterrequest = 'http://api.twitter.com/1/statuses/user_timeline.json?user_id=' . $user_id . '&include_rts=true&count=' . $tweetsToDisplay;
$twitterci = curl_init($twitterrequest);
curl_setopt($twitterci, CURLOPT_RETURNTRANSFER, TRUE);
$twitterinput = curl_exec($twitterci);
curl_close($twitterci);
return ($twitterinput);
</code>
When my Internet connection is really busy I ocasionally get the following message :
Fatal error: Maximum execution time of 30 seconds exceeded in D:...\www...\wp-content\themes...\home_tweet.php on line 26
How to prevent that, simply displaying nothing rather than this ugly error message ?
Answer: It might be more elegant to limit the time curl waits for an answer:
<code>curl_setopt($twitterci, CURLOPT_TIMEOUT, 10);
</code>
to give it 10 seconds.  That way you also get an opportunity to handle the timeout condition in a user-friendly way.
If that's not what you are looking for, have a look at How do I suppress a specific error in php


Disk usage in Perl Core

Question: I'm looking for a way to check the remaining free space on a disk within Perl. I can't use CPAN since I have to deploy the script on many servers with different versions of Perl, and I can't change it because my team leader ordered me that way.
Any idea? I tried File::stat but I can't use it on D:\ (the script runs on Windows versions).
Thanks!
Comment: If you can't use CPAN, and you can't use PAR, then you shouldn't be deploying Perl code. Just silliness.
Comment: I found a way using some horrible parsing method on `dir` system command
Answer: fsutil volume diskfree C:

For Windows servers you can run this cmd command from system() method.
Comment: It requires admin rights, I can't deal with that. Thanks anyway!
Comment: http://www.opennet.ru/base/dev/perl_win_disk_mon.txt.html read this article. There is more info there than just to know free disk space in windows server.
P.S. Don't worry about Russian language, it's only intro.

Disk usage in Perl Core


Microsoft SQL Server Management Studio Permissions

Question: Our software requires the business users (of the software) to have read and write access to the database (MS SQL Server).  The users are added to an active directory group with this SQL permission.  The business users also want to query the database as read only in SQL Server Management Studio.  Is there a way that the user can have read write access to the database from the software and read only from the back end in SQL Server Management studio?
Comment: Stack Overflow is really only for programming questions. This question is a better fit for [Server Fault](https://serverfault.com). That said, the answer is no. Permissions are assigned to credentials, regardless of how you access the database. Usually applications use only one account to access the database, then limit what data is shown based on the user logged in. It's not common for an application to use the user's account to access the database.
Comment: see https://stackoverflow.com/questions/5029014/how-to-add-active-directory-user-group-as-login-in-sql-server
Answer: As the SQL server permissions are assigned to the Active Directory group, the users in the group will be able to have the same permissions irrespective of from where they are accessing the database (from the software or MS SQL server management studio)
The permissions cannot be changed based on from where the users are accessing the database


Large file upload guidelines

Question: I have a site built in Drupal 7.23, which is supposed to handle large files uploads to it.
I have a node form with 5 File upload fields which is supposed to take 200MB files for each.
What should be the Apache server adjustments that i need to taken in favour of making the upload process seamlessly?
Also i have Video module with FFMPEG configured to convert on cron. Someday I got message form server support team that my FFMPEG is taking 100% CPU.
Also i got some MySQL errors, like Lock TimeOut etc. what to do ?
Please let me know an optimal settings for these kind of server which runs Drupal.
Comment: taking 100% CPU - are you in shared hosting ?
Comment: @Bala nop i am in VPS ~2GB i think
Comment: I think you can do it through https://drupal.org/project/jupload , using this method (not sure) you can upload the files without issue in your server, better see this page( https://drupal.org/node/1748456 ) , it not mentioned but it processed through ftp so I think it can do the job without affecting the server.
Comment: @Bala but that will ruin my UI..
Comment: It looks like UI integration and I'm not sure, better give a try.
Comment: See the document page, It showed there with UI
Comment: You should move to Xen VPS or dedicated server to avoid resource usage warning
Comment: It looks like, you have a disk i/o problem, most probably caused by another vps that shares the disk with you. This kind of problem drove me crazy, until I moved to an ssd cloud server - more expensive but much better disk performance, thus less memory and cpu needs.
Answer: It is normal for the CPU usage to be at 100% when FFMPEG runs. Video compression is a computationally difficult task.
See this related question. If you have a two core VPS then you could make sure that FFMPEG only uses one core and thus always leaves at least one core for Apache/PHP/MySQL.
I created a similar site and it generally worked but it certainly had the occasional errors. It was a 4-core VPS and when transcoding all four cores were often at 100%. If I were to design the site again I think I would use a video transcoding service such as Amazon's Elastic Transcoder. Making sure FFMPEG would recognize all the different file encodings especially MP4 was quite a pain.
Answer: You may try File Resumable Upload:

File Resumable Upload aka file_resup adds large files multiple and
  resumable upload to the File and Image field widgets.
Answer: I think you can do it with Remote File Source module without affecting locally.

Remote File Source allows you to add a file from a remote server to a
  filefield without transferring it locally.
Comment: I want to add files to the server and convert it into various format so that i can play it in various browsers. Also that is the requirement.

Large file upload guidelines


volume of the region bounded by the surfaces $x = 0, y = x, y = 2 - x^2, z = 0$ and $z = x^2$

Question: Find the volume of the region in the first octant bounded by the surfaces $x = 0, y = x, y = 2 - x^2, z = 0$ and $z = x^2.$
It is difficult for me recognize the region geometrically. Can someone please give some idea about the sketch of the region?
I am confused with the limits of integration.
Required volume = $\int_{z = ?}^{?}\int_{y = ?}^{?}\int_{x = ?}^{?}dxdydz.$
Answer: You can see the desired region in the $xy$-plane in this graph.

And $z$ goes from $0$ to $x^2$, so your desired integral is
$$\int_{x=0}^1 \int_{y=x}^{2-x^2}\int_{z=0}^{x^2} \,dz\,dy\,dx$$
$$=\int_{x=0}^1 \int_{y=x}^{2-x^2} x^2 \,dy\,dx$$
Note that I put the variables in a different order than you do. That seems to fit the problem better.
Answer: Firstly, consider the region in the $x,y$ plane bounded by $y=x$, $x=0$ and $y=2-x^2$. We see that, for a given $x$, that $y$ ranges from $x$ to $2-x^2$. If we make a similar diagram for $x,z$, we find that $z$ ranges from $0$ to $x^2$. We have that $x$ ranges from $0$ to $1$, as $y=x$ intersects $y=2-x^2$ at $x=1$. This gives the integral as
$$\int_{x=0}^{x=1} \int_{y=x}^{y=2-x^2} \int_{z=0}^{z=x^2} \mathrm{d}z\mathrm{d}y\mathrm{d}x$$


Guitar amp fender 15B

Question: How do I get distortion on my fender 15B amp if it doesn't have a distortion switch or a button? I have tried using existing knobs but just cant get the rock sound I'm after.
Answer: The Fender 15B is a bass amp. Bass amps are usually focused on clean signal replication and most do little to color the sound of the instrument whereas guitar amps impart more tonal signature to the sound.
As you are looking for distortion I assume you are not using a bass as this this effect is rarely used by bassists.
If you are playing an normal 6 string guitar you will need to either buy a distortion pedal or an suitable amp.

Guitar amp fender 15B


AngularJs: Unknown provider: $resourceProvider <- $resource <- DonorerCtrl

Question: I am trying to load in a list of "donors" for my angular application. I get the data from an API, but I doesn't work the way I want it to. I get this error:
$resourceProvider <- $resource <- DonorerCtrl
In my DonorerCtrl class I have the following code:
angular.module("testApp").controller("DonorerCtrl",
function($scope, $http, $resource) {
    console.log("Test fra donorerCtrl");

    $scope.donorerResource = $resource("http://bloodadmin.cloudapp.net/api/users/:donorid"),
    {id: "@donorid"}, { update: {method: "PUT"}};

    $scope.donorerVisits = $scope.donorerResource.query();

    $http (
        {
            method: "GET",
            url: "http://bloodadmin.cloudapp.net/api/donors"
        }).success(function(data) {
            $scope.donorerVisits = data;
        }).error(function() {
            alert("error");
        });

    $scope.donorerVisits = [];

});

I try to load it in my HTML file with this code:

            Fornavn
            Efternavn
            Køn
            Fødselsdag
            Læs mere

            {{visit.firstname}}
            {{visit.lastname}}
            {{visit.sex}}
            {{visit.age}}
            <button class="btn btn-default">Læs mere</button>

In my Index html I load in these JS files:

Answer: try:
angular.module("testApp", ['ui.router', 'ngResource']);

Comment: Thanks, seems to work, but now I have this error:
index.html:1 XMLHttpRequest cannot load http://bloodadmin.cloudapp.net/api/donors. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
Comment: You need to enable [CORS](https://gist.github.com/mlynch/be92735ce4c547bd45f6) on server side.


Convert DateTime with milliseconds to SQL DateTime

Question: I'm making a query like this :
<code>@" if (" + logic + @")
begin
    INSERT INTO [FRIIB].[dbo].[Incidents]
        ([RecTime]
        ,[Name]
        ,[Message])
    VALUES
        ('"     + dt.ToString("yyyy/MM/dd hh:mm:ss.fff") + //ODBC : Canonical DT Format
</code>
and got SQL like this :
<code>if (( 1 = 1 ))
begin
INSERT INTO [FRIIB].[dbo].[Incidents]
([RecTime],[Name],[Message])
VALUES
('2011.02.14 04:30:10.020',
</code>
and error like this :
can't convert varchar to datetime
How can I fix it ? What am I doing wrong ?
Answer: SQL Documentation about this is here: Supported String Literal Formats for datetime

So you could use ISO8601 (example: 2004-05-23T14:25:10.487), because, as stated in the doc:

The advantage in using the ISO 8601
  format is that it is an international
  standard with unambiguous
  specification. Also, this format is
  not affected by the SET DATEFORMAT or
  SET LANGUAGE setting.
Comment: How can I convert DateTime to 2004-05-23T14:25:10.487 ?
Answer: Hey you do something like this..
<code>  java.util.Date dt = new java.util.Date();

  java.sql.Date sqlDate = new java.sql.Date(dt.getDate());
</code>
and pass this sqlDate as a paremeter..


angularjs - one time binding not give any performance improvement in `ng-repeat`

Question: To increase the speed in ng-repeat instead of 2 way I have changed to single way binding to imporove the speed. But I am not finding any speed performace here at all. can any one help me to improve the speed in ng-repeat please?
my process out put shows as no big changes when i shuffle between 2 with single way ng-repeats
VM780 script.js:30 Process time: 124 //single way
VM780 script.js:30 Process time: 132 //double way
VM780 script.js:30 Process time: 120 //single way
VM780 script.js:30 Process time: 121 // double way
VM780 script.js:30 Process time: 124 // single way

here is the ng-repeat i use :

{{::d.name}}{{::d.address}}{{::d.city}}{{::d.country}}

Live Demo
Comment: It additionally should be `::d in data`. The optimization is pointless if you don't know what you're optimizing. In this case next digests will be affected after populating `data` - and there are no next digests. And it is not single way binding at all. It's one time binding.
Comment: actually `::d in data` throws error, instead I use `d in ::data` - But still no performance improvements.
Comment: Yes, it should be d in ::data. Of course, there won't be performance improvements on initial digest. And of course there will be performance improvement for `d in ::data` on next button presses - because data will be bound only once. This may not behave expected (changing $scope.data won't update the table), but there are significant performance improvements - like 100ms vs 5ms.
Answer: The problem here are wrong expectations of performance improvements. The script does nothing that would benefit from these optimizations. It generates a new set of data every time.
Similarly, the methodology for testing performance is also wrong, it just measures that time that it takes to generate a new set of data and do initial digest for it - which would be the same every time.
One-time bindings are beneficial during subsequent digests over same set of data.
A way to measure this is something like
  setInterval(function () {
    console.time('digest');
    $scope.$apply();
    console.timeEnd('digest');
  }, 1000)

This way

{{::d.name}}{{::d.address}}{{::d.city}}{{::d.country}}

will show some performance improvements over

{{d.name}}{{d.address}}{{d.city}}{{d.country}}

And it becomes critical when watchers count becomes higher.


How to find a string with specified length in a text file using findstr or grep command?

Question: I want to find a string of length 8 which starts with the characters "alo", in a text file.
For findstr, I have tried the following command - findstr /R "\<alo" file.txt. This command searches for strings starting with "alo" but cannot search for strings of length 8. For grep, I don't know how to do it.
Comment: Then I'd try `grep -E '\'`.
Comment: By "string", do you mean a line or a word?
Comment: Consider the following examples - Eg - alo44531, alogto99, etc
Comment: Are those meant to be examples of lines or words?
Comment: They are words.
Answer: grep -E '^alo(.*){5}$' filename

Answer: grep -woE  'alo.{5}' filename

-o is for printing only the match
-E is to use extended regex
-w will make the given expression match only whole words
The number inside the parenthesis specifies the number of character to match after the letters 'alo'


Apache2 configuration, .htacces and 310 error (www redirection)

Question: I have an ubuntu apache serveur, with many websites.
all my website have the same bug ( so it's look like a misconfiguration)
http://www.2sigma.fr <- it's work fine ( we see "en travaux")
http://2sigma.fr <- dont work, i got 310 error (cyclic redirection!)
here my .htaccess
Options +FollowSymlinks
RewriteEngine on
RewriteCond  %{HTTP_HOST}      ^2sigma\.fr$
RewriteRule  ^(.*)             http://www.2sigma.fr/$1      [R=301,L]

here my confguration
<VirtualHost *:80>
<IfModule mpm_itk_module>
AssignUserId sigma www-data
</IfModule>

    ServerAdmin email@example.com
    ServerName 2sigma.fr
    ServerAlias www.2sigma.fr
    DocumentRoot /home/sigma/www
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /home/sigma/www>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>
    ErrorLog /var/log/apache2/error_sigma
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
     CustomLog /var/log/apache2/access_sigma combined
    ServerSignature Off

If i use this .htaccess it's work fine :
Options +FollowSymlinks
RewriteEngine on
RewriteCond  %{HTTP_HOST}      ^2sigma\.fr$
RewriteRule  ^(.*)             http://www.google.fr/$1      [R=301,L]

I think that it is a apache configuration probleme... but i dont kno how to solve it.
Thanks for your help
Answer: Try this in your .htaccess:
  RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
  RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Comment: Are you sure there's not other outside influences? You might want to (very briefly) enable debug output to your logs to track the rules being parsed.
Comment: Hi,thanks for the help but it dont work. both http://2sigma.fr and http://www.2sigma.fr show the index.html without any rewriting
Comment: it's look like the rewritecond **%{HTTP_HOST} !^www\..+$ [NC]** dont match..
Comment: Did you restart apache to ensure it took effect?
Comment: yes... but no effect.


Which is the best way to create a tensor of frames to classify videos with Keras CNN-LSTM

Question: everyone, i'm facing the following problem.
I have a CNN-LSTM Keras Model to video classification. I'm trying to create a tensor to store frames i've got with OpenCV, as you can see in this snippet of code:
for i in list1:
    #Video Path
    vid = str(path + i) #path to each video from list1 = os.listdir(path)
    #Reading the Video
    cap = cv2.VideoCapture(vid)
    #To Store Frames
    frames = []
        for j in range(15): #i want 15 frames from each video
        ret, frame = cap.read()
        if ret == True:
            print('Class 1 - Success! {0}'.format(count))
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        frame = cv2.resize(frame,(28,28),interpolation=cv2.INTER_AREA)
        frames.append(frame)
X_data.append(frames)

But the problem is that i repeat this code for two classes of videos, and the shape of my final X_data is (2, 15, 28, 28). Should not that have more than 2 samples, once i have 145 videos in each folder?
My idea is to add another column to this X_data with the targets, 1 for the Class 1 of videos, and 0 for the Class 2 of videos, but with this shape i don't know what i have to do. :/
It is the best way to store 15 frames of each video in a tensor in order to use it to train a classifier (CNN-LSTM)?
Someone help me, please!
Thanks for the attention!
Answer:     frames = []  <# You reset frames on each video
        loop to construct frames
X_data.append(frames) <#You add the frames into X_data but frames only
                        has frames from last video in list1

You might want to move the X_data into the loop or something along those lines
Something along these lines will work:
for class,video_list in enumerate([negative_videos, positive_videos]):
    for i in list1:
        #Video Path
        vid = str(path + i) #path to each video from list1 = os.listdir(path)
        #Reading the Video
        cap = cv2.VideoCapture(vid)
        #To Store Frames
        frames = []
        for j in range(15): #i want 15 frames from each video
            ret, frame = cap.read()
            if ret == True:
                print('Class 1 - Success! {0}'.format(count))
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            frame = cv2.resize(frame,(28,28),interpolation=cv2.INTER_AREA)
            frames.append(frame)
        X_data.append(frames)
        y_data.append(class)


Spring Constant -> Create second order equation

Question: The Problem:
A frictionless spring with a 10-kg mass can be held stretched 1 meters beyond its natural length by a force of 40 newtons. If the spring begins at its equilibrium position, but a push gives it an initial velocity of 2.5 m/sec, find the position of the mass after t seconds.
How do I convert this to a second order equation and then solve it?
Spring constant would be 40nm = k * 1 meter -> k = 40
Thanks
ATTEMPTS BASED ON COMMENTS/ANSWERS
<code>10x'' + 40x = 0, when x(0) = 1 and x'(0) = 2.5

10r^2 + 40 = 0

10r^2 = -40

r^2 = -4

r = +- 2i

y  = Acos(2x) + Bsin(2x) = homogenous solution

y' = -2Asin(2x) + 2Bcos(2x)

1 = Acos(2*0) + Bsin(2*0) = A

2.5 = -2Asin(2*0) + 2bcos(2*0) = 2B

y = cos(2x) + 5/4sin(2x)
</code>
Answer: Hooke's law tells you that
$$F = -k x$$
and Newton's second law, that
$$F = ma = m\ddot{x}.$$
Putting these pieces together you get that
$$m\ddot{x} = -kx$$
or
$$10\ddot{x} = -40x,$$
which is the second-order equation you wanted. To solve it, you need a pair of initial conditions, which the problem provides you: $x(0) = 0$ (since the initial position is $0$) and $\dot{x}(0) = 2.5$ (I'm assuming the push gives it a velocity in the direction of increasing distention; the problem really should be more precise.) If you need help solving the ODE, you can ask, but first show the work of your attempt.
Comment: I think I did it, can you verify my setup please
Comment: Looks good to me!


Exchange web Services failed to connect

Question: I have an exchange online service in my office 365,
and i want to send email to other person mailbox, using different method
then i found Exchange Web Services, so i tried to do the basic example:
class Program
{
    static void Main(string[] args)
    {
        //note that there no option for exchange server 2016 (my exchange online use exchange server 2016), so i use the default option
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

        service.Credentials = new WebCredentials("email@example.com", "myPassword");
        service.UseDefaultCredentials = false;

        //for log purpose
        service.TraceEnabled = true;
        service.TraceFlags = TraceFlags.All;

        service.AutodiscoverUrl("email@example.com", RedirectionUrlValidationCallback);

        EmailMessage email = new EmailMessage(service);
        email.ToRecipients.Add("firstname.lastname@example.com");
        email.Subject = "HelloWorld";
        email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
        email.Send();

    }

    private static bool RedirectionUrlValidationCallback(string redirectionUrl)
    {
        // The default for the validation callback is to reject the URL.
        bool result = false;

        Uri redirectionUri = new Uri(redirectionUrl);

        // Validate the contents of the redirection URL. In this simple validation
        // callback, the redirection URL is considered valid if it is using HTTPS
        // to encrypt the authentication credentials.
        if (redirectionUri.Scheme == "https")
        {
            result = true;
        }
        return result;
    }
}

and there is exception in the AutodiscoverUrl, like this:
Microsoft.Exchange.WebServices.Data.ServiceXmlDeserializationException: 'The
expected XML node type was XmlDeclaration, but the actual type is Element.'

after i search a while, it said that exchange cannot find my domain, my exchange online setting is fine, i can send email, add appointment via outlook web access to other person in my mailbox
i've already change my nameserver to
ns1.bdm.microsoftonline.com
ns2.bdm.microsoftonline.com
but still doesn't fix my problem..
are there some setting that i missing?
Thx..
Answer: Instead of using
 service.AutodiscoverUrl("firstname.lastname@example.com", RedirectionUrlValidationCallback);

try
 service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

I would suggest you set
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

to the highest enumeration for Office365 rather then the lowest unless you trying to support Exchange 2007.

Exchange web Services failed to connect


Particle filter in Matlab - what is going wrong?

Question: I posted this question on Electronics.Stackexchange and someone told me I'll be better off posting it here.
Its an implementation of the Particle Filter using MATLAB but the results never follow the observations. I changed the weighting function to be Gaussian but still no avail.
NOTE: I haven't taken into account that the process/measurement noise is time-correlated. Will this significantly change the accuracy of my program? If so, how do I correct for it?
MY OLD QUESTION
I'm working on a particle filter experiment for multi-sensor fusion and I just programmed it in MATLAB. However, I get very low accuracies for my final values. Plus, I read a lot of literature where they talk about pdf of state and observations etc. but my practical knowledge is still extremely shaky, since I've had no formal training in filtering/Bayesian estimates etc.
I have devised my algorithm like this:

Initialize particles = I'm doing it as a Gaussian distribution - 10 particles
Move the 10 particles forward using the state transition equation:

\begin{equation}
X_{t+1} = A \times X_t + 0.1 \times rand()
\end{equation}
I'm only injecting Gaussian noise so far.

Using the observation, calculate the weights for the particles. I do this like a root mean square of the difference between predicted state and observation. For example, if my azimuth(a) = 40, pitch(p) = 3, roll(r)=4 in my state and in my observation it is a = 39, p = 3, r = 3, then I do rms = sqrt((40-39)^2 + (3-3)^2 + (4-3)^2). Then my weight is assigned as 1/rms in order for it to be inversely proportional to the 'distance' between the prediction and observation
Then I normalize these weights to get norm_weight = weight/norm(weight) so that their sum is equal to one.
Then I continue forward for all the observations. I have not included resampling yet because when I run this experiment, I do not experience any degeneracy, which is also very puzzling.

Where am I going wrong? I realized that I haven't 'computed' a lot of the Bayesian equations given in the literature i.e.
\begin{equation}
p(x|z_t) = p(z_t|x)\times p(x)/p(z)
\end{equation}
and I don't know where it fits in here either. Can somebody please help me?
My Matlab code looks like this:
function resultx = particlefilter(resultx_1, observationx, A, noiseP)
  for j = 1:length(observationx)
    for i = 1:length(resultx_1)
      apriori_state{i} = A*resultx_1{i} + noiseP;
      rms(i) = sqrt((observationx{j}(1) - apriori_state{i}(1))^2 +
                     (observationx{j}(2) - apriori_state{i}(2))^2);
      weight(i) = 1/rms(i);
    end;
    norm_weight = weight/norm(weight);
    for i = 1:length(apriori_state)
      plot(apriori_state{i});
    end
    disp(rms);
    disp(norm_weight);
  end

Comment: Please copy the rest of the question here.
Answer: The problem may stem from the fitness ratio you use in your code. The inverse of the distances may give very large differences in the resampling probabilities of the new generation of the samples. For example, let x stand for the rms values in your design and let them be
x = [0.1 1 1 3 10 50]

When you use the inverses, that leads to
y = (1./x) ./ norm(1./x)
y =
    0.9896    0.0990    0.0990    0.0330    0.0099    0.0020

As you see, the first sample dominates the next generation. It may converge to wrong proposals very easily. Alternatively, you may use a sigmoid-like function. For example,
z = exp(-x) ./ norm(exp(-x))
z =
    0.8659    0.3521    0.3521    0.0476    0.0000    0.0000

Now, the particles in the next generation will probably involve some samples similar to the second and third ones. So, the generation scheme will be more robust to erronous proposals.
Edit: Moreover, after dividing by the norms, the sum of the result is not 1. You might use sum instead.
y = (1./x) ./ sum(1./x)
y =
    0.8030    0.0803    0.0803    0.0268    0.0080    0.0016

z = exp(-x) ./ sum(exp(-x))
z =
    0.5353    0.2176    0.2176    0.0295    0.0000    0.0000