Is there a way to play WAV files in a cooperative way on Linux in Java?

Question: So far I only found two ways:

throw exception
play nothing

ad.2. Pretty recent code (2010)

http://www.developerfusion.com/article/84314/wired-for-sound/

but does nothing, not sound at all.
ad.1. For example:

Trouble playing wav in Java
http://www.anyexample.com/programming/java/java_play_wav_sound_file.xml
https://stackoverflow.com/a/2433454/210342

All I get is exception "Audio Device Unavailable". As this article (2008) -- lsof |grep snd — how to free a linux sound device -- explains Java has to get exclusive access to audio device.
However I cannot afford such condition. I use sound to notify myself on long running process (several hours), I cannot get rid of all sounds (including those forced via Flash ads) just to make Java comfy.
So for now I use total extreme -- I simply launch external program: https://stackoverflow.com/a/8370223/210342 . This is ugly as hell because well new program is launched just to make notification.
Question
Is there currently a way to play a WAV file:

on Linux,
in cooperative way (during Java playback there may be other audio played as well),
which makes sound,
in Java (no launching external programs)?

Java 1.6, openSUSE 11.4
Answer: Have you tried the Java Media Framework (JMF)?

The Java Media Framework API (JMF) enables audio, video and other
  time-based media to be added to applications and applets built on Java
  technology. This optional package, which can capture, playback,
  stream, and transcode multiple media formats, extends the Java 2
  Platform, Standard Edition (J2SE) for multimedia developers by
  providing a powerful toolkit to develop scalable, cross-platform
  technology.
Comment: Thank you. Actually it does not work for me ;-) but it does not work for a lot of people, even for the plain wav files. Thanks to other posts with problems related to JMF I found other suggestions -- like trying VLC-J.
Answer: This site provides a simple swing application to capture and play wav files
http://www.java-tips.org/java-se-tips/javax.sound/capturing-audio-with-java-sound-api.html
You can modify and use the code from the below site
http://www.anyexample.com/programming/java/java_play_wav_sound_file.xml
Cant you simply create a new thread whenever the play action is needed. So that the playing continues irrespective of the background processes
Comment: Please, pay a little attention -- I gave the second link already, it is repeating the same method I already mentioned it is **not** working. The sound is blocked not by Java, but by the system, adding new threads won't change the fact the audio is blocked (at least Java sees it that way).
Answer: So, thanks to AT answer I drifted from JMF to JMF problems, and that led me to VLC-J. And this is the answer -- in order to use multimedia in Java program simply don't use Java (pity, btw. that Java in year 2012 does not have reliable multimedia layer, gee.).
Marking as solved, because VLC-J allowed me to play audio without problem.
Main project site:
http://code.google.com/p/vlcj/
Minimal playback program:
http://code.google.com/p/vlcj/source/browse/trunk/vlcj/src/test/java/uk/co/caprica/vlcj/test/minimalmp3/Mp3Test.java
Comment: curious... what jdk were you testing with?  openjdk vs sun might be an issue
Comment: @hricosrealm, at the time of writing OP I was using Sun JDK.
Answer: Java has this support built in (available in javax.sound, javax.sound.sampled packages) on 1.4+ version. It works colaboratively with other applications on the system as it uses platform mixer (ALSA or PULSE)
Comment: The more you repeat the "answer" it does not become more right. Please read the question next time, thank you in advance.
Comment: @macias: In this case, have you checked if the permissions on /dev/(audio|mixer) allow you to open the device? Can you write to PULSE sockets? What distribution are you using?
Comment: If I couldn't, I wouldn't get any sound, would I? Again, check the question, I gave information about Java and system. However, in a second I will close this question as answered, because yesterday's AT's answer gave me the right idea.
Comment: @macias: indeed vlcj is a solution but it adds an extra layer of indirection java will depend on libvlc that will depend on OSS|ALSA|Pulse.
Please check this thread for a different (not necessarily better) solution: http://forums.fedoraforum.org/showthread.php?t=248326
Comment: of course I would gladly focus on Java-only solution, but sadly, I didn't find any, and don't have time to test and test, this and that, and something else. I spent with Java-only approach too many time, and vlc-j took me what, downloading the jar, and pasting the code. Job done.


Python nested dictionary gets overwritten even after keeping a copy

Question: I have a nested dictionary to look up some information . Because of python's way of tagging data , i have created copies of the dicts using the copy method of dict . But when I update the innermost dict , it changes other dicts of all other days (mon to fri) .
Here's how I initailize my main dictionary : self.faculty_to_day_hour_slot_map
self.faculty_to_day_hour_slot_map = {}
day_to_hour = {}
faculty_to_data = {}

hour_to_allotflag = {}
for hour in range(1 , 9):
    hour_to_allotflag.update({hour : {'alloted': False}.copy()}.copy()) ;

for day in ['mon' , 'tue' , 'wed' , 'thu' , 'fri' , 'sat']:
    day_to_hour.update({day : hour_to_allotflag.copy()}.copy()) ;

for faculty_object in self.faculties:
    self.faculty_to_day_hour_slot_map.update({faculty_object.id : day_to_hour.copy()}.copy()) ;

The problem occurs when I update the innermost dict like this :
self.faculty_to_day_hour_slot_map.get(faculty).get(day).get(hour)['alloted'] = True

For example :
self.faculty_to_day_hour_slot_map.get('uniqueid').get('mon').get(1)['alloted'] = True

This makes all the 'alloted' as True inside each day ( mon to fri) with hour = 1
How to fix this problem ? why is this occuring despite using copy method ?
The original dictionary looks like this :
{51: {'mon': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'tue': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'wed': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'thu': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'fri': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'sat': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}}},
 15: {'mon': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'tue': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'wed': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'thu': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'fri': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'sat': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}}},
 16: {'mon': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'tue': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'wed': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'thu': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'fri': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'sat': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}}},
 17: {'mon': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'tue': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'wed': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'thu': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'fri': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'sat': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}}},
 18: {'mon': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'tue': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'wed': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'thu': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'fri': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'sat': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}}},
 19: {'mon': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'tue': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'wed': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'thu': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'fri': {1: {'alloted': True},
   2: {'alloted': True},
   3: {'alloted': True},
   4: {'alloted': True},
   5: {'alloted': True},
   6: {'alloted': True},
   7: {'alloted': True},
   8: {'alloted': True}},
  'sat': {1: {'alloted': True},
..... and so on

Comment: try `deepcopy`.
Comment: Use `copy.deepcopy` in the `copy` module.
Comment: Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list)
Answer: copy() function creates a shallow copy of the object. What you might need here is a deep copy.
import copy
d1 = {"Strongest Avenger": "Thor"}
d2 = copy.deepcopy(d1)

https://docs.python.org/2/library/copy.html
Answer: As pointed out by the comments and the previous answer, you should use deepcopy. Also, in the interest of readability, you can use functools.reduce to create the nested dict.
from functools import reduce
from copy import deepcopy

faculty = list(range(10))
days = ['mon' , 'tue' , 'wed' , 'thu' , 'fri' , 'sat']
hours = list(range(1, 9))

res = reduce(
        lambda d, ks: {k: deepcopy(d) for k in ks},
        [hours, days, faculty],
        {'alloted': True}
        )


Losing a node reference? (javascript)

Question: So I have this JS code :
var pElt = document.createElement("p");
var aElt = document.createElement("a");
aElt.textContent = "Text";
aElt.href = "#";
pElt.appendChild(aElt);

aElt.style.color = "red";
pElt.innerHTML += " and more text";
//aElt.style.color = "red";

document.getElementById("content").appendChild(pElt);

console.log(aElt); // always show the red attribute

There's probably some answer around here, but I cannot even describe the problem ; so I went with "losing node reference", even though it's not what happens here. (edit: in fact, that's what happens here, silly :))
So... Please try the code as it is. It works, the link is red, everyone is happy. Now comment the "aElt.style.color = "red";" line, then uncomment the other one, two lines below.
...
It does not work, the link still appear in black. What I thought is that the pointer linked to my node was either not valid anymore or the aElt was moved to a different memory address. But when I type "console.log(aElt)", it outputs the node correctly (well... I think it does), so I don't get why I can't access it after the .innerHTML change.
What interests me is what happens under the hood :)
Thanks!

index.html :
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>Question!</title>

Answer: When you overwrite the content of the
 element by setting it's innerHTML, you're effectively turning the  back into HTML text, appending the  (as text), and then recreating new DOM nodes in the
.  Your old reference still refers to the original  you created.
You could instead create that  the same way you created the , and append that node to the
 instead of overwriting .innerHTML.
Comment: Thanks for making that clear. .innerHTML is definitely not my friend :)

Losing a node reference? (javascript)


Extending an existing location configuration instead of overwriting it

Question: What I have
I have Nginx configured to handle the .php files for all virtual hosts, and everything works fine.
location ~ \.php {
    include snippets/fastcgi-php.conf;
    keepalive_timeout 0;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}

The above sits in snippets/common.conf and is included to every virtual host configuration. The aforementioned fastcgi-php.conf sits next to it.
What I need
For a given virtual host, I need to deny access to all files except /example.php.
What I tried

location ~ ^/example {
    allow all;
}
location ~ ^/ {
    allow 220.127.116.11;
    deny all;
}

The restriction itself works fine, but the PHP file is now returned as a source text, instead of being handled. That means the above somehow overwrites the previous location ~ \.php, even though I haven't even included the .php extension here.

Create common-php.conf
include snippets/fastcgi-php.conf;
keepalive_timeout 0;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;

Reuse it in common.conf:
location ~ \.php {
    include snippets/common-php.conf;
}

And in my actual virtual host configuration:
location ~ ^/example {
    allow all;
    include snippets/common-php.conf;
}
location ~ ^/ {
    allow 126.96.36.199;
    deny all;
    include snippets/common-php.conf;
}

The problems with the above are:

It significantly complicates the setup
It seems redundant to configure /example.php twice
It doesn't fully work, as I'm getting 403 at e.g. /plugins/Feedback/angularjs/feedback-popup/feedback-popup.directive.html?cb=abcd1234 for some reason. The CMS I'm using is complicated, and for the previous two reasons, I didn't investigate further.

