Why are `drush pm-list` & `drush pm-updatestatus` disabling the default theme?

Question: I have a Drupal 7 site with 3 themes enabled:

Foo
Adminimal
Shiny

Foo is a custom theme for the front-end, located in /sites/foo/themes/ and set as the default.
Adminimal and Shiny are both installed via drush make into sites/all/themes/contrib/.
Running drush pm-updatestatus disables the default 'Foo' theme.
$ drush pm-updatestatus
Checking available update data ...                             [ok]
Failed to check available update data for Foo settings.        [ok]
Checked available update data for Administration menu.         [ok]
...
Checked available update data for Adminimal.                   [ok]
Checked available update data for Shiny.                       [ok]
Failed to get available update data for one project.           [error]
Checked available update data for 64 projects.                 [status]
 Name                                                        Installed Version  Proposed version  Message
 Administration menu Adminimal Theme (adminimal_admin_menu)  7.x-1.6            7.x-1.7           Update available
...
 Adminimal (adminimal_theme)                                 7.x-1.21           7.x-1.24          Update available
 Shiny (shiny)                                               7.x-1.6            7.x-1.7           Update available

The Failed to check available update data for Foo settings. & Failed to get available update data for one project. [error] lines from the output clearly look relevant, but I'm struggling to identify the underlying cause.
With the Drush's -d debug flag enabled the output includes this line before the Failed to get update data for on project [error]:
Undefined index: foo theme.inc:100 [1.78 sec, 35.7 MB]            [notice]

drush pm-list has the same effect.
Presumably there's something wrong with the declaration, or location of the Foo theme?
Checking the status report via the Drupal admin does not disable the Foo theme.
Why would drush pm-list & drush pm-updatestatus disable the default theme?
Comment: pm-updatestatus queries the Drupal servers for updated versions of modules. If this is a custom module, Drupal has no response from it: `Failed to get update data for on project [error]`. So this is normal for custom modules or themes. It should however not disable the theme.
Answer: Your themes for Drupal 7 should live here:

/sites/all/themes/THEMENAME - for all sites and all themes
/sites/example.com/themes/THEMENAME - for example.com of a multisite setup

Now in your case there is an additional note: You have the option to put your theme in a contrib and a custom subfolder. Themes in the custom subfolder would be skipped during the update process (see /r/drupal for cross reference). There is a caveat though: Apparently once you use contribyou also have to use custom otherwise it seems the whole tree breaks (see disqus)
Try to move the foo theme too: /sites/all/themes/custom/foo or /sites/example.com/themes/custom/foo then run drush rr and drush cc all
Comment: Hi @nhck, thanks for your help. I moved the theme to `/sites/all/themes/custom/foo` and ran `drush rr` and `drush cc all` as you suggested, but it hasn't resolved the issue. Both `pm-list` and `pm-updatestatus` are still disabling the Foo theme.
Comment: Through trial and error we've identified that setting the `--uri=foo.example.com` flag seems to prevent `pm-list` and `pm-updatestatus` from disabling the theme. Is setting the `--uri` flag mandatory for multisite? I haven't been able to find anything in Drush's documentation indicating that it is.
Comment: This article explains why setting `--uri` is significant for multisite, though it does not explain why `pm-list` and `pm-updatestatus` would disable the default theme when Drush is passed insufficient information to identify the multisite site. https://docs.acquia.com/articles/how-use-drush-multisite-installation
Comment: Interessting. Sorry that my answer wasn't sufficient. I've been wondering it there might be something in the info file of your theme that could make drush look for a project on drupal.org?
Comment: I had thought the same, but it looks very vanilla to me: http://pastebin.com/S4qpfBNm


CISCO Catalyst switch API

Question: I have a Cisco catalyst switch and there is a task to code some web gate which will allow billing to control ports in switch, gather different statistics, etc.
What is the modern way to achieve that? Earlier with a supermicro switch I just wrote a PHP script which did a shell_exec passing commands to netcat which connected to the switch. I don't think this the best way to do that so I am asking for help.
Maybe there are some libraries for that? For Perl I saw a library called Net::Appliance::Session and it looks really good as I see, but I am not that good in Perl so I am looking for something PHP/Ppython based.
Update
What I found so far for Python is Trigger and Exscript. Looks pretty nice for my simple port on/off and speed change tasks:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()
conn = SSH2()
conn.connect('188.8.131.52')
conn.login(account)
conn.execute('conf t')
print conn.response
conn.send('exit\r')
conn.close()

But I still think I am going to have some headache parsing different status reports, so maybe I need to do that using something different or split stats gathering and operation functionality. Use SNMP for stats for example.
Comment: Have a good, hard look at SNMP. This is still a good way to gather that kind of data from a switch.
Comment: Look at Cisco's own CiscoWorks software
Comment: Documentation on it so awful ... I haven't even found concrete CLI examples.
Besides i do not see the point of it. It's a standalone solution and i see how to communicate with it from code.
Comment: You might try the [clogin](http://www.shrubbery.net/rancid/man/clogin.1.html) expect script (part of [RANCID](http://www.shrubbery.net/rancid/))
Comment: You may wish to look at SNMP for writing, too.  See http://stackoverflow.com/questions/9170644/how-can-i-enable-disable-ports-in-cisco-catalyst-2960-with-c for an example.
Comment: I need not only to gather, but to control as well. Like disable port, change port's speed, etc.
Comment: Sorry guys, cannot comment yet, but i wanted to add my 2 here. Have you looked at using just the Paramiko SSH library exclusively in Python instead? Its expect-like, but a little different. Does what you want. I don't want to turn this into a Paramiko vs. Expect argument either. Everyone has their favorite right :-)
Comment: I did. I looked both into Paramiko and Expect. For my tasks they kind of the same. But i wanted to find something more Cisco oriented. I thought that at least somebody once upon a time wrote a small library for doing simple tasks with cisco equipment. And it seems there isn't. Either quite big overloaded libraries or something Paramiko like ...
Answer: I ended up using PySNMP. It wasn't clear that SNMP v3 has pretty encryption and it also allows not only to gather data but also manipulate the device.

CISCO Catalyst switch API


window.addEventListener doesn't work

Question: I was trying to do like press enter key to trigger a function, but it does not work fine.Hope someone can tell me what is wrong. Here is the code:
window.addEventListener("keypress", function () {
    if(key === 13)
        alert("Hello world");
});

Comment: `key` is undefined. What did you expect it to be?
Comment: Maybe you wanted the `.key` property of the event object that is passed as argument to your handler, but you'll need to declare a parameter for that.
Comment: You need to "debug" your code. The first step is opening the console. See if you notice any console errors. You will probably see something like "Uncaught ReferenceError: key is not defined". That will give you a clue as to what is wrong. Or, learn how to use "breakpoints" and place a breakpoint on the `if (key === 13)` line. When it stops there, examine the `key` variable and you will find that it is not defined. For more information on debugging, see https://ericlippert.com/2014/03/05/how-to-debug-small-programs/.
Answer: You have to get the event from the function that was attached to the keypress

http://jsfiddle.net/arunpjohny/SZ9TG/1/

window.addEventListener doesn't work


finding the radius of a cylinder based on camera position

Question: Not entirely sure this is the right forum, but I'll give it a go.
I have a cylinder that is projected onto a 2d plane (3d world with a virtual camera).
What I want to figure out is, given a point on the 2d viewing plane, how large does the cylinder need to be in order for it's "edge" to align with said point

Basically from that image:
given the red point how much larger does the cylinder have to be? (the blue line)
Comment: What do you mean by "it's edge", do you mean the "surface" of the cylinder, or do you mean the "upper circular edge" ?
Comment: I think I mean the surface
Answer: If you mean the bottom of the cylinder reaching the red point, you need 'Pythagoras Theorem'.
Just ignore the height of the cylinder.
You can  then work out its required radius (AB), in the 2D plane like this

Alternatively, if you mean that the cylinder should be enlarged to reach the dotted blue line, then it should be $4$ times the radius, going from a radius of $5$ to $20$, so the radius should be increased by $15$ units (green line)
Comment: I think same thing goes for the top of the cylinder. just throw a line from the camera towards the point(raycast) and see where that intersects the plane p0 (0,,0) and n (0,1,0). Then after ignoring the Y value of the intersection you can rightfully use pythagoras to get the upper radius


Inverse of a special Vandermonde Matrix with elements $i^{j-1}$

Question: I have a $(n+1) \times (n+1)$ Vandermonde matrix
$$
V_n=
\begin{pmatrix}
1 & 1 & \dots & 1\\
1 & 2 & \dots & 2^n\\
\vdots & \vdots & \ddots & \vdots\\
1 & n+1 & \dots & (n+1)^n\\
\end{pmatrix}
$$
and by observation (and lots of oeis.org searching) I suspect that
$$
V_n^{-1}=(b_{i,j})
$$
with
$$
b_{i,j}=\frac{(-1)^{i+j}}{n!}\binom{n}{j-1}\sum_{m=0}^{n+1-i} (-j)^{m}{ n+2\brack i+1+m}
$$
where ${ n\brack m}$ are unsigned Stirling numbers of the first kind. Now I wonder how to prove this?
My attempt
I am aware there is a Matrix inverse formula for Vandermonde matrices, for example mentioned in this post, but I failed to match it to the formula above. Another approach where I got farther was to use the definition of matrix multiplication for $V_{n}^{-1}V_n=(c_{i,j})$ and see whether it simplifies to the identity matrix. Here I've got after some algebra mess (it is lengthy to include here, but I can add if needed) to
$$
c_{i,j}=(-1)^{n+i-j}\sum_{k=n}^{n-i+j}(-1)^{k}{ n+2\brack k+i-j+2} {k+1 \brace n+1}.
$$
(here ${n \brace m}$ are Stirling numbers of the second kind for a change...)
From this we can see that for $j<i$ the sum is empty and we get a zero under the diagonal. For $i=j$ we get $c_{i,i}=1$ on the diagonal. So to finish the proof it needs to be shown there are zeroes above the diagonal, i.e. $c_{i,j}=0$ for $i<j$, and that is where I could not get any further.
Can we prove the last step somehow? Or is there another way to prove the inverse identity?
Answer: Use formula
$$V_n=S_nD_nP_n^T \tag{1}$$
which implies:
$$V_n^{-1}=(P_n^{-1})^T D_n^{-1}\underbrace{S_n^{-1}}_{s_n}\tag{2}$$
where $s_n$, resp. $S_n$, are the lower triangular matrices with Stirling numbers of the first, resp. second kind, $D_n=diag(1!, 2!, \cdots n!)$, and $P_n$ the lower triangular Pascal matrix.
Formula (1) is detailed in lemma 2 of this very interesting article entitled "On a connection between the Pascal, Stirling and Vandermonde matrices" by Yang and You (not Me and You). This article is mentionned in particular here where you will find other interesting informations.
It must be added that the inverse of Pascal matrix is easy to describe : it is obtained from $P_n$ by multiplying its entries $a_{ij}=\binom{i-1}{j-1}$ by $(-1)^{i+j}$.
From (2), can you retrieve your formula ? (for example the $(-1)^{i+j}$ comes from the above mentionned inversion of $P_n$).
Remark: Your attempt looks like verifying that $S_ns_n=I$, a property we have used above.
Comment: Thank you for the great reference! It works indeed, so far using these I have found $b_{i,j}=\sum_{m=1}^{n+1}\frac{(-1)^{m+j}}{(m-1)!}s(m,i)\binom{m-1}{j-1}$ which will be easy to transform to that of mine.
Comment: See as well this paper: "Symmetric functions and the Vandermonde matrix" (by Oruç and Akmaz), in particular their Theorem 4.1


Imprimir posição de uma matriz

Question: A intenção neste programa seria imprimir a posição linha e coluna em que se localiza o maior valor da dentro da matriz, alguém sabe me dizer por que no resultado está imprimindo 0x0 e se existe outro caminho mais eficaz? No meu teste é claro, o valor maior digitado não foi o primeiro.
#include<stdio.h>
#include<stdlib.h>

int matriz[3][3],i,j,maior=0,i1,j1;

main(){
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            printf("Digite um valor: ");
            scanf("%d",&maior);
            if(matriz[i][j]>maior){
                maior=matriz[i][j];
                i1=i;
                j1=j;
            }//fim if
        }//fim for j
    }//fim for i
    printf("%d x %d \n",i1,j1);
    system("pause");
}//fim do main

