text:
Q: Button stays in the last div when a div is removed I'm trying to fix my jQuery code. I want 'add content' button in the last div only. If a div is removed, the button stays in the last div. Suggestions please.
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
    $(document).on('click', '.addcontent', function () {
        if (i == 1) $(".question").html('');
        $(".hide_button").remove();
        $(".question").append('

Remove
Question ' + i + '
 This is div text
 <button class="addcontent hide_button' + i + '">Add content</button>
').show('slow');
        createdDivs++;
        i++;
    });
    $(document).on('click', '.deleteButton', function () {
        var id = $(this).attr("id");
        $("#" + id).remove();
        deletedDivs++;
        if (createdDivs == deletedDivs) {
            i = 1;
            $(".question").append('<button class="addcontent hide_button">Add content</button>').show('slow');
        }
    });
});

HTML:

    <button class="addcontent hide_button">Add content</button>

A: Try this:
Move your button out of your div:
HTML:

<button class="addcontent hide_button">Add content</button>

JS:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
    $(document).on('click', '.addcontent', function () {
        if (i == 1) $(".question").html('');
        $(".question").append('

Remove
Question ' + i + '
 This is div text

').show('slow');
        createdDivs++;
        i++;
    });
    $(document).on('click', '.deleteButton', function () {
        var id = $(this).attr("id");
        $("#" + id).remove();
        deletedDivs++;
        if (createdDivs == deletedDivs) {
            i = 1;
        }
    });
});

JSFIDDLE: http://jsfiddle.net/ghorg12110/a7L3cn1a/1/

A: Here is the updated/working code.
HTML:

    <button class="addcontent">Add content</button>

JavaScript:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
    $(document).on('click', '.addcontent', function () {
        if (i == 1) {
           $(".question").html('');
        }
        $(".question").append('

Remove
Question ' + i + '
 This is div text

').show('slow');
        createdDivs++;
        i++;
    });
    $(document).on('click', '.deleteButton', function () {
        var id = $(this).attr("id");
        $("#" + id).remove();
        deletedDivs++;
        if (createdDivs == deletedDivs) {
            i = 1;
        }
    });
});

A: A little hard to see what you have in mind, but I would have the button in all the divs and use CSS to show or hide the button.
div button { display: none; }

div:last-of-type button { display: inline; }

A: It's more efficient if you use CSS to overlap that property at the end and you will conserve the same element with the necessity of adding and removing it
html:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

  <button class="addcontent hide_button">Add content</button>

css:
.new-question {
  background-color: green;
  width: 300px;
  height: auto;
  position: relative;
  margin:0;
}
.deleteButton {
  background-color: red;
  width: 50px;
  height: 50px;
  margin-left: 100%;
  position: relative;
}
.addcontent{
  z-index: 1;
  top:-25px;
  left:200px;
  position:relative;
}
.content{
  min-height:30px;
}