I would like to configure access to the /example.php file without overwriting the existing PHP handler it has attached to it. Is this possible? Or are the includes my only option?
Please let me know if you can think of a better configuration for this task. Thank you!
Answer: That is, a very common error is doing something like
location / {
    ... some settings
}
location /admin {
    ... additional settings
}

and expecting that /admin/... request would use a combined settings. It won't, depending on location where the request will be finally served, only one settings set will be applied. However as I already said every request can traverse through several location blocks and some tricks can be done using variables manipulation. A certain variable can get changed several times while request travels through different locations and its actual value can be used in the final location as some directive parameter. This question solution won't use this technique, but it is possible for some other cases.
Many things (e.g. conditional headers) can be implemented using the (very powerful) nginx map feature. An alternative to allow/deny rules can be achieved combining the map and geo blocks to evaluate a variable acting as a flag to indicate should the request be blocked or not (some more generic example can be found here):
map $uri $restricted {
    /example.php     0;
    default          1;
}
geo $deny {
    18.104.22.168  0;
    default          $restricted;
}

Now to make a decision whether request should be blocked or not, you can use the following if block:
if ($deny) { return 403; }

It can be placed either at the server level or at the PHP handler location. However placing it at the server level would be more optimal since it will be executed at the earlier NGX_HTTP_SERVER_REWRITE_PHASE instead of NGX_HTTP_REWRITE_PHASE.
If for some reason you'd want to add the basic authentication instead of IP filtering, it can be achieved using the following trick:
map $uri $restricted {
    /example.php     off;
    default          "Protected area";
}
geo $realm {
    22.214.171.124  off;
    default          $restricted;
}

location ~ \.php$ {
    auth_basic $realm;
    auth_basic_user_file /path/to/.htpasswd;
    ...
}


Apache generating too many rotatelogs.exe on Windows?

Question: I'm seeing some odd behavior with Apache's rotatelogs.exe.  On one of my servers I'm seeing multiple rotatelogs.exe counting into the 100's.  Normally I usually only see 6 which I can rationalize to the 3 logs I have rotating.  Does anyone know why this might be happening and how I can prevent it from happening?  When the rotatelogs.exe processes get up into the 100's everything slows down and Apache is effectively shut down because it can't process requests anymore.
We are using the following line in our httpd.conf file:

ErrorLog "|\"C:/Program Files/Apache2/bin/rotatelogs.exe\" \"C:/Program Files/Apache2/logs/error_log.%Y-%m-%d-%H_%M_%S\" 20M"

Thanks in advance for the help!
Answer: I found this was a bug in the version of Apache we were using.  The RotateLogs processes were becoming unattached from the Apache instance and not shutting down properly.  By upgrading to the latest 2.0 branch of Apache (2.0.63 at the time of this writing) the problem was corrected.


esri-leaflet query mutliple features (with setWhere)

Question: We created a map in ArcGIS Online which is implemented with Leafletjs onto our website. Our aim is to query multiple features, but we don't know how, since we don't have much programming knowledge (geography students).
Specific problem: We have multiple dropdown menues concerning hiking trails and want to let users select for example the region and duration. But so far if the second selection is made, the choices from the previous selection are deleted and only the newest selection appeears.
Any suggestions? Thank you already! Corin & group
CODE:
one of the value definitions:

Choose a region

  <select id="region_nr">
    <option value=''>Alle anwählen</option>
    <option value='1'>Berner Oberland</option>
    <option value='2'>Graubünden</option>
    <option value='3'>Innerschweiz</option>
    <option value='4'>Mittelland</option>
    <option value='5'>Ostschweiz</option>
    <option value='6'>Tessin</option>
    <option value='7'>Wallis</option>
    <option value='8'>Westschweiz</option>
  </select>

and the query looks like this:
  var region_nr = document.getElementById('region_nr');
  var difficulty = document.getElementById('difficulty');
  var time_nr = document.getElementById('time_nr');
  var season = document.getElementById('season');

  region_nr.addEventListener('change', function(){
    trails.setWhere('region_nr="'+region_nr.value+'"');
  });

  difficulty.addEventListener('change', function(){
trails.setWhere('difficulty="'+difficulty.value+'"');
  });
  time_nr.addEventListener('change', function(){
trails.setWhere('time_nr="'+time_nr.value+'"');
  });
  season.addEventListener('change', function(){
    trails.setWhere('season="'+season.value+'"');
  });

Answer: Try this for example:
trails.setWhere('difficulty IN (' + difficulty.value + ')');

You can also have multiple values separated by a , .


Where is the kernel source in build?

Question: I build a yocto OS image, the image is done, but I can't find the kernel source.
I want to modify some files in the kernel source.
I see no any kernel source file in build/
Answer: i built for Yocto dunfell , core-image-minimal image for qemuarm machine
You can find kernel source in
build/tmp/work-shared/qemuarm/kernel-source

Where is the kernel source in build?


timerfd and read

Question: I have application, that periodically (by timer) check some data storage.
Like this:
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <sys/fcntl.h>
#include <unistd.h>

// EPOLL & TIMER
#include <sys/epoll.h>
#include <sys/timerfd.h>

int main(int argc, char **argv)
{
    /* epoll instance */
    int efd = epoll_create1(EPOLL_CLOEXEC);

    if (efd < 0)
    {
        std::cerr << "epoll_create error: " << strerror(errno) << std::endl;
        return EXIT_FAILURE;
    }

    struct epoll_event ev;
    struct epoll_event events[128];

    /* timer instance */
    int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);

    struct timespec ts;
    // first expiration in 3. seconds after program start
    ts.tv_sec = 3;
    ts.tv_nsec = 0;

    struct itimerspec new_timeout;
    struct itimerspec old_timeout;

    bzero(&new_timeout, sizeof(new_timeout));
    bzero(&old_timeout, sizeof(old_timeout));

    // value
    new_timeout.it_value = ts;

    // no interval;
    // timer will be armed in epoll_wait event trigger
    new_timeout.it_interval.tv_sec =
    new_timeout.it_interval.tv_nsec = 0;

    // Add the timer descriptor to epoll.
    if (tfd != -1)
    {
        ev.events = EPOLLIN | EPOLLERR /*| EPOLLET*/;
        ev.data.ptr = &tfd;
        epoll_ctl(efd, EPOLL_CTL_ADD, tfd, &ev);
    }

    int flags = 0;
    if (timerfd_settime(tfd, flags, &new_timeout, &old_timeout) < 0)
    {
       std::cerr << "timerfd_settime error: " << strerror(errno) << std::endl;
    }

    int numEvents = 0;
    int timeout = 0;
    bool checkTimer = false;
    while (1)
    {
        checkTimer = false;
        numEvents = epoll_wait(efd, events, 128, timeout);
        if (numEvents > 0)
        {
            for (int i = 0; i < numEvents; ++i)
            {
                if (events[i].data.ptr == &tfd)
                {
                    std::cout << "timeout" << std::endl;
                    checkTimer = true;
                }
            }
        }
        else if(numEvents == 0)
        {
            continue;
        }
        else
        {
            std::cerr << "An error occured: " << strerror(errno) << std::endl;
        }

        if (checkTimer)
        {
            /* Check data storage */
            uint64_t value;
            ssize_t readBytes;
            //while ( (readBytes = read(tfd, &value, 8)) > 0)
            //{
            //    std::cout << "\tread: '" << value << "'" << std::endl;
            //}
            itimerspec new_timeout;
            itimerspec old_timeout;
            new_timeout.it_value.tv_sec = rand() % 3 + 1;
            new_timeout.it_value.tv_nsec = 0;
            new_timeout.it_interval.tv_sec =
            new_timeout.it_interval.tv_nsec = 0;
            timerfd_settime(tfd, flags, &new_timeout, &old_timeout);
        }
    }

    return EXIT_SUCCESS;
}

This is simple description of my app.
After each timeout timer need to be rearmed by some value different in each timeout.
Questions are:

Is it necessary to add timerfd to epoll (epoll_ctl) with EPOLLET flag?
Is it necessary to read timerfd after each timeout?
Is it necessary to epoll_wait infinitely (timeout = -1)?
Answer: You can do this in one of two modes, edge triggered or level triggered. If you choose the edge triggered route then you must pass EPOLLET and do not need to read the timerfd after each wakeup. The fact that you receive an event from epoll means one or more time outs have fired. Optionally you may read the timerfd and it will return the number of time outs that have fired since you last read it.
If you choose the level triggered route then you don't need to pass EPOLLET, but you must read the timerfd after each wakeup. If you do not then you will immediately be woken up again until you consume the time out.
You should either pass -1 to epoll as the time out or some positive value. If you pass 0, like you do in the example, then you will never go to sleep, you'll just spin waiting for the time out to fire. That's almost certainly undesirable behaviour.
Comment: Seems like `read()` is a must in both cases. Without `read()`, in the case of `EPOLLET`, you will not get the next event (until `read()` occur), and without `EPOLLET`, you will continuously receive the event (until `read()` occur).
Answer: Answers to the questions:

Is it necessary to add timerfd to epoll (epoll_ctl) with EPOLLET flag?

No. Adding EPOLLET (edge trigger) does changes the behavior of receiving events. Without EPOLLET, you'll continuously receive the event from epoll_wait related to the timerfd until you've read() from the timerfd. With EPOLLET, you'll NOT receive additional events beyond the first one, even if new expiration occurs, until you've read() from the timerfd and a new expiration occur.

Is it necessary to read timerfd after each timeout?

Yes in order to continue and receive events (only) when new expiration occur (see above). No when periodic timer is not used (single expiration only), and you close the timerfd without reading.

Is it necessary to epoll_wait infinitely (timeout = -1)?

No. You can use epoll_wait's timeout instead of timerfd. I personally think it is easier to use timerfd than keep calculating the next timeout for EPOLL, especially if you expect multiple timeout intervals; keeping tabs on what is your next task when timeout occurs is much easier when it is tied to the specific event what woke up.

timerfd and read


Como fazer para que um grupo de parâmetros seja requerido se pelo menos um deles for informado?

