Keyboard shortcut to launch dmenu

Question: I've got a snippets file in my home directory with two simple commands
ls
whoami

Running the following terminal command utilizes dmenu to allow me to select a line in my snippets file and pipe the output to whatever application I have in focus (usually my terminal):
xdotool type $(grep -v '^#' ~/snippets | dmenu -i -l 50 | cut -d' ' -f1)

I want to bind Super+Ins to run that command above, and have attempted via Settings > Keyboard Shortcuts > + and entering the following for the command to issue:
gnome-terminal -e "xdotool type $(grep -v '^#' ~/snippets | dmenu -i -l 50 | cut -d' ' -f1)"

When I go ahead and use this new keyboard shortcut Super+Ins I get the following output
(grep-v^#~/snippets|dmenu-i-l50|cut-d -f1)

instead of the expected dmenu selection. What am I doing wrong? My OS is Ubuntu 22.04 under GNOME running X11.
Answer: Command substitution will not work from the shortcut definition. It must be run in bash for it to work. Instead, move your xdotool command in a small script and have the shortcut definition point to that script instead.
Comment: I see. It is the command substitution that does not work from within a shortcut key - command substitution works in scripts and on the bash shell. Thus, xdotool just literally types the string you provided. Changed the answer.
Comment: I tried your suggestion, added `sleep 0.3` to the command, and used the command directly as a shortcut key, but the output from `Super+Ins` is still `grep-v^#~/snippets|dmenu-i-l50|cut-d -f1)` instead of the expected dmenu snippet list. Were you able to get my concept working, or was this just your initial thoughts on how to fix the issue?

Keyboard shortcut to launch dmenu


Using the Dot Operator vs Bracketed Messages in Objective-C

Question: From 'Programming in Objective-C', 6th Edition, Stephen G. Kochan:

Although it's syntactically correct to write a statement such as myFraction.print, it's not considered good programming style. The dot operator was really intended to be used with properties; typically to set/get the value of an instance variable. Methods that do other work are typically not executed using the dot operator; the traditional bracketed message expression is the preferred syntax.

Are there performance drawbacks to backup this position, or is this merely social convention?
Answer: I don't think it's social convention that drives this. I think it's the improved readability that you get from it.
There isn't a performance hit but you will find it easier working with other devs if you follow the standard.
The Times Online style guide is one I work to and is fairly standard with Apple's own coding style.
Answer: It's just a social convention. Properties are just a syntax sugar. So when you use dot-notation, it is automatically translated into a call to a getter/setter.
But I'm totally agree with Mr. Stephen G. Kochan. Using dot-syntax for calling methods is misleading.
Answer: Messaging methods that are not properties with the dot syntax is allowed because at the time properties and dot operator were introduced there were hundreds of millions of lines of code just using get/set accessors methods, and that meant you could use the dot operator to signal that you were using property-like accessors even though they were not declared as properties. Theoretically, this could be removed by now.
Using the dot operator for something else than getting or setting properties is bizarre and will make your code incredibly confusing for yourself and for others, but there's no performance tax at runtime for doing so. On the flip side, there's also no reason to not declare your properties as properties any longer - particularly since it results in less code in Objective-C and enables them to show up as properties instead of as methods in Swift.


External Sort - merging issue for particular case

Question: I have understand what external sort does, what it for; yet I have an issue at my mind about merging extreme case.
external sorting  the first answer explains how external sort merging works. But what if:

assume that we have 10 units memory size and we want to sort 50 units file
first we slice the file into 5 runs( each of them 10 units ) and sort them individually
second we have to merge them with 4-way merge
and 10/4 = 2.5 ~ 2; we take 2 units(chunk) from each run, put them into memory and we start merging;
Then the actual question is: what if the second and the third chunk of the (assume) third run have
smaller elements than the first chunks of the other runs ? Will the merging process be successful ?

If I have mistakes about what I understand, any explanation will be helpful.
Answer: Well, there's no problem having smaller/greater elements in any of the files. Here is an example of the external sort process:
Your initial data:
data = [2, 5, 3, 7, 1, 6, 4, 8, 9]

Considering you have only 3 units of memory, you'd have the following shards, and results of sorting:
d1 = [2, 5, 3] -> sorting -> d1 = [2, 3, 5]
d2 = [7, 1, 6] -> sorting -> d2 = [1, 6, 7]
d3 = [4, 8, 9] -> sorting -> d3 = [4, 8, 9]

As you have three available units, you can read from the three shards at the same time, so, you'd have:
d = [], d1 = [2, 3, 5], d2 = [1, 6, 7], d3 = [4, 8, 9] -> min(d1, d2, d3) = 1
d = [1], d1 = [2, 3, 5], d2 = [6, 7], d3 = [4, 8, 9] -> min(d1, d2, d3) = 2
d = [1, 2], d1 = [3, 5], d2 = [6, 7], d3 = [4, 8, 9] -> min(d1, d2, d3) = 3
d = [1, 2, 3], d1 = [5], d2 = [6, 7], d3 = [4, 8, 9] -> min(d1, d2, d3) = 4
d = [1, 2, 3, 4], d1 = [5], d2 = [6, 7], d3 = [8, 9] -> min(d1, d2, d3) = 5
d = [1, 2, 3, 4, 5], d1 = [], d2 = [6, 7], d3 = [8, 9] -> min(d1, d2, d3) = 6
d = [1, 2, 3, 4, 5, 6], d1 = [], d2 = [7], d3 = [8, 9] -> min(d1, d2, d3) = 7
d = [1, 2, 3, 4, 5, 6, 7], d1 = [], d2 = [], d3 = [8, 9] -> min(d1, d2, d3) = 8
d = [1, 2, 3, 4, 5, 6, 7, 8], d1 = [], d2 = [], d3 = [9] -> min(d1, d2, d3) = 9
d = [1, 2, 3, 4, 5, 6, 7, 8, 9], d1 = [], d2 = [], d3 = [] -> []

What you may be concerned about is when you have limitation enough to allow you not to read at least one element from each file, or even if the decision was simply to read more elements from a given file, leaving behind another file to be read.
This is the same as the process above, with the only difference that, after reading, say, two files, and merging the data between them, you'd have to read from the third file and from the last file generated, which is the merge of files 1 and 2.
Since both the third file and the last file generated are surely sorted, you are able to sequentially scan the data from both files, merging the entries into an unique result.
Comment: Thanks for the detailed answer, now I understand well what happens in the memory.


How to group List array in LINQ

Question: I have an List<Array>, I'm using LINQ to find duplicates and count, but it's not work.
See the image you can see, lstMyList[0] and lstMyList[11] have the same value in Int[]
Here is lstMyList definition:
List<Array> lstMyList = new List<Array>();

I used code, but it's not work:
var group = lstMyList.GroupBy(t => t).ToArray();

or
Dictionary<int[], int> count = lstMyList.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());

Here is image: http://imageshack.com/a/img69/2552/h114.png
Maybe somebody can give me a hint about my problem.
Comment: What is the `lstMyList` class definition?
Comment: Having a key that is an `int[]` is probably not going to work for you. We need the class definition.
Comment: declare lstMyList
List lstMyList = new List();
or
List lstMyList = new List();
Comment: If you have two int arrays - both `int[] { 1, 2 }` - they are not equal to each other using standard equality as arrays are reference types and they only compare if the array is the same reference. Two arrays, even with the same values, are different.
Comment: See about [Enumerable.GroupBy Method with IEqualityComparer](http://msdn.microsoft.com/ru-ru/library/bb534334(v=vs.110).aspx)
Answer: First create comparer class:
sealed class ArrayEqualityComparer : IEqualityComparer<int[]>
{
    public bool Equals(int[] x, int[] y)
    {
        if (x == null && y == null)
            return true;
        if (x != null && y != null)
            return x.SequenceEqual(y);
        return false;
    }

    public int GetHashCode(int[] obj)
    {
        return obj.Length;
    }
}

Then you can use it in GroupBy clause.
List<int[]> lstMyList = new List<int[]> { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 1, 2 } };
var groups = lstMyList.GroupBy(t => t, new ArrayEqualityComparer())
                      .Select(g => new { g.Key, Count = g.Count() })
                      .ToArray();

Comment: It should be noted that this solution does have some potential drawbacks. The `g.Key` will be a reference to one of the "equal" arrays so careful if you modify the contents. Also the comparer will not equate `{1,2}` & `{2,1}` so, depending what the domain logic is, this could be an issue too.
Answer: Try this
var group = lstMyList.GroupBy(t => t,
              StructuralComparisons.StructuralEqualityComparer).ToArray();

Comment: I try but receive error: has some invalid arguments
Comment: Apologies. You might want to take a look at this for the fix http://stackoverflow.com/a/5601068/1808494

How to group List array in LINQ


Zombie heroku process after deleting project?

Question: Has anyone experienced deleted heroku projects that still runs on some undiscoverable process?
I've been hosting a discord bot on heroku on a single free worker dyno, here's a timeline of what happend:

On 4/25 migrated to a github deployment repo.
At some point starting 4/29 between 10:45 to 11:30pm, I started
receiving duplicate bot messages.
On 4/30 I attempted to deploy an update thinking there was a bug in my code, but after observed the following symptoms when I dug deeper:
a. messages I attempted to stop sending are still being sent, but only once
b. messages both the old and new version of the code sends are still being duplicated
c. Heroku logs continue to show code execution even when I disable the only worker dyno
From here I suspected the project have a zombie process, so I attempted to deleted the project and added a new copy of the project, but the same behavior continues.

I have no reason to suspect it was caused by code running else where: I only ever deployed the code on heroku. The discord tokens are being kept in heroku configs and copies of the code could not really be sending messages without.
What could be happening and what should I do next?
Comment: https://status.heroku.com/incidents/2236
Comment: Ah I checked for incidents over the weekend while debugging and didn't see any. That also explains why everything went back to normal at noon. Thanks
Answer: Try changing your token and re-inputting it into heroku.
Comment: Note: answers that are very brief and/or are questions back to the poster should probably be comments. You only need 50 rep points to comment under a question.


Need to add similar customer into array after performing groupBy but with a limit per customer and now with array size restriction