Comment: Sua matriz não é inicializada em lugar nenhum.
Answer: Mude:
scanf("%d",&maior);

Para:
scanf("%d",&matriz[i][j]);

Você não está lendo o valor correto.

Imprimir posição de uma matriz


Javascript, toggle display of two divs based on foreach on JSON object

Question: The basic thing I'm trying to do here is iterate through this JSON object containing 2 records (always only 2 records) and getting the value, which is a URL. Then setting the src of two divs to each of those URLS (which then creates two divs on the page that embed a PDF file), and finally toggling the display of each so that at any given time one of the embeds is display:block and one is display:none (only one embed should show at any given time, and they should cycle every 60 seconds.
The issues I have right now:

Setting the URL of each object as the src of each div
properly toggling the display of the divs, only setting each to hidden currently

How can I change my forEach here in order to properly toggle the displays of the embed sections, and how would I properly set the src of each embed with the corresponding URL value from the object?
<code>@section('content')

<embed class="pdf" src="https://test.s3.aws/test1.pdf#zoom=85&view=Fit&scrollbar=0&toolbar=0&statusbar=0&navpanes=0 " style="margin-top: 40px;position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">

<embed class="pdf" src="https://test.s3.aws/test2.pdf#zoom=85&view=Fit&scrollbar=0&toolbar=0&statusbar=0&navpanes=0 " style="margin-top: 40px;position:absolute; left: 0; top: 0; display:none" width="100%" height="100%" type="application/pdf">

@endsection

@section('loadjs')

<script>

var files = {"1":"https://test.s3.aws/test1.pdf",
             "2":"https://test.s3.aws/test2.pdf"}
;
const result = JSON.parse(files);

Object.entries(result).forEach((entry) => {
    const [key, value] = entry;
    console.log(`${key}: ${value}`);

    //need to get the URL, which is value here, into the src of each div
})

const divs = document.getElementsByClassName('pdf');

for(let i = 0; i < divs.length; i++) {
    setTimeout(() => {
        divs[i].style.display = none;
    }, i * 60000)
  }

//toggle display:none for each embed with a 60second timer

</script>

@endsection
</code>
Answer: Build the element you need with javascript
<code>Function myEmbeds (opt) {

let p = document.createElement("embed")
p.height = window.innerHeight
p.source = files[opt] // the url
p.type = "application/pdf"
p.width = window.innerWidth
return p
}
setTimeout(() => {
        document.appendChild(myEmbeds(1)) //i is even etc...
    }, i * 60000)

</code>
Comment: I think this makes sense to me for the most part, but how would I append the argments after the url starting with the ```#zoom```?
Comment: Modify the `source` parameter of the element. Maybe define a string constant from your files object `const partOfSource = files[0] + '#zoom'; `. Also,   Sorry I didn't get the appendChild() finished in the answer but that's just iterations on 1 or 0


Tenor API occasional returning undefined property

Question: Using the Tenor GIF Api.  I get this error, only about 10% of the time, the other 90% it works:
caught TypeError: Cannot read properties of undefined (reading 'media_formats')
var response_objects = JSON.parse(responsetext);

top_10_gifs = response_objects["results"];

var index = getRandomInt(10);

var image = document.getElementById("share_gif");
image.src = top_10_gifs[index]["media_formats"]["gif"]["url"];

var dimX = top_10_gifs[index]["media_formats"]["gif"]["dims"][0];
var dimY = top_10_gifs[index]["media_formats"]["gif"]["dims"][1];

return;

it throws the error where it tries to read the first ['media_formats'], saying it can't read undefined.
The object is loaded however, if I console.log the object right before that line it will have an object.  For some reason, only a small percentage of times, it is undefined.
Not sure why it's doing that.  Thanks
Comment: Sounds like `index` isn't a valid index in your array. Make sure that `getRandomInt(10)` is only returning values that are valid indexes in `top_10_gifs` and doesn't try and access an element beyond its length.
Comment: I am embarrassed to say, but the problem was that I was grabbing 8 GIFs when I called the API and then I was getting a random number up to 9, so the times when 9 was my random number it would return undefined.  I should've realized, the answer is in my question, it was only happening about 10% of the time.
Comment: Yes it was extremely obvious when you said it fails 1/10 times and that you also have code that creates a random number (10).
Answer: You can use a function like this to select a pseudorandom element from an array:
function getRandomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

Below is a code sample to help. It uses a payload that was obtained by using the example query in the API docs at the Trending GIFs endpoint.
Be sure to read the API documentation to understand the structure of the responses.

function getRandomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

/** @see https://tenor.com/gifapi/documentation#responseobjects-gif */
function extractGifProperties(gifObject) {
  const firstMediaObject = gifObject.media[0]?.gif;
  if (!firstMediaObject) throw new Error("Object has no media");
  const { dims: [x, y], url } = firstMediaObject;
  return { url, x, y };
}