Question: Em Python temos os valores default, que são opcionais quando chamamos uma função.
Queria saber se tem algum jeito de fazer com que um grupo de valores sejam opcionais, tipo ou se passa todos aqueles valores ou nenhum.
def func(nome=None, cpf=None):
    pass

Caso se passe apenas o nome ou o cpf daria um erro, só funcionaria se passar os dois ou nenhum. Não sei se minha pergunta fez sentido, espero que sim.
Answer:
TL;DR
  Para responder especificamente à pergunta, vá direto ao tópico "Respondendo especificamente a pergunta."

Em Python podemos chamar funções, enviando argumentos de forma "posicional" e/ou  "nomeada", para entender isso vejamos uma função que recebe 3 argumentos e apenas os devolve em uma tupla:
def f1(arg1, arg2, arg3):
    return (arg1, arg2, arg3)

Como esses argumentos não tem valores atribuídos (valores default), são considerados argumentos obrigatórios, sendo assim, para chamar essa função temos que passar os 3 argumentos obrigatoriamente, mas temos duas formas de fazer isso:
Chamando os argumentos de forma posicional:
>>> f1(1,2,3)
(1,2,3)

Ou de forma nomeada:
>>> f1(arg2=2, arg1=3, arg3=1)
(3,2,1)

Note que apesar da obrigatoriedade do envio dos 3 argumentos a ordem dos argumentos não precisa ser a mesma quando chamamos a função com a forma nomeada.
Podemos também fazer um mix, chamando parte de forma posicional e parte de forma nomeada, desde que a forma posicional anteceda a forma posicionada:
# Ok
>>> f1(1, 2, arg3=99)
(1, 2, 99)

# Error
>>> f1(1, arg2=2, 3)
SyntaxError: positional argument follows keyword argument

É importante observar que temos que enviar sempre os 3 argumentos, sem repeti-los, chamadas como as exemplificadas abaixo levantarão exceção de erros:
>>> f1(1, 2, arg1=10)
TypeError: f1() got multiple values for argument 'arg1'

>>> f1(arg1=1, arg3=3)
f1() missing 1 required positional argument: 'arg2'

>>> f1(1,2)
TypeError: f1() missing 1 required positional argument: 'arg3'

Chamar as funções enviando argumentos de forma posicional ou nomeada, qual é melhor?
A maioria dos programadores utiliza, na maior parte do tempo, a forma posicional, mas a forma nomeada torna as chamadas às funções mais claras, flexíveis e explícitas, mais de acordo com o zen do Python, vejamos esse código:
def save_txt(out_file, contents):
    with open(out_file,'w+') as f:
        for line in contents:
             f.write(line)

Essa função recebe como parâmetro out_file e contents pega as linhas de texto e grava no arquivo de saída, quais das chamadas abaixo ficam mais claras e flexíveis?
lines = '''
        Por que usar argumentos nomeados?
        Porque é mais claro e explícito
        '''
file_name = 'lines.txt'

# Chamada com argumentos de forma posicional
save_txt(file_name, lines)

# Chamadas com argumentos na forma nomeada:
save_txt(out_file=file_name, contents=lines)

# Segunda opcao para chamada nomeada
save_txt(contents=lines, out_file=file_name)

Argumentos "default":
Python também permite que os argumentos de uma função tenham valores atribuídos por omissão (Default), esses valores são atribuídos na definição da função:
def f1(arg1, arg2, arg3=99):
    return (arg1, arg2, arg3)

Agora é obrigatório enviar os 2 primeiros parâmetros na chamada à função, mas o ultimo é opcional, a chamada requer as mesmas regras para as chamadas anteriores:
Válidas:
>>> f1(1,2)
(1, 2, 99)

>>> f1(1,2,arg3=88)
(1, 2, 88)

>>> f1(arg3=3, arg2=2, arg1=1)
(1, 2, 3)

Inválidas:
>>> f1(arg3=77,1,2)
SyntaxError: positional argument follows keyword argument

>>> f1(arg1=1,2,3)
SyntaxError: positional argument follows keyword argument

Número arbitrário de argumentos, seguido da obrigação de argumentos nomeados:
Pode-se também definir uma função que recebe um número variável de argumentos seguido de argumentos obrigatoriamente nomeados, usando o operador *:
def f2(*args, default=99):
    return (args, default)

Nesse exemplo os primeiros argumentos (obrigatoriamente posicionais), não importa quantos sejam, serão recebidos na variável args que é do tipo tuple, note que a função exemplo tem como retorno uma tupla, então ao chama-la teremos como retorno uma tupla que contem a tupla args e o valor da variável default, vejamos alguns exemplos:
>>> f2(1,2,3)
((1, 2, 3), 99)

>>> f2(1,2,3,4,5,6,'teste',[1,2,3])
((1, 2, 3, 4, 5, 6, 'teste', [1, 2, 3]), 99)

>>> f2(1,2,default=3)
((1, 2), 3)

Somente argumentos nomeados, obrigatoriamente:
Para que a função aceite somente argumentos nomeados, de forma obrigatória, sem a necessidade de aceitar um número arbitrário de argumentos posicionais através do operador *, é só utilizar esse mesmo operador, sem nada na sua frente:
def f3(*, arg1, arg2, arg3):
    return(arg1, arg2, arg3)

Veja que agora é mandatório que a chamada seja feita através da forma de argumentos nomeados e obrigatoriamente enviando todos eles, embora ainda possamos variar a ordem dos argumentos, assim temos como chamadas válidas:
>>> f3(arg3=1,arg2=2,arg1=3)
(3, 2, 1)

>>> f3(arg1=3,arg2=2,arg3=1)
(3, 2, 1)

Mas as chamadas abaixo são inválidas:
>>> f3(1, 2, 3)
f3() takes 0 positional arguments but 3 were given

>>> f3(arg1=1, arg2=2)
TypeError: f3() missing 1 required keyword-only argument: 'arg3'

Argumentos nomeados, incluindo defaults:
também é permitido mixar a obrigatoriedade de argumentos nomeados com argumentos defaults, dessa forma a última chamada acima não produziria erro, para isso a função teria que ser definida como abaixo:
def f3(*, arg1, arg2, arg3=99):
    return(arg1, arg2, arg3)

O asterisco pode ser posicionado em qualquer lugar, por exemplo poderia-se se definir a função com apenas o primeiro parâmetro sendo posicional e os outros dois sendo nomeados obrigatórios, assim:
def f4(arg1, *, arg2,  arg3):
    return(arg1, arg2, arg3)

Nesse caso todos os argumentos seriam obrigatórios, sendo que os 2 últimos teriam que ser chamados, obrigatoriamente de forma nomeada, dessa forma teríamos como chamada inválida, por exemplo:
>>> f4(1, arg3=3)
f4() missing 1 required keyword-only argument: 'arg2'

Para que essa última chamada fosse válida, teríamos que ter definido a função da seguinte forma:
def f4(arg1, *, arg2=2,  arg3):
    return(arg1, arg2, arg3)

Argumentos nomeados de forma arbitrária
Com o Python é possível, também, que uma função receba um número arbitrário de argumentos nomeados, vamos usar como exemplo a função media_curso() de uma escola de cursos livres que recebe como parâmetro, o nome do curso e os nomes e notas dos alunos, para calcular a média aritmética da classe.
def media_curso(curso, **notas):
    return sum(list(notas.values()))/len(notas)

Vamos chamar a função para a turma de 4 alunos do curso de Python:
>>> media_curso('python', john=7, Doe=9, Foo=5, Bar=6)
6.75

Digamos que uma aluna ingresse atrasada no curso e no próximo mês a função teria que ser chamada incluindo a nota dela, então a chamada seria:
>>>> media_curso('python', john=9, Doe=6, Foo=8, Bar=5, Lena=9 )
7.4

O que os dois asteriscos (**) fazem é pegar todos os argumentos nomeados que foram enviados em sequencia, empacotar em um dicionário e atribuir ao argumento à sua frente (no caso notas), uma outra forma de chamar a função seria enviando um dicionário já "resolvido" ou "desempacotado", assim:
>>> d = {'john': 9, 'Doe': 6, 'Foo': 8, 'Bar': 5, 'Lena': 9}
>>> media_curso('python', **d )
7.4

Tudo misturado:
Como visto, podemos tanto passar como receber números arbitrários de argumentos, de forma nomeada ou não. É por isso que frequentemente vimos chamadas do tipo abaixo, principalmente no uso de herança, muito comum em frameworks como o Django.
def some_method(self, *args, **kwargs):
    # do something
    # ...
    super().some_method(*args, **kwargs)

Note que a convenção kwargs é para denotar argumentos enviados através de "key/Value". Essa é uma pratica comum quando se sobrepõe métodos de frameworks em que se deseja alterar o acessar parâmetros e então chamar o método "pai" na chamada super().
Respondendo especificamente a pergunta:
Depois da edição do título da pergunta notei que não deixei, de forma explícita, uma forma de atende-la especificamente, então elaborei, baseado no exposto acima, a seguinte solução:
def f(**args):
    if len(args)>0:
        if ['nome', 'cpf'] != list(args):
            return 'Erro' # Ou levante uma exceção aqui
    # Faça o que for necessário
    return 'Ok'

Testando:
# Sem nenhum argumento:
f()
'Ok'

# Somente com um argumento
f(nome='Foo')
'Erro'

# Com dois argumentos, sendo um com o nome errado
f(nome='Foo', idade=21)
'Erro'

# Com os dois argumentos exigidos
f(nome='Foo', cpf=1234)
'Ok'

Veja que com essa solução, os dois argumentos são obrigatórios se um deles for entregue, ou seja, ou você envia os dois ou não envia nada. Mas você pode colocar na frente um parâmetro obrigatório, por exemplo:
def f(cidade, **args):
    if len(args)>0:
        if ['nome', 'cpf'] != list(args):
           return 'Erro' # Ou levante uma exceção aqui
    # Faça o que for necessário
    return cidade