Question: I had asked a similar question a few days back and got the correct answers, but again we faced new issues. So here is the new problem statement. I am fetching customer contacts from salesforce which are coming as an array of objects as shown below.
Input Payload:
<code>    [
        {
            "customerID": 1,
            "contactName": "Jonhn1"
        },
        {
            "customerID": 1,
            "contactName": "Jonhn2"
        },
        {
            "customerID": 1,
            "contactName": "Jonhn3"
        },
        {
            "customerID": 1,
            "contactName": "Jonhn4"
        },
        {
            "customerID": 1,
            "contactName": "Jonhn5"
        },
        {
            "customerID": 2,
            "contactName": "Jonhn6"
        },
        {
            "customerID": 2,
            "contactName": "Jonhn7"
        },
        {
            "customerID": 2,
            "contactName": "Jonhn8"
        },
        {
            "customerID": 2,
            "contactName": "Jonhn8"
        },
        {
            "customerID": 3,
            "contactName": "Jonhn9"
        },
        {
            "customerID": 3,
            "contactName": "Jonhn10"
        },
        {
            "customerID": 4,
            "contactName": "Jonhn12"
        },
        {
            "customerID": 4,
            "contactName": "Jonhn13"
        },
        {
            "customerID": 5,
            "contactName": "Jonhn14"
        },
        {
            "customerID": 5,
            "contactName": "Jonhn15"
        },
        {
            "customerID": 5,
            "contactName": "Jonhn16"
        },
        {
            "customerID": 6,
            "contactName": "Jonhn17"
        },
        {
            "customerID": 7,
            "contactName": "Jonhn17"
        }
    ]
</code>
I needed the output to be an array of arrays, each sub-array should have all the customer details of at most three different customers and We had to put a limit on the number of customers in an array. I got the solution till the above statement as shown below
<code>%dw 2.0
output application/json
import * from dw::core::Arrays
var a = payload groupBy $.customerID pluck $
---
flatten(a map
    (if (sizeOf($)>4)
            $ divideBy sizeOf($) map(flatten($))
            else
    (a filter (sizeOf ($)<= 4) divideBy 3 map (flatten ($)))
    ) distinctBy $)
</code>
NEW PROBLEM:
<code>flatten(a map
        (if (sizeOf($)>4)
                $ divideBy sizeOf($) map(flatten($))
                else
</code>
above part of the solution is just fine.
<code> (a filter (sizeOf ($)<= 4) divideBy 3 map (flatten ($)))
    ) distinctBy $)
</code>
I want some logic in this part. We want each array to have a max of 4 records.
In the given example, there will be a separate array for customer 1, and for remaining, customers create arrays having a maximum of 4 entries, if after adding two customer array sizes is exceeding more than 4, put them in different arrays. If after adding 3 customers in an array size is less than 4, keep them in the same array.
Background
As we have to send each array to the SAP Function module which takes 10 minutes to update 1000 records and our dedicated load balance gives gateway timeout after 10 minutes.
So we have to send max records and also want to avoid timeout issues ( we have to use dlb we cant call workers directly ).
expected output :
<code>[
    [
        {
            "customerID": 1,
            "customerName": "Jonhn1"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn2"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn3"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn4"
        },
        {
            "customerID": 1,
            "customerName": "Jonhn5"
        }
    ],
    [
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn7"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn8"
        },
        {
            "customerID": 2,
            "customerName": "Jonhn6"
        }
    ],
    [
        {
            "customerID": 3,
            "customerName": "Jonhn9"
        },
        {
            "customerID": 3,
            "customerName": "Jonhn10"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn12"
        },
        {
            "customerID": 4,
            "customerName": "Jonhn13"
        }
    ],
    [
        {
            "customerID": 5,
            "customerName": "Jonhn14"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn15"
        },
        {
            "customerID": 5,
            "customerName": "Jonhn16"
        },
        {
            "customerID": 6,
            "customerName": "Jonhn17"
        }
    ],
    [
        {
            "customerID": 7,
            "customerName": "Jonhn17"
        }
    ]
]
</code>
Comment: Dheeraj, you just need a sizing on each array now where we have  3 different customers in an array?
Comment: Right @AnuragSharma, each array should have constraints on max entries.
Comment: dheeraj did you get answer for this?
Comment: Not yet @AnuragSharma
Comment: i thought someone replieed here, but can you try reduce function?
Comment: this is lilttle sconfusing becasue you said,you want each array to have a max of 4 records. but you are saying this too that If after adding 3 customers in an array size is less than six, keep them in the array.
Comment: dheeraj,could you please clarify this?
Comment: Hi @AnuragSharma sorry for the late reply, if we talk about second logic, I can have a max of 4 records in an array. Sorry that 6 was a typo, "If after adding 3 customers in an array size is less than 4, keep them in the same array"
Comment: did correction in the question
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/242007/discussion-between-anurag-sharma-and-dheeraj-kain).
Answer: Please try the below code that gives the expected output.
<code>%dw 2.0
output application/json
import * from dw::core::Arrays
var a = payload groupBy $.customerID pluck $
---
flatten(a map
    (if (sizeOf($)>4)
            $ divideBy sizeOf($) map(flatten($))
            else
    (a filter (sizeOf ($)< 5) reduce ($$++$) divideBy 4)
    ) distinctBy $)

</code>
As I said in my comments, try to use reduce.


iPod was stolen. Can I retrieve my Minecraft PE world?

Question: So my iPod was stolen while it had my favorite Minecraft pocket edition world. Can I get it back? It was not backed up. Any way I can retrieve it?
Answer: If it wasn't backed up to iCloud then the only way is getting your iPod back.


Repeated random sampling and kurtosis on unbalanced sample

Question: I have an unbalanced dataset with people from liberal and conservative background giving rating on an issue (1-7). Would like to see how polarized the issue is.
The sample is heavily skewed towards liberal (70% of the sample). How do I do repeated sampling using R to create a balanced sample (50-50) and calculate kurtosis?
For example, I have total 50 conservatives. How do I randomly sample 50 liberals out of 150 repeatedly?
A sample dataframe below:
<code>  political_ort   rating
    liberal         1
    liberal         6
    conservative    5
    conservative    3
    liberal         7
    liberal         3
    liberal         1
