LightDM not Behaving as Expexted

Question: I seem to be having some odd lightdm behavioral issues. So far this what I have in my /etc/lightdm/lightdm.conf file:
user-session=gnome-classic
greeter-session=unity-greeter
greeter-show-manual-login=true
allow-guest=false
greeter-hide-users=true

How I'd expect lightdm to behave based on the above is the means to type in a username, list of available users hidden and the guest account not available.  However all I get is as follows:

I've read on these forums and elsewhere that unless greeter-session is set to lightdm-gtk-greeter the options in my lightdm.conf file will not be honored.
However, if I make the changes accordingly then reboot, all I see is as follows:

I'm running 12.04.2 within a VM.
Any help would be greatly appreciated.
Thanks in advance,
Dan.
Comment: UPDATE:  I didn't realize that lightdm-gtk-greeter was a package.  Once I installed the it, I was able to avoid the low-graphics issue, however, there's been a misunderstanding on my part.  I also didn't realize that by specifying lightdm-gtk-greeter it would display the old gnome greeter.  I want the unity greeter.  For clarity, even with the gnome greeter, i was still unable to enter usernames etc.  Seems no matter what i do, i get the same un-desired affect with both the gnome and unity greeters.
Comment: ANOTHER UPDATE:  I'm going through the process of elimination in an attempt to resolve this but now I'm even more confused than ever.  I set greeter-hide-users=false so I was expecting to see some users within the greeter and although that was the case, I can now also see Login option!  If I select Login, it immediately asks for a password (no username option).  Totally confused!!!  Can anyone confirm whether this behavior associated to a bug?
Answer: Resolved!!!!!!
Transpired that the issue was nothing to do with lightdm.  An application had been installed that made some custom changes to the /etc/pam.d/lightdm and /etc/pam.d/lightdm-autologin files.  I restored them to their defaults and the issue was resolved.  I'm now seeing exactly what I was expecting.  I hope I've not upset the application in question too much by doing do:-)!!
Thanks to those who bothered to take the time to read this post!

LightDM not Behaving as Expexted


My server potentially hacked . How to clean a server from rogue processes

Question: I am a newbie and my first server seems to have been hacked. I am not sure how to clean it. There are processes hogging the CPU that am not the owner of. All the 12 CPUs are almost all running at 100%. Kindly see htop screen shot
htop on the server
I have run a netstat and below is a summary of the output
<code>sudo netstat -anolp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    Timer
tcp        0      0 127.0.0.1:9001          0.0.0.0:*               LISTEN      4869/java           off (0.00/0/0)
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      15327/mongod        off (0.00/0/0)
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      4124/mysqld         off (0.00/0/0)
tcp        0      0 127.0.0.1:9100          0.0.0.0:*               LISTEN      24415/node_exporter off (0.00/0/0)
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      16039/nginx -g daem off (0.00/0/0)
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      5824/config.ru      off (0.00/0/0)
tcp        0      0 127.0.0.1:9168          0.0.0.0:*               LISTEN      24370/ruby          off (0.00/0/0)
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      13595/sshd          off (0.00/0/0)
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      2370/master         off (0.00/0/0)
tcp        0      0 127.0.0.1:9121          0.0.0.0:*               LISTEN      24450/redis_exporte off (0.00/0/0)
tcp        0      0 127.0.0.1:9090          0.0.0.0:*               LISTEN      24429/prometheus    off (0.00/0/0)
tcp        0      0 127.0.0.1:9187          0.0.0.0:*               LISTEN      24421/postgres_expo off (0.00/0/0)
tcp        0      1 my.ser.ver.ip:41037    22.214.171.124:2017     SYN_SENT    26521/mbb           on (57.32/6/0)
tcp        0      0 my.ser.ver.ip:45599    18.104.22.168:29135     ESTABLISHED 32265/DDosClient    off (0.00/0/0)
tcp        0      0 127.0.0.1:9001          127.0.0.1:54729         ESTABLISHED 4869/java           keepalive (2412.64/0/0)
tcp        0      0 my.ser.ver.ip:49366    188.8.131.52:8080     ESTABLISHED 14106/hald-daemon   off (0.00/0/0)
tcp        0      0 my.ser.ver.ip:57275    220.127.116.11:443     ESTABLISHED 20238/wDHnu         keepalive (45.40/0/0)
tcp        0      0 127.0.0.1:9001          127.0.0.1:54909         ESTABLISHED 4869/java           keepalive (2445.40/0/0)
tcp        0      0 my.ser.ver.ip:56654    18.104.22.168:6969      ESTABLISHED 27006/XDTQK         off (0.00/0/0)
</code>
I tried killing them using kill with their PID one by one but after some time they came up again. So I checked my cron, and there were some entries there that I didn't do so I clear them as well. I compared the crons with a new box I just launched.
I disabled the root login, created another sudoer with pem file instead. Now I need to find a way to clean this once and for all and I lack experience. Can anyone please help me out?
Thanks in advance
Comment: Nuke it from the orbit and rebuild. That's the only sure way
Answer: If you're 100% sure you got hacked, the best way of action is to set up from scratch.

Sure you could maybe fix it and get your machine back, but would you really be able to trust in that installation afterwards?
Do you know you fixed all backdoors they might have installed?

And most importantly take that server offline so it cant be used for the attackers purposes.
While the machine is offline for public you might want to diagnose the breach and learn from it security wise, and then set it up from scratch. I see from your screen-shot that you have GitLab running on that machine. This should be the only data you should backup and take over, but not before scanning it thoroughly and checking the database for any rogue entries which would allow new breaches.
And forget about playing back a backup, it might contain still the hole which allowed the attacker to get in.
So back up your data and then install this machine from scratch, and foremost re-roll all passwords which might have been compromised as well in the process.
Sorry to tell you this but thats the best course of action you can take.
Comment: If you are a new user it is safe to assume any potential cracker knows more than you do, thus a fresh install is the way to go. I would not transfer ANYTHING from the cracked server PERIOD. Read up on security, there is a reason the root account is locked by default, and I guess you found out why.
Comment: Very well noted. Will wait for couple more answers and will take a decision
Comment: Fine with me :) I wont be able to get any reputation todays anyways hehehe, hit the cap already for today.


Can I sync my save games between 3DS and Wii U?

Question: Shantae and the Pirate's Curse is finally available in my region, and having greatly enjoyed Shantae: Risky's Revenge on DSi, I obviously want to buy the sequel; only it's available on both 3DS and Wii U, and I'm not quite certain which version I'd like to buy.
Before I decide, I'd like to know if both versions can synchronize their save games. If they can, I could just buy both and stop worrying about which version to buy.
Answer: No. There is no cross-compatibility of save files between 3DS and Wii U games. This is the case for all games at this time.
Comment: That's a shame. I had hoped I could take the easy Way Forward...
Comment: uuuuuhhhh. Ouch. :)
Comment: Now I'm extra excited for the NX


Firebase User ID and Current User ID on code do not match

Question: I am new to Firebase and I assumed the user id generated by Firebase Database is the same one I get by using currentUser.getUid(). But as you can see, those two values don't match for my current user.
I can't figure out the reason. Please help. How to solve this?
Answer: As i can see in your screenshots you are using two different ways for having that unique key, a uid provided by the firebaseUser object and the unique key generated by the push() method. It's obvious that are not the same, becase there are different principles.
The first one is the uid provided by the Firebase authentication and the second by the push() method, that generates a unique id based on the time of the generation.
The best way for using as an identifier for your users is not the uid, nor the pushed id, is the email address, because if a users deletes his account and sign-in again, he'll gets a new uid.
If you want to use the uid, this is the way in which you can retrieve it:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
    String uid = firebaseUser.getUid();
}

Hope it helps.
Comment: Can you please tell me the right way to retrieve the firebase user id? Or provide me a link for it?
Answer: Those are totally different things. ID that you get with getUid() is an ID that is created when user is signed up to Firebase Authentication. Other one is key created based on the current timestamp in the Firebase Database when you call push() method. What you could do is instead of creating new person in your database with push method, use the id that you get from getUid()


Minimum number of states of a DFA recognizing the regular expression $(a+b)^*b(a+b)$

Question:
The minimum number of states in min DFA of regular expression $(a+b)^*b(a+b)$ is _____.

My attempt:
I have drawn this DFA and found the answer to be 3:

Somewhere it was explained that we need "trap" state, so the answer would be 4.
Question:
Is my DFA not correct? Can you explain it, please?
Comment: Your automaton is not correct in fact it does not recognize the word **bba** which is part of the language you have to recognize.
Comment: @Maczinga, you are correct. We need  **one more final state**?
Answer: Note that the regular language you wish to recognize can be expressed in words as "the second-last symbol of the string is $b$". As mentioned in Maczinga's comment, your proposed DFA is not correct because it does not accept $bba$. It also does accept $bab$, which it shouldn't.

To show that at least four states are necessary, consider any DFA over $\{a,b\}$ with three states. Since there are four length-2 strings over $\{a,b\}$, two of them must yield the same state when run on this DFA. By going through the six possibilities we will show that either exactly one of the two strings is in the language, or we can append each by the same character yielding two length-3 strings which yield the same state when run over the DFA, but of which only one is in the language.

If $aa$ and $ab$ yield the same state, then $aaa$ and $aba$ also both yield the same state, but $aba$ is in the language while $aaa$ is not.
If $aa$ and $ba$ yield the same state, note $ba$ is in the language, but $aa$ is not.
If $aa$ and $bb$ yield the same state, note $bb$ is in the language, but $aa$ is not.
If $ab$ and $ba$ yield the same state, note $ba$ is in the language, but $ab$ is not.
If $ab$ and $bb$ yield the same state, note $bb$ is in the language, but $ab$ is not.
If $ba$ and $bb$ yield the same state, then $baa$ and $bba$ also yield the same state, but $bba$ is in the language while $baa$ is not.

I'll leave it to you to construct a 4-state DFA which recognizes the language.
Answer: Here is the DFA that solves the question.
States: A, B, C, D
Arcs: (A,A,a) (A,B,b) (B,C,a) (B,D,b) (C,A,a) (C,B,b) (D,C,a) (D,D,b)
Final states: C, D
Initial state: A
(A,B,a) means that there is an arc from A to B with label a