Agora você não consegue mais chamar se não enviar pelo menos o argumento cidade, embora as condições anteriores para nome e cpf continuem válidas.
Comment: Eu recomendaria um livro em que essa resposta fosse um dos capítulos!  :-)
Mas acho que ela  aborda de forma direta apenas metade do problema da  pergunta feita: como obrigar todos os argumentos. Mas não aborda "como permitir nenhum agumento" - claro que entendendo até aqui, a pessoa pode construir uma aplicação bem sólida. (eu mesmo, vendo todas as possiblidades descritas assim estou imaginando se não há uma forma mais simples do que os decoradores que sugeri)
Comment: @jsbueno, Depois da edição do título pelo  Anderson, tive um outro entendimento da pergunta, então baseado no que ja tinha escrito, elaborei uma abordagem para atender, acredito com um pouco mais de tempo poderia ficar melhor.
Answer: Claro que a linguagem não tem como trazer prontos todos os usos imaginados possíveis - seja para lista de parâmetros, seja pra outras coisas.
Mas ela inclui mecanismos o suficiente para você poder implementar isso -
no caso, uma boa forma é fazer uso de decoradores! Decoradores são uma sintaxe para funções que modificam outras funções.
Esta resposta usa aspectos bastante avançados da linguagem - não tem problema se apesar de entender os conceitos não der pra entender todo o código agora -
os exemplos abaixo usam conceitos e mecanismos sólidos o suficiente da linguagem  para serem incorporados num projeto de produção (isso é: não dependem de detalhes de implementação, ou funcionalidades não documentadas).
Decorator que checa os parâmetros:
Então no caso, você pega os controles que, sem esse mecanismo, teriam que ficar em código normal, dentro da função - um "if" para checar se os valores foram passados, por exemplo, e move essa lógica para o decorador.
Isso é tranquilo. Outra coisa que precisamos é fazer isso funcionar pra funções genéricas: isso é, o decorador não vai saber se a função em que ele vai ser aplicado vai ter 1, 2 ou 10 parâmetros opcionais.
O módulo inspect tem funções que permitem checar isso - e aí podemos levantar um TypeError com a mensagem apropriada (ou retornar um valor de erro fixo, se você preferir).
No caso, o módulo inspect sim, tem classes e utilitários para lidar com todas as formas possíveis de parâmetros - inclusive anotações, listas de argumentos em ordem, parâmetros passados como dicionários, etc...isso faz com que seu uso seja um pouco complicado -
Para o caso em questão, são alguns passos: Usar inspect.signature para extrair a assinatura da função, no objeto retornado, (que é uma de classe Signature do módulo inspect), chamamos o método bind para aplicar os parâmetros passados, e no objeto retornado por isso chamamos o método apply_defaults e em seguida olhamos se, uma vez aplicados os parâmetros, sobrou algum dos valores padrão que você determinou = para isso comparamos os argumentos que foram vinculados com o que a Signature tem em seu atributo Parameters.
Soa complicado, mas é preciso fazer uma vez só - e você pode manter num módulo utils.py no seu projeto:
from functools import wraps
import inspect

def all_or_nothing(func):
    signature = inspect.signature(func)

    @wraps(func)
    def wrapper(*args, **kw):
        bound_args = signature.bind(*args, **kw)
        bound_args.apply_defaults()

        all_ = True
        any_ = False
        for parameter, argument in zip(signature.parameters.values(), bound_args.arguments.values()):
            if parameter.default == argument:
                all_ = False
            else:
                any_ = True
        if any_ and not all_:
            raise TypeError(f"Either pass all optional arguments or no argument in call to {func.__name__}")
        return func(*args, **kw)

    return wrapper

(Seria possível fazer um decorador mais simples, sem usar o módulo "inspect", baseado apenas no número de argumentos passados - mas ele não teria vantagens sobre esse a não ser não exigir que quem escreva o decorador em si saiba usar as funcionalidades do módulo).
Funcionando:
In [137]: @all_or_nothing
     ...: def func(nome="", cpf=None):
     ...:     pass
     ...:
     ...:

In [138]: func("alo", 123)

In [139]: func()

In [140]: func("alo")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
(...)
TypeError: Either pass all optional arguments or no argument in call to func

Usando Polimorfismo
Uma outra abordagem, também com decoradores, permite emular o polimorfismo - uma caracteristica que existe em linguagens estaticamente tipadas como Java e C++ - nesse caso, você cria funções com o mesmo nome, mas com lista de parâmetros distintas, e o mecanismo de decoradores despacha a chamada para a função apropriada de acordo com os parâmetros passados.  (O mesmo mecanismo do Python também tem que dar um jeito decoradas terem  o mesmo nome).
A própria linguagem Python já tem um decorador especial que faz algo parecido, mas apenas baseada no tipo do primeiro parâmetro - o functools.singledispatch - mas ele não faz o despacho entre números de parâmetros diferentes (e nem permite que as funções decoradas tenham o mesmo nome). Então basicamente esse mecanismo teria que ser recriado - isso, como o anterior, apesar de complexo, não é extenso, e pode ser feito uma única vez:
from functools import wraps
import inspect

def polymorph(original_func):
    registry = {}
    original_signature = inspect.signature(original_func)
    def register(func):
        registry[tuple(inspect.signature(func).parameters.keys())] = func
        return wrapper

    @wraps(func)
    def wrapper(*args, **kw):
        arg_names = tuple(original_signature.bind(*args, **kw).arguments.keys())
        try:
            dispatchee = registry[arg_names]
        except KeyError:
            raise TypeError(f"No registered version of {func.__name__} found requiring parameters {arg_names}")
        return dispatchee(*args, **kw)

    register(original_func)
    wrapper.register = register
    wrapper.registry = registry
    return wrapper

E isso funcionando:
In [184]: @polymorph
     ...: def func(nome="", cpf=123):
     ...:     print(nome, cpf)
     ...:
     ...:
     ...:
     ...:
     ...:

In [185]: @func.register
     ...: def func():
     ...:     print("no parameters")
     ...:
     ...:

In [186]: func()
no parameters

In [187]: func("alo", 123)
alo 123

In [188]: func("alo")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
(...)
TypeError: No registered version of func found requiring parameters ('nome',)

Note que não seria difícil estender esse mecanismo para atuar verificar também os tipos dos parâmetros dados por anotações - e isso possibilitaria "polimorfismo completo" - como existe em linguagens como Java ou C++ em pouco mais de 20 linhas de código
Answer: Primeiro, leia as respostas:

Usando decoradores, por jsbueno
Aula de parâmetros, por Sidon

Mas uma solução específica para o seu problema - isto é, algo que não seja genérico e independente da função - é validar manualmente as condições. Possuindo dois parâmetros que, por padrão, são None, você pode verificar se ambos são None ou se ambos são diferente de None. Se apenas um deles ser None significa que nem todos os parâmetros foram informados.
O operador lógico XOR resolve bem o problema:
def func(nome=None, cpf=None):
    if ((nome is None) ^ (cpf is None)):
        raise ValueError('Nem todos os parâmetros foram informados')
    print('Ok')

Assim:
>>> func()
'Ok'

>>> func('Anderson', 123)
'Ok'

>>> func('Anderson')
ValueError: Nem todos os parâmetros foram informados

>>> func(cpf=123)
ValueError: Nem todos os parâmetros foram informados

Answer: Pelo que entendi, o que tu quer é obrigar a passagem dos dois valores ou não passar nenhum, o meio termo não te interessa, é isso?
Em algumas linguagens a sobrescrita de métodos se da por criar um novo com o mesmo nome, porem com outros parâmetros e assim uma outra lógica, em python isso não ocorre, nele tu tem este recurso de definir um valor default.
Para este teu caso, o melhor a fazer é criar uma verificação interna, se ambos os campos foram devidamente preenchidos ou nenhum, então lança um retorno, caso contrario lança outro retorno.


How do I compare individual likert scale items

Question: I am looking to compare individual likert scale items.
I measured respondent's level of agreement (in a 5 point-scale) for several items (e.g. from 1 to 5 how much is A competent to treat your condition? how much is B? C? and so on..- 11 items in total). I want to analyse if the scores for each statement are significantly different?
I am considering the data as ordinal and as such using non-parametric analysis. So far what I did was a Friedman test (which should indicate if there is agreement between k set of ranking) (p<0.001). So indeed the distribution of the several scores (of the several items) are different. But I also wanted to know which items are statistically significanly different. So I did a Kendall correlation for all items.

Is this the right approach?
Can anyone let me know what is the best way to compare likert-scale items?
Answer: As I understand your question, Friedman's test is a reasonable test to use.
You are treating the items as treatments, groups, or "subjects"†.  And you are treating respondents as blocks or raters.  And you have unreplicated complete block design.
But you might want to reconsider your choice of post-hoc test.  If you want to compare among the items, you want to use an accepted post-hoc test for Friedman's.  One common test is often called Conover test. Another is often called Nemenyi test.
These are available in software packages.
For some references, and other tests, see the descriptions for functions beginning with "frd" in this R package.
Using correlations will not make sense as a post-hoc test for how you are using the Friedman test, though they may be interesting to answer other questions.

† Sorry, it's not my terminology, but confusingly the term "subject" is used for the treatments, especially when Kendall's W, an effect size statistic for Friedman's test, is being discussed.


Integrability of a function on the unit ball and the complement of the unit ball

Question: Consider the function $f_a(x)=|x|^a$, $0\neq x \in \mathbb{R}^d$,$f_a(0)=0$,where $|x|$ denotes the Euclidean distance from $x$ to the origin in $\mathbb{R}^d$, and $a \in \mathbb{R}$ is a fixed parameter. For which values of $a$ is $f_a$ integrable on the unit ball $B=\{ x\in \mathbb{R}^d:|x| \leq 1 \}$. What about for integrability on $\mathbb{R}^d$\ $B$, for which values of $a$ is $f_a$ integrable?
Answer: The volume element in $\mathbb{R}^n$ can be written as
$$
d^{n}x=\left(r^{n-1}dr\right)\left(d^{n-1}\Omega\right),
$$
where $d^{n-1}\Omega$ is the area element on the surface of the $n$-sphere, and $\int d^{n-1}\Omega$ is the surface area of the unit $n$-sphere (e.g., $2\pi$ for $n=2$ and $4\pi/3$ for $n=3$).  So the integrability of $f(x)=|x|^{a}$ on the unit ball depends on whether $r^{a+n-1}$ is integrable at $r=0$; and its integrability on the complement of the unit ball depends on whether $r^{a+n-1}$ is integrable as $r\rightarrow\infty$.  In particular, the integral of $r^{a+n-1}$ is proportional to $r^{a+n}$ for $a\neq -n$, and to $\log r$ for $a=-n$, giving the following cases:

$a<-n$: $\; f(x)$ integrable over $B^{c}$ but not $B$;
$a=-n$: $\; f(x)$ not integrable over $B$ or $B^{c}$;
$a>-n$: $\;f(x)$ integrable over $B$ but not $B^{c}$.


Function not working with spaces in file

Question: def square(sq):
    grid = len(sq)
    for line in sq:
        if len(line) != grid:
            raise ValueError

while True:
try:
    filesname = input("Enter the filename:") + ".txt"
    file = open(filesname,"r")
    readFile = file.readlines()
    file.close()
    thelist = [line.strip() for line in readFile]
    square(thelist)
    print ("File has:")
    print("\n".join(thelist))

except FileNotFoundError:
    print ("The file name you have entered does not exist. Please try again.")
except ValueError:
    print ("")
    print ("Incorrect file format")
else:
    break

The file I am trying to open is:
A B C
B C A
C A B

I want to open the file and check if it is a square grid and then report back to the user if it is or not. As you can see the file above is a square grid, however my program says it is not.
When I execute this code it keeps saying "incorrect file format". I think it has something to do with the square function and that it doesn't take into consideration the spaces between the letters and I am not sure how to fix this, can anyone help me?
Comment: Use `split()` not `strip()`
Answer: You've got a sound-alike problem:
>>> "A B C\n".split()
['A', 'B', 'C']
>>> "A B C\n".strip()
'A B C'

In other words, use split(), not strip().
Comment: Thanks. I am using "for lines in thelist:print(lines)" to print the square out. How can I print it without the brackets and commas around the letter?
Comment: @LKINLKER , use `''.join(lines)`


Warning: 'newdata' has x rows but variables found have >x rows with coxph and survfit

Question: I have reviewed the other similar questions and I don't believe I have found the answers.
I am trying to do Cox regression with two co-variates - sex and disease status.
Original data frame looks a bit like this:
Patient ID: 1001, 1002
Age: 56, 60
Sex: Male, Female
Mortality event: 1 0
Follow up years: 6,7

I have called cxmod <- coxph(Surv(Mortality event, time) ~ Disease_status + Sex, data = original data)
I have set up a dummy_df as a grid as per instructions for this package for the co-variates:
Sex Male  Disease_status 0,
Sex  Female Disease_status 0,
Sex Male Disease status 1,
Sex Female Disease status 1

I have renamed the rownames as letters since I understood this is what was needed.
However when I call:
cxsf <- survfit(cxmod, data= orginal_data_frame, newdata = dummy_df, conf.type = "none")

I get the following error message:
Warning message:
'newdata' had 4 rows but variables found have 500000 rows

Furthermore, if I call surv_summary(cxsf) to help visualise the plot - the R sessions gets terminated encountering a fatal error.
Can anyone advise on what's going wrong?
Comment: Welcome to SO,first provide some sample data, second format your question with crtl+k, also maybe ask this question in https://stats.stackexchange.com/
Answer: You do not need to provide the original dataset to survfit because already the model has been trained using it and now the parameters exist in the model itself (cxmod).
survfit(cxmod , newdata = dummy_df, conf.type = "none")


Question from quadratic equations

Question: Let $$f(x) = –x^2+ 2px – (3p + 4)$$. If $f(x)$ is positive for atleast one real $x$ then the smallest positive integral value of $p$ is:
(1)     $2$
(2)     $3$
(3) $4$
(4) $5$
What I did, Since for atleast one value of $x$ ,$f(x)$>0
Or,$$ x^2- 2px + (3p + 4)<0$$
Now ,how should I proceed ?
Comment: Please keep the hints or explanation comprehensible as I am a 12th grade student.thanks
Comment: I'd suggest substituting those values in for $p$ and seeing what happened. Here we could use the discriminant to help us a bit, or we could graph them to see what happens.
Comment: Since $f$ is positive for some $x$ and opens downward. You can assume that there are two real roots to the equation $f=0$. Use the quadratic formula to generate these roots as functions of $p$. The discriminant(expression under the radical sign in the formula) must necessarily be positive. Examination of this term will allow you to finish the problem.
Comment: @JEM after checking the discriminant I get,
Comment: (p-4)(p+1)>0...what should I do now ?
Comment: I don't get a minimum value through this because it goes down to negative infinity ,right?
Comment: @YashLekhwani: You have it. There is only one choice that satisfies that.
Comment: Oh yeah..I'm sorry I'm speaking non sense it says positive integral value..:)My bad..thanks anyways..
Answer: "Complete the square" to get:
$$\begin{align}-x^2 + 2px - (3p + 4) &= -(x^2 -2px + (3p + 4))\\
&= -(( x - p)^2 + (3p+4) - p^2)\\ &= -(x-p)^2 + p^2 - 3p - 4\\
&= -(x-p)^2 + (p-4)(p+1)\end{align}$$
Since $-(x-p)^2 \le 0$ for all real $x$ and $p$, the maximum value of $-x^2 + 2px - (3p + 4)$ is $(p-4)(p+1)$. In other words,
$$-x^2 + 2px - (3p + 4) \le (p-4)(p+1)$$
with equality achieved at $x = p$.
Since we need $f(x)$ to be positive for at least one real value of $x$, it suffices to find $p$ for which the maximum value of $f(x)$ is positive. In other words, the required values of $p$ are:
$$(p - 4)(p +1) > 0$$
whose solution set is $p > 4$ or $p < -1$.
Hence the least possible positive integral value of $p$ is $5$.
Comment: Beautiful explanation.Although the method is nearly same as what I finally used,it made it more clear to me.@YiyuanLee.thanks a lot.
Comment: Hey!!Ur 17 too.All the very best wishes from me.Continue chasing your passions!!hehe..:)
Comment: No problem, thanks and all the best to you to! Since you are new to Math.SE : Do remember to mark any of the answers posted to your question as the solution via the tick beside it, if you found it sufficient and useful.

Question from quadratic equations


Intellij does not open existing projects after update

Question: I updated to Intellij 2018.3.5 today and now it wont open any of my previous projects that are .idea based. In the logs I can see the following. This was working fine with 2018.3.4.
This appears to happen only in Ubuntu not in Windows.
<code>2019-03-07 14:58:06,594 [ 246696]   INFO - roject.impl.ProjectManagerImpl - Fatal error initializing plugin com.intellij.uiDesigner
com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.intellij.uiDesigner
    at com.intellij.ide.plugins.PluginManager.handleComponentError(PluginManager.java:253)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.handleInitComponentError(PlatformComponentManagerImpl.java:43)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:504)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:104)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:88)
    at com.intellij.openapi.project.impl.ProjectImpl.init(ProjectImpl.java:264)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:285)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.loadProject(ProjectManagerImpl.java:314)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.loadProject(ProjectManagerImpl.java:306)
    at com.intellij.projectImport.ProjectOpenProcessorBase.doOpenProject(ProjectOpenProcessorBase.java:197)
    at com.intellij.ide.impl.ProjectUtil.openOrImport(ProjectUtil.java:137)
    at com.intellij.ide.actions.OpenFileAction.doOpenFile(OpenFileAction.java:111)
    at com.intellij.ide.actions.OpenFileAction.lambda$prepareFileChooserAndOpen$1(OpenFileAction.java:66)
    at com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl.choose(FileChooserDialogImpl.java:145)
    at com.intellij.openapi.fileChooser.FileChooser.chooseFiles(FileChooser.java:114)
    at com.intellij.openapi.fileChooser.FileChooser.chooseFiles(FileChooser.java:91)
    at com.intellij.ide.actions.OpenFileAction.prepareFileChooserAndOpen(OpenFileAction.java:58)
    at com.intellij.ide.actions.OpenFileAction.lambda$actionPerformed$0(OpenFileAction.java:44)
    at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:315)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:435)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:419)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:403)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:719)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:668)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:363)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: com.intellij.diagnostic.PluginException: Could not initialize class java.awt.dnd.DragSource [Plugin: com.intellij.uiDesigner]
    ... 39 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class java.awt.dnd.DragSource
    at com.intellij.ide.palette.impl.PaletteWindow.<init>(PaletteWindow.java:75)
    at com.intellij.ide.palette.impl.PaletteToolWindowManager.<init>(PaletteToolWindowManager.java:43)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.picocontainer.defaults.InstantiatingComponentAdapter.newInstance(InstantiatingComponentAdapter.java:193)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.doGetComponentInstance(CachingConstructorInjectionComponentAdapter.java:85)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.instantiateGuarded(CachingConstructorInjectionComponentAdapter.java:62)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.getComponentInstance(CachingConstructorInjectionComponentAdapter.java:45)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:462)
    ... 36 more