</code>
Comment: Thanks! Not really. I'm looking to sample the same number of liberals as conservatives. So if there are 10 conservatives, would like to sample 10 from 70 liberals repeatly.
Comment: Does this answer your question? [Sampling from a data.frame while controlling for a proportion \[stratified sampling\]](https://stackoverflow.com/questions/29360799/sampling-from-a-data-frame-while-controlling-for-a-proportion-stratified-sampli)
Answer: What you're describing is termed 'undersampling'. Here is one method using tidyverse functions:
<code># Load library
library(tidyverse)

# Create some 'test' (fake) data
sample_df <- data_frame(id_number = (1:100),
                        political_ort = c(rep("liberal", 70),
                                          rep("conservative", 30)),
                        ratings = sample(1:7, size = 100, replace = TRUE))

# Take the fake data
undersampled_df <- sample_df %>%
# Group the data by category (liberal / conservative) to treat them separately
  group_by(political_ort) %>%
# And randomly sample 30 rows from each category (liberal / conservative)
  sample_n(size = 30, replace = FALSE) %>%
# Because there are only 30 conservatives in total they are all included
# Finally, ungroup the data so it goes back to a 'vanilla' dataframe/tibble
  ungroup()
# You can see the id_numbers aren't in order anymore indicating the sampling was random
</code>
There is also the ROSE package that has a function ("ovun.sample") that can do this for you: https://www.rdocumentation.org/packages/ROSE/versions/0.0-3/topics/ovun.sample


What is the damage increase of Symmetra's Photon Projector?

Question: I was wondering if anyone knew what the damage increase of her primary weapon (photon projector's energy beam) was, per second.
Comment: I know that the damage output hasn't changed, I just wanted to know the damage changes per second, which you just answered. Thanks
Comment: I dont thing there's Damage boost, only max-range boost of 2m
Comment: The longer that the energy beam is locked on a target, the higher the damage output gets. My question is the numbers for that damage output (over-time)
Comment: As I said, I'm pretty sure those haven't changed from 7.5/15/30 per hit (4 hits per second) takes a second to move to higher damage tier.
Answer: The Symetra Photon projector does
7.5/15/30 dmg per hit. She does 4 his per second and it takes a second to move up a tire.
Meaning she'll do 120 dps after 3 seconds of continuous shooting at someone.
It's worth nothing that this damage output will not be changed in the reworked Symetra. The only change regarding her weapon is the range. It's being boosted to 7m from 5m.
Comment: The damage only ramps up while dealing damage, and decays at the same rate after 1 second of not dealing any damage.


Signing PDF document with qualified certificate - smartcard

Question:
I have a problem with my applet for signing PDF documents using smartcard. It works fine for not qualified certificates but won't for qualified. I'm using SunPKCS11 provider. It's CryptoTech card. Here's part of code, where i'm trying to operate on this provider:
String pkcs11config = "name = " + PROVIDER + "\nlibrary = \"" + value + "\"";
byte[] pkcs11configBytes = pkcs11config.getBytes();
final ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11configBytes);
pkcs11Provider = new sun.security.pkcs11.SunPKCS11(configStream);
Security.addProvider(pkcs11Provider);

And here is code, when the problem occured:
final KeyStore keyStore = KeyStore.getInstance(TYPE, pkcs11Provider);
        keyStore.load(null, PIN);

And the constants:
public static final String PROVIDER = "CryptoTech";
private static final String TYPE = "PKCS11";

Here's exception stacktrace:
java.io.IOException: load failed
    at sun.security.pkcs11.P11KeyStore.engineLoad(P11KeyStore.java:763)
    at java.security.KeyStore.load(Unknown Source)
    at pl.emsi.sign.card.CardManager.getKey(CardManager.java:165)
    at pl.emsi.sign.logic.DocumentLogic$1.success(DocumentLogic.java:79)
    at pl.emsi.sign.card.CardManager$1.driverSelected(CardManager.java:92)
    at pl.emsi.sign.card.CardManager$2.driverSelected(CardManager.java:121)
    at pl.emsi.sign.card.CardManager$7.actionPerformed(CardManager.java:414)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.WaitDispatchSupport$2.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: javax.security.auth.login.LoginException
    at sun.security.pkcs11.SunPKCS11.login(SunPKCS11.java:1238)
    at sun.security.pkcs11.P11KeyStore.login(P11KeyStore.java:849)
    at sun.security.pkcs11.P11KeyStore.engineLoad(P11KeyStore.java:753)
    ... 54 more
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_PIN_LOCKED
    at sun.security.pkcs11.wrapper.PKCS11.C_Login(Native Method)
    at sun.security.pkcs11.SunPKCS11.login(SunPKCS11.java:1222)
    ... 56 more

I've already checked that the PIN isn't locked, because other application (no need to mention the name of this application) signs the PDF document without any problems. The PIN is 100% correct, also.
If there's some information missing, please, let me know.
EDIT1:
By: "It works fine for not qualified certificates but won't for qualified" i meant that the not qualified certificates was placed on different smartcards than this qualified certificate.
Comment: Smartcards sometimes require different pins for different usages. If a smart card e.g. has key material for both qualified and and merely advanced signatures (the first for signing contracts, the second for authenticating at an electronic door lock), the respective PINs usually can be chosen independently.
Comment: It might help to use some pkcs11 logger (e.g. [this one](https://github.com/jariq/pkcs11-logger)) to inspect what is going on (you can compare what different programs vs. different cards do and spot the difference). Good luck!
Comment: @vlp Isn't that logger "pay-to-use" for non open source applications?
Comment: @HubertPopiołkiewicz (To be honest) I don't know. I use a similar logger I have from SafeNet and not this one -- but this one is the only publicly available I am aware of...
Comment: @vlp I have changed the license of pkcs11-logger to a more permissive Apache 2.0 license so it is now completely free even for commercial use.
Answer: SOLVED
Okay, I found a solution for my problem.
It turned out that the provider was trying to use card's slot with id 0 by default. Card, at which there was problem, have non qualified certificates on three first slots. Tokens on these slots isn't initialized. The qualified cert I was trying to use is placed on fourth slot.
I used IAIK PKCS11 Wrapper to get info about Tokens of this card. Here's code sample:
        try {
            Module module = Module.getInstance(value);
            module.initialize(null);
            Slot[] slots = module.getSlotList(true);
            TokenInfo[] infos = new TokenInfo[slots.length];
            for (int i = 0; i < slots.length; i++) {
                infos[i] = slots[i].getToken().getTokenInfo();
            }
            printTokenInfos(infos);
            if (slots.length == 0) {
                System.err.println("No token available!");
                return;
            }
        } catch (TokenException | IOException e1) {
            e1.printStackTrace();
        }

        [...]

    private void printTokenInfos(TokenInfo[] infos) {
        int counter = 0;
        for (TokenInfo info : infos) {
            System.out.println("Token: " + counter++);
            System.out.println(info);
        }
    }

    //"value" passed to Module's getInstance method is th path for .dll module
    //used for one's type of card.

From this place I can determine which slot I should use. It can be accomplished by adding slotListIndex parameter to Provider's configuration input stream. E.g.
    String pkcs11config = "name = " + PROVIDER + "\nlibrary = \"" + value + "\"\nslotListIndex = " + slotIndex;

Helpful sites for this issue:
IAIK JCA/JCE
https://javaczysen.blogspot.com/ - unfortunately, only in polish.
Answer: Pass null in place of PIN parameter in keyStore.load method(keyStore.load(null, null)) will result in password prompt from respective token driver. You can validate the PIN this way...
Comment: Already checked this method by providing PasswordCallback - still the same problem.


What is the best way to handle close buttons in dialogs in a mobile app?

Question: I have a small dialog where a user can add an email to subscribe.
I am torn between changing the subscribe button to take 50% of the place and adding cancel or simply make the x bigger.

Any other suggestions?
Answer: I would recommend going with the cancel option since most users might not be used to the concept of using the close icon (the X) to close a dialog in a mobile app (you have them in websites) but then with a mobile app the common affordance to what I have found is to to have a distinct cancel option as shown below:
Answer: For the most part I would go with a dedicated 'Cancel' labelled button rather than an 'x' on mobile.
The target area is generally to small for the user to have a fluid interaction. If you make the 'x' a bigger target area it can be used. A good size might be the one used for delete options(red -). It seems to work quite well for apple so far.

Not exactly related to your scenario, but a general trend in iOS search/input fields. Put a small cancel button near the input field.


Is the back button in Windows 8 apps purely chronological?

Question: The back button is ubiquitous in Windows 8 ("Metro") apps.

What exactly is its meaning? The Microsoft apps I have seen and the Visual Studio page templates use the button in a chronological manner (back to the page you came from).
But I am currently developing some apps where chronological navigation sometimes does not really make sense (*) and I'm tempted to use the back button for hierarchical navigation instead (back to the page that is above the current one).
Is this a good idea? Does it break user expectations? Does it break the Microsoft UX guidelines or maybe even cause problems during certification?
(*) Think of a game, for example: You go from the start page to a level overview page to a page where you play the selected level. When the level is finished, navigation automatically jumps to the level overview. Now, it would be strange if the back button brought you back to play the level (again?) instead of the start page, or not?
Answer: 2 different usage patterns mentioned in the Win 8 UX navigation pattern guidelines:
Initial pattern says Back button should take you back to previously visited page and not hierarchy.

Header and Back button:
The header labels the current page and is useful for wayfinding. The Back button makes it fast to get back to where you were.

Further down there is another example which mentions:

The header menu contains a link to each section page (level 2) as well as a link back to the hub (level 1), enabling users to move around the app quickly.

Based on this, I would answer your question with:
Do some user testing and find out which way feels more intuitive to your app and use that.
Comment: Could you please add a link to the corresponding guidelines?
Comment: @SebastianNegraszus my bad, forgot to include it :)


How to connect AWS Elasticache Redis cluster to Spring Boot app?

Question: I have Spring Boot app which connects to Redis cluster, using Jedis Connection Factory:
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
redisClusterConfiguration.setPassword(redisProperties.getPassword());
jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration);

and reading list of nodes from application.yml:
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    timeout: 300s
    cluster:
      nodes: 127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382

Now we want to switch to Elasticache since we are hosting our Redis cluster on AWS anyway.
It would be done quite easily. If AmazonElastiCache lib could be used.
Then we could just connect to Elasticache cluster with AWS credentials, pull available nodes put it in the list and pass it to Jedis instead hardcoding them in application.yml, like:
//get cache cluster nodes using AWS api
private List<String> getClusterNodes(){
    AmazonElastiCache client = AmazonElastiCacheClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();
    DescribeCacheClustersRequest describeCacheClustersRequest = new DescribeCacheClustersRequest();
    describeCacheClustersRequest.setShowCacheNodeInfo(true);
    List<CacheCluster> cacheClusterList = client.describeCacheClusters(describeCacheClustersRequest).getCacheClusters();
    List<String> nodeList = new ArrayList<>();
    try {
        for (CacheCluster cacheCluster : cacheClusterList) {
            for(CacheNode cacheNode :cacheCluster.getCacheNodes()) {
                String nodeAddr = cacheNode.getEndpoint().getAddress() + ":" +cacheNode.getEndpoint().getPort();
                nodeList.add(nodeAddr);
            }
        }
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    return nodeList;
}

But DevOps team said that they can't configure AWS access on all labs and they have reasons for it. Also instead of connecting to AWS and pulling all available clusters we need to connect to specific one by URL.
So I tried to pass Elasticache cluster url directly to Jedis as standalone and as a cluster in application.yml configuration.
In both cases connection is established, but when App tries to write to Elasticache its gets MOVED exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.data.redis.ClusterRedirectException: Redirect: slot 1209 to 10.10.10.011:6379.; nested exception is redis.clients.jedis.exceptions.JedisMovedDataException: MOVED 1209 10.10.10.102:6379

Which as I understand means that App tried to write to one of the nodes in Elasticache, but wasn't able to connect.
So the question would be is there a way to connect to Elasticache Redis cluster from Spring Boot app using only Elasticache cluster URL?
I know that it's doable if Elasticache Memecache is used.
Also Jedis driver is not a hard requirement.
Thank you.
Answer: After some research we learned that if AWS Elasticache cluster end-point is set as a node in RedisClusterConfiguration then driver (Jedis or Lettuce) is able to connect and find all the nodes in a Elasticache cluster. Also if one of the nodes goes down driver is able to communicate with Elasticache cluster through some other node.
We migrated to Lettuce driver while working on this upgrade as well, since Lettuce is default driver provided in Spring Boot Redis Started and supports latest Redis versions. Lettuce connections are designed to be thread-safe too, Jedis not.
Code example:
List<String> nodes = Collections.singletonList("****.***.****.****.cache.amazonaws.com:6379");
RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(nodes);
return new LettuceConnectionFactory(clusterConfiguration);

Comment: is " "****.***.****.****.cache.amazonaws.com:" a Elastic cluster host name?
Answer: Inspired from Above Answer:, complete more detailed code
 List<String> nodes = Collections.singletonList("<cluster-host-name>:<port>");
 RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(nodes);

 ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder().closeStaleConnections(true)
 .enableAllAdaptiveRefreshTriggers().build();

 ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder().autoReconnect(true)
 .topologyRefreshOptions(topologyRefreshOptions).validateClusterNodeMembership(false)
 .build();
 //If you want to add tuning options
 LettuceClientConfiguration  lettuceClientConfiguration = LettuceClientConfiguration.builder().readFrom(ReadFrom.REPLICA_PREFERRED).clientOptions(clusterClientOptions).build();

 LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(clusterConfiguration, lettuceClientConfiguration);
 lettuceConnectionFactory.afterPropertiesSet();//**this is REQUIRED**
 StringRedisTemplate redisTemplate = new StringRedisTemplate(lettuceConnectionFactory);

Comment: `afterPropertiesSet` is required, because you seems to be not using `LettuceConncectionFactory` as a `@Bean`


PowerBI Count all Rows With Value In Group

Question: This seems like one of the use cases for groups, but maybe I'm understanding them wrong.
I have a table that shows a count of all rows like this:
User | Completed Tasks
Bob  | 2
Jim  | 1
Pete | 1

The table it comes from looks like this:
User | Type
Bob  | A
Bob  | B
Jim  | A
Pete | C

This is very simplified - in reality there are about 80 different types - I'm hoping to get 5 of them in a group called Secondary and the rest in a group called Primary
For the example, say I want A and B to be considered "primary" and C to be secondary.
The new table would look like this:
User | Completed Tasks | Primary | Secondary
Bob  |        2        |    2    |     0
Jim  |        1        |    1    |     0
Pete |        1        |    0    |     1

I tried creating a group of Type with 5 called Secondary and the rest called Primary, but I was having trouble figuring it out.
I just want a Count of types for that particular group based on the filtered values and everything.
Is there an easy way to do this or do I need to create a measure/calculated column?
Answer: Another way to approach this is to create a calculated column for Group
Group = IF(table[Type] IN {"A","B"}, "Primary", "Secondary")

You can then use the Group as the columns on a matrix and count the Type column.

Note that this approach scales better if you want to break into a lot more groups. You'd likely want to use a SWITCH in that case like this:
Group =
    SWITCH(TRUE(),
        Table1[Type] IN {"A","B"}, "Primary",
        Table1[Type] IN {"C"}, "Secondary",
        Table1[Type] IN {"D", "E", "F"}, "Tertiary",
        "Other"
    )

Comment: This looks awesome - maybe more what I was looking for. Thanks for your reply
Answer: I ended up solving this by creating two calculated columns.
The Dax for the primary would be a 1 for each row not in the Secondary list:
PrimaryCount = IF(table[Type] in {"C","D","E","F","G"},0,1)

The Dax for the secondary would be a 1 for each row IN the Secondary list:
SecondaryCount = IF(table[Type] in {"C","D","E","F","G"},1,0)

Then, just add those to your table values and make sure Sum is selected (the default).
I figured using groups would be easier, but I suppose this is simple enough and seems to work.


I'm out of filters and keep choking to death

Question: I'm at the part of the game where you're on the surface fighting Nazis, specifically in the big area with all the old cars and the spotlight.
I ran out of air filters in the previous area and now I just choke to death and respawn at the checkpoint, is there a hidden air filter somewhere or should I just keep going?
Also, advice for preventing this in the future would be much appreciated!
Answer: Im fairly certain the game is designed to not allow this to happen. If it keep happening and you reset at the checkpoint enough it just adds minutes onto your filter time to enable you to get through the section.
If this doesnt work then a  workaround it you can take the mask off and put it back on which gives you around 8 seconds of air each time. Simply repeat this until you find more air filters.


What times are "high risk" for the jungler to visit your lane?

Question: There are certain times in the early game when you should be on "high alert" for a jungler to come into your Lane. For example early level 2 ganks, after they completed their first jungler route, etc.
Is it possible to say "at 3 minutes top lane should be extra careful as that's when the jungler reaches there" or is there just too much variation in jungler clear times and routes for that to be useful?
Comment: highly depends on the jungler you are playing against and the elo
Comment: when there is no vision of the enemy jungler or some kind of information on their whereabouts.
Answer: You pretty much got the biggest one but...
In general, you want to watch your minimap.  If you haven't seen the enemy jungler in awhile, assume he's about to gank you.  If you are toplane and you see the jungler bottom, take another look at the map in about a minute.  You aren't likely to get ganked before then.  If the enemy jungler ganks mid from topside, and leaves assume that he will be up to you in the next 15-20 seconds until you see another appearance.
Using those general rule of thumbs, play aggressive when you know you have a good window without the enemy jungler.  If you don't know where they are or they were mid on your side assume that they are going to be ganking you soon.  On my 2nd or 3rd back I'll generally grab an extra ward beyond my trinket.  I'll usually wait to ward until I see the enemy jungler since he could be in those bushes waiting for me to facecheck as I ward.  Once I see him, if he's far bottom, I'll wait 30 seconds to ward (this is assuming I'm top).  If he's mid, I'll ward immediately and like I said, if I don't have vision I'll place a ward if I know I'm pretty safe (my laner is pretty far away) otherwise I'll play passive until I'm given an opportunity.
An extra tip, is that people will often place a pink in one of the solo river bushes near mid or behind their red buff to get some easy vision.  (You are more likely to lose the pink in the river, but it's a lot more valuable for vision.  Essentially it's a bit of a risk factor if they find it or not.)
Comment: Waiting to see them elsewhere before warding is good advice, I've died a couple of times by being jumped just as I go to ward.
Comment: Great information here. Another thing I would mention as "high risk" is the chance of the enemy team trying for your red buff at the very beginning. It doesn't happen too often, but if you're not prepared when it does, it cripples your own jungler.
Comment: @Thebluefish I think thats a bit unrelated, but anyways I ward the red at 55 seconds to offset that issue.  It's really your junglers job to do the early scouting after that on his red to make sure he's not being counter jungled there.
Answer: There is no formular when to watch out since game-balance changes to fast. It is not like in starcraft2 where you can actually time enemy strategies. That being said, here is some general advice:

Most junglers won't gank you prior Level 3. And they (mostly) level
slower than champs on lane. So you could start to be prepared once
you hit level 3.
Get wards ... the safest gank prevention method :)
Talk to you team and call the jungler when he is seen.
Play jungle yourself. A jungler knows how and when a jungler will
gank you.