const exampleJsonResponse = `{"locale":"en","results":[{"id":"18362005","title":"","content_description":"Riding Ride GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[498,373],"url":"https://media.tenor.com/i5_1W_8TSCwAAAAC/riding-ride.gif","preview":"https://media.tenor.com/i5_1W_8TSCwAAAAD/riding-ride.png","size":692155}}],"bg_color":"","created":1599383710.072795,"itemurl":"https://tenor.com/view/riding-ride-em-kentucky-derby-gif-18362005","url":"https://tenor.com/bpcXx.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"11877851","title":"fascinator hat","content_description":"Fascinator Hat GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[400,224],"size":1029336,"preview":"https://media.tenor.com/HZ0WxfZCCzUAAAAD/fascinator-hat.png","url":"https://media.tenor.com/HZ0WxfZCCzUAAAAC/fascinator-hat.gif"}}],"bg_color":"","created":1527135800.757915,"itemurl":"https://tenor.com/view/fascinator-hat-fascinator-hat-derby-hat-kentucky-derby-hat-gif-11877851","url":"https://tenor.com/XZ8p.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"25733140","title":"","content_description":"Congratulations Graduates GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[498,490],"preview":"https://media.tenor.com/Gav-54IlnzoAAAAD/congratulations-graduates.png","url":"https://media.tenor.com/Gav-54IlnzoAAAAC/congratulations-graduates.gif","size":1690200}}],"bg_color":"","created":1653070690.161676,"itemurl":"https://tenor.com/view/congratulations-graduates-2022-smile-thumbs-gif-25733140","url":"https://tenor.com/bT8wO.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"25612481","title":"","content_description":"Happy Nurses Day Nurses Week2022 GIF","content_rating":"","h1_title":"","media":[{"gif":{"preview":"https://media.tenor.com/9eFhF10aFk8AAAAD/happy-nurses-day-nurses-week2022.png","size":1705147,"url":"https://media.tenor.com/9eFhF10aFk8AAAAC/happy-nurses-day-nurses-week2022.gif","dims":[498,498]}}],"bg_color":"","created":1651905045.451034,"itemurl":"https://tenor.com/view/happy-nurses-day-nurses-week2022-gif-25612481","url":"https://tenor.com/bTC8H.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"20131689","title":"","content_description":"Nurse GIF","content_rating":"","h1_title":"","media":[{"gif":{"url":"https://media.tenor.com/9R-hX7LdYNgAAAAC/nurse.gif","size":8683504,"preview":"https://media.tenor.com/9R-hX7LdYNgAAAAD/nurse.png","dims":[396,498]}}],"bg_color":"","created":1611786335.480743,"itemurl":"https://tenor.com/view/nurse-gif-20131689","url":"https://tenor.com/bwDkP.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"4952882","title":"Probably... - Jimmy Fallon","content_description":"Probably... - Jimmy Fallon GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[360,202],"preview":"https://media.tenor.com/sgpv_xrzl1kAAAAD/probably-jimmy-fallon.png","size":287873,"url":"https://media.tenor.com/sgpv_xrzl1kAAAAC/probably-jimmy-fallon.gif"}}],"bg_color":"#312b16","created":1453218819.305683,"itemurl":"https://tenor.com/view/probably-jimmy-fallon-probably-so-late-night-talk-show-gif-4952882","url":"https://tenor.com/uWDm.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"20573934","title":"","content_description":"Maury Lie GIF","content_rating":"","h1_title":"","media":[{"gif":{"preview":"https://media.tenor.com/S7o7J22Ug6gAAAAD/maury-lie.png","size":1240277,"dims":[498,351],"url":"https://media.tenor.com/S7o7J22Ug6gAAAAC/maury-lie.gif"}}],"bg_color":"","created":1614641701.426476,"itemurl":"https://tenor.com/view/maury-lie-detector-truth-gif-20573934","url":"https://tenor.com/byunO.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"11914056","title":"","content_description":"Vacation Beach GIF","content_rating":"","h1_title":"","media":[{"gif":{"preview":"https://media.tenor.com/86M19TSvg5wAAAAD/vacation-beach.png","dims":[354,498],"url":"https://media.tenor.com/86M19TSvg5wAAAAC/vacation-beach.gif","size":1740550}}],"bg_color":"","created":1527713768.214871,"itemurl":"https://tenor.com/view/vacation-beach-palmtree-island-tropical-gif-11914056","url":"https://tenor.com/X9ym.gif","tags":[],"flags":[],"shares":1,"hasaudio":true,"hascaption":false,"source_id":"","composite":null},{"id":"12894208","title":"","content_description":"Rowan Atkinson Crown GIF","content_rating":"","h1_title":"","media":[{"gif":{"size":1284039,"preview":"https://media.tenor.com/vkNNRDGgVyIAAAAD/rowan-atkinson-crown.png","url":"https://media.tenor.com/vkNNRDGgVyIAAAAC/rowan-atkinson-crown.gif","dims":[434,480]}}],"bg_color":"","created":1542331771.337598,"itemurl":"https://tenor.com/view/rowan-atkinson-crown-crowing-king-mr-bean-gif-12894208","url":"https://tenor.com/2gxg.gif","tags":[],"flags":[],"shares":1,"hasaudio":true,"hascaption":false,"source_id":"","composite":null},{"id":"21617044","title":"","content_description":"Eurovision2021 Esc2021 GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[498,305],"preview":"https://media.tenor.com/qFg0O1EY-tUAAAAD/eurovision2021-esc2021.png","url":"https://media.tenor.com/qFg0O1EY-tUAAAAC/eurovision2021-esc2021.gif","size":3016431}}],"bg_color":"","created":1621421522.757008,"itemurl":"https://tenor.com/view/eurovision2021-esc2021-eurovision-esc-esc2022-gif-21617044","url":"https://tenor.com/bCRKa.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"12737723","title":"","content_description":"Meme Funny GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[286,200],"size":94453,"preview":"https://media.tenor.com/oliG35OmL8oAAAAD/meme-funny.png","url":"https://media.tenor.com/oliG35OmL8oAAAAC/meme-funny.gif"}}],"bg_color":"","created":1540145260.515944,"itemurl":"https://tenor.com/view/meme-funny-gif-12737723","url":"https://tenor.com/1BPj.gif","tags":[],"flags":[],"shares":1,"hasaudio":true,"hascaption":false,"source_id":"","composite":null},{"id":"20756900","title":"","content_description":"Honeycardi GIF","content_rating":"","h1_title":"","media":[{"gif":{"preview":"https://media.tenor.com/6iPz_tx_FWwAAAAD/honeycardi.png","dims":[498,498],"size":4681711,"url":"https://media.tenor.com/6iPz_tx_FWwAAAAC/honeycardi.gif"}}],"bg_color":"","created":1615840348.277114,"itemurl":"https://tenor.com/view/honeycardi-gif-20756900","url":"https://tenor.com/bzfYS.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"17009888","title":"","content_description":"Friends Best Friends GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[498,498],"url":"https://media.tenor.com/D5j9wmeBnNEAAAAC/friends-best-friends.gif","size":916834,"preview":"https://media.tenor.com/D5j9wmeBnNEAAAAD/friends-best-friends.png"}}],"bg_color":"","created":1587879474.619193,"itemurl":"https://tenor.com/view/friends-best-friends-having-a-friend-like-you-is-priceless-gif-17009888","url":"https://tenor.com/bjxdc.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"15307671","title":"","content_description":"Taco Time Dancing GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[286,498],"url":"https://media.tenor.com/WfPqwlGNOsUAAAAC/taco-time-dancing.gif","preview":"https://media.tenor.com/WfPqwlGNOsUAAAAD/taco-time-dancing.png","size":3501360}}],"bg_color":"","created":1571189538.525299,"itemurl":"https://tenor.com/view/taco-time-dancing-nido-drums-drums-gif-15307671","url":"https://tenor.com/bcon5.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"18961518","title":"","content_description":"Fish GIF","content_rating":"","h1_title":"","media":[{"gif":{"url":"https://media.tenor.com/34rdAROzAQsAAAAC/fish.gif","preview":"https://media.tenor.com/34rdAROzAQsAAAAD/fish.png","dims":[498,348],"size":881917}}],"bg_color":"","created":1603768655.896917,"itemurl":"https://tenor.com/view/fish-gif-18961518","url":"https://tenor.com/brIU6.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"18125358","title":"","content_description":"Meme Yugioh GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[498,350],"url":"https://media.tenor.com/21S1aJvKD9UAAAAC/meme-yugioh.gif","preview":"https://media.tenor.com/21S1aJvKD9UAAAAD/meme-yugioh.png","size":2142713}}],"bg_color":"","created":1597553062.920117,"itemurl":"https://tenor.com/view/meme-yugioh-anime-cartas-yami-gif-18125358","url":"https://tenor.com/bodoE.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"16557937","title":"","content_description":"Be The Light Darkness To Light GIF","content_rating":"","h1_title":"","media":[{"gif":{"url":"https://media.tenor.com/_RfAI2hfItoAAAAC/be-the-light-darkness-to-light.gif","preview":"https://media.tenor.com/_RfAI2hfItoAAAAD/be-the-light-darkness-to-light.png","size":9985015,"dims":[498,498]}}],"bg_color":"","created":1583964534.465082,"itemurl":"https://tenor.com/view/be-the-light-darkness-to-light-everything-is-connected-love-and-light-blessed-be-gif-16557937","url":"https://tenor.com/bhDDF.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"13967115","title":"","content_description":"Macedonia Macedonia Is Greek GIF","content_rating":"","h1_title":"","media":[{"gif":{"dims":[480,480],"preview":"https://media.tenor.com/5e9U1oDOSrIAAAAD/macedonia-macedonia-is-greek.png","size":2174073,"url":"https://media.tenor.com/5e9U1oDOSrIAAAAC/macedonia-macedonia-is-greek.gif"}}],"bg_color":"","created":1555708885.461171,"itemurl":"https://tenor.com/view/macedonia-macedonia-is-greek-macedonian-star-vergina-pella-gif-13967115","url":"https://tenor.com/6LEd.gif","tags":[],"flags":[],"shares":1,"hasaudio":true,"hascaption":false,"source_id":"","composite":null},{"id":"17060441","title":"","content_description":"Cinco De Mayo Happy Cinco De Mayo GIF","content_rating":"","h1_title":"","media":[{"gif":{"url":"https://media.tenor.com/VQCKbMN4IjAAAAAC/cinco-de-mayo-happy-cinco-de-mayo.gif","dims":[498,498],"size":302326,"preview":"https://media.tenor.com/VQCKbMN4IjAAAAAD/cinco-de-mayo-happy-cinco-de-mayo.png"}}],"bg_color":"","created":1588279889.435228,"itemurl":"https://tenor.com/view/cinco-de-mayo-happy-cinco-de-mayo-mexico-5th-of-may-fifth-of-may-gif-17060441","url":"https://tenor.com/bjKmz.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null},{"id":"21438393","title":"","content_description":"Dancing Cinco GIF","content_rating":"","h1_title":"","media":[{"gif":{"preview":"https://media.tenor.com/fqOhkgayXxoAAAAD/dancing-cinco.png","size":3740089,"dims":[336,498],"url":"https://media.tenor.com/fqOhkgayXxoAAAAC/dancing-cinco.gif"}}],"bg_color":"","created":1620230573.113449,"itemurl":"https://tenor.com/view/dancing-cinco-de-mayo-celebration-gif-21438393","url":"https://tenor.com/bB7gH.gif","tags":[],"flags":[],"shares":1,"hasaudio":false,"hascaption":false,"source_id":"","composite":null}],"next":"1683294157.535297"}`;
const data = JSON.parse(exampleJsonResponse);

const first10Results = data.results.slice(0, 10);
const gifObject = getRandomElement(first10Results);
if (!gifObject) throw new Error("Results array was empty");
const properties = extractGifProperties(gifObject);

console.log(properties);
Answer: I used the example from the docs and they were spot on: https://developers.google.com/tenor/guides/quickstart
I got an undefined error because I was grabbing 8 GIFs and then using a random number to choose one of those GIFs.  The random number was 0-9, so when it chose 9 it would return undefined.


Fazer um update de varios campos e valores em uma mesma tabela

Question: Estou fazendo um sistema muito simples para controle de estoque, e na parte de editar os produtos, eu estou fazendo desta forma: faço uma query num banco de dados, e listo campos de texto com o nome dos produtos e a quantidade respectiva, como na imagem em anexo:

Desta forma o usuário poderia alterar tudo o que quisesse, e ao clicar em enviar, fazer um update de todos os campos no banco, de acordo com a ordem certa.
A minha dúvida é: Como fazer isso ?
Atualmente meu formularia está assim:
<form action="update_pcs.php" method="POST">
            Peça
            Qtd.

                <?php foreach($rtn as $pcs){ ?>
                        <input type="text" name="txtNome[]" id="txtNome" value="<?=$pcs['pc_nome']?>" />
                        <input type="text" name="txtQtd[]" id="txtQtd" value="<?=$pcs['num']?>"/>
                        <input type="hidden" name="txtId[]" id="txtId" value="<?=$pcs['id']?>" />

                <?php } ?>

            <input type="submit" value="Enviar" name="btnEnvia" />
    </form>

E o arquivo update_pcs.php, que deve fazer o update:
<?php

    include_once 'mdl.php';
    $conexao = new modelDB();

    $qtd = $_POST['txtQtd'];
    $nom = $_POST['txtNome'];
    $id = $_POST['txtId'];

    $dados = array('nome'=>$nom,
                    'qtd'=>$qtd,
                    'id'=>$id);

    /*isso faz com que o campo nome de $dados seja um array, qtd outro array e id outro*/
    foreach($dados as $dado){

        /* Atualmente estou fazendo desta forma, mas não está funcionando */
        $nomeAt = $dado['nome'];
        $qtdAt = $dado['qtd'];
        $id = $dado['id'];

        $conexao->alteraDb("update pcs_estq set pc_nome ='{$nomeAt}', num = '{$qtdAt}' where id = '{$idAt}'");
    }

A função está correta pois quando troco as variaveis por valores, funciona corretamente. Acredito que esteja errando na ideia de passar um array, mas nao sei como fazer. Não sei se estou fazendo da forma correta, ou se estou fazendo a melhor forma. Se puderem me ajudar serei grato, obrigado.
Answer: Seu problema está no array $dados e na iteração dele pelo foreach. As variáveis$qtd, $nom e $id são arrays. Logo quando você faz:

$dados = array('nome'=>$nom,
                    'qtd'=>$qtd,
                    'id'=>$id);
Está criando um array de array. Para que seu foreach funcione do jeito que você escreveu, modifique o formulário desta forma:
<?php $count = 0; foreach($rtn as $pcs){ ?>
                    <input type="text" name="txtDados[<?= $count ?>][nome]" id="txtNome" value="<?=$pcs['pc_nome']?>" />
                    <input type="text" name="txtDados[<?= $count ?>][qtd]" id="txtQtd" value="<?=$pcs['num']?>"/>
                    <input type="hidden" name="txtDados[<?= $count ?>][id]" id="txtId" value="<?=$pcs['id']?>" />

            <?php $count++; } ?>

Dessa forma, terás apenas um array, $txtDados. No arquivo update_pcs.php, troque a variável $dados para $dados = $_POST['txtDados'];
Comment: Encontrei uma solução parecida com a sua no stack em inglês, porém a sua foi ligeiramente melhor, obrigado e parabéns ! Espero um dia poder retribuir.


Carregar paginas sem refresh ao clica na opção de menu