2019-03-07 14:58:39,041 [ 279143]   WARN - roject.impl.ProjectManagerImpl - Fatal error initializing plugin com.intellij.uiDesigner
com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.intellij.uiDesigner
    at com.intellij.ide.plugins.PluginManager.handleComponentError(PluginManager.java:253)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.handleInitComponentError(PlatformComponentManagerImpl.java:43)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:504)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:104)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:88)
    at com.intellij.openapi.project.impl.ProjectImpl.init(ProjectImpl.java:264)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:285)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.newProject(ProjectManagerImpl.java:196)
    at com.intellij.projectImport.ProjectOpenProcessorBase.doOpenProject(ProjectOpenProcessorBase.java:204)
    at com.intellij.ide.impl.ProjectUtil.openOrImport(ProjectUtil.java:137)
    at com.intellij.ide.actions.OpenFileAction.doOpenFile(OpenFileAction.java:111)
    at com.intellij.ide.actions.OpenFileAction.lambda$prepareFileChooserAndOpen$1(OpenFileAction.java:66)
    at com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl.choose(FileChooserDialogImpl.java:145)
    at com.intellij.openapi.fileChooser.FileChooser.chooseFiles(FileChooser.java:114)
    at com.intellij.openapi.fileChooser.FileChooser.chooseFiles(FileChooser.java:91)
    at com.intellij.ide.actions.OpenFileAction.prepareFileChooserAndOpen(OpenFileAction.java:58)
    at com.intellij.ide.actions.OpenFileAction.lambda$actionPerformed$0(OpenFileAction.java:44)
    at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:315)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:435)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:419)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:403)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:719)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:668)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:363)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: com.intellij.diagnostic.PluginException: Could not initialize class java.awt.dnd.DragSource [Plugin: com.intellij.uiDesigner]
    ... 38 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class java.awt.dnd.DragSource
    at com.intellij.ide.palette.impl.PaletteWindow.<init>(PaletteWindow.java:75)
    at com.intellij.ide.palette.impl.PaletteToolWindowManager.<init>(PaletteToolWindowManager.java:43)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.picocontainer.defaults.InstantiatingComponentAdapter.newInstance(InstantiatingComponentAdapter.java:193)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.doGetComponentInstance(CachingConstructorInjectionComponentAdapter.java:85)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.instantiateGuarded(CachingConstructorInjectionComponentAdapter.java:62)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.getComponentInstance(CachingConstructorInjectionComponentAdapter.java:45)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:462)
    ... 35 more
2019-03-07 14:59:20,708 [ 320810]   INFO - ution.rmi.RemoteProcessSupport - Terminating: 17961/Maven3ServerImpl9b795730
2019-03-07 14:59:20,721 [ 320823]   INFO -           #cursive.repl.server - Shutting down local REPL
</code>
Comment: caused by `java.lang.NoClassDefFoundError: Could not initialize class java.awt.dnd.DragSource`. Please try deleting the installation and re-installing from scratch - looks as if the installation is broken
Comment: Okay so it does open after I reinstall but I had quite a lot of settings which are all now gone. It is a lost couple of hours it would have been great if the in place update worked in the first place
Answer: IntelliJ IDEA reinstall will fix this problem.
You can reinstall without removing the IDE folders with the configuration, only the installation folder.
This way all your settings will be preserved. You can also use IDE Settings Sync plug-in to keep your settings in the JetBrains account and easily backup/sync them between the machines.
Another option is to use the Toolbox app for the seamless updates which also supports reverting to the previous version if something goes wrong.


What is "Allegro non molto"?

Question: Some parts of The Four Seasons are marked as having a tempo of "Allegro non molto" (Fast not very?), however, I do not see this tempo as being one of the standard ones. There is normally Allegro (Fast) and Molto Allegro (Very Fast). What is Allegro non molto?
Comment: Be aware that tempo descriptions historically do not refer to specific BPM. They changed over time and reflect the composer's best effort to express something that is not scientific, it's artistic. Only in modern scores for film and TV are metronome values sacred. Outside of that, and a few other situations, tempo is part of the interpretation.
Comment: It would be helpful if you could be more specific than "some parts", as well as indicating which edition you're using.
Comment: "Allegro (ma) non troppo" is an alternative and also a better Italian.
Comment: Guess I got Ninja'd, or perhaps Icarus'd, by @Wyck
Comment: Like in all music you are allowed a certain artistic license. No two renditions of a piece is going to sound exactly the same.
Comment: Nice fight club reference in your name btw.
Comment: Notice that allegro means joyful too.
Comment: Fast, but not so fast that your feathers come off.  ;)
Comment: "Move fast, but not so fast that your feathers fall off"
Comment: If you speak Italian as Vivaldi did, you're not applying a standard tempo marking, you're simply saying how fast and in what character you want it played, in your own language. Though certain Italian markings did become widespread in the 18th-19th centuries, plenty of composers bucked the trend. Benjamin Britten for example preferred English markings, so in *A Midsummer Night's Dream* he writes things like "gently flowing crotchets" (plus a metronome mark IIRC).
Answer: On one of my metronomes, allegro is marked as 120-168 bpm. On another, it's 150-178 bpm. No great help!
Back in the days when bpm wasn't the datum point, composers would use (vague) tempo names to give a sort of ball-park speed for their compositions. Partly because that's all there was, partly to afford performers some leeway. After all, most 'classical' (serious) pieces would (and do) fluctuate a fair bit even during the same sections.
So - allegro is 'quick'. But Vivaldi didn't want it too 'quick', as often quick pieces have the tendency to accelerate to 'even quicker' as they progress.
Thus - allegro (quick) non (not) molto (much, very) is what Vivaldi hoped would be moving along, without appearing to be in too much of a hurry. Still giving, actually, plenty of leeway, according to my metronomes...
Answer: It means what you wrote, "Fast, not very" meaning, "fast, but don't overdo it". Vivaldi is making clear that a fast tempo should be taken, but not, say, vivace.
A more common instruction would be "allegro non troppo" (fast, but not too fast).
Comment: Allegro ma non troppo is more accurate.
Answer: Allegro is quick or fast. Non means not and molto means much. Fast but not too much.
Comment: In most cases, "molto" is more idiomatically translated as "very."
Comment: Molto bene meaning very good.
Comment: And _molto allegro_ meaning "very fast."
Answer: Allegro literally means "cheerful" so you are supposed to play it as such, but in a moderate way ("non molto = not too much").
Comment: This provides the argument I was missing from other answers. The fact, that *Allegro* appears on metronomes neither implies, that speed is its main characteristic, nor that it was so at Vivaldi's time.

What is "Allegro non molto"?


Views performance issue

Question: I have a website with 4 views (and sometimes 5 views) on the homepage. The problem is that when I try to open the website, it takes minutes to load and the cpu goes crazy because of mysql processes.
Screenshot of cpu usage

Output of SHOW PROCESS LIST

I work on a dedicated server with 8GB of RAM, 1900Mhz Intel Hexa-Core Xeon and 4 × 300GB SAS (RAID 10)
I have been using drupal for years, and never encountered such an issue. Any ideas how to fix this?
Update Views query:
SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language, node.created AS node_created, users_node.picture AS users_node_picture, users_node.uid AS users_node_uid, users_node.name AS users_node_name, users_node.mail AS users_node_mail, taxonomy_term_data_node.tid AS taxonomy_term_data_node_tid, taxonomy_term_data_taxonomy_term_hierarchy.tid AS taxonomy_term_data_taxonomy_term_hierarchy_tid, 'node' AS field_data_field_news_photo_node_entity_type, 'node' AS field_data_field_op_section_term_node_entity_type, 'node' AS field_data_body_node_entity_type, 'user' AS field_data_field_user_realname_user_entity_type, 'user' AS field_data_field_user_organization_user_entity_type, 'user' AS field_data_field_profile_picture_user_entity_type
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid
LEFT JOIN (SELECT td.*, tn.nid AS nid
FROM
{taxonomy_term_data} td
LEFT JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
LEFT JOIN {taxonomy_index} tn ON tn.tid = td.tid
WHERE  (tv.machine_name IN  ('sections')) ) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_data_node__taxonomy_term_hierarchy ON taxonomy_term_data_node.tid = taxonomy_term_data_node__taxonomy_term_hierarchy.tid
LEFT JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_data_node__taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN {field_data_field_news_photo} field_data_field_news_photo ON node.nid = field_data_field_news_photo.entity_id AND (field_data_field_news_photo.entity_type = 'node' AND field_data_field_news_photo.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('news')) AND (field_data_field_news_photo.field_news_photo_fid IS NOT NULL ) AND (node.language IN  ('***CURRENT_LANGUAGE***')) ))
ORDER BY node_created DESC
LIMIT 12 OFFSET 0
EXPLAIN output.
Comment: if you manually run the sql's in phpMyAdmin or similar, what is the execution time?
Comment: can you post the views performance data as well? it's shown when you preview a view. also devel can print the query log so you can pin point which query is the worst.
Comment: I get the same results even if the homepage has one only view. I updated the question with the query from views preview. Also, i have about 9000 nodes.
Comment: Add explain to the front of the query and post that output
Comment: @mikeytown2; added a screenshot.
Comment: @Geoff; phpMyAdmin output: `Query took 0.0457 sec`. Devel query log: `43900.53 ms`
Comment: does it take a long time for the preview to render? or only the final page? Do you have any custom overrides for Views in play? have you tried changing themes, and disabling modules to see if there's a conflict anywhere?
Comment: query execution time in views preview `14799.12 ms`. Theme; i get the same response using bartik theme. Modules; any ideas which modules could cause this?
Answer: The process list is saying that Mysql is writing to tmp tables.  The issue is the way you configured mysql.  Check the my.cnf configuration, and make sure that the temporary tables are large enough.
Comment: In my.cnf, I have `tmp_table_size=1024M`. Should I increase that? Are there any other settings to set?
Comment: Try using phpmyadmin advisor, http://mysqltuner.com/ or https://tools.percona.com/wizard

Views performance issue


Solve equation $\lfloor\arcsin x\rfloor+\lfloor\arccos x\rfloor+\lfloor\arctan x\rfloor=\ln x$

Question:
Solve over reals: $$\lfloor\arcsin x\rfloor+\lfloor\arccos x\rfloor+\lfloor\arctan x\rfloor =\ln x$$

I believe it has no solution, but I don't know how to prove it.
Comment: @ryan Solving over $\mathbb{R}$ requires $x\in(0,1]$. In that interval, $\ln x\leq 0$. Consider the values of the inverse trig functions on the LHS.
Comment: This is a problem that can be solved by a short exhaustive search. Since the left side of the equation is an integer, $\ln x$ must be an integer, so
$$
x\in\{ \ldots, e^{-3}, e^{-2}, e^{-1}, e^0=1, e^1, e^2, e^3, \ldots \}.
$$

Notice that since $-1.57\approx-\pi/2 <\arctan x < +\pi/2\approx +1.57, $ and so $\lfloor\arctan x\rfloor \in \{ -2,-1,0,1 \}.$