That is:


Worldguard problem in guard action

Question: I'm running a Minecraft PvP server.
But concerning only "guard", there is a problem.
When non-OP players try to guard action by right clicking and holding sword, the player receives worldguard message "Hey! Sorry, but you can't use that here." .
However, damage is successfully reduced by guarding.
I tried so many things: change "passthrough" to "allow", cancel right click event using "Skript", asking google...
But they didn't work at all, so it is shown.
How can I disable the message?
Answer: Flag determining the use of things that can do this is interact, which denies all interaction with blocks. Therefore if you right click and the flag is in play, it won't allow you to right click the block and tells you the message. So the right-click interaction with block you looking at will be denied, not the holding of sword in defensive maneuver (therefore you can see that defense was succesful).
However that shall not probably pop up when you aim with the sword into the air, but you did not mentioned if it is all the times or so.
So you need to use
/region flag <name of region> interact allow

However it will allow all interact actions , such as chest opening, levers, etc, if you don't deny them separately (flags like use, chest-access etc).
For more information, here is the actualized manual: http://docs.enginehub.org/manual/worldguard/latest/regions/flags/

Worldguard problem in guard action


problem capturing delimiter with preg_split

Question: I have a pipe-delimited dump file from an SQL Server, and I want to import it into MySQL. The lines are delimited by \r\n, and that sequence also occurs in some fields! So I want to use a regular expression to find the actual lines and make an INSERT statement out of them.
However, I'm having trouble including the delimiter in my match string. I thought using PREG_SPLIT_DELIM_CAPTURE would do the trick but apparently I'm doing something wrong. My delimiter is three spaces followed by three numbers, which is actually the id that I need for the row:
$ cat test.php
<?
$string = '   897|a|Hello\r\n   583|b|Line\r\nBreak\r\n   332|c|Yet\r\nMore\r\nLine\r\nBreaks\r\n';

$lines = preg_split( '/   \d{3}\|/', $string, NULL, PREG_SPLIT_DELIM_CAPTURE);
print_r($lines);

$ php test.php
Array
(
    [0] =>
    [1] => a|Hello\r\n
    [2] => b|Line\r\nBreak\r\n
    [3] => c|Yet\r\nMore\r\nLine\r\nBreaks\r\n
)

My delimiters are missing.
$ php -v
PHP 5.3.3-7+squeeze1 with Suhosin-Patch (cli) (built: Mar 18 2011 17:22:52)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

What am I doing wrong, or how do I get what I want?
Answer: You need to group your delimiter into parenthesis, or else the _DELIM_CAPTURE will have no effect.
$lines = preg_split( '/   (\d{3}\|)/', $string, NULL, PREG_SPLIT_DELIM_CAPTURE);

Here, the manual mentions it en passant as flag description:

PREG_SPLIT_DELIM_CAPTURE
  If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
Comment: No, `preg_split` will only give them out separated. You would have to construct a `preg_match_all` pattern if you wanted them combined.
Comment: I had read that, but I didn't understand what parenthesized meant, although its fairly obvious now :P
Comment: OK, that gives me an array with the delimiter being one element and the shard being the next... is there any way to get them as part of the same element? Assertions or something like that?
Answer: Above answer will give you delimiter in separate array element.
Check this one instead:
preg_split how to include the split delimiter in results?


For the number of divisors function, $d(n)$, deduce all positive integers when $d(n)$ is odd

Question: From the definition I have deduced $d(n)$ is multiplicative by letting $n=p_1^{a_1}p_2^{a_2}\cdots p_k^{a_k}$, where
$$d(p_1^{a_1}p_2^{a_2}\cdots p_k^{a_k})= (a_1+1)\cdots(a_k+1)=d(p_1^{a_1})\cdot d(p_2^{a_2})\cdots d(p_k^{a_k})$$
as we know the divisors of $n$ are $d=p_1^{b_1}p_2^{b_2}\cdots p_k^{b_k}$ where each $b_k$ gives a distinct divisor in the form of $(a_k+1)$.
However, I am unsure how to find the given integers, $n$, for the two points below;

$d(n)$ is odd
$d(n)= p_0,$ where $p_0$ is a fixed prime.
Answer: For $d(n)$ to be odd all the expressions $(a_j+1)$ must be odd, thereby implying each exponent $a_j$ must be even. So the number $n$ must be a perfect square.
Likewise for $d(n)$ to be prime, note that we can only have at most one term in the product representation of $d(n)$.
Answer: Hint 1: In order for $d(n)$ to be odd, each of $a_1+1, a_2+1, \ldots, a_k+1$ must be odd.
Hint 2: In order for $d(n)$ to be odd, prove that $k=1$ and that $a_1+1$ must be prime.


JQuery sorting a table without the plugin

Question: Is there a jquery function to sort a table. I am aware of the JQuery Tablesorter plugin but I want to avoid using it if possible.
As a FYI - The table that I have a header with custom images to indicate ascending and descending. The data type could be pretty much any type.
EDIT:Can I do sorting of a table in Javascript?
Comment: my solution worked for you?
Answer: It is very much possible. You can do it like this
function sortTable(table, col, reverse) {
    var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
        tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
        i;
    reverse = -((+reverse) || -1);
    tr = tr.sort(function (a, b) { // sort rows
        return reverse // `-1 *` if want opposite order
            * (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
                .localeCompare(b.cells[col].textContent.trim())
               );
    });
    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

function makeSortable(table) {
    var th = table.tHead, i;
    th && (th = th.rows[0]) && (th = th.cells);
    if (th) i = th.length;
    else return; // if no `<thead>` then do nothing
    while (--i >= 0) (function (i) {
        var dir = 1;
        th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
    }(i));
}

function makeAllSortable(parent) {
    parent = parent || document.body;
    var t = parent.getElementsByTagName('table'), i = t.length;
    while (--i >= 0) makeSortable(t[i]);
}

window.onload = function () {makeAllSortable();};

Take a look at this Fiddle
(I am not the author of code above or that fiddle, I just found it while searching for the solution.)
Comment: This one is working perfectly, the only issue is when there are numeric data in the columns, its not sorting properly. 1, 1112, 2, 54, 73 should be sorted as 1, 2, 54, 73, 1112. But here its taking each number as a character and then sorting. Any solution for this. I have tried to convert the values using parseInt() but not working.
Comment: and what if I have multiple tables and I only want to sort one table?
Comment: parent.getElementsByTagName('table')[1] -- for 2nd tale
Answer: Javascript guru Stuart Langridge has a nice alternative to using jQuery called tablesorter.js
http://www.kryogenix.org/code/browser/sorttable/
I've used it before; works great and it's pretty lightweight.
Comment: Your answer doesn't fullfill the question: without a plugin.
Answer: I had to change the sorting function a little bit so it would ignore non-numeric chars,
hopefully this will save somebody some time....
function sortTable(table, col, reverse) {
    var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
    tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
    i;

    reverse = ((+reverse) || -1);

    tr = tr.sort(function (a, b) { // sort rows
        return reverse * (Number(a.cells[col].textContent.replace(/[^\d.-]/g, ''))
             - Number(b.cells[col].textContent.replace(/[^\d.-]/g, '')));
    });

    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}

Answer: https://www.w3schools.com/howto/howto_js_sort_table.asp
function sortTable() {
  var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
  switching = true;
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /* Loop through all table rows (except the
    first, which contains table headers): */
    for (i = 1; i < (rows.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Get the two elements you want to compare,
      one from current row and one from the next: */
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      // Check if the two rows should switch place:
      if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        // If so, mark as a switch and break the loop:
        shouldSwitch = true;
        break;
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark that a switch has been done: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
  }
}

Answer: For small tables, I do it this way...
sortTable = function(tableName, rowClass, columnNumber, ascending) {
    var row, cell, cellContent;
    var comparisonRow, comparisonCell, comparisonContent;

    $("#" + tableName + " tr." + rowClass).each(function(i) {
        row = $("#" + tableName + " tr." + rowClass + ":eq(" + i + ")");
        cell = $(row).find("td:eq(" + columnNumber + ")");
        cellContent = $(cell).html();

        $("#" + tableName + " tr." + rowClass).each(function(j) {
            comparisonRow = $("#" + tableName + " tr." + rowClass + ":eq(" + j + ")");
            comparisonCell = $(comparisonRow).find("td:eq(" + columnNumber + ")");
            comparisonContent = $(comparisonCell).html();

            if ( (ascending && cellContent < comparisonContent) || (!ascending && cellContent > comparisonContent) ) {
                $(row).insertBefore(comparisonRow);
                return false;
            }
        });
    });
};

Explanation: The function walks through each row (of a specified class) of the specified table, takes note of the HTML content (from the cell of the specified column), and then walks through all of the table's rows comparing the cell content (again from the specified column). When the cell content is less or greater (based on whether "ascending" is set to true), the row is inserted in front of the one to which it was being compared.
A sample call would be...
sortTable("sample_table", "data_row", 0, true);

...which would sort rows that have the class "data_row", inside the table named "sample table", based on cells in the first column (i.e, column index 0) in ascending order.
For larger tables and additional features, I use...

DataTables

Right of the box, I find DataTables much easier to use than TableSorter (e.g., no need for referencing or incorporating additional CSS and artwork unless you want), and the documentation is excellent. I also like the default functionality (e.g., its Search function).


Grant writing permission to /snap devices

Question: I installed blender with snap and I want the app to use blender's numix-circle-icon so I tried to replace /snap/blender/47/blender.svg but I have this error with sudo:
File systeme is only readable I test to chmod it but it make same error. I found those directory are mounted device from /var/lib/snapd/snaps/ So I ask you, how to grant writing on snap devices & them mounted dirs?
Comment: However, see https://askubuntu.com/a/1278031/19626 for how to override the snap-provided .desktop file. You can point to a different icon.
Comment: It's not a *permission* issue. Snaps use squashfs, which is compressed and read-only. You simply cannot change any content without re-making the entire Snap package.
Answer: There is a snap application called 'overlay' - you can install it via Snap Store. This little app makes it possible to remount a snap read/write. However, it needs to be repeated every time the system starts up, so you have to write a script that is called on system startup, which remounts the particular snap r/w using 'overlay' and copies the needed files there. (Actually you don't have to use the 'overlay' application, you can remount a snap r/w using just 'mount' command with overlayfs, but that application simplifies it).
Comment: Thanks you very much for your answer!


Sonarqube migration 6.7.7 LTS to 7.9 => ERROR: relation "live_measures" already exists (PostgreSQL)

Question: Database (PostgreSQL) migration failed with 'Create table live_measures' failed, caused by
ERROR: relation "live_measures" already exists

when updating SonarQube from 6.7.7 LTS to 7.9 LTS
2019.07.12 07:25:41 INFO  web[][o.s.s.p.d.m.DatabaseMigrationImpl] Starting DB Migration and container restart
2019.07.12 07:25:41 INFO  web[][DbMigrations] Executing DB migrations...
2019.07.12 07:25:41 INFO  web[][DbMigrations] #1930 'Add QUALITY_GATES.IS_BUILT_IN'...
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1930 'Add QUALITY_GATES.IS_BUILT_IN': success | time=177ms
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1931 'Populate QUALITY_GATES.IS_BUILT_IN'...
2019.07.12 07:25:42 INFO  web[][o.s.s.p.d.m.s.MassUpdate] 3 quality_gates processed (0 items/sec)
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1931 'Populate QUALITY_GATES.IS_BUILT_IN': success | time=64ms
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1932 'Make QUALITY_GATES.IS_BUILT_IN not null'...
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1932 'Make QUALITY_GATES.IS_BUILT_IN not null': success | time=62ms
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1933 'Remove quality gates loaded templates'...
2019.07.12 07:25:42 INFO  web[][o.s.s.p.d.m.s.MassUpdate] 1 delete loaded templates for quality gate processed (0 items/sec)
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1933 'Remove quality gates loaded templates': success | time=16ms
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1934 'Rename quality gate "SonarQube way" to "Sonar way"'...
2019.07.12 07:25:42 INFO  web[][o.s.s.p.d.m.s.MassUpdate] 1 quality gates processed (0 items/sec)
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1934 'Rename quality gate "SonarQube way" to "Sonar way"': success | time=9ms
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1935 'Drop LOADED_TEMPLATES table'...
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1935 'Drop LOADED_TEMPLATES table': success | time=133ms
2019.07.12 07:25:42 INFO  web[][DbMigrations] #1936 'Delete person measures'...
2019.07.12 07:26:26 INFO  web[][o.s.s.p.d.m.s.MassUpdate] 66219 snapshots processed (1103 items/sec)
2019.07.12 07:26:26 INFO  web[][DbMigrations] #1936 'Delete person measures': success | time=44397ms
2019.07.12 07:26:26 INFO  web[][DbMigrations] #1937 'Drop index on project_measures.person_id'...
2019.07.12 07:26:26 INFO  web[][DbMigrations] #1937 'Drop index on project_measures.person_id': success | time=22ms
2019.07.12 07:26:26 INFO  web[][DbMigrations] #1938 'Create table live_measures'...
2019.07.12 07:26:26 ERROR web[][DbMigrations] #1938 'Create table live_measures': failure | time=27ms
2019.07.12 07:26:26 ERROR web[][DbMigrations] Executed DB migrations: failure | time=44914ms
2019.07.12 07:26:26 ERROR web[][o.s.s.p.d.m.DatabaseMigrationImpl] DB migration failed | time=45028ms
2019.07.12 07:26:26 ERROR web[][o.s.s.p.d.m.DatabaseMigrationImpl] DB migration ended with an exception
org.sonar.server.platform.db.migration.step.MigrationStepExecutionException: Execution of migration step #1938 'Create table live_measures' failed
at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:79)
at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:67)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:52)
at org.sonar.server.platform.db.migration.engine.MigrationEngineImpl.execute(MigrationEngineImpl.java:68)
at org.sonar.server.platform.db.migration.DatabaseMigrationImpl.doUpgradeDb(DatabaseMigrationImpl.java:105)
at org.sonar.server.platform.db.migration.DatabaseMigrationImpl.doDatabaseMigration(DatabaseMigrationImpl.java:80)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalStateException: Fail to execute CREATE TABLE live_measures (uuid VARCHAR (40) NOT NULL,project_uuid VARCHAR (50) NOT NULL,component_uuid VARCHAR (50) NOT NULL,metric_id INTEGER NOT NULL,value NUMERIC (38,20) NULL,text_value VARCHAR (4000) NULL,variation NUMERIC (38,20) NULL,measure_data BYTEA NULL,update_marker VARCHAR (40) NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL, CONSTRAINT pk_live_measures PRIMARY KEY (uuid))
at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:97)
at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:77)
at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:117)
at org.sonar.server.platform.db.migration.version.v70.CreateTableLiveMeasures.execute(CreateTableLiveMeasures.java:53)
at org.sonar.server.platform.db.migration.step.DdlChange.execute(DdlChange.java:45)
at org.sonar.server.platform.db.migration.step.MigrationStepsExecutorImpl.execute(MigrationStepsExecutorImpl.java:75)
... 9 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: relation "live_measures" already exists
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:307)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:293)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:270)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:266)
at org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:175)
at org.apache.commons.dbcp2.DelegatingStatement.execute(DelegatingStatement.java:175)
at org.sonar.server.platform.db.migration.step.DdlChange$Context.execute(DdlChange.java:82)

