Access to a function declared within an anonymous function?

Question: I have a file called bbUI.js which contains this bit of JavaScript. Outside of that file, I'd like to be able to call "var x = new iScroll(...)", but I currently get the error "ReferenceError: Can't find variable: iScroll".
(function(){
var iScroll = function (el, options) {
        var that = this,
            doc = document,
            i;

        // More code
    };
})();

From what I can tell, iScroll is defined within an anonymous function, and is itself anonymous but assigned to the identifier iScroll. If that's accurate, should I be able to call "var x = new iScroll(...)" in other places in my code?
Answer: The iScroll function only exists within the scope of the anonymous function it's wrapped in.  To use it elsewhere, you need to make it global.
You can make it global by removing the function it's wrapped in, or by setting window.iScroll = iScroll inside the anonymous function.
Answer: Remove the anonymous function that wraps the code:
(function(){   // <- this
  ...
})();          // <- this

The anonymous function prevents that code from polluting the global variables, so iScroll is defined only within that anonymous function.
Answer: Answer to this question depends on what do you really want to achieve and what the purpose of a self executing function. Anyway.. here iScroll is inside the self executing function and you have to make it available in the scope outside. I have given below two methods to do this.
Either just make it global by removing var keyword
(function(){
 iScroll = function (el, options) {
        var that = this,
            doc = document,
            i;

        this.show = function(){
           alert("hello world");
        }
    };

})();

or by adding a variable iScroll externally and returning the function.
var iScroll = (function(){
       return function (el, options) {
            var that = this,
                doc = document,
                i;

            this.show = function(){
               alert("hello world");
            }
        };
})();

to test
var iscroll = new iScroll();
iscroll.show();

Answer: Another option could be the following:
var iScroll = (function(){

     var iScroll = function (el, options) {
     };

     return iScroll; // <-- add this line

})();


How can I remove residue left from peel and stick tiles?

Question: I have old peel and stick vinyl tiles coming up off my vinyl flooring. I want to keep the floor underneath.
What gets rid of glue residue but is safe to use in house?
Comment: I've used soy based mastic removers before. The brand I used wad Bean-e-do
Answer: The approach is usually progressive. You try a less aggressive cleaner to see if it works, and if not, then move on to a more aggressive. At some point, you may find that the cleaner damages the surface, so test in an inconspicuous area.
I would use paper towels and a mild scrubbing pad, and I would use cleaners in the following order:

a soap based cleaner, such as Murphy's Oil Soap
strong household cleaner with grease cutter, such as Formula 409
a residue remover, such as Goo-Gone
a mild solvent, such as denatured alcohol
a stronger solvent, such as mineral spirits
a mild stripper, such as a citrus based product
a very strong solvent, such as acetone or lacquer thinner (but at this point you are almost sure to damage the surface of the flooring finish).
Comment: WD-40 is an example of a medium to strong solvent. I'm not sure why you would have started with that one...
Comment: I tried wd 40 and it helps but stinks really bad and leaves sticky and oily residue
Answer: I have found an easy way if you are going to recover the floor with some other type of floor covering first i heat an iron and soften tile by laying iron over cloth so tile lifts easily then i sprinkle the floor with fine sawdust and rub in i leave the sawdust fir 15 minutes while lifting more tiles then brush off excess when completed the area i wish to work on i leave for half hour brush off again then vacuum and you are left with a clean floor with only very fine trace of sawdust
Comment: + for the sawdust idea.  I've used it so many times, and it works so well—but not to REMOVE the glue.. it just makes it non-sticky
Answer: I pried up old peal and stick tile using heat gun, leaving very sticky glue residue, tried cleaning with hot water, mineral spirits and finally acetone. None worked. So finally I pealed off one tile and just sprinkled corn starch onto residue, making it no longer tacky at all. Not going to scrape anything as I plan on going over top of the concrete floor with floating click together vinyl.
Answer: If you are leaving the tiles in place: peanut butter and a little rubbing. The only problem is it will remove the deep shine, in that area. Just give the flooring a little Mop & Glow..
Comment: OP said that they're removing the tiles.
Answer: I removed the tiles, sprayed linoleum with Goo Gone,wiped up Goo Gone.  Lineoleum is clean. Quick and easy.
Answer: You can try applying  apple cider vinegar to it and let it sit. Of that doesn't work get yourself some goof off. That should do the trick.
Answer: I had a sticky floor issue after removing self stick 12x12 tiles. I took some advice and tried baking soda and it worked beautifully.
Comment: Nobody on this page appears to have suggested using baking soda. Can you explain how to use it, or at the very least link to where you found that advice? Thanks!


How do the laser pods (mines) work?

Question: I'm not sure to understand how the laser pods work, especially their culture/farming system.  It looks like you can only have one laser pod per defense tree you own at a time: once the laser pod has been produced, the defense tree it came from won't be able to grow a new seed into a new laser pod until the first one you produced get destroyed.
Also: how are the final laser pod's specs (energy/fight/speed) determined?  Is it some sort of average between 1/ the asteroid where the seed comes from and 2/ the asteroid where the defense tree host is situated?
Answer: You got that right on the way they grow:
Laser mines (not pods) can grow only on defense trees and only one mine per tree can be alive at any given time. That means, if a mine gets destroyed, eventually a new one will grow on the tree from which the old one originated.
The stats of a mine are determined solely by the asteroid on which they grow. The stats of the seedlings or even the flowers that made the tree are not relevant.
I can confirm those information from my own experience playing the game, but it is also discussed and explained in this forum thread.
Comment: Hey, thanks for the answer !  Are you sure about the "mine" term ?  In the android version, I'm almost sure it's called "laser *pods*" :o
Comment: I'm 100% sure that they are called "mines" on the PC version. Have a look at the Steam achievements, they also refer to it as mine (http://steamcommunity.com/stats/Eufloria/achievements/). But maybe they changed it for Android, dunno.
Answer: Just adding to Sentry's answer, a defense tree only produces laser mines/pods if it has a flower added to it. So if the flower is lost, the tree won't produce laser pods.
I frequently use my mines to destroy enemies' flowers on enhanced Dyson or Defense Trees in asteroids with a few number of seeds.
http://en.wikipedia.org/wiki/Eufloria#Gameplay
Comment: Yes they are only destroyed by mines :/ .. I usually take 3 or 4 to make sure that mines don't get killed by defense trees
Comment: Is it possible to destroy a flower already attached to a tree?
Comment: You can and you **must**
Comment: My seedlings ignore flowers. Are they destroyed only by mines?

How do the laser pods (mines) work?


How to stage changes with gitpython

Question: Does anyone know what the equivalent of git commit -a is in gitpython?
I have tried repo.index.commit, but don't see how to add the -a option.
repo.index.add adds only new files, not existing files that have been modified. It doesn't seem to support the update function as in git add -u.
I could do something like repo.git.commit('-a'), or even
repo.git.add('-u')
repo.index.commit(comment)

But I would think the high-level interface should be capable of doing this. Am I missing something?
Thanks in advance,
Evert
Comment: i'm having the same issue, and below answer doesn't seem to help.
Answer: You are not missing anything. GitPython acts more like plumbing, not like the porcelain that is git add -u and git commit.
Therefore it is viable and recommended to use the provided git command wrapper to get work done quickly as already demonstrated in your example (e.g. repo.git.add(update=True)).
Even though it is possible to implement anything purely in GitPython, it wouldn't perform as well or be as proven as the respective native git implementation already is.
GitPython starts to become powerful if you want to access git repository data quickly and conveniently through a relatively convenient and pythonic API. Examples include accessing branch and tag information, or querying commits in all detail.
Comment: Sorry for the late reply, I noticed just now I forgot to thank you, @Byron. I appreciate the efforts in maintaining a library like gitpython, glad to better understand its philosophy. Thanks again!

How to stage changes with gitpython


Flutter integration test - how to load a JSON file?