And $\lfloor \arcsin x \rfloor, \lfloor \arccos x \rfloor \in \{ -2,-1,0,1 \}. \qquad$
Comment: How far have you gotten with it?
Comment: x is between 0 and 1 for all the functions to exist, but I don't know where to go from here.
Comment: Good.  I haven't done this, but the next step would be to look at the function values.  If $0<x\leq1$ then then right-hand side is $\leq0$.  What about the left-hand side?
Comment: Hint: Use the monotony of the inverse trigonometric functions to show that they are positive in the domain $(0, 1]$
Answer: Hints:
As @bjoyn93 points out, we need only solve over $(0,1]$. All three functions, $\arcsin x, \arccos x, \arctan x$ are continuous and increasing or decreasing, so we can use this to divide the interval into sub-intervals where the LHS takes particular values. The easiest case is $\arctan x$, which has a range of $(-\pi/2,\pi/2)$ and thus only passes near the three integers $-1,0,1$. In fact, over $(0,1]$, its floor is identically $0$.
When do $\arcsin x, \arccos x$ pass by integers? What constant value would the LHS take between each of these crossing-points?
Answer: Here's a picture over the interval $(0,1]$. I've marked the critical points of the floored inverse trigonometrical functions to better see how this functions behave.

Simply put, there are three cases:

$x \in (0, \cos 1]:$ Then $0+1+0=\ln x \Rightarrow x = e \notin (0, \cos 1]$.
$x \in (\cos 1, \sin 1):$ Then $0+0+0=\ln x\Rightarrow x = 1 \notin (\cos 1, \sin 1)$
$x \in [\sin 1, 1]:$ Then $1+0+0=\ln x\Rightarrow x = e \notin [\sin 1, 1]$.

In conclusion, no solution.


Solving $\ln|1+y|=\ln|x|-\ln|x+1|+c$ for $y$

Question:
How do I solve the following equation for $y$?
$$\ln|1+y|=\ln|x|-\ln|x+1|+c$$

I want to get rid of the absolute values in a mathematically correct way.
Sorry if the format of the equation is incorrect, I do not know how to fix it.
Comment: [Here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is how to use MathJax. You should clearly state your motivation for asking this question, so that we can better help you ([how to ask a good question](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)). Can you think of any ideas to remove the natural logarithms?
Comment: I could take e raised to the ln power on both sides.
Comment: Yes, and can you continue?
Comment: No, I can't continue from there.
Comment: Where are you stuck then? Please edit your question to show what you have tried so far.
Comment: I still have the absolute values after I take e raised to the ln power on both sides. I want to get rid of them.
Comment: There is no way to get rid of the absolute values unless you restrict the domain, such as $x > 0$. Why do you want to get rid of the absolute values?
Comment: I see! I checked the answer and it has no absolute values. I must have missed something then.
Answer: Rearrange to get
$$
|1+y|=\frac{|x|}{|x+1|}e^c.
$$
then if $y>-1$ you get
$$
y=-1+\frac{|x|}{|x+1|}e^c
$$
and if $y<-1$ you get
$$
y=-1-\frac{|x|}{|x+1|}e^c
$$
in which for both cases $x\neq 0,1$.
To get rid of $|x|$ you can use $|x|=\sqrt{x^2}$ or then you split the intervals of $x$ by
$$
\frac{|x|}{|x+1|}=\frac{x}{x+1}
$$
when $x>$ or $x<-1$ and
$$
\frac{|x|}{|x+1|}=-\frac{x}{x+1}
$$
when $-1<x<0$.
Comment: @MikaelHelin your solution is not correct. In $2\ln(1+y)$ you silently assume that $1+y>0,$ which is not necessarilly. Also, you first put away logarithmes to return back to them ... in an incorrect way. I am sorry but I am going to downvote your answer, so that the (+1) you have now does not mislead the readers.
Comment: @user376343 Thanks for politely commenting. You get an upvote.
Comment: It seems you are losing a (real) solution when squaring. Set $C=\frac{\lvert x\rvert}{\lvert x+1\rvert} e^c$, then $\lvert 1+y\rvert=C$ or $1+y=\pm C$ or $y=-1\pm C$
Comment: That big $C$ is a function of $x$.
Comment: I think you wrote your comment while I was fixing typos.
Comment: "square and take logarithm": taking the logarithm is useless here.
Answer: Exponentiate both sides to get
$$|1+y| = \frac{|x|}{|x+1|}e^c.$$
Since $c$ is an arbitrary constant, so is $e^c$, so rename it $A$,
but note that $A$ is positive because it's equal to $e^c$.  So we have
$$|1+y| = A\frac{|x|}{|x+1|}.$$
If you remove the absolute values, you get a $\pm:$
$$1+y = \pm A\frac{x}{x+1}.$$
One $\pm$ does the job for both sides.  Now here the magic:
But simply declaring that $A$ is no longer just positive, but
can take negative values, you don't need the $\pm$ anymore. We'd say that $A$ absorbs the $\pm.$
$$1+y =A\frac{x}{x+1}.$$
Subtract $1$ from both sides and you're done.
Comment: Thank you! This is exactly what I was looking for!


Gostaria de saber se é possível ter uma máscara de telefone em um text View

Question: Gostaria de saber  como fazer para ter uma máscara de telefone em um campo text View.
No meu caso tenho uma listView com contatos onde em cada linha dessa listView aparece o nome do contato e o telefone.
Gostaria que o telefone ficasse com a máscara (##)####-####.
Lembrando que no cadastro de cliente a máscara já funciona.
Desde já agradeço a quem, de qualquer forma, puder ajudar de forma clara e específica pois não tenho muita experiência. Muito Obrigado.
Meu código de Cadastro de cliente:
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.DialogInterface;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import br.gestaoBd.BancoDeDados.ClienteDao;
 import br.gestaoBd.Beans.Cliente;

 public class CadCliente extends Activity {

EditText edId, edNome, edEmail, edTelefone, edEndereco, edCpf, edRg;
ClienteDao cliDao;

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.cad_clientes);
    edId = (EditText) findViewById(R.id.cadEdId);
    edNome = (EditText) findViewById(R.id.cadEdNome);
    edEmail = (EditText) findViewById(R.id.cadEdEmail);
    edTelefone = (EditText) findViewById(R.id.cadEdTelefone);
    edTelefone.addTextChangedListener(Mask.insert("(##)####-####", edTelefone));
    edEndereco = (EditText) findViewById(R.id.cadEdEndereco);
    edCpf = (EditText) findViewById(R.id.cadEdCpf);
    edCpf.addTextChangedListener(Mask.insert("###.###.###-##", edCpf));
    edRg = (EditText) findViewById(R.id.cadEdRg);
    edRg.addTextChangedListener(Mask.insert("##.###.###-#", edRg));

    Cliente clienteRecebido = (Cliente) getIntent().getSerializableExtra("Cliente");
    if (clienteRecebido != null) {
        montaTela(clienteRecebido);
    } else {
        montaTela(new Cliente());
    }

    Button btnSalvar = (Button) findViewById(R.id.btSalvar);
    btnSalvar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Cliente cli = new Cliente();
            cli.setId(Integer.valueOf(edId.getText().toString()));
            cli.setNome(edNome.getText().toString());
            cli.setEmail(edEmail.getText().toString());
            cli.setTelefone(Mask.unmask(edTelefone.getText().toString()));
            cli.setEndereco(edEndereco.getText().toString());
            cli.setRg(Mask.unmask(edRg.getText().toString()));
            cli.setCpf(Mask.unmask(edCpf.getText().toString()));

            if (cli.getNome().equals("")) {
                edNome.setError("Preencha o nome");
                return;

            } else if (cli.getEmail().equals("")) {
                edEmail.setError("Preencha o Email");
                return;

            } else if (cli.getTelefone().equals("")) {
                edTelefone.setError("Preencha o telefone");
                return;

            } else if (cli.getEndereco().equals("")) {
                edEndereco.setError("Preencha o endereço");
                return;

            } else if (cli.getRg().equals("")) {
                edRg.setError("Preencha o RG");
                return;

            } else if (cli.getCpf().equals("")) {
                edCpf.setError("Preencha o CPF");
                return;
            }

            if (cli.getId() > 0) {
                getCliDao().alterar(cli);
                ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                        ToastManager.INFORMATION);
            } else {
                getCliDao().inserirCliente(cli);
                ToastManager.show(getBaseContext(), "Salvo com Sucesso",
                        ToastManager.INFORMATION);
            }
        }

    }
    );

    Button btnLimpar = (Button) findViewById(R.id.btLimpar);

    btnLimpar.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            montaTela(new Cliente());
        }
    }
    );

    Button btExcluir = (Button) findViewById(R.id.btExcluir);
    btExcluir.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            final Cliente cli = new Cliente();
            cli.setId(Integer.valueOf(edId.getText().toString()));
            cli.setNome(edNome.getText().toString());
            cli.setEmail(edEmail.getText().toString());
            cli.setTelefone(edTelefone.getText().toString());
            cli.setEndereco(edEndereco.getText().toString());
            cli.setRg(edRg.getText().toString());
            cli.setCpf(edCpf.getText().toString());
            AlertDialog.Builder builder = new AlertDialog.Builder(CadCliente.this);
            builder.setTitle("Deseja Excluir?");
            builder.setMessage("O Cliente será deletado!");

            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    getCliDao().excluir(cli);
                    montaTela(new Cliente());
                    ToastManager.show(getBaseContext(), "Cliente excluído",
                            ToastManager.INFORMATION);

                }

            });

            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    ToastManager.show(getBaseContext(), "Cancelado",
                            ToastManager.INFORMATION);
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        }
    });

}

private void montaTela(Cliente cliente) {
    edId.setText(String.valueOf(cliente.getId()));
    edNome.setText(cliente.getNome());
    edEmail.setText(cliente.getEmail());
    edTelefone.setText(cliente.getTelefone());
    edEndereco.setText(cliente.getEndereco());
    edCpf.setText(cliente.getCpf());
    edRg.setText(cliente.getRg());

}

public ClienteDao getCliDao() {
    if (cliDao == null) {
        cliDao = new ClienteDao();
    }
    return cliDao;
}

}