Comment: The official answer is to restore your database and try it again. But first try to delete the table mentioned by hand and try to start the migration again. Check the end result if this succeeds and keep your saved database for a while.
Answer: Thank's so much @jeroen-heier
That pointed me to the right direction. After
DROP TABLE "live_measures";
ALTER TABLE organization_alm_bindings DROP COLUMN members_sync_enabled;
ALTER TABLE webhooks DROP COLUMN secret;

the migration finished successful. Thank you.

Sonarqube migration 6.7.7 LTS to 7.9 => ERROR: relation “live_measures” already exists (PostgreSQL)


How to detect multiple clicks in a row on a button - like android developer options

Question: I would like to implement the a similar behaviour to android settings app of the developer options. I mean when a user clicks on a button for a 7 times in a row with a small delay between every click a popup will appear ask him to enable an hidden feature in the app.
How can I implement this behaviour?
Comment: On each click increase a counter :) If you want to check for the time save also a time variable and compare with it and on each click update the it. If the time is longer than predefined time interval, just start counting from 1 again.
Comment: I thought maybe there is a something which is already implemented by system like double click or long click :)
Comment: Well there might be, but It seems faster to just write it sometimes :)
Comment: @kirotab as the good solution, but you have to add a timer when the button is clicked, so when a click is too far after the previous one it restarts to 0 instead of pursuing the count.
Answer: I have developed it based on the watchdog concept. An instance of TimerWatchDog does the job if it doesn't refresh in the specified time. ContinuousClicksHandler uses an instance of TimerWatchDog along with counting the clicks.
Usage:
val clicksCount = 7
val maxInterval = 1000L

val continuousClicksHandler = ContinuousClicksHandler(clicksCount, maxInterval)

continuousClicksHandler.registerCallback(object : ContinuousClicksHandler.ContinuousClicksCallback {

    override fun onContinuousClicksSuccessful() {
        println("onContinuousClicksSuccessful!")
    }

    override fun onContinuousClicksFailed() {
        println("onContinuousClicksFailed!")
    }

})

button.setOnClickListener {
    val count = continuousClicksHandler.click()
    showToast("Needs ${clicksCount - count} more clicks to succeed!")
}

ContinuousClicksHandler.kt
/**
 * @author aminography
 */
class ContinuousClicksHandler(
    private val clicksCount: Int,
    maxInterval: Long
) {

    private var callback: ContinuousClicksCallback? = null
    private val timerWatchDog = TimerWatchDog(maxInterval)
    private var currentClicks = 0

    fun click(): Int {
        if (++currentClicks == clicksCount) {
            timerWatchDog.cancel()
            currentClicks = 0
            callback?.onContinuousClicksSuccessful()
        } else {
            timerWatchDog.refresh {
                currentClicks = 0
                callback?.onContinuousClicksFailed()
            }
        }
        return currentClicks
    }

    fun registerCallback(callback: ContinuousClicksCallback) {
        this.callback = callback
    }

    interface ContinuousClicksCallback {

        fun onContinuousClicksSuccessful()

        fun onContinuousClicksFailed()
    }

}

TimerWatchDog.kt
import java.util.*

/**
 * @author aminography
 */
class TimerWatchDog(private val timeout: Long) {

    private var timer: Timer? = null

    fun refresh(job: () -> Unit) {
        timer?.cancel()
        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() = job.invoke()
        }, timeout)
    }

    fun cancel() = timer?.cancel()

}

Answer: You can do this with this OnClickListener. It works with 7 continuous clicks with less than 500ms between each click. Basically, we just remember the number of clicks and the time of the last click and work with that. Shouldn't be too hard to understand and/or modify.
...
view.setOnClickListener(continuousClickListener);
...

private final View.OnClickListener continuousClickListener = new View.OnClickListener() {

    private long lastTimeMs = 0;
    private int clickCount = 0;

    @Override
    public void onClick(View v) {
        long now = System.currentTimeMillis();
        if (lastTimeMs == 0 || now - lastTimeMs < 500) {
            lastTimeMs = now;
            clickCount++;
            if (clickCount >= 7) {
                // do stuff
                showToast("quiz enabled");
            } else {
                if (clickCount > 2) {
                    showToast((7-clickCount) + " more for quiz");
                }
            }
        } else {
            lastTimeMs = 0;
            clickCount = 0;
        }
    }
};

Answer: Thanks for your smart code.
I've noticed a tiny bug. It happens when you click once, then wait more than 500ms then click again. This second click was not taken into account. So I adapted a little your code. NOTE: I removed the counter indication because I don't need it.
Here's the code:
private final View.OnClickListener continuousClickListener = new View.OnClickListener() {

        private long lastTimeMs = 0;
        private int clickCount = 0;

        @Override
        public void onClick(View v) {
            long now = System.currentTimeMillis();
            if (lastTimeMs == 0 || now - lastTimeMs < 500) {
                lastTimeMs = now;
            } else {
                lastTimeMs = 0;
                clickCount = 0;
            }
            clickCount++;
            if (clickCount >= 7) {
                Toast.makeText(getBaseContext(),
                        "Connection with test profile", Toast.LENGTH_SHORT).show();
            }
            Log.v(TAG, "clickCount=" + clickCount);
        }
    };