js:
$(function (){
var i = 1,
    contentQuestion = $('

'),
    remove = $('
Remove
').appendTo(contentQuestion),
    content = $('#content');
$('.addcontent').on('click', function () {
  content.append(contentQuestion.clone().append('Question ' + i + '
 This is div text'));
  i += 1;
});
content.on('click', '.deleteButton', function () {
  $(this.parentNode).remove();
});
});

jsbin:
http://jsbin.com/gequveroba/1/edit?html,css,js,output


text:
Q: PL/SQL Cursor whose query is based on a variable I've got a PL/SQL block that's basically
DECLARE
    PIDM            NUMBER(8);
    CLM_TEST_SCORE  NUMBER(5);
    CURSOR C_STUDENT IS
        select PIDM
        from   SOSC.DW_ALL_COLLECTOR
        order by PIDM;

    CURSOR C_CLM_SCORES IS
        select max(to_number(SORTEST_TEST_SCORE))
        from   SATURN.SORTEST
        where  SORTEST_PIDM   = pidm;
BEGIN
    OPEN C_STUDENT;
    LOOP
        CLM_TEST_SCORE := '';

        FETCH c_Student INTO pidm;
        EXIT WHEN c_Student%notfound;

        OPEN C_CLM_SCORES;
        FETCH C_CLM_SCORES INTO CLM_TEST_SCORE;
        CLOSE C_CLM_SCORES;

        insert into some_table (CLM_TEST_SCORE)
        values (CLM_TEST_SCORE);

    END LOOP
END

As far as I'm aware, the pidm referred to in C_CLM_SCORES is the PIDM NUMBER(8) declared in line 2. That would mean that the query the cursor refers to mutates every iteration of the LOOP, depending on the current value of pidm. That doesn't jive with my understanding of cursors as a query-in-progress, as the underlying query changes every LOOP. Maybe it's the original author taking advantage of a clever DB algorithm?
This code works. I just have absolutely no idea why. What the heck is going on here?

A: You have an overly confusing block of code that is a nightmare to debug as you have:

*

*SQL statements that refer to column name and local variables with the same identifier (PIDM and CLM_TEST_SCORE).

*Cursors that change every iteration because they contain a bind variable referring to local variables (PIDM).

*Highly inefficient use of loops.

If you want to make it clearer, you can rewrite the PL/SQL block so that you do not have duplicate identifiers and use a parameterised cursor:
DECLARE
  v_PIDM            SOSC.DW_ALL_COLLECTOR.PIDM%TYPE;
  v_CLM_TEST_SCORE  some_table.CLM_TEST_SCORE%TYPE;

  CURSOR C_STUDENT IS
    select PIDM
    from   SOSC.DW_ALL_COLLECTOR
    order by PIDM;

  CURSOR C_CLM_SCORES(p_pidm NUMBER) IS
    select max(to_number(SORTEST_TEST_SCORE))
    from   SATURN.SORTEST
    where  SORTEST_PIDM = p_pidm;
BEGIN
  OPEN C_STUDENT;
  LOOP
    FETCH c_Student INTO v_pidm;
    EXIT WHEN c_Student%notfound;

    OPEN C_CLM_SCORES(v_pidm);
    FETCH C_CLM_SCORES INTO v_CLM_TEST_SCORE;
    CLOSE C_CLM_SCORES;

    insert into some_table (CLM_TEST_SCORE)
    values (v_CLM_TEST_SCORE);
  END LOOP;
END;
/

However, that is still very inefficient as each iteration performs a SELECT and an INSERT and will generate log entries. You can make it much simpler and more efficient to rewrite the whole thing as a single SQL statement:
INSERT INTO some_table (clm_test_score)
SELECT ( select max(to_number(SORTEST_TEST_SCORE))
         from   SATURN.SORTEST s
         where  s.SORTEST_PIDM = c.pidm )
FROM   SOSC.DW_ALL_COLLECTOR c;

db<>fiddle here

A: The code in the question is an advertisement for "Why should implicit cursors be used?". If you rewrite your code as below it becomes much easier to understand:
BEGIN
  FOR rowStudent IN (select PIDM
                       from SOSC.DW_ALL_COLLECTOR
                       order by PIDM)
  LOOP
    FOR rowScores IN (select max(to_number(SORTEST_TEST_SCORE)) AS CLM_TEST_SCORE
                        from SATURN.SORTEST
                        where SORTEST_PIDM = rowStudent.PIDM)
    LOOP
      insert into some_table (CLM_TEST_SCORE)
        values (rowScores.CLM_TEST_SCORE);
    END LOOP;  -- rowScores
  END LOOP;  -- rowStudent
END;

This eliminates all of the variables and cursor definitions, and all the code is right in front of you where you can see it at a glance.
If you wanted to tighten it up a bit further you could use a join to get down to just one cursor:
BEGIN
  FOR rowStudent_scores IN (SELECT d.PIDM, MAX(TO_NUMBER(s.SORTEST_TEST_SCORE)) AS CLM_TEST_SCORE
                              FROM SOSC.DW_ALL_COLLECTOR d
                              INNER JOIN SATURN.SORTEST s
                                ON s.SORTEST_PIDM = d.PIDM
                              GROUP BY d.PIDM)
  LOOP
    insert into some_table (CLM_TEST_SCORE)
      values (rowStudent_scores.CLM_TEST_SCORE);
  END LOOP;  -- rowStudent_scores
END;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use templates to normalize number in range from 0 to 1? I'm designing a class which is RGB color representation.
It has three properties: red, green and blue.
Until now, I had those 3 properties in type unsigned char int (from 0 to 255). I'd like to use C++ templates, so I could also use other types, like float, double or int.
However, I need to know the maximum value, which probably could be solved with std::numeric_limits. The problem are floating point numbers. They should be in range 0..1. Do you have any ideas how to hack this problem?
My goal is to be able convert red, green and blue from not known type into number 0..1.

A: template<class T>
RGBClass {
public:
    RGBClass():
        max_value(std::numberic_limits<T>::max())
        /* ... */
    {}
    /* ... */
    const T max_value;

private:
    T R_;
    T G_;
    T B_;
};

template<>
RGBClass<float> {
public:
    RGBClass():
        max_value(1),
        /* ... */
    {}

    // convert other type to float 0..1
    template<class OTHER_TYPE>
    RGBClass(const OTHER_TYPE& other):
        max_value(1),
        R_((float)other.R_ / (float)other.max_value),
        /* ... */
    {}
    const float max_value;

private:
    float R_;
    float G_;
    float B_;
}

A: template<typename T, typename=void>
struct pixel_component_range {
  static constexpr T max() { return std::numberic_limits<T>::max(); }
};
template<typename F>
struct pixel_component_range<F, typename std::enable_if<std::is_floating_point<F>::value>::type>
{
  static constexpr T max() { return 1.f; }
};

now pixel_component_range<T>::max() evaluates to the max value of integers, and 1. for floating point values.


text:
Q: In the book "Charlotte's Web," or In the book "Charlotte's Web",? When stating a book title, is the comma before or after the quotations?

A: The best possible answer is: whatever your teacher thinks is correct.  I'm not kidding. Sometimes teachers just get it wrong, and it's often best to just keep your mouth shut and go along with what the teacher thinks.  The normal rules about quotation marks are also slightly different in Britain and America.
With that out of the way, here's the answer. If you follow the rules of British English, put the comma outside the quotes:

In the book "Charlotte's Web", Charlotte is a spider who wants to....

because that matches the structure of the sentence.  If you follow the rules of American English, put the comma inside the quotes:

In the book "Charlotte's Web," Charlotte is a spider who wants to....

because that looks prettier.
In British English, the rule about putting a comma inside the quotes is only for when you are quoting what somebody said:

"Look at Charlotte's web," said Wilbur.

If you are using a word processor, it's probably better to use an italic font to mark the title, like this:

In the book Charlotte's Web, Charlotte is a spider who wants to....

but, again, this depends on your teacher's attitude.


text:
Q: multipart/form-data request failing in react-native I get the following error when I set the 'Content-Type' as 'multipart/form-data' in react-native.
Below is my code -
const formData = new FormData();
formData.append('org_id', org_id);
formData.append('ans', userAns);
formData.append('remark', userRemark);
formData.append('img', userImg);
files.forEach(file => {
  formData.append('files', {
    name: file.fileName,
    type: file.type,
    uri: file.uri,
  });
});
const resp = await multiPartInstance({
  method: 'PUT',
  url: `${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
  data: formData,
});
return Promise.resolve(true);

I am using axios for calling apis. multiPartInstance is an axios instance -
const multiPartAccessToken = async (config: AxiosRequestConfig) => {
  config.headers = {
    Accept: 'application/json',
    access_token: useTokenStore.getState().accessToken,
    'Content-Type': 'multipart/form-data;',
  };
  config.timeout = 30000;
  return config;
};

I've tried the above with fetch also but I keep getting the same error. The strangest part is that this request hits the server, server sends a response too but I get this error react-native side. I've noticed if I don't use FormData I don't get any error. But I need to use FormData as I have to upload image files.
Environment Details -

*

*Windows version 21H2 (OS Build 22000.376)

*react-native 0.66.3

*react 17.0.2

*axios ^0.24.0

*react-native-image-picker ^4.3.0 (used for selecting images)

*Flipper version 0.99.0

I've tried the solutions posted on below forums but they didn't work for me.

*

*request formData to API, gets "Network Error" in axios while uploading image

*https://github.com/facebook/react-native/issues/24039

*https://github.com/facebook/react-native/issues/28551

A: I am as follow and works perfectly:
    const oFormData = new FormData();
    images.map((val, index) => {
        oFormData.append("image", {
            uri: val.uri,
            type: val.type,
            name: val.fileName
        });
    });
    return axios.post(postServiceUrl, oFormData);

A: Somehow react-native-blob-util doesn't give this error. I modified my code as below -
import ReactNativeBlobUtil from 'react-native-blob-util';

const fileData = files.map(file => {
  return {
    name: 'files',
    data: String(file.base64),
    filename: file.fileName,
  };
});
try {
  const resp = await ReactNativeBlobUtil.fetch(
    'PUT',
    `${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
    {
      access_token: useTokenStore.getState().accessToken,
      'Content-Type': 'multipart/form-data',
    },
    [
      ...fileData,
      // elements without property `filename` will be sent as plain text
      {name: 'org_id', data: String(org_id)},
      {name: 'ans', data: String(userAns)},
      {name: 'remark', data: String(userRemark)},
      {name: 'img', data: String(userImg)},
    ],
  );


text:
Q: How to split one table into two in a single statement? I've got an old table I want to split into two, but I'd rather not run two near-identical queries across the whole thing. The following does not work because you can only return column from the table you're inserting into:
WITH comment_insert AS (
    INSERT INTO comments (content)
        SELECT content
          FROM old_schema.comments
          JOIN area ON area.id = old_schema.comments.area_id
        RETURNING id, area.id AS area_id
)
INSERT INTO area_comment (parent_id, area_id)
SELECT comment_insert.id,
       comment_insert.area_id
  FROM transitional_schema.mon_area_comment

Is it possible to do something like this, putting some columns in the "parent" table and the parent ID plus some other columns into another table, using a single query?

A: Modelling scheme:

CREATE TABLE old_table (id INT, val1 INT, val2 INT);
INSERT INTO old_table VALUES (11,111,1111), (22,222,2222);

CREATE TABLE new_table1 (id INT GENERATED ALWAYS AS IDENTITY, val1 INT);
CREATE TABLE new_table2 (id_table1 INT, val2 INT);

WITH cte AS
(
INSERT INTO new_table1 (val1)
SELECT val1
FROM old_table
RETURNING id, val1
)
INSERT INTO new_table2 (id_table1, val2)
SELECT cte.id, old_table.val2
-- use both old table
FROM old_table
-- and CTE table
JOIN cte
    ON old_table.val1 = cte.val1; -- the relation is set
                                  -- by the value saved into new table
                                  -- not by old primary index

SELECT * FROM new_table1;
SELECT * FROM new_table2;

id | val1
-: | ---:
 1 |  111
 2 |  222

id_table1 | val2
--------: | ---:
        1 | 1111
        2 | 2222

db<>fiddle here
Pay attention - in last INSERT both CTE and source table are used.


text:
Q: VMWare Tools fails on CentOS 6.7 minimal with "initctl: Job failed to start" I am posting this here because I struggled with this and ultimately found the solution elegantly saved in another website which is no longer up (wayback machine: https://web.archive.org/web/20141017041537/http://www.utterlyforked.com/vmware-fusion-5-and-cent-6-4/)
I am using VMware Fusion 7.1.2 and I installed a CentOS 6.7 minimum build from an ISO, and then proceeded to Install VMWare Tools by clicking the Virtual Machine dropdown and selecting "Install VMWare Tools". Some installation guides suggest that a wizard will walk you through this but that's not the case, as the CD is not mounted automatically, so you have to go through mounting the drive and running the perl install script from the console or terminal prompt. The VMWare Help on this is very clear, for what it's worth:
mkdir /mnt/cdrom
mount /dev/cdrom /mnt/cdrom
cd /tmp
tar zxpf /mnt/cdrom/VMwareTools-x.x.x-yyyy.tar.gz
umount /dev/cdrom

Perl needs to be installed, so:
yum install perl

Then, run the VMWare Installer:
cd vmware-tools-distrib
./vmware-install.pl

After powering through the defaults, I get:
...
Do you want to enable Guest Authentication (vgauth)? [yes]

No X install found.

Creating a new initrd boot image for the kernel.
vmware-tools-thinprint start/running
initctl: Job failed to start
Unable to start services for VMware Tools

Execution aborted.

Users have gotten past the initctl: Job failed to start message in a variety of ways, but in this specific case, the answer is very clear.
I'll post @ukandrewtaylor's answer below, copied shamelessly from the Internet Wayback Machine. If you're that Andrew from Utterly Forked, please claim your answer :-)

A: From https://web.archive.org/web/20141017041537/http://www.utterlyforked.com/vmware-fusion-5-and-cent-6-4/
Just a really quick drive-by posting. I'm currently working the new Vagrant VMware provider. I thought I'd build a quick Cent6.4 basebox (more to come on this later) and I ran in to what I believe are a few quirks with VMware tools.
Please get in touch if I'm misunderstanding what's going on here, but, I think that the latest version of VMware tools has some incompatibilities with an out-of-the box Cent build (perhaps just the minimal install which I always use).
Firstly:
When installing VMware-tools the first time around I was getting errors with
initctl: Job failed to start
Unable to start services for VMware Tools

There's a few internet fingers pointed at the ThinPrint setup; I'm not using printing at all but I'm going to speculate that an install of CUPS and a few other things will fix this. I thought I'd just disable it but this is where if you're new to CentOS 6.0 you'll be confused and the internet won't really help you.
As of 6.0 CentOS ships with upstart. You can google upstart vs sysvinit but for the purposes of fixing VMware tools, just remove /etc/init/vmware-tools-thinprint.conf:
rm /etc/init/vmware-tools-thinprint.conf

You should then be able to run:
/etc/vmware-tools/services.sh start

to start everything you'll need and it should automatically via upstart next time you reboot. You'll not see anything in chkconfig as the VMware tools daemon isn't LSB compliant. You'll know if everything is running as it should because you'll get an output when you start vmware tools
Starting VMware Tools services in the virtual machine:
Switching to guest configuration: [ OK ]
VM communication interface: [ OK ]
VM communication interface socket family: [ OK ]
Guest filesystem driver: [ OK ]
Mounting HGFS shares: [ OK ]
Blocking file system: [ OK ]
Guest operating system daemon: [ OK ]

and you'll see the running process
1959 ? Ssl 0:00 /usr/sbin/vmware-vmblock-fuse -o subtype=vmware-vmblock,default_permissions,allow_other /var/run/vmblock-fuse
1981 ? S 0:00 /usr/sbin/vmtoolsd

Secondly:
Blocking file system: [FAILED]

If you're getting this when running /etc/vmware-tools/services.sh start it's down to VMware now relying on the FUSE project libs which aren't necessarily installed. Fix with
yum install fuse-libs

Hope this helps somebody.
Andrew

A: I managed to install VMware Tools successfully (no errors) in CentOS 6.7 minimal (and no GUI) on VMware Workstation 12 this way:

*

*login as root
sudo su

*update system
sudo yum update

*Install gcc, perl, fuse-libs (credit to @aaryno), nmap (not necessary but useful for checking if ssh port is open) and reboot
sudo yum install gcc
sudo yum install perl
sudo yum install nmap
sudo yum install fuse-libs
shutdown -r now

*follow instructions in the official vmware KB
http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1018414
Skip steps 11 and 12. For step 14 instead of 'end vmware install' go to removable devices > cd > disconnect.

*reboot again

*to check if the service is running properly enter:
/etc/vmware-tools/services.sh status

Specifications
VMwareTools-10.0.1-3160059
VMware® Workstation 12 Pro - 12.0.1 build-3160714
CentOS Release 6.7 (Final) - Kernel 2.6.32-573.8.1.el6.i686 on an i686


text:
Q: How can I animate a submit button to cover the field and display a "Success" message? I'm a designer working along side a developer and I'm trying to help him recreate one of the design elements I created. On our website, we have a section to subscribe to our newsletter. The way I have this envisioned is so that after the user enters their email and clicks submit, the submit button will expand to cover the field and will display a "Success!" message.
How can I go about making this happen? Thanks in advance!

A: I hope this solves.
JsFiddle.
$("#btn").click(function(){
    $(this).val("Success!")
    $(this).animate({
        marginLeft: '-180px',
        width:"220px"
    });
});

<input type="email" id="field"><input style="width:auto;" type="button" value="Subscribe" id="btn">

A: I guess you'd like to see something like this:

$("#btn").click(function(){
    $(this).val("Success!")
    $(this).animate({
        marginLeft: '-110px',
        width:"140px"
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="width:100px" id="field"><input style="width:30px;font-size:25px;" type="button" value="ok" id="btn">

A: Demo
This should give a you a start:
$(".formFill button").click(function(){
    var $this=$(this);
    var width=$this.outerWidth();
    var inputWidth=$this.siblings("input").outerWidth();

    $this.attr("disabled",true);
    $this.text("Subscribing...");

    $this.animate({
        width:width+inputWidth,
        "margin-left":-inputWidth-4
    });

    //Imitate an ajax post with setTimeout
    setTimeout(function(){
        //succeed
        $this.text("Success!");

        setTimeout(function(){
            //return to normal
            $this.attr("style","");
            $this.removeAttr("disabled");
            $this.text("Subscribe");
        },2000);
    },3000);

});


text:
Q: 13.04 no context menu after rabbitvcs install I was using rabbit in 12.04 LTS and then upgraded to 13.04 while rabbit menu was gone. So I went to the install page and followed the instructions:

*

*sudo add-apt-repository ppa:rabbitvcs/ppa

*sudo apt-get update

*sudo apt-get install rabbitvcs-nautilus3

*restart computer, no context menu. So I continued:

*sudo apt-get install rabbitvcs-gedit

*sudo apt-get install rabbitvcs-cli

*

*Log out

*log in

*open nautilus,

*right click on random folder

but still no "Rabbit VCS" in the context menu. I am certainly doing something incorrectly. But cannot figure out what...
EDIT
Nautilus version is 3.6.3 and it si basically the default which comes with Ubuntu 13.04 - in Ubuntu it is called as "Files"
Contents of .config/rabbitvcs/RabbitVCS.log :
2013-06-18 10:02:45,462 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,047 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/sv2013-06-18 10:02:45,462 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,047 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,047 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,437 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,437 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
n/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,047 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/XmlChanger' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,437 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
2013-06-19 09:56:19,437 ERROR   rabbitvcs.vcs.svn       The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.
Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/rabbitvcs/vcs/svn/__init__.py", line 254, in statuses
    update=update)
ClientError: The path '/home/janipav/workspace/MassFileSender' appears to be part of a Subversion 1.7 or greater
working copy.  Please upgrade your Subversion client to use this
working copy.

Contents of /usr/share/rabbitvcs/configspec.ini
[general]
language = string(default="English")
enable_attributes = boolean(default=True)
enable_emblems = boolean(default=True)
enable_recursive = boolean(default=True)
show_debug = boolean(default=False)
show_unversioned_files = boolean(default=True)

[external]
diff_tool = string(default="/usr/bin/meld")
diff_tool_swap = boolean(default=False)

[cache]
number_repositories = integer(default=30)
number_messages = integer(default=30)

[logging]
type = option("None", "File", "Console", "Both", default="Both")
level = option("Debug", "Warning", "Info", "Error", "Critical", default="Error")

A: You can fix the missing context menu. I suggest removing the installed PPA version and the ppa (How do I remove a PPA added via command-line?), reinstall the version from Ubuntu and follow the instructions I derived from the bug reported: https://bugs.launchpad.net/ubuntu/+source/rabbitvcs/+bug/1093533.
You need to download the following file http://rabbitvcs.googlecode.com/svn/trunk/clients/nautilus-3.0/RabbitVCS.py
Copy it (using root/su/sudo) to:
/usr/share/nautilus-python/extensions/RabbitVCS.py
You may also need to create the following symlink:
sudo ln -s /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0

You will need to restart your session (log out and back in again) to see the changes.

A: So, it seems like you have .svn files belonging to your older version of rabbitvcs(probably 1.6). These need to be upgraded to 1.7, which is the version you have installed. To do this, execute the following on a terminal:
svn upgrade

You need to reboot for this to complete. To reboot: sudo reboot


text:
Q: Proof by Induction on a recursive function its been a while since I have done proofs and am struggling on a question:
Let $T(n)$ be defined recursively as follows: $T(1)=c$ and $T(n)=3T(n/3)+c, \forall n\geqslant 3$, where $c$ is some arbitrary positive constant and $n=3^k$ for some non-negative integer $k$. Prove by induction on $k$ that $T(n)=(3c)/(2) n - c/2$.
So far I have been able to break it down to the following:

*

*Base Case = $T(1) = c$

*Recursive Case = $T(n)=3T(n/3)+c$

*Since $n=3^k$ this makes the recursive case: $T(3^k) = 3T(3^{k-1})+c$
Beyond that I am struggling at where to start. I know I need to prove it for the lowest possible value i.i. $k=1$, which I think gives me:
$T(3)=3T(3/3)+c$
$= 3T(1)+c = 4c$
I don't think this is right though and don't really know why.
Any help is appreciated.

A: You are virtually there. The induction is really an induction on $k$ starting at $0$, to prove $T(n) = (3c/2)\cdot n - c/2$ where $n = 3^k$:
For the base case:
$$T(3^0) = T(1) = c = (3c/2)\cdot 3^0 - c/2$$
For the inductive step, the inductive hypothesis is:
$$T(3^k) = (3c/2)\cdot  3^k - c/2$$
and using this and the recursive definition, you get:
$$T(3^{k+1}) = 3T(3^k) + c =  3\left[(3c/2)\cdot  3^k - c/2\right] + c= (3c/2)\cdot 3^{k+1} - c/2$$
which completes the inductive proof


text:
Q: Get fully qualified name of a Python class (Python 3.3+) How can I get name of class including full path from its module root? For Python 3.3 and up?
Here is example of Python code:
class A:
    class B:
        class C:
            def me(self):
                print(self.__module__)
                print(type(self).__name__)
                print(repr(self))

x = A.B.C()
x.me()

This code outputs me on Python 3.3:
__main__
C
<__main__.A.B.C object at 0x0000000002A47278>

So, Python internally knows that my object is __main__.A.B.C, but how can I get this programmatically? I can parse repr(self), but it sounds like a hack for me.

A: You are looking for __qualname__ (introduced in Python 3.3):
class A:
    class B:
        class C:
            def me(self):
                print(self.__module__)
                print(type(self).__name__)
                print(type(self).__qualname__)
                print(repr(self))


text:
Q: How to execute emacs grep-find link in the same window? When I use grep-find it opens another window (area in the frame) with a list of results that I can select. When I select one it opens the target file in a different window than grep-find is in.
How can I get the target file to open in the same window as the grep results (replacing the grep results window with what I am actually looking for).
How can I keep grep-find from opening a separate window (have it so it opens in the current window). My goal is I look for something, I find it, I go to it, all within the same window. I would like to add this to my .emacs file.

A: It doesn't look like there is any way to configure the compile package to do what you're asking.  And there's no easy way to use advice to tweak the behavior.  I think you have to resort to editing the function which actually jumps to the error, which you can do with the following addition to your .emacs (tested in Emacs 23.1):
(eval-after-load "compile"
'(defun compilation-goto-locus (msg mk end-mk)
  "Jump to an error corresponding to MSG at MK.
All arguments are markers.  If END-MK is non-nil, mark is set there
and overlay is highlighted between MK and END-MK."
  ;; Show compilation buffer in other window, scrolled to this error.
  (let* ((from-compilation-buffer (eq (window-buffer (selected-window))
                  (marker-buffer msg)))
     ;; Use an existing window if it is in a visible frame.
     (pre-existing (get-buffer-window (marker-buffer msg) 0))
     (w (if (and from-compilation-buffer pre-existing)
        ;; Calling display-buffer here may end up (partly) hiding
        ;; the error location if the two buffers are in two
        ;; different frames.  So don't do it if it's not necessary.
        pre-existing
      (let ((display-buffer-reuse-frames t)
        (pop-up-windows t))
        ;; Pop up a window.
        (display-buffer (marker-buffer msg)))))
     (highlight-regexp (with-current-buffer (marker-buffer msg)
             ;; also do this while we change buffer
             (compilation-set-window w msg)
             compilation-highlight-regexp)))
;; Ideally, the window-size should be passed to `display-buffer' (via
;; something like special-display-buffer) so it's only used when
;; creating a new window.
(unless pre-existing (compilation-set-window-height w))

(switch-to-buffer (marker-buffer mk))

    ;; was
;; (if from-compilation-buffer
;;     ;; If the compilation buffer window was selected,
;;     ;; keep the compilation buffer in this window;
;;     ;; display the source in another window.
;;     (let ((pop-up-windows t))
;;       (pop-to-buffer (marker-buffer mk) 'other-window))
;;   (if (window-dedicated-p (selected-window))
;;       (pop-to-buffer (marker-buffer mk))
;;     (switch-to-buffer (marker-buffer mk))))
;; If narrowing gets in the way of going to the right place, widen.
(unless (eq (goto-char mk) (point))
  (widen)
  (goto-char mk))
(if end-mk
    (push-mark end-mk t)
  (if mark-active (setq mark-active)))
;; If hideshow got in the way of
;; seeing the right place, open permanently.
(dolist (ov (overlays-at (point)))
  (when (eq 'hs (overlay-get ov 'invisible))
    (delete-overlay ov)
    (goto-char mk)))

(when highlight-regexp
  (if (timerp next-error-highlight-timer)
      (cancel-timer next-error-highlight-timer))
  (unless compilation-highlight-overlay
    (setq compilation-highlight-overlay
      (make-overlay (point-min) (point-min)))
    (overlay-put compilation-highlight-overlay 'face 'next-error))
  (with-current-buffer (marker-buffer mk)
    (save-excursion
      (if end-mk (goto-char end-mk) (end-of-line))
      (let ((end (point)))
    (if mk (goto-char mk) (beginning-of-line))
    (if (and (stringp highlight-regexp)
         (re-search-forward highlight-regexp end t))
        (progn
          (goto-char (match-beginning 0))
          (move-overlay compilation-highlight-overlay
                (match-beginning 0) (match-end 0)
                (current-buffer)))
      (move-overlay compilation-highlight-overlay
            (point) end (current-buffer)))
    (if (or (eq next-error-highlight t)
        (numberp next-error-highlight))
        ;; We want highlighting: delete overlay on next input.
        (add-hook 'pre-command-hook
              'compilation-goto-locus-delete-o)
      ;; We don't want highlighting: delete overlay now.
      (delete-overlay compilation-highlight-overlay))
    ;; We want highlighting for a limited time:
    ;; set up a timer to delete it.
    (when (numberp next-error-highlight)
      (setq next-error-highlight-timer
        (run-at-time next-error-highlight nil
                 'compilation-goto-locus-delete-o)))))))
(when (and (eq next-error-highlight 'fringe-arrow))
  ;; We want a fringe arrow (instead of highlighting).
  (setq next-error-overlay-arrow-position
    (copy-marker (line-beginning-position)))))))

The eval-afer-load portion just ensures that you re-define it after Emacs defined it, so that your change takes hold.

A: You can add a binding (e.g. Alt-m) and do the following
(define-key grep-mode-map "\M-m" (lambda()
                                   (interactive)
                                   (compile-goto-error)
                                   (delete-other-windows)
                                   (kill-buffer "*grep*")))

I didn't find a way to replace the standard "Enter" / Mouse-click binding with a custom function

A: There is an another approach:
(defun eab/compile-goto-error ()
  (interactive)
  (let ((cwc (current-window-configuration)))
    (funcall
     `(lambda ()
        (defun eab/compile-goto-error-internal ()
          (let ((cb (current-buffer))
                (p (point)))
            (set-window-configuration ,cwc)
            (switch-to-buffer cb)
            (goto-char p ))))))
  (compile-goto-error)
  (run-with-timer 0.01 nil 'eab/compile-goto-error-internal))

A: I had the same question, and found this answer over at emacs.stackexchange https://emacs.stackexchange.com/a/33908/20000
(defun my-compile-goto-error-same-window ()
  (interactive)
  (let ((display-buffer-overriding-action
         '((display-buffer-reuse-window
            display-buffer-same-window)
           (inhibit-same-window . nil))))
    (call-interactively #'compile-goto-error)))

(defun my-compilation-mode-hook ()
  (local-set-key (kbd "o") #'my-compile-goto-error-same-window))

(add-hook 'compilation-mode-hook #'my-compilation-mode-hook)

Pressing o in the *grep* buffer will open the location and file in the same frame.
I found this an elegant solution without deleting frames or too much lisp code and just hooking into compilation-mode-hook.


text:
Q: Avoid inherited ELMAH errors in an ASP.NET subapplication I have a parent IIS application that uses ELMAH and a child ASP.NET application (virtual directory) that doesn't use ELMAH. When I try to browse my subapplication I get this error:

Could not load file or assembly 'Elmah' or one of its dependencies. The system cannot find the file specified.

Which is understandable as my child application's bin folder doesn't contain any ELMAH assemblies.
The problem probably is that the parent web.config file contains this:
  <configSections>
    <sectionGroup name="elmah">

    </sectionGroup>
  </configSections>

As far as I understand there is no way to stop <configSections> inheritance, see e.g. How to stop inheritance of <configSections>in Web.Config. Is there a way to run my ELMAH-free subapplication then?

A: You cannot keep your subapplication ELMAH-free because of the parent configuration. However - since I imagine you don't want to reference the assemblies from the parent - what you can do is tell your subapplication to look for assemblies in the parent bin folder with the probing configuration.
This way your subapplication doesn't need to know what assemblies exist for the parent, only that if an unknown assembly is needed it can be found in the parent folders

Edit: That's indeed a bummer. Clearing and removing configsections tags was considered too complex by Microsoft :

<clear /> and <remove /> were never implemented for configSections and sectionGroups because of the difficulty involved attempting to merge different definitions of the same section-handlers and section groups.

Hence the path workaround. You could also set up the applications so they are not related in terms of hierarchy, if this is critical

A: I have found that adding enableConfigurationOverride="false" to the application pool definition fixes this problem.
From the MSDN docs:

Optional Boolean attribute. When true, indicates that delegated settings in Web.config files will processed for applications within this application pool. When false, all settings in Web.config files will be ignored for this application pool.The default value is true.

There are two methods of doing this, where ChildApplicationName should be replaced with the value of your application pool name.
Method 1 (preferred/advised):
Execute the following command in appcmd in Administrator mode:
appcmd.exe set config -section:system.applicationHost/applicationPools /[name='ChildApplicationName'].enableConfigurationOverride:"False" /commit:apphost

Method 2:
The second involves directly editing the %windir%\System32\inetsrv\config\applicationHost.config file allows the application to effectively ignore the parent application. For various reasons, I don't advice doing this, but I leave this here for posterity.
In order to set this, do a search for your child application pool name. It should be under the xpath. /configuration/system.applicationHost/applicationPools.
<configuration>
  <system.applicationHost>
    <applicationPools>
      ...
      <add name="ChildApplicationName" enableConfigurationOverride="false" />
      ...
    <applicationPools>
  <system.applicationHost>
<configuration>


text:
Q: Kafka10 heartbeat.interval.ms property I am confused with the property heartbeat.interval.ms and poll() method.
I hope, poll() method will send the heartbeat when we invoke the poll() method. Say, heartbeat.interval.ms is configured to 1 sec, but the poll() method takes 2 secs to complete the processing. Will it send heartbeat after 2 secs or every one second thru the background thread.

A: Personally, I see heartbeat.interval.ms as the lower bound for heartbeat interval. That's to say, if you set it to 1 second, heartbeat thread must wait for at least 1 second to send the heartbeat request, but it's possible for the thread to wait up 1.5 seconds before sending request.
As of 0.10.1, heartbeating is moved from the user thread which calls poll to a separate thread, so it has no interleaving with poll things anymore. See further information in details: KIP-62


text:
Q: ZF2 Tutorial error with TableGateway and AdapterInterface I'm currently getting the following error:
Catchable fatal error: Argument 2 passed to Zend\Db\TableGateway\TableGateway::__construct() must implement interface Zend\Db\Adapter\AdapterInterface, none given, called in /vagrant/zend/module/Album/Module.php on line 33 and defined in /vagrant/zend/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/TableGateway.php on line 31

I have been searching this for a while now and I'm only following the ZF2 tutorial. Any idea what can be wrong and how to solve it ?

A: After a few hours troubleshooting I have found out that the issue wasn't on the getServiceConfig method and it was one on the AlbumTable where I have forgot to add, on the construct, the TableGateway parameter.
The ZF2 error message doesn't help much and is misleading but once I have fixed the AlbumTable constructor (re-copied it) it worked.


text:
Q: PHP File upload, image not posted I'm trying to create a form to upload a file, the problem is that the file won't be uploaded. in my code it returns "Image not uploaded".
I've searched a lot online and all the examples uses the same code.
Code:
<?php
if (isset($_FILES['image_url']) && is_uploaded_file($_FILES['image_url']['tmp_name'])) {
    $is_img = getimagesize($_FILES['image_url']['tmp_name']); //Is an image?
    if (!$is_img) {
        $userfile_name = "It isn't an image";
    }
    else {
        if (!file_exists("/images/products/" . $_FILES['image_url']['name'])) {
            $uploaddir = '/images/products/';
            $userfile_tmp = $_FILES['image_url']['tmp_name'];
            $userfile_name = $_FILES['image_url']['name'];
            move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name);
        }
        else {
            $userfile_name = $_FILES['image_url']['name'];
        }
    }
}
else {
    $userfile_name = "Image not uploaded";
}

?>
  <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?> " enctype="multipart/form-data">

Immagine:
    <input type="file" name="image_url"/>

<input type="submit" value="Salva" />

  </form>

The form has also other fields and the data are correctly send to the server.

A: Try this
 <?php
if (isset($_FILES['image_url']) && is_uploaded_file($_FILES['image_url']['tmp_name'])) {
    $is_img = getimagesize($_FILES['image_url']['tmp_name']); //Is an image?
    if (!$is_img) {
        $userfile_name = "It isn't an image";
    }
    else {
        if (!file_exists("images/products/" . $_FILES['image_url']['name'])) {
            $uploaddir = 'images/products/';
            $userfile_tmp = $_FILES['image_url']['tmp_name'];
            $userfile_name = $_FILES['image_url']['name'];
            move_uploaded_file($userfile_tmp, $uploaddir . $userfile_name);
        }
        else {
            $userfile_name = $_FILES['image_url']['name'];
        }
    }
}
else {
    $userfile_name = "Image not uploaded";
}

?>
  <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?> " enctype="multipart/form-data">

Immagine:
    <input type="file" name="image_url"/>

<input type="submit" value="Salva" />

  </form>


text:
Q: Getting ejabberd to notify an external module on client presence change I have an ejabberd server at jabber.domain.com, with an xmpp component written in python (using sleekxmpp) at presence.domain.com.
I wanted the component to get a notification each time a client changed his presence from available to unavailable and vice-versa.
The clients themselves don't have any contacts.
Currently, I have set up my clients to send their available presence stanzas to admin@presence.domain.com, and I do get their online/offline presence notifications. But I feel this isn't the right approach.
I was hoping the clients wouldn't be aware of the component at presence.domain.com, and they would just connect to jabber.domain.com and the component should somehow get notified by the server about the clients presence.
Is there a way to do that?
Is my component setup correct? or should I think about using an xmpp plugin/module/etc..
Thanks

A: It is not difficult to write a custom ejabberd module for this.   It will need to register to presence change hooks in ejabberd,  and on each presence packet route a notification towards your external component.
There is a pair of hooks  'set_presence_hook'  and 'unset_presence_hook' that your module can register to,  to be informed when the users starts/end a session.
If you need to track other presence statuses, there is also a hook 'c2s_update_presence' that fires on any presence packets sent by your users.
Other possibility, without using a custom module, is using shared rosters.  Add  admin@presence.domain.com  to the shared rosters of all your users,  but in this case they will see this item reflected on their roster.

A: It is possible for a component to subscribe to a user's presence exactly the same way a user does. Also it is possible for the user to subscribe to a component's presence. You just have to follow the usual pattern, i.e. the component/user sends a <presence/> of type subscribe which the user/component can accept by sending a <presence/> of type subscribed.
You can also have the user just send a presence to the component directly.
There is no need to write custom hooks or create proxy users.


text:
Q: How can we limit file descriptor to always be less than 1024? There is limitation in select system call that it will not work beyond 1024. This is what document says
WARNING: select() can monitor only file descriptors numbers that
       are less than FD_SETSIZE (1024)—an unreasonably low limit for
       many modern applications—and this limitation will not change.
       All modern applications should instead use poll(2) or epoll(7),
       which do not suffer this limitation.

we have experienced this behaviour only in AWS EC2 instance. Outside of AWS fd is always < 1024
Is there a setting in Linux system (Suse Linux 15 SP2) that will always create fds < 1024?

A: You don't want to do this. Linux always uses the lowest possible file descriptor. So if you get file descriptor 1024 then it means file descriptors 0 up to 1023 were all used already.
If you make Linux only use file descriptors 0-1023, then your program still won't work, because instead of getting file descriptor 1024, you'll get an error saying there aren't any more file descriptors it can use.
You should:

*

*Make sure your program closes file descriptors when it's done with them.
Maybe the reason descriptors 0-1023 were all used is because you forgot to close them. So many sure your program closes them.
If they were real file descriptors that your program was actually using, not just ones you forgot to close, then continue to step 2...

*Use poll instead of select, like the document says. It is not a difficult change.

*Consider using epoll, which is more efficient than select when you are polling a lot of file descriptors at the same time. However, it is much more complicated.


text:
Q: pdftotext for firebase functions? I need to extract text from pdf and for that on my local system i am using pdftotext(poppler) (on ubuntu 18.4 LTS) now i want to deploy the function to Firebase Functions but firebase functions does not have it by default.
Is there any portable version of pdftotext(poppler) as standalone executable so i can spawn it in firebase functions?
Can't use xpdf as it does not allow to extract text but poppler does.
Is there any portable(without any dependency) version of pdftotext from poppler ?


text:
Q: Mouse moving out of the Game with dual screen I'm using a dual-screen setup and some games seem to not lock the mouse to the screen, especially in Battlefield 2142 a while ago I often left the game with my cursor, which was bad when I tried to turn around quickly to shoot someone, suddenly I was back in Windows and quite dead in the game because I clicked on the Windows desktop or another window on the second screen which caused BF2142 to minimize.
The last game I played a few days ago that had this problem was Stubbs the Zombie (of which I heard here on GSE) which didn't even try to keep the mouse on the screen, I couldn't turn right much or my mouse ended up on the second screen minimizing the game when I clicked at the wrong moment.
I remember a few other games where I had this problem a little longer in the past, so is there a solution to this problem without forcing me to disable the second monitor?

A: Using a multi-monitor system left me way unsatisfied in certain needs on my W7 system, so I bought http://www.realtimesoft.com/ultramon/ (after carefully evaluating it). One of it's useful features I just later discovered was that I can bind a shortcut to disable the other monitor (which ever this is is configurable).
since its seldom I can really make use of the second monitor, I actually often prefer to disable it during gameplay and re-enable it afterwards. That automatically saved me from the mouse moving problem. It may be overkill of MouseJail just fits your needs though.
In my case CTRL-ALT-Q disables my left (secondary) monitor and re-enables it upon pressing again. Works when being in most games, in a few it doesn't and you'd have to perform this before starting the game. Upon re-enabling the other monitor again, window positions are restored properly too.
Windows 7 also has a built-in shortcut to disable or change your multi-monitor settings. Windows Key + P will bring up a dialog to change options. It's very quick and convenient.

A: There may be a built in Windows way to do it but this Lifehacker link suggests a tiny program called MouseJail to keep the mouse on the correct screen.


text:
Q: There are $n$ horses. At a time only $k$ horses can run in a single race. What is the minimum number of races required to find the $m$ fastest horses? The following question was asked and not (yet) answered at Math Stack Exchange.

There are $n$ horses. At a time only $k$ horses can run in the single race. What is the minimum number of races required to find the top $m$ fastest horses? Please explain your answer.

The $n = 25, k = m = 5$ case was a Google interview question and there are various answers on the web. But I am not sure what the right answer should be for this. Any ideas?

A: A trivial lower bound is $n/k$, since clearly every horse must race to obtain the answer.
I think we can get $O(n/k)$ upper bound, by adapting the median-of-medians selection algorithm.
First, note that, up to a constant factor, this problem is equivalent to finding the $m$th best horse. For the reduction one way, simply find the $m$ best horses and the $m-1$ best horses and see which horse mysteriously disappeared. For the reduction the other way, find the $m$th best horse, then race every other against it to find which are better and which are worse. (In fact, you don't need to do this - it's not hard to check that if you've found the $m$th best horse through repeated racing, you already know which are better and which are worse.)
For $k=2$, the median-of-medians algorithm is known to give an $O(n)$ time bound, as was pointed out by Ralph Furmaniak. We will also use this to handle $k\leq 4$.
So assume $k\geq 5$ and is odd. Let $T(n)$ be the time it takes to find the $m$th horse among $n$ horses. Then divide the horses into groups of $k$, race them in time $n/k$, and take the median of each. Then select the median of those medians in time $T(n/k)$, and pivot on it in time $n/(k-1)$. (to pivot, the pivot horse must race each other horse only once. This allows us to remove at least $n(k+1)/4k$ of the horses, so we can find the $m$th horse in time $T(n (3k-1)/4k)$. So we get:
$$T(n) \leq T\left(\frac{n}{k}\right) + T\left(  \frac{n(3k-1)}{4k}\right) + \frac{n}{k}+\frac{n}{k-1} $$
By induction,
$$T(n) \leq \frac{4k}{k-3} \cdot \left( \frac{n}{k}+\frac{n}{k-1} \right) = O \left(\frac{n}{k}\right)$$
In fact we obtain an explicit constant of $8+o(1)$.
This ignores non-unique divisibility, which should only lead to a small error term unless $k$ is very large as a fraction of $n$.


text:
Q: Videos in Simulink show too fast when I run videos, for example this here from Simulink:
http://de.mathworks.com/help/vision/examples/tracking-cars-using-optical-flow.html
everything works fine, but all my videos in Simulink run too fast. About 5 times faster then normal. I use Win10 64bit, and also Matlab/Simulink for 64bit. The video files play with correct speed in Windows Media Player or all other Media Player.
Why are the videos play so fast in Simulink?
Thanks for help

A: Simulink is a simulation framework, which returns the results as fast as possible. Unless you artificially slow it down, it will always run as fast as your PC allows. If you really want to slow it down choose one of the options listed here, but this is typically not what you want to do. Instead I recommend to write the results back to an avi-file if you really need to analyse the results in detail.


text:
Q: Telerik RadGrid GridTemplateColumns programmatically I need to make multiple RadGrids with editable columns throughout them.  I understand how to make bound columns and make template columns but i do not know how to place Textbox's and Dropdownlists inside of those template columns.
string templateColumnName = "ContactName";
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new MyTemplate(templateColumnName);
templateColumn.HeaderText = templateColumnName;

what do I do after this.

A: You should instantiate the desired webcontrol within the container. This happens in the InstantiateIn method. I'd recommend that you examine this link:
Programmatic creation
If you need more info, you can also examine this one:
Creating Web Server Control Templates Programmatically
Let us know if you have any specific question about that.


text:
Q: Get the equation from a polyfit to apply further derivatives I have managed to perform a polynomial fit to a set of smoothed data. Now, I would need to get the polynomial equation so that I can perform first and second derivatives to the polynomial and find maximums and minimuns. Although I can get the coeficients easily with polyfit, I don't know how to get the whole polynomial so that I can apply to it the derivatives. I was thinking on using SimPy to perform the derivatives but I don't think I can without the whole polynomial equation built.
Here's my code so far:
import matplotlib.pyplot as plt
import numpy as np
from pandas import *
from math import factorial
from scipy import interpolate
import numpy.polynomial.polynomial as poly
import itertools

# savitzky_golay definition
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
    try:
        window_size = np.abs(np.int(window_size))
        order = np.abs(np.int(order))
    except ValueError:
        raise ValueError("window_size and order have to be of type int")
    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window_size size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window_size is too small for the polynomials order")
    order_range = range(order+1)
    half_window = (window_size -1) // 2
    # precompute coefficients
    b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
    m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
    # pad the signal at the extremes with
    # values taken from the signal itself
    firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
    lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
    y = np.concatenate((firstvals, y, lastvals))
    return np.convolve( m[::-1], y, mode='valid')

import os, sys
#get the xlsx files
files= os.listdir(r'C:\Users\Dani\Desktop\REACTIVITY')
file=[f for f in files if f[-4:]=='xlsx']

for file in file:
    #read the files
    data=pandas.read_excel(file, sheet_name=0)

    y1=np.array(data["Viscosity"])
    x=np.array(data["Time (s)"])
    y2=np.array(data["Temperature (oC)"])

    fig, ax1 = plt.subplots()
    #create initial axis
    ax1.set_xlabel("Time (s)", labelpad=10)
    ax1.set_ylabel("Viscosity", color='blue', labelpad=10)
    ax1.tick_params(axis='y', labelcolor='blue')

    #smooth data by using savitzky_golay
    yhat=savitzky_golay(y1, 51, 3)
    ax1.plot(x,yhat, color='blue',linewidth=2)
    #create temperature graph
    ax2=ax1.twinx()
    ax2.set_ylabel(u'Temperature (C)' , color='red', labelpad=10)
    ax2.plot(x, y2, color='red',linewidth=2)
    ax2.tick_params(axis='y', labelcolor='red')

    #fit the Viscosity smoothed data to a polynomial
    for i in itertools.count():
        #create the polynomial fit for different degrees
        coefs=poly.polyfit(x, yhat, i)
        fit=poly.polyval(x, coefs)
        #calculate rsquare
        ybar = np.sum(yhat)/len(yhat)
        ssreg = np.sum((fit-ybar)**2)
        sstot = np.sum((yhat - ybar)**2)
        square = ssreg / sstot

        if square > 0.995:
            #get the desired degree
            ax1.plot(x, fit, color='black', linestyle='--',linewidth=2)
            print(square)
            print(coefs)
            print(i)
            break

    plt.show()


text:
Q: Prove: $\forall a,b\in \mathbf{R^+}, \exists m\in \mathbf{N}$ such that $(m-1)a\leq b \leq ma$. Prove: $\forall a,b\in \mathbf{R^+}, \exists m\in \mathbf{N}$ such that $(m-1)a\leq b \leq ma$.
Proof:
Since $a,b \in \mathbf{R^+}$ we have that $\frac{b}{a} > 0$. Let $A = \{n \in \mathbf{N} : \frac{b}{a} < n  \}$. It's obvious that $A$ is non empty and is bounded below. Let $\inf{A} = m$, then we have that $\frac{b}{a}\leq m$. Suppose $m = 1$, then clearly $0\leq \frac{b}{a} \leq 1$. Suppose $m > 1$. Since $m$ is the smallest natural number greater than $\frac{b}{a}$, it is implied that $m-1 \leq \frac{b}{a} \leq m$. Since $a>0$ multiplying the inequality by $a$ gives $(m-1)a\leq b \leq ma$ as desired.
Is this a valid proof?
EDIT: I should say let $\min{A} = m$ since I cannot show that $\inf(A) \in A$.

A: $(m-1)a\le b\le ma\iff ma-a\le b\le ma\Rightarrow -a\le0$ wich  is obvious.
Thus the statement of the post it is true.


text:
Q: IMPOSSIBLE to configure your SDK Via Configure | Project Default | Project Structure | SDKs Hello Installing Android Studio seems to be a nightmare !

*

*I've downloaded this build : android-studio-ide-135.1538390-windows

*At the first execution it says that JVM is missing

*So I've installed : jdk-8u25-windows-i586.exe

*Next run Now I get a message saying that I need an environnement variable to catch the JDK

*OK I set it also

*Finaly the JDK can be found.... but the nightmare is not finish

*I launch Android Studio and try to open a new Project

*Now it does not found the SDK which was suposed to come with the IDE

*OK back to Download I get : installer_r23.0.2-windows.exe (Very explicit name !!) and I install it

*I try again : still no SDK

*I keep calm I continue to follow the rules

Your Android SDK is Missing, out of date or is missing Templates
  You can configure your SDK Via Configure | Project Default | Project Structure | SDKs

So I try to set
C:\Program Files (x86)\Android\android-sdk
But the IDE refuse to keep that setting
Now I give-up I need some help
Maybe let the SDK installed on Program_Files is not a good idea ?
Thanks for any help

A: Simple Open the Android Studio.
First click on File menu then Project Structure then you will find an option to set the SDK location. Now instead of writing path simply browse then you are done.
It should solve your problem.

A: I filed a bug report about that earlier today.
Just start creating or importing a project from the welcome dialog. You should be prompted to supply the SDK path at that point, and (so far) that seems to stick.


text:
Q: Linux web server partitioning: How should I do it? I've order a dedicated server which will have 2x1TB hard disks. I'd like a little help though on how I should partition the disks.
Everything will be setup using software raid1 (mdadm) and all of the user data will reside in /home (this includes apache2 website files alongside everything else). I was thinking about something like the following:

*

*4MB bios_grub (since I'll be using a GPT)

*1GB /boot (just because - yes I know that it's too much)

*50GB / (this will include /usr as well)

*740GB /home

*50GB /var (logs, mails, others)

*150GB /var/lib/mysql (MySQL files)

*8GB swap

What do think? I may be assigning less space to /var/lib/mysql since we don't expect to have lot's of MySQL databases (I even think that 10GB will be more than enough for our needs).
What would you change and why?

A: Consider using LVM - Logical Volume Management. It lets you manage the storage in a flexible way - online resizing of volumes and snapshots and else.

A: I don't think it is any use to seperate /boot, /, /var. That kind of micro-partitionning was in the mood of the late 90's and early 2000's, but I really don't think it is still recommended.
I even feel like the /var/lib/mysql is superfluous, if you don't plan to put the database on a really different hard drive.

A: I wouldn't bother with so many partitions, it's not necessary unless you're partitioning to separate disks. It's also possible it could cause headaches down the line if they become full.
Generally I use something like the following:
/boot - 1GB
/     - 5GB - 10GB
/data - Rest of disk
swap  - RAM X2

/boot and / are potentially oversized here but I prefer to have too much space than risk too little. If you're unsure though, check the docs for your distribution as they'll very likely offer recommended partitioning schemes.

A: For a standalone server, using RAID1 makes some sense - although you might consider using independent (non-mirrored) swap partitions on the 2 disks. If you ever get into swapping you're just slowing the system down by writing to both disks. If it's likely that you'll have a disk failure at the same time that the system has run out of physical memory, then the really you need more RAM or less memory hungry config.
I disagree with Stephane that splitting your disk into different partitions is no longer necessary - it's a good way to protect your system from overflowing logs and partitioning reads / writes still brings performance benefits.
Using more partitions than you need seems sloppy - looking at your setup, I think it would be worth keeping /home on the same filesystem as /
I don't know anything about the applications it will run, but suspect that split between user content and database favours the former too much - but then again I work mostly with database-intensive stuff.


text:
Q: Best mysql structure for my data table Im very new to mysql, and any help would be much appreciated!
I have my main table with product information. (9000+ products)
    id       name          size     color
    9809355  product one   small    blue
    0109425  product two   large    black

I also have cron script that that gets the following data of each product every hour (from ebay or amazon):
    id       price     timestamp
    9809355  $672.00   07/26/2012 @ 2:00pm
    0109425  $82.00    07/26/2012 @ 2:00pm

(prices are allways changing)
What is the best way to store this data?
my options seem to be creating a table for each product, or placing all my data into one table for product prices.

A: Creating a table for each product is rarely ever the correct approach.  This would needlessly complicate joins -- if you wanted to obtain a list of all products, how would you do it with separate tables?
If you want to decouple the price data from the price details, you could create a price table that has a one-to-one relationship with the product information table.  I don't generally advocate for one-to-one relationships, but sometimes it is the right approach.


text:
Q: How to add EC2 instance to ECS cluster using AWS Node SDK I am trying to programmaticly create a ECS cluster with EC2 instance in it. As far as I understand I should first create an ECS cluster , than EC2 instance and then register instance using this method :
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ECS.html#registerContainerInstance-property
Is it how I should do it? Which arguments are mandatory? How to get instanceIdentityDocument and instanceIdentityDocumentSignature?
thanks

A: I would use the User Data of the EC2 instance to launch the instance directly into the ECS cluster. This is the User Data you'll want to use:
#!/bin/bash
echo ECS_CLUSTER=your_cluster_name >> /etc/ecs/ecs.config

The details of this are described in the AWS docs. You can also use this user data in an Auto Scale Group Launch Configuration.
Apart from that, it might be worth it to look into languages that where made to provision infrastructure, like Terraform (also for AWS) or CloudFormation (specifically for AWS).


text:
Q: Android SDK/NDK error with python-for-android/kivy I'm on Fedora Linux 19, using the latest Android SDK, latest java SDK, and NDK=R9. Using the instructions here, I'm trying to create a python/kivy installation specialized for android, by running the command, ./distribute.sh -m "kivy". It produces the output below. Can anyone tell me what's going wrong here, and what I can do to fix it? Thank you.
./dist*sh -m "kivy"

Check build dependencies for Fedora
Avoid check build dependencies, unknow platform Fedora
Check enviromnent
SDK located at /home/ljm/Developer/android-sdks
NDK located at /home/ljm/Developer/android-ndk-r9
NDK version is r9
API level set to 18
Check mandatory tools
Distribution will be located at /home/ljm/Developer/workspace/python-for-android/dist/default
The distribution /home/ljm/Developer/workspace/python-for-android/dist/default already exist
Press a key to remove it, or Control + C to abort.

Entering in ARM enviromnent
Compiler found at /home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc
PATH is /home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/:/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86_64/bin/:/home/ljm/Developer/android-ndk-r9:/home/ljm/Developer/android-sdks/tools:/home/ljm/Developer/android-ndk-r9:/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/:/home/ljm/Developer/android-sdks:/home/ljm/Developer/android-sdks/platform-tools:/home/ljm/Developer/android-sdks/tools:/usr/local/bin:/usr/bin:/bin:/usr/games:/usr/local/sbin:/usr/sbin:/homeljm.local/bin:/homeljmbin
Leaving ARM enviromnent
Read kivy recipe
Module kivy depend on pygame pyjnius android
Read pygame recipe
Module pygame depend on python sdl
Read pyjnius recipe
Module pyjnius depend on python sdl
Read android recipe
Module android depend on pygame
Read python recipe
Module python depend on hostpython
Read sdl recipe
Module sdl depend on python
Ignored python, already processed
Ignored sdl, already processed
Ignored pygame, already processed
Read hostpython recipe
Ignored python, already processed
Modules changed to hostpython python sdl pygame pyjnius android kivy
Run get packages
Download package for hostpython
Module hostpython already downloaded
Download package for python
Module python already downloaded
Download package for sdl
No package for sdl
Download package for pygame
Module pygame already downloaded
Download package for pyjnius
Module pyjnius already downloaded
Download package for android
No package for android
Download package for kivy
Module kivy already downloaded
Run prebuild
Call prebuild_hostpython
Call prebuild_python
Call prebuild_sdl
Call prebuild_pygame
Call prebuild_pyjnius
Call prebuild_android
Call prebuild_kivy
Run build
Call build_hostpython
Call build_python
Call build_sdl
Entering in ARM enviromnent
Compiler found at /home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc
Android NDK: WARNING:/home/ljm/Developer/workspace/python-for-android/src/jni/../jni/application/Android.mk:application: non-system libraries in linker flags: -lpython2.7
Android NDK:     This is likely to result in incorrect builds. Try using LOCAL_STATIC_LIBRARIES
Android NDK:     or LOCAL_SHARED_LIBRARIES instead to list the library dependencies of the
Android NDK:     current module
Android NDK: WARNING:/home/ljm/Developer/workspace/python-for-android/src/jni/../jni/png/Android.mk:png: LOCAL_LDLIBS is always ignored for static libraries
rm -f /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/lib*.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi-v7a/lib*.so /home/ljm/Developer/workspace/python-for-android/src/libs/mips/lib*.so /home/ljm/Developer/workspace/python-for-android/src/libs/x86/lib*.so
rm -f /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/gdbserver /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi-v7a/gdbserver /home/ljm/Developer/workspace/python-for-android/src/libs/mips/gdbserver /home/ljm/Developer/workspace/python-for-android/src/libs/x86/gdbserver
rm -f /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/gdb.setup /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi-v7a/gdb.setup /home/ljm/Developer/workspace/python-for-android/src/libs/mips/gdb.setup /home/ljm/Developer/workspace/python-for-android/src/libs/x86/gdb.setup
Install        : libapplication.so => libs/armeabi/libapplication.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libapplication.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libapplication.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libapplication.so
Install        : libsdl.so => libs/armeabi/libsdl.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libsdl.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl.so
Install        : libsdl_main.so => libs/armeabi/libsdl_main.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libsdl_main.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_main.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_main.so
Install        : libsdl_ttf.so => libs/armeabi/libsdl_ttf.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libsdl_ttf.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_ttf.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_ttf.so
Install        : libsdl_image.so => libs/armeabi/libsdl_image.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libsdl_image.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_image.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_image.so
Install        : libsqlite3.so => libs/armeabi/libsqlite3.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libsqlite3.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsqlite3.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsqlite3.so
Install        : libsdl_mixer.so => libs/armeabi/libsdl_mixer.so
install -p /home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/libsdl_mixer.so /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_mixer.so
/home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-strip --strip-unneeded  /home/ljm/Developer/workspace/python-for-android/src/libs/armeabi/libsdl_mixer.so
Leaving ARM enviromnent
Call build_pygame
Entering in ARM enviromnent
Compiler found at /home/ljm/Developer/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc
running install
running build
running build_py
running build_ext
building 'pygame.surface' extension
arm-linux-androideabi-gcc -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -I/home/ljm/Developer/workspace/python-for-android/src/jni/png -I/home/ljm/Developer/workspace/python-for-android/src/jni/jpeg -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl/include -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_mixer -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_ttf -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_image -fPIC -D_REENTRANT -I/home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7 -c src/surface.c -o build/temp.linux-i686-2.7/src/surface.o
In file included from /home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7/Python.h:126:0,
                 from src/pygame.h:75,
                 from src/surface.h:28,
                 from src/surface.c:26:
/home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7/modsupport.h:27:1: warning: 'PyArg_ParseTuple' is an unrecognized format function type [-Wformat=]
 PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...) Py_FORMAT_PARSETUPLE(PyArg_ParseTuple, 2, 3);
 ^
src/surface.c: In function 'surf_get_locked':
src/surface.c:755:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
         Py_RETURN_TRUE;
         ^
src/surface.c:756:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
     Py_RETURN_FALSE;
     ^
src/surface.c: In function 'surf_convert_alpha':
src/surface.c:1279:28: warning: variable 'src' set but not used [-Wunused-but-set-variable]
     SDL_Surface *newsurf, *src;
                            ^
arm-linux-androideabi-gcc -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -I/home/ljm/Developer/workspace/python-for-android/src/jni/png -I/home/ljm/Developer/workspace/python-for-android/src/jni/jpeg -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl/include -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_mixer -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_ttf -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_image -fPIC -D_REENTRANT -I/home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7 -c src/alphablit.c -o build/temp.linux-i686-2.7/src/alphablit.o
In file included from /home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7/Python.h:126:0,
                 from src/pygame.h:75,
                 from src/surface.h:28,
                 from src/alphablit.c:25:
/home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7/modsupport.h:27:1: warning: 'PyArg_ParseTuple' is an unrecognized format function type [-Wformat=]
 PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...) Py_FORMAT_PARSETUPLE(PyArg_ParseTuple, 2, 3);
 ^
In file included from src/surface.h:28:0,
                 from src/alphablit.c:25:
src/pygame.h:678:14: warning: 'PyGAME_C_API' defined but not used [-Wunused-variable]
 static void* PyGAME_C_API[PYGAMEAPI_TOTALSLOTS] = { NULL };
              ^
arm-linux-androideabi-gcc -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -I/home/ljm/Developer/workspace/python-for-android/src/jni/png -I/home/ljm/Developer/workspace/python-for-android/src/jni/jpeg -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl/include -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_mixer -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_ttf -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_image -fPIC -D_REENTRANT -I/home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7 -c src/surface_fill.c -o build/temp.linux-i686-2.7/src/surface_fill.o
In file included from /home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7/Python.h:126:0,
                 from src/pygame.h:75,
                 from src/surface.h:28,
                 from src/surface_fill.c:20:
/home/ljm/Developer/workspace/python-for-android/build/python-install/include/python2.7/modsupport.h:27:1: warning: 'PyArg_ParseTuple' is an unrecognized format function type [-Wformat=]
 PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...) Py_FORMAT_PARSETUPLE(PyArg_ParseTuple, 2, 3);
 ^
In file included from src/surface.h:28:0,
                 from src/surface_fill.c:20:
src/pygame.h:678:14: warning: 'PyGAME_C_API' defined but not used [-Wunused-variable]
 static void* PyGAME_C_API[PYGAMEAPI_TOTALSLOTS] = { NULL };
              ^
/home/ljm/Developer/workspace/python-for-android/src/tools/liblink -lm -L/home/ljm/Developer/workspace/python-for-android/build/libs -L/home/ljm/Developer/workspace/python-for-android/src/obj/local/armeabi/ -lm -lz -DANDROID -mandroid -fomit-frame-pointer --sysroot /home/ljm/Developer/android-ndk-r9/platforms/android-18/arch-arm -I/home/ljm/Developer/workspace/python-for-android/src/jni/png -I/home/ljm/Developer/workspace/python-for-android/src/jni/jpeg -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl/include -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_mixer -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_ttf -I/home/ljm/Developer/workspace/python-for-android/src/jni/sdl_image build/temp.linux-i686-2.7/src/surface.o build/temp.linux-i686-2.7/src/alphablit.o build/temp.linux-i686-2.7/src/surface_fill.o -L/home/ljm/Developer/workspace/python-for-android/build/python-install/lib -lsdl -lm -lpython2.7 -o build/lib.linux-i686-2.7/pygame/surface.so
arm-linux-androideabi-ld: -arch: unknown option
arm-linux-androideabi-ld: use the --help option for usage information
error: command '/home/ljm/Developer/workspace/python-for-android/src/tools/liblink' failed with exit status 1

A: In accordance with the above suggestion of downgrading the API and NDK (to 14 and r8c, respectively), I've downgraded the android tools, and the problem seems to have been resolved. Thanks!


text:
Q: SocketCan Error: Sending frame to hardware that is not powered up I'm sending a message on a CAN bus with no powered on nodes. The CAN message returned has a message ID of 0x2000 0088, which indicates a CAN_ERR_FLAG.
CAN_ERR_PROT and CAN_ERR_BUSERROR are set.
Data[0..7]: 0x00 0x00 0x80 0x19 0x00 0x00 0x00 0x00
Decoding the data[2] = CAN_ERR_PROT_TX
and, data[3] = CAN_ERR_PROT_LOC_ACK
This is an expected condition as there are no nodes on the bus to acknowledge the message.
But...
We are epolling on the device and its continuously reporting the above error. Even if we turn on a CAN node we still receive these errors.
If we start our application with the CAN node powered on everything behaves as expected.
Wireshark capture
How should we recover from this condition?


text:
Q: Подсчет числа записей в таблице Добрый день! Делаю к сайту движок комментариев статей. Пишу следующий код (на PDO).
$sql = "SELECT COUNT(*) as count FROM comments, blog
WHERE (blog.id_blog = $article_id) and (blog.id_blog = comments.code_blog)";
$result = $conn->query($sql);
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch();
$member = $row['count'];

При обновлении страничке в браузере выдается следующая ошибка:
Fatal error: Call to undefined method mysqli_result::setFetchMode()
in S:\home\localhost\www\book-fan\details.php on line 98
Вопрос почему PDO не видит метод setFetchMode?
A: Насколько я вижу из текста ошибки, вы используете mysqli, а не PDO
Покажите, как инициализируете соединение.
Попробуйте

$row = $result->fetch_assoc();

И закомментируйте строчку

$result->setFetchMode(PDO::FETCH_ASSOC);


text:
Q: Learning Python: Print 3 consecutives lines from a PIPE i have the following code:
def cmds(cmd):
    cmd= Popen(cmd, shell=True, stdout=PIPE)
    lines = command.stdout.read().splitlines()

I have a command that outputs lines like this:
2011/03/30-201
CLIENT 3
Failed
23:17
0.0000

2011/03/31-3
CLIENT 2
Completed
00:47
1.0019

I want to read the first 3 lines for a block, then more 3 lines for next block and more 3 ...
I do have no idea how to do this.

A: Well, if lines = command.stdout.read().splitlines() produces a list of lines like this:
['2011/03/30-201', 'CLIENT 3', 'Failed', '23:17', '0.0000', '', '2011/03/31-3', 'CLIENT 2', 'Completed', '00:47', '1.0019']

You can just loop through it and print until you encounter a blank entry, then reset the counter. It's not very elegant, but it's the most naïve way of doing it:
lines = command.stdout.read().splitlines()
i = 0

for line in lines:
  if line != '':
    if i < 3:
      print(line)
  else:
    i = 0

  i += 1

A: Untested:
def cmds(cmd):
    infile = Popen(cmd, shell=True, stdout=PIPE).stdout
    print infile.readline()
    print infile.readline()
    print infile.readline()
    while True:
        line = infile.readline()
        if not line:
            break
        if line == '\n':
            print infile.readline()
            print infile.readline()
            print infile.readline()

That has the advantage of working on arbitrarily huge files because it only stores the data it's currently working on and not the entire output of your command.


text:
Q: Dynamic metadata according platform? Is it possible to detect the platform within the metadata.rb file of a Cookbook?
For example, something like this:
if node['platform'] == 'aix'
   depends "cats", "< 1.0"
end

if node['platform'] == 'ubuntu'
   depends "cats", "> 1.0"
end

But that is not possible since node is not available in that context. Is there any other way?

A: No, cookbook dependencies are entirely static. This has been discussed for some point in the future but no major proposals have emerged. If you are interested in contributing I would invite you to submit a Chef RFC with a proposed fix if you can come up with one :)
The sticky point is usually that there are reasons for conditional dependencies beyond simply per-platform logic. This comes up often for things like runit vs. systemd, mysql vs. postgres, and apache vs. nginx.


text:
Q: Erlang: Compute data structure literal (constant) at compile time? This may be a naive question, and I suspect the answer is "yes," but I had no luck searching here and elsewhere on terms like "erlang compiler optimization constants" etc.
At any rate, can (will) the erlang compiler create a data structure that is constant or literal at compile time, and use that instead of creating code that creates the data structure over and over again?  I will provide a simple toy example.
test() -> sets:from_list([usd, eur, yen, nzd, peso]).

Can (will) the compiler simply stick the set there at the output of the function instead of computing it every time?
The reason I ask is, I want to have a lookup table in a program I'm developing.  The table is just constants that can be calculated (at least theoretically) at compile time.  I'd like to just compute the table once, and not have to compute it every time.  I know I could do this in other ways, such as compute the thing and store it in the process dictionary for instance (or perhaps an ets or mnesia table).  But I always start simple, and to me the simplest solution is to do it like the toy example above, if the compiler optimizes it.
If that doesn't work, is there some other way to achieve what I want?  (I guess I could look into parse transforms if they would work for this, but that's getting more complicated than I would like?)
THIS JUST IN.  I used compile:file/2 with an 'S' option to produce the following.  I'm no erlang assembly expert, but it looks like the optimization isn't performed:
{function, test, 0, 5}.
{label,4}.
    {func_info,{atom,exchange},{atom,test},0}.
  {label,5}.
    {move,{literal,[usd,eur,yen,nzd,peso]},{x,0}}.
    {call_ext_only,1,{extfunc,sets,from_list,1}}.

A: No, erlang compiler doesn't perform partial evaluation of calls to external modules which set is. You can use ct_expand module of famous parse_trans to achieve this effect.

A: providing that set is not native datatype for erlang, and (as matter of fact) it's just a library, written in erlang, I don't think it's feasibly for compiler to create sets at compile time.

A: As you could see, sets are not optimized in erlang (as any other library written in erlang).
The way of solving your problem is to compute the set once and pass it as a parameter to the functions or to use ETS/Mnesia.


text:
Q: Cut and Fold Polyhedron! I have two convex polyhedra such that their sums of side areas are equal. It is true that I can cut one of them and flatten it on the plane, then fold the flattened polygon to reach the other polyhedron?
For special case in which these two polyhedra are cube and regular tetrahedron, The answer in Yes I think. But I think the answer is "No, not necessarily" in general case, and I think the problem is difficult!

A: If this says what I think it says, the answer is "NO" for even the example cited, since you are prescribing the intrinsic metric on the polyhedron, and it is a celebrated theorem of A. D. Alexandrov (which is a slightly tweaked theorem of Cauchy) that the intrinsic metric determines the convex polyhedron uniquely. For more, see Alexandrov's "Convex Polyhedra"

A: The general answer is sometimes Yes, various unfold/refold pairs
of convex polyhedra exist, but not always,
depending on what is meant by "cut."
Here is an example that Erik Demaine, Marty Demaine, Anna Lubiw, and I worked out carefully:
The Latin-cross unfolding of the cube can refold
into precisely 23 distinct convex polyhedra,
as displayed below (all of the same surface area):
the cube,
two doubly covered flat quadrilaterals,
seven tetrahedra,
three pentahedra, each with one or more quadrilateral faces,
four hexahedra,
and six octahedra:

Fig. 25.30, p.408 in Geometric Folding Algorithms: Linkages, Origami, Polyhedra, 2007.

Here is a "movie" of one of the refoldings to a tetrahedron:

But more generally, in the 2012 paper Refold Rigidity of Convex Polyhedra, we showed that every convex
polyhedron can be cut open and refolded to an incongruent convex polyhedron.

But if the cutting is restricted to follow edges of the convex polyhedron
("edge unfoldings"),
then there are "refold-rigid" polyhedra.
For example, each
of the 43,380 edge unfoldings of a dodecahedron may only fold back to
the dodecahedron.

Added.
I apologize for not initially understanding Morteza's precise question, which
asks whether or not, for any two given pair of convex polyhedra $P$ and $Q$
with the same surface area, is it always possible to cut
open $P$ and refold to $Q$. This remains an open question as far as I know.
It is a version of Open Problem 25.31 (Fold/Refold Dissections) in
Geometric Folding Algorithms.


text:
Q: Fast modulo 3 or division algorithm? is there a fast algorithm, similar to power of 2, which can be used with 3, i.e. n%3.
Perhaps something that uses the fact that if sum of digits is divisible by three, then the number is also divisible.
This leads to a next question.  What is the fast way to add digits in a number?  I.e. 37 -> 3 +7 -> 10
I am looking for something that does not have conditionals as those tend to inhibit vectorization
thanks

A: This comp.compilers item has a specific recommendation for computing modulo 3.
An alternative, especially if the maximium size of the dividend is modest, is to multiply by the reciprocal of 3 as a fixed-point value, with enough bits of precision to handle the maximum size dividend to compute the quotient, and then subtract 3*quotient from the the dividend to get the remainder.  All of these multiplies can be implemented with a fixed sequence of shifts-and-adds.  The number of instructions will depend on the bit pattern of the reciprocal.   This works pretty well when the dividend max is modest in size.
Regarding adding digits in the number... if you want to add the decimal digits, you're going to end up doing what amounts to a number-conversion-to-decimal, which involves divide by 10 somewhere.   If you're willing to settle for adding up the digits in base2, you can do this with an easy shift-right and add loop.  Various clever tricks can be used to do this in chunks of N bits to speed it up further.

A: 4 % 3 == 1, so (4^k * a + b) % 3 == (a + b) % 3.  You can use this fact to evaluate x%3 for a 32-bit x:
x = (x >> 16) + (x & 0xffff);
x = (x >> 10) + (x & 0x3ff);
x = (x >> 6) + (x & 0x3f);
x = (x >> 4) + (x & 0xf);
x = (x >> 2) + (x & 0x3);
x = (x >> 2) + (x & 0x3);
x = (x >> 2) + (x & 0x3);
if (x == 3) x = 0;

(Untested - you might need a few more reductions.)  Is this faster than your hardware can do x%3?  If it is, it probably isn't by much.

A: Not sure for your first question, but for your second, you can take advantage of the % operator and integer division:
int num = 12345;
int sum = 0;
while (num) {
    sum += num % 10;
    num /= 10;
}

This works because 12345 % 10 = 5, 12345 / 10 = 1234 and keep going until num == 0

A: If you are happy with 1 byte integer division, here's a trick. You could extend it to 2 bytes, 4 bytes, etc.
Division is essentially multiplication by 0.3333. If you want to simulate floating point arithmetic then you need closest approximation for the 256 (decimal) boundary. This is 85, because 85 / 256 = 0.332. So if you multiply your value by 85, you should be getting a value close to the result in the high 8 bits.
Multiplying a value with 85 fast is easy. n * 85 = n * 64 + n * 16 + n * 4 + n. Now all these factors are powers of 2 so you can calculate n * 4 by shifting, then use this value to calculate n * 16, etc. So you have max 5 shifts and 4 additions.
As said, this'll give you approximation. To know how good it is you'll need to check the lower byte of the next value using this rule
n ... is the 16 bit number you want to divide
approx = HI(n*85)
if LO(n*85)>LO((n+1)*85)THEN approx++

And that should do the trick.
Example 1:
3 / 3 =?
3 * 85 = 00000000 11111111 (approx=0)
4 * 85 = 00000001 01010100 (LO(3*85)>LO(4*85)=>approx=1)
result approx=1

Example 2:
254 / 3
254 * 85 = 01010100 01010110 (approx=84)
255 * 85 = 01010100 10101011 (LO(254*85)<LO(255*85), don't increase)
result approx=84

A: If you're dealing with big-integers, one very fast method is realizing the fact for all
    bases 10 +/- multiple-of-3
i.e.
    4,7,10,13,16,19,22…. etc

All you have to do is count the digits, then % 3. something like :
** note :  x ^ y is power, not bit-wise XOR,
          x ** y being the python equivalent

function mod3(__,_) {
   #
   # can handle bases
   #   { 4, 7,10,13,16,19,
   #       22,25,28,31,34 } w/o conversion
   #
   # assuming base digits :
   #
   #    0-9A-X for any base,
   # or 0-9a-f for     base-16

   return \
   (length(__)<=+((_+=++_+_)+_^_)\
       && (__~"^[0-9]+$")  )\
   ? (substr(__,_~_,_+_*_+_)+\
        substr(__,++_*_--))%+_\
   :\
    (substr("","",gsub(\
   "[_\3-0369-=CFILORUXcf-~]+","",__))\
       +                  length(__) \
    + gsub("[258BbEeHKNQTW]","",__))%+_
}

This isn't the fastest method possible, but it's one of the more agile methods.


text:
Q: GSheets VLookup array to search multiple tabs for multiple references So I have a Google sheet with multiple tabs and need to reference data in column A in order to display the data in rows B, C, D, E etc
Here's what I currently have: =ArrayFormula(IF(lEN(B4), IFerror(VLOOKUP(T(B4),{Data1!$A$1:$A$561; Data2!$A$1:$A$673; Data3!$A$1:$A$1217, Data4!$A$1:$A$1217},1,1,FALSE),"Not found"),))
I'm not getting any errors, but I'm also not getting any results, even using exact values so it makes me think I'm missing something.
Any ideas?

A: try:
=INDEX(IF(LEN(B4), IFNA(VLOOKUP(B4,
 {Data1!A1:E561;
  Data2!A1:E673;
  Data3!A1:E1217;
  Data4!A1:E1217}, {2,3,4,5}, 0), "Not found"), ))


text: Q: IOS 14 Advertising Support package on TVOS not working Does the IOS 14 Advertising Support package support TVOS platform? When trying to use it on TVOS to implement the ATT popup, i get "The type or namespace name "Advertisement" does not exist in the namespace "Unity".