Question: Boa Noite galera! Estou fazendo um sistema de escola, nele vai ter niveis de acesso, menu para cada acesso. Quero fazer o seguinte, quando eu clicar em alguma opção do menu lateral, onde esta escrito "BLANK" na parte do meio, quero que apareça a pagina correspondente, sem mudar de pagina. Enfim, fiz umas aplicações anteriores com ajax, mas não ficou tão bom, ouvi falar no Angular e tal, vocês poderiam me dar um rumo? Se só dá para fazer com ajax, ou o angular serve para isso? Pois nao entendi muito bem o que ele faz, e se existe framework para isso, desde já, obrigado!

Comment: Isso que você está falando é fazer um [Single Page Applicaiton](https://www.codeschool.com/beginners-guide-to-web-development/single-page-applications). O Angular é um ótimo framework para isso. Nós temos 2 Angular:  o **AngularJS**, que foi a primeira versão, e o **Angular**, que é totalmente diferente do seu antecessor mas muito mais complicado (Ao meu ver) Aparentemente você não entende muito sobre isso, então conselho ir pelo AngularJS que é mais simples. Inicie algum projeto utilizando Angular e [AngularJS Routing](https://www.w3schools.com/angular/angular_routing.asp) e poste dúvidas =)
Comment: Bom, angular eu não sei. Mas se quiser com ajax, eu faço uma resposta
Comment: [sugiro que veja esse vídeo](https://youtu.be/AljlfNqZp_E)
Comment: Obrigado galera!!! Vou ver o vídeo e tentar fazer a Single Page
Answer: Acho que não precisa de tanto, amigo. Via javascript você consegue o que precisa de forma rápida e sem a necessidade de plugins. A solução passa por encapsular cada página em uma DIV e controlar a propriedade "display" alternando entre visível e invisível conforme a ação do usuário sobre o menu. Tudo ficará em uma única página que será mostrada onde está escrito "blank", porém somente o conteúdo de uma DIV aparecerá por vez.
function toggle(nome_da_div, estado) {
        var display = document.getElementById(nome_da_div).style.display;
        document.getElementById(nome_da_div).style.display = estado;
    }

Ao clicar em um item de menu você pode chamar a função acima para alterar a visibilidade da DIV:
toggle('div-nome-tal', 'block'); // visível
toggle('div-nome-tal', 'none'); // invisível

Esta é a maneira mais simples de fazer. Contudo, se quiser usar um plugin, sugiro que pesquise sobre Bootstrap que tem uma série de recursos prontos para isso:
https://getbootstrap.com/docs/4.0/components/collapse/
Comment: Pelo que entendi da questão, a página não seria 100% carregada a priori, mas sim a sua estrutura com a parte dos menus. Creio que, além do _toggle_ de aparecer e sumir, seria adequado por na sua resposta o como tratar a requisição ajax de modo a inserir o conteúdo dinamicamente nas `div`s adequadas. Também guardaria quem está sendo exibido no membro para que, eu mandar exibir as informações de algo do menu, se ocultasse automaticamente o item selecionado anteriormente, mas esse último detalhe é mais um preciosismo para evitar bugs/diminuir a manutenção do que algo que responda a questão
Comment: Obrigado!! Vou implementar essa solução


Notation without flats or sharps in equally tempered tuning

Question: Considering only equally tempered tuning, do full notes such as C, D, E, etc have any special characteristics compared to flats and sharps, so that they 'deserve' a separate letter?
If no, would it make sense to simplify the notation to N1..N12 in case no other tunings except 12-TET existed in the world?
Comment: [MIDI Note Numbers](https://newt.phys.unsw.edu.au/jw/notes.html)
Comment: There's also the cognitive aspect. Seven distinct items with a few variants are easier to tell apart than twelve different ones (particularly if it's seven items whose names are already known from reading and writing).
Answer: Letter names for notes are a holdover from historical naming conventions, but they are also very useful in terms of representing concepts from tonal music. For instance, the seven letter names without accidental alterations [A, B, C, D, E, F, G] provide a diatonic collection, specifically the C-major diatonic collection. By changing the B to Bb (Bflat) or by changing the F to F# (Fsharp), you still obtain diatonic collections, the F-major and G-major diatonic collections respectively. (See the circle of fifths.) In this sense the notes without flat or sharp alterations are not in any way preferable to those with alterations, they are just different and provide alternative scales.
Historically, those seven lettered notes without alterations were doing exactly what you propose, but they were ordering the notes of a seven-note diatonic scale rather than a twelve-note chromatic one. Your proposal to number each of the twelve notes in twelve-tone equal temperament was finally proposed in the twentieth century after the tuning and usage of these twelve notes as individual entities was solidified throughout the common practice period. Musical set theory often numbers the notes (called pitch classes) as the residues mod 12, specifically the numbers 0–11. This is exactly what your proposal does except that in terms of the modulus 12, the numbers 12 and 0 are equivalent. You can imagine the notes as elements on a traditional clock face. The most common version of this integer notation places C=0, C#=1, D=2,..., B=11. Note that all enharmonically equivalent notes (that is notes that sound the same but are spelled differently, e.g. C# and Db) share a single integer (1 in the case of C# and Db). This naming convention is very useful for modern or atonal applications, but it is less helpful in terms of tonal music, which is primarily structured around seven-note diatonic scales.
Comment: Also found this: https://en.wikipedia.org/wiki/Twelve-tone_technique
Answer: One of the main characteristics, on pianos and other keyboard instruments, is that basically the simple letter names are the white keys. Yes, occasionally white keys are called # or b, but that's not the general state of affairs.
I guess on most other instruments, the letter names are more academic. And where they are on the stave isn't too important - C and C# both share the same line/space. But that then poses a problem for your idea. How would your  now potentially 12 different notes be portrayed?
Comment: The portraying part will not change, the proposal is basically a renaming to avoid confusion for new learners (such as me) ;-) Otherwise I get a feeling that simple letter notes are 'better' than flats or sharps, which they are not.


Prevent users from including their username in their password

Question: I'm aware of the Password Policy module that has a number of features for forcing the user to constrain their passwords to certain criteria, but this module does not contain an option to prevent users from including arbitrary strings in their passwords (such as their own username).
Ex. User bob receives a validation error if they try to change their password to anything that includes the string "bob", such as "889bobisthebest99".
Does anyone know how to code custom functionality to achieve this result for Drupal 7.5 or a module that already does what I'm looking for?
Comment: The answer will depend on the version you're targeting. The 7.x-1.x, 7.x-2.x, & 8.x versions each have their own way of providing extendable constraints.
Answer: I found that the Password Policy module actually does have an option to prevent the user from including their username in their password. The broader issue about how to restrict arbitrary strings from a user's password still stands though.
Answer: The Password Strength module for Drupal 7 offers the closest functionality to what you desire. Full disclosure, I'm the author of the module!
In particular, it utilizes the Zxcvbn-PHP library for discovering patterns in passwords. So, for your example the Zxcvbn-PHP library would detect "bob" and "best" as simple dictionary words in the password and the Password Strength module would report that as a validation error to the user (depending on module settings). Read more about the Zxcvbn-PHP library at https://github.com/bjeavons/zxcvbn-php.
You may be able to configure or hook into the module to further accomplish your goals.


PHP + Mysql and memcache or phpsessions

Question: I currently manage a game that handles around 8K daily users, the current server setup is
<code>VPS: 16GB+8cores+ 160GBSSD.
Handles 8K daily users that are generating 600K daily direct calls to the mysql DB;
The situation is: The game is growing, and server response is slowing down.
</code>
So! I'm looking for options to avoiding having an incredibly slow server, and saw Memcache as a viable solution, and studying it I came up with 2 questions, which are:
Is it safe to store ONE Key value per user, that contains all user data, perhaps as a concatenated string that would be around 100 characters long, and then update the DB every once in a while? ->that would mean having thousands of keys at the same time.
The idea is not to replace mysql, just to aid it in the users session and be able to update the DB every so often, for this situation would Sessions or Memcache be the right way to go?
Comment: Have you done any performance tuning on MySQL?
Answer: You can make quite big values, however, using Redis would be better. With Memcached you are limited to Key->Value pairs, Redis has alot more features and offers you more (and better) solutions for what you want (more like a database).
But both Redis and Memcache are in-memory solutions, so make sure they don't contain mission critical data. Otherwise you could decide to let Redis dump it's database on file every xxx actions or x minutes, use master-slave replication / cluster, and so on.
Comment: @FelipeZuleta Be aware that you still need to write changes out to disk as soon as is practical, otherwise you open a window for potential exploits (e.g. duplicating gold or items).
Comment: oh wow, I didn't know about Redis, will definitely explore! thanks a lot Jeroen!
Comment: @FelipeZuleta Another option would be to replace MySQL (I know you say that's not your goal, but SQL and relational databases are not always the best option. Something like Redis with disk dumps or MongoDB may be a better fit for your purposes...)
Comment: Hi Michael! thanks for the reply, I'll keep that in mind.  Hi voretaq7, I'll check out both Redis and MongoDB :) thanks!

PHP + Mysql and memcache or phpsessions


How to get the data for specify month and divide it by the number of days

Question: I would like to check with you ,
I would like to do a summary for my application.
Such that it will give me an average for my price based on month.
This mean that I've a set of records, which I've already filter by month.
If month = Jan, I would like to get all the Jan data and divide by the number of days in the month.
Right now,
I'm only able to take out the months.
I would like to check,
If I would want to do "  would like to get all the Jan data and divide by the number of days in the month. ", how can I do it?
Can anyone suggest to me?
Im new to android, and trying to learn things.
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.summary);

        monthDate = (EditText)findViewById(R.id.month);
        avgPrice = (TextView)findViewById(R.id.showavfPriceTV);
        exFuel = (TextView)findViewById(R.id.showexFuelTV);
        avgFC = (TextView)findViewById(R.id.showavgFCTV);
        doneButton = (Button)findViewById(R.id.doneBTN);
        exitButton = (Button)findViewById(R.id.exitBTN);

            // First we need to make contact with the database we have created using
            // the DbHelper class
            AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

            // Then we need to get a readable database
            SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

            // We need a a guy to read the database query. Cursor interface will do
            // it for us
            // (String table, String[] columns, String selection, String[]
            // selectionArgs, String groupBy, String having, String orderBy)
            Cursor cursor = sqliteDatabase.query(
                    AndroidOpenDbHelper.TABLE_NAME_LOG, null, null, null, null,
                    null, null);
            // Above given query, read all the columns and fields of the table

            startManagingCursor(cursor);

            // Cursor object read all the fields. So we make sure to check it will
            // not miss any by looping through a while loop
            while (cursor.moveToNext()) {
                // In one loop, cursor read one undergraduate all details
                // Assume, we also need to see all the details of each and every
                // undergraduate
                // What we have to do is in each loop, read all the values, pass
                // them to the POJO class
                // and create a ArrayList of undergraduates
                String id = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_ROWID));

                final String date = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_DATE));
                String price = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_PRICE));
                String pump = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_FUEL));
                String cost = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_COST));
                String odm = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_ODM));
                String preodm = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_PREODM));
                String fcon = cursor.getString(cursor
                        .getColumnIndex(AndroidOpenDbHelper.KEY_CON));

            // If you don't close the database, you will get an error
            sqliteDatabase.close();
                Log.i("FuelLog", "dataBundle " + date);

        monthDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               // showDialog(DATE_DIALOG_ID);
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getFragmentManager(), "datePicker");
            }
        });

doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (monthDate.getText().toString().equals(date.subSequence(3,9).toString()))

{

                    Log.d("MONTHDATE","date : "+ monthDate.getText().toString());
                    Log.d("BBUNDLEDATE","date : "+ (date.subSequence(3,9).toString()));

                     Intent intent=new Intent(getApplicationContext(),homeActivity.class);
                     startActivity(intent);

                }
                else
                {
                     Intent intent=new Intent(getApplicationContext(),about.class);
                     startActivity(intent);
                    Log.d("ELSEMONTHDATE","date : "+ monthDate.getText().toString());
                    Log.d("ELSEBUNDLEDATE","date : "+ (date.subSequence(3,9).toString()));
                }

            }
        });
}

    }

Answer: Supposing you have the SUM of your monthly data for a single month,
Cursor cur = myDB.rawQuery
    ("SELECT SUM(Price) FROM Prices WHERE Month = 1", null);
if(cur.moveToFirst())
{
    return cur.getInt(0);
}

Even better, you can have a single query to get the months and the summed prices per each month of the given year:
String sql = "SELECT Month, SUM(Price) FROM Prices WHERE Year = ? GROUP BY Month ORDER BY Month";

Divide your single monthly datum by:
Calendar cal = new GregorianCalendar(2014, Calendar.JANUARY, 1); // Specify an year and a month basing on your datum
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

Just keep in mind this: (fromm the SQLite reference site)
sum(X) and
total(X)
    The sum() and total() aggregate functions return sum of all non-NULL values in the group. If there are no non-NULL input rows then sum() returns NULL but total() returns 0.0. NULL is not normally a helpful result for the sum of no rows but the SQL standard requires it and most other SQL database engines implement sum() that way so SQLite does it in the same way in order to be compatible. The non-standard total() function is provided as a convenient way to work around this design problem in the SQL language.
The result of total() is always a floating point value. The result of sum() is an integer value if all non-NULL inputs are integers. If any input to sum() is neither an integer or a NULL then sum() returns a floating point value which might be an approximation to the true sum.

Sum() will throw an "integer overflow" exception if all inputs are integers or NULL and an integer overflow occurs at any point during the computation. Total() never throws an integer overflow.

ALSO NOTE
It's always a good idea to put dummy values (0.0) for months where no price is specified
Comment: Do you have 1 or more data for each month? If you have more, sum them as shown in my answer. If it's only 1 value, it's enough. Then you'll average this value by dividing by days (which returns the maximum number of days in the specified month of the specified year).
Comment: I don't understand,
can you explain further?
Comment: I'm just confuse on how do I get the data.
For instance,
I have a set of record, 2 records are Jan, 3 records are Feb.
if I click on Summary(feb),
I would like to add the PRICE record for the month FEB together and then divide by number of days.

How can I do so?
Comment: how can I add the PRICE ?
Comment: sorry, this code   ("SELECT SUM(Price) FROM Prices WHERE Month = 1", null); is suming them together?
Comment: Yes, for January only, since I specified the condition "WHERE Month = 1". You would prefer a whole recordset of sums of the monthly prices: **String sql = "SELECT Month, SUM(Price) FROM Prices GROUP BY Month ORDER BY Month";**
Comment: Can we talk in the chat?
Comment: OK, let's continue in the chat
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/46333/discussion-between-tobor-and-chloe)


how to append option text to a list in jquery

Question: I have a tried a few things to get this to work with no luck. I have a select box with a button next to it.  When the button is clicked, the text from the currently selected item needs to be placed inside li tags and appended to a ul inside another div.

<select id="select-pub">
<option value="1">Publisher 1</option>
<option value="2">Publisher 2</option>
<option value="3">Publisher 3</option>
<option value="4">Publisher 4</option>
</select>

I started here, but how can I get the text within li tags and append that to the ul?

Any ideas? I've been failing at this all afternoon!
Answer: You can create a
 set the text and append it like this:
$('.add-button').click(function() {
  $('
', { text: $('#select-pub :selected').text() })
     .appendTo('#publisher-results ul');
});

You can test it out here, this uses the $(html, props) construction method then uses .appendTo() to place it inside the
, it's broken onto 2 lines just to prevent scrolling on SO, it need not be broken up in your code.
Comment: For some reason I am getting li's with no text in them. I'm using this in a modal window and it's just dumping blank li's...I am using your code exactly...any help is appreciated...it's at www.jontakiff.com/list-append/overlay.html


Examine convergence of improper integral

Question: How do i test out convergence of improper integral
Given integral is $$\int_0^{\infty}\frac{x^m\cos(ax)}{(1+x^n)}dx$$
Answer is the given improper integral is convergent if $-1 < m < n $. I am thinking of applying p test, but how do i deal with $\cos(ax)$ term in numerator?
Thanks
Comment: Hint: at $x=0$ $\cos(ax)\sim 1$, and you may use p-test. At $x=\infty$ use Dirichlet
Comment: @MichaelGaluza i didn't study Dirichlet test yet, will absolute convergence work here(i thought it might get me rid of cosine).
Answer: Some hints: The integral may not converge absolutely; the problem is at $\infty.$ Let $m=1,n=2$ to see this. You don't need to know Dirichlet to decide whether the integral is convergent. Try integrating by parts: Integrate $\cos (ax),$ differentiate $x^m/(1+x^n).$


Organic groups organizational problem

Question: Apologies if this question has already been answered.  I'm developing an emergency notification site using Drupal 7 and Organic Groups and currently it's building-driven -- i.e., the buildings are the groups which have users connected to them.  They can add notes, photos, etc. and all works well.
Now it seems that it would be better to have an event-driven system.  Admins could create an event (such as a hurricane) and then assign those buildings that are in the path of the event.  I've tried creating a new Event content type and using the Entity Reference module, linking the Building list to the Event.  However, when it comes time to create a View to display the information I'm running into the following error message when I build the view relationship using Entity Reference: Referenced Entity: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'og_membership.field_affected_buildings_target_id' in 'on clause'
Here is my exported view (note that it doesn't have any fields yet but it does have the broken relationship):
<code>$view = new view();
$view->name = 'event_list';
$view->description = 'Displays all emergency events with affected buildings.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Event List Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Events';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'title',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'field_address' => 'field_address',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_address' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Entity Reference: Referenced Entity */
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['id'] = 'field_affected_buildings_target_id';
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['table'] = 'og_membership';
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['field'] = 'field_affected_buildings_target_id';
$handler->display->display_options['relationships']['field_affected_buildings_target_id']['label'] = 'Building';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'event' => 'event',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'events';
</code>
Thanks to anyone who can point me in the right direction!
Answer: I had the same case.
I removed the entity reference (which cause the problem) from Relationships and added necessary fields with Rendered Entity Formatter.
You can choose any view mode you want and show all the required data. No Relationships are required.

Organic groups organizational problem


How can I stop a running operation in the SLIME REPL?

Question: Is there a way to stop a running operation in the SLIME REPL?
The Clojure SLIME folks apparently have some way to do this, so how about in ordinary Common Lisp?
Thanks /Erik
Answer: As expected, it turns out it was quite simple. To stop a running operation use the command slime-interrupt (C-c C-b).
Comment: `C-c C-c` is wrong! It compiles the last expression. `C-c C-b` is `M-x slime-interrupt`.


Can self typing be used with abstract types?

Question: I'm trying to achieve F-bounded polymorphism without using generics. I also need to use self-typing as I will be referencing this and expecting it to be typed as the subtype.
trait MyTrait[T] { self: Self => // Compilation error: cannot reference 'Self'
   type Self <: MyTrait[T]

   def doSomethingWithSubtype() {
      ...
   }
}

I can achieve this quite easily using type parameters (i.e. generics), but would like to know if I'm missing something to make the above compile. Can you use abstract types in this way?
Similar questions:
These provide workarounds for similar problems, leading me to believe the above is impossible?
F-Bound Polymorphism with Abstract Types instead of Parameter Types?
F-bounded quantification through type member instead of type parameter?
Answer: You can self-type to an abstract type, with one tricky limitation: it has to be defined outside of your trait, but still in scope in a way that allows implementations to implement it with some type. You can do that by wrapping the whole thing into a trait:
trait MyTraitSystem {
    type TraitImpl <: MyTrait

    trait MyTrait { self: TraitImpl =>
        def doSomething(t: TraitImpl): String
    }
}

// with an example implementation of the trait:

object MyImpl extends MyTraitSystem {
  case class TraitImpl(data: String) extends MyTrait {
    def doSomething(t: TraitImpl): String = t.data + " " + data
  }
}

This is equivalent to this version using a type parameter:
trait MyTrait[T <: MyTrait[_]] { self: T =>
  def doSomething(t: T): String
}

// with an example implementation of the trait:

case class TraitImpl(data: String) extends MyTrait[TraitImpl] {
  def doSomething(t: TraitImpl): String = t.data + " " + data
}

Apart from an import MyImpl._ for the abstract-type version, they can be used the same way:
scala> import MyImpl._
    import MyImpl._

scala> val a = TraitImpl("hello")
a: MyImpl.TraitImpl = TraitImpl(hello)

scala> val b = TraitImpl("world")
b: MyImpl.TraitImpl = TraitImpl(world)

scala> b.doSomething(a)
res0: String = hello world

The abstract-type version is more verbose, but it works. You also need to carry around a MyTraitSystem in any method/class/... that needs to use TraitImpl so as to provide the type:
object SomewhereElse {
  def doSomethingElse(s: MyTraitSystem)(t: s.TraitImpl) =
    ??? // s.TraitImpl is the implementation type
}

Compared to the type parameter version:
object SomewhereElse {
  def doSomethingElse[T <: MyTrait[_]](t: MyTrait[T]) =
    ??? // T is the implementation type
}

This is probably only one of several ways to do this, but I don't think any way can match the conciseness of the type-parameter-based version.
Comment: Great answer, thank you. "The abstract-type version is more verbose, but it works." - it looks like doing it this way is counteractive to what I'm trying to achieve :P I will continue using type parameters!
Comment: @LawrenceWagerfield yes, it usually is counteractive. It plays well with the cake-pattern though, that's could be one reason to use it in some cases.


Can't find element with selenium? (Tried implicit and explicit waits)

Question: I am new to programming and extremely new to web scraping. I need to scrape a table from a web page, where the table is displayed after a video.
As I said on the title, I tried implicit waits like:
driver.implicitly_wait(40)
...
inputElement = driver.find_element_by_class_name("_td")

(I tried the same with the xpath)
and explicit waits:
wait = WebDriverWait(driver, 40)
wait.until(EC.visibility_of_element_located(By.XPATH("path...")

(tried the same with class name)
This is what I get:
NoSuchElementException: Message: no such element: Unable to locate element
I would REALLY appreciate your help!
Comment: Are you sure you got the right element path or class name?
Comment: Yes. I've tried the same with elements that are displayed at the same time of the table (just to check) and unfortunately get the same results
Comment: What website is it? Also check if it's under an iframes.
Comment: It's this website: https://ficeda.com.mx/index.php?id=precios I am trying to scrape the "Abarrotes" table
Comment: If you go to the developer tools you will see that there are iframes.
Comment: Just checked and I think it is under an iframe as you said! Does wait.until not work with iframes?
Comment: You want to driver.switchTo()  to the iframe element.
Comment: the wait will work but we need to focus the iframe element.
Comment: Ok I will try it and update you once it (hopefully) works!! I can't thank you enough!!
Answer: There is an iframe we need to switch to so do this prior to looking for your elements.
 iframe = driver.find_element_by_tag_name('iframe')

 driver.switch_to.frame(iframe)


I wanted to display an image whenever I pressed a button into a label widget inside a function

Question: import tkinter as tk
from tkinter import *
from PIL import ImageTk , Image

def addCards():
    img = Image.open("widgetClass\poker2.png")
    img = img.resize((50 , 70) , Image.ADAPTIVE)
    imgTest = ImageTk.PhotoImage(img)

    cards = tk.Label(
        master=frame,
        image=imgTest
    )

    cards.place(x = 20 , y=50)

root = tk.Tk()
root.title("Display images")
root.geometry("400x400")
root.resizable(False , False)

frame = tk.Frame(borderwidth=2 , height=100 , highlightbackground="red" , highlightthickness=2)
frame_b = tk.Frame(borderwidth=2 , height=100 , highlightbackground="red" , highlightthickness=2)

label = tk.Label(frame , text="Picture demo")
button = tk.Button(frame_b , text="Add cards" , command=addCards)

frame.pack(fill=X)
frame_b.pack(fill=X)
label.place(x=0 , y=0)
button.place(x=0 , y=0)

root.mainloop()

I am trying to display an image using the addCard() function , but it just display an empty label. I am expecting whenever I pressed the add card button , there is an image pop out at the first frame , but no image was display unfortunately.
Answer:
I am expecting whenever I pressed the add card button , there is an
image pop out at the first frame , but no image was display
unfortunately.

The problem can be fixed.
On line 20:
Change this:
cards.place(x = 20 , y=50)

to:
cards.place(x = 2, y=20

Add this on line 21:
def addCards():
     .
     .
     .

    cards.place(x = 2, y=20)
    cards.image = imgTest #<== Add this.

Screenshot:


Error: could not find function "setup_twitter_oauth

Question: When I run my API setup code on my laptop I don't have a problem, but when my friend runs it she is getting this message.
Error:

could not find function "setup_twitter_oauth"

The code is (I took out all the personal info obv):
options(RCurlOptions = list( capath = system.file
("CurlSSL", "cacert.pem", package = "RCurl"), ssl.verifypeer = FALSE))
reqURL<-"https://api.twitter.com/oauth/request_token" accessURL<-
"https://api.twitter.com/oauth/access_token" authURL<-"//api.twitter.com/oauth/authorize"

There's a https: after the "authURL <-" but i don't have 10 reputation to post 3 links:
consumerKey<-"XXXX" consumerSecret<-"XXXX" access_token<- "XXXX" access_secret<- "XXXX"

setup_twitter_oauth(consumerKey, consumerSecret, access_token, access_secret)

Any help is greatly appreciated!
Comment: Please improve formatting by using  making some parts of question as code, it can be edited)) What language do u use? As I see it should be R, I think problem is related with autif. file, once you autent. it remembers you, but not your friend.
Comment: http://thinktostart.com/twitter-authentification-with-r/ look here, should help
Answer: try to use this:
twitteR:::setup_twitter_oauth()
And be sure that you have already install properly the twitter library.


Sorting a part of Java ArrayList

Question: What is the most efficient way of sorting only a part of ArrayList?
Say all elements from index 0 to 3 in an Arraylist which contains 10 elements.
Is there a library function available in Java?
Apart from Collections.sort(list) which sorts the entire List!
Writing a highly optimised custom sort function will take some work.
Answer: In Java 8+, use List#sort.
list.subList(0,3).sort(null) ;

In earlier Java:
Collections.sort(list.subList(0,3));

Note: '3' here is excluded from sorting.
To quote the documentation:

public List subList(int fromIndex,
int toIndex)
Returns a view of the portion of this list between the specified
fromIndex, inclusive, and toIndex, exclusive.
Comment: this is a correct answer. Collections.sort does the sorting in place and List.subList returns a list that is backed by the original list.
Comment: There is a fencepost error in this solution, as this command will actually exclude the element in index 3.
Answer: use the subList [inherited from AbstractList] method in ArrayList. And then use Collections.sort() on that sub-list. That is if writing a highly optimised custom sort function is truly hard work.
Comment: While "inherited from `AbstractList`" is not wrong, as such, it's mostly irrelevant. It's more important that `subList` is defined by `List`, in my opinion.
Comment: @anirvan [Sure it does](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-).
Comment: AFAIK, `List` does **NOT** define `subList`. Hence, the relevance of letting the OP know where exactly does `ArrayList` inherit that behaviour from.
Comment: @TavianBarnes `List` is an interface, so what I was merely implying is that it doesn't _implement_ it, while `AbstractList` does.

Sorting a part of Java ArrayList


Adding datatable for two words id

Question: I have a table with id ='home_approval request'.I want to add datatable using this id .
    Its working if id='approval'. Now datatable is not working for two word id separated by space
var table_home = $('#home_approval').DataTable();

$(document).ready(function() {
  $('#home_approval').DataTable();
});

      Name
      Position
      Office
      Age
      Salary

      Tiger Nixon
      System Architect
      Edinburgh
      61
      $320,800

      Cedric Kelly
      Senior Javascript Developer
      Edinburgh
      22
      $433,060

      Sonya Frost
      Software Engineer
      Edinburgh
      23
      $103,600

      Quinn Flynn
      Support Lead
      Edinburgh
      22
      $342,000

      Dai Rios
      Personnel Lead
      Edinburgh
      35
      $217,500

Comment: The issue is because you cannot have spaces in an `id`. Remove them.
Comment: You can have more informations about `id` here: https://www.w3schools.com/html/html_id.asp
Comment: @ Rory McCrossan in html or in jquery
Comment: HTML, and therefore jQuery and Javascript too by proxy.
Comment: `id` can not have spaces in between words/letters (IN HTML). as well cannot used in jquery too. If you want spaces then use `class`
Answer: As mentioned on  w3c id attribute must not contain white-spaces.

Tip: The id attribute can be used on any HTML element.
Note: The id value is case-sensitive.
Note: The id value must contain at least one character, and must not
  contain whitespace (spaces, tabs, etc.).

Adding datatable for two words id


Compute a metric that punishes on the basis of type and distance

Question: Suppose I have a single important point on a 2D graph called "Alpha A". All other points on the surface are of two types: "Beta A" and "Beta B".
I'd like to compute a metric of 'Alpha A' relative to the beta points with these properties:

Punish greater distances from 'Alpha A' regardless of type, e.g., with (1/distance)
if type == 'Beta A', give stronger weighting than if type == 'Beta
B', e.g., make 'Beta B' negative.

Sample data frame:
color     distance
match        10
match        33
no_match     88
match       1000

Here is a very naive solution to my problem in pseudo code:
metric = 0

for (point in df){
     if (color == match){
         weight = 1*(1/distance)
     } else {
         weight = -1*(1/distance)
     }
     metric  = metric + weight
 }

I don't doubt this problem is common and that there are myriad techniques
to solve it. However, as I don't know the correct terminology to search with, finding information has not been very successful...
To be clear, I am not trying to predict the location of 'Alpha A'.
I am simply trying to compute a metric that is informative about its environment.

DF
df = data.frame(color = c('match', 'match', 'no_match', 'match'), distance = c(10, 33, 1, 0))

Comment: Is this question not more suited for CrossValidated? The code you type would almost work as is in R.
Comment: The code is trivially straightforward here. I have code that works. So you're right: this was more suited for CrossValidated as the real question is about weighting, not coding.
Answer: Use this
df$weight <- NULL
df$weight = 1*(1 - 1/df$distance)
df$weight[df$color!="match"] = -1*df$weight[df$color!="match"]

Answer: It's not clear what you are asking for.
If it's how to find more literature concerning this is a Nearest Neighbor problem or, perhaps more correctly, a Nearest Set problem.
You haven't explained how you use this metric. It will be most positive if the nearest neighbors are of color==match; most negative if they are of opposite color; and zero if equidistant from both.
Is this what you want?
If so, this is correct. The only question would be if it falls off rapidly enough so that its magnitude is less than some value unless "pretty close" to some set, say by using 1/(1-distance^2).
Edit:
Actually, 1/(1+distance) might be better or you may find yourself dividing by zero.
Comment: Yes. Exactly. I was just a bit confused about what I wanted exactly. That weighting works nicely. I had used an exponential decay f(n) before 1/dist and that was too steep for my purposes. Thanks.


Custom theme for module?

Question: I am creating a new module in drupal 7 called coolmodule and I'm trying to figure out how to bind content to the file sites/all/modules/coolmodule/coolmodule.tpl.php file.  Here's the block view code in my coolmodule.module;
function coolmodule_block_view($delta = '') {

    $block['subject'] = t('My Special Module');

    $block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

    return $block;
}

But for some reason, pages with this block does not render sites/all/modules/coolmodule/coolmodule.tpl.php.  What am I doing wrong?
Answer: you are missing a hook_theme() function
see you defined a theme for your block by using:
$block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

but you never told it how to relate your theme with the template file, this work is done in hook_theme() function.
function coolmodule_theme() {
    $items['coolmodule'] = array(
        'template' => 'coolmodule',   // here comes your template name
        'render element' => 'content'
    );

    return $items;
}

Don't forget to clear your cache

Custom theme for module?


gallerys don`t work in my wordpress-site

Question: i have a problem with almost every gallery-plugin... they don`t work on my homepage,
check:
http://ntm.at/r0sa/?page_id=116
does anyone know what to do?
is something wrong with my php or css files?
Thank you!
Comment: Error: TypeError: jQuery(...).nggSlideshow is not a function
Source File: http://ntm.at/r0sa/?page_id=116
Line: 158. It seems that you haven't implemented it fully.
Comment: Read the plugin manual and try again.
Comment: oh thanks, but what should i do now??
Comment: I have voted to close this question because it's too localized, and unlikely to help any future visitors.  The best questions have a small self-contained example, which contains just enough code to demonstrate the problem, without anything extra. Doing this can be a lot of work, but it's a critical part of the process of troubleshooting your problem.
Answer: I can't test it but I think this error is because jQuery is being included twice on the page (once locally and once with googleapi).
In the header block you have.

In the body block you have.

One needs to be removed.
Comment: that`s an idea... but how can i remove it? should i delete this line in sidebar.php:
Comment: you need to delete one or the other, I'll have to leave that to you. I've updated my answer though
Comment: thanks for your help and i think it`s the solution... but when i click on sidebar.php i can only see ONE line looking like this, in the header block i see nothing like this... where did you found that?
Comment: I looked at the source of you page, that's the best I can do, I can't see the content of your php files. If you use some sort of IDE for development you should easily be able to search for it.
Comment: ok, so i deleted jquery from my wp-includes-folder, but it`s still not working... if i delete the googleapi- one, it works, but then the sidebar is not visible any more, because it needs jquery... have i done something wrong?
Comment: You may need to make another question for this issue. I would guess that whatever you have in your sidebar should be in a $(document).ready(); block
Comment: ok, i will ask otherwise- but you were close to the solution, thank you therefore!


How do you know if the covariance structure you select for your random effects in a mixed model is the best one?

Question: There are many different types of covariance structures to choose from. How do you assess what the best structure is? For example, if I am choosing between unstructured vs. compound symmetry. Is there a certain test I need to run when I run the model in SAS or R?
Answer: A couple of points:

To select the appropriate covariance structure for your data, it is advisable to have an adequate specification of your mean structure. This means including even terms that you may not need (e.g., interaction or nonlinear terms).
There are indeed many different covariance structures available in various software. Before going into statistically selecting which one is appropriate for your data, it would be a good idea to restrict the options to covariance structures that are plausible/relevant for your design. For example, if you have longitudinal data, typically, you expect that correlations decay with the time lag. If you have a multilevel design, e.g., students nested in classes, and classes nested in schools, then you would typically start with a generalization of the compound symmetry structure.
The tools to use for selecting between competing covariance structures for your data depend on whether these structures are nested or non-nested. When nested, you can use a likelihood ratio test to get an indication on which fits the data better. Because many times you also have missing data, I typically recommend favoring a more complex structure than a more parsimonious one. Hence, using a higher significance level than the typical 5%. When you have non-nested structures you could use the AIC.


Suppose F is a subset of the first category in metric space X, and E is a subset of F. Prove that E is of the first category in X.

Question: I know that a subset of a nowhere dense subset is still nowhere dense. But since being of the first category doesn't imply nowhere dense, I couldn't use that fact directly. How should I proceed here?
Comment: Do you know the definition of  a first category set?
Comment: @KaviRamaMurthy Yes, namely being a countable union of nowhere dense subsets.
Answer: $F=\cup _n F_n$ where each $F_n$ is nowhere dense. Now $E=\cup_n (E \cap F_n)$ and $E \cap F_n$ is a subset of a nowhere dense set , so it is nowhere dense.
Comment: Thanks so much. I can't believe I didn't see that.


Java: Generic accepting only enum types

Question: Assuming that I have a basic enum like:
public enum Color { Red, Green, Blue}

How can one write a generic class which only accepts "enum classes" so that a concrete instantiation of that generic class might look like MyClass<Color>?
Edit:
What a actually want to do is to write a generic abstract class containing a function returning all enum "entries"  as list:
public abstract class EnumListBean<E extends Enum<E>> {

    public List<E> getEnumList() {
        return Arrays.asList(E.values());
    }

}

While Day.values() is available E.values() is not. What i am doing wrong here?
Comment: No its implementation should not be limited to one concrete enum type but to arbitrary enum types. I just used `Day` to describe more concretely what i want.
Answer: public class EnumAcceptor<E extends Enum<E>> {
    ...
}

Use E as a type inside your class.
Answer: See Istvan Devai for answer to original question.
For the follow up, methods like values() are static methods, so you're out of luck trying to get that from a generic parameter. As a poor solution, you can pass the enum's Class object into the constructor. and use Class.getEnumConstants. But you might as well pass MyEnum.values() into the constructor rather than the class, and so avoid reflection altogether. It's a real shame there isn't a sensible enum metaclass.
Answer: An enum really declares a class derived from Enum. As such, you can use:
public class MyClass<T extends Enum> { }

Comment: You're mixing generics and raw types.
Answer: Note that @Istvan's solution can only accept elements of the enum, which is fine if that is all you want.
Although you cannot pass the enum itself as a parameter (because it does not actually have an object equivalent) you can specify that you must receive the class of the enum in your constructor and derive the enum's details from that:
public class EnumAcceptor<E extends Enum<E>> {
  public EnumAcceptor(Class<E> c) {
    // Can get at the enum constants through the class.
    E[] es = c.getEnumConstants();
  }

  enum ABC {
    A, B, C;
  }

  public static void main(String args[]) {
    EnumAcceptor<ABC> abcAcceptor = new EnumAcceptor<ABC>(ABC.class);
  }
}

Comment: Oops - duplicate of @Tom's post - sorry Tom :(
Answer: You can't use E.values() due to type erasure -- the type of E is not available at run-time.
For the specific case in your question, you're probably better off using Guava's Lists.newArrayList:
List<Color> days = Lists.newArrayList(Color.values());

Java: Generic accepting only enum types


Conditional probability and calculation

Question: if $P(F|E)=3P(F|E^c)$
$P(E)=0.3$
$P(F)=0.4$
Then $P(E|F)=??$
How do i use the conditional probability equation that has been given in the question
Answer: From the first equality you wrote,
$$P(F|E) = \frac{P(F\cap E)}{P(E)} = \frac{P(F\cap E)}{.3} = 3P(F|E^{c}) = 3\frac{P(F\cap E^{c})}{P(E^{c})} = 3\frac{P(F\cap E^{c})}{.7} $$
We can rearrange some terms to get
$$P(F\cap E) = \frac{3*.3}{.7} P(F\cap E^{c}) = \frac{9}{7}P(F\cap E^{c})$$
Now, since $P(F) = P(F\cap E) + P(F\cap E^{c})$, substitute the above equality into this one to get
$$\frac{2}{5} = .4 = P(F) = P(F\cap E) + P(F\cap E^{c}) = \frac{9}{7} P(F\cap E^{c}) + P(F\cap E^{c}) = \frac{16}{7}P(F\cap E^{c})$$
Therefore $P(F\cap E^{c}) = \frac{\frac{2}{5}}{\frac{16}{7}} = \frac{14}{80} = \frac{7}{40}$. Now
$$P(F\cap E) = \frac{2}{5} - \frac{7}{40} = \frac{9}{40}$$
By definition, $P(E|F) = \frac{P(E\cap F)}{P(F)}$, which will be $\frac{\frac{9}{40}}{\frac{2}{5}} = \frac{45}{80} = \frac{9}{16}$
Answer: $P(E)=0.3$
$P(E^c)=1-0.3=0.7$
$P(F)=0.4$
$P(F|E)=3P(F|E^c)$
$P(F\cap E) = 3 \frac{P(F\cap E^c)}{P(E^c)}$
$P(F\cap E) = 3 \frac{P(F)−P(F\cap E)}{P(E^c)}$
Because $P(F\cap E^c)=P(F)−P(F\cap E)$
$P(F\cap E).P(E^c) = 3P(F)− 3P(F\cap E)$
$0.7P(F\cap E) + 3P(F\cap E) = 3×0.4$
$3.7P(F\cap E) = 1.2$
$P(F\cap E)=\frac{1.2}{3.7}$
$P(F\cap E)=0.324$
Hope you now solve for $P(E|F)$

Conditional probability and calculation


What is a sub-collection of events when trying to define mutual independence?

Question: Let $H_{1}$, ..., $H_{n}$ be n events. $H_{1}$, ..., $H_{n}$ are jointly independent (or mutually independent) if and only if for any sub-collection of k events ($k \leq n$) $H{_{i1}}$, ..., $H_{i_{k}}$
My definition of mutual independence:
$P(\cap^{k}_{j=1}E_{1j}) = \Pi^{k}_{j=1}P(E_{ij})$.
I read this and assumed something along the lines of:
S = {HHH, HHT, HTH, THH, THT, TTH, HTT, TTT}
Let $H_1$ be equal to the event of getting a heads on the first toss. So $H_1$ = {HHH, HHT, HTT, HTH}.
I then thought that an example of a sub-collection of an event would be $H_{11} = {HHH}$. Although, I think I am wrong.
But I do not see how my idea of a sub-collection of an event, helps clear up my definition of mutual independence. I think that I may be reading the definition wrong.
edit: $E_{12} = HHT, E_{13} = HTT, \ldots$
Answer: Let $H_1, H_2, H_3$ be the events we need to be independent. Any subcollection of events means that we can take any of these events. To be independent, they should satisfy four conditions:
$$
k=2,\; i_1=1,\;i_2=2: \quad \mathbb P(H_1\cap H_2)=\mathbb P(H_1)\mathbb P(H_2).
$$
$$
k=2,\; i_1=1,\;i_2=3: \quad \mathbb P(H_1\cap H_3)=\mathbb P(H_1)\mathbb P(H_3).
$$
$$
k=2,\; i_1=2,\;i_2=3: \quad \mathbb P(H_2\cap H_3)=\mathbb P(H_2)\mathbb P(H_3).
$$
$$
k=3,\; i_1=1,\;i_2=2,\;i_3=3: \quad \mathbb P(H_1\cap H_2\cap H_3)=\mathbb P(H_1)\mathbb P(H_2)\mathbb P(H_3).
$$
If you take $H_1=\{HHH, HHT, HTT, HTH\}$, you should take the other events $H_2$,  $H_3$ and so on to check independence. Say, $H_2=\{HHH, HHT, THH, THT\}$ means that the second coin is head. Let also $H_3=\{HHH, HTH, THH, TTH\}$ means that the third coin is head.
Take $k=2$ and events with numbers $i_1=1$ and $i_2=2$. They are $H_1$ and $H_2$. Their intersection is $H_1\cap H_2 = \{HHH, HHT\}$. Probability of this event is $\frac28=\frac14=\frac12\cdot\frac12=\mathbb P(H_1)\cdot \mathbb P(H_2)$.
Then take the other pari of events $H_1$ and $H_3$ and so on.


É possível disparar um arquivo dentro de um servidor através de uma página web?

Question: Gostaria de saber se é possível executar um comando dentro de um servidor através de uma página na Web, o que eu preciso é que através dessa página eu possa abrir um script VBS que tenho salvo ou até mesmo abrir um aplicativo. Não importa a linguagem aplicada, há uma maneira fácil de se fazer isso?
Comment: Acredito q php faz facil isso: http://php.net/manual/pt_BR/function.system.php
Answer: Creio que nesse caso o senhor deva procurar uma dependência se não quiser criar algo muito complicado. Com poucos minutos de pesquisa, encontrei este:

node-command-line.

Não tenho muito conhecimento em C/C++, mas creio que com um addon você também possa chegar em resultados parecidos. Leia mais sobre criar addons para Node.JS na documentação oficial.


One or two-sided test for classifier accuracy?

Question: As far as I could reconstruct, caret::confusionMatrix uses a one-sided binomial test to compute the p-value of the accuracy being better than the "no information rate" (NIR). However, for computing the 95% confidence interval, it seems to use a two-sided test. Is this mixing of tests legitimate, and, if so, why? Wouldn't a one-sided confidence interval be more appropriate?
Below is my code to check my assumptions:
library(caret)
library(tidyverse)

# For the example from the reference paper,
# http://www.jstatsoft.org/article/view/v028i05/v28i05.pdf,
# Section 6: Characterizing performance (p. 15)
tb2 = tibble(
  true      = as.factor(c(rep('mutagen', 600), rep('nonmutagen', 483))),
  predicted = as.factor(c(rep('mutagen', 528), rep('nonmutagen', 453), rep('mutagen', 102)))
)
cm = confusionMatrix(tb2$predicted, tb2$true, positive = "mutagen", mode="everything")

print(cm)

# the p-value is internally computed as:
bt1 = binom.test(
  cm$table[1,1] + cm$table[2,2],
  sum(cm$table),
      p = sum(cm$table[,1]) / sum(cm$table),
  alternative = "greater"
)

print(bt1)
print(bt1$p.value == cm$overall[['AccuracyPValue']])

# ...but the confidence interval is computed using a two-sided test:
bt2 = binom.test(
  cm$table[1,1] + cm$table[2,2],
  sum(cm$table),
      p = sum(cm$table[,1]) / sum(cm$table),
  alternative = "two.sided"
)

print(bt2)
print(bt2$conf.int[1] == cm$overall[['AccuracyLower']])
print(bt2$conf.int[2] == cm$overall[['AccuracyUpper']])

Edit:
Consider the following confusion matrix:
Confusion Matrix and Statistics

          Reference
Prediction  0  1
         0  9  4
         1  3 16

               Accuracy : 0.7812
                 95% CI : (0.6003, 0.9072)
    No Information Rate : 0.625
    P-Value [Acc > NIR] : 0.04646

[...]

The p-value is < 0.05, but the 95% CI includes the no-information-rate. These two measures send IMO conflicting messages.
Edit:
I could, of course, "manually" compute one-sided CI, using binom.test, as the code above does for the caret example data:
95 percent confidence interval:
 0.6281009 1.0000000

Is there some statistically valid reason why caret isn't doing it for me? In the sense of hypothesis testing, should I be guided by the caret's p-value (one-sided) or the CI (two-sided)? In the former case, I'd reject $H_0$ for my data above, and in the latter I'd fail to reject.
Answer: Usually the claim complementary to the one you hope to establish is posed as the null, so you can say that the alternative is consistent with the data when you reject. With the one-sided p-value, you are presumably hoping to establish that your classifier is better. The one-sided null $H_0$ would be that Acc $\le$ NIR versus the one-sided alternative $H_a$ that it is better, Acc $>$ NIR.
The one-sided p-value is smaller than $5\%$, so you reject the null and say the data is consistent with the classifier being better. The interpretation is that if there was no difference between them, the probability of seeing an accuracy of $0.7812$ ($25$ correct in $32$ trials with $p=0.625$) is  1-binomial(32,24,.625) = binomialtail(32,25,0.625) = $4.6\%$, which is fairly unlikely.
I do agree that the one-sided CI would be better for this use case, so let me try to give guidance on how to calculate it to see if it is consistent with the p-value. You can get it by looking at a $90\%$ two-sided CI, because the overlap between two one-sided $95\%$ CIs makes one two-sided $90\%$ CI.
Doing just that gets you:
. cii proportions 32 25, level(90)

                                                         -- Binomial Exact --
    Variable |        Obs  Proportion    Std. Err.       [90% Conf. Interval]
-------------+---------------------------------------------------------------
             |         32      .78125    .0730792        .6281009    .8925531

You can also use the inverse of the right cumulative binomial directly to get the LB like this:
. display invbinomialtail(32, 25, .05)
.62810094

This means that the one-sided interval is $[0.6281, 1]$. This excludes $0.625$, so you would reject the null that the classifier is the same or worse. The one-sided CI and the one-sided p-value are consistent.
So why is there a two-sided CI presented as well? I don't really know why caret defaults to this for certain, but I suspect it is because people often want to know an informative upper bound too, since better than NIR is a not very impressive. People want a sense of how much better and the two-sided interval gives you that, at a price. It tells that true accuracy values between the upper bound and 1, like 0.95, are also inconsistent with the data you have, just like 0.55 was not supported by the data on the left. I expect this is the reason why a CI is reported rather than a p-value: it gives you a better sense of range. Had the true value been outside that interval, the confidence interval construction procedure would have resulted in an interval different than the one observed with probability 95% or greater.
You should use a one-sided superiority test if you want to test the hypothesis that your classifier is better and you don't care by how much, since you would continue to use it as long as it better regardless if it wins by an inch or a mile. But you should really use the test that corresponds to the question you want to answer. Only you know what that is at this point, and you should definitely not pick a test just because it yields significant results. There is no such thing as "in the sense of hypothesis testing". That's like saying "in the sense of a screwdriver", should I use a Phillips head or a flathead? The answer depends on the screw/analysis goal.
Why does caret not report the other one-sided p-value or CI? If you somehow made a classifier that was worse than NIR, you could just do the opposite of what it says, and you would have a better classifier.
To sum up, if you just want to know that your model is better than the most naive thing you can do (or some other baseline), a one-sided test/CI is good enough. If you want to spend your $5\%$ to also acquire more precise knowledge of the extent to which your classifier is better, then you should use the two-sided test. This will cost you some precision at the lower end of the interval. Software gives you both since those are the two most reasonable questions in the context of classifier performance.
Comment: Thank you for your answer, but it doesn't solve my problem: Should I use a one-sided or a two-sided hypothesis test (and, tangentially related, why does `caret` report both)? I updated my question.
Comment: @IgorF. I responded to your updated question above. Let me know if the answer makes more sense.


Como fazer um scraping que muda de pagina

Question: Preciso criar um bot que entra na página inicial de um determinado site, pegue  todas os link's das postagens, entre em uma, capture uma div que contenha o vídeo e parta para o próximo link capturado na index.
Eu já criei a parte que captura os link, agora preciso saber como fazer a parte para acessá-los e capturar a div que possua o vídeo
request("https://www.site.com", function(error, response, html)
{
    if(!error)
    {
        var $ = cheerio.load(html)
        var resultado = [];

        $("div.mozaique > div.thumb-block").each(function(i)
        {
            var title = $(this).find("div.thumb-under > p > a").eq(0).text();
            var link  = $(this).find("div.thumb-under > p > a").attr("href");
            var img   = $(this).find("div.thumb-inside > div.thumb > a > img").attr("data-src");

            resultado.push({
                id: i,
                title: title,
                link: link,
                img: img
            });
        });
    }

    // Escrevendo o arquivo .json com o array
    fs.writeFile('resultado.json', JSON.stringify(resultado, null, 4), function(err) {
        console.log('JSON escrito com sucesso! O arquivo está na raiz do projeto.')
    })
});

Se não ficou claro, basicamente preciso:

Entrar no site
Capturar os link dos posts e armazená-los
Entrar no primeiro link capturado
Pegar uma div que contenha um link .mp4
Ir para o próximo link capturado e repetir o passo 4 e 5.
Comment: Já tentou criar uma função para acessar o link e capturar o vídeo? Dessa forma você poderá fazer um `for` nos links capturados.
Comment: Exatamente isso que não estou conseguindo fazer!
Answer: Pelo que eu entendi você quer fazer vários requests e ir compondo os arrays com os elementos que você vai pegando da página. Você precisa chamar outra função e criar um loop dela para fazer os requests de acordo com os links dos array. Ficaria algo assim:
request("https://www.site.com", function(error, response, html)
{
    if(!error)
    {
        var $ = cheerio.load(html)
        var resultado = [];

        $("div.mozaique > div.thumb-block").each(function(i)
        {
            var title = $(this).find("div.thumb-under > p > a").eq(0).text();
            var link  = $(this).find("div.thumb-under > p > a").attr("href");
            var img   = $(this).find("div.thumb-inside > div.thumb > a > img").attr("data-src");

            resultado.push({
                id: i,
                title: title,
                link: link,
                img: img
            });
            //Verifica se o array já acabou de ser composto
            if(i==$("div.mozaique > div.thumb-block").length){
                accessURI();
            }
        });

    }
});

let i = 0;
function accessURI(){
    if(i==resultado.length){
        //Call back do loop
    }
    request(resultado[i].link,{data: i++}, (error, response, body)=>{
        //Componha o array com as divs
        accessURI()
    })
}

Comment: Pedro não entendi muito bem, esse sua função não, pode dar uma exemplo de como usar?


A difficulty in using squeeze theorem.

Question: Given that: $\forall x \in \mathbb{R}, \sin^2(3x) \leq x^2f(x)\leq 3x^2 + 6\sin(x^2),$ then $$ \begin{equation*}
\lim_{x \rightarrow 0}
f(x) =
\end{equation*}$$
i)0
ii)9
iii)$\infty$
iv) The limit does not exist.
My idea is to divide by $x^2$ the whole inequality and so the answer is 9, but I am hesitated to do this because I am not sure that $x^2 \ne 0$.
Comment: The limit literally means that x is approaching zero but isn't identically zero so you are fine, same thing happens in limits like $\lim_{x\to 1} \frac{x^2-1}{x-1}=\lim_{x\to 1} x+1 = 2$
Comment: @Triatticus you mean $x^2 - 1$ I think
Comment: Yes I did mean that, for some reason I wrote plus
Answer: Yes, that's the way to do it.  In a limit $x\to0$, you are assuming  $x\ne0$, so your idea works fine.
Comment: So the answer is 9 right?
Answer: Limit $x\to 0$ tells you, how your function behaves when $x$ approaches $0$, but is not $0$, so your approach is correct.
For example, if
$h(x)=\begin{cases}
1& x\neq 0\\
2& x = 0
\end{cases}$
then $\lim_{x\to 0} h(x) = 1$, even though $h(0) = 2$.
Comment: So the correct answer is 9?
Comment: @Intuition I would say so:)

A difficulty in using squeeze theorem.


SSRS running very slow and error client rendering

Question: I have a SSRS report rendered through sharepoint site.
and i come across an error message:
Unsupported RPL stream version detected: 109.108.1112887328. Expected version: 10.6.
An error occurred during client rendering.
can anyone give me some idea how to solve.
thanks in advance
Comment: Can you try with re-staring your SQL Server Agent? and also take a look into https://connect.microsoft.com/SQLServer/feedback/details/355502/unsupported-rpl-stream-version-detected-10-0-0-expected-version-10-3
Answer: If you are using SharePoint, MS lists this as a not reproducible bug, https://connect.microsoft.com/SQLServer/feedback/details/355502/unsupported-rpl-stream-version-detected-10-0-0-expected-version-10-3
If you aren't using SharePoint, like me, a restart of the SSRS service will fix this.