Thanks !


What is the "Browser" process?

Question: What is the Browser process?
Is the process safe or malicious?
Thanks for help,
Top results:
Answer: To know from what folder this Process is running :
<code>   sudo ls -l /proc/<Pid>/cwd
</code>
In your case Pid is  24916
So you can know what is this "Browser"

What is the "Browser" process?


How to detect 15 to 20 item in minecraft?

Question: In Minecraft, how can I detect five or more item in players inventory?
I alraedy know: <code>@p[nbt={Inventory:[{id:"minecraft:cod",Count:5b}]}]</code>
But it only works with five item and no more or less.
Comment: @MBraedley Please refrain from answeing in comments if you can't provide a full answer. It might discourage other users from answering, and it feels almost like "reserving" an answer for you.
Answer: You can tally how many of an item a player has in their inventory, then use /scoreboard to detect if that tally is more or less than 5.
First, create a dummy objective. This will keep track of how many of a certain item you have in your inventory (in this example, cods)
<code>/scoreboard objectives add cod_count dummy
</code>
Next, run this command to match your cod_count score with your item count.
<code>/execute as @p store result score @s cod_count run clear @s cod 0
</code>
You can now detect if you have 5 or more cods with this command:
<code>/execute as @p[scores={cod_count=5..}] run tellraw @s "You have more than 5 items"
</code>
Detecting a range, like in your title, is just as easy:
<code>/execute as @p[scores={cod_count=15..20}] run tellraw @s "You have between 15 and 20 items"
</code>
Comment: If you want to do this for all players on a multiplayer server, it's a simple matter of switching the `@p`'s with `@a`.
Comment: …and if you want it for a single stack, you need to type out the command for 15, 16, 17, 18, 19 and 20.


Vuetify Navigation Drawer Starts Closed and Then Opens a Second Later

Question: I have set up a Vuetify Navigation Drawer on NuxtJS using Vuex to handle the state of the drawer.  Everything works fine except for one problem -- namely, that when I load the page on a desktop, the drawer starts out closed and then a split second later opens up.  Here is a video of my doing a hard refresh to see what I am referring to:  https://www.loom.com/share/477eb0933b3840d2bf7a9b55aaa8e934
Here is my code:
//app-bar.vue
<template>
  <v-app-bar app color="indigo" dark>
    <v-app-bar-nav-icon @click.stop="mainDrawer = !mainDrawer" />
    <v-toolbar-title>Application</v-toolbar-title>
  </v-app-bar>
</template>

// nav-drawer.vue
<template>
  <v-navigation-drawer v-model="mainDrawer" app>
    <v-list dense>
      ...LIST_ITEMS
    </v-list>
  </v-navigation-drawer>
</template>

// index.js (vuex file)
import Vuex from "vuex";

const createStore = () => {
  return new Vuex.Store({
    state: {
      mainDrawer: null
    },
    getters: {
      getMainDrawer: state => state.mainDrawer
    },
    mutations: {
      toggleMainDrawer(state, value) {
        state.mainDrawer = value;
      }
    },
    actions: {
      toggleMainDrawer({ commit }, value) {
        commit("toggleMainDrawer", value);
      }
    }
  });
};

export default createStore;

Any idea why this is happening and what I can do to change it.  I should note, that when I run the page using Android Studio Emulator it works just fine.  It's only desktop that I have an issue.
Thanks.
Comment: I just came across this same issue. Any chance you found an answer?
Answer: I had the same issue and tried many ways to fix it.
The only way i have found so far is to use the navigation drawer prop called disable-resize-watcher .
Its default value is false, so when you reload the page for some reason the nav drawer opens up. Setting this prop's value to true will fix the problem.
Comment: Thanks! It was driving me nuts; for me this issue popped after an update..
Comment: I am facing the same issue and `disable-resize-watcher` is not work for me
Comment: adding `disable-resize-watcher` worked for me thanks
Comment: `disable-resize-watcher` not working
Answer: Few things that you should look into to fix this:

Are you using v-app as the root of your appliacation. According to this doc, it is mandatory to do it.
Do you really need app prop on your v-navigation-bar and v-app-bar. The documentation describes it's use:

Designates the component as part of the application layout. Used for dynamically adjusting content sizing. Components using this prop should reside outside of v-content component to function properly.


Global variable seg fault

Question: I am getting a segmentation fault and I cannot figure out why. I have a global TcpClient object that has a pointer to an Agent object. I am trying to access the agent pointer in a function when the segmentation fault occurs. In main, I have the cout statements before and after I set the agent member in TcpClient and both statements give me the same address.
TcpClient client((char*)PORT);
Agent* agent = new Agent;

int main(int argc, char* args[]) {
    //initialization code for agent's members
    cout<<"\nagent: "<<agent;
    client.setAgent(agent); //set it here
    cout<<"\nclient agent: "<<client.getAgent()<<"\n";
}

Then I have this function in TcpClient that gets called during the run (after setting the agent of course). I get the segmentation fault when I try to access agent. I have a cout statement in the beginning that tells me agent is 0x0.
void TcpClient::getCommand(char* command) {
    std::cout<<"\nagent: "<<agent;

}

The setAgent is a typical setter -
void TcpClient::setAgent(Agent*& a) {agent = a;}

class Agent;
class TcpClient {
    //functions and stuff
private:
    Agent* agent;
};

The agent member isn't accessed anywhere else in the code. The only thing I can come up with is that there is something about the TcpClient object being global that could make this happen, but I do not know what. Am I right about this? Any help is appreciated.
When I run the code, the debugger says -
Program received signal SIGSEGV, Segmentation fault.
__memcpy_ssse3_rep () at ../sysdeps/i386/i686/multiarch/memcpy-ssse3-rep.S:1454
1454    ../sysdeps/i386/i686/multiarch/memcpy-ssse3-rep.S: No such file or directory.
    in ../sysdeps/i386/i686/multiarch/memcpy-ssse3-rep.S
(gdb) back
#0  __memcpy_ssse3_rep ()
    at ../sysdeps/i386/i686/multiarch/memcpy-ssse3-rep.S:1454
#1  0x08049c52 in Agent::setGoal (this=0x0, g=...) at agent.cpp:33
#2  0x0805075e in TcpClient::getCommand (this=0x805aac8,
command=0xbffff18d "1 3 1\n") at tcpclient.cpp:80
#3  0x08050b8d in TcpClient::communicate (this=0x805aac8) at tcpclient.cpp:153
#4  0x0804e0f8 in main (argc=1, args=0xbffff3f4) at mainclient.cpp:119

Comment: Don't use `new` when you don't need it. Don't use global variables. Don't use `char*`. Use a debugger to see where the segfault occurs.
Comment: Where/when is `Agent* agent = new Agent;` being called?
Comment: That is in the main file above the int main() function.
Comment: I do that because I need to access that in a thread function in main.
Comment: What did your debugger say? Seems to me like you are running into static initialisation order problems, and that the code pasted does not accurately represent the code you're _actually_ running.
Comment: original post is updated with debugger
Comment: If that's the case, leave myAgent as a pointer (`Agent*`) and simply do `myagent = a;`
Comment: (Thought I posted this earlier but I guess it didn't finalize or something) - I do not have enough rep to answer my own question. I got the segmentation fault to go away, but I'm not sure why. I have a function called communicate (which just lets server and client talk to each other) that calls the getCommand function I posted above. Right before I call getCommand, there was a memset call for a local char*. All I did was remove that line and the segmentation fault went away. I don't know why that worked, but it did. Thanks everyone for the help.
Answer: You should read the compiler/linker warnings, I'm fairly sure it'll be throwing some at you about ambiguous names.
Do not use "agent" as a variable name for class members when you've already defined it earlier as a global; use something like private: Agent* myAgent; (and of course change setAgent to use it) and you should hopefully find the issue goes away.
Additionally, *& basically cancels itself out; the private member is a pointer so you should be using a pointer in the set method - I suspect your segfault is because of a bad operation on either what it thinks is a pointer and actually isn't or vice versa.
Comment: I don't get any warnings when I compile it. Unfortunately, this did not help the problem I have now, but I will remember this in future programs.
Comment: also, why are you using `TcpClient::setAgent(Agent*& a)` - the private member is a pointer so it should just be `Agent* a` - please also show the code for `TcpClient::getAgent()`
Comment: Agent*& TcpClient::getAgent() {return myAgent;}
Comment: yeah, declare myAgent as simply `Agent` not `Agent*&` then in setAgent do `myAgent = *a;`
Comment: What if he doesn't want a copy, but for the two pointers to point to the same object?  In that case, what's being done is completely reasonable.
Answer: I have a function called communicate (which just lets server and client talk to each other) that calls the getCommand function I posted above. Right before I call getCommand, there was a memset call for a local char*. All I did was remove that line and the segmentation fault went away.
Thanks for help everyone.
Comment: originally was a comment because I did not have enough rep to answer, but figured I would go ahead make it an answer so I can accept.
Answer: Is void TcpClient::setAgent(Agent*& a) {agent = a;} written as intended, or did you mean Agent *a?
If you pass an Agent object, the syntax is Agent &a, which means "a is the address of the passed Agent object."
If you pass a pointer (which you're doing here), the syntax is Agent *a, which means "a is passed as a (possibly null) pointer to an Agent object."
Comment: Well no, Agent *a would be passing the address of an Agent object, because that is what pointer contains.  Agent &a would be passing an actual Agent variable to the TcpClient, and if you wanted the TcpClient Agent to point to the same object, you'd still need to get the memory location by calling `agent = &a`.
Comment: I meant it as is. My understanding is that I am passing a reference to a pointer, instead of just a copy. So when I access the pointer and change something about it, it gets changed in other places as well.
Comment: What the OP is doing is passing a reference to a pointer, so that he has a handle on the actual pointer variable he passed in.  If he wanted, he could change what a points to and it would also change what the global agent variable points to, but that is not what is being done so it seems unnecessary.  `setAgent(Agent *a)` should suffice.

Global variable seg fault


Need advice which template is better?

Question: I posted here recently looking to improve a template in hopes to increase engagement with the page and decrease bounce rate.
Here is an example of a page how it used to look before:
http://www.problemio.com/problems/problem_dev.php?problem_id=213
Here is what it looks like now thanks to the advice on people here:
http://www.problemio.com/problems/problem.php?problem_id=213
Here is what I changed:
<code>1) problem text has white background
2) Social bookmarks and voting moved to the right so it doesn't distract from main content
3) I aligned the grid lines to be more consistent throughout the page. (does it show?)
</code>
Which one looks better the problem_dev.php link? Or the problem.php ?
Also, what other improvements should I make? I am sure many things are still not perfect with the page.  Any suggestions what to improve next?
Also, one question: on the right side divs, the headings for them, should they be centered or left-adjusted?
Comment: You still didn't implement one of the main suggestions: show proposed solutions in full.
Comment: @dnbrv the reason I didn't do it is that I am still wondering if it might to a good way to get people engaged with the site.. might do it soon at some point...not sure.
Comment: Also, I am getting mixed feedback on whether I should present all the content at once, or get people engaged with it bit by bit and discover features, etc.  So not too certain how to best handle it.
Comment: You should post screen shots of the different layouts as well to avoid link rot and so users don't have to use external URLs.
Comment: Hi Genadinik, please make your question more specific - right now you're asking for general critique, which is something this site isn't meant for. Try editing your question to ask something specifically about UI or UX and less a matter of a person's opinion on which is better.
Comment: @Rahul ok makes sense - in the future will try to be more specific :)
Answer: "problem_dev" is better, not because it looks better, but because the points of interaction are better grouped.
Voting up and down, when moved into the sidebar will be easy to ignore entirely, when I assume it's something you really want to promote.
In addition, I recommend using fewer boxes, allowing more white space.
Move 'email friends' to the sidebar, reserve main column for core functionality.
Comment: well, you see, I was thinking that the more important interaction would be to comment, or suggest problem solutions. Tats why I moved the voting to the side.
Comment: If this site is supposed to be something like StackExchange sites, then what even more important than gathering answers is providing _relevant_ answers. The cream needs to rise to the top. There's no shame in starting with what works and tweaking it.