I hope this helps.
Best Regards,
zTonic
Comment: As you states, most junglers won't gank prior to level 3. I would say, this is true and false. They can try a quick gank at lvl 2, right after the blue/red. They will not kill you but cripple you for after.
And also, shaco definitely can.
Answer: Lets say you are top lane and the enemy is on the blue side of the map.
If the enemy jungler starts at his red he should clear his blue around ~3;30 and hit level 3.
meaning you can expect a gank top to hit around 3;50.
after that its all about warding and map awereness.
Answer: I guess you can add some more points here.
First of let's start with early game. You should pay attention to the enemy top and bot laner. Are they low on mana? Did they come to lane later? If you pay attention to this you can decide whether their jungler started at red or blue. According to this you can plan your defense. An important point here is that the jungler out levels you in the first 3-4 minutes of the game. He is level 3 and you are level 2 if he ganks after both buffs. Play defensively or get vision!
Always hug the side where you do not expect the jungler to be. If he started blue and takes red to get level 3, hug the blue side of your lane and the other way around. Timing enemy buffs or keeping them in mind is another important point. If you see that the enemy midlaner gets blue you should be careful in bot / top lane respectively because you know the jungler is around.
The best wards are deep wards in the enemy jungle, in my opinion, because you get warned earlier and can back off accordingly. Deep wards at his red or his blue or at the jungle entrances from mid lane. This will give you time enough not to die to ganks.


Do swarmers count towards kill awards in multiplayer?

Question: In multiplayer, you get bronze, silver and gold awards that give you experience. Some of these are for 25, 50 and 75 kills with each gun and in total.
When fighting the Reaper troops, Swarmers will be released from Ravagers when you shoot them.  Does killing these count towards the above awards?
Answer: No. Swarmers, like Turrets, do not count towards Kill Awards.
Comment: This answer previously stated that Husk kills did not count towards certain rewards. This is false - the issue is that Throw doesn't count as a biotic kill if an enemy dies due to the physics damage. Husks contribute equally to kill awards like most everything else.


Get list of the components of NASDAQ-100

Question: I am trying to programmatically fetch the list of companies included in NASDAQ-100. I tried scraping Nasdaq-100-Index-Components using Beautiful Soup - bs4, but so far without much success.
How can I get this list (tickers and company names)?
s = requests.Session()
s.headers.update(
    {
        "Accept-Language":"en-US,en;q=0.9",
    "Accept-Encoding":"gzip, deflate, br",
    "User-Agent":"Java-http-client/"
    }
)
r = s.get("https://www.nasdaq.com/market-activity/quotes/nasdaq-ndx-index")
soup = BeautifulSoup(r.content, "html.parser")
res = json.loads([x for x in soup.find("script", {"type": "application/json"})][0])

This only returns a very limited list and I suspect that this naive scraping doesn't really get all the data.
Comment: The information you're looking for isn't visible in the HTML. The page is dynamically fed with Javascript. Open that page in your favourite browser and look at the page source and you'll see what I mean. There's probably an API out there somewhere that will get you this information but it may not be free
Comment: I might be ready to pay for an API but I cannot find it. Can you point to the line which actually loads the data into the HTML page? I failed to find it.
Comment: To add to the previous comment, if you really need to fetch these tickers from this specific web page you can use selenium which can access the web page using a browser and from which you will be able to see the data fed with Javascript. But finding another source for your ticker will probably be simpler.
Answer: As data is dynamic generated go to chrome developer mode to Network tab
and find data by searching in box and refresh website now you can find link which content company list data as json data
import requests
headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"}
res=requests.get("https://api.nasdaq.com/api/quote/list-type/nasdaq100",headers=headers)
main_data=res.json()['data']['data']['rows']

for i in range(len(main_data)):
    print(main_data[i]['companyName'])

Output:
Activision Blizzard, Inc. Common Stock
Adobe Inc. Common Stock
Advanced Micro Devices, Inc. Common Stock
Align Technology, Inc. Common Stock
..

Image
Answer: Using QQQ ETF
To obtain an official list of Nasdaq 100 symbols as constituents of the QQQ ETF:
def list_qqq_holdings() -> pd.DataFrame:
    # Ref: https://stackoverflow.com/a/75846060/
    # Source: https://www.invesco.com/us/financial-products/etfs/holdings?ticker=QQQ
    converters = {'Holding Ticker': lambda s: s.rstrip(' ')}
    return pd.read_csv(url, converters=converters, index_col='Holding Ticker')

Using Wikipedia
To obtain an unofficial list of Nasdaq 100 symbols, pandas.read_html can be used. A parser such as lxml or bs4+html5lib is also required as it is used internally by pandas.
Note that the list on Wikipedia can be outdated.
import pandas as pd

def list_wikipedia_nasdaq100() -> pd.DataFrame:
    # Ref: https://stackoverflow.com/a/75846060/
    url = 'https://en.m.wikipedia.org/wiki/Nasdaq-100'
    return pd.read_html(url, attrs={'id': "constituents"}, index_col='Ticker')[0]

>> df = list_wikipedia_nasdaq100()
>> df.head()
                    Company  ...                      GICS Sub-Industry
