DELETE all using Left join of 3 tables

Question: SELECT * FROM property
LEFT JOIN installmentagreement
ON property.PId=installmentagreement.PId
LEFT JOIN installments
ON installmentagreement.Id=installments.Id
LEFT JOIN rentagreement
ON property.PId=rentagreement.PId
WHERE property.PId=39

This is the SELECT query that works as expected. I want to DELETE the result of this SELECT query. I used this query.
DELETE FROM property( SELECT * FROM property
LEFT JOIN installmentagreement
ON property.PId=installmentagreement.PId
LEFT JOIN installments
ON installmentagreement.Id=installments.Id
LEFT JOIN rentagreement
ON property.PId=rentagreement.PId
WHERE property.PId=39)

And this also.
DELETE FROM property
LEFT JOIN installmentagreement
ON property.PId=installmentagreement.PId
LEFT JOIN installments
ON installmentagreement.Id=installments.Id
LEFT JOIN rentagreement
ON property.PId=rentagreement.PId
WHERE property.PId=39

But it returns with Syntax Error. I want to covert the SELECT query into DELETE query. The DB I am using is MySQL.If there is any other better solution please suggest. Please help!
Comment: ehrm...it's a `LEFT JOIN`, so shouldn't this just be `DELETE FROM property WHERE PId = 39`?
Comment: No, Actually the table "InstallmentAgreement" and "RentAgreement" contains the foreign Key of table "Property". While the table "Installments" contain the foreign key of table "InstallmentAgreement"
Comment: use a cte, perhaps... assuming you are trying to delete from all the tables in your join.
Answer: I would recommend using aliases for clarity and more:
SELECT *
FROM property as p
LEFT JOIN installmentagreement as ia
ON p.PId=ia.PId
LEFT JOIN installments as i
ON ia.Id=i.Id
LEFT JOIN rentagreement as ra
ON p.PId=ra.PId
WHERE p.PId=39

Then you can convert easily to delete statement as follows:
delete p
FROM property as p
LEFT JOIN installmentagreement as ia
ON p.PId=ia.PId
LEFT JOIN installments as i
ON ia.Id=i.Id
LEFT JOIN rentagreement as ra
ON p.PId=ra.PId
WHERE p.PId=39

And if you wanted to delete records from some of the left-joined tables before you delete the property records, you can just as easily change the alias in the delete statement:
delete ra
FROM property as p
LEFT JOIN installmentagreement as ia
ON p.PId=ia.PId
LEFT JOIN installments as i
ON ia.Id=i.Id
LEFT JOIN rentagreement as ra
ON p.PId=ra.PId
WHERE p.PId=39

Comment: My friend this query is fine but on records it is giving me Foreign KEY constraint error. Actually the table "InstallmentAgreement" and "RentAgreement" contains the foreign Key of table "Property". While the table "Installments" contain the foreign key of table "InstallmentAgreement". Can you fix this query to solve this constraint please. According to the error, what I understood is that first I have to DELETE the rows from the tables which contain foreign keys, i.e. "RentAgreement" , "Installments", "InstallmentAgreement" and then from the table property.
Comment: Delete in this order - ra, ia, i and p.
Comment: Tried that. Still no luck. ERROR " Cannot delete or update a parent row: a foreign key constraint fails (`pak`.`installmentagreement`, CONSTRAINT `installmentagreement_ibfk_1` FOREIGN KEY (`PId`) REFERENCES `property` (`PId`))"
Comment: If you are deleting ia before p, this error will not show up.
Answer: MySQL supports deleting from multiple tables in one statement, but you need to specify the tables you want to delete from:
DELETE p, ima, i, ra
    FROM property p LEFT JOIN
         installmentagreement ima
         ON p.PId = ima.PId LEFT JOIN
         installments i
         ON ima.Id = i.Id LEFT JOIN
         rentagreement ra
         ON p.PId = ra.PId
WHERE p.PId = 39;

Of course, you don't have to include all four tables after the DELETE, just the ones you want to delete from.
Comment: My friend this query is fine but on records it is giving me Foreign KEY constraint error. Actually the table "InstallmentAgreement" and "RentAgreement" contains the foreign Key of table "Property". While the table "Installments" contain the foreign key of table "InstallmentAgreement". Can you fix this query to solve this constraint please. According to the error, what I understood is that first I have to DELETE the rows from the tables which contain foreign keys, i.e. "RentAgreement" , "Installments", "InstallmentAgreement" and then from the table property.
Comment: @HaseebAhmed . . . I don't know if it would make a difference, but you could try `delete ra, i, ima, p`.  You may have other records that are generating the foreign key problems.
Comment: Tried that. Still no luck. ERROR " Cannot delete or update a parent row: a foreign key constraint fails (`pak`.`installmentagreement`, CONSTRAINT `installmentagreement_ibfk_1` FOREIGN KEY (`PId`) REFERENCES `property` (`PId`))"

DELETE all using Left join of 3 tables


Does YouTube Analytics API just give you statistics of your channel?

Question: I am wondering if there is a way that I can get statistics of other channels. I only can see the statistics of my videos. When I use other contentOwners or channels, it says it is forbidden.
Some of the statistics are for yourself like "Total viewcounts (and more) for all self-uploaded content"
But some others like "Top 10 – Most watched videos for a content owner" should work for everyone, right?
Does anyone know the solution that how can I get statistics of different channels?
Thank You
Comment: hi , do you have any solution for this ?? kindly help me out ...
Comment: No, I could not find any solution for this. I am still looking forward to the answer.
Answer: YouTube Analytics API is only for videos on your own channel, or, if you are a content owner, any of your channels or claimed videos. It reflects most of the data that you can see on https://www.youtube.com/analytics Likewise, that data is only available to yourself.
What is available though, is the "statistics" part of the YouTube Video API. Here you can get the data that's available on the watch page. For example:
<code>GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=9bZkp7q19f0&key={YOUR_API_KEY}
</code>
Returns
<code>{
  "kind": "youtube#video",
  "etag": "\"gMjDJfS6nsym0T-NKCXALC_u_rM/cCAW8VtIzXW5zJKDbjuP9BMWnt4\"",
  "id": "9bZkp7q19f0",
  "statistics": {
    "viewCount": "2072823300",
    "likeCount": "8559755",
    "dislikeCount": "1090659",
    "favoriteCount": "0",
    "commentCount": "5247867"
  }
}
</code>
Here is the reference to the YouTube API with a neat little "Try it" section in the bottom to play around with:
https://developers.google.com/youtube/v3/docs/videos/list#try-it


definition errors in Allgro 5 'multiple definition of ... first defines here ...'