Need advice which template is better?


TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough'

Question: I am  try to create Transformation Pipeline for housing data
from sklearn.base import BaseEstimator, TransformerMixin
rooms_ix, bedrooms_ix, population_ix, household_ix = 3,4,5,6
class CombineAttributesAdder(BaseEstimator, TransformerMixin):
    def __init__(self, add_bedrooms_per_room = True):
        self.add_bedrooms_per_room = add_bedrooms_per_room
    def fit(self, X, y=None):
        return self
    def transfrom(self, X, y=None):
        rooms_per_househond = X[:,rooms_ix]/X[:,household_ix]
        population_per_household = X[:,population_ix]/ X[:, household_ix]
        if self.add_bedrooms_per_room:
            bedrooms_per_room = X[:,bedrooms_ix]/X[:rooms_ix]
            return np.c_[X, rooms_per_househond, population_per_household, bedrooms_per_room]
        else:
            return np.c_[X, rooms_per_househond, population_per_household]

My Pipeline code which i used for Pipeline  :-
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from imblearn.pipeline import make_pipeline
num_pipline = Pipeline([
    ('imputer', SimpleImputer(missing_values=np.nan, strategy='median')),
    ('attribs_adder', CombineAttributesAdder(add_bedrooms_per_room=False)),
    ('stand_scaler', StandardScaler()),
])
housing_num_transform = num_pipline.fit_transform(housing_num)

It trough Error :-
Comment: You defined the `transfrom` method, but meant `transform`.
Comment: Please add more details which line I need to change
Answer: In the body of your CombineAttributesAdder class, you misspelled the word transform. The method definition should look like this:
class CombineAttributesAdder(BaseEstimator, TransformerMixin):

    def __init__(self, add_bedrooms_per_room = True):
        self.add_bedrooms_per_room = add_bedrooms_per_room

    def fit(self, X, y=None):
        return self

    def transform(self, X, y=None):  # <-- not 'transfrom'
        ...

For each transformer, Pipeline objects will call fit_transform  which, in turn, will call the methods fit and transform. Because of this typo, the program cannot find the corresponding method and throws the error.


Balkan OrgChart nodeMenu stops working if I edit its HTML