Ticker                       ...
ATVI    Activision Blizzard  ...         Interactive Home Entertainment
ADBE             Adobe Inc.  ...                   Application Software
ADP                     ADP  ...  Data Processing & Outsourced Services
ABNB                 Airbnb  ...     Internet & Direct Marketing Retail
ALGN       Align Technology  ...                   Health Care Supplies
[5 rows x 3 columns]

>> symbols = df.index.to_list()
>> symbols[:5]
['ATVI', 'ADBE', 'ADP', 'ABNB', 'ALGN']

Using Slickcharts
import pandas as pd
import requests

def list_slickcharts_nasdaq100() -> pd.DataFrame:
    # Ref: https://stackoverflow.com/a/75846060/
    url = 'https://www.slickcharts.com/nasdaq100'
    user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0'  # Default user-agent fails.
    response = requests.get(url, headers={'User-Agent': user_agent})
    return pd.read_html(response.text, match='Symbol', index_col='Symbol')[0]

These were tested with Pandas 1.5.3.
The results can be cached for a certain period of time, e.g. 8 hours, in memory and/or on disk, so as to avoid the risk of excessive repeated calls to the source.
A similar answer for the S&P 500 is here.


Solve for the coefficients of a quadratic surface given certain initial conditions.

Question: Here is a problem on my homework.  I have been able to work through part of it but i have hit a bump in the road:
Let $L$ be the line determined by the equations $y = 6,~x = 10 z$. If we rotate $L$ around the x-axis, we get a surface whose equation is  $A x^2+B y^2+C z^2 = 1$.  Solve for the coefficients $A$, $B$, and $C$.
Hint: Pick a point on the line and rotate it around the x-axis...you will get a circle. Think about how the radius of that circle changes as the point changes.
$B$ is fairly easy to solve for.  If i plug in $x=0$, then $z=0$ as well, and you can easily plug in $y=6$ and get $B=1/36$.
After that I don't know where to go.  I can plug in a value for $x$ and get the relationship between $A$ and $C$ to be $C=-100A$.
How can I finish solving for these coefficients?  I believe that taking the Hint into account, making the circles, then the radius of the circle "slice" would be the value of C.
Thanks!
Comment: Actually i think i've just realize that since we are rotating all the way around the x axis, then the radius of the circle would be $y=6$ for $x=0$,  and then it would increase from there based on the value of C.
Answer: I figured out the solution:
First analyze the curve at the point $(0,4,0)$.  When you take that point and rotate it around the x-axis, you get a circle of radius $y$, which is 6.
This circle of $radius=6$ is entirely in the $yz$ plane.  You can analyze it without the $x$ component for a minute.  The equation of circle will then be $y^2+z^2=6^2$ at $x=0$.
To get this to be in the same form as the equation given, you  must divide both sides by 36.  Thus the coefficients $B$ and $C$ will be equal to $1/36$. The resulting equation is: $(1/36)y^2+(1/36)z^2=1$.
Now choose another value for $x$ to obtain the value of $A$. Using $z=1$ and $x=10$ you get the following:
$$A(10)^2+(1/36)(6)^2+(1/36)(1)^2=1$$
Simplify that to $100A=-(1/36)$
Then $A = -1/(3600)$.
Thus the solution is $(-1/3600)x^2+(1/36)y^2+(1/35)z^2=1$.


Translating .htaccess to Tuckey UrlRewriteFilter

Question: I'm building a project using Spring Boot and Angular 1.5.X and I am struggling to handle full page refreshes of Angular routes - typical "404 because the path I made doesn't actually exist" problem. I've done a fair bit of research and the solution that I keep seeing is to implement a .htaccess file with the following snippet in order to redirect all unknown requests back to the index (I pulled the following from this post)
RewriteEngine On
Options FollowSymLinks

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/$1 [L]