Question: I am writing a Flutter integration test with a mock client that returns a JSON response for each of the REST endpoints my app calls.
These JSON responses are stored in separate JSON files, but I am unable to access the files when the test is running.
I've tried loading the files by creating and reading a new file object. Flutter: how to load file for testing but it could never find the file.
I also tried putting my JSON files into assets. This worked, but also resulted in the test JSON files being bundled when I built the APK.
Simplified Mock Client:
MockClient integrationMockClient = MockClient((request) async {
  switch (request.url.toString()) {
    case 'https://staging.company.com/api/123':
      return Response(readJsonfile('myJsonFile.json'), 200);

Simplified integration test main function - passes mock client in. test_driver/app.dart
void main() async {
  enableFlutterDriverExtension();
  final app = await initializeApp(
    integrationMockClient
  );
  runApp(app);
}

When I try and read a file it can never find it. Possible because flutterDriver runs the 'real app' with no access to files stored in test directories.
How can I access a JSON file from an integration test without it being bundled in production code/APK?
Comment: Have you found the solution?
Comment: Sadly no. I implemented a dodgy workaround by storing the JSON in a dart string
`const String successJson = '{"value": 5, "Name": "test"}'`
Comment: Is there any workaround that came up in the last 4 month, I really on the JSON I'm loading in...?
Comment: The accepted answer at https://stackoverflow.com/questions/45780255/flutter-how-to-load-file-for-testing has an additional relevant answer below it, https://stackoverflow.com/a/57086750/6668797, which might address "*but it could never find the file*" unless you are more specific about your issue.
Comment: Haha, I did the same thing after unsuccessful research :D
Comment: @TWL above method works for mobile & desktop but what about loading json file for flutter-web as 'dart:io' doesn't support browser to access disk system
Answer: Put JSON into String variable, like this. const String objectJson = """{JSON}""";
Wrap your JSON with a triple quotation mark """
and use it on integration tests, instead of reading it from a file
Answer: I encountered similar issues accessing file resources using flutter driver for integration tests. What I did as a workaround was to parse the JSON response directly, instead of storing the JSON response as a file.
Here's a sample that you can try out. This uses https://jsonplaceholder.typicode.com as its endpoint sample.
test('Test http', () async {
    final file = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  final json = jsonDecode(file.body.toString());
  print('json contents: $json');
  print('userId: ${json['userId']}');
  final userId = json['userId'];
  expect(userId, 1);
});


Apt-get update not finding servers when host-only adapter is enabled

Question: I have this problem where i cannot update because it's just not finding the server. This only happens when i enable host-only adapter.
With only NAT, i can successfully update my server.
I'm just so desperate because literally nothing is working.
r0657757@ubuntu:~$ sudo apt-get update
0% [Working]

IP configuration:
source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto enp0s3
iface enp0s3 inet dhcp

auto enp0s8
iface enp0s8 inet static
        address 192.168.1.6
        netmask 255.255.255.0

I can successfully ping to any website.
I've tried uncommenting line 54 of /etc/gaia.conf file, changed the resolv.conf file to the DNS of Google, and tried disabling anti-virus.
Any ideas?
Comment: That is expected behavior for host-only. See https://www.virtualbox.org/manual/ch06.html#network_hostonly . Your Ubuntu guest VM should NOT be using host-only if you want to keep it updated.
Comment: Please don't use screenshots for text. Instead, paste the text, select it with your mouse, and press the `{}` button in the editor.
Comment: Then how can i use putty without host-only?
Answer: Host-only as its name implies means that the VM is linked only to the host, not to the Internet. You may enable packet forwarding (aka "Internet sharing") on the host to give Internet access to the VM.
Comment: I tried sharing the internet to the VM's host-only adapter. But still can't update and now i can't even use ssh from putty to my VM.
Comment: Okay the Ip of the adapter changed automatically so had to manually reset it after sharing the connection, i now can use putty but i still cannot update.
Comment: I fixed it, when sharing the wifi with the host-only adapter, i had to manally set the Ip to the same subnet of my host also i had to manually add google's DNS addresses in the ipv4 configuration! Thanks!


How to quicky update images in java GUI

Question: I want to know what is the fastest way to display and update images in JAVA. I'm receiving a series of images continuously from a socket and i want to display them in real time. I'm currently using a Jlabel inside a JFrame.
<code>void refreshScreen(BufferedImage bufImg)
{
label.setIcon(new ImageIcon(bufImg));
frame.repaint();
frame.getContentPane().repaint();
}
</code>
However this is extremely slow and takes 15-20 seconds to update even on my fast computer. What would be the ideal way to do this?
Comment: No need to call repaint if a JLabel's Icon changes. The key for you is to read in the images in a background thread, create your ImageIcon and set your label's Icon on the Swing event thread. Note your speed has nothing to do with Swing and all to do with transmitting the images through a Socket.
Answer: The problem would not be updating the image. When you set the Icon of a JLabel it will repaint itself immediately.
The problem would probably be in receiving the image over the socket (the speed of you computer has no effect here). You must make sure that the code that uses the socket does not block the Event Dispatch Thread as this will prevent the GUI from repainting itself. So you need to use a separate Thread for the Socket connection.
Read the section from the Swing tutorial on Concurrency for more information.
Comment: I'm calling refreshScreen() each time i receive an image in the socket. I see that the images come to the socket quickly but there is a lag in displaying it. So i guess socket isn't the bottleneck here.Its the displaying of the image.
Comment: @user2600028, the problem is not in the displaying of the image. That will happen immediately once the image is fully loaded. As I suggested earlier, you must be blocking the EDT so it can't repaint the image. Read the tutorial.

How to quicky update images in java GUI


Black Screen Ubuntu 14.04 – a possible cause

Question: Black Screen Ubuntu 14.04 – a possible cause
LATER EDIT:
After posting here all the informations that I have gathered these few days, I have made also two movies about this Black Screen issue, and the temperature sensor, and I uploaded them on Youtube.
Here they are:
The first video:
https://www.youtube.com/watch?v=9hxdFxxTozg
The second video:
https://youtu.be/Esqm4tlpLJk
Help that those ones make the things a little bit more clear for you.

Hello everyone. I think I have found a cause for the famous BLACK SCREEN on Ubuntu 14.04, and I hope to find a solution for this problem here.
I am struggling with a black screen issue on Ubuntu 14.04.
My desktop has multiple operating systems running, each one installed on a different HDD.
My desktop runs Ubuntu 14.04, Ubuntu 12.04 and Windows 7.
Both Ubuntu 12.04  and Windows 7 run with no problem, but Ubuntu 14.04 presents from time to time a black screen. If sound is running in the time of event, the sound continues to run, only the screen image is missing.
On Ubuntu 14.04 (and only on that OS) the black screen can appear a minute after the system is on and going, or after an hour, or after two hours, or the system can run a day or two with no problems at all! Only to present that black screen again three days later. And that is more confusing for me.
I have google searched and entered in numerous threads about this BLACK SCREEN issue (this is why I sayd  the famous BLACK SCREEN on Ubuntu 14.04), but with no success.
The graphic card is an old ASUS EAH 3870X2 (AMD ATI) with two graphic processors.
It has no more support for drivers on Linux from the manufacturer (and I will never ever again buy AMD ATI products).
However, somewhere on the big www somebody said something about the BLACK SCREEN issue on a laptop that he had just purchased, showing the black screen problem. He tested the GPU temperature with the command sensors in Terminal. The temperatures presented there were way too high. That guy finally returned the laptop in the 30 days time he had for no matter what return. And that was all.
Following that path I tested my Ubuntu 14.04 with the sensors command in Terminal on Ubuntu 14.04, and to my stupefaction the result shown was a + 115 C for one GPU processor, and a + 91 C for the second GPU processor!!!!!!!!!!!
And that with almost no video activity at all, only the OS running a fresh boot and the Terminal on (of course).
I have rebooted on Ubuntu 12.04 to seek for temperature results. Here I could place in terminal the command:
aticonfig --  odgt
and the result was:
Default Adapter ATI Radeon HD 3870 X2
Sensor 0: Temperature 56 C.
Then I rebooted on Windows 7, and the results obtained from HWINFO64 were somewhere on the same range, 53 C on one GPU, and 52 C on the second GPU.
Is it possible that Ubuntu 14.04 operating system is killing the graphic card output if the temperature is too high?
If it does, then why the GPU temperature on 14.04 is listed so high?
My graphic card cannot reach + 115 C on a fresh boot with no activity at all!!!! And it does not, because on Ubuntu 12.04 and w7 the temperature shows temperatures somewhere around 56 C.
So, what is happeninng on Ubuntu 14.04 with GPU Temperature sensors?
What is the solution for this problem? Possiby this problem affects many others who are struggling with this BLACK SCREEN issue. Many of them have this problem even from trying to boot a live Ubuntu  DVD that leads them only to a black screen. Even the installation of this OS is compromised.
Later Edit:
Today I have tried a few more tests regarding GPU temperatures on different operating systems on my  desktop, and the black screen phenomen.
First, I booted on Windows 7 and opened HWiNFO64.
I looked at the temperatures of the GPU (fresh boot, no hard video load, only HWiNFO64 sensors running):
GPU Thermal Diode 51 C
GPU Thermal Diode 49 C
Then I have completely stopped one of the two coolig fans of the graphic card (the graphic card has two cooling fans, it is a big graphic card).
I kept the cooler on hold for two minutes. The time was registered with a cronometer on my telephone.
After two minutes the video on my monitor was still on and going strong. No problems at all.
The temperatures of the GPU after two minutes (one cooling fan blocked by me, only HWiNFO64 sensors running):
GPU Thermal Diode 62 C
GPU Thermal Diode 51 C
I released the fan and let the cooler to run a few minutes to cool again the graphic card.
After that I have stopped both cooling fans of the graphic card.
After two minutes the video on my monitor was still on and going strong. No problems at all.
The temperatures of the GPU after two minutes (both cooling fans blocked by me, only HWiNFO64 sensors running):
GPU Thermal Diode 73 C
GPU Thermal Diode 68 C
So, on W7 the system was still going on after two minutes, with both cooling fans stopped.
Next I did the same tests on Ubuntu 12.04 and on Ubuntu 14.04. Here, due the fact that the temperature was not displayed on continuosly, but the command must be entered on Terminal, I asked my wife to help me. She was quicly paste the command (aticonfig --  odgt on 12.04, respectively sensors on 14.04, copied previously) and then hitting Return, to obtain the results, while I was keeping the fans blocked and watching the time on the stopwatch.
On Ubuntu 12.04 the results were:
 With one of the two GPUs coolig fans stopped:
The system presented a black screen after 1 minute and 12 seconds.
The last temperature displayed on terminal was 55 C.
With both GPUs coolig fans stopped:
The system presented a black screen after 48 seconds.
The last temperature displayed on terminal was 58 C.
On Ubuntu 14.04 the results were:
The temperatures with the system 14.04 fresh boot
radeon-pci-0300
Adapter: PCI adapter
temp1:       +112.0°C
radeon-pci-0400
Adapter: PCI adapter
temp1:        +95.0°C
With one of the two GPUs coolig fans stopped:
The system presented a black screen after 7 seconds.
The last temperatures displayed on terminal were
radeon-pci-0300
Adapter: PCI adapter
temp1:       +122.0°C
radeon-pci-0400
Adapter: PCI adapter
temp1:        +97.0°C
With both GPUs coolig fans stopped:
The system presented a black screen after 4 seconds.
The last temperature displayed on terminal were somewhere the same of the ones above (122 C).
Then I have completed a cicle by running the tests again on w7. That in order to see if the computer has been getting or not warmer on the use, and leading to worst results on Ubuntu 14.04.
But again, the computer was still going on on W7 after two minutes of cooling fans blocked. The result were
the temperatures of the GPU after two minutes (one cooling fan blocked by me, no hard video load):
GPU Thermal Diode 55 C
GPU Thermal Diode 52 C
the temperatures of the GPU after two minutes (both cooling fans blocked by me, no hard video load):
GPU Thermal Diode 71 C
GPU Thermal Diode 73 C
Conclusion:

On windows 7 the system was still showing video content even after two minutes of both cooling fans blocked.
On Ubuntu 12.04 the system displayed a black screen after 1 minute and 12 seconds with one cooling fan blocked, and after 48 seconds with both cooling fans blocked.
On Ubuntu 14.04 the system displayed a black screen after 7 seconds with one cooling fan blocked, and after 4 seconds with both cooling fans blocked

Ubuntu 14.04 performs the worst of the three OSs.
I am sure that my graphic card cooling system is good.
That is due to the fact that, even it is a 6 years old graphic card, I have recently (two months ago) cleaned it up.
I have completely dismounted it, changed the thermal paste, changed the thermal pads, cleaned it up.
It runs with no problems on w7.
I cannot even block the video display on w7, even with both coolers completely stopped.
Something is about the way that Ubuntu s  Temperature sensors read the values, and about how Ubuntu  takes the decision to kill the video output.
Especially on Ubuntu 14.04 this is a problem who affects many people.
For the moment I have added to my system two cooling fans to blow over the graphic card. One 100x100 mm fan, and a smaller one.
Still I hope to find a better solution for this problem.
Best regards.
Comment: I can see now that the if we apply x2 on the 56 C reported by Ubuntu 12.04, then 56 x 2 = 112 C. Near the 115 C reported by Ubuntu 14.04. Does Ubuntu 14.04 somewhat doubles the results of the real temperature? And why? The fact that the GPU have two processors mislead the sensors result?
Comment: No, the result from 12.04 doesn't need to be doubled.
Comment: Could it be possible that the OS is confusing °F with °C? For instance, 50°C equals 122°F. If the sensor sent an indication of 122°F and the OS interpreted that as 122°C then there would be a problem, as the OS would believe that the GPU had reached a temperature of 252°F!
Answer: While I was looking for more informations about temperature sensors on Ubuntu, I found a page about lm-sensors on Ubuntu here: https://help.ubuntu.com/community/SensorInstallHowto
They say in that post that:
As you can see, some sensors are obviously incorrect (e.g. AUX Temp and Case/Aux Fan); this tends to be the case with at least some of the sensors on most motherboards.
The AUX Temp in the example that they mentioned was:
AUX Temp:   +124.5°C  (high = +80.0°C, hyst = +75.0°C)  ALARM  sensor = thermistor
So, for Ubuntu OSs:

sensors can detect obviously incorrect temperatures, as shown on that article about lm-sensors.
sensors can detect obviously incorrect GPU temperatures, as shown in my post above with a wrong + 115 C GPU temperature detected by 14.04 for my GPU.
Ubuntu can take the decision to kill the video output, as demonstrated by me by blocking one or both graphic card cooling fans, leading to a black screen monitor.

Yes, I am pretty sure that I have found one of the possible causes for the black screen Ubuntu!
Comment: It would be good if people who are facing now this black screen issue when trying to install Ubuntu on their laptops or desktops, they would cooperate.

It would be interesting that those people would try to cool their systems heavily before and during  the run of the Ubuntu's installation DVD.

If by cooling their system heavily when running of Ubuntu's live DVD, they manage to get to the Ubuntu desktop, that could  mean that it is possible that they are facing a sensors incorrect GPU temperatures detection.
Answer: Now, armed with these informations that I gathered the last two or three days, I can see better the things that had happened with my computer on the last two months.
As I have told you previously, about two months ago I have serviced my 6 years old ASUS EAH 3870X2 Graphic Card, who was waiting that maintenance stored somewhere in a box in my house. My destop had another Graphic Card installed at that time. I have completely dismounted the ASUS EAH 3870X2, changed the thermal paste, changed the thermal pads, I cleaned everything up. After that, I have installed the  ASUS EAH 3870X2 Graphic Card on my desktop.
Due to the fact that the motherboard (an ASUS P5E3 Premium) has two slots for Graphic Cards, I have decided to install the  ASUS EAH 3870X2 Graphic Card on the slot the closest to the bottom of the dektop case.
I was thinking that the air close to the bottom of the case is the cool air, and the warm air is located higher inside the case.
But I can see now that that was a bad idea.
That because the space left between the graphic cards cooling fans, and the bottom of the desktop was very small, maybe 3 centimeters (a little more than one inch).
I think that the warm air blown out by the GPU coolers was sucked back again by the same vents, and leading to a fast temperature rising.
At least high temperatures for the 14.04 sensors, because for 12.04 and w7 were running with no problems.
What happened was that after this Graphic Card installation (in this position) I have been able to run Ubuntu 12.04 and windows 7 with no problems at all.
When I was trying to run Ubuntu 14.04 the system booted, sometimes leading me to a black screen, and sometimes I get as fas as to to be able to see the desktop for maybe 20 seconds, and after that I was getting the black screen.
I have had the Graphic Card mounted in this position for about 6 weeks. In those 6 weeks I have tried to solve this situation on Ubuntu 14.04.
I have been able to enter in the OS with nomodeset, no black screen at all when running on nomodeset, but due to the fact that AMD ATI has stopped the support for this Graphic Card for 14.04, and I have had no drivers available to install, I was unable to work around and find a permanent solution.
I was even thinking to reinstall 14.04 to get back my OS. But running the installation DVD took me to the famous black screen.
I have even thought to install something else, so I tried to install Linux Mint, or Ubuntu Mate, but the installation DVD's all send me only to look at a black screen.
After that, I  thought what about this situation is due to the fact that the Graphic Card is mounted in the wrong motherboard slot?
It is said that, if you have only one memory RAM stick available, it is best to insert it on the motherboard's RAM slot the closest to the processor.
What if the same thing was also true for the Graphic Card?
So I took the Graphic Card, and mounted it on the other slot, the one closest to the processor.
That gave some more space below the Graphic Card, between the cooling fans and the bottom of the case. Now the free space is around 7,5 cm (about 3 inches).
After that move, a miracle happened: my Ubuntu 14.04 was running again!!!!!
It was not perfect, as he had from time the the black screen issue, but it worked a lot better than before!
It run without the need of nomodeset.
It's true that I had the black screen issue from time to time, but at least it worked fine 98% of the time!
The fact that I still have the black screen issue every now and then was the reason that I have continued to search for possible causes. And that leaded me to make these tests and to post these observations here.
Hope that these observations help, and hope that someone will find solutions for the video black screen issues on Ubuntu.
Answer: I think you've hit on a good solution.  I had a similar thing happen with Ubuntu 14.04, but on an Nvidia GeForce card (a 12 old one, but decent, even today).  This card continues to show high temps due to wear and tear from old age, but in Ubuntu it was worse.  Nice job helping everyone out with, what I think is, the most stumper of a question out there.


How do I detect a failed subprocess in a bash read statement?

Question: In bash we can set an environment variable from a sequence of commands using read and a pipe to a subprocess. But I'm having trouble detecting errors in my processing in one edge case - a part of the subprocess pipeline producing some output before erroring.
A simplified example which takes an input file, looks for a line starting with "foo" and sets var to the first word on that line is:
set -e
set -o pipefail
set -o nounset

die() {
  echo $1 > /dev/stderr
  exit 1
}

read -r var rest < <( \
    cat data.txt \
    | grep foo \
    || die "PIPELINE" \
) || die "OUTER"

echo "var=$var"

Running this with data.txt like
blah
zap foo awesome
bang foo

will output
var=zap

Running this on a data.txt file that doesn't contain foo outputs (to stderr)
DEAD: PIPELINE
DEAD: OUTER

This is all as expected.
We can introduce another no-op stage like cat at the end of the process
...
read -r var rest < <( \
    cat data.txt \
    | grep foo \
    | cat \
    || die "PIPELINE" \
) || die "OUTER"
...

and everything continues to work.
But if the additional stage is paste -s -d' ' and the input does not contain "foo" the output is
var=
DEAD: PIPELINE

Which seems to show that the pipeline errors, but read succeeds with an empty line. (It looks like paste -s -d' '  outputs a line of output even when its input is empty.)
Is there a simple way to detect this failure of the pipeline, and cause the main script to error out?
I guess I could check that the variable is not empty - but this is a simplified version - I'm actually using sed and paste to join multiple lines to set multiple variables, like
read -r v1 v2 v3 rest < <( \
   cat data.txt \
   | grep "^foo=" \
   | sed -e 's/foo=//' \
   | paste -s -d' ' \
   || die "PIPELINE"
) || die "OUTER"

Answer: You could use another grep to see if the output of paste contained something:
read -r var rest < <( \
    cat data.txt \
    | grep foo \
    | paste -s -d' '  \
    | grep . \
    || die "PIPELINE" \
) || die "OUTER"

Answer: In the end I went with two different solutions depending on the context.
The first was to pipe the results to a temporary file. This will process the entire file before performing the read, and thus any failures in the pipe will cause the script to fail.
cat data.txt \
    | grep "^foo=" \
    | sed -e 's/foo=//' \
    | paste -s -d' ' \
    > $TMP/result.txt
    || die "PIPELINE"

read -r var rest < $TMP/result.txt || die "OUTER"

The second was to just test that the variables were set. While this meant
there was a bunch of duplication that I wanted to avoid, it seemed the most bullet-proof solution.
read -r var rest < <( cat data.txt \
    | grep "^foo=" \
    | sed -e 's/foo=//' \
    | paste -s -d' ' \
    || die "PIPELINE"
    ) || die "OUTER"

 [ ! -z "$var" ] || die "VARIABLE NOT SET"


Can a blade's Affinity Chart reward be earned before completing the previous level?

Question: I recently unlocked level 3 of Dromarch's Affinity Chart. Level 2 of the Raging Tiger skill is incomplete with a hidden unlock condition of "???" while level 3's condition is visible as "Use Raging Tiger (0/11)".
Is it possible to complete a blade's level 3 Affinity Chart reward before completing the level 2 reward? Will progress towards level 3 count if I haven't completed level 2?
Comment: Found a strange overlap of conditions on Gorg's Ability Chart. FTL level 1's condition is "Help an incapacitated ally (0/3)" while level 2 has "Help an incapacitated ally (0/2)".
Comment: Well, you can easily try this by yourself. But I don't think helping an incapacitated ally should overlap, there would be no reason to make a lower request for a higher skill level otherwise.
Answer:
Is it possible to complete a blade's level 3 Affinity Chart reward before completing the level 2 reward?

While my current save is not in a really good spot to test this, but I'm going with No. While reviewing Myrtha's affinity chart, I have her level 4 nodes unlocked. As you can see in the screenshots below, she has a handful for level 2 and 3 not completed. I know for a fact I've used Lightning Buster and Photo Edge a numerous amount of times after unlocking these nodes, but yet they do not any progression towards completion.

Will progress towards level 3 count if I haven't completed level 2?

The answer to this one is that it depends on the node. As shown above, progression towards level 3 nodes does not count if level 2 is not completed. However, there are some nodes that have "Previous instances count toward total" as sub-text
Comment: I was able to confirm that level 3 rewards cannot be unlocked before level 2. I also noted a few extra things: •Affinity rewards for drivers must also be unlocked in level-order. •Poppi α's affinity chart rewards for Tiger! Tiger! high scores are retroactive, despite not being listed as such. (Play 1 round of Tiger! Tiger! and the condition will unlock based on previous high scores). •If you've completed a level 2 condition, progress towards the level 3 condition won't count until you check that blade's Affinity chart


Adding a smart switch to a box originally containing two single-pole switches

Question: I currently have two single-pole switches in one box, with the first/upper controlling an interior light and the second/lower controlling an exterior light. I want to replace the second/lower with a smart switch while keeping the first/upper as a single pole. The smart switch calls for a neutral wire and a ground wire in addition to the load and line. However, my box does not appear to have a ground, or the ground was somehow incorporated into a bypass.

If I understand correctly, the neutral wire goes to the three white wires that are bundled under a wire cap at the back of the box and pass from top to bottom without going through a device. The load wire is the red wire that comes from the bottom of the first/upper switch (and currently attaches to the bottom of the second/lower switch). The line wire goes from the top of the second/lower switch through the bottom of the box to the rest of the circuit. However, the wire running from the bottom of the first/upper switch to the bottom of the second/lower switch is bundled via wire cap with two other wires that come from the top and the bottom of the box. Is that supposed to be the ground?
Also, what is that other yellow wire that feeds into the top of the first/upper switch rather than being screwed onto the side?
Answer: Legal colors in conduit wiring:
ALWAYS-HOT: black, brown, red, orange, yellow, pink, blue, or purple
SWITCHED-HOT: black, brown, red, orange, yellow, pink, blue, or purple
There's a convention of black for always and red for switched, but that's purely optional.
Now, these 2 switches have independent control, right? Neither switch is dependent on the other to be on, right?   So... that tells us that whichever wires go to BOTH switches must therefore be always-hot.  Therefore, red is always-hot.
Black is on the other switch terminal, so it must be switched-hot.
On the other switch, I see 2 yellow wires on the same terminal.  One uses the screw and the other uses the backstab.  Sloppy using the backstab but somebody really, really wanted to use the 50 cent switches instead of the $3.00 ones.  Anyway, those must be switched-hot, even though there are two of them.
Neutral, you've met. Make sure those neutrals are part of the same cable or conduit as the hots you are intending to switch, as that's a Code requirement. But they are, here.
I have no idea why there are 2 wires going to the switched-hot. Normally that indicates more than one lamp.  However that's how it was done, so that's how it should continue.  They'll be pigtailed to the new switch unless it has provision for 2 wires (most better switches do).
As for grounds... this hole is already tapped for a machine screw (bolt) of size  #10-32.  Readily available in North America, they even sell green ones just for ground screws - but any will do.
Comment: I notice a certain similarity between the code-compliant "always hot" color list and the code-compliant "switched hot" color list... ;)
Comment: @Freeman that's nothing. You should see the code-compliant "traveler" color list :)  And the 208 3-phase list, and the 480 3-phase list, and - well, if it's 240V wild-leg, the wild leg must be orange.  Now you know ALL the color rules in the book!
Comment: By code the grounding screw is required to be green if code compliance is important.
Answer: It looks very much like your wiring is run in conduit and that's very handy because the conduit itself should be carrying your ground for you (unless something was done incorrectly).
To install your new smart switch:

Unscrew the wire nut from the white bundle in the back and add the white from the new switch to it. That nut looks to be pretty small, so the addition of a 4th wire may be too much for it. You may need to purchase a larger wire nut (or there might possibly be a big enough one in the package with your new switch, but those tend to be pretty small, too).
Connect one of the hots from the new switch to the red wire where the red wire nut is.*
Connect the other hot to the black wire on your switch.
Connect the green/bare ground wire from the switch to the metal box itself. There should be a green grounding screw somewhere in the box for that purpose, though it's not readily apparent. There also appears to be a bare wire along the left-hand side of the box, and that could be a ground wire. Track that to see where it leads.

As to the 2nd question about the other yellow wire. That's called a "backstab" and they're rather unpopular. It's a way of attaching wiring to the switches that's a bit easier and faster because you just "stab" the wire into the hole in the back of the switch. The bad part is that it's held by a spring on the inside of the switch and it can work loose over time. It's likely that the wire runs to a 2nd light that's controlled by this switch.

*Note that I suggest you do these steps one wire at a time (i.e. never have 2 wires disconnected from the switch). This will help prevent the dreaded, "uh oh... which wire was supposed to go under this wire nut?" panic. Even when I'm replacing a light switch/dimmer (as I just did in my own house over the weekend) that I previously installed, I replace one wire at a time to ensure that I'm not confusing myself as to which wire is which. It's not critical on a plain toggle switch which wire goes to which terminal, but it can be very important on smart switches, and when you're disconnecting wire nuts from pig tails in the back of the box.
Comment: I think it's interesting that backstabbing is looked down upon in the US as opposed to screws, while it's apparently the other way around in Germany - almost all "home electrician" stuff uses spring-loaded connectors. Personally I hate those and would much prefer screw terminals, because there's not a single industry in which using something as flimsy as that would ever be acceptable - except, of course, for electricians over here.
Comment: That is interesting, @towe. While they're still code-compliant here (or new ones wouldn't be made & sold), they're frowned upon by many electricians. The newer "screw & clamp" ones are nearly as easy as a backstab and much more reliable if the screw is torqued properly.
Answer: You do have a ground or a bare copper on the left side, if your wiring is run in conduit (it looks like it is) the box itself should be ground even if the bare ground is not. So installing a green 10-32 grounding screw on the back right small hole will be a NEC  compliant way if your smart switch has a green wire. You are correct the whites look to be neutrals. The incoming hot will still need to be jumpered to both switches. The 2 yellow wires are on the same terminal one back stabbed and the other screwed down I like pig tails but this method is code compliant. I can't tell on my computer monitor but it looks like the red is the hot , jumpered to both switches then the other side black would be the switched hot   Similarly the red to the other switch hot to 2 yellows switched hots. Without testing that's how I would call it and wire it. The model of the smart switch would have helped us give a connection list usually if the smart switch has red it is the switched conductor black is the hot white you have figured out to the other 3 and a green wire to the box would wire it up from what I see.


How to write a list of numbers as bytes to a binary file?

Question: I have a list of bytes as integers, which is something like
[120, 3, 255, 0, 100]

How can I write this list to a file as binary?
Would this work?
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(newFileBytes)

Comment: You ask "Would this work?". Have you tried it?
Comment: Should be `TypeError: argument 1 must be string or buffer, not list`.
Answer: This is exactly what bytearray is for:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)

If you're using Python 3.x, you can use bytes instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytes is just an alias for str. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.
Python 3.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'

Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'

Comment: @Perkins: Sure, and you should avoid generator expressions if you need to work on 2.3, be careful with both `str.encode` and `struct.pack` if you need to work on 2.2. But 2.6 has been out for 5 years now; all three Ubuntu LTSs still in support, all three OS X versions in support, the previous major version of CentOS/RHEL, etc., all come with it built in. If you need to support 2.5 or 2.1 or 1.6 or whatever, you probably know…
Comment: @feersum: Of course; that's what binary vs. text mode _means_ in 2.x. It doesn't matter what type your bytes come from. (In 3.x, of course, binary vs. text mode means that you write bytes vs. unicode, and the `\r\n` feature is part of the universal newlines options for text.)
Comment: With Python 2 on Windows, I found that writing a `bytearray` still converts `\n` to `\r\n`, making it unsatisfactory for binary data, if the "b" flag is not passed when opening the file.
Comment: Nice use of builtin types. Just note that bytearray was added in 2.6, if you want to support legacy systems, it should be avoided.
Comment: I'm not sure bytearray() is a good choice for file writing. You would need to limit the size to manageable chunks. Otherwise once your filesizes get too high you will run out of memory.
Answer: Use struct.pack to convert the integer values into binary bytes, then write the bytes. E.g.
newFile.write(struct.pack('5B', *newFileBytes))

However I would never give a binary file a .txt extension.
The benefit of this method is that it works for other types as well, for example if any of the values were greater than 255 you could use '5i' for the format instead to get full 32-bit integers.
Comment: @MarkRansom: Well, this is still definitely a good solution to the more general problem of "I have a list of integers of some arbitrary but fixed size, how can I write them to a binary file?" and I can see people searching for that question and finding this one…
Comment: struct.pack is the better answer; it is far more flexible than simply creating a bytearray.
Comment: @Perkins I didn't make the assumption that the values would even be less than 256 much less in the ASCII range. Even if they are, .txt files should be reserved for those that make sense to a human which never applies to binary data.
Comment: You're right, struct.pack is also the way to go if you are going to be writing data with values above 255, since neither bytearray nor chr can handle larger integer values.
Comment: .txt is fine if you have some way to knowing that the data you are writing all falls inside the printable ascii range.  However, you are correct I think in this case, since the example data includes non printable characters.
Comment: @Perkins: But `struct.pack` can't handle values above 255 either. Nothing can, because there is no meaningful thing for them to do. You will get a `struct.error` instead of a `ValueError`, but otherwise there's not much difference. (Well, in 3.x, I guess `chr` will actually give you a `UnicodeEncodeError` instead…)
Comment: @abarnert, I didn't intend to pack them to bytes but to 4-byte integers. I've edited the answer to be clearer.
Comment: @MarkRansom: Given that he has "a list of bytes as integers", I don't think that's the output he wants.
Comment: @abarnert how did I miss that little detail in the question? Thanks!
Comment: struct.pack can support values larger than 256, just not with the "i" format, use 'l' instead, so struct.pack('l',257) works fine, because it handles the numbers as longs instead of ints.
Comment: @Perkins: You're mixing up your `struct` formats. Or maybe you're mixing up your C types. `int` is at least 16 bits, so it can already handle values >256. `long` is at least as long as `int`; on many platforms (Win32, Win64, most 32-bit *nix) but not all (most 64-bit *nix) it's in fact exactly the same size. And at any rate, the `'i'` and `'l'` formats don't actually use `int` or `long` unless you specify native packing; they both explicitly use 32 bits. It's `B` that can't handle values larger than 255. (And it's 255, not 256, of course.)
Comment: Right, that all makes sense, been a long time since I messed around with the `struct` module, and most of the C I use is on an embedded 8bit system with 16 bit longs, you are of course right when I actually take the time to think about it.
Answer: To convert from integers < 256 to binary, use the chr function.  So you're looking at doing the following.
newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))

Comment: No, I mean < 256, but the encoding should be `charmap` rather than `ascii`, and works in python2 as well as python3.  The `ascii` encoding only works in python2.
Comment: You must mean < 128. As python3 complains:
UnicodeEncodeError: 'ascii' codec can't encode character '\x89' in position 0: ordinal not in range(128)
Answer: As of Python 3.2+, you can also accomplish this using the to_bytes native int method:
newFileBytes = [123, 3, 255, 0, 100]
# make file
newFile = open("filename.txt", "wb")
# write to file
for byte in newFileBytes:
    newFile.write(byte.to_bytes(1, byteorder='big'))

I.e., each single call to to_bytes in this case creates a string of length 1, with its characters arranged in big-endian order (which is trivial for length-1 strings), which represents the integer value byte. You can also shorten the last two lines into a single one:
newFile.write(''.join([byte.to_bytes(1, byteorder='big') for byte in newFileBytes]))

Answer: You can use the following code example using Python 3 syntax:
from struct import pack
with open("foo.bin", "wb") as file:
  file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))

Here is shell one-liner:
python -c $'from struct import pack\nwith open("foo.bin", "wb") as file: file.write(pack("<IIIII", *bytearray([120, 3, 255, 0, 100])))'

Answer: Use pickle, like this: import pickle
Your code would look like this:
import pickle
mybytes = [120, 3, 255, 0, 100]
with open("bytesfile", "wb") as mypicklefile:
    pickle.dump(mybytes, mypicklefile)

To read the data back, use the pickle.load method
Comment: This does not produce a binary file of 5 bytes length, where the only content is 120, 3, 255, 0, 100. In a closed system, this may be acceptable though.
Answer: Convenient function to write array of int to a file,
def write_array(fname,ray):
    '''
    fname is a file pathname
    ray is an array of int
    '''
    print("write:",fname)
    EncodeInit()
    buffer = [ encode(z) for z in ray ]
    some = bytearray(buffer)
    immutable = bytes(some)
    with open(fname,"wb") as bfh:
        wc = bfh.write(immutable)
        print("wrote:",wrote)
    return wc

How to call the function,
write_array("data/filename",[1,2,3,4,5,6,7,8])

And wrap the following in a class for readable encode/decode:
Encode = {}
Decode = {}
def EncodeInit():
    '''
    Encode[] 0:62 as 0-9A-Za-z
    Decode[] 0-9A-Za-z as 0:62
    '''
    for ix in range( 0,10): Encode[ix] = ix+ord('0')
    for ix in range(10,36): Encode[ix] = (ix-10)+ord('A')
    for ix in range(36,62): Encode[ix] = (ix-36)+ord('a')
    for ix in range( 0,10): Decode[ix+ord('0')] = ix
    for ix in range(10,36): Decode[(ix-10)+ord('A')] = ix
    for ix in range(36,62): Decode[(ix-36)+ord('a')] = ix

def encode(x):
    '''
    Encode[] 0:62 as 0-9A-Za-z
    Otherwise '.'
    '''
    if x in Encode: return Encode[x]
    # else: error
    return ord('.')

def decode(x):
    '''
    Decode[] 0-9A-Za-z as 0:62
    Otherwise -1
    '''
    if x in Decode: return Decode[x]
    # else: error
    return -1


How to load or save Doctrine associated entity into Zend_Auth session

Question: I am looking for some good solutions for a problem.
I am usig Doctrine 2.1 integrated to Zend Framework. I am using Zend_Auth with Zend_Auth_Storage_Session where I have stored User's entity. But entity of User is associtad to other Entity => AclRole. Each User has one AclRole.
For the first time, when I load user throught EntityManager, the AclRole is loaded as soon as call it in User. But when other page is loaded and entity of User is loaded from session, her 'locale' attribute is NULL.
Is there any good solution of this?
Answer: I have an excellent solution, that i am using in my project, i will send you the github link when i've checked in my code today ;)


Recurrence relations help please?

Question: How do I solve this recurrence relation?
$$
a_k = a_{k-1} + k
$$
when $a_0 = 2$.
Comment: See also [Telescoping Series](http://en.wikipedia.org/wiki/Telescoping_series).
Comment: possible duplicate of [Solving the recurrence relation $T(n)=T(n-1)+cn$](http://math.stackexchange.com/questions/217162/solving-the-recurrence-relation-tn-tn-1cn)
Answer: hint: $a_k = (a_k-a_{k-1})+(a_{k-1}-a_{k-2})+\cdots + (a_2-a_1) +(a_1-a_0)+a_0 = k+(k-1)+(k-2)+\cdots + 2+1+2$
Answer: Note that
$$ a_k - a_{k-1} = k, $$
so
$$ a_{n}-a_0 = \sum_{k=1}^{n} (a_k-a_{k-1}) = \sum_{k=1}^n k = \frac{1}{2}n(n+1). $$

Recurrence relations help please?


Prove that $\sum_{k=1}^{n}\binom{n}{k}=\sum_{k=0}^{n-1}2^{k}$

Question: I know it has something to do with the binomial theorem but I'm not sure how the changed summation limits affect it.
$$\sum_{k=1}^{n}\binom{n}{k}=\sum_{k=0}^{n-1}2^{k}$$
Comment: $(1+1)^n=\cdots$
Answer: $$
\sum_{k=1}^n{n\choose k}=-1+\sum_{k=0}^n{n\choose k}=-1+2^n=\frac{1-2^n}{1-2}=\sum_{k=0}^{n-1}2^k.
$$
Comment: Just a note to the OP. Mercy uses properties of binomial sums and geometric series to get the result.
Answer: $$(1+x)^n = \sum_{k=0}^n \binom{n}{k} x^k  = 1 + \sum_{k=1}^n \binom{n}{k}x^k \implies (1+x)^n\bigg|_{x=1} = \cdots$$
$$\sum_{k=0}^{n-1} 2^k = \frac{2^n - 1}{2-1} $$
Answer: $$\sum_{k=1}^{n}\binom{n}{k}=-1+\binom{n}{0}+\sum_{k=1}^{n-1}2^{k}=-1+\sum_{k=0}^{n-1}2^{k}=-1+2^n=$$
$$=2^n-1=\frac{2^n-1}{2-1}=1+2+...+2^{n-1}=\sum_{k=0}^{n-1}2^{k}$$
Answer: Binomial Theorem
$$
(a+b)^n=\sum_{k=0}^n \binom{n}{k}a^kb^{n-k}.
$$
Set $a=b=1$ and get
$$
2^n=(1+1)^n=\sum_{k=0}^n\binom{n}{k}.
$$


Task manager CPU Usage

Question: I have two processors in my machine. The CPU usage that appears in task manager for a process P.exe is in the range 4-7%. Is that CPU usage a percentage of the usage of both the CPU by the process P ?
I later changed the affinity of the process P to a single core. The CPU usage of the process increased to be in the range 6-9%. How can changing the affinity of the process to a single core increase the CPU usage of the process P ?
Answer: Maybe your process was being moved from one core to another for processing and the task manager as you might figure, normalizes the data that it shows you (if it updates every second and for example you had 100% cpu usage on .1 seconds, 100x.1=10 so it shows you 10%). what i can figur out from that is that your second core was processing the program occasionally and measuring about 2%-3% and your first core was processing it more times than the second core measuring about 4%-7%.
If you set the affinity to two you should see that probably when the core 1 curves or spikes down during the execution, the core 2 curves or spikes up by about the same amount. maybe because it's a small graph you have to zoom it or enlarge or use a process that takes more processing power so the fluctuations become larger and you can see what i'm talking about.
Answer: The process P is a capable of being processed with multiple cores, thus will work faster and more efficiently with multi-core. If you're only using one core, your CPU is working harder thus CPU usage increases. It's like running using only 1 leg instead of 2. Even to go the same distance, it uses more energy and time to use 1 leg than it does 2.

Task manager CPU Usage


How to use spaces in Template Literals?

Question: I have a
 element showing dynamic content using Template Literals (template strings).

Galley Details
{`${galleyCartsDet[0].quantity} Full Cart ${galleyCartsDet[1].quantity} Half Cart${galleyCartsDet[2].quantity} SMU${galleyCartsDet[3].quantity} Stowage`}

How can I use spaces in the given template string?
`${galleyCartsDet[0].quantity} Full Cart ${galleyCartsDet[1].quantity} Half Cart${galleyCartsDet[2].quantity} SMU${galleyCartsDet[3].quantity} Stowage`

Comment: *"get a space after `${}` [...] space before the beginning of `${}`"* - Sorry, _where_ do you want the space? Your question is a bit unclear... Also, did you try an ` `? That outputs a space too.
Comment: I need the space in the beginning of ${} . I am searching for   usage inside `` literal
Comment: Needs more details such as where are you getting the variable from, and whether you are using any framework for this, and so on...
Answer: You can use spaces in a template string in this way:
`\u00A0\u00A0${option.value}\u00A0\u00A0`

\u00A0 = non-breaking space
\u0020 = normal space

How to use spaces in Template Literals?


How can I trim this value stored in cloud Firestore using flutter?

Question: I'm working on a flutter app. I don't want to convert the value to an Integer and want it to be stored as 75.33. Thanks in advance :)
Comment: Do you want to save it in `double` in Firestore?
Comment: yes, double would work too
Answer: When sending it to firebase, convert it using .toStringAsFixed(2), if you want it as it is in the image:
double value = 75.333333333333;
print(value.toStringAsFixed(2)); //=> "75.33"

FirebaseFirestore.instance.collection('collectionName').doc('docName').update({'Percentage': value.toStringAsFixed(2)});

(2) is the number of digits you want, if you want it 75.333 use .toStringAsFixed(3).`


Trouble Reading numbers from a .txt file and arranging them into A-F grading, as well as finding max, min, and average numbers

Question: I'm a little stuck on actually getting the scanner to open the file I have and arrange the numbers. The computer tells me it recognizes the file I ask it to open, but then doesn't display the numbers. Any help would be greatly appreciated, thank you very much!
package helloworld;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class textToArray {

        public static void main(String[] args) throws FileNotFoundException{
        //Open the file
        File f = new File(" ");
        System.out.println("Welcome to the Exam Statistics Program!");
        Scanner scanner = new Scanner( System.in );

        System.out.println("Please enter the name of the file: ");

        String input = scanner.nextLine();

        //Create a new scanner to read the file
        Scanner s = new Scanner(input);
        //Declare an array with length of 100
        int[] array = new int[100];
        int i = 0, min, max, sum = 0;
        //Loop through the file if there is a next int to process it will continue

        for(i = 0; s.hasNextInt(); i++){
            //We store every int we read in the array
            array[i] = s.nextInt();
        }

        //Close the scanner object
        s.close();
        //As the for loop will stop when there is no new int to read so the i++ will stop at the number of int in the file
        //We use this number to calculate the average
        int nbInArray = i;
        //initialize min and max to the first array value which is for now empty
        min = max = array[0];
        for(int j = 0; j<nbInArray ; j++){
            //Now we test if the new value if bigger than the initial value (0 or empty) the new value will become the max
            if (array[j]>max){
                max = array[j];
                }
            //Otherwise if the the value is smaller than the initial value the new value will become the minimum
            //And so on every time we test if we have a smaller value the new one will become the min
            if (array[j]<min){
                min = array[j];
                }
            //The sum was initialised to 0 so we add every new int to it
            sum = sum + array[j];
        }

        //We compute the avg , i declared it double in case we have decimal results
        //double avg = sum / nbInArray;
        //finally we print out the min, max and the average
        System.out.println("The minimum is: "+min);
        System.out.println("The maximum is: "+max);
        //System.out.println("The averange is: "+avg);

}
}

Comment: Please post some example contents to be used as the input file, so that we can reproduce your problem.
Comment: Not knowing what you are inputing it isn't possible to be helpful
Answer: You almost got it! Change this line:
Scanner s = new Scanner(input);

to:
Scanner s = new Scanner(new File(input));

Comment: Thanks so much, this was a big help. I found out another problem area was that I'm on a mac so I needed to specify the folder the document is in
Answer: Hello you have to change some lines on your code:
    File f = new File(input);

//Create a new scanner to read the file
Scanner s = new Scanner(f);

You can also check that the user give you an existing file by using
  f.exists();

last advice a class name should start with a capital letter.


C# String Search with multiple substrings

Question: So I'm working on a filter for a resource list and one of the filters is the Name property(string).
As a(dumb) example : resource name is "Big,Red/Square Table" and the filter is "Table Red", it should be a valid resource
This is what I could come up with using the little time I had:
static void ApplyNameFilter(ref ApplicationViewModel model, string filter)
{
    if (string.IsNullOrEmpty(filter) || filter == "") return;
    char[] separators = {' ', ',', '.', '/', '\\', '|', '_', '-'};
    var validResources = new List<ResourceModel>();

    foreach (var resource in model.ResourcesViewModel.Resources)
    {
        var filterSubstrings =
            filter
            .ToLower()
            .Split(separators)
            .ToList();

        var resourceSubstrings =
            resource.Name
            .ToLower()
            .Split(separators)
            .ToList();

        resourceSubstrings.ForEach(substring => {
            if (filterSubstrings.Contains(substring))
                filterSubstrings.RemoveAll(sub => sub == substring);
        });

        if (filterSubstrings.Count == 0)
            validResources.Add(resource);
    }

    model.ResourcesViewModel.Resources = validResources;
}

Should I take a different approach for this?
EDIT:
Ended up going with this until I figure out RegEx
static void ApplyNameFilter(ref ApplicationViewModel model, string filter)
{
    if (string.IsNullOrEmpty(filter)) return;

    char[] separators = {' ', ',', '.', '/', '\\', '|', '_', '-'};
    var filterSubstrings =
        filter
            .ToLower()
            .Split(separators)
            .ToList();

    var validResources = model.ResourcesViewModel.Resources
        .Where(resource => filterSubstrings.All(fs => resource.Name.ToLower().Contains(fs)))
        .ToList();

    model.ResourcesViewModel.Resources = validResources;
}

Comment: Yeah. Definitely look towards a `regex` solution - you'll definitely have more concise code.  There are other ways to skin this cat, but you'd have to be digging back to your comp sci 101 past and thinking about dynamic programming (at least that's what's coming to my mind, LOL). Single responsibility principle based approach also might make your life a lesser hell, here, as well.  In both the `regex` and non-regex approaches, try to leverage an immutability based approach. You're going to really appreciate that you didn't change things in-place, later on.
Comment: @Xeyth, To add on code4life excellent comment. I will also clarify, about specific point, if the method you are working with, only need the resource list, you do not want to let the method "know" all of your object and his hierarchy. some of the reasons for that is: in case the hierarchy will change, or you will want to use this logic in some other part of your application. you don't need to pass things that the method doesn't care, nor should you.
Comment: @Xeyth, If you only wants to "beautify" your method, you can work with `.Intersect` or `.All`, which is immutable and also, almost gives you the solution. e.g: `filterSubstrings.Intersect(resourceSubstrings).Count() == filterSubstrings.Count` OR `filterSubstrings.All(fs => resourceSubstrings.Contains(fs))`. Also you don't need to compute the `filterSubstring` in every iteration, they do not change. so put them out of your loop.
Comment: I haven't used too much RegEx though, I know it's damn powerful. Is there a way to generate proper regex patterns based on ones input?
Comment: @Xeyth: absolutely.  If you're using .NET 4.5 or higher, it gets even easier since you get to leverage string interpolation. For instance, `$"{your variable here}regex expression here"` - that's just a very raw, off-the-cuff example.  I strongly suggest googling regex, you are not going to need a very complex regex, for what you are trying to do.
Comment: @OrelEraki Yeah, I was planning to change that, this was a quickie method. Thanks though!
Comment: @code4life I'll definitely look into learning RegEx then, thanks.
Answer: You can use LINQ to make this more concise (and probably faster, as you are creating Lists and removing elements over every resource unnecessarily, though a non-LINQ solution could be even faster).
var validResources = model.ResourcesViewModel.Resources
                        .Where(resource => {
                            var resourceSubstrings = resource.Name.ToLower().Split(separators).ToHashSet();
                            return filterSubstrings.All(fs => resourceSubstrings.Contains(fs));
                        })
                        .ToList();

If you are willing to accept all the filter substrings being inside the Name regardless of the separators, then you can simplify to just be:
var validResources = model.ResourcesViewModel.Resources
                        .Where(resource => filterSubstrings.All(fs => resource.Name.ToLower().Contains(fs)))
                        .ToList();


Can you create duplicate character names in Planetside 2?

Question: I know I cant switch faction, so am I able to just create a new character with the same username? Or do I have to delete my original?
Answer: No.
Every single character of any user of any faction on any server has a unique name.
Although first-hand evidence is hard to come by in the form of a FAQ topic or something similar, there are enough leads:

It can be inferred from randomly found screenshots of character screens;

Or from visiting fora threads like this one.

This has probably played a major role in how in Planetside 2 "every username is already taken".
Advice: change the capitalization of one of the characters, since it will register as a unique username (unless taken, of course).
Comment: Am I able to delete a former account so I can use its name again?
Comment: @THECAKEISTALKING yes, you are, but you might have to wait a while before it gets registered (I've read it can take up to 24 hours), and the name *could* be claimed in the meantime (the risk partially depending on its uniqueness).


Why did Wubi install Gnome when I gave it the Xubuntu ISO?

Question: I downloaded the Xubuntu ISO file from the official site. But after installing it through the wubi installer I still got gnome interface instead of Xfce. What's gone wrong? What should I do? I double checked the file.
Answer: The Wubi installer ignored your ISO, and simply downloaded and installed regular Ubuntu instead.
Uninstall Wubi, and try again. Follow the instructions in this answer on how to get wubi.exe to use your pre-downloaded ISO:

How do I get the Wubi installer to use a pre-downloaded ISO?

Finally, to be safe, physically disconnect your Ethernet cable OR disable wireless (turn switch off, etc.) before you press the Install Button on Wubi.


Jmeter: How to get exact response of page

Question: I am new to Jmeter so i don't know if am asking a silly question. I am testing the performance of a web application but while testing i notice that there are multiple requests on a page. For e.g. when a user access a page www.xyz.com then there are static content plus there is another request to the server from the same page which is displaying data in a grid (www.xyz/getdata) plus there are js and css files. I want to know if there is way to retrieve all the request of a page.I have already tried the http request sampler with 'retrieve all embedded resources from html file' turned on but when i viewed all the request in view result tree it is displaying 34 requests where as Chrome is displaying 68 requests so i am not sure this is the correct way.
Answer: You give us not much information. But I guess, that your web page use AJAX call to retrieve JS, pictures and so on. Jmeter can't get these files because Jmeter don't execute your HTML file like a web browser.
It's possible that you find a plugin for Jmeter or you have to simulate your AJAX calls or you have to change your tool. Please look to XLT from Xceptance XLT or phantomjs and derivates or WPT.
Comment: your XLT link seems broken. Could you please provide relevant link? Thanks in advance
Comment: The company name is Xceptance, hence the link is https://www.xceptance.com/en/xlt/
Answer: First of all if you're trying to simulate a realistic load you need to "tell" JMeter to behave  more like a real browser. It includes:

HTTP Cookie Manager (in majority of cases it's a must) to deal with cookies and authentication
HTTP Cache Manager to represent browser cache
HTTP Header Manager with browser's (Chrome in your case) User-Agent string. Some sites vary output for different user agents.
You already know about embedded resources.

You can also try recording your test case via JMeter HTTP Test Script recorder, capture additional requests, place them in your test plan, better under Transaction Controllerto avoid getting metrics separately.
If JMeter will be unable to record extra requests, you'll need to capture them via any sniffer tool, the easiest is HttpFox Firefox Addon, the most powerful is Wireshark and manually construct missing requests.
In general if your missing resources are totally external it isn't a good idea to load-test them.
Answer: I just did it.
You must use Jmeter + Webdriver Sampler + PhantomJS Config. This way:
1) Download and install the WebDriver Set of plugins. Plugin installation is documented here.
2) Download and put the phantomjs executable somewhere on your disk.
3) Create a test plan just like shown on Webdriver Two minute tutorial, but replace FireFoxConfig with "bzm - PhantomJS Driver Config".
4) On PhantomJS Driver Config, open the PhantomJS tab and set the path to the phantomjs.exe on your disk.
5) On the WebDriver Sampler view, type in the following script:
<code>var selenium = JavaImporter(org.openqa.selenium)
var fileUtils = JavaImporter(org.apache.qpid.util)
var io = JavaImporter(java.io)
var supportUi = JavaImporter(org.openqa.selenium.support.ui)

WDS.sampleResult.sampleStart()

// set the browser window dimension to fit your needs
var dimension = new selenium.Dimension (4080, 9000);
WDS.browser.size = dimension;
WDS.browser.manage().window().size = dimension;

// put your webpage bellow
WDS.browser.get('http://MYPAGE.com')

// take a screenshot of the page, save it to disk
var screenshot = WDS.browser.getScreenshotAs(selenium.OutputType.FILE)
fileUtils.FileUtils.copy(screenshot, new io.File('C:\\PATH\\TO\\screenshot.png'))

WDS.sampleResult.sampleEnd()
</code>
Answer: You can record the session with the Jmeter itself, and you get all the retrieve a webpage is doing:
Apache JMeter HTTP(S) Test Script Recorder


Spring Web MVC 3.1.1 argument resolver called before interceptor

Question: I'm configuring my Spring MVC 3.1.1 app as summarized below. Logging shows that 'MyArgumentResolver.resolveArgument' is invoked before 'MyInterceptor.preHandle'. When using both in an old fashion configuration (with exclicitly defined AnnotationMethodHandlerAdapter bean etc.) they are invoked vice versa. I read that <mvc:annotation-driven> is somehow critical, since its configuration does not complement other settings of mvc: namespace. Am I facing the same problem?
<code><mvc:annotation-driven>
  <mvc:message-converters>
   ...
  </mvc:message-converters>
  <mvc:argument-resolvers>
    <bean class="[...].MyArgumentResolver"/>
  </mvc:argument-resolvers>
</mvc:annotation-driven>
<mvc:interceptors>
  <mvc:interceptor>
    <mvc:mapping path="/home/**" />
    <bean class="[...].MyInterceptor" />
  </mvc:interceptor>
</mvc:interceptors>
</code>
Many Thanks!
Answer: Spring 3.1 with <mvc:annotation-driven> uses a different set of classes for handling requests - e.g., AnnotationMethodHandlerAdapter is replaced with RequestMappingHandlerAdapter. You can read more about that here: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-31-vs-30
In order to work properly with those classes, they've added a new HandlerMethodArgumentResolver that supersedes the old WebArgumentResolver interface. However, I believe that Spring will automatically try to "upgrade" old WebArgumentResolvers by wrapping them in an AbstractWebArgumentResolverHandlerAdapter, which is the behavior that I was seeing during the process of upgrading. The JavaDoc for AbstractWebArgumentResolverHandlerAdapter says:

Note: This class is provided for backwards compatibility. However it is recommended to re-write a WebArgumentResolver as HandlerMethodArgumentResolver. Since supportsParameter(org.springframework.core.MethodParameter) can only be implemented by actually resolving the value and then checking the result is not WebArgumentResolver#UNRESOLVED ...

After stepping through the code, I think what may be happening in your case is that it the new classes call the supportsParameter function before executing preHandle in the interceptors, but the implementation of AbstractWebArgumentResolverHandlerAdapter actually calls the resolveArgument method and checks for 'UNRESOLVED' as the return type in order to determine if the argument resolver supports the given argument, which would give the appearance of them being called out of order.
I suspect if you rewrite your argument resolver to implement the new HandlerMethodArgumentResolver interface, it will solve your problem.
Comment: Many thank roblg. Changing the interface to [HandlerMethodArgumentResolver](http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/method/support/HandlerMethodArgumentResolver.html) solved the problem. My [WebArgumentResolver](http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/bind/support/WebArgumentResolver.html) expects the interceptor to set a request attribute and throws an exception if the attr. is missing. As you said, resolveArgument was called before the interceptor's preHandle to check if the resolver is applicable.


Proving that two measures are equal

Question: Let $\lambda$ be the lebesgue measure on  $\mathbb{R}$, Let $\mathcal{M}(\mathbb{R}^n)$ be the system of lebesgue measurable sets of $\mathbb{R}^n$ and $t>0$.
Show that $\mu: \mathcal{M}(\mathbb{R}^n)\to [0,\infty], \mu(A):=t^{-n}\lambda(tA)$ defines a measure and that $\lambda(A)=\mu(A)$ for all $A\in \mathcal{M}(\mathbb{R}^n)$
My work:
We have:$$\mu(\emptyset)=t^{-n}\cdot \lambda(t\cdot \emptyset)=t^{-n}\cdot \lambda(\emptyset)=t^{-n}\cdot 0=0 \quad \checkmark$$ and $$\mu\left(\bigcup\limits_{n=1}^{\infty}A_n\right)=t^{-n}\lambda \left(\bigcup\limits_{n=1}^{\infty}tA_n\right)\\ =t^{-n}\sum \limits_{n=1}^{\infty}\lambda(tA_n)=t^{-n}\sum \limits_{n=1}^{\infty}t^n\cdot t^{-n}\lambda(tA_n) =t^{-n}\sum \limits_{n=1}^{\infty}t^n\mu(A_n)$$  Hence:$$\mu\left(\bigcup\limits_{n=1}^{\infty}A_n\right)=\sum \limits_{n=1}^{\infty}\mu(A_n) \quad \checkmark  $$
All in all, $\mu$ is a measure. But how can I show the second part, namely that $\lambda(A)=\mu(A)$ for all $A\in \mathcal{M}(\mathbb{R}^n)$?
Comment: Well, the identity that you are dealing with must be reminiscent of dilating a rectangle by $t,$ the area gets $t^n$ because of dimension. Monotone class theorem or $\pi-\lambda$ systems let you show that it suffices to check in a generating set of a $\sigma$ algebra.
Comment: Are you familiar with Monotone class theorem?
Comment: Unfortunately, no. I have heard of monotone classes but never researched any further.
Comment: Well, I wouldn't mind if you write down how you'd prove it. I could do some research to understand your answer.
Comment: It may help to say what textbook you are studying from. Most measure theory textbooks will contain a theorem (derived using Monotone class theorem, Dykin $\pi-\lambda$ theorem, or otherwise) that gives conditions for two measures to by identical. All the theorems tell you (as a corollary) that to check that a given measure is equal to the Lebesgue measure, it suffices to check equality on rectangles.
Answer: The Lebesgue measure is defined by the restriction of the lebesgue outer measure to lebesgue measurable sets. The outer measure is defined by
$$ \lambda^*(A) = \inf \{ \sum_{j} \text{Vol} (I_j)  \; \vert  \; A \subset \bigcup_{j \in \mathbb N} I_j \}$$
where the $I_j$'s are compact rectangles which cover $A$.
Let $A$ be a lebesgue measurable set and $t > 0$. We start by showing that $tA$ is lebesgue measurable. To do this we establish the fact that
$$ \lambda^*(tA) = t^n \lambda^*(A) $$
This follows by definition of the outer measure
\begin{align*}
\lambda^*(tA) &= \inf \{ \sum_{j} \text{Vol} (I_j)  \; \vert  \; tA \subset \bigcup_{j \in \mathbb N} I_j \} \\
&= \inf \{ \sum_{j} \text{Vol} (I_j)  \; \vert  \; A \subset \bigcup_{j \in \mathbb N} \frac{1}{t}I_j \} \\
&= \inf \{ t^n \sum_{j} t^{-n}\text{Vol} (I_j)  \; \vert  \; A \subset \bigcup_{j \in \mathbb N} \frac{1}{t}I_j \} \\
&= \inf \{ t^n \sum_{j}\text{Vol} (\frac 1 tI_j)  \; \vert  \; A \subset \bigcup_{j \in \mathbb N} \frac{1}{t}I_j \} \\
&= t^n \inf \{\sum_{j}\text{Vol} (\frac 1 tI_j)  \; \vert  \; A \subset \bigcup_{j \in \mathbb N} \frac{1}{t}I_j \} \\
&= t^n \inf \{\sum_{j}\text{Vol} (\tilde{I}_j)  \; \vert  \; A \subset \bigcup_{j \in \mathbb N} \tilde{I}_j\} \\
&= t^n \lambda^*(A).
\end{align*}
We now show that $tA$ is lebesgue measurable if $A$ is measurable. By definition we must show that for any $E \subset \mathbb R^n$
$$ \lambda^*(E) = \lambda^*(E \cap tA) + \lambda^*(E \cap (tA)^c)$$
Since $(tA)^c = tA^c$ we have
\begin{align*}
\lambda^*(E \cap tA) + \lambda^*(E \cap (tA)^c) &= \lambda^*(E \cap tA) + \lambda^*(E \cap tA^c) \\
&= \lambda^*(t \frac 1 t E \cap tA) + \lambda^*(t \frac 1 t E \cap tA^c) \\
&= \lambda^*\big( t  (\frac 1 t E \cap A) \big) + \lambda^*\big( t(\frac 1 t E \cap A^c)\big) \\
&= t^n \lambda^*( \frac 1 t E \cap A) + t^n \lambda^*(\frac 1 t E \cap A^c)\\
&= t^n \big( \lambda^*( \frac 1 t E \cap A) + \lambda^*(\frac 1 t E \cap A^c)\big) \\
&= t^n \lambda^*(\frac 1 t E) = \lambda^*(E).
 \end{align*}
Therefore $tA$ is Lebesgue measurable. Since $tA$ and $A$ are both Lebesgue measurable we have by definition that
$$ \lambda^*(tA) = \lambda(tA) \quad \text{and} \quad \lambda^*(A) = \lambda(A)$$
Hence $ \lambda(tA) = t^n \lambda(A)$ which is equivalent to  $\lambda(A) = \mu(A)$.
Comment: @Analysis see my edit.
Comment: How'd you know that $tA$ is lebesgue mesurable? Thank you very much, very clean!
Comment: Brilliant explanation.

Proving that two measures are equal


Assigning a nullptr to a member-pointer

Question: Can anyone tell me why the internal representation of a nullptr assigned to a data member pointer of type Class::* is -1 for MSVC, clang and g++? For a 64-bit system (size_t)1 << 63 would be best, because if you use a nullptr member pointer that way you will touch kernel memory for sure and have a crash so this would be a nice debugging aid.
Is there a deeper reason behind -1?
Sample:
struct X
{
    int x, y;
};

using member_ptr = int X::*;

member_ptr f()
{
    return nullptr;
}

... results in the following binary with g++:
movq    $-1, %rax
ret

Comment: @Locke: I'm not taling about C but C++. C hasn't any member-pointers.
Comment: @GoswinvonBrederlow -1 and ~0 are the same number
Comment: The C standard library allows a null pointer to be defined by a system for legacy purposes. I am very surprised you managed to find a case where that was actually the case. What type of system are you running on?
Comment: @drescherjm: I'm talking about _member_ pointers, these are internally just offsets, not absolute pointers.
Comment: @Mgetz OK but `size_t(1) << 63` would also be an invalid pointer, and accessing it would lead to a nice crash, as the question states. By contrast, `-1` is an offset that's almost guaranteed not to cause a crash.
Comment: @BonitaMontero it is, however I'm not a compiler implementer. My assumption is that this is carry over from prior implementation. E.g. it's consistent on [multiple architectures](https://godbolt.org/z/4Y84fvscP) whereas the value you suggest would need to be specified for _every single architecture_.
Comment: @Mgetz: Of course it would have to be defined for an implementation since the standard doesn't make any assumptions on that.
Comment: It doesn't matter that's it UB because it's for debugging purposes only.
Comment: There's no speed difference in loading 0, -1 or (size_t)1 << 63.
Comment: @BonitaMontero, KonradRudolph: On x86_64 loading a 0 is `31 ff                   xor    %edi,%edi`, which is the fastest. Loading a `~(0LLU)` is `48 c7 c7 ff ff ff ff    mov    $0xffffffffffffffff,%rdi`. Loading a `1LLU << 63` is `48 bf 00 00 00 00 00 00 00 80    movabs $0x8000000000000000,%rdi`. That's an extra 3 byte in the opcode which has some performance cost. On Mips64 the last needs a whole extra opcode: https://godbolt.org/z/3nehjcoM6
Comment: It should not be -1 for msvc. It should be 0 regardless of 64 or 32 bit.
Comment: Interesting. Maybe something we can look at on godbolt.org with a small example code. I don't look at the assembly very often these days. In the late 1990s I had to write asm for some medical imaging code to improve performance but these days I mainly use libraries.
Comment: Why -1? Because it's an invalid pointer for a member offset but 0 is valid for the implementation. In your example the value for `&X::x` is 0.
Comment: Of course it is an invalid pointer, but the value I suggested is also invalid and would help debugging.
Comment: @KonradRudolph undefined behavior is undefined. That's the only response I have.
Comment: I don't think it is `-1`, that would limit things. It should be `~0` leaving `(1 << 64) - 1` valid offsets to be used as member pointers. Now fighting about `1 << 64` or `1 << 63` seems silly. But consider a 16 bit system and `struct A { char buf[32768]; int used;}`. Having `1 << 16` or `1 << 15` would make a real difference. Also most CPUs can represent an immediate of `~0` directly in opcodes but `1 << 63` would need to load a constant, possibly via GOT and indirections.
Comment: @BonitaMontero yes but if I'm writing common tools or working with devs having conventions are a good thing. So having the convention always be -1 simplifies what has to be documented for a new architecture. But again... ask the GCC/MSVC devs.
Comment: @GoswinvonBrederlow: Didn't you notice my suggestion of (size_t)1 << 63 as a debugging aid ?
Comment: @user253751 `~(0LLU)`
Comment: @BonitaMontero I saw. It would pretty reliably crash your code when you use it. But it's UB and you aren't supposed to use it at all. So compilers do not optimize for that case. They optimize for well formed code. And `~(0LLU)` is faster than `1LLU << 63` on many CPUs.
Comment: @GoswinvonBrederlow The whole point of the question is that *accidental use* of a nullptr member should ideally cause a crash, instead of silently doing something incorrect. For other cases of UB, compiler vendors are often careful to implement it such that accidental misuse triggers loud error messages (especially in debug mode). OP's question is: why not also in this case, since it appears straightforward?
Comment: @KonradRudolph No, the question was why `-1` (or more likey `~(0LLU)`) was used when other values would be better for detecting ill-formed code. And the answer is speed and it being the least likely proper value.
Comment: @GoswinvonBrederlow The first sentence of your comment paraphrases my own comment while omitting crucial details, nothing more. The second sentence of your comment is completely wrong (*both* assertions in that sentence are incorrect).
Comment: @GoswinvonBrederlow: As a member-pointer isn't casteable to anything the compiler can have arbitrary values for nullptr. So the compiler could have different values for optimized and non-optimized code.
Comment: @GoswinvonBrederlow Ah, I was wrong. Thanks for your last comment, it is illuminating. Mind converting it into an answer? I think this is probably (at least part of) the actual reason.
Answer: There are three reasons why ~(0LLU) is preferable:

Member pointers can be anything from 0 to the size of the struct or class. Using ~(0LLU) has the least risk of colliding with an actually valid member pointer. You can't really have a struct the size of size_t:
<source>:2:21: error: size '9223372036854775808' of array 'x' exceeds maximum object size '9223372036854775807'
    2 |     long long x[1LLU<<63];

<source>:2:15: error: size of array 'x' exceeds maximum object size '9223372036854775807'
    2 |     long long x[1LLU<<62];

Note that limit is (1LLU<<63) - 1. So that kind of negates this argument. Might be different on a 16bit system.

On x86_64 loading a 0, ~(1LLU) and 1LLU << 63 becomes
31 ff                            xor    %edi,%edi
48 c7 c7 ff ff ff ff             mov    $0xffffffffffffffff,%rdi
48 bf 00 00 00 00 00 00 00 80    movabs $0x8000000000000000,%rdi

Loading 0 is the fastest. Loading 1LLU << 63 is the longest opcode and that alone has performance costs. So using ~(0LLU) as the member pointer nullptr has a slight performance advantage.
It's similar on many architectures. On Mips64 the last needs a whole extra opcode: https://godbolt.org/z/3nehjcoM6

It's customary from the old C days that a function returns -1 or ~(0LLU) as error code except for pointers where 0 is used. Member pointers can't use 0.

Personally I think the compiler developers where just following old habits (reason 3). That it's also faster is just luck (or those old C geezers knew what they where doing choosing their error codes :).
As for why the compiler can't use ~(0LLU) when optimizing and 1LLU << 63 when debugging: You can compile some translation units as optimized code and some a debug code. They would then follow incompatible ABIs and couldn't be linked together.
Comment: @BonitaMontero Nope. You can include the same header in to TUs and declare member pointers, pass them around, compare them to nullptr. They have to be compatible.
Comment: You can't cast a member-pointer to anything and the value could be different in non-optimized and optimized code.

Assigning a nullptr to a member-pointer


If $x_n \to x$ and $y_n \to y$ weakly. Then $\langle x, y\rangle = \lim_n \langle x_n, y_n\rangle$

Question: I'm trying to show below property, i.e.,

Let $(H, \langle \cdot, \cdot\rangle)$ be a real Hilbert space. Let $x,y, x_n, y_n\in H$ such that $x_n \xrightarrow{n \to \infty} x$ and $y_n \xrightarrow{n \to \infty} y$ in the weak topology $\sigma(H, H^*)$. Then $\langle x, y\rangle = \lim_n \langle x_n, y_n\rangle$.

Could you have a check on my below attempt?
Is there another way that does not use below lemma?

Thank you so much for your help!

Let $\sigma (H, H^*) \otimes \sigma (H, H^*)$ be the product topology of $\sigma (H, H^*)$ and itself.

Lemma $\sigma (H, H^*) \otimes \sigma (H, H^*)= \sigma (H^2, (H^2)^*)$.

By above Lemma, $(x_n, y_n) \xrightarrow{n \to \infty} (x, y)$ in $\sigma (H^2, (H^2)^*)$. Clearly, the map $(u, v) \mapsto \langle u, v \rangle$ belongs to $(H^2)^*$. The claim then follows.
Comment: Wait @Analyst $(u,v)\mapsto \langle u,v\rangle $ is not even a linear map. It is a Bilinear map .
Comment: @esoteric-elliptic $H^*$ is the continuous dual of $H$, and $\sigma(H, H^*)$ is the coarsest topology on $H$ such that every $f \in H^*$ is continuous w.r.t. $\sigma(H, H^*)$. Please see [here](https://en.wikipedia.org/wiki/Weak_topology#Weak_topology_induced_by_the_continuous_dual_space).
Comment: Sorry - could you explain what $\sigma(H,H^\ast)$ is precisely?
Comment: I don't think this is true. However , I might be wrong. Maybe you can use the Riemann Lebesgue Lemma to come up with some counter examples in $L^{2}[0,2\pi]$ . What is true is that if $x_{n}\xrightarrow{w} x$ and $y_{n}\to y$ then $\langle x_{n},y_{n}\rangle \to \langle x,y\rangle$ by just noting that $||x_{n}||$ is bounded by UBP and then using Cauchy-Schwartz
Comment: @Mr.GandalfSauron Even the statement is not true, I would love to see where is the logical mistake in my argument...
Comment: @Analyst I see. Let me think .
Answer: Any orthonormal sequence $e_n$ tends to $0$ weakly, due to the Bessel inequality. But $\langle e_n,e_n\rangle =1.$
Comment: Ah . lol . I was overthinking it. Maybe in the back of my mind, I was thinking of $x_{n}$ and $y_{n}$ to be distinct sequences. But your example is short and sweet.
Comment: @Mr.GandalfSauron Thanks. Your example is based on the same idea. I can  take, as you did, $f_n=e^{in}e_n,$ to spoil the convergence of $\langle e_n,f_n\rangle$ whatsoever, as the sequence $e^{in}$ is dense in the unit circle.
Comment: Yeah exactly. In Hilbert space theory, sometimes the relation that $\langle v,e_{n}\rangle\to 0$ is itself called Riemann Lebesgue Lemma. Using Bessel's Inequality, the proof is easier however than the standard real analysis proof.
Answer: The statement is not true in general. Consider $L^{2}[0,2\pi]$ . Take $x_{n}=\sin(nx)$ and $y_{n}=(-1)^{n}\sin(nx)$
Then for any $v\in L^{2}[0,1]$ , $\langle v,x_{n}\rangle$ and $\langle v,y_{n}\rangle $ tend to $0$ by Riemann-Lebesgue Lemma. $\langle f,g\rangle =\int_{0}^{2\pi}f(x)g(x)\,\,d\lambda(x)$
But   $\langle x_{n},y_{n}\rangle $ is positive for $n$ odd and negative for $n$ even . Hence is not convergent
What is true is that if one of the sequences say $x_{n}\to x$ , i.e. $||x_{n}-x||\to 0$ . Then you have $\langle x_{n},y_{n}\rangle -\langle x,y\rangle = \langle x_{n}-x,y_{n}\rangle +\langle x,y_{n}\rangle-\langle x,y\rangle$ .
Now as $y_{n}$ converges weakly, it is norm bounded by Uniform Boundedness Principle. Thus $||y_{n}||\leq C$
So by Cauchy-Schwartz $|\langle x_{n}-x,y_{n}\rangle|\leq ||x_{n}-x||\cdot||y_{n}||\leq C||x_{n}-x||\to 0$ and also $\langle x,y_{n}\rangle-\langle x,y\rangle \to 0$ .
Thus you have $\langle x_{n},y_{n}\rangle \to \langle x,y\rangle$


What references to Sombra exist in the game now?

Question: Sombra is being teased quite heavily as the next hero for Overwatch, and I know that there are some easter eggs hidden in some maps and voice lines.
For example, Reaper will sometimes say "Where is Sombra when you need her?" and on a few maps, there are pictures and news clippings of her.
What are the currently known references to her existence within the Overwatch universe?
Comment: I think this question could be improved if you included some evidence of why you think this is the case. Otherwise you risk the question being closed due to speculation. You might find some evidence on the Overwatch Gamepedia. http://overwatch.gamepedia.com/Sombra
Comment: Some more thoughts too, https://www.youtube.com/watch?v=TtZKsae55EU&feature=youtu.bea
Answer:
There is an interaction in which Reaper says "Where is Sombra when you need her?"
There is a picture of a newspaper in Dorado. The Spanish phrase translates to "Who is Sombra (or Shadow)?"
A picture of some classified files, including Soldier: 76, Jack Morrison (who's now Soldier: 76), and Sombra.
On the third point in Dorado, there are security terminals that say "UNAUTHORIZED ACCESS. PROTOCOL SOMBRA."

These are the references in-game. A lot of more information can be found at this reddit post which I used as reference for this answer.
Comment: That should be "its Portuguese counterpart" I am fairly certain. That is from the Brazilian Overwatch account on Twitter. Also, it looks like Portuguese to me.
Comment: Don't forget [this](https://pbs.twimg.com/media/CmsjJH1UMAEcsVT.jpg:large) and its [Spanish counterpart](https://pbs.twimg.com/media/Cmsra3dWIAANceq.jpg), which adds the name A. Amari. While not specifically mentioning Sombra, it is widely believed that she is, in fact, this support sniper.
Comment: Oh yeah, I didn't forget, it's definitely on the link I put there. However OP's question was "what references to sombra exist in game" so I only mentioned the ones in the game, not outside of it.
Comment: Yeah, I was a little slow on editing my comment, but it's never really mentioned that the sniper is Sombra herself, and the "in game" point is valid.
Comment: It's definitely portuguese, but it's the same thing on the spanish one (A.Amari also shows there). Blizzard probably reviewed and editted it out on the US version afraid of giving too much information, but didn't update the translations.
Answer: If Pharah gets a direct kill with her missile Launcher and S.76 is nearby, he may say "You must've got that from your mom." While it's not a direct reference to Sombra, there is lots of speculation that Sombra is Pharah's mother, and it's confirmed that Pharah's mom fought alongside Soldier 76 in the defense of Overwatch HQ. She was presumed dead, but then again, so was Reaper and S.76.
Comment: As it turns out, Pharah's mom is a different character, [Ana](https://playoverwatch.com/en-us/heroes/ana/), who was announced earlier today.


SOA vulnerabilities

Question: I am a post graduate student. I have to do a masters thesis on SOA vulnerabilities(SOA security). In the sense, finding vulnerabilities in web services or finding solutions to the existing vulnerabilities. In that direction i have been searching for vulnerabilities in SOA. Once the vulnerability is find i have to stimulate it and show to my guide. Some attacks i found in OWASP in the corresponding areas are DOS attacks, Injection attacks(SQL injection,XPath injection). I could not able to take a proper decision at the moment so as what to do next.
 Can anyone please tell me how could i proceed to successfully reach the destination?
Comment: post graduate != masters; it would be worth stating your country or retranslating
Comment: @Will : last time I checked, a Masters IS post-graduate. It's something you pursue after graduating.
Comment: I stand corrected, it was my lousy translating
Answer: To help you out a bit on your research i'm stating this website:
http://www.packetstormsecurity.com
This website has alot of information regarding to exploits / hacks / fixxes and alot of info about cross site server scripting / dos-attacks / sql-injection etc etc etc.
If you really need more info or nice articles about various attacks and fixxes you should seriously consider checking out that page.
Comment: This site is great. It provides a lot of security-related information and the descriptions of vulnerabilities are very well written. Definitely your number one site regarding web-security.
Comment: deffo, best site regarding that kind of shizzle ;)
Comment: packet storm is for script kiddies of the 1990's.  That site is so old and all it contains is outdated papers and forgotten exploit code.
Comment: Bullox, there is alot of updated material and everyday new exploits / fixxes etc gets submitted.
Answer: Generally, you should discuss this in depth with your tutor rather than ask the internet in general.
Comment: You could have commented on her post instead of faking an answer :P
Comment: @Younes it was genuine advice.  I've said it before too: http://stackoverflow.com/questions/1245885/project-ideas-on-algorithms-data-structures-and-parallel-programming/1245918#1245918
Comment: The question isn't about SOA nor how it works nor anything technical, its "not able to take a proper decision at the moment so as what to do next" and that's a question about the academic task at hand.
Comment: Will,   If you are having trouble finding direction then it follows that you should ask for help.  Stack Overflow is about helping programmers, and this question is helping a programmer do research.
Comment: If, as I interpret, the question is how to graduate, then I think my advice to discuss it with the tutor is very sound.
Answer: The field of computer security is massive and there is always something to explore.   This is one of the reasons why I love hacking.
Currently I am working on a masterpiece exploit that will be the basis for my Blackhat/Defcon talk in august.   I think that writing exploit code is vital for understanding the exploitation process.  Even if you are the most Arian of white hats,  you must write exploit or you will always be behind the attacks in terms of skill.  I love going to hacker cons to get now ideas for my security research.  It is also helpful to see new attacks.
Some things that you have no mentioned are Memory manipulation attacks such as buffer overflows.   Modern buffer overflows are more difficult to exploit than Aleph One's smashing the stack for fun and profit.    You should look into modern bypasses to ASLR such as heap spraying or heap feng shui.   Attacks like jmp2reg (jmp2esp jump2ebx ect...) are also interesting for bypasses for ASLR.
Attacking ActiveX components is fun. I used H.D. Moore's AxMan with great success.  Here is the remote code execution exploit I found using AxMan: http://www.milw0rm.com/exploits/7910 .  Here are more exploits that I have written: http://www.milw0rm.com/author/677  .  The best fuzzer is by far PeachFuzz, and writing a some pit files for it can be very fruitful research.
Buffer overflows and sql injection are the most talked about,  but there are a couple hundred categories for vulnerabilities and they are identified by CWE numbers. Its worth exploring,  I think it will surprised you what NIST thinks a vulnerability is.

SOA vulnerabilities


Prove that a sequence diverges

Question: Let $b > 1$. Prove that the sequence $\frac{b^n}{n}$ diverges to $\infty$
I know that I need to show that $\dfrac{b^n}{n} \geq M $, possibly by solving for $n$, but I am not sure how.
If I multiply  both sides by $n$, you get  $b^n \geq Mn$, but I don't know if that is helpful.
Comment: try taking logarithms with base $b$ to $b^{n} \geq Mn$. How does the growth of $n$ compare to that of $\log_{b}n$?
Answer: Since $b>1$, we can write $b=1+a$, where $a>0$. From binomial theorem, we then have
$$b^n = (1+a)^n = \sum_{k=0}^n \dbinom{n}k a^k > \dbinom{n}2 a^2$$
Hence, we get that
$$\dfrac{b^n}n > \dfrac{(n-1)a^2}2$$
I trust you can take it from here.
Answer: You could use L'Hospital's rule:
$$
\lim_{n\rightarrow\infty}\frac{b^n}{n}=\lim_{n\rightarrow\infty}\frac{b^n\log{b}}{1}=\infty
$$

Prove that a sequence diverges