Meu Cliente Adapter:
 import android.content.Context;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.ImageView;
 import android.widget.TextView;
 import br.gestaoBd.Beans.Cliente;
 import br.gestaoBd.Mask;
 import br.gestaoBd.R;
 import java.util.List;

 public class ClienteAdapter extends BaseAdapter {

private Context context;
private List<Cliente> clientes;

public ClienteAdapter(Context context, List<Cliente> clientes) {
    this.context = context;
    this.clientes = clientes;
}

public int getCount() {
    return clientes.size();
}

public Object getItem(int position) {
    return clientes.get(position);
}

public long getItemId(int position) {
    return clientes.get(position).getId();
}

public View getView(int position, View convertView, ViewGroup parent) {
    Cliente cliente = clientes.get(position);

    LayoutInflater layout = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = layout.inflate(R.layout.linhacli, null);

    Log.i("AULA", "Montou:" + cliente.getNome());
    Log.e("ERRO", "Valor da variavel estava nullo!");

    ImageView imgImageView = (ImageView) view.findViewById(R.id.imageView1);
    imgImageView.setImageResource(R.drawable.sem_foto);

    TextView edNome = (TextView) view.findViewById(R.id.textView1);
    edNome.setText(cliente.getNome());

    TextView lblTelefone = (TextView) view.findViewById(R.id.textView2);
    lblTelefone.setText(cliente.getTelefone());

    return view;
}
}

Minha Lista de clientes;
 import static android.R.id.list;
 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ListView;
 import br.gestaoBd.BancoDeDados.ClienteDao;
 import br.gestaoBd.Beans.Cliente;
 import br.gestaoBd.listaadapters.ClienteAdapter;
 import java.util.ArrayList;
 import java.util.Collections;

 public class ListClientes extends Activity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

ListView lista;
ArrayList<Cliente> clientes;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_clientes);

    lista = (ListView) findViewById(R.id.listview);

    lista.setOnItemLongClickListener(this);
    lista.setOnItemClickListener(this);

    atualizar(null);
}

public void atualizar(View view) {
    ClienteDao cliDao = new ClienteDao();

    clientes = cliDao.getListagem();
    lista.setAdapter(new ClienteAdapter(getBaseContext(), clientes));

}

public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Intent cadClienteIntent = new Intent(this, CadCliente.class);
    cadClienteIntent.putExtra("Cliente", clientes.get(position));
    startActivity(cadClienteIntent);
    return true;
}

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent cadPedidoIntent = new Intent(this, CadPedido.class);
    cadPedidoIntent.putExtra("Cliente", clientes.get(position));
    startActivity(cadPedidoIntent);

}

}

Answer: Para isto, vamos fazer igual ao TextView.
Mas ao invés de passar em um changeListener, vamos passar a String pronta!
Na sua classe Mask,implemente o seguinte método:
  public static String addMask(final String textoAFormatar, final String mask){
        String formatado = "";
        int i = 0;
        // vamos iterar a mascara, para descobrir quais caracteres vamos adicionar e quando...
        for (char m : mask.toCharArray()) {
            if (m != '#') { // se não for um #, vamos colocar o caracter informado na máscara
                formatado += m;
                continue;
            }
            // Senão colocamos o valor que será formatado
            try {
                formatado += textoAFormatar.charAt(i);
            } catch (Exception e) {
                break;
            }
            i++;
        }
        return formatado;
    }

No seu cliente adapter:
  TextView lblTelefone = (TextView) view.findViewById(R.id.textView2);
   lblTelefone.setText(Mask.addMask(cliente.getTelefone(), "(##)####-####"));

Comment: Perfeito! @Thiago Luiz Domacoski . Muito Obrigado


suppress section numberings in nbconvert to latex?

Question: Is it possible with nbconvert --> latex --> PDF to suppress section numberings?
Essentially I would like to keep the simple font size distinctions that the markdown header syntax (#, ##, etc.), and ipynb section headings provide (nbconvert --to latex appears to treat these same), and still use these to define section headings, but without the numberings. Then I also have the option of adding my own numbers manually.
I can cope with losing some aspects of general latex document structuring and functionality. Ideally though I would like to keep that information, and just suppress the numberings in the PDF.
Cheers.
Comment: which IPython version do you use?
Comment: Possible duplicate of [How to remove heading numbers in Jupyter during pdf conversion?](https://stackoverflow.com/questions/35077571/how-to-remove-heading-numbers-in-jupyter-during-pdf-conversion)
Answer: You can simply use the stared version of the LaTeX heading tags (section*, subsection*).
To do so, you have to create a custom template (e.g. secnum.tplx) which could look like the following
for IPython 1.x:
((*- extends 'latex_article.tplx' -*))

((* block h1 -*))section*((* endblock h1 -*))
((* block h2 -*))subsection*((* endblock h2 -*))
((* block h3 -*))subsubsection*((* endblock h3 -*))
((* block h4 -*))paragraph*((* endblock h4 -*))
((* block h5 -*))subparagraph*((* endblock h5 -*))

for IPython 2.x:
((*- extends 'article.tplx' -*))

((* block h1 -*))\section*((* endblock h1 -*))
((* block h2 -*))\subsection*((* endblock h2 -*))
((* block h3 -*))\subsubsection*((* endblock h3 -*))
((* block h4 -*))\paragraph*((* endblock h4 -*))
((* block h5 -*))\subparagraph*((* endblock h5 -*))

for IPython 3.x:
As IPython 3.x removed the heading cell type these approaches are no longer applicable here.
((* extends 'article.tplx' *))

((* block commands *))
\setcounter{secnumdepth}{0} % Turns off numbering for sections
((( super() )))
((* endblock commands *))

Note that stared headings will not be present in the TOC.
To use these templates, call them during the conversion like
ipython nbconvert --to=latex --template=secnum.tplx file.ipynb


Sybase IQ Load Table using client file is failing

Question: I am using Sybase IQ 15 version database.
trying to load IQ table from delimited flat file
Load Table test (a,b)
using client file '/xyz/test.dat'
ESCAPES OFF
FORMAT BCP
DELIMITED BY '|';

is it failing with below error
Msg 21, Level 14, State 0:SQL Anywhere Error -1006140: I/O Error on file/xyz/test.dat - (hos_clientfileio.cxx 142)

set below option on IQ server level ,still getting same error
set option allow_read_client_file='on' ;
grant READCLIENTFILE to finsrv ;

data file is on unix client machine and File content as below

1|01
2|02

Can someone please help/advice?
Comment: NOTE: I'm assuming `/xyz/` is an attempt to mask your actual directory structure.] Have you verified that you've provided the correct (full) path to the file?  At the OS level command prompt, does `ls /xyz/test.dat` show your file or generate an error?
Comment: Yes, /xyx/ is masked value and ls command lists correct file without error
Answer: Its likely a userright permission settings issue.
Try to change all the directories of /xyz/test.dat to 755 (drwxr-xr-x):
shell command at client machine:
1 - sudo chmod 755 -R /xyz/
or
2 - find /xyz/ -type d -exec chmod 755 {} \;
See also here on SO for more detail on user-rights and here for official Ubuntu explanation.


Modules to set up audio podcast functionality

Question: I am looking for modules to set up audio podcast functionality which allows playing of uploaded audio files as well as take audio source as external links like iTunes links. Any recommendations?
Answer: Take a look at FileField Podcaster

Using Views2, this module delivers a way to podcast with nodes that
  have CCK FileFields included as RSS file enclosures. It provides a
  podcast-compatible (as determined by Apple) RSS feed, using node
  variables, getID3, filefield in cck, and filefield meta data to
  generate the RSS tags
Comment: thanks @Gokul, this module is on my list, I have a doubt if i handle external links out of the box. Will give a try.
Answer: Successfully Tested with combination of
remote_file_source

Remote File Source allows you to add a file from a remote server to a
  filefield without transferring it locally.

Jplayer

The jPlayer module provides a wrapper around the jPlayer JavaScript
  library. This library provides an HTML5-based player, that uses a
  Flash fallback for browsers that do not yet support it. This module
  provides a default presentation for the player, as well as integration
  with CCK file fields and a display style for Views. This makes it
  possible to easily convert the display of any file field into an audio
  player.


mysql result to array

Question: how is the fastest way to make a mysql result to an array?
static function result($sql){
    if(!$result = self::$link->query($sql)){
        echo 'SQL: '.$sql.'
'.self::$link->error;
    }

    return $result;
}

static function rows($sql, $mode='assoc'){
    $result = self::result($sql);

    $row_arr = array();
    if($mode == 'assoc'){
        while($row = $result->fetch_assoc()) $row_arr[] = $row;
    }
    elseif($mode == 'row'){
        while($row = $result->fetch_row()) $row_arr[] = $row;
    }
    $result->close();

    return $row_arr;
}

Comment: Don't know, have you had a look at the documentation? It seems there is  (http://www.php.net/manual/en/mysqli-result.fetch-all.php) if you have the native driver.
Comment: Faster than what you have? How fast is it? Is it slow? Have you done any profiling?
Comment: isn't there a method in mysqli which can do it?
Comment: downvoted as this seems to be a RTFM question
Answer: Use mysqli_result::fetch_all.
Comment: what does it mean that its available only with mysqlnd?
Comment: "As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing."
Answer: MySQLND means native driver.

The PHP script language features three different "extensions" to connect to the MySQL Server. The PHP term "extension" is comparable to the MySQL terms "Connector" and "Driver", please check the MySQL Reference Manual for details. The following extensions exist:

ext/mysql
ext/mysqli
PDO_MYSQL

All PHP MySQL extensions are part of the source code of PHP. The source code and binaries are available from http://php.net. Both the PHP manual and the MySQL Reference Manual contain a detailed documentation of which extension to use.

http://dev.mysql.com/downloads/connector/php-mysqlnd/
Comment: This should be a comment to my answer. Please delete it and add the comment to my answer or I'll flag this in 5 minutes.
Comment: I'm unable to comment though.
Answer: function returnMeArray(){
    $q = mysql_query("your query");
    $myarray = array();
    while ($arr = mysql_fetch_array($q)) {
        $myarray = $arr;
    }
    return $myarray;
}

Comment: `$myarray = $arr` should be `$myarray[] = $arr` else the $myarray will be overridden and I guess this does the same as what clarkk showed in his example
Comment: Don't think so. It is wrong, have you tested it? It'll return just the latter row...

mysql result to array