I have Tuckey's UrlRewriteFilter installed - according to this blog post since I don't have a WEB-INF folder - and it is working. It starts and it reads the urlrewrite.xml successfully. However, I don't know what to put in my urlrewrite.xml - I haven't the slightest clue of how to translate the above into something that the UrlRewriteFilter can understand. I've browsed the manual for the UrlRewriteFilter and I don't really know where / how to start.
Basically, what do I have to put in my urlrewrite.xml so that if I hit F5, my website doesn't puke back 404 errors?
Any help is appreciated.
Edit 1
I should mention that all of my API endpoints are prefaced with /api/** in order to distinguish them from links on my front end - an example would be /api/open/getUser and /api/secured/updateSettings.
Edit 2
Couple things I've discovered so far. One is that the UrlRewriteFilter can actually support .htaccess files and I did get it (as far as I can tell) to load in by moving the .htacess into my Resources folder and tweaking the code sample in the above blog post slightly, changing this
 private static final String CONFIG_LOCATION = "classpath:/urlrewrite.xml";

to
 private static final String CONFIG_LOCATION = "classpath:/.htaccess";

and
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "MyProject");

to
Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(), "MyProject", true);

The addition of the true tells the filter to use a .htaccess file. Awesome, problem solved right? Not quite - it's hard to explain but it doesn't seem like the UrlRewriteFilter was/is reading the .htacess correctly. I was using an .htacess tester to verify that the regex's and rewrite conditions were working as I expected and they seemed to be. The tester said that they were fine. However, the UrlRewriteFilter would freak out and get stuck in some kind of loop, to the point that Java would throw a stack overflow exception (as to why, I've no idea - I can't seem to find a way to set the filter's logging level to debug via Java D:< ).
So clearly that didn't work - I am currently attempting to translate the .htaccess into urlrewrite.xml myself, and here is what I've managed to created so far.
<urlrewrite use-query-string="true">
<rule match-type="regex" enabled="true">
    <note>
        Any URI that ends with one of the following extensions will be allowed to continue on unimpeded.
        Buried in the manual was the single line that said a "-" in the "to" will allow the request to
        continue on unmodified.
    </note>
    <from>\.(html|css|jpeg|gif|png|js|ico|txt|pdf)$</from>
    <to last="true">-</to>
</rule>

<rule match-type="regex" enabled="true">
    <note>
        Any URI that is prefaced with "/api/open/**" or "/api/secured/**" will be allowed through unmodified.
    </note>
    <condition type="request-uri" operator="equal">\/api\/(open|secured)\/([a-zA-Z0-9\/]+)</condition>
    <from>^.*$</from>
    <to last="true">-</to>
</rule>

<rule match-type="regex" enabled="false">
    <note>
        This one is supposed to be a "when all else fail" rule - if the other two rules don't match,
        forward to the index and let Angular figure out the rest.
        !! This one seems to be getting stuck in a loop of sorts !!
    </note>
    <from>^.*$</from>
    <to last="true">/</to>
</rule>
</urlrewrite>

The first two seem to be working splendidly. The third rule (the one with enabled set to false for good reason) does not - it also appears to getting stuck in the same filter loop (or whatever is happening - the stack trace is so big that Intellij is like "nah man") as the .htacess method. Making progress.
Answer: Huzzah, I managed to get it! It was a right pain the butt since I couldn't figure out how to turn on debugging and see what the filter was actually doing, but alas, I have succeeded!
Spent one metric crap ton of time using a regex tester, and this is what I came up with. I am by no means even remotely close to a regex master, so please try to contain your nausea should you have any.
<urlrewrite use-query-string="true">

<rule match-type="regex" enabled="true">
    <note>
        - "/post/**" and "/user/.../**" are optional - this is because when you're on, say, "/post/20" and you hit
            F5, the browser will attempt to get the static assets from "/post/**"
        - the second group is used to see if the request is for a static asset
        - take advantage of back references and forward only the part that matches the second group
        - i.e. "/post/20" as URI -> hit F5 -> "/post/scripts/mainController.js" request of server -> "/scripts/mainController.js" forwarded
        - i.e. "/user/Tester/home" -> hit F5 -> "/user/Tester/scripts/mainController.js" -> "/scripts/mainController.js" forwarded
    </note>
    <condition type="request-uri" operator="equal">\/?(post\/|user\/[a-zA-Z0-9]+\/)(.*.(html|css|jpe?g|gif|png|js|ico|txt|pdf))</condition>
    <from>^.*$</from>
    <to last="true">/%2</to>
</rule>

<rule match-type="regex" enabled="true">
    <note>
        Any URI that is prefaced with "/api/open/**" or "/api/secured/**" will be allowed through unmodified.
    </note>
    <condition type="request-uri" operator="equal">\/api\/(open|secured)\/([a-zA-Z0-9\/]+)</condition>
    <from>^.*$</from>
    <to last="true">-</to>
</rule>

<rule match-type="regex" enabled="true">
    <note>
        - Register, browse, search, and upload are all single level urls - the "\z" is to match the end of the string,
            otherwise "/register" would match "/registerController.js"
        - Inbox CAN be like "/inbox/favorites" so that's why it has a secondary regex - my Regex-Fu isn't good enough to combine
        - Settings always has a secondary level
        - User always has either home, gallery (w/ page and number), or favorites (w/ page and number)
        - A post will always have a number
    </note>
    <condition type="request-uri" operator="equal" next="or">\/(register\z|browse\z|search\z|upload\z|inbox\z|tag\z)</condition>
    <condition type="request-uri" operator="equal" next="or">\/inbox\/(favorites\z|uploads\z|comments\z)?</condition>
    <condition type="request-uri" operator="equal" next="or">\/settings\/[A-Za-z-_0-9]+</condition>
    <condition type="request-uri" operator="equal" next="or">\/user\/[A-Za-z-_0-9]+\/(home\z|gallery\/[0-9]+\/[0-9]+|favorites\/[0-9]+\/[0-9]+)</condition>
    <condition type="request-uri" operator="equal" next="or">\/post\/[0-9]+</condition>
    <from>^.*$</from>
    <to last="true">/</to>
</rule>

The rules are not as general as I'd like, but they are functional (I have a sneaking suspicion that those five conditionals daisy chained together are a bit of a performance hit). The rules are pretty much specifically tailored solely to my needs but hopefully they can at least be starting point to anybody else who was in my shoes about 4 days ago.
Another important thing to take note of is that in your Angular config (if you're using HTML5 mode - I don't believe that the following is required for hashbang mode), make sure you set requiredBase to true, like:
$locationProvider.html5Mode({
    enabled: true,
    requireBase: true
});

and include a
<base href="/">

in the  of your index.html file. If you don't, Angular will get confused and parts of your application might not quite load correctly - parts of my URI were being trimmed, for example.
Also, tip for anybody new to using .htaccess / UrlRewriteFilter, go get yourself Postman in order to test your rules - probably a major "well, duh" for most, but for the rest of us it'll be a life saver :)
If anybody has any tips on how to improve the efficiency / combine the regex's at all, please let me know.


When I use drain cleaner the whole house smells like sulfur for a couple hours

Question: I used it in the bathtub, & another time in the basement suds tub, the whole house would smell. Last year I checked the vent pipe on the roof & removed a lot of old paper wasp nests, but am still having the problem.
Comment: What kind of pipes do you have? Are they copper / steel / cast or PVC?

Despite what the bottle says, Drano can eat certain metals and cause toxic fumes in your house while it does it.
Answer: I would advise against Drano. The sulfur smell you are smelling is because it is mainly composed of Sulfuric Acid. If you smell it throughout your house it might be damaging your pipes.
To clear a clog I would recommend a plunger and a drain snake before resorting to any acids. If those do not work I would recommend a plumber.
However, be cautious now. If you are manually clearing your pipes, anything that you pull out might be covered in acid, so make sure to use hand, eye, and nose/mouth protection.
Comment: [Drano is lye-based](https://blog.jiffyondemand.com/why-plumbers-advise-against-drano/), not acidic and not sulfuric.
Comment: That would make sense, I see some of the manufacturers have come out with the "gel" version advertised as safe on pipes,
Comment: It looks like it is doing it on 2 separate vent pipes, one in the basement, the other on the bathroom


Set id attribute of element to jstl variable

Question: <input type = "radio" name = "skillLevel[${status.index}].skillLevelId" id = "skillLevel[${status.index}].skillLevelId" value = "3"/>

For input name attribute the value skillLevel[${status.index} works fine but for id attribute IDE shows error -
Bad value "skillLevel[   ].skillLevelId" for attribute "id" on element "input": An ID must not contain whitespace.

Syntax of id:
An ID consists of at least one character but must not contain any whitespace.
Is there any way. I just want unique id value for input element as the above statement is within loop. On every iteration I want unique id value.
Answer: try this id
id = "skillLevel${status.index}"

Answer: Solved the problem using jsp:element and jsp:attribute tags. Here is the solution :
<jsp:element name="input">
    <jsp:attribute name="type">radio</jsp:attribute>
    <jsp:attribute name="id">skillLevel[${status.index}].skillLevelId</jsp:attribute>
    <jsp:attribute name="name">skillLevel[${status.index}].skillLevelId</jsp:attribute>
    <jsp:attribute name="value">3</jsp:attribute>
</jsp:element>


"%s ", string not printing space after string

Question: In this code snippet here:
printf("shell> ");
fgets(input, MAX_INPUT_SIZE, stdin);

//tokenize input string, put each token into an array
char *space;
space = strtok(input, " ");
tokens[0] = space;

int i = 1;
while (space != NULL) {
  space = strtok(NULL, " ");
  tokens[i] = space;
  ++i;
}

//copy tokens after first one into string
strcpy((char*)cmdargs, ("%s ",tokens[1]));
for (i = 2; tokens[i] != NULL; i++) {
  strcat((char*)cmdargs, ("%s ", tokens[i]));
}

printf((char*)cmdargs);

With the input: echo hello world and stuff, the program prints:
helloworldandstuff

It seems to me that the line strcat((char*)cmdargs, ("%s ", tokens[i])); should concatenate the string at tokens[i] with a space following it. Does strcat not work with string formatting? Any other ideas what might be going on?
Comment: read: [What is the proper use of the comma operator?](http://stackoverflow.com/questions/17902992/what-is-the-proper-use-of-the-comma-operator?lq=1)
Comment: Yes it compiles as is here just fine. One warning about the `printf((char*)cmdargs);` statement, but that's it. And that statement is only there for debugging purposes.
Comment: it Does compile because of comma operator, while simply `"%s ", tokens[i]` is not valid as what you think
Answer: strcat does not support formatting strings, it just does concatenation. Moreover, your use of the extra pair of parenthesis cause the C compiler to parse this as a comma operator, and not as arguments passed to the function.
That is, strcat((char*)cmdargs, ("%s ", tokens[i])); will result in a call strcat((char*)cmdargs, tokens[i]); as the comma operator invoke side-effect of all expression, but return the last value.
If you want to use strcat, you should write:
strcat((char*)cmdargs, " ");
strcat((char*)cmdargs, tokens[i]);

The same thing apply to the strcpy function call too.
Answer: Write your own version of a formatting string-concatentating function, if that's what you want:
(untested)
int strcatf(char *buffer, const char *fmt, ...) {
    int retval = 0;
    char message[4096];
    va_list va;
    va_start(va, fmt);
    retval = vsnprintf(message, sizeof(message), fmt, va);
    va_end(va);
    strcat(buffer, message);
    return retval;
}

...
strcatf((char*)cmdargs, "%s ", tokens[i]);
...

Comment: actually interesting!!, but do we need () at call ?
Comment: You want to remove the extra parenthesis in the call of `strcatf` otherwise you get the same issue with the comma operator.


Pygame Becomes Unresponsive after running for a few seconds

Question: I'm trying to write a GUI to display the Knights Tour backtracking algorithm. I have the algorithm working but when running the GUI, it becomes unresponsive after a few seconds.
import pygame
import time

# Init Gui

pygame.init()

# Window Size
WIN_DIMENSION = 800

win = pygame.display.set_mode((WIN_DIMENSION, WIN_DIMENSION))
pygame.display.set_caption("Knights Tour")

# Board Size
N = 8

TARGETMOVES = N**2

# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (180, 0, 0)

def DisplayGui(board, final=False):

    win.fill(black)

    for i in range(N):
        ydraw = i * (WIN_DIMENSION/N)
        for n in range(N):
            xdraw = n * (WIN_DIMENSION / N)
            pygame.draw.rect(win, red, (xdraw, ydraw, WIN_DIMENSION/N, WIN_DIMENSION/N), 3)
            displayText(board[i][n], xdraw, ydraw)

    while final:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                final = False
                print("CLOSING")

    pygame.display.update()
    #time.sleep(1)

def text_objects(text, font):
    textSurface = font.render(str(text), True, white)
    return textSurface, textSurface.get_rect()

def displayText(text, xdraw, ydraw):
    font = pygame.font.Font('freesansbold.ttf', 7 * N)
    TextSurf, TextRect = text_objects(text, font)
    TextRect.center = ((xdraw + (WIN_DIMENSION / N) / 2), (ydraw + (WIN_DIMENSION / N) / 2))
    win.blit(TextSurf, TextRect)

def checkValid(board, movx, movy):
    '''
        params:
        movx => next x move
        movy => next y move

        checks if move is valid
    '''
    if (movx >= 0 and movy >= 0 and movx < N and movy < N and board[movx][movy] == " "):
        return True
    return False

def printBoard(board):
    '''
        Prints Board
    '''
    for i in range(len(board)):
        print(board[i])

def KnightsTour():
    currx = 0
    curry = 0

    # Init board
    board = [[" " for i in range(N)] for i in range(N)]

    xmoves = [-2, -2, -1, -1, 1, 1, 2, 2]
    ymoves = [1, -1, 2, -2, 2, -2, 1, -1]

    totalmoves = 1

    board[0][0] = 0
    DisplayGui(board)

    if generateMove(board, currx, curry, totalmoves, xmoves, ymoves):
        printBoard(board)
        DisplayGui(board, True)
    else: print("Invalid")

def generateMove(board, currx, curry, totalmoves, xmoves, ymoves):
    if totalmoves == TARGETMOVES:
        return True

    print("X: {} <> Y: {}".format(currx, curry)) # draw  board here

    DisplayGui(board)

    for i in range(8):

        nextx = currx + xmoves[i]
        nexty = curry + ymoves[i]

        if checkValid(board, nextx, nexty):
            board[nextx][nexty] = totalmoves

            if generateMove(board, nextx, nexty, totalmoves+1, xmoves, ymoves):

                return True
            # backtracking
            board[nextx][nexty] = " "

    return False

if __name__ == "__main__":
    KnightsTour()

I tried to slow it down using sys.sleep() but that didn't help it. I have no idea whats causing the GUI to freeze. The algo still runs in the background.
Comment: I suspect the GUI is locking up because the code "starves" the pygame event queue, never calling `pygame.event.get()` because `final` passed to `DisplayGUI()` (which handles events) is not true until the last move(?).  All that said, I ran it for some minutes, and it did not lock up for me.  I think you should try to re-factor the looping such that events are checked on every display update, and window-close is properly handled somehow.  Maybe run the algorithm in a sub-thread, and post update events to a main loop for display.
Comment: Can you toss different `print()` statements in your different loops to narrow down what the program is doing when the GUI becomes unresponsive?
Comment: I agree with what @Hoog says, you should try debugging by adding prints throughout, but also I cannot find anything obviously wrong. Possibly you keep initializing and launching the window?
Comment: Variable and function names should generally follow the `lower_case_with_underscores` style.
Answer: If you want to overcome this problem without changing your code significantly you can call pygame.event.pump() in your DisplayGui() function. This will make your operating system / window manager believe that your program hasn't frozen.
def DisplayGui(board, final=False):

    win.fill(black)
    if not final:
        pygame.event.pump()
    for i in range(N):
        ...

It would be more helpful to actually handle QUIT events so you could end the program prematurely without ending the python process.
If you're considering reorganising your code, perhaps this openbook would be useful. This section describes a standard game loop which should look something like:
event handling → update state → draw new state → update display


How to add multiple activities under one onCreateOptionsMenu(Menu menu)

Question: I want to add multiple activities under one `onCreateOptionsMenu(Menu menu) in my android app, I have already added two activities and they are working fine but third activity isn't working, following is my code
onCreateOptionsMenu(Menu menu)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public final boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_item_share:
            shareURL();
    }
    if(item.getItemId() == R.id.menu_item_refresh){
        mWebView.reload();
        return true;
    }
    if(item.getItemId() == R.id.share_this_app)
        mShareActionProvider.setShareIntent(getDefaultShareIntent());
    return super.onOptionsItemSelected(item);
}

private void shareURL() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
    startActivity(Intent.createChooser(shareIntent, "Share This Website!"));
    shareIntent.setPackage("com.whatsapp");
}

/** Returns a share intent */
private Intent getDefaultShareIntent(){
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "download the app");
    intent.putExtra(Intent.EXTRA_TEXT," play.google.com ");
    return intent;
}