Question: The menu works fine but it is off to the right so i need to move it left. Once i edit it, the button no longer brings up the nodeMenu.
var chart = new OrgChart(document.getElementById("tree"), {
    template: 'myTemplate',
    enableSearch: true,
    scaleInitial: 0.5,
    layout: OrgChart.treeRightOffset,
    sticky: false,
    menu: {
        pdf: { text: "Export PDF" },
        png: { text: "Export PNG" },
        svg: { text: "Export SVG" },
        csv: { text: "Export CSV" }
    },
    toolbar: {
        fit: true,
        expandAll: true,
        collapseAll: true,
    },
    collapse: {
        level: 3,
        allChildren: true
    },
    editUI:  new editForm(),
    nodeBinding:{
        field_0: 'name',
        field_1: 'title',
        img_0: 'avatar'
    },
    nodeMenu: {
        add: { text: "Add" },
        edit: { text: "Edit" },
        remove: { text: "Remove" }
    },

Once i add the code below, the nodeMenu button will look different, changes the pointer on hover but now clicking on it has no effect.
OrgChart.templates.myTemplate.nodeMenuButton =
    '<g style="cursor:pointer;" transform="matrix(1,0,0,1,193,15)" data-ctrl-n-menu-id="{id}">'
    + '<rect x="-4" y="-10" fill="#000000" fill-opacity="0" width="22" height="22">'
    + '</rect>'
    + '<line x1="0" y1="0" x2="0" y2="10" stroke-width="2" stroke="rgb(255, 202, 40)" />'
    + '<line x1="7" y1="0" x2="7" y2="10" stroke-width="2" stroke="rgb(255, 202, 40)" />'
    + '<line x1="14" y1="0" x2="14" y2="10" stroke-width="2" stroke="rgb(255, 202, 40)" />'
    + '</g>';

Answer: Your nodeMenu works just fine.
Your trial may have expired or you have another issue.
Please create code demo to isolate the issue.
Answer: It was a bug in the software, fixed by using a later version.
After reaching out to Balkan it was a confirmed bug as I was using a licensed version that was 2 years old.
When you use the Balkan code editor you access their latest free version via . Which is why it was working through the code example but not on my test environment.
It is very important to always make sure to reference software versions when dealing with a peculiar issue.


How to kill a Brute effectively

Question: The Brutes are giant Reaper-Giant hybrids that are very well armored, to the point where I'm sure their entire health bar is their armor.  However, it seems to me that there is a certain point where it is most weak against my shots but I am unable to figure out which part of its body to aim for.
Any suggestions?
Comment: Just handled my first one.  That thing was a bear to deal with...
Comment: The first scripted one was fine, but facing the 2 after kinda jumped me in the middle of a melee kill...it wasn't pretty.
Answer: Your initial thoughts are correct about the armor. This link describes how to kill a brute and offers a brief video with some general info.
http://www.ign.com/wikis/mass-effect-3/Brute
Brute's defenses consist entirely of a yellow Armor bar. To deplete this you can use fire-based attacks and Powers meant to reduce armor. The most important thing to remember is to keep your distance. Stay behind cover and roll out of the way when it nears you. If it hits you, your shields will evaporate. Hit it with Grenades and other explosives. Armor Piercing Rounds and Disrupter Ammo are good to help reduce the armor, but explosives can momentarily pause the creature, giving you valuable time to get away.
The other thing I've been doing a lot is saving my grenades for large enemies and bosses only.  I've really only had to deal with brutes and atlases so far, but having grenades while your other abilities are in cooldown makes a big difference.
Answer: As with most creatures, Aim for the Head!
Specifically, you'll want to aim for that Turian head grafted onto the front of the Brute. Nail it right between the eyes, and it won't last long.
Comment: This wasn't true until the 10/4/2012 patch that now allows for 40% bonus to headshots on brutes, banshees, and geth primes.
Comment: simple but true...  DO IT!
Answer: As a Sentinel, I've found that the Lob Grenade power is extremely useful, particularly when you're being surrounded by multiple brutes. 3-4 grenades should drop them to almost 1/4 of their armor strength.
Couple of shots of Warp interspersed with Lob Grenades should make mincemeat of the brutes. Also, do run away from brutes - climb the ladders, brutes can't climb them. Close/melee encounters with the brute will leave you in jelly in no time
Answer: Vanguard with fast power recharge could easily melee even groups of brutes. (At least on normal difficulty.)
Just charge, hit, roll side-way and charge again. Repeat until brute is dead.
One thing: Do not charge while brute is about to pouce. It will interrupt your melee and drop your shields.
Answer: The soft spot is the exposed spine just behind the head.  Not as much armor plating there so you can knock a good chunk of his armor down.
Answer: with the vanguard, you can easily kill numerous brutes using charge and nova. just make sure you have a fast cool down and you move back or sideways before you nova. thats if you got the radius for nova. same tactic with banshee

How to kill a Brute effectively


Disable/Non-Clickable an HTML button in Javascript

Question: I have following HTML snippet for a button:
HTML:

      <button id="reset" type="reset" title="Clear Photos"></button>

      Clear

CSS:
div.ClearButton
{
   vertical-align: top;
   display: inline-block;
   background: url(../CustomControl/buttons.png?ver=365321878) no-repeat scroll -343px -443px rgba(0, 0, 0, 0);
   height: 16px;
   overflow: hidden;
   width: 16px;
}

div.Clear
{
   vertical-align: top;
   display: inline-block;
   overflow: hidden;
   cursor: pointer;
   padding-left: 2px;
   padding-bottom: 6px;
   padding-right: 6px;
   padding-top: 4px;
}

On a certain event, I need to disable this button completely. I tried with the following code, but it does not disable/gray out the button and it's still clickable.
var resetBtn = document.getElementById("reset");
resetBtn.disabled = true;

As someone suggested that the CSS I have applied is causing this issue. Please suggest how can I make this button non-clickable.
Comment: Setting `.disabled` on the element *should* work.  Is it not?  Is this code executing at all?  Is `resetBtn` being populated with a DOM element at all?
Comment: Yes code is executing and resetBtn is being populated with a DOM element.
Comment: That should work, .disabled = true is a way to disable a button. Furthermore, it works in this fiddle: http://jsfiddle.net/ZJeC4/ which probably means that you are calling it too early (button does not exist yet).
Comment: try this      ---           $('#reset').attr("disabled", "disabled");
Answer: Use :
resetBtn.disabled = "disabled";

This works in all browsers -> http://jsfiddle.net/fMV4B/
Answer: Using Only CSS:
//CSS
.no-click {pointer-events: none;}

<input class="no-click" />

Comment: This will still leave the button focusable and clickable by means of the keyboard.
Comment: this is the simplest answer
Answer: You can do it with the method : setAttribute()
Your js will be like that :
document.getElementById("reset").setAttribute('disabled','disabled');

Answer: This JSFiddle shows it working, based on this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_disabled. It could be that it's not working as expected because your CSS is making it visually appear different. Remove you CSS first to make sure the JavaScript it working as expected.
Here's the code for the JSFiddle:
<button type="button" id="test">Click Me!</button>

Do you have an example of when your JavaScript is running?
Comment: I am thinking the same way. I have placed all CSS in my post. Can you please suggest a way to disable button completely. The disable button code works when I remove CSS.
Comment: I'm guessing your background image (../CustomControl/buttons.png?ver=365321878) needs changing when you set 'disabled' to true. The easiest way to do this is to create a 'div.ClearButtonDisabled' class that has a different background image, slightly greyed out. Without being able to see the image and style of the button it's hard to know for sure.
Comment: good idea, i will do that but how can I remove hand-shaped cursor when I move the cursor over button?
Comment: A Button shouldn't have a hand icon. Even when clickable the button should have a default arrow pointer. In your CSS you're setting 'cursor: pointer' - this is where the hand-shaped cursor is coming from. In your disabled CSS class, set 'pointer: auto;'
Comment: use event.stopPropagation() in your event
Answer: Have you read through this answer or tried
https://stackoverflow.com/a/3014678/2992661
resetBtn.setAttribute('disabled', 'disabled');

Comment: Note that `setAttribute` is different than changing the *property* via `.disabled =`.  I think it should still work the same, though.
Comment: True, I'd just taken that from the linked article to save the OP the time :)
Comment: `setAttribute` does mostly make sense if the attribute not is natively supported.
Answer: Your code works fine.
The problem is almost certainly that the JavaScript code is either not being called at all or is being called in the wrong spot.
If you run this code immediately, make sure that the DOM is loaded (window.onload callback, or preferably have your JS code right before ).
Otherwise just make sure that any event that runs the JS code is actually firing.
Comment: JS runs fine. I have used alerts to verify this. I think the CSS I have applied is not allowing disabled property to work.
Answer: Try this code:
To disable the submit button with jQuery, you just need to add a "disabled" attribute to the submit button.
$('#buttonId').click(function(){

    $('#buttonId').attr("disabled", true);
});

To enable back the disabled submit button, set the "disabled" attribute to false, or remove the "disabled" attribute:
$('#buttonId').attr("disabled", false);
or
$('#buttonId').removeAttr("disabled");


ListViewItem content is not stretching when using a DataTemplateSelector

Question: My ListView is not behaving as I want and I can't seem to find anything useful on this topic.
So the problem is, that I have a ListView which uses a DataTemplateSelector based on Datatype.
So this all works fine and shows the correct control, but the problem is, that the items do not stretch horizontally!
All solutions regardings ListViewItems not stretching suggest to use

and to set
   ScrollViewer.HorizontalScrollBarVisibility="Disabled"

in the ListView.
This does work fine when no DataTemplateSelector is used, but in combination with that DataTemplateSelector it doesn't and the controls in the list do not get their parents size.
The DataTemplateSelector is by the book and works fine, so it is omitted here.
I tried all kind of combinations of Width="Auto", HorizontalAlignment and HorizontalContentAlignment, but I could not make it work. I could imagine that it might help to pass the Width or HorizontalContentAlignment in this DataTemplateSelector, but I couldn't find a way to do this.
Here is the minimal XAML:
 <UserControl.Resources>

    <DataTemplate x:Key="DrawDataTemplate" DataType="viewModels:DrawSectionViewModel">
      <infrastructure:DrawSectionItem />
    </DataTemplate>

    <DataTemplate x:Key="FeedDataTemplate" DataType="viewModels:FeedSectionViewModel">
      <infrastructure:FeedSectionItem />
    </DataTemplate>

    <infrastructure:SectionTemplateSelector x:Key="SectionTemplateSelector"
                                            FeedSection="{StaticResource FeedDataTemplate}"
                                            DrawSection="{StaticResource DrawDataTemplate}">
    </infrastructure:SectionTemplateSelector>

  </UserControl.Resources>

<ListView Grid.Column="0" Width="Auto" Margin="0,0,0,0"
              ItemsSource="{Binding LeftSections }"
              ItemTemplateSelector="{StaticResource SectionTemplateSelector}"
              ScrollViewer.VerticalScrollBarVisibility="Disabled"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              ItemContainerStyle="{StaticResource ListViewItemContainerStyle}" />

Any help would be greatly appreciated
Thanks
Added the item controls. The Draw section is pretty much the same structure.
<UserControl x:Class="Infrastructure.FeedSectionItem"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" Height="45" Width="188" FontFamily="Segoe UI Light" Background="Black"
              >

    <Grid Margin="0" >
        <StackPanel Orientation="Vertical" Margin="10,0,0,0" HorizontalAlignment="Left" Width="Auto">
            <TextBlock Text="Feed" Foreground="White" FontWeight="Bold" FontSize="16" />
            <TextBlock Text="" Foreground="White" FontWeight="Bold" />
        </StackPanel>
    </Grid>
</UserControl>

Comment: Could you share xaml for infrastructure:DrawSectionItem and infrastructure:FeedSectionItem?
Comment: Added it to the main question
Comment: Try to remove Width="188" from your UserControl.
Comment: Removing the width from the UserControl indeed does work! I would however only consider this a workaround, since now I can't really design my UserControl anymore because it shrinks automatically as no width is set. Setting the Grid to a width brings me back to the initial problem.  I could remove the width each time after designing the Control... works, but does not appear to be a clean solution for a theoretically easy problem.
Comment: Ok in that second a good workaround came to my mind, which is to add a MinWidth to the Control. Then it has a width which can be used for design and the actual width in the ListView is also working as expected.
Comment: You can use d:DesignWidth to set the width of the user control for design.
Answer: Remove Width="188" from your UserControl.
In the designer you can set d:DesignWidth="188"


How to transfer a Terraria PC map to Xbox One?

Question: I've looked around, and do not see a place in my Xbox One to look at specific files, so I have no clue how to drop maps onto my external drive to play Terraria on.
Background info: I bought an Xbox One for myself for Christmas, and it came with a 350gb hard drive and some of the smallest games take like 10gbs to download so I bought a 4tb drive for 100 dollars, much less than they wanted for a much smaller internal Xbox One drive by the way.
So how do I get a Terraria map from my PC onto my external drive, to play it on my Xbox? I've seen some kids on YouTube bragging about an all items map, but they don't show how to drop the map (transfer it from PC to Xbox).
So what do I do?
Answer: It's not possible. There are too many differences between the two games for them to be compatible with one another.
To make it even more impossible, when you plug an external hard drive into an Xbox One, it has to be formatted. That means all files on the drive will be wiped. So even if you put a PC map on it, it would get deleted in the format process. The same goes for when you plug the hard drive back into a PC.  You will have to format it again.
Comment: I'd suggest you don't try to copy files manually. Depending on what you do, you might even violate the Microsoft Terms of Service.
Comment: Also, I believe that YouTube video you watched was for Xbox 360.  I found a forum saying they were only able to get the all items map to work with that method. Still, with the hard drive formatting blocking you, it won't be possible.
Answer: If you can get a PC map to Xbox 360 the rest is easy get horizon, first extract a world's file from 360 Terraria with a world on it and then download your world and replace the contents of world0.wld with the one you want save and rehash and then plug it into the Xbox 360 if the world works then upload to Xbox One and download it once it's on Xbox One.


Having my applications open on startup

Question: Hello I am running Ubuntu Mate and what is anoying is when I have all my apps open and power off at the end of the day. The next mornining I have a blank screen and have to open up all the apps I use for the day. Is their a way to have that apps I want to use open when I power on?
Comment: Check https://askubuntu.com/a/1083619/66509 .
Comment: You've tagged you're running Lubuntu (ie. LXQt desktop) but say you're running Ubuntu-MATE.  Please provide OS & release details as what you've provided contradicts (MATE is a GTK3 desktop, LXQt used by Lubuntu is a Qt5 desktop, and what you're asking about is desktop related)
Answer: Click on the grid to open applications; at the top (in the search bar), enter 'startup' and click on the suggested 'startup applications'. You can then add the programs you want to open when you start up.

Having my applications open on startup


problem displaying cells in the tableview - Swift

Question: I am trying to display text in cell labels from information import into firebase. I currently have a problem, because the cells are formed, but I don't see the text information in the labels as shown in the pictures. can you tell me why i can't see the information and how to solve the problem.
Thanks.
 struct List {

var heure: String?
var date: String?
var location: String?
var event: String?
var title: String?
var comment: String?

    init(heure: String?, date: String?, location: String?, event: String?, title: String?, comment: String?) {
    self.heure = heure
    self.date = date
    self.location = location
    self.event = event
    self.title = title
    self.comment = comment
   }
}

class FourthViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var Button: UIButton!
@IBOutlet weak var TableView: UITableView!

var activityList = [List]()

var ref : DatabaseReference!
let userID = Auth.auth().currentUser?.uid

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 174
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activityList.count
    }
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(identifier: "PassViewController") as? PassViewController {
        vc.Heure?.text = activityList[indexPath.row].heure
        vc.Date?.text = activityList[indexPath.row].date
        vc.Location?.text = activityList[indexPath.row].location
        vc.Titre?.text = activityList[indexPath.row].title
        vc.Event?.text = activityList[indexPath.row].event
        vc.Comment?.text = activityList[indexPath.row].comment
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ActivityViewCell

        let test = activityList[indexPath.row]
        cell.Titre?.text = test.title
        cell.Heure?.text = test.heure
        cell.Date?.text = test.date
        cell.Location?.text = test.location
        cell.EventType?.text = test.event
        cell.comment?.text = test.comment

        return cell

        }

override func viewDidLoad() {
    super.viewDidLoad()
    TableView.register(ActivityViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
    ref = Database.database().reference()
    TableView.dataSource = self
    TableView.delegate = self
    fetchActivityList()

       }

func fetchActivityList() {

    ref = Database.database().reference()
    ref.child("Activities").child(userID!).observe(.childAdded, with: { (snapshot) in
                let results = snapshot.value as? [String : AnyObject]
                let titre = results?["Title"]
                let heure = results?["Heure"]
                let date = results?["Date"]
                let location = results?["Location"]
                let event = results?["EventType"]
                let comment = results?["Comment"]
        let myAct = List(heure: heure as! String?, date: date as! String?, location: location as! String?, event: event as! String?, title: titre as! String?, comment: comment as! String?)
                self.activityList.append(myAct)
                DispatchQueue.main.async {
                    self.TableView!.reloadData()
                }
           })
        }
    }

Image
Cell View
Comment: All your cells properties are optional. Are they `nil`? Like `cell.Titre`, is it nil? Where is defined your cell? In a xib? In Storyboard? If it's in a xib, you need to register the xib, not the class. When you do `let test = activityList[indexPath.row]`, could you check the values? You need to know if the issue in when fetching the data and retrieving it, or the UITableView part (ie display)...
Comment: The cell is defined in storyboard and all of values are nil
Comment: Which values? The cell labels, or the `activityList` properties?
Comment: all cell labels are nil
Comment: DId you connect the IBOutlets?
Comment: Yes, I connected the IBOutlets. I still have the problem. I put a breakpoint in fetchActivityList() and it tells me that all values are nil
Answer: First of all, you should carefully debug whether you fetched your activityList successfully. Set a breakpoint into your fetchActivityList() and print your results.
Secondly, its important how you instantiate a cell: either in InterfaceBuilder or directly in code. You have to register a cell based on type of instantiation.
@available(iOS 5.0, *)
open func register(_ nib: UINib?, forCellReuseIdentifier identifier: String)

@available(iOS 6.0, *)
open func register(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String)

Also, while registering a cell's class you may try to use ActivityViewCell.self instead of ActivityViewCell.classForCoder()
Futhermore, it would be great if you try to set breakpoints into
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

and
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

to figure out whats going on step by step.
I believe it would be great if you take a closer look to some codeStyle rules and try to keep them in future. For example, you may use Ray Wenderlich code style rules:
https://github.com/raywenderlich/swift-style-guide
And as another advice, try to get more information about architectural patterns (e.g. MV patterns). Thats the way to make your code clearer and objects relationships more intuitive.
I hope you're gonna figure out and resolve your issue! Have a nice day!
Comment: I put a breakpoint and In "cell" it tells me that all values are nil and section = (Int) 0


What is "ganking"?

Question: In reading about "griefing" and "smurfing", the term "ganking" came up...is there a good definition for it?
Comment: I would prefer to have a CW version for adding new terms, rather than asking a dozen of these
Comment: Is this going to be a chain question? Humour aside, I know of one definition (which is not griefing but an actual form of strategy) but don't know if it's necessarily a universal one.
Comment: Despite the answers both mentioning groups of players, a single player can absolutely gank other players.  If you're max level and you're in the first contested zone just killing every lowbie you see, then you're ganking them.
Answer: Ganking is when a big group of players team up on one lone player, usually by surprise.  Level differential is not necessary to be called ganking.  In many games (mostly MMOs), this is a form of griefing, but in other games it is a legitimate and encouraged strategy.
For example, in DotA, ganking is an integral part to team victory.  One player may roam around the map helping to ambush and team up on enemies who get caught out of position.
Comment: In World of Warcraft I've always heard the term being used as being killed by a single enemy player. I think it just means being ambushed unexpectedly where one side has the surprise advantage.
Comment: @Ivo: That's camping, which usually follows a gank, but isn't ganking in itself.
Comment: "big group of players team up on one lone player" that's not ganking - that's zerging.
Comment: In WoW ganking refers to killing that person over and over again and letting him corpse-run (being dead in WoW) back over and over again
Comment: @car i agree, in WoW usage its normally some rogue levels above you who pops up out of nowhere and stun-locks you and works you to death
Comment: Your answer is not consistent: `Ganking is when a big group of players team up on one lone player` vs `One player may roam around the map helping to ambush and team up on enemies who get caught out of position` is ganking group killing or ambushing?
Comment: @colind They are not mutually exclusive.
Comment: @davidb Terms are different per game. This is a generic definition that broadly applies across many games, but may not apply to all games. Zerging has connotations of unorganization and no leadership, however, while ganking can be very organized and is usually includes an ambush rather than mere overwhelming numbers.
Comment: I guess what I'm trying to say is that your first line reads like a definition "Ganking is x",  and that definition is not good.  I agree about "ambush" being an important part of the definition, but it's not mentioned until you get into examples.
Comment: @ColinD Actually, that is consistent—the one roaming character *joins up with* those already in that lane, so the surprise is that the enemy (who thinks it is safe, being an even match for its opponent in lane) is outnumbered and doesn't know it. Also, please do not abuse code formatting for quotation. Quotation marks, and if you must, italics or bold, do that job fine. Code formatting is for code fragments, and non-traditional browsers (e.g. screen readers for the blind) have to try to display it as code—which may make it very difficult to understand as text. For accessibility, don't do that.
Comment: But consistent or not, I think the emphasis on groups is wrong here. The emphasis of the term is on the ambush.
Answer: Ganking is when a group of player join together to take on a single player. The term probably formed from the words "gang" and "yanking" (the sudden application of large force).
While this strategy can be employed for griefing it is also often applied for "honorable" gameplay.
By combining forces the gang is able to:

Take down more advanced players than they could beat individually
Take down an equally advanced player more quickly (i.e. before reinforcements arrive or the target is able to flee)
Reduce the danger of loosing any individual team member in what would otherwise be a more evenly matched encounter.
Comment: possibly "gang" and "kill"
Comment: I'd say it's more likely to have formed from a combination of gang and [flank](http://en.wiktionary.org/wiki/flank), which is attacking from a side.
Comment: @3ventic I find that highly unlikely since in most games there's very little benefit to a flanking attack.
Answer: There's a lot of bad definitions for gank out there (and in here).
Gank, according to wiktionary is:

To kill, ambush, or defeat with little effort; used in online games.

In other words, to attack in a way in which the defender has no chance and rapidly loses, to pick an unfair fight.
And their examples are great:

Our group totally ganked this guy.

If ganking required a group, then why mention the group?  One person may gank another.

I hate it when corpse-campers gank me over and over again.

If ganking was repeated killing, why mention that?  You may be ganked once or many times.
If ganking was camping a corpse, why mention it?  Ganking may or may not involve corpses.

In WoW, ganking is usually one high level character killing one lower level character.  This usually occurs in 0-3 seconds - any longer and there is the possibility of escape for the victim.  You also see ganking in lower level battlegrounds, where a twinked character can gank a non-twinked character in one or two global cooldowns.

In Eve Online, you have gank squads (they go around killing smaller squads), and you have suicide gankers (they kill you, and then die quickly to the npc system security - but then their alt/buddy comes by and loots you).
Comment: Yes, this is the definition in WoW that I always understood:  "In WoW, ganking is usually one high level character killing one lower level character. This usually occurs in 0-3 seconds - any longer and there is the possibility of escape for the victim".   Like, if your character is level 70, and a level 100 character attacks you, then that's ganking.  No chance of escape, because killing you would only require 1 hit !!!  Considered bad sportsmanship, because you get ZERO honor points (PvP points) for doing it... you're just wasting the other player's time.
Answer: Going back over 10 years, it has always just meant one or more players ambushing and defeating another player.   "You got ganked!"  Kind of like, "you got knocked the ** out!"..  Really no special strategy or classification involved.
Comment: It's nice to explain why you chose to downvote someone's answer
Answer: In EVE: Online, ganking does not necessarily mean the attackers have superior numbers, just that they have an obvious advantage. The most common example is suicide ganking, where one or more players attacks one player, usually a freighter or industrial, in high sec with expectation of being killed by CONCORD shortly afterward. Being in high sec space the victim is unprepared for battle as they are relying on CONCORD to dissuade any would-be attackers.
Answer: Ganking is when a big group of high-level players attack a low-level player who has no chance of defending himself. This is considered a form of griefing.
Answer: When, in my practice(in WoW) ganking is just series of killing the same player(s). I mean, no matter, how much players attack or what is level difference, but if one player(players) was able to kill another player(s) several times in a row (for any reason, ex: level difference, gear difference, lack of gaming skill, mad skillz or attackers just exceed in quantity, as mentioned above), thats exactly what we name ganking. Just that simple.
Answer: Basically is when you got a surprise attack from two or more enemies, usually a large group of enemies, where you have almost no chance in survive. and they don't spend too much resources on you either. Being an "easy kill".
NOTE: A group can be "ganked" by a larger group (e.g 2 versus 5).

The term gank has several meanings, but often implies an
  overwhelmingly large group killing you and/or your group. ("A 60
  Hordie ganked me"" or "Alliance players are ganking lowbies") It
  frequently carries the implication the attack is overwhelming or
  otherwise clearly biased against the individual, either being
  substantial lower in level or having been previously weakened by an
  unrelated threat.
Successful ganks usually consist of very short fights and depend on
  tactics like high burst DPS and the ability to hide;

Source

Verb

gank (third-person singular simple present ganks, present participle ganking, simple past and past participle ganked)
(transitive, Internet, online gaming, slang) To kill, ambush, or
  defeat with little effort; used in online games.

Our group totally ganked this guy.
I hate it when corpse-campers gank me over and over again.

Source

Etymology From German Gang
Comment: The etymology for "gank" that you give is not for the English word, it's for the Serbo-Croation word meaning a hall, passage, corridor, from the German noun "Gang" meaning "walk" (as in "I took a walk").
Comment: I got the data from the same source that above. I'll look and see what I found about it.
Comment: @MichaelAyres Yes, and that source has definitions, etymology, etc. for the Serbo-Croation word following the stuff about the English word. Easy to see how you got confused.

What is "ganking"?


Making GET requests from URLs with flask

Question: Making GET requests from urls can be done with the python requests library like this:
import requests
response = requests.get("https://someapi.io/api/data")
response.json()

I'm currently trying to make GET requests from URLs with the flask request module but i can't find any useful information.
Comment: The `request` thread local proxy object in Flask and the `requests` library are two fundamentally different things and don't serve the same purpose.
Comment: Possible duplicate of [How can I send a GET request from my flask app to another site?](https://stackoverflow.com/questions/15463004/how-can-i-send-a-get-request-from-my-flask-app-to-another-site)
Answer: Flask is a server, the request object you can access on flask.request is the context of the request you received on the related API request.
Please see: https://flask.palletsprojects.com/en/1.1.x/
The requests library is not related and with this one, you can do all the GET requests you want.
You can do a request in one of your API requests handled by your flask server but you would have to use directly the request module and not the request object of the flask module.


How to compare object in foreach loop?

Question: I'm currently doing a checking for item in cart. The item can  be redeemed multiple time but is limited to certain number. Each item has an attribute redeem_count which store the number of time that it can be redeemed. So, below is my coding for checking the total number of each item redeemed.
var previousCoupon = "";
var currentCoupon = "";
int count = 0;
foreach (var p in cart.Promotions)
{
    var query = db.wmp_mst_mcp_promo
               .Where(a => a.wmp_mcp_promo_id == p.PromotionId)
               .Where(a => a.wmp_redeem_count != null && a.wmp_redeem_count > 0)
               .SingleOrDefault();

    if (query != null)
    {
        currentCoupon = query.wmp_mcp_promo_id;

        if (previousCoupon == currentCoupon)
            count++;
        else
            count = 0;

        previousCoupon = currentCoupon;

        if (count > query.wmp_redeem_count)
            result.Invalidate(string.Format("You are not allowed to redeem more than {0} \"{1}\" voucher in 1 order", query.wmp_redeem_count, query.wmp_descriptions));

As you can see, the coding works but only if the same item are redeemed in order. This might not valid because not all customer will redeem the item in order. Bug will occur if they redeem for example item A, then item B, and then item A again. It will work only if item A, item A then item B.
Edited
I want to store any item that have same ID and get only one of it attribute redeem_count so that I can do if statement on it. The redeem_count is different for each item.
Example
Item in cart

item A - 2 (redeem_count=2) Valid
item B - 2 (redeem_count=1) Invalid
item C - 3 (redeem_count=4) Valid

So it will throw the result.Invalidate
Any help? Thanks.
Comment: I would iterate all Promotions, check if the Id is inside a HashSet. If it is increase redeem_count, if it isnt add that Id to HashSet. Would that be what you want?
Comment: @wkl sorry. i mistyped it.
Comment: @Mats391 Hi. Actually I want to compare the ID of each item and if it same with other item, the count for the item will increase. But only the count for that item increase. Example, if item A occur twice, so the count for item A become 2 while if item B is 3, the count for item B become 3 too.
Comment: Still do not quite get when to increase what count, but I do think the better solution is to remember the objects you already looked at and check if your item is already in those. I would have done it similar to wkl answer
Answer: I would do something like (pseudocode):
var dict = new Dictionary<string /*item_Id*/, int /*count*/>;
// count redemptions for each id
foreach(var item in cart)
{
    if(dict.ContainsKey(item.Id))
         dict[item.Id]++;
    else
        dict.Add(item.Id, 1);
}

// check if any of them violate the allowed maximum
foreach( var itemId in dict.Keys)
{
    if(dict[itemId ] > GetMaxRedeemCount(itemId))
    {
        result.Invalidate(...);
        // you may want to break here...
        // break;
    }
}

Comment: Could already compare `count` to redeem count in the first loop after adding. Would get rid of second loop
Comment: @Mats391 Yes, this would remove the second loop but it would perform even more comparisons and calls to `GetMaxRedeemCount`(one per item instead of one per item_id). So I do not see an advantage w.r.t. performance. Concerning readability, personally, I would prefer two loops (and maybe even convert each of them to a separate method).
Answer: Try this solution;
 var previousCoupon = "";
        var currentCoupon = "";
        int count = 0;
        foreach (var p in cart.Promotions)
        {
            var query = db.wmp_mst_mcp_promo
                .Where(a => a.wmp_mcp_promo_id == p.PromotionId)
                .Where(a => a.wmp_redeem_count != null && a.wmp_redeem_count > 0);
if (query != null)
{
       foreach(var queryItems in query)
              {
                currentCoupon = query.wmp_mcp_promo_id;

                if (previousCoupon == currentCoupon)
                    count++;
                else
                    count = 0;

                previousCoupon = currentCoupon;
            }
}
                if (count > query.wmp_redeem_count)
                    result.Invalidate(string.Format("You are not allowed to redeem more than {0} \"{1}\" voucher in 1 order", query.wmp_redeem_count, query.wmp_descriptions));

Comment: i saw ur edit now.  Can u try debug and can u tell me what is results ur linq code, is that giving u any value invalid? because i think this code always give valid jus one result
Comment: Yes, there would be only one result like you stated. I want it to check each of the item if any of it are redeemed more than it's redeem_count. I used foreach loop for that but it only work like I mention on the question above where the same item need to be next to each other.

How to compare object in foreach loop?


MUI v5 Date Pickers: Is there a way to remove the SwitchViewButton?

Question: Is there any way to remove the SwitchViewButton (the one that displays the month and year) from the calendar picker or replace it with my own component?
Their API provides the following prop to modify them in the StaticDatePicker:
components = { LeftArrowButton?: elementType, LeftArrowIcon?: elementType, OpenPickerIcon?: elementType, RightArrowButton?: elementType, RightArrowIcon?: elementType, SwitchViewButton?: elementType, SwitchViewIcon?: elementType }
But when I try sending 'null' to any of them, it completely ignores them and renders the same thing.
Date Picker view
Answer: Instead of passing null to them, I was able to get them to not display by passing an sx value to each one's props.
So instead of:
<DatePicker
     components={{SwitchViewButton: null}}
/>

You can do:
<DatePicker
     componentProps={{
          switchViewButton: { sx: { display: 'none' } }
     }}
/>

It's not perfect, but it gets the job done, at least in my limited experience. I think this is because when you pass null to the component prop, it just uses the default.
Note: The components prop uses Pascal case (ActionBar), while componentsProps uses camel case (actionBar) per the documentation
Answer: <DatePicker disableOpenPicker />

Add this attribute to your DatePicker component and just control the opening with open={}.


Tossing biased coins sample space

Question: There are 9 fair coins and one biased which always comes up tails. The experiment is picking one coin and tossing it 4 times, what is the sample space then?
$10*2^4$ seems not considering that biased coin. Shouldn't the sample space be $9*2^4 + 1$?
Thanks in advance.
Answer: Actually, both can be correct,although $9 \times 2^4 +1$ makes more sense.
One thing that you should realize (and no, this is not told usually in class, so it is important) is that there is no problem if you include "extra" outcomes in your sample space which cannot occur. You can simply adjust these to have probability zero, so that in any calculations the "extra" outcomes will not be considered because they will have probability zero.
For example, if you do include the outcome that you took the biased coin and got $4$ heads, say, then this could occur in the sample space : but it would have probability zero. This way, you could have $10 \times 2^4$ outcomes, but some of them would be extra, so will be given probability zero.
On the other hand, you could choose not to include these at all. This would lead to $9 \times 2^4$ outcomes for each of the fair coins, and $1$ for the biased coin, giving your second answer. This is more trimmed, but I would accept the first as an answer if the probabilistic explanation accompanied it.
Comment: Thanks, great explanation!
Comment: You are welcome!

Tossing biased coins sample space


Identifying cars in drone images

Question: I am trying to identify cars in drone images (like from a quad copter), so I started using opencv's haar classifier. However, it produces a lot of false positives and does not always detect cars correctly. I was thinking a CNN would be better for this job, however I've never done a project like this and I am not sure how to proceed.
Code:
<code>import cv2
import numpy as np
import sys

img = cv2.imread(sys.argv[1], 1)
print(img)

car_cascade = cv2.CascadeClassifier('cars.xml')

cars = car_cascade.detectMultiScale(img, 1.1, 1)
print(len(cars))

for (x,y,w,h) in cars:
    cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)

cv2.imshow('img1', img)
cv2.waitKey(5000)
cv2.destroyAllWindows()
</code>
Answer: If you are OK with using something other than opencv, then this solution is viable.
Thankfully Google has come to the rescue and has made a pretty simple and open source solution.
The tensorflow object detection api, makes it really easy to start with object detection. You can use models that google has provided - detection model zoo, or you can even train your own.
To get started just follow the installation guide and you should be good to go, to run the demo!
Then follow the object detection demo guide - which should get you detecting many different types of objects - from cars, to people, to dogs and even kites!
Comment: This can be helpful, also the original course by profile Andrew Ng. On Coursera: https://www.google.co.in/amp/s/sandipanweb.wordpress.com/2018/03/11/autonomous-driving-car-detection-with-yolo-in-python/amp/
Comment: I will check this out, I can definitely use something other than opencv. Thank you!
Comment: If you want to stick with opencv - they recently released a new version, which now includes the `dnn` module.  The sample code for it is here: https://github.com/opencv/opencv/blob/3.4/samples/dnn/object_detection.py . Video demo: https://docs.opencv.org/3.4/da/d9d/tutorial_dnn_yolo.html
Comment: Opencv, I would think, is more lightweight than tensorflow - so if running on slower hardware maybe use opencv. If accuracy is top priority then I would stick with tensorflow.

Identifying cars in drone images