Question: i try to compile my allegro 5 program but i get this for some reason
i want to make sort of an engine like structure so i made an app class to make it easier to make game for like ludum dare
so you will make a class and make it inherit from app and just fill out the update init and draw methods
i am really a beginner in compiling from the terminal (i use linux)
my build script looks like this
gcc src/*.cpp build/Game $(pkg-config allegro-5 allegro_font-5 --libs --cflags)
./build/Game
pause
hope i get an answer
/usr/bin/ld: /tmp/ccbdAHA8.o: in function `Pislify::DefaultWindowConfig()':
main.cpp:(.text+0x0): multiple definition of `Pislify::DefaultWindowConfig()'; /tmp/ccwYzbn9.o:Engine.cpp:(.text+0x0): first defined here
/usr/bin/ld: /tmp/ccwYzbn9.o:(.data.rel.ro._ZTIN7Pislify4GameE[_ZTIN7Pislify4GameE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
collect2: error: ld returned 1 exit status

my code :
Engine.hpp
#ifndef ENGINE_HPP
#define ENGINE_HPP

#include <allegro5/allegro5.h>
#include <allegro5/allegro_font.h>

namespace Pislify
{
    struct WindowConfiguration
    {
        int WindowWidth;
        int WindowHeight;
        char* WindowTitle;
        int FPS;
    };
    WindowConfiguration DefaultWindowConfig()
    {
        WindowConfiguration conf;
        conf.WindowWidth = 1280;
        conf.WindowHeight = 720;
        conf.FPS = 60;
        conf.WindowTitle = "game";
    }
    class Game
    {
        WindowConfiguration config;
        void Start();

        ALLEGRO_TIMER* timer;
        ALLEGRO_EVENT_QUEUE* queue;
        ALLEGRO_DISPLAY* disp;
        ALLEGRO_FONT* font;

    public:
        ALLEGRO_EVENT event;
        Game(WindowConfiguration c);
        Game(int w,int h,char* t);
        virtual void Init(){}
        virtual void Update(){}
        virtual void Draw(){}
    };
}

#endif

engine.cpp
#include "Engine.hpp"
using namespace Pislify;
void Game::Start()
{
    //Initialize allegro
    al_init();
    al_install_keyboard();

    //initalize Allegro's Vars
    timer = al_create_timer(1.0 / config.FPS);
    queue = al_create_event_queue();
    disp = al_create_display(config.WindowWidth, config.WindowHeight);
    font = al_create_builtin_font();

    //some more al config
    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_display_event_source(disp));
    al_register_event_source(queue, al_get_timer_event_source(timer));

    //game loop
    Init();

    bool ShouldClose;
    al_start_timer(timer);

    while(!ShouldClose)
    {
        al_wait_for_event(queue, &event);

        Update();

        //time to draw? draw!
        if(event.type == ALLEGRO_EVENT_TIMER)
        {
            Draw();
        }

        //close Window?
        if((event.type == ALLEGRO_EVENT_DISPLAY_CLOSE))
        {
            break;
        }
    }
    al_destroy_font(font);
    al_destroy_display(disp);
    al_destroy_timer(timer);
    al_destroy_event_queue(queue);
}

Game::Game(WindowConfiguration c)
{
    config = c;
    Start();
}

main.cpp
#include "Engine.hpp"

using namespace Pislify;
int main()
{
    Game g(DefaultWindowConfig());
    return 0;
}

Answer: Since you're including Engine.hpp in multiple source files, you have to mark it as inline. Doing so will allow the function to be defined multiple times.
namespace Pislify
{
    //...
    inline WindowConfiguration DefaultWindowConfig()
    {
        WindowConfiguration conf;
        conf.WindowWidth = 1280;
        conf.WindowHeight = 720;
        conf.FPS = 60;
        conf.WindowTitle = "game";
    }
    //...

Quote from https://www.cplusplus.com/articles/2LywvCM9/
5. By marking it as inline, you can put a function definition in a header file (i.e. it can be included in multiple compilation unit, without the linker complaining)


Understanding residue of meromorphic 1-form.

Question: I didn't understand this residue computation of the product of a meromorphic function $f$ on an algebraic curve and meromorphic 1-form $\omega \in L^{(1)}(-D)$ :
$Res_{p}(f \omega) \quad = \text{ coefficient of the term } \dfrac{1}{z_{p}}dz_{p} \text{ of }$ $$\sum_{k}a_kz_p^k\sum_{n = D(p)}^{\infty}c_nz_p^ndz_p \quad = \sum_{n=D(p) }^{\infty}c_na_{-1-n} $$
This is an extract taken from Rick Miranda's book on Riemann surfaces and algebraic curves, page 187. I did not understand the last equality, if someone could explain it with details I would be grateful. Thank you.
Answer: Haha, I'm actually reading this text now as well. I just read this section. Note that
$$
\left(\sum_ka_kz_p^k\right)\left(\sum_{n=D(p)}^{\infty}c_nz_p^n\right)=\sum_{k,n}^{\infty}a_kc_nz^{k+n}_p,
$$
so the coeffient we're looking for is the coefficient where $k+n=-1$, or
$$
\sum_{k+n=-1}a_kc_n=\sum_{n=D(p)}^{\infty}a_{-n-1}c_n.
$$
It's just using the common identity
$$
\left(\sum_{n=1}^{\infty}a_n\right)\left(\sum_{k=1}^{\infty}b_k\right)=\sum_{n,k=1}^{\infty}a_nb_k
$$
which is useful to know.
I hope this helps.
Comment: Ok ! Thank you ! Very clear ! :)


What preparations can I do before I paint the ceiling of my bathroom?

Question: I want to paint my bathroom ceiling, but there are some bathroom fixtures that I can't remove and that will be very hard to cover up.
What preparations can I do, and what should I keep in mind when painting? Is there anything I can do to avoid paint splatter on furniture, walls and floors?
My bathroom is shown in the picture below. I can not remove the shower walls, the lights above the mirror or the WC (obviously). (It's possible to remove the shower walls, but I don't want to do it in case I'll mess something up when mounting them back up)
The ceiling is made of drywall (though I don't think it's of any relevance).

Please feel free to edit my grammar / choice of words.
Answer: Any home improvement centre sells two essential things for this: painter's tape and plastic sheeting. Buy a thin plastic for the walls, and thicker one for the floor (or, better yet, use drop cloth for the floor). Buy wide painter's tape, it's much easier to use it to attach plastic sheets to walls, shower doors, etc.

Tape and cover everything. There will definitely be splatter, so cover every square inch of every surface. It will take only a half an hour or so, for a bathroom of this size, especially if you have someone to help you to spread and hang the plastic.
Just hang plastic sheets from top of the wall to the floor, completely covering any wall-attached fixtures, etc. Use painter's tape first to tack the sheet to the wall, and then use a long strip to completely cover the area where the wall meets the ceiling. Make sure sheets overlap, so there is complete coverage.

Cover the glass shower walls completely, from both sides. Again, just hang a sheet of plastic on them, attaching it with painter's tape.

Cover the floor completely. Use drop cloth, or thick plastic sheeting. Drop cloth is preferrable as it's not slippery, and will absorb any paint splatter or minor spills.

Pull out potlights' trim. They are usually just spring-loaded, and will go out if you pull a bit. No need to remove the pot lights, and don't cover them completely so they won't overheat, but pull the trim out so you can paint around their holes freely.

Use a brush to paint corners and along the wall border.

Use a pole and a roller to paint the ceiling (and wear a hat, otherwise your hair will be full of paint splatter. Don't ask how I know this).
Comment: Excellent and thorough advice.  If an accident occurs (something becomes uncovered by accident and a spot or two occurs), most of those surfaces will be easy to clean if done quickly, or scrapped carefully with a razor blade.  Also, if you need to leave the room during or just after the painting, make sure to not track anything to the next room that splattered onto the drop cloth.  (A smaller drop cloth just outside the room might be helpful)
Comment: Don't know what type of bulbs are above the sink but you should probably keep them off so you don't melt the plastic to them. Use an old lamp with a 150W bulb to light the room while you work.
Comment: [Pull down masking films](https://tinyurl.com/ya5rs4m3) are convenient when covering walls!
Answer: To expand a little on haimg's answer.
Cover the floor first, even extending the covering up the walls a little to catch spills. Then cover the walls.
The most important step, is prepping the surface to be painted. Scrap and sand any rough spots.
Use a cleaner, such as borax or TSP to clean any residues.
Patch holes using a plaster material. Not rubber based spackling paste, that tends to shrink.
After the surface is smooth, prime with a mildew and stain resistant primer to allow the final coats to cover evenly.


Closing incoming connection in Apache/PHP

Question: I've got a script which receives large file uploads via a PUT request. These files have some processing done on the fly as they are uploading. Sometimes we can detect that a file is invalid in the first few bytes so we die() with an error message. The only problem is that the client still sends the rest of the data which is a huge waste. Is there a way to shutdown the incoming connection?
Code:
$fp = fopen('php://input', 'rb');

// Do some data checking here
if( <invalid> ) {
    fclose($fp);
    die('Error');
}

stream_socket_shutdown looked like it might do the job but it has no effect.
Is there any way to do this? Even if I have to write an extension just for this?
Comment: http://php.net/manual/en/features.connection-handling.php
Answer: You may want to give the following a shot and see if this terminates the connection properly:
$fp = fopen('php://input', 'rb');

// Do some data checking here
if( <invalid> ) {
    fclose($fp);
    header("Content-Length: 0");
    header("Connection: close");
    flush();
    die('Error');
}

Comment: Thanks for the suggestion. I'll give this a try and report back.


Selecting distinct rows from a table where 2 columns have the same foreign keys (inversely included)

Question: I have a message table with fields id, time, isread, message, messagestatus, receiver and user. I want to retrieve the latest message (based on time) a user with an id of 1 sent or received to any other users.
for example if a user with id 1(sender) sends a message to user with id 2(receiver) and if user with id 2 sends user with id 1 a message. only the most current message sent between both of them should be picked
My already existing table looks like this :

i tried SELECT *  from (SELECT MAX(time) as time ,sender,receiver from message group by sender,receiver) as f
where receiver=1  or sender=1 limit 20
but it only displays the sender, receiver and time while other columns like message, id, messagestatus and read are omitted, plus it does not find the general last message sent between two users, but instead finds the most recent message sent between user1 and another user when user1 is the sender and the other user is the receiver and also finds the last message when user1 is the receiver and the other user is the sender.
Comment: Please share the sample input and expected output.
Comment: If you only ever want to do this for one user, and thus only ever return one record, just use `ORDER BY time DESC LIMIT 1` instead of using aggregation. If you want this for multiple users in a single query, use windowed / analytic functions, and update your question to clarify that.
Answer: If you want the most recent messages sent or received by user "1", then use filtering, not group by:
select m.*
from messages m
where 1 in (m.sender, m.receiver) and
      m.time = (select max(m2.time)
                from messages m2
                where (m2.sender = m.sender and m2.receiver = m.receiver) or
                      (m2.receiver = m.sender and m2.sender = m.receiver)
               );

If two messages could have exactly the same timestamp, then:
select m.*
from messages m
where 1 in (m.sender, m.receiver) and
      m.id = (select id
              from messages m2
              where (m2.sender = m.sender and m2.receiver = m.receiver) or
                    (m2.receiver = m.sender and m2.sender = m.receiver)
              order by m2.time desc, m2.id desc
              limit 1
             );

Comment: you are a genius sir
Comment: Just rechecked the query sir, there is a slight problem.  https://imgur.com/a/lbsEuBy  since user1 (sender) sent a message to user3 (receiver) and user3(sender this time) also sent a message to user1 (receiver this time), it should also check the most recent message in the  conversation between them as a whole
Comment: @Oto-obongEshiett . . . That is what the subquery is doing.
Comment: if the subquery is supposed to get a single conversation from user one and any other user, then it is not working 100% , because it is getting me last message user1 sent and also the last message  he received from a particular user (e.g if user1 sent a message to user2 and user2 sent a messge to user1) ..... please sir, try to make a dummy table, you would understand the problem better :(
Comment: Can you set up a db<>fiddle or something similar?  The only issue is that you might have two messages at exactly the same time.
Comment: Noticed i cannot create a foreign key constraint in the fiddle. http://sqlfiddle.com/#!18/a7540/1 . but i noticed the problem as you said came from the time (they are exactly the same).  imgur.com/a/lbsEuBy , so in a case where i have a problem like this, even tho is less likely to happen, how do i ask postgres to pick up the one with the larger id out of the two.
Comment: @Oto-obongEshiett . . .I added that to my answer a while ago (just didn't format it right).
Comment: ohh alright thank you, seen. it works perfectly now. I am grateful


Get intersection Ray with square

Question: I have a class Ray and Square
public class Rayo {
public Point origen;
public Vector direction;

Square{
X,Y,Widht, height;
}

I need intersection between this two, how? my code crossProduct in java is
public static Vector productoCruz(Vector a, Vector b) {
        return new Vector(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
    }

To apply the product point you need two vectors, and I only have 1 (the ray vector), where do I get the other vector?
Answer: The best algorithm depends on the condition like whether or not the square is axis aligned for example. I'm gonna discuss the more general case which can find find intersection for any arbitrary oriented square. The algorithm works by first checking the intersection of ray with the plane containing the square or rectangle etc. Then check if the ray is within bounds of the square.
For this you require the following information
Ray's in the form $R =e+td $ where $e$ is the origin or eye point and $d$ is the direction vector.
Secondly you need to define your square by using the following information

Poisition - This might be the vector to the center or any corner of the square. The algorithm I'm describing assumes it is one of the corners.
Normal - Self explanatory.
Width and Height not as scalars but as vectors. These can be called the two edge vectors. I will denote them as $e1$ and $e2$. Note that both edge vectors need to grow outward from the corner of the square chosen in point 1.

After you have the following information you first need to compute Ray - plane intersection. The plane being where your square lies. This is done as follows. We know the point normal form of a plane as,
$(p-p1).n= 0$
If we suppose $p$ is our ray here and $p1 = position$, then we will have,
$(e+td - p1).n=0$
$(e+td - p1).n=0$
$e.n + td.n - p1.n = 0$
$t = p1.n - e.n/d.n$
$t = (p1-e).n/d.n$
If $t \geq 0$ then we have an intersection. Now all we need to do is check whether the ray lies inside the square or anywhere else on the plane. This is easy to do.
$intersect\_point = e + td$
$v = intersect\_point - p1$
$width = ||e1||$
$height = ||e2||$
$proj1 = v.e1 /width $
$proj2 = v.e2 / height$
$if((proj1 < width \;\&\&\; proj1 > 0) \;\&\&\; (proj2  < height \;\&\&\; proj2 > 0) )$
$return \, true$
Note that the above assumes that the edge vectors grow outward from the corner, i.e. A square with the corners A,B,C,D in clockwise fashion starting from  the top left. If we choose corner $A$ then the edge vectors are $\vec{AB}$ and $\vec{AD}$.
Comment: The normal is for the square. you need to define it when initializing the square. It's a necessary information required in the Square structure. `Normal` is a vector that is perpendicular to the plane containing the square. If for example your square is located at `1,0,0` looking left, the normal is gonna be `-1,0,0`. The normal can be caluclated by taking the cross product of the two edge vectors e1 and e2.
Comment: Well for sphere the intersection procedure is different altogether. These are basic intersection procedures given in almost any good book for graphics and games. I'd recommend you to read "Fundamentals of Computer Graphics by Peter Shirley" or "Essential maths for games by Van Verth".
Comment: That's a great step to be honest. Most of peter shirley books include raytracing stuff, I have personally read the above one so i can tell it's a good book. These two are more than enough for now. For more advanced stuff there is "Physically Based Rendering"
Comment: the p1 is position to ray?, also this should resolve with crossProduct ?
Comment: p is the ray direction and p1 is the vector describing the position to the square. No need for cross product in this method
Comment: how i get the normal (n)  to this t=(p1−e).n/d.n
Comment: I'm new, I do not know much about graphics, can you explain how I get the normal please?
Comment: i edited my question,
I can not graph the square, I can only graph spheres
Comment: thanks for the recommendation, I will leave my project to understand more about graficacion,
could you recommend more books please, I am very interested in this topic.

Get intersection Ray with square


Multiple antrun tasks in maven

Question: How would you execute ant tasks at different phases in a maven build cycle?
Answer: I used this in the build/plugins section
<code><plugin>

    <artifactId>maven-antrun-plugin</artifactId>
    <executions>

        <execution>
            <id>clean</id>
            <phase>clean</phase>
            <configuration>
                <tasks>
                    <echo message = ">>>>>>>>>>>>>>>>>>>>>>>>>>clean"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>

        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <configuration>
                <tasks>
                    <echo message = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>compile"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>

        <execution>
            <id>package</id>
            <phase>package</phase>
            <configuration>
                <tasks>
                    <echo message = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>package"/>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>

    </executions>

</plugin>
</code>

Multiple antrun tasks in maven


Parallel Run and Task-Core Assignment

Question: I use the script suggested in Run parallel multiple commands at once in the same terminal in order to run some applications in parallel. It works fine, however, I want to stick each application to a single core and my question is how to make sure that each of those applications runs on a distinct core? Where to insert "taskset -c"s ? Before each application's run command inside the script and/or before the script's command itself when I run it from the terminal??
Answer: Newer versions of GNU Parallel supports progressing ctrl-c.
Linux is pretty good at scheduling tasks, so only use taskset after you have timed that it really does benefit performance.
To get a number 0..n-1 (e.g. 0..7) the tempting solution is:
# This is wrong
... | parallel taskset -c $(({#}%8)) {}

This, however, will only work if jobs take exactly the same amount of time. With 8 jobslots if job 1..7 takes 2 seconds, and job 8 takes 1 second. Then job 9 will be run while job 1 is running.
A better solution is to define your own replacement string that counts jobslots 0..7:
echo '--rpl "{%%} \$_=slot()-1"' >> ~/.parallel/config
... | parallel taskset -c {%%} {}

Comment: @Ole Tange Can you add an option to parallel so it can do this itself? Also, you might want to disclose you're the developer of parallel (for which I thank you)
Comment: This isn't quite going to work, because {#} substitutes for the overall job number, not the current slot the job is running in.  So if you want to run 1000 jobs on eight processors, when the ninth job starts up, taskset will display a "taskset: failed to set pid 0's affinity: Invalid argument" error because it will try to run "taskset -c 9", which doesn't exist.  Run "parallel taskset -c $(({#}%7)) {}" instead.
Comment: Thanks, this is excellent. Note that if you do use {%}, some processes might not execute as the core numbers start at 0 - so, say if you have 8 cores, the 8th core is core 7 whereas {%} will produce 8 (and result in an affinity error). I used `-j7` (i.e., num cores - 1) along with {%} to circumvent the issue. Yes, you won't get to use core 0, but in that case, you might be better off with the `taskset -c $(({#}%7)) {}` method.

Parallel Run and Task-Core Assignment


Integers seen as a continuous shape

Question: In a popular maths book I find this sentence, in the context of an explanation of the difference between discrete and continuous, especially as regards groups:

The group of integers is discrete; that is to say, its elements do not
  combine into a continuous geometric shape in any natural sense.

I have no problem with the sentence in itself, within the limits of a popular exposition. I was just asking myself: Is there a "non-natural", but non-trivial, sense in which integers can be seen as forming a continuous "geometric shape"?
Answer: There are countably many integers ($\mathbb{Z}$) and rationals ($\mathbb{Q}$), and hence a 1-1 correspondence between the integers and the rationals. The rational numbers are dense in $\mathbb{R}$ so you might be able to think of $\mathbb{Q}$ as a "line", and by countability also $\mathbb{Z}$.
Comment: Perhaps a very "hole-y" line. You could also map it to the unit circle by a bijective argument with $\mathbb{Q}$ again. Let $\frac{p}{q}$ be a rational number in lowest terms. Consider the map $\frac{p}{q}\mapsto e^{2\pi ip/q}$. If I recall correctly, this is a dense subset of the unit circle. Again, this is has holes but you can't get around that.
Answer: The concept of continuity I think you're trying to express is captured by the topological concept of connectedness. There do exist countable connected spaces (even Hausdorff ones), but most constructions are odd. If you applied something like this to $\mathbb{Z}$ there wouldn't be a good notion of distance like there is in the standard topology of $\mathbb{Z}$ (every countable metric space is disconnected).

Integers seen as a continuous shape


Definition of notation $\mathbb Z_n$

Question: What does the notation $\mathbb Z_n$ mean, where $n$ is also an integer. I have only seen $n$ being a positive integer up to now. some examples are $\mathbb Z_2$ or $\mathbb Z_3$
This is the context: How to prove $x^{2}+x=1$ has a solution in $\mathbb{Z}_{p}$ if and only if $p=5$ or $p\equiv \pm1\bmod 5$
Comment: Do you know what a congruence class is?
Comment: $\Bbb Z_n$ usually denotes either $\,\Bbb Z/n\Bbb Z$ or its (isomorphic) ring of normal forms $\,\{0,1,2,\cdots,n-1\},\,$ see [this answer](https://math.stackexchange.com/questions/646576/isomorphism-of-mathbbz-n-mathbbz-and-mathbbz-n).
Answer: $\mathbb{Z}_n$ is another (shorter) name for $\mathbb{Z}/n\mathbb{Z}$, the ring of residue classes modulo $n$. A residue class modulo $n$ is the set of all integers which give the same rest when divided by $n$. There are exactly $n$ residue classes, corresponding to the $n$ reminders on division by $n$, $0$ to $n-1$.
The key point is that the reminder of $i+j$ on division by $n$ is the sum of the individual reminders, and the analogue is true for the product. So no matter which member of two given residue classes you choose, the sum will always be in the same residue class, as will be the product.
It only makes sense if $n$ is an integer $\ge 2$. If $n$ happens to be prime, it is a field, that's why those are most interesting. Strictly speaking you could also write $\mathbb{Z}_1$, but that would only contain one element.
Comment: And it is somewhat unfortunate when $n$ is a prime, since most people (from what I understand) use $\mathbb{Z}_p$ to indicate the $p$-adic integers and $\mathbb{Z}/(p)$ (or something to this effect) for the usual finite ring.
Comment: $\Bbb Z_1$ certainly does "make sense" - it is the zero ring $\{0\}$ where $1 = 0$. Also $\Bbb Z_n$ may denote the isomorphic ring of normal forms $\{0,1,2,\ldots,n-1\},\,$ see my comment on the question.
Answer: $p\equiv\pm1$ (mod 5) means (roughly speaking) that the remainder when dividing $p$ by 5 is 1 or -1. So $p$ could be 4,6,9,11,14, etc. $p$ would still be a positive integer though.

Definition of notation $\mathbb Z_n$


remove elements from a list in ml

Question: I´m trying to write a function that produces a new list containing the given list without the element x.
Moscow ML says that some cases are unused in this match.
fun delete (x,list) = delete(x,[])
 |delete(x,(first::rest)) = if first = x then delete(x,rest) else first::delete(x,rest)

Answer: Here's how I'd do it on Standard ML::
fun delete (item, list) =
    case list of
    []=>[]
      | xs::ys => if item = xs then delete(item,ys)
          else xs::delete(item,ys)

Without using cases:
fun delete (item, list) = List.filter(fn x => x <> item) list

Nevermind the polyequal signs.
Comment: How do I write it without case list of...? Think my code look quiet the same so maybe idon´t do to much wrong:)
Comment: If you don't want to use cases, then I'd suggest you do the following: fun delete (item, list) = List.filter(fn x => x <> item) list
Answer: When a call to delete is performed, the patterns defining the function are (essentially) tried in order. Since the first pattern already matches every list, the second pattern will never be reached. That's why the compiler complains.
In other words, you either have to reorder your cases, or better, make them disjoint (e.g. by replacing list with [] in the first case).
Extra hint: The right-hand side of the first case also seems wrong. This will always go into an infinite recursion.
Answer: That's because your first case matches any list, so the second case will never be used.
Remember that the case are tried in the order they're written, not selected based on which is the "best" match.
You also have a slight problem of infinite recursion with
delete (x,list) = delete(x,[])

Since list will match [], it will just recurse forever.
If you delete something from an empty list, the result should be the empty list.
You can do one of two things.
Either move the non-empty case first:
fun delete (x, y:ys) = if y = x then delete(x, ys) else y::delete(x, ys)
  | delete (x, list) = []

Or, more common, make the first case only match the empty list:
fun delete (x, []) = []
  | delete (x, y:ys) = if y = x then delete(x, ys) else y::delete(x, ys)

Comment: I am sorry, what is this part `delete (x, list) = []` really for? I could not understand this part's role in this recursive way. THanks
Comment: @Huzo  It's the recursive base case, which does nothing. I kept the name "list" from the original code. You could also write `[]`, or `_`.

remove elements from a list in ml


How to send QKeyEvent to specific qml item?

Question: I'm trying to send a custom QKeyEvent (like Keypress key B) to an item (like TextField) in my QML file. This is what I've wrote which it doesn't work. It seems that the item (TextField) doesn't get my event (I'm assuming this because no B characters appended to my TextField's text). I'm capturing click signal in my ClickHandler class and then in my handleClick slot, I try to post an custom event to my focused item which in here is a TextField.
ClickHandler.h
class ClickHandler : public QObject
{
    Q_OBJECT
    QQmlApplicationEngine* engine;
    QApplication* app;
public:
    explicit ClickHandler(QQmlApplicationEngine *,QApplication* app);

signals:

public slots:
    void handleClick();
};

ClickHandler.cpp:
#include "clickhandler.h"
#include <QMessageBox>
#include <QQuickItem>

ClickHandler::ClickHandler(QQmlApplicationEngine* engine, QApplication* app)
{
    this->engine = engine;
    this->app = app;

}

void ClickHandler::handleClick()
{
    QObject* root = engine->rootObjects()[0];
    QQuickItem *item = (root->property("activeFocusItem")).value<QQuickItem *>();
    if (item == NULL)
        qDebug() << "NO item";
    QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,Qt::Key_B,Qt::NoModifier);
    QCoreApplication::postEvent(item,event);
}

main.cpp:
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject* root = engine.rootObjects()[0];
    ClickHandler* ch = new ClickHandler(&engine, &app);
    QQuickItem* button = root->findChild<QQuickItem*>("button");

    QObject::connect(button, SIGNAL(clicked()), ch, SLOT(handleClick()));

    return app.exec();
}

main.qml:
ApplicationWindow {
    objectName: "rootWindow"
    visible: true
    Column {
        TextField {
            id: textId1
            objectName: "text1"
            text: "text1 message"
            focus: true
        }

        TextField {
            id: textId2
            objectName: "text2"
            text: "text2 message"
        }
        Button {
            objectName: "button"
            text : "Click me";
        }
    }
}

Comment: Hi @Shnd! Did you solve your last issues? Did you see my answers? I see you're using here `activeFocusItem` so I suppose some of your old questions are already solved. If so, please mark those questions as solved or ask for help again.
Comment: Yes @Tarod. actually i solved many of my problems thanks to you and some other folks. I'm trying to find some spare time in order to write my own answer for those questions. But put all this aside, Thank you for all your time you have put on my questions and give me great responses. :)
Answer: If you implement the onPressed handler you can see where the problem is.
ApplicationWindow {
    objectName: "rootWindow"
    visible: true
    Column {
        TextField {
            id: textId1
            objectName: "text1"
            text: "text1 message"
            focus: true

            Keys.onPressed: {
                console.log("textId1: " + event.key + " : " + event.text)
            }
        }

        TextField {
            id: textId2
            objectName: "text2"
            text: "text2 message"

            Keys.onPressed: {
                if (event.key === Qt.Key_B) {
                    console.log("I like B's but not QString's")
                }
            }
        }

...

This code prints qml: textId1: 66 : because the text for that key is empty.
You need to create the event using something like this:
Qt::Key key = Qt::Key_B;
QKeyEvent* event = new QKeyEvent(QKeyEvent::KeyPress,
                                 key,
                                 Qt::NoModifier,
                                 QKeySequence(key).toString());

Comment: Thank you, that was exactly what the problem was. Could you just tell me why it is not sufficient to use Qt::Key_B ? doesn't it mean you want to send key press event B (whatever key B means to the item)? Could you give me a practical example were you want to map key B to some other text ?!
Comment: I've just updated the answer. Actually, set the text in `QKeyEvent` is not always necessary. You could just get the `key` to do different tasks. For example, get the left cursor key `Qt.Key_Left` and move an `Item`. About your last question, I'm afraid I don't have a good example to give you :( I suppose It really depends on what you want to achieve.


Display an image in Java Swt?

Question: i'm new to Java and Swt. I would like to simply display an image Splash Screen of my application. I can't find any "image widget".
How can i do ?
Thanks
Answer: I don't believe there is an "image widget" in SWT. Rather, you can render the image in SWT widgets.
For example, the Label widget:
<code>...set up...
Shell shell = new Shell(SWT.ON_TOP);
Label label = new Label(shell, SWT.NONE);
label.setImage(someImage);
...more set up...
shell.open();
</code>
In regards to your overall goal: SWT splash screen example

Display an image in Java Swt?


Java: add a list to another list without copy the reference

Question: I want to make each line read from the csv as a sub_list and add such sub_list to a master_list.

so it would be something like:
[[line 1] [line 2] ....[last line]]
How to make sure the sub_list added in the master_list is not affected by the changes in the original sub_list. I understand it's something to do with shallow vs deep copy. What is the correct way to do it. The reason for doing in this way is because I might use the sublist for other different operations elsewhere. once I need to do so, I need to clear the content inside it as an empty list. Hence I want to maintain the use of the same list for different tasks.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVReader {

    public static void main(String[] args) {

        String csvFile = "E:\\country.csv";
        String line = "";
        String cvsSplitBy = ",";
        List<String> sub = new ArrayList<String>();
        List<List> master = new ArrayList<List>();

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] country = line.split(cvsSplitBy);
                sub.add(line);
                master.add(sub);
//              System.out.println(sub);
                sub.remove(0);

//                System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(master);

    }

}

this prints out empty list "[]".
Comment: Can you take a step back and first tell us what this code is supposed to be doing?
Comment: Each sublist inside the master list needs to be a different list because it has different content. Trying to reuse the same sublist is just causing you problems.
Comment: You can always put `List sub = new ArrayList();` inside the `while` loop and remove the call to `sub.remove(0);`
Comment: please see my update on the question. thanks
Comment: @ Anoop R Desai your method will certainly works but I every time when looping i have to create a new list. i prefer a strategy like: set sublist = current line -> add sublist to the master_list -> set sublist [] as empty for next time looping. how to do it?
Comment: Why do you want to make sublist empty at the end? In any case, creating a new sublist every at every iteration does not imply you have many lists in memory - they get garbage collected anyway.
Comment: because I might use sublist for other different operations elsewhere. once I need to do so, I need to clear the content inside it as an empty list. Hence I want to maintain the use of the same list for different tasks.
Comment: In that case, you can create a clone of sublist inside the loop, add the cloned list to the `master_list` and then empty the sublist. To create a clone, have a look [here](https://stackoverflow.com/a/6536128/1898437). But as @TimBiegeleisen mentioned, you might want to take a step back and review.
Comment: if you don't like working with `List>`, you can use two dimention array `String[][]`
Comment: @ Anoop R Desai  I think the clone method should be 95% similar to my desired strategy. I tried this: new_sub = sub.clone() but it would work. what is a correct way for using clone() method?
Answer: Try move declaration of sub variable onto the while block.
    String csvFile = "E:\\country.csv";
        String line = "";
        String cvsSplitBy = ",";
        List<List> master = new ArrayList<List>();

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] country = line.split(cvsSplitBy);
                List<String> sub = new ArrayList<String>();
                sub.add(line);
                master.add(sub);
//              System.out.println(sub);
//              sub.remove(0);

//                System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(master);

Comment: your method will certainly works but I every time when looping i have to create a new list. i prefer a strategy like: set sublist = current line -> add sublist to the master_list -> set sublist [] as empty for next time looping. how to do it?
Answer: Two Points:-
1 - Change your master list as below. you should not create generic list (Raw type). If you create list as raw type, You will be able to enter any data type input. It will create issue as there can be multi data type list.
2 - when you enter in while loop, create/assign new reference to sub list and then add it to master.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVReader {

    public static void main(String[] args) {

        String csvFile = "E:\\country.csv";
        String line = "";
        String cvsSplitBy = ",";
        List<String> sub = new ArrayList<String>();
        List<List<String>> master = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] country = line.split(cvsSplitBy);
                sub = new ArrayList<String>();
                sub.add(line);
                master.add(new ArrayList<String>(sub));
//              System.out.println(sub);
                sub.remove(0);

//                System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(master);

    }

}

Comment: does this method empty the existing sub? is this equal to "set current sub as []" ?
Comment: what will happen to the old sub? does it override the old sub, which is equal to set old sub as empty list?
Comment: first old sub will be stored in master. we are using new operator while saving in master so it will create a deep copy of sub while storing in master. then whie loop will empty it. run the code in debug mode you can check it.
Comment: yes. this partially solve the problem. But please take a look at my original question. I simply want to use and update one single sublist without constantly creating new different lists. I want to make a deep copy of the current sub into the master, then reset it to empty at the end of the while loop for next looping.
Answer: You can do this
public static List<String[]> getTestData(String fileName) {
    List<String[]> records = new ArrayList<String[]>();
    try {
        String record;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
        while ((record = file.readLine()) != null) {
            System.out.println(record);
            String fields[] = record.split(",");
            records.add(fields);
        }
        file.close();
        return records;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


Ubuntu Live CD not so persistent (Unetbootin)

Question: I have the following problem. I am trying to make Ubuntu Live USB (actually Lubuntu, but problem is the same with Ubuntu) with the persistency option. I use Unetbootin (both on Windows and Ubuntu problem is the same), set all options - and have working USB stick with Live CD. The problem is, even if I set preserved space to 1 Gb, I can't save any changes made on USB.
http://ubuntuhandbook.org/wp-content/uploads/2013/07/Unetbootin.png
My test is the following - I make USB stick with Live CD, I Try Ubuntu without installing, type command:
<code>sudo adduser cheshire
</code>
fill all details, I have two folders in /home/ catalogue - ubuntu and cheshire. But after reboot I have again only /ubuntu/ catalogue. Actually I really need USB stick which will preserve this data - what I need the most is the openssh-server option.
Answer: there is a program called etcher, for linux, windows, and osx. it seems to work really well for this job, although the options are limited.


How to get data from JSON string?

Question: I have a JSON string like this:
{
    "response":[2,
        {
            "id":"187",
            "name":"John",
            "surname":"Corner"
        },
        {
            "id":"254",
            "name":"Bob",
            "surname":"Marley"
        }
    ]
}

How can I parse it using GSON lib in Java?
I tried:
static class SearchRequest {
    private Names[] response;

    static class Names {
        private int id;
        private String name;
        private String surname;
    }
}

but it doesn't works :(
Comment: Do you see exceptions due to your JSON string, I modified it and the program worked correctly. Take a look at my answer.
Answer: response array contains not only Names, it also contains an integer value: response[0]=2.
So you must use something like
private Object[] response;

ADD:
I think, you have no need to change your JSON, because your response is private, so you should use getters:
static class SearchRequest {
    private Object[] response;

    static class Names {
        private int id;
        private String name;
        private String surname;
    }

    public List<Names> getNames() {
        List list = new ArrayList();
        list.addAll(Arrays.asList(response));
        return (List<Names>) list.subList(1, response.length);
    }

    public int getAmount() {
        return (Integer) response[0];
    }

    public void setNames(List<Names> names) {
        response = new Object[names.size() + 1];
        response[0] = names.size();
        for (int i = 0, namesSize = names.size(); i < namesSize; i++) {
            response[i + 1] = names.get(i);
        }
    }
}

Comment: Oh my goodness! Yeah! Thank you very much. You are right, but Object[] response is not easy solution...I will try to edit JSON string and parse it without integer element.
Comment: Thank you very much. I understand you. In method getNames you changed a type of Object from 1 till end of Array to Names.
Comment: I don't know why but my compiler told me that it can not cast from List to List
Comment: @user1203901 Sorry, I fix it. Try now.
Answer: I prepared a sample code for testing your case, used gson-2.1.jar as library and run it correctly. I modified your JSON string by removing "2," from the beginning of response array since it caused exceptions. Take a look at and test this code:
import com.google.gson.Gson;

public class Test
{
    static class SearchRequest
    {
        private Names [] response;

        static class Names
        {
            private int id;
            private String name;
            private String surname;
        }
    }

    public static void main ( String [] args )
    {
        Gson gson = new Gson();
        String str = "{ \"response\":"
                   + "[{\"id\":\"187\",\"name\":\"John\",\"surname\":\"Corner\"},"
                   + "{\"id\":\"254\",\"name\":\"Bob\",\"surname\":\"Marley\"}]}";

        SearchRequest request = new SearchRequest();
        request = gson.fromJson( str, SearchRequest.class );
        System.out.println( "name of 1st: " + request.response [ 0 ].name );
        System.out.println( "surname of 2nd: " + request.response [ 1 ].surname );
    }
}

Output:
name of 1st: John
surname of 2nd: Marley

Comment: Yeah, thanks, I did the same ^_^. It's easier then use Object[] :)

How to get data from JSON string?


How do I show the health bars of enemies I have already scanned?

Question: If I use a Magic Lens on an enemy in battle I can see it's health bar for THAT battle and it's information is added to the Monster List. But it only appears for that battle. Is there any way for it to appear for all enemies in future battles after that point? Or do I need to scan every individual monster whose health bar I want every time?
Answer: Sadly, there's no way to do so. If you really want to know your ennemy's HP, you have to scan it again. Hopefully, the circumstances where you need to do so are rare (Bosses, or need to kill an enemy with a special attack)


KEDA scaledown event take 5 minute

Question: My pods used to scale down in few seconds 20-30 but i dont know what happened now it taken 5 minute to scale down and when I added minreplica in KEDA YML  file the time from 1 to 0 pods take few seconds but for n to 1 pod it take 5 minutes what I understanded that thus HPA behaviour it take the responsability of scale down from n ->1 pod and from 1->0 pod KEDA is responsible for the event
I added this to scaledobject file but its being ignored
spec:
  scaleTargetRef:
    name: consumer-deployment
  pollingInterval: 5
  cooldownPeriod: 10
  minReplicaCount: 0
  maxReplicaCount: 5

how to reduce this time that is by default 5 minute
**Im using k8s with docker desktop **
Comment: I carefully read your response, but unfortunately, the problem hasn't been resolved yet. As you mentioned,  the role of coolInterval and pollingInterval , which have default values of 300 seconds. However, in my configuration, I have set them to a lower value, I think they being ignored or something like this.

it weird  that this problem appeared out of nowhere. I haven't made any changes to the KEDA YAML file since I created it, and it was functioning perfectly .
Answer: As mentioned in the document :

The period to wait after the last trigger reported active before
scaling the resource back to 0. By default it's 5 minutes (300
seconds).
The cooldownPeriod only applies after a trigger occurs; when you first
create your Deployment (or StatefulSet/CustomResource), KEDA will
immediately scale it to minReplicaCount. Additionally, the KEDA
cooldownPeriod only applies when scaling to 0; scaling from 1 to N
replicas is handled by the Kubernetes HPA.

Your cool down period will be dependent on pollingInterval. This is the interval to check each trigger on. By default KEDA will check each trigger source on every ScaledObject every 30 seconds. So you can minimize pollingInternal time to reduce your cool down period.
However,you can enable/disable scaling rules either by editing the replica count to 0 or you can use a single field called Pause autoscaling.
Add this below annotation to your deployment :
metadata:
   annotations:
      autoscaling.keda.sh/paused-replicas: "0"

This annotation will pause autoscaling no matter what number of
replicas is provided. The above annotation will scale your current
workload to 0 replicas and pause autoscaling. You can set the value of
replicas for an object to be paused at any arbitrary number. To enable
autoscaling again, simply remove the annotation from the ScaledObject
definition.
Comment: excuse my question I just started learnig k8 :
the pause replica config will pause HPA from autoscaling and KEDA will stay function normaly or the hole autoscaling process will stop ?
Comment: Pause autoscaling can be useful to instruct KEDA to pause autoscaling of objects, if you want to do to cluster maintenance or you want to avoid resource starvation by removing non-mission-critical workloads. Hence it will pause the whole autoscaling process. Refer to this [link](https://keda.sh/docs/2.10/concepts/scaling-deployments/#pause-autoscaling) for more information.

KEDA scaledown event take 5 minute


What bonusses does a Roman Empire and a Roman Republic give?

Question: After some time in the Roman campaign a civil war breaks out. After dealing with the senate loyalist faction I get the option to chose between a Roman Republic or an Empire.
I chose the empire option which gave me a reduction in corruption and a reduction in upkeep costs. What would the choice for a republic have given me?
Answer: Choosing the republic gives you two extra recruitment slots and a 10% discount on unit training across all provinces.
Answer: .
<code>Playing as Carthage, Empire gives: -10% unit upkeep and -25% corruption
---
And Republic gives:
2 recruitment slots and -10% discout on unit training across all provinces
</code>


Do Illusions have all passive abilities as my hero has? Even from items?

Question: I am a long time Dota Player, but still this question I can't answer.
I know that your Illus always get the lifereg of your hero and attack speed etc.
But what happes if I buy a basher ?
Do my Illus stun with their own cooldown of 1 sec for a bash or is It just me ?
So wouldn't be panthom lancer even more op with basher ?
Answer: Yes and No, Illusion benefits from a lots of passive abilities may they be granted by items or skills but not all.
You can not benefit from bashes on illusion (Bash from basher, Abyssal blade, or Barathrum's bash for example). That would be way too powerfull. For the same reason, Feedback (diffusal blade's orb effect) works on illusion but only melee one.
You can take a look on the Illusion page of the wiki which give a quite exhausitve list of the passive your illusions benefit (or dont benefit) from.
Comment: okay, thank you. i thought the same but wasnt 100% sure.
Answer: Illusions do not benefit from item raw damage or attack speed, they benefit only from item stats (int, agi, str) or auras such as radiance's or vladimir's. Note that they bestow the aura, but may not benefit from it, which is the case of the lifesteal aura from Vladimir's.
The only orb effect that works on illusions is Diffusal Blade feedback orb, and this is for melee heroes only. Also it is worth noting that illusions get the critical chance from Daedalus/Crystalis, but not the raw damage.
As for passive abilities, yes, illusions do benefit from most of these. For example, Chaos Knight's illusions have Chaos Strike, and Mortred's illusions (if one have Manta Style) have Blur and Coup de Grâce.
Comment: Hello, I disagree on the item part because illusions benefit from radiance, true sight of gem, true strike of MKB or damage from quelling blade. Not only diffusal blade.
Comment: My bad, I forgot to state that illusions benefit from aura-like items and critical hit-like items (MKB once used to be a 1x critical so it never missed). I edited the answer with more details.


Are there any known NP-hard group theoretic problems?

Question: Are there any known NP-hard group theoretic problems which take as input finite groups given as Cayley tables (that is, not as a list of generators and product relations)?
I'm talking about abstract groups, not permutation groups. It seems that all known group theoretic problems that are hard seem to be variations of the word problem (in which case, the group is infinite) or computing distances between a permutation and a subgroup of the symmetric group (see Buchheim, Cameron, Wu https://webspace.maths.qmul.ac.uk/p.j.cameron/preprints/sd.pdf).
Comment: This is a good find! However, all of the problems in the MO thread deal with succinct input models rather than the Cayley table (verbose) model.
Comment: https://mathoverflow.net/questions/321547/are-there-any-computational-problems-in-groups-that-are-harder-than-p might be of interest; I didn't check how the problems given in answers accept their input though
Answer: I don't believe so. The two main problems of interest in the Cayley table model are membership testing and isomorphism testing. Membership testing belongs to $\textsf{L}$ by reduction to path finding on an appropriate Cayley graph.
Isomorphism testing belongs to $\beta_{2}\textsf{L} \cap \beta_{2}\textsf{FOLL} \cap \beta_{2}\textsf{SC}^{2}$ by the generator enumeration strategy. Every group has a generating set of size at most $O(\log n)$ (and a cube generating set of size $O(\log n)$), and so we can guess a generating set with $O(\log^{2} n)$ bits and then perform marked isomorphism testing efficiently in parallel. The $\beta_{2}\textsf{FOLL}$ and $\beta_{2}\textsf{SC}^{2}$ bounds rely on guessing cube generating sequences.
It is known that $\beta_{2}\textsf{FOLL}$ cannot compute Parity. As Parity is $\textsf{AC}^{0}$-reducible to Graph Isomorphism, this shows that Group Isomorphism is strictly easier than Graph Isomorphism.
Furthermore, there is considerable evidence that Graph Isomorphism is not $\textsf{NP}$-complete. All of this evidence applies to Group Isomorphism as well.

If GI is $\textsf{NP}$-complete, then the Polynomial-Hierarchy collapses to $\textsf{PH} = \Sigma_{2} \cap \Pi_{2} = \textsf{AM}$ (the last equality is again a consequence of the collapse and is not known to be true).
GI is in the low hierarchy of $\textsf{NP}$. So GI is unlikely to be $\textsf{NP}$-complete, as again $\textsf{PH}$ would collapse (https://www.sciencedirect.com/science/article/pii/0022000088900104?via%3Dihub).
GI is low for $\textsf{PP}$ and $\textsf{C=P}$. This is not known to be true for any $\textsf{NP}$-complete problem (https://link.springer.com/article/10.1007/BF01200427)
If GI is $\textsf{NP}$-complete, then $\textsf{NP} \subseteq \textsf{DTIME}(n^{\text{poly} \log n})$, which implies that $\textsf{EXP} = \textsf{NEXP}$. It is widely believed that $\textsf{EXP} \neq \textsf{NEXP}$. (https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.47.2228&rep=rep1&type=pdf)
The decision and counting variants of GI are equivalent. This is not known to be the case for any $\textsf{NP}$-complete problem (https://www.sciencedirect.com/science/article/abs/pii/0020019079900048).

Also, Tensor Isomorphism problems in the multidimensional array (verbose) model have the same upper bounds as Graph Isomorphism. So even these much harder problems are unlikely to be NP-complete. (https://arxiv.org/pdf/1907.00309.pdf)


An error occurred (AccessDenied) when calling the PutPublicAccessBlock operation: Access Denied

Question: I'm trying to implement PutPublicAccessBlock operation on S3 bucket inside my account. My code sample as below.
    s3Client.put_public_access_block(
    Bucket= name,
    PublicAccessBlockConfiguration={
        'BlockPublicAcls': True,
        'IgnorePublicAcls': True,
        'BlockPublicPolicy': True,
        'RestrictPublicBuckets': True
    })

Even though lambda has AmazonS3FullAccess , but it's still not able to perform above action and getting Access Denied  error.
Any idea why is it happening?
Comment: can you add the full error message
Comment: The bucket name is correctly spelled and is definitely in an AWS account that your credentials are associated with? Is this AWS account part of an AWS Organization that has service control policies?
Comment: Yes bucket name is correctly spelled as I am doing other action on it. Yes, account is part of org. But I am trying to change things with lambda in my own account. I don't think that should give me an issue tbh
Comment: Service Control Policies at the org level could potentially be denying you permission for this S3 action.
Answer: To do whatever you want in a bucket with lambda, you need to give permission to do that job in the lambda role and in the bucket policy.
{
  "Id": "ExamplePolicy",
  "Version": "2022-07-02",
  "Statement": [
    {
      "Sid": "ExampleStmt",
      "Action": [
        "s3:PutBucketPublicAccessBlock"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::<bucket_name>/*"
      ],
      "Principal": {
        "AWS": [
          "arn:aws:iam::<id_account>:role/<lambda_role_name>"
        ]
      }
    }
  ]
}

Documentation (Español)


Problems upgrading from 14.04 to 16.04 January 2020

Question: I am trying to upgrade from 14.04 to 16,04
I am using this steps suggested by https://www.youtube.com/watch?v=g6GUGoX5u8M&t=197s ,  however I am stuck after the first step and this is what it shows on my screen:
<code>Reading package lists... Done
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://repo.vivaldi.com stable Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 9658E8044A3AA3D6
W: Failed to fetch http://repo.vivaldi.com/archive/deb/dists/stable/Release
W: Failed to fetch http://dl.google.com/linux/chrome/deb/dists/stable/Release  Unable to find expected entry 'main/binary-i386/Packages' in Release file (Wrong sources.list entry or malformed file)
W: Failed to fetch http://ppa.launchpad.net/patrick-dessalle/ppa/ubuntu/dists/trusty/main/binary-amd64/Packages  404  Not Found [IP: xx.xxx.xx.xx xx]
W: Failed to fetch http://ppa.launchpad.net/patrick-dessalle/ppa/ubuntu/dists/trusty/main/binary-i386/Packages  404  Not Found [IP: xx. xxx. xx.xx.xx]

W: Some index files failed to download. They have been ignored, or old ones used instead.
W: Duplicate sources.list entry http://dl.google.com/linux/chrome/deb/ stable/main amd64 Packages (/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-amd64_Packages)
</code>
I can not continue with step 2.
I would appreciate your help.
Thanks.
Comment: I looked at one of those PPA's, it didn't support 14.04 either (support ended at 11.10) - http://ppa.launchpad.net/patrick-dessalle/ppa/ubuntu/dists/   Disable or delete those PPA's you weren't able to use since 2012 (well before 2014-April or 14.04).  I would also stick with official guides, or on sites like this (eg. https://help.ubuntu.com/community/EOLUpgrades).   I'd also consider a re-install given the lack of maintenance the system appears to have had.
Comment: Welcome to AskUbuntu, during upgrading LTS to the newer release, the PPA and non-official Ubuntu packages are not going to upgrade themselves. You can do it later, if the package is still valid in the newer release. Simply type 'sudo do-release-upgrade' then you get it.
Answer: First of all, you are working with an unsupported version of Ubuntu, version 14.04. "Unsupported" also means no upgrade is supported anymore. So quit your attempts to upgrade this way immediately.
As a general advise, do not upgrade over an older version. Instead make sure that the backup of your private user files is up to date, and then perform a fresh install of the latest long term release edition of Ubuntu 18.04.
A fresh install is the best, most tested and most trouble free approach for any operating system. Doing so, you are adopting the thoroughly tested system defaults. In contrast, when you upgrade, you are carrying over old configuration which may not be optimal, may conflict with newer configuration settings, or cause more severe issues altogether.
A fresh install takes no more than 15 - 20 minutes. It is the least likely to run into problems. You then have a stable, fresh and tested system where you can put your own data back.
Answer: You are likely to encounter quite a few errors thanks to the fact that you are using 14.04, a old release, and EOL, so it doesn't support any upgrades.  Backing up your data and making a clean, fresh installation of the release of your choice (I recommend 20.04 Focal Fossa) would be the right thing to do.


3 tables - FK integrity from tb1 bad. tb2 & tb3 are good. tb1 is the main - how do I compare and find out what id are bad in tb2 & tb3

Question: I have brought my data from Salesforce. There is a main table for Cases and it references the Accounts table and Contacts table. The Accounts table and Contacts table are compliant. The Cases table has problems with both the Accounts and Contacts table. I want to clean the data between both that matches and remove the rest to create integrity. I have used below to find what matches. However, I want to know what does not match and if I have Ids that can match them through other routes.
Is there another statement I can use for just what doesn't equal?
SELECT Contact.AccountId AS Contact, Account.Id AS Account, [Case].ContactId AS [Case]
FROM Account
INNER JOIN [Case] ON Account.Id = [Case].AccountId
INNER JOIN
Contact ON Account.Id = Contact.AccountId AND [Case].ContactId = Contact.Id AND Account.Id = Contact.AccountId

Ultimately I want to create the FK relationships from Case to Account & Contact.
Answer: You should either do a left join and check for nulls, or use not exists() queries:
SELECT Contact.AccountId AS Contact, Account.Id AS Account, [Case].ContactId AS [Case]
FROM Account
left JOIN [Case] ON Account.Id = [Case].AccountId
where case.accountid is null

or
SELECT Contact.AccountId AS Contact, Account.Id AS Account, [Case].ContactId AS
[Case]
FROM Account
where not exists(elect * from case where case.accountid=account.id)

Comment: That put me on track. I realized I needed to see all of the matches from Case to Account and Case to Contact and compare. I don't know if I went the fastest route, but it gave me the nulls and a single ID that was running rampant  and not making it consistently to other tables. I came up with:
`Select  a.id As AccountId, s.AccountId As CaseAcct, s.ContactId AS CaseCon, c.Id AS Conid, s.CreatedDate
From Contact c full join
[Case] s
 on s.ContactId = c.Id
  full join Account a
   on a.Id = s.AccountId
    order by CreatedDate desc`

This showed me what was causing the issues.
Comment: Great. The best answers are the ones that don't just give you the code, but point you in the direction to work it out for yourself. Glad to be of help and well done.


Is it a structural concern that my plumber cut through 6 studs to install water line?

Question: We had a plumber come out and install a water line for a pot filler and it looks like he cut through 6 studs without our permission on the exterior wall of the house. We are worried it could cause structural issues. Can anyone provide an opinion?
Comment: Are they 2x6 or 2x4 studs and how deep are the cutouts?  Usually people drill holes for pipes in studs/joists.  If in a cold climate, should try to not place water pipes in exterior walls.
Comment: How deep is the notch and what size stud?
Comment: Beams are horizontal, @MiG, posts are vertical. ;)
Comment: Not my native language, where the word is the same for both categories :)
Comment: What does the larger structure look like? At first glance I would say yes, a beam's strength is only as much as its smallest cross section, and it looks like that's been decimated (not to mention buckling length is reduced).  How much of the beams is left at the cuts?
Comment: Is this a 1 story home? What is the size of the house? Is this in an end wall or side wall? Are you located in a seismic area or high wind area?
Comment: Is this a bearing wall (are trusses sitting on the wall)?
Answer: Those studs can be notched up to 25% if it's a load bearing wall (likely) or exterior wall (very lilely due to insulation). So for a 2x4 that could be notched 7/8in deep, for a 2x6 it could be just over 1.25in.
Those lines look like they are under 1.5in since they appear to have a smaller diameter than the 1.5in lumber. So this could be marginally ok.
For a better answer you'd have to let us know what the depth of those studs is (e.g. 3.5in for a 2x4, and 5.25in for a 2x6), and what the size of the notch is. It could help to know whether the wall is load bearing, but that may be more difficult to determine by a lay person.

Ref: Western Wood Products Association http://files.engineering.com/download.aspx?folder=2fda658c-dda7-403f-9165-d97f6092084c&file=notch_and_holes.pdf


Select2 is not sending remote parameters

Question: I am trying to send to parameters to one servlet, but I can't do it's works,
always I receive "null".
I found some examples around the web, but none work for me.
Could someone give me some idea why is not working?
Here my code:
        $('#cboCli').empty();
        $('#cboCli').select2({
            theme: "bootstrap",
            width: "100%"
        });
        $('#cboCli').append("<option>Cargando ...</option>");
        $.ajax({
            type: "POST",
            url: "Cuenta",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: function (term, action,tipocuen) {
                return {
                    action: 'BUSCACONSULTA',
                    tipocuen: $("#cboTipoCue").val(),
                    term: term
                };
            },
            success: function (data) {
                $('#cboCli').empty();
                $.each(data.aaData, function (i, data) {
                    $('#cboCli').append('<option value="' + data.id + '">' + data.nombre + '</option>');
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Ocurrio un Error: " + XMLHttpRequest.responseText);
            }
        });

The parameters "action" and "tipocuen", never arrive to my servlet!
Thanks in advance!
Answer: data parameter for $.ajax is wrong. As stated in jQuery api document, data must be a PlainObject, String or Array.
Change it like the following:
data: {
     action: 'BUSCACONSULTA',
     tipocuen: $("#cboTipoCue").val(),
     term: term
},

And I think this has nothing to do with jquery-select2.
If you want to send params correctly, I think you should bind $.ajax to some event.


Installing Ubuntu in dual boot mode with Windows 7 Ultimate

Question: I have a bootable usb for Ubuntu 14.04 when I go for installing Ubuntu I don't get to see "Install Ubuntu alongside Windows" option, however Windows 7 Ultimate is already installed on my machine. How do I make my machine dual boot for windows 7 and ubuntu?
Comment: possible duplicate of ["Install alongside" option missing. How do I install Ubuntu beside Windows using "Something Else"?](http://askubuntu.com/questions/163962/install-alongside-option-missing-how-do-i-install-ubuntu-beside-windows-using)
Comment: here is a complete walkthrough for windows-dual-booting for nearly any problem you maybe face: http://askubuntu.com/a/228069/354350
Answer: Often, Ubuntu installer cannot identify Windows in the HD. Even if it does, it is better to select "Do something else" and create a partition manually and install Ubuntu. I'm saying this because once I tried the "install alongside" option and the result was that the whole HD was formatted and Ubuntu got installed on it.


The player's coordinates are not displayed in debug list, how can I find them without commands?

Question: I went through all the settings of the Minecraft, but did not find any settings for the debug list
Well, maybe a couple of settings for the type of Profiler, etc.
The essence does not change, a solid chunk of the data about coordinates, lighting, condition of the unit, all disappeared, this is as it should be in this version?
Versions where tested-,1.13.2, 1.15.2
And by the way, hidden commands like displaying chunks or hitboxes don't work for me either
I didn't know how to solve this problem.
Result:Tell me how to solve this problem?
Answer: You have gamerule reducedDebugInfo set to true. This will get rid of some of the info on your debug screen, including XYZ coordinates.
Type the following command into the chat to turn it off:
/gamerule reducedDebugInfo false


How to add a shortcut event in javafx with combination of Ctrl + P +X

Question: table.setOnKeyPressed(new EventHandler<KeyEvent>() {
  // final KeyCombination kb = new KeyCodeCombination(KeyCode.P, KeyCombination.CONTROL_DOWN);
  // final KeyCombination k = new KeyCodeCombina

  public void handle(KeyEvent key) {
    if (key.getCode() == KeyCode.P && key.isControlDown()) {
      //My Code
    }
  }
});

I want to invoke the event with the shortcut keycombination of Ctrl+P+X
Answer: It is actually a little hard to understand what Ctrl+P+X means.  I am going to assume it means that you press ctrl, then you press p, then you press x (potentially releasing the p before you press the x).  I'll also assume that the order matters, e.g. press ctrl, then press x then press p would not count.  Anyway a bit of speculation on my part, perhaps not exactly what you want, but hopefully you will get the gist of the provided solution and be able to adapt it to your situation.
The solution monitors both key presses and releases so that it can keep track of the state of key presses to determine if the key combination triggers.
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.time.LocalTime;

public class KeyCombo extends Application {

    KeyCombination ctrlP = KeyCodeCombination.keyCombination("Ctrl+P");
    KeyCombination ctrlX = KeyCodeCombination.keyCombination("Ctrl+X");

    @Override
    public void start(Stage stage) throws Exception {
        Label lastPressedLabel = new Label();

        TextField textField = new TextField();

        BooleanProperty pDown = new SimpleBooleanProperty(false);

        textField.setOnKeyPressed(event -> {
            if (ctrlP.match(event)) {
                pDown.set(true);
            }

            if (pDown.get() && ctrlX.match(event)) {
                pDown.set(false);
                lastPressedLabel.setText(
                        LocalTime.now().toString()
                );
            }
        });

        textField.setOnKeyReleased(event -> {
            if (!event.isControlDown()) {
                pDown.set(false);
            }
        });

        VBox layout = new VBox(10,
                new Label("Press Ctrl+P+X"),
                textField,
                lastPressedLabel
        );
        layout.setPadding(new Insets(10));
        Scene scene = new Scene(layout);
        stage.setScene(scene);

        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

If you can, I'd advise trying to use a simpler control scheme, e.g. just Ctrl+P or Ctrl+X (which is directly supported by the key code combination event matching), rather than using a composite control scheme of Ctrl+P+X.
Comment: Thanks. But this is not the thing i wanted. I am trying to press the keys together, i.e, the way we press Ctrl+Alt+del for an event. But instead of the Alt modifier i want P pressed down.
Comment: Do you want it to work also when pressed in the order P+Ctrl+X? (the same way Alt+Ctrl+Del works)
Comment: I'm sure you can tweak the solution to get exactly what you want.


Member's name in WebsPhere cluster at runtime

Question: I am trying to gets the member's name of member in WebSphere cluster. I can get the hostname, and node name from from AdminService
AdminService adminService = AdminServiceFactory.getAdminService();

but i am not able from admin service to get member's name. I found that this is providing by cluster mbean in websphere, but i can't find any code examples how can i get this cluster mbean and use in my javacode.
Answer: The process name will return the name of the application server (cluster member), which can be obtained from the AdminService.
AdminServiceFactory.getAdminService().getProcessName()


Can you go up into pipes using Propeller Mario's Propeller jump?

Question: I know this may seem obvious to many, but I have had trouble going up into pipes when I've used the Propeller Jump. Does using that move prevent you from going into a pipe, or am I simply not aiming well enough?
Comment: Are you pressing up as you're directly under the pipe?
Comment: Yes. Does it have to be dead center of the pipe?
Comment: No, not really.
Comment: If you are jumping, be sure to actually hit the pipe.
Answer: Yes, you can, and there are at least a few pipes that are really only accessible in this way, particularly in single player. Here's a video example of one such pipe (Note: this does contain something of an exploration spoiler):

As I recall, you can simply hold the up button as you propel yourself upwards, so I would suggest trying that. That was typically pretty consistent for me.
Comment: Thanks for the answer. I didn't watch the video due to the spoilers, but I believe you.


Import path in pytest

Question: I have Python Flask project with following structure of my project (I removed uneccesary things):
server
    src
        service
            __init__.py
            User.py
    tests
        pytest.ini
        service
            test_user.py

Where pytest.ini contains:
[pytest]
python_paths = ../src

And test_user.py:
from service.User import UserService

def test_empty_db():
    service = UserService()
    users = service.get_all()  # Get all users from DB.
    assert len(users) = 0  # There should be users.

Now, I would like to run this test. When I run pytest or pytest server from root of project, everything is ok. However, when I want to run the specified file pytest server/tests/service/test_user.py error appears:

from services.User import UserService
E   ModuleNotFoundError: No module named 'service'

Is there any way to fix it?
Answer: You can try to make your imports more absolute inside your test_user.py like: from server.src.service.User import …
Or you can also try adding a __init__.py to your tests directory.
Answer: Your error message is showing services.User while you code is showing service.User, could it be a typo?

Import path in pytest


Android emulator http-proxy SSL handshake failure

Question: I have a local HTTP proxy set up for debugging .json request and response data from my Android application.  I deploy it to a Nexus One emulator image running Android 4.2.2 with the command line option -http-proxy http://localhost:8888.  I'm using a stock ADT Build: v21.1.0-569685.  I can validate that the HTTP proxy can handle HTTPS connections with the following code snippet I run using groovy:
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

FileInputStream fis =
    new FileInputStream( "./.mitmproxy/mitmproxy-ca-cert.pem" );
BufferedInputStream bis = new BufferedInputStream( fis );
CertificateFactory cf = CertificateFactory.getInstance( "X.509" );
KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load( null,"".toCharArray() );
while ( bis.available() > 0 )
{
    Certificate cert = cf.generateCertificate( bis );
    ks.setCertificateEntry( "mitmproxy", cert );
    System.out.println( cert.toString() );
}
TrustManagerFactory tmf =
    TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm() );
tmf.init( ks );
SSLContext ctx = SSLContext.getInstance( "TLS" );
ctx.init( null, tmf.getTrustManagers(), null );
SSLSocketFactory sslFactory = ctx.getSocketFactory();
try
{
    String url = "https://www.openssl.org/";
    Proxy proxy =
        new Proxy(
            Proxy.Type.HTTP,
            new InetSocketAddress( "127.0.0.1", 8888 ) );
    HttpsURLConnection conn =
        ( HttpsURLConnection ) new URL( url ).openConnection( proxy );
    conn.setSSLSocketFactory( sslFactory );
    String s =
        new Scanner(
            conn.getInputStream(),
            "UTF-8" ).useDelimiter( "\\A" ).next();
    System.out.println( s );
}
catch ( Exception e )
{
    e.printStackTrace();
}

This snippet fetches the HTTPS resource just fine, logs the request and response unencrypted, and works beautifully.  The proxy also works when accessing HTTPS resources from a browser configured to use it as its proxy, so I'm pretty sure the problem is not with the proxy.  Based on the certificate, you can tell I'm using the mitmproxy, but this code also works with the OWASP ZAP proxy.  But with either proxy, after installing the appropriate CA root certificate on the Android image, HTTPS requests from the image fail with the following events being logged to the mitmproxy event log:
127.0.0.1:56210: connect
127.0.0.1:56210: 400: SSL handshake error: (-1, 'Unexpected EOF')
127.0.0.1:56210: disconnect
  -> handled 0 requests

On the Android side, the following exception is thrown:
05-23 16:13:30.109: E/HttpUrlConnectionClient(827): Network error
05-23 16:13:30.109: E/HttpUrlConnectionClient(827): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x2a180890: Failure in SSL library, usually a protocol error
05-23 16:13:30.109: E/HttpUrlConnectionClient(827): error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:766 0x45dc2ba8:0x00000000)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:420)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:219)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:480)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:444)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:294)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:244)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:286)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:181)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.integralblue.httpresponsecache.compat.libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:273)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.ehi.national.mobile.network.HttpUrlConnectionClient.send(HttpUrlConnectionClient.java:178)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.ehi.national.mobile.network.AppClient.send(AppClient.java:212)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.ehi.national.mobile.network.MsiClient.send(MsiClient.java:87)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.ehi.national.mobile.services.SimpleService.runService(SimpleService.java:134)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.ehi.national.mobile.task.InitTask.doInBackground(InitTask.java:84)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at com.ehi.national.mobile.task.InitTask.doInBackground(InitTask.java:1)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at java.lang.Thread.run(Thread.java:856)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x2a180890: Failure in SSL library, usually a protocol error
05-23 16:13:30.109: E/HttpUrlConnectionClient(827): error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:766 0x45dc2ba8:0x00000000)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:378)
05-23 16:13:30.109: E/HttpUrlConnectionClient(827):     ... 20 more

Other HTTP requests get logged and recorded as expected.  What am I missing in the SSL setup for the Android image to complete the SSL handshake with the HTTP proxy successfully?
Comment: Did you ever find the answer? I'm having the same problem on Android 2.3.3. I installed the cert in the emulator image by [this method](http://varutra.com/blog/?p=69) but keep getting the 400 error.
Answer: Android Developers gives two methods for supplying proxy; the one you used and an environment variable method.  Maybe try the env var and see if it works?
From the Android Developers page:

If the -http-proxy  command is not supplied, the emulator looks
  up the http_proxy environment variable

I found the details on the Android Developers page.


How can I obtain Steam achievements in Torchlight after "finishing" the main story?

Question: I finished the main story of Torchlight way before Steam introduced achievements. Now I have my Level 50 character and am doing quests.
Is the only way to get some of the achievements (such as "Over the Brink", etc.) for events occurring in the main story to replay it?
Answer: Yes, replaying the story is the only way to earn the acheivements.
I was in this situation myself, but I used the special function to "retire" my character, so at least I had bonuses with my new one.
Comment: There is an other way. You could try the "Steam Achievment Manager" (3rd party software) which allow you to manually unlock any achievment in steam games (potentially VAC-risky). Though, i don't remember it being legal, so i won't be posting a link here. Google it yourself.
Comment: @Lysarion Seeing as it is legal and you cannot be VAC-banned for it, here it is: [Steam Achievement Manager](http://gib.me/sam/).
Comment: @ArdaXi - Is it _really_ legal? Are you sure? Is there some official source?
Comment: Oh, also then there's the question of "what's the point of 'achieving' achievements by using an editor.' :/
Comment: @ver Legality has nothing to do with it. The TOS doesn't disallow it either. I can't give you an official source because they don't **condone** it, but they can't detect it either.


Mouse requiring clicking twice in most cases, not sure why?

Question: I'm running Ubuntu 16.04.3 using an Apple Magic Mouse (version 1) and I'm finding that I have to click twice to select things quiet often. But I can't establish a pattern to get it to happen all the time. When it does happen it seems to do it many times consecutively.
Is anyone else experiencing this?
Comment: Replace the mouse (and it's an hardware problem therefore off topic here).
Comment: I concur that this sounds like a hardware issue. There may be some dirt in the actual electrical button underneath the casing. Also, the small metal sheet that's used in the button to provide tactile feedback wears out over time with use. Either bend it back into shape, replace the button (if you can find a replacement part and know how to solder), or replace the entire mouse.
Answer: This issue turned out to be that Ubuntu's drivers for the Magic Mouse (hid_magicmouse I think?) introduce a middle button region on the Magic Mouse. When disabled this acts as a dead zone. I discovered that my finger was sitting right on the edge of the left click region and the right click region so my first click was often in the middle while my second click was just slightly more to the left and hence it worked.
Although I didn't try this, I theorize you could reassign the middle region to behave as left click as well.
Thank you for your feedback guys.


Create NodeList of all Document nodes manually

Question: I currently generate a NodeList of all the Document nodes (in document order) manually. The XPath expression to get this NodeList is
//. | //@* | //namespace::*

My first attempt for walking the DOM manually and collecting the nodes (NodeSet is a primitive NodeList implementation delegating to a List):
private static void walkRecursive(Node cur, NodeSet nodes) {
    nodes.add(cur);

    if (cur.hasAttributes()) {
        NamedNodeMap attrs = cur.getAttributes();
        for (int i=0; i < attrs.getLength(); i++) {
            Node child = attrs.item(i);
            walkRecursive(child, nodes);
        }
    }

    int type = cur.getNodeType();
    if (type == Node.ELEMENT_NODE || type == Node.DOCUMENT_NODE) {
        NodeList children = cur.getChildNodes();
        if (children == null)
            return;

        for (int i=0; i < children.getLength(); i++) {
            Node child = children.item(i);
            walkRecursive(child, list);
        }
    }
}

I would start the recursion with calling walkRecursive(doc, nodes) where doc is the org.w3c.Document and nodes a (yet empty) NodeSet.
I tested this using this primitive XML document:
<?xml version="1.0"?>
<myns:root xmlns:myns="http://www.my.ns/#">
  <myns:element/>
</myns:root>

If I for example canonicalize my manually created NodeSet and the NodeList generated by the initially mentioned XPath expression and compare the two byte for byte, then the result is equal and seems to work just fine.
But, if I iterate over the two NodeLists and print debug info (typeString simply generates a string representation)
for (int i=0; i < nodes.getLength(); i++) {
    Node child = nodes.item(i);
    System.out.println("Type: " + typeString(child.getNodeType()) +
                       " Name:" + child.getNodeName() +
                       " Local name: " + child.getLocalName() +
                       " NS: " + child.getNamespaceURI());
}

then I receive this output for the XPath-generated NodeList:
Type: DocumentNode Name:#document Local name: null NS: null
Type: Element Name:myns:root Local name: root NS: http://www.my.ns/#
Type: Attribute Name:xmlns:myns Local name: myns NS: http://www.w3.org/2000/xmlns/
Type: Attribute Name:xmlns:xml Local name: xml NS: http://www.w3.org/2000/xmlns/
Type: Text Name:#text Local name: null NS: null
Type: Element Name:myns:element Local name: element NS: http://www.my.ns/#
Type: Text Name:#text Local name: null NS: null

and this for the manually generated NodeList:
Type: DocumentNode Name:#document Local name: null NS: null
Type: Element Name:myns:root Local name: root NS: http://www.my.ns/#
Type: Attribute Name:xmlns:myns Local name: myns NS: http://www.w3.org/2000/xmlns/
Type: Text Name:#text Local name: null NS: null
Type: Element Name:myns:element Local name: element NS: http://www.my.ns/#
Type: Text Name:#text Local name: null NS: null

So, as you can see, in the first example the NodeList additionally contains the Node for the XML namespace:
Type: Attribute Name:xmlns:xml Local name: xml NS: http://www.w3.org/2000/xmlns/

Now my questions:
a) If I interpret xml-names11 correctly, then I don't need the xmlns:xml declaration:

The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace. It MAY, but need not, be declared, and MUST NOT be undeclared or bound to any other namespace name. Other prefixes MUST NOT be bound to this namespace name, and it MUST NOT be declared as the default namespace.

Am I correct? (at least c) hints in that direction)
b) But then, why does the XPath evaluation add it anyway - shouldn't it just include what was there in the first place instead of automagically adding things?
c) This can cause trouble with XML canonicalization, although it shouldn't - declarations of the xml namespace should be omitted during canonicalization. Does anyone know of (Java) implementations that get this wrong?

Edit:
Here's the code I used to evaluate the XPath expression that contained the 'xml' namespace node:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
InputStream in = ...;
try {
    Document doc = dbf.newDocumentBuilder().parse(in);
    XPathFactory fac = XPathFactory.newInstance();
    XPath xp = fac.newXPath();
    XPathExpression exp = xp.compile("//. | //@* | //namespace::*");
    NodeList nodes = (NodeList)exp.evaluate(doc, XPathConstants.NODESET);
} finally {
    in.close();
}

Comment: I'm not getting this extra attribute (jdk1.6.0_18)
Comment: @Maurice: Strange, I get it even with JDK 5 and 7. I'll add the code I used for evaluating the XPath expression.
Comment: my mistake, I misread your post
Answer: Since you can write
<myns:root xml:space="preserve" xmlns:myns="http://www.my.ns/#">
  <myns:element/>
</myns:root>

without declaring the "xml" prefix, then it must be there implicitly. It is therefore correct to include the namespace node for this namespace declaration in the //namespace:* location step
So,
a) you are wrong, you need it (well, depending on the purpose of your code)
b) see above
c) no, but I've seen other namespace corner cases where things went haywire (e.g. Problem with conversion of org.dom4j.Document to org.w3c.dom.Document and XML Signature


Efficient Way to create a 2d array of random shuffling of a range of numbers

Question: I need to create a N x M numpy array of randomly shuffled numbers 0 to N. That is to say that each row of the matrix has exactly one of each numbers 0 to N in a random order with no repeating elements and every number is represented.
The best I've been able to come up with so far is (for N = 10 and M = 5)
import random
import numpy as np

a = np.array([random.sample(range(10), 10) for x in range(5)])

which gives me
[[5 9 1 3 8 2 6 4 0 7]
 [4 8 5 2 9 3 7 6 0 1]
 [8 4 6 7 9 2 0 5 1 3]
 [3 5 4 9 2 0 6 7 1 8]
 [6 0 4 7 3 2 1 8 5 9]]

My current solution does work, but I'd like to only have one random library if possible (I'm using numpy elsewhere so a numpy only solution would be ideal). I'm assuming numpy has an easier way to do this, but I'm currently missing it.
Comment: It doesn't reduce the number of library calls you need to make, but `a = np.array([np.random.permutation(10) for _ in range(5)])` might be cleaner.
Comment: Edit your question to reflect this
Comment: Thanks @Divakar, that was a perfect answer. Guess i didn't find the correct search terms when i was digging around
Comment: import numpy as np, of course.... then ... np.random.randint(0, 10, size=(5, 10))
Comment: @JohnColeman that was my initial thought, but I wasn't sure how to create the array so that it has the same random 0->N but in different orders
Comment: @NaN, the problem is i need it to be the range(0, N) but shuffled. I.E. no repeated elements and every element is there exactly once.
Comment: @NaN I've tried to make the question more clear
Comment: My current solution does work, but i'd like to only use one random library if possible (preferably numpy)
Answer: If the issue is simply to only use one random library (as you said in your comments), you could just use numpy.random.choice with the argument replace=False, which ensures each element is not repeated:
import numpy as np

a = np.stack([np.random.choice(range(10), 10, replace=False) for _ in range(5)])

>>> a
array([[0, 9, 3, 5, 8, 7, 1, 4, 6, 2],
       [5, 6, 8, 3, 0, 4, 7, 9, 2, 1],
       [7, 4, 9, 5, 0, 1, 6, 8, 3, 2],
       [9, 0, 3, 8, 5, 7, 6, 1, 4, 2],
       [5, 6, 0, 1, 3, 4, 9, 8, 7, 2]])