menu_main.xml
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">

<item
    android:title="@string/share"
    android:id="@+id/menu_item_share"
    android:showAsAction="always"
    android:icon="@drawable/share"
    />

<item
    android:id="@id/menu_item_refresh"
    android:title="Refresh"
    android:showAsAction="never"
    android:icon="@drawable/refresh"
    />

<item
    android:id="@+id/share_this_app"
    android:title="Share this app"
    android:showAsAction="never"
    android:actionProviderClass="android.widget.ShareActionProvider"/>

From above, menu_item_share and menu_item_refresh is working, but Share this app isn't working.
Comment: There is no `return true;` for the last one.
Comment: Put all possibilities in that switch statement. Or use only ifs.
Comment: `I have already added two activities` ??? Activities? Nowhere i see an Activity.
Comment: `but Share this app isn't working.` Share this app ? Can't you be precise? And what is `not working`? What should happen that does not happen? You are only setting an intent. Nowhere you start an activity there.
Comment: @greenapps now i have added menu_main.xml to question as well, by share this app isn't working. i mean after clicking on share this app option it should be able to send my apps google play store link to other apps, but the share this app option isn't responding .
Comment: `it should be able to send my apps google play store link to other apps, ` Really? Why do you thinkk it would? You are only setting an intent. You are not starting it.
Comment: `mShareActionProvider`. You are not showing what that is and how it is instantiated.
Comment: http://stackoverflow.com/questions/17928709/using-android-action-bar-share-intent
Comment: `How to add multiple activities`. Pretty bad description of your problem.
Comment: @greenapps it worked, thank you very much.
Comment: @greenapps i quoted question like that because i wasn't aware about how to use single onCreate for multiple actions.
Answer: Hey I think this would help...
You have written
  android:showAsAction="never".
So it would generate an error while putting an icon inside the menu icon(three dots at toolbar).
Hence put the value "always" or  "ifRoom" for this attribute.
Hope this would work  :-)
Answer: It's probably your are missing a return true statement below this line mShareActionProvider.setShareIntent(getDefaultShareIntent());. You can simply follow a clean structure to achieve your task.
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_item_share: {
        shareURL();
        break; //or, return true;
    }
    case R.id.menu_item_refresh: {
        mWebView.reload();
        break; //or, return true;
    }
    case R.id.share_this_app: {
        mShareActionProvider.setShareIntent(getDefaultShareIntent());
        break; //or, return true;
    }
    return super.onOptionsItemSelected(item);
}

Comment: not working, now its force closing the app after clicking on share this app, i have added both share intents in question, if you can have a look at it and let me know if there is something wrong with them.
Comment: you already have used what you need in shareURL() method. (1) create a method like 'shareURL()'. (2) follow: https://developer.android.com/training/sharing/send.html to share your app_playstore_url via other apps. (3) call the new method when you press on R.id.share_this_app
Comment: you can accept/upvote the answer if it was helpful. Your little inspiration encourages us to spend more time here :)


Scala Lift - ActorPing alternative

Question: I've recently implemented the ajax comet upload with progress found here:
https://github.com/mbk/ajaxupload_with_comet
When compiling I get an error saying ActorPing is deperected, what should I be using instead?
Thanks in advance :)
Answer: I think LAPinger is what you're looking for.

Scala Lift - ActorPing alternative


If i have a sine table, should i query the whole table into memory on wakeup?

Question: If i have a sine table, should i query the whole table into memory on wakeup?
Or should i query the table one every Sin(...) call? It seems a little more expensive to me to be hitting the database on every call of Sin(...), would it be correct practice to just cache the whole table into C# memory on wakeup?
Comment: Alright, well for a smallish lookup table that doesn't change - yes, definitely load it into memory on start.
Comment: In fact, are you sure you need a table? Is calling `Math.Sin` on the fly measurably too slow? It's infinitely faster than hitting the database.
Comment: If you trying to learn SQL manipulations why would you even load that in memory - make whatever you need to be SQL query... Whole thing sound like bad idea as practical question - there is no way loading data from DB would be better than computing that table every time....
Comment: How many rows do you have in this table? I wouldn't expect much more than 1000.. In which case, definitely keep it in memory - in fact, just pregenerate it with `Math.Sin`, you don't need a database.
Comment: im new to sql so trying to practice with lookup tables
Comment: i guess what i meant is that i understand sql but using c# and sql together is what i am trying to practice
Answer: Just using Math.Sin will be much faster than hitting the database, and not much slower than using an in-memory lookup table. This isn't really a good candidate for using a lookup table.
However, since you commented that you're just practising - yes, for a small table that doesn't change often (or ever), you should load it into memory on startup.
Answer: The answer depends on how many times you need to compute sin in your program's lifetime. If you need to do it once or twice an hour, querying DB or storing the table in memory makes no difference.
If you need to query sin often, storing the table in memory would make more sense. It goes without saying that lookups in the in-memory table need to be done in an efficient way: running a linear search on a million-row table in a tight loop could kill performance, even in comparison to a database alternative.


How to write http layer sniffer

Question: I want to write an application layer sniffer (SMTP/ftp/http).
Based on my searchs, first (and perhaps hardest!) step is to reassemble the tcp stream of the sniffed connections.
Indeed, what I need is something like the "follow TCP stream" option of wireshark, but I need a tool which do it on live interface and automatically. As I know, Tshark can extract TCP streams data from the saved pcap files automatically (link) but not from live interfaces. Can Tshark do it on live interfaces???
As I know, TCPflow can do exactly what I want, however, it can not handle IP defragmentation and SSL connections (I want to analyse the SSL content in the case I have the server private key).
Finally, I also try bro network monitor. Although it provides the list of TCP connections (conn.log), I was not able to get TCP connections contents.
Any suggestion about mentioned tools or any other useful tool is welcome.
Thanks in advance, Dan.
Answer: perl Net::Inspect library might help you. It also comes with a tcpudpflow which can write tcp and udp flows into separate files, similar to tcpflow. It works on pcap files or can do live captures. The library handles IP fragmenting. It also comes with a httpflow tool to extract HTTP requests and responses (including decompression, chunked encoding..). It does not currently handle SSL.
As the author of this library I don't think that extracting TCP flows is the hardest part, the HTTP parser (exluding decompression, including chunked mode) is nearly twice as big than IP and TCP combined.
Answer: This example works for reassembling application data of a single protocol:
<code>tshark -Y "tcp.dstport == 80" -T fields -d tcp.port==80,echo -e echo.data
</code>
It captures live http data, reassembles it, and outputs it as raw hex.
I can add a small script to parse the hex into ascii if you like.

I want to analyse the SSL content in the case I have the server private key

TL;DR: This can't be done with a capturing tool alone.
Why not: Because each SSL session generates a new secret conversation key, and you can't decrypt the session without this key. Having the private server key is not enough. The idea behind this is that if someone captures your SSL traffic, saves it, and then a year later he "finds" the private server key, then he still won't be able to decrypt your traffic.

How to write http layer sniffer


replacement for useThousandsSeparator in flex 4.5

Question: I've been migrating to flex 4.5 from flex 4.
I've used Numberformatter  to format number in the following method:
var numberFormatter:NumberFormatter = new NumberFormatter();
numberFormatter.precision=1;
numberFormatter.useThousandsSeparator=true;

that would work for an mx component. but if i'd like to use s component, both
of these properties don't apply.
I've learned that I can use fractionalDigits instead of percision.
I still didn't find a way to replace the propery useThousandsSeparator. that actually adds "," as a thousand seperator.
any ideas how to reslve the issue?
thank you
Kfir
Answer: I think thousand separator has be replaced by groupingSeparator
Comment: can you provide an example? groupingSeparator sets what the seperator will be. how do I enable it ?
Comment: ah ok i found it! numberFormatter.groupingPattern="3;*" awesome thanks


O(N) lookups but O(log(N)) comparisons when using upper_bound on a sorted list

Question: <code>list<Person> lp;
...
lp.sort(PersonNameLess());

Person newPerson;
...
lp.insert(upper_bound(lp.begin(), lp.end(),
          newPerson, PersonNameLess()), newPerson);
</code>
In the effective c++ 3rd edition, page 198, Item 45, it says as follows:

the lookup takes linear time, but it performs only a logarithmic
  number of comparison

Question: Why does it perform only a logarithmic number of comparisons?
Comment: Wow... I had no idea `binary_search` and friends only required forward iterators...
Answer:
Why does it perform only a logarithmic number of comparisons?

Because the list is sorted and upper_bound perform a binary search.
Comment: And moving the iterator to the next comparison site takes linear time because it's a list.


Retrieve google contact profile picture

Question: I need to retrieve google contacts information including contact's profile picture. To do this I use code below and everything works except contact's profile picture: the link that I get leads to nowhere. Is there any other way to get contact's profile picture link?
<code>    GoogleCredential gc = new GoogleCredential();
    gc.setAccessToken(accessToken);
    ContactsService contactsService = new ContactsService("ServiceName");

    contactsService.setOAuth2Credentials(gc);
    URL url = new URL("https://www.google.com/m8/feeds/contacts/default/full/?max-results=10000");
    ContactFeed feed = null;

    try {
        feed = contactsService.getFeed(url, ContactFeed.class);
    } catch (ServiceException e) {
        e.printStackTrace();
    }

    List<SocialContact> contacts = new ArrayList<>();

    if (feed != null) {
        for (ContactEntry entry : feed.getEntries()) {
            SocialContact contact = new SocialContact();

            if (entry.hasName()) {
                Name name = entry.getName();

                if (name.hasFullName()) {
                    if (name.hasGivenName()) {
                        String givenName = name.getGivenName().getValue();

                        if (name.getGivenName().hasYomi()) {
                            givenName += " (" + name.getGivenName().getYomi() + ")";
                        }

                        contact.setFirstName(givenName);

                        if (name.hasFamilyName()) {
                            String familyName = name.getFamilyName().getValue();
                            if (name.getFamilyName().hasYomi()) {
                                familyName += " (" + name.getFamilyName().getYomi() + ")";
                            }
                            contact.setLastName(familyName);
                        }
                    }
                }
            }

            for (PhoneNumber number : entry.getPhoneNumbers()) {
                contact.setPhone(number.getPhoneNumber());
            }

            for (Email email : entry.getEmailAddresses()) {
                contact.setEmail(email.getAddress());
            }

            contact.setProfileImageURL(entry.getContactPhotoLink().getHref());
            if(contact.getEmail() != null){
                contacts.add(contact);
            }
        }
    }
</code>
Answer: It sounds like you are using the Contacts API but maybe you should use the People API instead. The code below is modified from these docs:
<code>ListConnectionsResponse response = peopleService.people().connections().list("people/me")
    .setPersonFields("names,emailAddresses,photos")
    .setPageSize(10000)
    .execute();

List<Person> connections = response.getConnections();
    if (connections != null && connections.size() > 0) {
        for (Person person : connections) {
            List<Name> names = person.getNames();
            if (names != null && names.size() > 0) {
                System.out.println("Name: " + person.getNames().get(0)
                        .getDisplayName());
            } else {
                System.out.println("No names available for connection.");
            }

            List<Photo> photos = person.getPhotos();
            if (photos != null && photos.size() > 0){
              System.out.println("Photo URL: " + person.getPhotos().get(0).getURL());
            }
        }
    } else {
        System.out.println("No connections found.");
    }
</code>
Comment: This solution returns only people which was added in contacts. Every other contacts who wrote to me doesn't returns. But photo URL returns correct and I can see contact's profile picture

Retrieve google contact profile picture


Venn diagram of $A \cup B = B$

Question: I have to draw 3 Venn diagrams. A $\cup$ B = B. B $\cap$ A = B. B - A = B. I understand how to shade all of these, but I do not understand what "= B" is in any of these. I've searched and can't find any examples with = B.
Comment: If you take B as the empty set? It works for   B ∩ A = B.
Answer: Presumably you know how to draw a Venn diagram for $A$ and $B$ under the assumption, for example, that $A\subseteq B$.
Now suppose you know $A\cup B=B$. What does that tell you about the relationship between $A$ and $B$? Can you convert the statement "$A\cup B=B$" into a statement about $\subseteq$, which would let you draw a Venn diagram?
Answer: "= B" means that the shaded part will be exactly the set B. The pictures below can help you.

Shade the union of the circles in the first picture and shade the intersection of the circles in the second. In this case, what is the color of B?
Comment: In the second picture B is red? I don't understand what the "=" sign means when making Venn diagrams. A $\cup$ B = B mean the union of A and B is B?
Comment: @theguy1991 Yes, is red. Yes, A ∪ B = B means that the union is B. Notice that for this to happen, the set A have to be inside of the set B.

Venn diagram of $A \cup B = B$


(node:2157) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead

Question: I'm using MEAN stack and every time I save an user i get this warning
(node:2157) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
this is where I save user data
user.save(function(err, user) {
    if (err) return res.status(500).send({message: There was an error creating user. Please try again later: ${err}})
    return res
      .status(200)
      .send({ message: 'user successfully created' });
  });

what should I do to delete warning in console?
Answer: You should look this answer.
You need to plugin a promise library (q, bluebird, the es6 one...)
For bluebird:
mongoose.Promise = require('bluebird');

For es6:
mongoose.Promise = global.Promise;

More information you can find in docs.


Best way to deploy multiple client websites by Wagtail

Question: I want to create wagtail websites for my clients. The websites will be identical and have the same features, but the templates should be different. Every time I update a feature to a new version, all websites will get the latest version automatically. By this approach, I don't need to deploy new feature versions (or base website version) to my clients separately.  I just need to deploy once and all clients will get the latest website version.  I will use the 'Multi-instance' feature of Wagtail which seems to fit my needs.
In the documentation on 'Multi-instance' it states:

multiple sites share the same, single set of project files.
Deployment would update the single set of project files and reload
each instance.

https://www.accordbox.com/blog/add-bootstrap-theme-wagtail/
Let's say I want to have two different blog templates (different Bootstrap themes) in this tutorial.  The blog template file is 'post_page.html', and is a project file, so it will be deployed once, and all websites will get the same template in the 'Multi-instance' feature of Wagtail.
So my question is:
How can I deploy one blog template (post_page.html) to one client website, & another blog template to another client website?
Comment: Are you familiar with django-environ and environment files?  If not, I would suggest first looking at that library.  How do you manage your virtual environments?  And on what platform will you be deploying for production?  NGINX/uWSGI, Apache, or something else?
Answer: I think you will want to include all the template variations in your code base and then choose which one to use at request time. To choose a template file dynamically, you create a get_template method.
So the question becomes how do you configure which site uses which template(s). I would suggest looking into wagtail.contrib.settings for a place to map a site to its templates. Where I work we support 3 variations - but they come as a set. You can't pick the blog template from A and mix with the calendar template from B. We do this for our own sanity - especially since many of our blocks support display options of their own; for example, the 3 display options here are just styles the user can choose for the same block.
Answer: You could use the following approach (converted from Phoebe Factorial's solution for Multi-Site Wagtail.)
<code>class SitePage(Page):
    def get_template(self, request):
        template_name = super().get_template(request)
        DOMAIN = settings.DOMAIN

        return [
            settings.DOMAIN + '/' + template_name,
            template_name,
        ]

    class Meta(Page.Meta):
        abstract = True

class BlogPage(SitePage):
    ...
</code>
this would look for the template in the following ordered locations:

templates/<module>/<DOMAIN>/<template_name>
templates/<module>/<template_name>

Of course, if you'd prefer not to default to a generic template, you could remove the second item in the return list for SitePage.


How do you put mana symbols in your name?

Question: In all of the Magic the Gathering: Duals of the Planeswalker games so far, you can add mana symbols (and other symbols?) to your name using special character sequences.
What are all the character sequences?
Comment: Note that this is for magic online http://www.wizards.com/Magic/Digital/MagicOnline.aspx?x=mtg/digital/magiconline/howdoi/talk
Comment: One of them had a symbol at the beginning of the name, so when they spoke in the chat, I could see. As magic online, mana showed up as {U} or {W} for example. Problem is, if I try to type them they wont work. Did not try to put them in the name though.
Comment: @キキジキ Yeah, the symbols all have `{#}`, where `#` is some letter or number (possibly more than one??).  But there doesn't seem to be a list of them all online anywhere.
Answer: According to this post on steam, this is what you have to use:
Anything enclosed in {} in your Steam Profile name will be interpreted by the game as a symbol. The mana symbols are BWRUG (black, white, red, blue and green respectively). X, 0-9, and k-p (lower-case) are colorless mana costs. Various other letters and punctuation produce other symbols, such as Xbox or PS buttons, arrows, etc.


How to use intent in android react native module

Question: I wrote codes to access android native from react native,
to show the toast-like example on react native docs http://facebook.github.io/react-native/docs/native-modules-android.html
It works well, but when I try to use intent, there's an error.
Can someone help?
package com.myApp;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class QRModule extends ReactContextBaseJavaModule{

    public QRModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "QRCode";
    }

    @ReactMethod
    public void show(String message) {
        Intent intent = new Intent(this,DimoActivity.class);
        startActivity(intent);
        //Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}

Comment: We need the exact error text, not the picture please.
Comment: can u put error of android studio.
Comment: You should share your code in the question for two reasons.
1) If someone wants to help you, they can't just copy-paste your code because you shared an image.
2) The link might break so other people won't be able to use the help that you get.
Comment: i'm sorry i was added my code above, i think that because QRmodule class is not extend from AppCompatActivity, can someone help?
Comment: Did you find any fix regarding this?
Answer: You can simply use this great package: react-native-intent-launcher
Answer: a simple way.
In your QRModule you need to call the reactContext that contain the Activity reference from react native.
getCurrentActivity().startActivity(intent,CODE);


How do you complete zombotany 2?

Question: I just bought a minigame pack with the minigame zombotany 2. I am trying to complete the zombotany 2 but can only get past 50%  of the minigame before the zombies overwhelm me. Is there a recommended strategy to complete the minigame?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116205/discussion-between-melon-pult-and-a-bakker).
Answer: Seeing you can apparently not open the guide links.
The trick is to use as few lanes as possible. This can be achieved by using Garlic to force Zombies away from the lanes you got plants on. and then let AoE plants like Gloomshrooms to damage them by placing them just below and above the water.
Alternatively you can also use cattails on water to cover all lanes.
Pumpkin shields in combination with tall nuts also do wonders as long as you try to use as few lanes as possible.
O and before you got enough sun to build the Gloomshrooms/cattails you should use Potato-Mines and squashes to cover the lanes.

How do you complete zombotany 2?


Best practice to improve own answer

Question: If someone posts a detailed answer, with step by step, screen captures... gets votes, and it occurs that :

the answer doesn't solves fully the issue
the answerer finds the exact solution
but that solution is partially or completely different from the original one

Is it better to :

leave the original one intact, and post and edit below ? (does not "betrays" the existing votes)
completely rewrites it ? (better for readability and future use)
write a second answer besides the first one ??? (looks confusing)
Answer: It is rare that I've seen any multi-answer replies to a question by the same user.
Typically, the practice is to just to update the existing answer for whatever reason that the question has changed the context (e.g. UI updates no longer reflect instructions, a question has been updated with a left out detail, etc.). If preserving the original answer is important, you can insert some header noting postscript changes (e.g. "Edit: Answer worked in Drupal 8.3.x, added info for Drupal 8.4.x") into the body of the answer.
I'd say the only reason to add a 2nd answer is if the answer takes a completely different approach to the question, thus violating what the original answer achieves. For example, an answer might take a site builder approach (e.g. add & configure this module) or a developer approach (e.g. add a custom module and plug into the relevant APIs) which will solve the problem for 2 different sets of people.
Comment: I totally agree on _if the answer takes a completely different approach to the question_.

Best practice to improve own answer