How to programatically create and get Web Apps under App Services in Windows Azure?

Question: I would like to programatically get and create Web Apps under App Services in Windows Azure.
How to create it by using its REST API?
Answer: As far as I know, if you want to use REST API to get and create Web App, you need generate a access token. To generate access token we need talentID, clientId, clientSecret. We need to assign application to role, after that then we can use token in common. More information about how to assign application to role please refer to the article .This blog also has more detail steps to get AceessToken.
Notice: I use C# Codes to show a example.
Then you could send request as below:
Get webapp:
Url: https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/Microsoft.Web/sites?api-version={api-version}

Method: PUT

Parameter:
subscriptionId  The identifier of your subscription where the snapshot is being created.
resourceGroup   The name of the resource group that will contain the snapshot.
api-version The version of the API to use.

The codes is as below:
  // Display the file contents to the console. Variable text is a string.
    string tenantId = "xxxxxxxxxxxxxxxxxxxxx";
    string clientId = "xxxxxxxxxxxxxxxxxxxxx";
    string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    string subscriptionid = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    string resourcegroup = "BrandoSecondTest";

    string version = "2015-08-01";
    string authContextURL = "https://login.windows.net/" + tenantId;
    var authenticationContext = new AuthenticationContext(authContextURL);
    var credential = new ClientCredential(clientId, clientSecret);
    var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
    if (result == null)
    {
        throw new InvalidOperationException("Failed to obtain the JWT token");
    }
    string token = result.AccessToken;
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites?api-version={2}", subscriptionid, resourcegroup, version));
    request.Method = "GET";
    request.Headers["Authorization"] = "Bearer " + token;

    request.ContentType = "application/json";
    var httpResponse = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        Console.WriteLine(streamReader.ReadToEnd());
    }

    Console.ReadLine();

Create WebApp:
You should send your webapp template in the request content.
Then you could send request as below:
Url: https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/Microsoft.Web/sites/{appname}?api-version={api-version}

Method: PUT

Parameter:
subscriptionId  The identifier of your subscription where the snapshot is being created.
resourceGroup   The name of the resource group that will contain the snapshot.
appname:  The name of your webapplicaiton you want to create
api-version The version of the API to use.

Request content:
{
  "location": "East Asia",
  "properties": {
    "name": "YourWebpplcaitonName",
    "serverFarmId": "Yourserviceplan"
  }
}

Here is a C# example, hope it gives some tips:
string body = File.ReadAllText(@"D:\json.txt");
            // Display the file contents to the console. Variable text is a string.
            string tenantId = "xxxxxxxxxxxxxxxxxxxxxxxxx";
            string clientId = "xxxxxxxxxxxxxxxxxxxxxxx";
            string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxx";
            string subscriptionid = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            string resourcegroup = "BrandoSecondTest";
            string appname = "Brandosss";

            string version = "2015-08-01";
            string authContextURL = "https://login.windows.net/" + tenantId;
            var authenticationContext = new AuthenticationContext(authContextURL);
            var credential = new ClientCredential(clientId, clientSecret);
            var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }
            string token = result.AccessToken;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Web/sites/{2}?api-version={3}", subscriptionid, resourcegroup,appname, version));
            request.Method = "PUT";
            request.Headers["Authorization"] = "Bearer " + token;
            request.ContentLength = body.Length;
            request.ContentType = "application/json";
            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(body);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            // Get the response
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                Console.WriteLine(streamReader.ReadToEnd());
            }

Comment: Hi Brando. Thank you so much for your answer. I really appreciate. I wanted to know if there is any way wherein we can authenticate API request with Certificate(classic way) and not with Token. By that way we can ignore creating service principal, I hope. Do you have any idea?
Comment: I don't suggest you use classic certificate. According to this article:https://feedback.azure.com/forums/223579-azure-portal/suggestions/7473259-management-certificates,The new management stack doesn't make use of management certificates.


Protect 120vac circuit from accidental 240vac connection

Question: Does anyone have experience with setting up protection for circuits that are 120vac nominal, but could be accidentally exposed to 240vac if the wrong plug is used?
In this case the application is for a camper that recently experienced this exact problem when an outlet on a new building was mistakenly powered with 240vac, which fried the fuses on several 120vac camper appliances (fortunately, mostly an easy fix this time). For reference, the camper is rated at 120vac, 30 amps max draw.
I found several over-voltage protection modules that sound like they could work, but have 1 to 2 seconds of delay after powering-on before they would trigger.
Ex:
Module 1,
Module 2
It seems like that much delay would be too much, but I don't really know.
Please let me know if you have any thoughts on this issue, or if there are better solutions.
There are faster options per the Wikipedia surge protection page: crowbar circuits, transient voltage suppression diodes and a few others, but they don't seem to be commonly available as a commercial product. I can solder something up if needed, but off-the-shelf seems safer.
Comment: @whatsisname, I believe the issue was that the outlet was mis-wired, so the outlet that was plugged into had the wrong voltage for the requirement for the specific plug shape.
Comment: XY problem. What you need (IMHO) is a voltmeter connected to a TT-30P plug, that you use BEFORE you connect your trailer to (code-violating) improperly wired outlets. I found one in a few seconds of searching that has a plug, a receptacle, and bluetooth to display the voltage on a phone, tablet, or computer. You'd plug that in, check the voltage, and ONLY after it showed good plug in your trailer to the receptacle on it. Or you probe the receptacle with a DMM before plugging in. Or use a listed/fused plug adapter to plug in something like a kill-a-watt or other NEMA 5-15P voltmeter
Comment: ...and as per usual - you're a few decades out of date on voltages. You are protecting 120VAC from 240 VAC any time in the last 50 years in the USA, at least. Assuming your trailer power panel has a main breaker (fuse?) you could also install a hardwired voltmeter on the line into the trailer before the main breaker or fuse, and turn off the breaker (or pull the fuse) before plugging in the cord, then check the voltmeter before turning the breaker on or installing the fuse.
Comment: Don't codes require different shaped outlets for each voltage, so you can't accidently mismatch voltages?
Comment: Thank you for the feedback and suggestions (and correction on the voltages haha). It's not my camper, but a relative's who is not particularly tech-savvy, so I was aiming for the fully automated protection route. I agree that a manual voltage check is a cheap and simple solution if they just have to plug something in and look at a screen.
Answer: There's a gizmo made precisely for this job
What you want is a Southwire 34930 (plug-in) or 35530 (hardwired).  These devices are made for the express purpose of protecting RVs/travel trailers from improper receptacle wiring, and have a built-in overvoltage cutout function as part of their protection features.
Comment: @Mandias -- the 30A version is what you want since your trailer is a 30A trailer.  I wouldn't worry much about joule ratings (you might want a higher joule rating if you are in say Florida a bunch due to the prevalence of big lightning-induced surges on your grid, but that's about it)
Comment: Thank you for the suggestion. Do you happen to have an opinion on the different joules of surge protection offered? Also, I was under the impression that when choosing power-handling electronics it's a good idea to over-spec to give some "wiggle room", but these models are rated the same as the max current (30A). Does that matter in this case?
Answer: If you wanted to fully automate "protection", rather than depending on manually checking voltage before plugging in, I guess a 30A or greater relay that's "normally off" and is only turned "on" when some supervisory circuit is happy with the power quality on the input would work. The 120V side would never see 240V input, even for a second, in the situation you are practically trying to prevent (plugging into a miswired outlet.) In a more far-fetched situation (voltage suddenly changes to 240 from 120, which would be unusual in the extreme) how much exposure there would be would depend on how fast it could be switched off. But for plugging into bad power, it would never switch on at all.
The only place I can think to get a supervisory relay and power quality circuit "off the shelf" would likely be prohibitively expensive - a UPS with a 120V 30A in and out connection. But depending on how much it's worth to you, that might be the way to do it. Good ones switch off for voltage too high, voltage too low, and may have capacity to regulate "voltage somewhat too high or low" without going over to batteries. And they do provide some level of battery backup when power input is not good.


How to filter a list of dates by year interactively in SwiftUI

Question: I have a NSManagedObject Subclass coming from a core data entity MyEntity with:
@NSManaged public var name: String
@NSManaged public var date: Date

and a list. I prepared a ScrollView that holds Buttons (?) that could be used to filter the list
func groupYears(fetchedResults: FetchedResults<MyEntity>) -> [Int] {
    var result = [Int]()
    for fetchedResult in fetchedResults {
        let component = Calendar.current.dateComponents([.year], from: fetchedResult.date)
        if !result.contains(component.year!) {
            result.append(component.year!)
        }
    }
    return result
}

@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \MyEntity.date, ascending: true)]) var fetchedResults: FetchedResults<MyEntity>

VStack {
    ScrollView(.horizontal, showsIndicators: false) {
        HStack(spacing: 15) {
            Button(action: {}) { Text("all") }
            ForEach(groupYears(fetchedResults: fetchedResults), id: \.self) { year in
                Button(action: {}) { Text(String(year)) }
            }
        }
    }
    List(fetchedResults, id: \.self) { result in
        VStack(alignment: .leading) {
            Text(result.name)
            Text(dateFormatter.string(from: result.date))
        }
    }
}

I want to click a button and the list should dynamically filter the related year.
How can I filter the list dynamically?
Comment: Does this answer your question? [How to properly group a list fetched from CoreData by date?](https://stackoverflow.com/questions/59180698/how-to-properly-group-a-list-fetched-from-coredata-by-date)
Comment: @pawello2222 Maybe you answered before my edit. Thank you anyhow. I want to now how can I filter the list dynamically?
Answer: You can add a property to store your selected year:
@State var selectedYear: Int?

Button(action: {
    self.selectedYear = nil
}) {
    Text("all")
}
ForEach(groupYears(fetchedResults: fetchedResults), id: \.self) { year in
    Button(action: {
        self.selectedYear = year
    }) {
        Text(String(year))
    }
}

And then filter the list by this selected year:
ForEach(fetchedResults.filter({ isDateInSelectedYear($0.date) }), id: \.self) { ...

func isDateInSelectedYear(_ date: Date) -> Bool {
    if selectedYear == nil {
        return true
    }
    return Calendar.current.component(.year, from: date) == selectedYear
}

Comment: @T.Karter You can make `selectedYear` optional. Then if it's `nil` you return true in `isDateInSelectedYear`.
Comment: Thank you! What logic can I apply to the "all" button?


Is my reinforced concrete ceiling still safe?

Question: The ceiling of my Honk Kong flat has exposed corroded steel and crumbling concrete. The plaster easily falls out of there, and there are cracks in the roof.

Is this fixable?
Is this still safe?
What can/should I do to fix it?
Comment: I'm voting to close this question because it requires an engineer on-site and includes multiple questions.
Comment: This isn't a DIY question.  What does the building owner say about this?
Comment: The flaking paint by itself is an indication of moisture issues. The fact that the concrete has spalled off indicates that the rebar inside is rusting (and expanding, which pops the concrete off). Rusted rebar is not as strong as un-rusted rebar. So there little doubt that this structure is not as strong as it was intended to be. Whether or not it's become a safety issue can only be determined by a professional on-site inspection. It's not something you can ignore. It's not going away, and worst-case is another [Champlain Towers](https://www.google.com/search?q=champlain+towers) incident.
Comment: Please see the [help]. You need to ask a single question, which isn't purely a matter of opinion, and which doesn't require much more information than you have provided.
Answer: If you're near a salty body of water, the salt water can cause corrosion like this, where the corrosion generates pressure that spalls the concrete. Most likely, though, this is just old reinforced concrete with corrosion (and spalling) caused by moisture.
The high alkalinity of new concrete protects reinforcing steel from corrosion, even if the concrete is saturated with water. Unfortunately atmospheric CO₂ reacts with the concrete to nullify the high alkalinity that provides this corrosion protection. For well placed concrete, the low alkalinity spreads inward from the surfaces at a rate of about 0.04" per year. Search the web for "rebar passivation layer" if you want more information.
My expectation is that your rebar lost its passive layer and is now corroding from moisture. If there's still any strength left in the rebar, you would want to prevent further corrosion by stopping moisture from soaking into the concrete. With better pictures, ceiling thickness, rebar diameter and spacing, etc., I could give you safety and repair opinions for free over the tubes here, but you should get a local professional to actually look at this in person. Common structural pathologies based on local practices will be familiar to this person, and he'll also be able to notice things that you might have ignored as unimportant.


Book that helps recognizing underlying mathematical expression of numerical results

Question: I strongly remember having seen a couple of years ago a huge book that only consisted out of an enormous table over hundreds of pages containing approx. 10⁵ numerical results in ascending order with their symbolic expression as a counterpart, so to help numerical researchers recognising numerical results as mathematically meaningful constants.
Something like

...
0.577215664    |    $\gamma$ ,(Euler-Mascheroni-Constant)
0.577252312    |    some other expresion
...

Unfortunately, I can't find the book now - Is anyone out there who can help me finding it?
Thanks a lot.
Comment: Have you ever tried using mrob.com/pub/ries/?
Comment: Why don't you try using Inverse Symbolic calculators http://isc.carma.newcastle.edu.au/standardCalc ? Just tpe the second number : you will get two amazing results.
Comment: Thank you for this useful hint, @Santiago! I'm surprised I never heard of it before. And although it's much easier to use than any book, I'm still curious to find it..
Answer: "A Dictionary of Real Numbers" by Jonathan and Peter Borwein This book contains "just over $100000$ eight-digit real numbers in the intervalle $[0,1]$. I found it too very useful!
The online counterpart is the ISC.
Other online substitutes :

The inverse symbolic calculator ISC+
RIES
the identify instruction in Wolfram Alpha
Comment: That's it, thank you so much!
Comment: You are welcome @Benjamin W G!


Play sound through two or more outputs/devices

Question: I have one sound card and one pair of Bluetooth headphones. I want to play my audio through both my sound card and my Bluetooth headphones.
I believe Windows has checkboxes that allow you to "check" outputs to enable/disable them, but Ubuntu seemingly has the equivalent of radio selectors (you can only select one at a time).
Bonus question:
On a similar note, I have 5 analog output channels on my sound card (in addition to my digital & HDMI audio) -- I would like to be able to determine what comes out of each of those ports (e.g. "front speakers" on all 5 or "front", "center", "back", etc).
Comment: Yes, the version of `paprefs` in Ubuntu 18.04 repos is useless (because it still thinks GConf is in fashion and hence fails to work). The best alternative is to, you know, load the `module-combine-sink` of PulseAudio yourself (because that's all `paprefs` does behind-the-scene anyway). Use command `pactl load-module module-combine-sink` and check the Sounds section of Ubuntu Settings.
Comment: I have read all answers, checking answer date too. What is the current solution for ubuntu 18.04?
Comment: In Ubuntu 19.10 solution with paprefs works out of box again.
Comment: Ubuntu 20.04 - `paprefs` worked for all hard-connected speakers, after closing all audio settings & restarting the pulsaudio `killall pulseaudio` however it disconnected my bluetooth speaker - had to reconnect and switch to it and back to the multioutput :)
Comment: it works but the timing is a mess. i understand now why no professional wanted to write software for linux. the complete audio architecture is a bit of a mess. pulseaudio being more network oriented and jack single audio device. it is hard to create tight sync between multiple audio devices. The synchronisation issues are simply not easy to solve.
Answer: With paprefs you have access to a virtual output device that enables simultaneous output to all attached sound cards and devices:
sudo apt install paprefs

Then in the terminal run paprefs, select Simultaneous Output tab, and check Add virtual output for simultaneous output on all local sounds cards.

The additionally created audio output device for simultaneous output may be selected in the Output tab from the PulseAudio Sound Preferences menu (pavucontrol):

In this example it is shown for an HDMI-device, but, as soon as your Bluetooth device is recognized, it will also be available for simultaneous output.
The changes may need a restart of PulseAudio to take effect, either by logging out and back in to your session or by running pulseaudio -k in a terminal.

In case paprefs does not do the job or if you prefer to have paprefs not installed, use this command from the command line:
pactl load-module module-combine-sink

To unload the module from the command line and reset PulseAudio to defaults, just restart PulseAudio with:
pulseaudio -k

or issue:
pactl unload-module module-combine-sink

Comment: This gets the job done.  As I get deeper into audio development, I would really like to be able to select specific devices and/or ports, though.
Comment: doesnt work for me in ubuntu 16.04. I don't see any such option like "Simultaneous output" in the sound preferances window
Comment: this one doesn't work for me in 18.04. If you know how I can do this with ALSA please help me here: https://askubuntu.com/q/1042485/586277
Comment: @NathanJ.Brauer: you may be interested in [this answer](http://askubuntu.com/questions/14077/how-can-i-change-the-default-audio-device-from-command-line/14083#14083). For changing ports see also the pulseaudio wiki I linked to there.
Comment: @Jollywatt - Separate volume control of each audio device is possible through ***PulseAudio Preferences*** (`pavucontrol`), under both 'Playback' and 'Output' tabs.
Comment: yes I followed the steps correctly but it didn't worked. Then I tried it on another ubuntu machine and it worked. So I reinstalled pulse audio on my machine and now it's working. The problem was pulseaudio -k was not killing pulseaudio it was throwing some permission errors. now it's fixed. thank you
Comment: Didn't create a device on Ubuntu 20.04.
Comment: @Velkan: thanks for the notice. Paprefs appears to be broken. Try with the command I gave in an edit to this answer.
Comment: Works on Ubuntu 20.10, too.
Comment: but what if i want to use the built-in speakers along with an audio line that does not have bluetooth? i used this solution but since the audio jack is not connected to something that has an audio card, sound options does not recognize it...
Comment: Is there any way to fix the delay between bluetooth speaker and build in speakers? It seems to me that they are quite in syc one time and far appart another.
Comment: The delay comes from buffers needed for the A2DP protocol. Not much we can do about this, unfortunately.
Comment: @node_man: did you install and set up **paprefs** as shown in the first part of my answer? It would be a prerequisite for creating a simultaneous sink.
Comment: How can one control each output device's volume independently? If that can't be done, this answer is almost useless.
Comment: @Takkat, yea, I did instead add the `load-module module-combine-sink` into `~/.config/pulse/default.pa` as other comments say. It's working.
Comment: @Velkan you need to CLOSE ALL AUDIO SETTINGS WINDOWS, then `killall pulseaudio` and then reopen them when audio starts again, tested on Ubuntu 20.04 right now and it works
Comment: @Takkat however I had a different issue - killing pulsaudio also disconnected my bluetooth speaker - I had to reconnect to it again and switch output device to the bluetooth speaker and back to the virtual multioutput :)
Answer: Ubuntu
I've just confirmed this solution still works on Ubuntu 14.04 LTS.

Install: Open terminal and type sudo apt install paprefs go to the tab exactly as per the picture above and select the option.
Initial Run:

Remaining in terminal, type pulseaudio -k to kill and restart pulseaudio (this way with current systemd pulseaudio user service).
Then go to your sound settings and you will see the option to output to multiple sound devices.
Props to whoever wrote paprefs it's a brilliant little piece of software I would actually like to see included in Ubuntu without requiring additional installation.

Apple Mac OS X
A similar solution is available via an included piece of software and whats so great about pulseaudio is that the sound seems to be perfectly in-sync from both outputs so it must be adjusting for the lag as well which is why its so impressive; otherwise we would be hearing a slightly delayed version from one output and another.
Comment: This also works on Ubuntu 16.04.1 LTS
Comment: thanks for doing the work to check if solution is still valid!
Comment: Thanks, just confirmed this works in Linux Mint 20. It's per user so you have to do the command as the desktop user.
Answer: In Kubuntu 18.04, Plasma 5.12 paprefs is not needed, as a similar setting is already there:

A new output option should become available after reboot, called "Simultaneous output".

Or in pavucontrol:

In 18.10 with Plasma 5.13.5 that "Simultaneous output" option has been removed, so paprefs is needed.
Comment: "Simultaneous output" is still available on my ArchLinux with KDE 5.19.2
Answer: I could not get Takkat's proposal work out of the box in Debian 8.7, although I restarted the system.
I assume you have completed Takkat's proposal in installing paprefs.
Extension on Takkat's answer which works based on Arch Linux wiki where keep analog input and Pulse calls that "duplex"
# /etc/pulse/default.pa
# http://unix.stackexchange.com/a/180374/16920
load-module module-alsa-sink device=hdmi:0
load-module module-combine-sink sink_name=combined
set-default-sink combined

Then restart pulseaudio:
pulseaudio -k

Comment: For me, this one worked when I had device="hw:0,0" as per `aplay -l` (see https://forums.linuxmint.com/viewtopic.php?t=264540#p1436479)
Comment: Make sure to put at top of file! This works for me (hw:0,0) on Ubuntu 18.04.2, playing on two HDMI monitors, after I moved the lines to the top.
Answer: Because LeonidMew was asking about 18.04 (I'm using 18.04.2), here's my version.
The GUI paprefs tried to combine one HDMI with one analog output, instead of both hdmi. So I edited the file /etc/pulse/default.pa as described by Léo Léopold Hertz
$ gedit /etc/pulse/default.pa  # make changes as in method a or b below
$ pulseaudio -k # then restart pulseaudio

Both the following methods work on their own, so pick one (make sure to add these lines to the top of the file, I put it right after .fail ! Otherwise it doesn't work).
Method A
load-module module-alsa-sink device=hw:0,0
load-module module-combine-sink sink_name=combined

Method B
load-module module-alsa-sink device=hw:1,3 sink_name=hdmi
load-module module-alsa-sink device=hw:1,7 sink_name=hdmi2
load-module module-combine-sink sink_name=combined slaves=hdmi,hdmi2
set-default-sink hdmi-combined

Reference
Method A
For reference, the hw:0,0 comes from aplay -l
$ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: PCH [HDA Intel PCH], device 0: ALC892 Analog [ALC892 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 1: ALC892 Digital [ALC892 Digital]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: NVidia [HDA NVidia], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: NVidia [HDA NVidia], device 7: HDMI 1 [HDMI 1]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: NVidia [HDA NVidia], device 8: HDMI 2 [HDMI 2]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: NVidia [HDA NVidia], device 9: HDMI 3 [HDMI 3]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

Method B
And the 1:7 and 1:3 comes from
$ pacmd list-sinks | grep -e 'name:' -e 'alsa.device ' -e 'alsa.subdevice '
    name: <alsa_output.pci-0000_00_1b.0.iec958-stereo>
        alsa.subdevice = "0"
        alsa.device = "1"
    name: <alsa_output.pci-0000_01_00.1.hdmi-stereo-extra1>
        alsa.subdevice = "0"
        alsa.device = "7"

On the GNOME "sound settings" I set the other HDMI from 2nd monitor as output, and then re-ran the command
$ pacmd list-sinks | grep -e 'name:' -e 'alsa.device ' -e 'alsa.subdevice '
    name: <alsa_output.pci-0000_00_1b.0.iec958-stereo>
        alsa.subdevice = "0"
        alsa.device = "1"
    name: <alsa_output.pci-0000_01_00.1.hdmi-stereo>
        alsa.subdevice = "0"
        alsa.device = "3"

To verify these numbers are correct, I ran
$ aplay -D plughw:1,3 /usr/share/sounds/alsa/Front_Right.wav
$ aplay -D plughw:1,7 /usr/share/sounds/alsa/Front_Right.wav

which sounded on their respective monitors.
Answer: To complement the excellent answer from Takkat, I found the default name given to the new device was excessively long and distorted the Sound Settings dialog. In order to shorten that name, I had to additionally execute the following command:
gconftool --set --type string /system/pulseaudio/modules/combine/args0 sink_properties=device.description=Combined

Comment: How do I undo this?!
Answer: Nowadays
Actually, with pipewire, just the GUI part seems to bee missing for this to work (in GNOME, as of GNOME 45).
Actually, there are many GUI tools for this and similar tasks (like distorting audio or so), just search for pipewire on Flathub e.g..
I tested some and found Helvum to be good and working for that use case.. In the self-proclaimed "graphical patchbay for PipeWire". You can just connect the same source twice there or mix that up even more:
.
I.e. drag and drop the source from the left to the right, where the audio devices are. (Note FL is left audio and FR is right audio)
The disadvantage/important thing to note is the source only appears once it has audio output and you need to configure this for each application. (though, the benefit of course is, you can configure it separately)
The benefit is this also works on immutable distros.
My tries
Before using Fedora Silverblue 39 I tried using the paprefs:
$ rpm-ostree install paprefs
Checking out tree 9450953... done
Enabled rpm-md repositories: fedora rpmfusion-free fedora-cisco-openh264 updates rpmfusion-free-updates updates-archive
Importing rpm-md... done
rpm-md repo 'fedora' (cached); generated: 2023-11-01T00:12:39Z solvables: 70825
rpm-md repo 'rpmfusion-free' (cached); generated: 2023-11-04T16:49:08Z solvables: 445
rpm-md repo 'fedora-cisco-openh264' (cached); generated: 2023-12-12T17:22:46Z solvables: 4
rpm-md repo 'updates' (cached); generated: 2024-03-18T02:04:08Z solvables: 24253
rpm-md repo 'rpmfusion-free-updates' (cached); generated: 2024-03-10T16:19:26Z solvables: 164
rpm-md repo 'updates-archive' (cached); generated: 2024-03-18T02:34:06Z solvables: 36849
Resolving dependencies... done
error: Could not depsolve transaction; 1 problem detected:
 Problem: package pulseaudio-module-gsettings-16.1-5.fc39.x86_64 from fedora requires libpulsecore-16.1.so()(64bit), but none of the providers can be installed
  - package pulseaudio-module-gsettings-16.1-5.fc39.x86_64 from fedora requires pulseaudio(x86-64) = 16.1-5.fc39, but none of the providers can be installed
  - package pipewire-pulseaudio-1.0.4-2.fc39.x86_64 from @System conflicts with pulseaudio provided by pulseaudio-16.1-5.fc39.x86_64 from fedora
  - package pipewire-pulseaudio-1.0.4-2.fc39.x86_64 from @System conflicts with pulseaudio-daemon provided by pulseaudio-16.1-5.fc39.x86_64 from fedora
  - package pulseaudio-16.1-5.fc39.x86_64 from fedora conflicts with pulseaudio-daemon provided by pipewire-pulseaudio-1.0.4-2.fc39.x86_64 from @System
  - package paprefs-1.2-5.fc39.x86_64 from fedora requires pulseaudio-module-gsettings, but none of the providers can be installed
  - conflicting requests


NotImplementedError: ElasticNetworkInterfaces(AmazonVPC).describe_network_interface_attribute is not yet implemented

Question: How describe a network interface attribute for a mock_ec2 in test_elastic_network_interfaces_get_by_description function?
@mock_ec2 def test_elastic_network_interfaces_get_by_description():
    ec2 = boto3.resource("ec2", region_name="us-east-1")
    ec2_client= ec2.meta.client

    vpc = ec2.create_vpc(CidrBlock="10.0.0.0/16")
    vpc.reload()
    subnet = ec2.create_subnet(
        VpcId=vpc.id, CidrBlock="10.0.0.0/24",
        AvailabilityZone="us-east-1a")

    desc = str(uuid4())
    eni1 = ec2.create_network_interface(
        SubnetId=subnet.id, PrivateIpAddress="10.0.10.5", Description=desc )

    # The status of the new interface should be 'available'
    waiter = ec2_client.get_waiter("network_interface_available")
    waiter.wait(NetworkInterfaceIds=[eni1.id])

    eni1.modify_attribute(SourceDestCheck={'Value': False})
    eni1.reload()
    response = eni1.describe_attribute(Attribute='description')

python           3.7
mock            4.0.3
moto            2.1.0
sure            2.0.0
aiobotocore     1.4.2
boto3          1.18.2
botocore     1.20.106
coverage        5.5

What is needed to implement or fix to run or pass the test?
Answer: If you're asking how to implement this feature in Moto, the documentation should help here: http://docs.getmoto.org/en/latest/docs/contributing/new_feature.html
TLDR:
There is a script that will generate the scaffolding for a new feature.

Check out the Moto source code
Install the project (make init)
Run the scaffold-script: scripts/scaffold.py

It's always possible to open an issue, or create a draft PR in Moto - they are happy to help out if you want to contribute.
https://github.com/spulec/moto
Answer: If after update or scaffold-script of moto library the method is not implemented in a library yet and continue an error like this :

NotImplementedError:
ElasticNetworkInterfaces(AmazonVPC).describe_network_interface_attribute
is not yet implemented

An easy solution for the test is a monkeypatch function that lets simulates the method not implemented.

def client_mock(Attribute='description'):
    return {
        'Attachment': {
            'AttachTime': 34545,
            'DeleteOnTermination': False,
            'DeviceIndex': 123,
            'NetworkCardIndex': 123,
            'InstanceId': 'eni1.instanceid',
        },
        'Description': {
            'Value': 'Vpc network inteface'
        },
        'Groups': [
            {
                'GroupName': 'name group',
                'GroupId': 'grupoid'
            },
        ],
        'NetworkInterfaceId': 'eni.id',
        'SourceDestCheck': {
            'Value': False
        }
    }

and put it with attributes on the pass at respective the function or method
monkeypatch.setattr(eni1, "describe_attribute", client_mock)

If you know a better solution, please post it!


creating a list using meteor

Question: Hi I am creating a money lend tracking website using meteor. It is my first attempt to learn meteor js. I tried writing the following piece of code in my js file
var lists = new Meteor.Collection("Lists");

But when I go back in Chrome developer console after refreshing page and type
lists
ReferenceError: lists is not defined
get stack: function () { [native code] }
message: "lists is not defined"
set stack: function () { [native code] }
__proto__: Error

Is there something i am missing ? Could any one help me.
Comment: Why are you refreshing the page? And where is this line of code found? You just said "in my js file". Is it in the global scope? Otherwise `lists` isn't globally available
Comment: i have added this line as the first line in lendLibrary.js file.
Answer: You can't access lists from your web console because code is scoped with each file. In meteor your code would be run as
function() {
    var lists = new Meteor.Collection("Lists");
    ....
}

So to access your collection in the console you need to globally scope it by changing your line to:
lists = new Meteor.Collection("Lists");

So that lists can be used anywhere such as other files and the webkit console
Answer: Those using the book, "Getting Started with meteor.js", from which this example originates.... are instructed by the author to use the var keyword before "lists", thereby local scoping that variable and causing the mismatch between what the book says you should see and what you actually see in a browser console.  This is a mistake in the book and I have been unable to find any online errata for the book.
Comment: This seems like it should be a comment, not an answer.
Answer: From the book "Getting Started with Meteor.js JavaScript"
Errata type: Code| Page number: Chapter 2. Reactive Programming… It's Alive!, | Errata date: 18-4-2013
In the example:
var lists = new Meteor.Collection("Lists");
should read instead
lists = new Meteor.Collection("Lists");
The reason is that "...Meteor 0.6 has added file-level JavaScript variable
scoping. Variables declared with var at the outermost level of a JavaScript
source file are now private to that file. Remove the var to share a value
between files."

creating a list using meteor


Designing App Interface for Parkinson's Patients?

Question: I am currently in the process of designing a UI for an app to be utilized by Parkinson's patients. I am struggling to make the interface as intuitive as possible, as of now I have minimized visual clutter (max 4 buttons on a screen), color coded menus, and reduced multi-level menus whenever possible (always one level away from the home screen).
What other accommodations can be made to ensure maximum usability? What research already exists around this topic?
Comment: What a cool project. And a great opportunity for user research. Meet with patients, watch them work with other sites, and have them work with yours. I'm envious.
Answer: People with Parkinson Disease (or PD as it's also known) need special considerations as you correctly figured. However, keep in mind that most of those considerations are covered by special peripherals rather than specific UI. As a matter of fact, just following common WAI- ARIA guidelines is more than enough.
Keep in mind that, like many people with diseases, they want to forget they have a disease, and they don't want to be treated in a special way, so try to minimize any "hey, I know you have a very complex disease so I made a site for you" approach. Simple accessibility should be more than enough.
Since you need to do this, I assume you have access to people with PD, or at least knowledgeable professionals, so be sure to research the subject, because unlike what many UX professionals would think, working with people with diseases or disabilities is a really different thing that we might think. Additionally, you can read Improving Computer Interaction for People with Parkinson's Disease, a very interesting research on HCI for PD patients.
Addendum:
You can find a real case of the research for an app for PD patients at
REMPARK
If you have access to Springer, you can get these papers:

The Re-design of a PDA-based System for Supporting People with Parkinson's Disease
Design and Evaluation of a Medication Application for People with Parkinson's Disease

And on Google Books you can find Universal Access in Human-Computer Interaction: User and Context Diversity which I really recommend. I got it when we built a system for Alzheimer patients and its contents can be adapted to PD as well, so if it's within your possibilities, try to grab it. There are some free pages available just in case
Comment: Great answer, particularly in the advice to not be condescending (easy to do accidentally), as well as to get actual input from those with PD.
Comment: I have occasional hand tremors, and what I find annoying on mobile phones is a spinner control with an "OK" button right below it!  (So if you see a gas station in a certain navigation app where the gas price is $5.19, blame me!)
Comment: Some mention of Fitt's law (https://en.wikipedia.org/wiki/Fitts%27s_law) seem applicable here too.
Answer: My father has late-stage PD and after watching him use his Mac for the last 15 years here are some thoughts in no particular order:

Assume the user can't use both hands or combinations of keys. My father uses his non-dominant hand with a track-ball because it shakes less, but has to use the keyboard and click with the same hand. Try that one out yourself some time; brutal.
Double clicking is a no-go. As is anything that is based on timing.
Keep it simple and make sure the UI inputs are large targets.
People with PD often suffer from vision problems. Make sure you address vision related accessibility issues. Also, they can experience shade-blindness for certain colors; so address that like you would accessibility for shade-blind users.

Good luck with your project!
Comment: Good to have data based on actual observation!  Based on [this comment](http://ux.stackexchange.com/questions/94253/designing-app-interface-for-parkinsons-patients#comment151518_94259), you might extend your "large targets" bullet point: "...and that your 'Done' or 'Exit' button is far away from everything else."
Answer: I think you should go a week or so using some of the peripherals that these patients would use. You probably know UX as you experience the web, but you should get to know the challenges that they face when they're not using a mouse and a screen. They might have a hard time reading on the screen because of the shaking, so maybe they use a screen reader with voice controls.
Trying them out will shock you and open your eyes to whole new world of UX issues. Maybe you can attempt to address those in this project. Everything that you mentioned will definitely help the other less-serious patients so do that all as well.
Also, you're probably asking the wrong group of people. You should go to a place like /r/Parkinsons/ and ask them. I'm sure they'd love to help.
Answer: I would give larger hit areas than we would for regular users as parkinson's patients experience tremors. Maybe try to simulate that with a shaking screen and try to use the interface yourself to experience how useable it in in that state. The best way would be to test out your interface on your target users and to adjustments based on your feedback.
Comment: Or try using the app with your left hand if your are right-handed! Or use gloves that work on cell phones, using gloves that are too big for you.
Answer: It could be useful to explore an alternative voice input. If a user has trouble pressing a control is there another way they could do it with voice? Could there a big voice activation control on each screen? I agree with another comment that it would be really useful to test the app with people with Parkinson's.
Answer: This is a perfect example of the importance of including the user in the user experience design. The contributions from the experts on this site and very valuable and will help you a ton, but getting input from the actual users as early as possible in any design situation will highlight important details early and avoid you having to try and retro-design them.
If you are not able to work directly with some of the patents it would also help to work with some of the people who care for them on a daily basis.


Question regarding Update panel and partial postback?

Question: suppose i have many server side controls in my update panel. so how could i know from the client side that which server side control causes partial postback in update panel. please help me with sample code.
Answer: You should register a handler for the update panel client event.
<code> Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(onBeginRequest);
 function onBeginRequest(sender, args) {
    var elem = args.get_postBackElement();
 }
</code>
The elem is the control you need. More info MSDN


Correlation matrix with huge dataset - Python

Question: In python, when I have a dataset X, whose rows are the different elements of the sample and the columns are different feature of the sample, I usually calculate the correlation matrix as follows (assuming zero mean):
import numpy as np
np.transpose(X).dot(X)/row

Now I have a dataset X that has 10 milion rows and 1 milion of columns, and if I try to calculate that correlation matrix, the computer remains blocked.
The alternative of performing a for-loop seems to me impracticable, because is very slow also with smaller datasets.
How shoul I manage such amount of data?
Comment: _"How shoul I manage such amount of data?"_ — My advice is. start with a subset of it and build a feeling with it: which data structures, which algorithms do the best, which results are important and which can be neglected... Later a more knowledgeable you will be able decide how much of the data is significant and how you are going to process it.
Comment: have you looked at http://docs.scipy.org/doc/scipy/reference/sparse.html . Given you have a million features, unless each document is massive, you must by definition have lots of negatives, you shouldnt be storing it all in a normal matrix.
Comment: 1 million columns? What kind of data requires 1 million *columns*? You may want to rethink your problem, because this type of dataset may cause problems elsewhere as well.
Comment: @Evert It is a dataset from a natual language processing problem: rows are documents, while columns are booleans: column i indicates wether the word that in the dictionary occupies the position i is or not present in the document.
Comment: Why not, for each document, store a list of position indices where the word can be found. An empty list means the word is not there, a list like [5432, 12345] means the word is found in positions 5432 and 12345. Those lists will be a lot shorter than a million columns of boolean flags.
Comment: Just found on PyPi

[***bitarray-0.8.1*** **efficient arrays of booleans -- C extension**](https://pypi.python.org/pypi/bitarray/0.8.1)

From their blurb:  _This module provides an object type which efficiently represents an array of booleans._
Answer: Maybe you could use a generator? I don't know if it would be acceptably fast but it would be better memory-wise so that the computer won't block.
Something like this https://gist.github.com/thatdatabaseguy/2577076
Paraphrasing the example:
import numpy as np

def my_gen(some_tuple):
    for each in some_tuple:
        yield each

X = np.fromiter(my_gen(database.get_data()))  # get_data() would return a cursor

Edit:
This is in the case you cannot find another way of reducing/ transforming/ splitting your data. Either way it is going to be difficult to handle on a single computer.
Good luck!


C# How to read a binary file into int[] without a BinaryReader loop?

Question: As far as I know, the BinaryReader loop performance is poor. Another method I can think of is to first ReadAllBytes and then Buffer.BlockCopy into int[], but that would result in an additional copy.
Is it possible to read a huge binary file directly into int[] efficiently?
Comment: What is your performance profiling of the BinaryReader loop? Where did you see the bottleneck? Can it come due to slow disk I/O or a anti-virus tool in the background? Or is it just guessing, cause in .Net 3.5 it was slow? By the way, if we talk about performance, what version of .Net are you using?
Comment: Can you not use `ReadAllBytes` and either use bytes or use `Enumerable.Cast` to convert to int?
Comment: Are you saying, without actually saying, that every four bytes in the file represents a single integer value?
Comment: @jmcilhinney Good point and quite likely
Comment: Possible duplicate: https://stackoverflow.com/questions/1238388/faster-unsafe-binaryreader-in-net
Answer: You can use MemoryMarshal.AsBytes to read all data:
using var stream = new FileStream(...);
var target = new int[stream.Length / 4];
stream.Read(MemoryMarshal.AsBytes(target.AsSpan()));

No BinaryReader is used in that case. Be aware of endianness of int representation. This code above might cause problems if the file doesn't match to your hardware.
Comment: @埃博拉酱 If the stream does not support `Length` then at some point the code will have to loop. And it won't be possible to pre-size the result buffer, which means that some data copying will be required.
Comment: This is perfect as long as the stream supports the Length property - and things become difficult if it does not …
Answer: If you want to read the array as another type, you can use MemoryMarshal.Cast.
using System;
using System.Runtime.InteropServices;

class Program
{
    public static void Main(string[] args)
    {
        byte[] arrayByte = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
        Span<int> spanInt = MemoryMarshal.Cast<byte, int>(arrayByte);

        Console.WriteLine("0x{0:X8}", spanInt[0]); // For little endian it will be 0x44332211.
        Console.WriteLine("0x{0:X8}", spanInt[1]); // For little endian it will be 0x88776655.
    }
}

Another alternative is Unsafe.As. However, there are some problems, such as Length not reflecting the converted type value. I recommend using the MemoryMarshal class.
using System;
using System.Runtime.CompilerServices;

class Program
{
    public static void Main(string[] args)
    {
        byte[] arrayByte = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
        int[] arrayInt = Unsafe.As<byte[], int[]>(ref arrayByte);

        Console.WriteLine("Length={0}", arrayInt.Length); // 8!? omg...
        Console.WriteLine("0x{0:X8}", arrayInt[0]); // For little endian it will be 0x44332211.
        Console.WriteLine("0x{0:X8}", arrayInt[1]); // For little endian it will be 0x88776655.
    }
}

Comment: ...as far the endianness in the file matches those of the machine. In my old code still have a int composition made by OR-ing the bytes.
Comment: OK, Added endian comment.
Comment: MemoryMarshal.Cast returns a Span, which doesn't implement IEnumerable, which often leads to me having to ToArray it again, resulting in an extra copy. Instead, after Unsafe.As, you can append a Take to correct the array length error, and it returns IEnumerable, and no copy occurs.
Comment: Another problem is that Unsafe.As seems not working on Android. It's simply converting the bytes into ints.


HTML5 Drag and Drop upload is not working on below the version IE 10

Question: I am using the HTML5 DND file uploading http://html5demos.com/dnd-upload but it is not working in the below the version IE 10
Webpage error details in IE browsers
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BTRS124829; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C)
Timestamp: Wed, 2 Jan 2013 06:17:02 UTC

Message: Object doesn't support this property or method
Line: 57
Char: 1
Code: 0
URI: http://html5demos.com/dnd-upload

Answer: Per the previous answers, its not just about FileReader.
Drag and Drop cannot be used perfectly in versions less than IE10. Even IE9 has some problems, let be IE8.
The browser should also support the DnD API
Check this link to another answer - Internet Explorer 9 Drag and Drop (DnD)
Check my application that allows drag drop of image files from your OS in to the browser:
HTML-5-DD - BackboneJS
It has 2 parts:
1. HTML5 Drag drop, that allows drag drop from OS to Browser
2. FileReader API that helps reading the image files as DataURI and appending the images
If your browser does not support Drag Drop, you won't be able to drag drop images in a way that can be understood by JavaScript.
Conclusion: FileReader is not the main feature that IE needs to suport for your scenario, its also and importantly the Drag Drop
Comment: @Karthik, Happy new year. Also, here's a link to a better tutorial - Native HTML5 Drag Drop - http://www.html5rocks.com/en/tutorials/dnd/basics/
Answer: This is because HTML5 uses File API & FileReader API which are not supported in IE whose versions are below 10.
Check the compatibility list here
Hope this helps.
Comment: Its not just the **`FileReader API`**, its also the support for HTML5 Drag and Drop itself
Comment: thanks is any other DND upload available with working in ie versions?
Comment: you can use flash uploaders like `uploadifive` for dnd. [demos](http://www.uploadify.com/demos/) [docs](http://www.uploadify.com/documentation/)


Conditional independence of sigma-algebras

Question: If ${\mathcal{H}_1}$ and ${\mathcal{H}_2}$ are conditionally independent given $\mathcal{G} \subseteq {\mathcal{H}_2}$, are they conditionally independent given $\mathcal{F}$ such that  $\mathcal{G} \subseteq \mathcal{F} \subseteq {\mathcal{H}_2}$? Does the same hold for arbitrary $\mathcal{G},\mathcal{F}$ such that $\mathcal{G} \subseteq \mathcal{F}$?
Intuitively, it seems to me that having more information in the condition should't change conditional independence of ${\mathcal{H}_1}$ and ${\mathcal{H}_2}$, but when trying to prove it formally, I can see no guarantee that something like that would hold.
If the statement doesn't hold, a hint for a counterexample would be welcome.
EDIT: ${\mathcal{H}_1},{\mathcal{H}_2},\mathcal{G},\mathcal{F}$ are all assumed to be $\sigma $-algebras in the text above.
EDIT 2: I think the above statement would imply: If $X$ is a random variable on $\left( {\Omega ,\mathcal{A},\mathbb{P}} \right)$ and ${{\rm H}_1},{{\rm H}_2},\Gamma  \subseteq \Omega $ such that ${\left. X \right|_{{{\rm H}_1}}}$ and ${\left. X \right|_{{{\rm H}_2}}}$ are conditionally independent given ${\left. X \right|_\Gamma }$ such that $\Gamma  \subseteq {{\rm H}_2}$, then ${\left. X \right|_{{{\rm H}_1}}}$ and ${\left. X \right|_{{{\rm H}_2}}}$ are conditionally independent given ${\left. X \right|_\Phi }$ in case that $\Gamma  \subseteq \Phi  \subseteq {{\rm H}_2}$.
If the former statement doesn't imply the latter or if it doesn't hold, I'm really only interested in the latter statement. ${\left. X \right|_{\rm H}}$ denotes the restriction of $X$ to ${\rm H}$.
Answer: Using this statement, it follows that it suffices to prove that $\mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{G}} \right] = \mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{F}} \right] = \mathbb{E}\left[ {{1_{{H_1}}}|{\mathcal{H}_2}} \right]$.
From the assumption it follows that $\mathbb{E}\left[ {{1_{{H_1}}}|{\mathcal{H}_2}} \right] = \mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{G}} \right],\forall {H_1} \in {\mathcal{H}_1}$. We also have $\mathbb{E}\left[ {\mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{F}} \right]{1_F}} \right] = \mathbb{E}\left[ {{1_{{H_1}}}{1_F}} \right]$ from the definition of conditional expectation. It also holds that $\mathbb{E}\left[ {{1_{{H_1}}}{1_F}} \right] = \mathbb{E}\left[ {\mathbb{E}\left[ {{1_{{H_1}}}|{\mathcal{H}_2}} \right]{1_F}} \right]$ since ${\mathbb{E}\left[ {{1_{{H_1}}}|{\mathcal{H}_2}} \right]}$ is $\mathcal{F}$-measurable because $\mathcal{F} \subseteq {\mathcal{H}_2}$. From the assumption it then follows that $\mathbb{E}\left[ {\mathbb{E}\left[ {{1_{{H_1}}}|{\mathcal{H}_2}} \right]{1_F}} \right] = \mathbb{E}\left[ {\mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{G}} \right]{1_F}} \right]$, so $\mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{G}} \right] = \mathbb{E}\left[ {{1_{{H_1}}}|\mathcal{F}} \right] = \mathbb{E}\left[ {{1_{{H_1}}}|{\mathcal{H}_2}} \right]$.
This proves the statement.


Sublime text: How to do sentence case (capitalize the first letter of a sentence)

Question: I'm aware that there is Edit > Change Case menu. But there's no option for sentence case.
How do I achieve this? Is this possible for regex to achieve this?
Answer: You can use this regex:
find
(^|\.\s|…\s)([a-z])

and replace with
\1\u\2

Explanation:

The first find group (parénthesis group) captures a line beginning or a dot followed by a space or three dots character followed by a space.
The second group captures a letter.
In the replace expresion \1 and \2 refer to the captured groups.
\u means translate one character to uppercase.
This capitalizes lines starting with a character and sentences starting after other sentences.
Comment: (^|\.\s|…\s)([a-z]) can be used to catch "..." character as well.
Answer: Find:

(.)(.*)

Replace:

\u\1\L\2

That would make

This Is A Demo

into

This is a demo

Answer: It is a possible duplicate of Sublime Text - command to make first character uppercase.
By the way, in brief, you could use the key-map CtrlK,CtrlI, writing in your "user keybinding file":
{ "keys": ["ctrl+k", "ctrl+i"], "command": "title_case" }

Comment: "Title Case" is not "Sentence case".
Comment: Select first word of each sentence and make it title case


Cannot set member variable to null

Question: I would really like to provide a minimal working example for this question, but I did not succeed in creating one. So I'll just describe what's happening and hope that someone can be of help anyway.
Somewhere in my code, I have these lines:
long i = 0;
while (this.someField != null) {
    this.someField = null;
    i++;
}
long j = i;

(This code is the result of lots of debugging I have already done to find the cause of my problem.)
This code is deployed on a WebLogic Application server. I have a breakpoint set just before the while loop. I debug the code remotely with IntelliJ.
When the code hits the breakpoint, I execute it step-by-step. The code just keeps looping through the while loop, but someField never becomes null. So I set a second breakpoint at the line after the loop, and hit continue. The code immediately exits the loop and stops at this line. I can tell that there are no more executions of the loop because I inspect i afterwards. However, this.someField still isn't null. I tried it multiple times, so I am quite sure that the reason why the code keeps executing the loop is that I am debugging it.
I have no idea how to debug this problem. My observations just don't make any sense (unless I apply quantum mechanics). What could cause such behavior? Is this a bug in my JVM? A bug in the debugger? Something else?
Edit:
The field is declared like this:
 private Vector<KeyValuePair> someField = null;

It is private and I ensured that is is not changed by another thread by setting breakpoints on all methods that mangle with it.
Comment: Any chance concurrency is part of the mystery? Can you show the definition of `someField`?
Comment: There are other threads on the application server, but they're all running in different deployments and cannot possibly interfere with this object.
Comment: I think you need to try harder to produce a minimal example. At the moment your question is impossible to answer, and it's not clear why you need a `while` loop to set a field to `null`.
Comment: I am perfectly aware that I should not need the `while` loop. I just added it because I was baffled about the field not becoming `null` after a normal assignment.
Comment: The chance might be small but since it happend to me as well I'll ask anyways: Are you 100% sure that the code which is running on the server is the very same your debugger sees? Are you sure the server is set up to isolate deployments? Are you sure there's no reflection code that accessed the field?
Comment: I did decompile the `.class` with IntelliJ and it showed the same code as I have here. I also inserted a function call at the position of the while loop and redeployed just to make sure that redeployment does deploy the code I see. The function got called, so I am pretty sure the code I see is actually the one deployed on the machine.
Comment: A colleague speculated that when I stop the step-by-step-debugging, the JIT compiler optimizes the `while`-loop away and that's why I get to the line behind it. Could that be possible? It wouldn't explain while the field doesn't become null though.
Comment: May be a silly question, but do you do you have any expression in debug mode that sets someField to a value? if Yes, the object would be set to some value on every turn, but at least that would explain why you have this issue.
Comment: How do you know the field is not null after the loop? Is it only the debugger telling you this, or do you have other confirmation?
Answer: This seems to be a problem with the IntelliJ debugger. The debugger sets the value while debugging, and the control flow changes according to this modification. When I used the Eclipse debugger instead, the problem vanished.

Cannot set member variable to null


Why I encountered Diablo in The Forgotten Tower in Diablo II?

Question: I was playing Diablo II LoD recently with sorceress on Hell difficulty. Unexpectedly, when I got to The Forgotten Tower, instead of The Countess I encountered Diablo boss. Was not prepared for that and died. When going there second time everything was OK, The Countess was there. I haven't found on the Internet any information about this. All I found was Uber Diablo and Pandemonium Diablo, but it seems that they should spawn in another location.

Why Diablo was there? Is it some event, bug or maybe easter egg? I am playing with PlugY mod, maybe it did spawn Diablo? However, I haven't found anything related in its configuration file.
Answer: All of the information about Uber Diablo can be found here
The PlugY mod has a built in function to spawn Uber Diablo at random intervals. Usually Uber Diablo only spawns on multiplayer battle.net games, but since that's not possible on single player, PlugY just randomly does it.
The fact that he spawned in The Forgotten Tower, is because he will always spawn and the first Super Unique enemy you encounter. More information about Super Unique monsters can be found in the Uber Elder link at the top of the answer. If you want him to go away so you can complete that quest, save and quit and go back into your character. He will despawn from that location and randomly appear whenever PlugY decides is the right time for him to come back.
Comment: Ah, I see. It was a bit misleading that Uber Diablo in game is called simply Diablo. It seems that PlugY is automatically selling a lot of SoJ's to spawn Uber Diablo, I somehow missed that in configuration. I guess that setting option ActiveAutoSell=0 will disable that, but haven't tested yet.


C++ Fixed Size Container to Store Most Recent Values

Question: I would like to know what the most suitable data structure is for the following problem in C++
I am wanting to store 100 floats ordered by recency. So when I add (push) a new item the other elements are moved up one position. Every time an event is triggered I receive a value and then add it to my data structure.
When the number of elements reaches 100, I would like to remove (pop) the item at the end (the oldest).
I want to able to iterate over all the elements and perform some mathematical operations on them.
I have looked at all the standard C++ containers but none of them fulfill all my needs. What's the easiest way to achieve this with standard C++ code?
Comment: [std::queue](http://en.cppreference.com/w/cpp/container/queue) is good for this problem i think
Comment: @Shan floating-point errors accumulation.
Comment: I can't iterate over the whole std::queue very easily - I want to take a weighted average of all the items.
Comment: @CalG Why you can't do? each time you insert/Pop into queue update avg value.
Comment: If you just need average, why don't go with a running sum and running average? O(1) space and O(1) time complexity :-)
Answer: You want a circular buffer. You can use Boost's implementation or make your own by allocating an array, and keeping track of the beginning and end of the used range. This boils down to doing indexing modulo 100.
Comment: @Abhinav I don't get it. If you store the same value several times, the general solution is not to be smart about it and just store the thing 20 times. If you need to prune duplicates, *then* you will need a more specific solution. Nowhere in the OP is it made case of duplicate values.
Comment: Will you be able to handle duplicates. I mean if there is a number say 20 being used again and again, whole buffer would be having 20 all over. Am I missing something?
Comment: @Abhinav why, yes. OP doesn't mention special treatment for duplicates.
Comment: I actually used std::deque to solve my problem                                                 if (myDeque.size() > 100){ myDeque.pop_front() }                                         However a circular buffer would have been appropriate
Comment: Quentin , IMHO if a problem is not specified, we go for general solution. In that sense a circular buffer is wrong answer.
@CalG , please update your question if yours is a specific case (I bet it cant be) otherwise this is too specific solution and therefore not correct in all situations!
Comment: A simple question would be: Why one needs MRU? Because the items would be needed (search may be). In this case last 100 items and items would mean 100 unique. A cache would be a perfect example of this. If 100 items in a MRU cache in which if an element is used 100 times, it wouldn't discard rest of the elements from cache.
Comment: @Abhinav you're extrapolating. But if we're at it then my guess at the context would rather be "display a smoothed measured value by averaging the 100 latest samples", as OP mentions taking the average of all the values — which would be skewed were you to ignore multiple occurences of the same value.
Comment: @Quentin Yes the solution is perfect but overly complicated. I would go with a running sum and running average in that case. O(1) space and O(1) time complexity :-)
Comment: @Abhinav that'd be perfect, if not for the floating-point error accumulation.
Comment: that can be taken care of by using double precision for running average to take care of these.
Comment: @Abhinav *maybe*. Maybe not. Anyway, this is off-topic again, fulfilling OP's specifications closely ought to be it.
Answer: Without creating your own or using a library, std::vector is the most efficient standard data structure for this. Once it has reached its maximum size, there will be no more dynamic memory allocations. The cost of moving up 100 floats is trivial compared to the cost of dynamic memory allocations. (This is why std::list is a slow data structure for this). There is no push_front function for vector. Instead you have to use v.insert(v.begin(), f)
Of course this assumes what you are doing is performance-critical, which it probably isn't. In that case I would use std::deque for more convenient usage.
Comment: Why there will be no more dynamic memory allocations, once `std::vector` has reached its max size? As you know, we can `push_back` as many times as possible and the underlying memory grows up infinitely(reallocation). How `std::vector` can be a container the OP wants? OP wants a fixed-sized container, retaining only the recent N elements.
Comment: @starriet Once the vector has reached the highest size it ever will during the run of the program, it won't allocate any more times. If you push_back beyond this size, then it wasn't at its maximum size..
Comment: Thanks. By the way, the complexity of `std::vector::insert` is linear(O(n)), so I think it's not very "performance-critical". Isn't it possible to make a faster data structure than O(n), for a fixed-sized container?
Comment: @starriet The problem is limited to 100 floats, which is small for a computer. If the upper limit were unbounded, I wouldn't suggest this. Other containers have front insert with better complexity, but could perform more dynamic memory allocations or have poorer memory locality and can make overall performance worse. You have to consider the complexities and costs of all parts of the solution, and not just 1 of the functions that will be called. A circular buffer based on a contiguous array, as suggested in the accepted answer, is better solution than mine.
Answer: Just saw that you need to iterator over them. Use a list.
Your basic function would look something like this
void addToList(int value){
    list100.push_back(value);
    if(list100.size() > 100){
        list100.pop_front();
    }
}

Iterating over them is easy as well:
for(int val : list100){
    sum += val;
}
// Average, or whatever you need to do

Obviously, if you're using something besides int, you'll need to change that. Although this adds a little bit more functionality than you need, it's very efficient since it's a doubly linked list.
http://www.cplusplus.com/reference/list/list/
Comment: Granted, on small data sets the difference won't be noticeable, but that's not to say we shoud give into premature pessimisation. An array lays its elements contiguously and is the most cache-friendly structure as nothing is wasted. A list, on the other hand, has no requirement to fit neatly on a cache line at all. And even if by pure luck all your nodes end up being side-by-side, you're wasting at best 80% of the cache space for the pointers, and the CPU needs to repeteadly jump through them instead of merely incrementing a register. `std::list` is for flexibility, not speed.
Comment: A list is particularly ill-suited for this job. You need neither the extensibility, nor the O(1) middle insertion, and traversal will be hurt by the fragmentation of your data.
Comment: Yes, but how do I iterate over all the values and take an average?
Comment: Nope. Thats incorrect IMHO. what about same element is always pushed 100 times. your queue will have only 1 element in 100 locations.
Comment: i think a circular buffer is the better fit since he has the requirement of a fixed size.
Comment: I agree on the circular buffer. I was sticking with `std::`, as the OP requested. How would it hurt traversal? An array goes from memory location to memory location just like a list. I suppose it COULD be affected by how the memory is paged, but with 100 values, I don't see that being an issue.
Answer: You can use either std::array, std::dequeue, std::list or std::priority_queue
Answer: A MAP (std::map) should be able to solve your requirement. Use Key as the object and value as the current push number nPusheCount which gets incremented whenever you add an element to map.
when adding a new element to map, if you have less than 100 elements, just add the number to the MAP as key and nPushCount as the value.
If you have 100 elements already, check if the number exists in map already and do following:

If the number already exists in map, then add the number as key and nPushCount as value;
If doesnt, delete the number with lowest nPushCount as value and then add the desired number with updated nPushCount.
Comment: This is way too complicated a solution for a fairly simple problem


Rotate each grid item around its own center in THREE.js

Question: I want to create a grid of geometries (ROWS * COLUMNS) and wanna rotate each individual mesh around it's own center.
I generate the grid through two for loops, translate the single elements to there correct position and push them into an array to use them again in the animation function. In the animation function I iterate again over all the elements and rotate every single one.
the problem is that even though I address each element individually and I have translated each element to the right place, each element still revolves around the center of the page and not its own center (see the screenshot)
Here is my current attempt:

const main = () => {

  const ROWS = 4;
  const COLUMNS = 4;
  const ITEMS = [];

  const canvas = document.querySelector('#canvas');
  const renderer = new THREE.WebGLRenderer({canvas, antialias: true});
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(1, window.innerWidth/window.innerHeight, 0.1, 1000);

  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor('#e5e5e5');

  camera.position.z = 500;

  // GEOMETRY
  for (let x = 0; x < COLUMNS; x++) {
    for (let y = 0; y < ROWS; y++) {
      const geometry = new THREE.BoxGeometry(1, 1, 0.5);
      const edges = new THREE.EdgesGeometry(geometry);
      const edgesMaterial = new THREE.LineBasicMaterial({ color: 0x1940EB });
      const edgesMesh = new THREE.LineSegments(edges, edgesMaterial);
      ITEMS.push(edgesMesh);
      edges.translate(x*1.5, y*1.5, 0);
      scene.add(edgesMesh);
    }
  }

  scene.position.set(-COLUMNS/2, -ROWS/2, 0);

  const animation = () => {
    requestAnimationFrame(animation);
    ITEMS.map(item => {
      item.rotation.x += 0.01;
      item.rotation.y += 0.01;
    })
    camera.updateMatrixWorld();
    renderer.render(scene, camera);
  }

  const onWindowResize = () => {
    const w = window.innerWidth;
    const h = window.innerHeight;
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    renderer.setSize(w, h);
  }

  animation();
  onWindowResize();

  window.addEventListener('resize', onWindowResize, false);
};

window.addEventListener('load', main, false);
body {
  padding: 0;
  margin: 0;
  height: 100vh;
}

canvas {
  display: block;
}

<canvas id="canvas"></canvas>

Can someone explain to me why the elements individually addressed in the animation function still do not revolve around themselves?
Thanks for your help
Answer: Because the code is moving the geometry itself so that it's center is no longer in the middle of the box.
change
      edges.translate(x*1.5, y*1.5, 0);

to
      edgesMesh.position.set(x*1.5, y*1.5, 0);

This will move the Object3D in the scenegraph instead of the vertices of the geometry data.

const main = () => {

  const ROWS = 4;
  const COLUMNS = 4;
  const ITEMS = [];

  const canvas = document.querySelector('#canvas');
  const renderer = new THREE.WebGLRenderer({canvas, antialias: true});
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(1, window.innerWidth/window.innerHeight, 0.1, 1000);

  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor('#e5e5e5');

  camera.position.z = 500;

  // GEOMETRY
  for (let x = 0; x < COLUMNS; x++) {
    for (let y = 0; y < ROWS; y++) {
      const geometry = new THREE.BoxGeometry(1, 1, 0.5);
      const edges = new THREE.EdgesGeometry(geometry);
      const edgesMaterial = new THREE.LineBasicMaterial({ color: 0x1940EB });
      const edgesMesh = new THREE.LineSegments(edges, edgesMaterial);
      ITEMS.push(edgesMesh);
      edgesMesh.position.set(x*1.5, y*1.5, 0);
      scene.add(edgesMesh);
    }
  }

  scene.position.set(-COLUMNS/2, -ROWS/2, 0);

  const animation = () => {
    requestAnimationFrame(animation);
    ITEMS.map(item => {
      item.rotation.x += 0.01;
      item.rotation.y += 0.01;
    })
    camera.updateMatrixWorld();
    renderer.render(scene, camera);
  }

  const onWindowResize = () => {
    const w = window.innerWidth;
    const h = window.innerHeight;
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    renderer.setSize(w, h);
  }

  animation();
  onWindowResize();

  window.addEventListener('resize', onWindowResize, false);
};

window.addEventListener('load', main, false);
body {
  padding: 0;
  margin: 0;
  height: 100vh;
}

canvas {
  display: block;
}

<canvas id="canvas"></canvas>

You might find this article useful


Clementine has high CPU usage even after shutting it down

Question: I have an issue with Clementine: sometimes (even after switching it off) it takes up a lot of CPU like on the screen here

On the screen there are visible 2 instances of Clementine but both of them are already switched off.
Anyone also having this problem ?
If this matters I have the music files on ntfs partition which I mount every time I boot the system (maybe it does some indexing or things like that). BTW : can I make ubuntu mount this partition automatically ?
Comment: How can I check that  ?
Comment: Can you please check if Clementine is trying to update something? Like your internet radio lists or something or getting channel lists from last.fm, coz it was like that for me then, but after that, it calmed down.
Comment: It will say the current task it is doing at the bottom, near shuffle and repeat buttons
Comment: This sounds like a bug! Have you reported it at http://launchpad.net/clementine ? If not do so! :)
Comment: @Alvar I did not. I will do it in free time.
Answer: I would like to confirm I'm having exactly the same issue:
Basicly, when I "quit" clementine (by rightclicking the indicator icon and hitting "quit", not just using the close button), the process will remain active, and will keep doing whatever it was doing in the background.
Sometimes the cpu load will simply jump to 25-150% (don't ask me where that 150% comes from... "top" acting strange), and of course, that won't change by "quitting" the application.
Worse yet: start clementine again, and it'll spawn a new process instead of using the existing one! That second process can be extremely cpu-consuming as well.
(@nitstorm 's comment) There is nothing on the interface indicating that clementine is doing anything in the background.
Now I found a solution to this problem: according to http://code.google.com/p/clementine-player/issues/detail?id=2088 , it looks like it's a bug due to compatibility issues between clementine and the nvidia drivers.
One of the bug reports has posted the following command:
<code>Exec=env __GL_NO_DSO_FINALIZER=1 clementine
</code>
I can confirm after a few tests, the above command fixes the issue.
To make life easier in ubuntu, you can change the clementine command in the menu editor.
--
EDIT: In the menu editor, it seems you can't just use the command, so I made a script like this:
<code>#!/bin/bash
Exec=env __GL_NO_DSO_FINALIZER=1 clementine
</code>
Saved as clementine.sh (don't forget to "chmod 755" the script to make it executable), and linked the Clementine menu entry to this script instead of the default command.
Works like a charm now, even when started from the dash instead of the launcher (if you have clementine set as default for music).


Is it possible to manage R sessions?

Question: Is it possible to manage R sessions, as in:

Connect your R console to an existing R session process?
Can two R sessions transfer data to one another?

One might desire this in the following likely scenario:

You're happily working on your R project and have generated data that took 3 hours to compute.
You decide to save your workspace in the case of a technical issue.
Upon saving your Rstudio decides to hang for eternity, however, leaving the R session unaffected.

In this scenario, you would want to

Connect to the R session with a terminal to retrieve your data anyway.
Setup another new R session that continuously synchronizes with the existing R session as a backup session.

Is it possible?
Answer:
Connect your R console to an existing R session process?

Not possible.

Can two R sessions transfer data to one another?

Yes, there are multiple ways to do this. The general keyword for this is "inter-process communication". You can use files, named pipes or sockets, for example. To serialise the data you can use either builtin functions (saveRDS, readRDS) or packages (e.g. feather).
But for your given use-case, there's a much simpler solution:
Never rely on RStudio to save your R session. Instead, do so explicitly by calling saveRDS (or, to save the whole workspace, which I don't generally recommend, save.image). In fact, the general recommendation is to disable the RStudio options for saving and restoring the session!
Make sure that your preferences look like this:

Is it possible to manage R sessions?


How do I show that $\frac a{1 - a^2} + \frac b{1 - b^2} + \frac c{1 - c^2} \ge \frac {3 \sqrt 3}2$

Question: For $0 \lt a, b, c \lt 1$, if $ab + bc + ca = 1$, show that $$\frac a{1 - a^2} + \frac b{1 - b^2} + \frac c{1 - c^2} \ge \frac {3 \sqrt 3}2.$$
I want to use trigonometric substitution:
For the angles $A, B, C$ of any acute triangle, $$\tan A + \tan B + \tan C = \tan A \tan B \tan C,$$ $$\frac 1{\tan A \tan B} + \frac 1{\tan B \tan C} + \frac 1{\tan C \tan A} = 1.$$
Also, $\tan A, \tan B, \tan C \gt 0$. So I substitute $a, b, c$ for $\frac 1{\tan A}, \frac 1{\tan B}, \frac 1{\tan C}$ respectively. Then the inequality in question becomes $$\frac {\tan A}{1 - \tan^2 A} + \frac {\tan B}{1 - \tan^2 B} + \frac {\tan C}{1 - \tan^2 C} \le -\frac {3 \sqrt 3}2.$$
Here $A, B, C \not = \frac {\pi}4$ since $a, b, c \not = 1$.
By the trigonometric identity $\tan 2A = \frac {2 \tan A}{1 - \tan^2 A}$, we have
$$\tan 2A + \tan 2B + \tan 2C \le -3 \sqrt 3,$$
where $0 \lt A, B, C \lt \frac {\pi}2$, $A, B, C \not = \frac {\pi}4$, and $A + B + C = \pi$.
How do I proceed?
Edit: The restriction $a, b, c \lt 1$ was added after the question had received some answers, thanks to Michael Rozenberg, who pointed out this mistake.
Answer: hint:  Lets use $a = \tan\left(\frac{A}{2}\right)$. You can define $b, c$ similarly, then your inequality becomes: $\tan(A) + \tan(B) + \tan(C) \geq 3\sqrt{3}$, with $0 < A,B,C < \dfrac{\pi}{2}$ and $A+B+C = \pi$. And this inequality is standard result of convexity of $\tan(x)$ over $\left(0,\frac{\pi}{2}\right)$.
Comment: Thanks a lot! Still another question: Can this inequality be proved from the mean inequality? Because this exercise actually appears at the end of a chapter introducing the AM-GM bound.
Comment: I think you can.
Comment: But how, then? My primary intuition was to use the AM-GM bound but I just cannot see how. Can you give me a hint or something?
Comment: Sure. I am working on it.
Answer: It's obviously wrong! Try $a=1.01$ and $b=c=\sqrt{2.0201}-1.01$.
Comment: Since you are giving an answer that disagrees with both the Question and the two other posted Answers, you might help your Readers follow your objection more easily by spelling out the computation.
Comment: @hardmath $\sum\limits_{cyc}\frac{a}{1-a^2}-\frac{3\sqrt3}{2}=-51.8567...$ for my counterexample.
Comment: Okay, my arithmetic (I made a Google Sheet) gives $-49.25865721$ for the expression that is supposed to be bounded below, but the sum $ab+bc+ca$ does come out to be $1$.  So I agree with the basic conclusion.
Comment: @hardmath I think your are wrong with $-49.25...$
Comment: @hardmath I wrote $\frac{3\sqrt3}{2}$ before and if you got another number so it's your mistake  and it's not my mistake.
Comment: Put it this way: Since I got $\frac{a}{1-a^2} + \frac{b}{1-b^2} + \frac{c}{1-c^2} = −49.25865721$, this is the expression that is supposed to be bounded below by $\frac{3\sqrt{3}}{2}$. If we now subtract $\frac{3\sqrt{3}}{2}$, we get $−49.25865721 - 2.59807621135 = -51.8567334214$.  It matches your figure, just as you wrote the subtraction.
Comment: Note that there was a comment, now removed, by someone else who thought that $ab + bc + ca = 1$ was not true with your example.  The point I was making there is that it is true.
Comment: Maybe I missed some restrictions to $a, b, c$. And since you've provided your counterexample, the proofs provided ought to be wrong. Can you point out where the wrong step is and how can I refine my question?
Comment: Maybe adding $a, b, c \lt 1$ will do? Okay, I just noticed that in the trigonometric substitution it is assumed that $a, b, c \lt 1$, since $a = \tan \frac A2 \lt \tan \frac {\pi}4 = 1$, where $0 \lt A \lt \frac {\pi}2$. I'll edit it. Thank you @MichaelRozenberg. But actually I think this should posted as a comment instead of an answer...
Comment: @YuxiaoXie:  That is the restriction I suspect is needed (so $a,b,c \in (0,1)$).  But I would defend Michael's posting this as an Answer, because it does settle your original framing of the Question (I have no problem with your adjusting the problem to take account of Michael's observation).
Answer: We can prove $S=\sum\tan A=\prod\tan A$
Using AM GM inequality if $\tan A,\tan B,\tan C\ge0,$ $$\dfrac{\sum\tan A}3\ge\sqrt[3]{\prod\tan A}$$
$$\iff\dfrac S3\ge\sqrt[3]S\implies\left(\dfrac S3\right)^3\ge S\iff S^2\ge27$$ as $S\ne0$
Can you take it from here?
Answer: If you only want to prove it with AM-GM, I will give one proof using AM-GM and Cauchy-Schwarz.
Note that the given condition implies that $a+b+c\geq\sqrt 3$. In addition, I will use the following two inequalities. $$(a+b+c)(ab+bc+ca)\leq a^3+b^3+c^3+6abc$$ and $$abc\leq\big(\dfrac{ab+bc+ca}{3}\big)^{\frac{3}{2}}.$$ Now,
$$\sum\limits_{a,b,c} \dfrac{a}{1-a^2}\sum\limits_{a,b,c} a(1-a^2)\geq (a+b+c)^2.$$ But $\sum\limits_{a,b,c} a(1-a^2) = (a+b+c)(ab+bc+ca)-a^3-b^3-c^3\leq abc\leq \dfrac{6}{3\sqrt 3}=\dfrac{2}{\sqrt 3}$. These two combined together implies that $$\sum\limits_{a,b,c} \dfrac{a}{1-a^2}\geq\dfrac{(a+b+c)^2}{\dfrac{2}{\sqrt 3}}\geq\dfrac{3 \sqrt 3}{2}.$$
 The first inequality is called Schur's inequality.
EDIT.
Actually an even easier solution is obtained by using $$\dfrac{a}{1-a^2}+\dfrac{9}{4}a(1-a^2)\geq 3a,$$ by AM-GM. Thus, $\sum\limits_{a,b,c} \dfrac{a}{1-a^2}\geq\dfrac{3}{4}\sum\limits_{a,b,c} a+\dfrac{9}{4}\sum\limits_{a,b,c} a^3\geq\dfrac{3}{4}\cdot\sqrt 3 + \dfrac{9}{4}\cdot\dfrac{1}{\sqrt 3} = \dfrac{3 \sqrt 3}{2}$. That $a+b+c\geq\sqrt 3$ and $a^3+b^3+c^3\geq\dfrac{1}{\sqrt 3}$ are trivial from the given condition.


How to replace a particular field in a file based on the content of another field?

Question: I have a file with the following format:
A 485C72F95C72E15C EXTERNAL
B CC32480A3247F84A SYSTEM
C EC2A63F12A63B76C EXTERNAL

I want to supply the letter in the first column using the value of the variable 'letter', and replace the value in the second column with a value I supply in the variable 'id'. The third column may or may not differ or match in any case. The first and second columns will never contain spaces or special characters.
I've tried to use sed, but my sed-fu is not strong. I came up with this:
letter=A
id=MYNEWIDSTRING
sed "/$letter /s/[^ ]*/$id/2"

The output is:
A MYNEWIDSTRING EXTERNAL
B MYNEWIDSTRING SYSTEM
C EC2A63F12A63B76C EXTERNAL

The id is replaced in two lines, I'm assuming this is due to 'A ' being matched at the end of the original id string.
I know to use sed -i to edit the file inplace, but not doing it yet, as my command is still a bit dodgy.
Where have I gone wrong, or should I be using a different method?
Answer: Anchor it (^ is start of line) so that the A is only matched if it's the first character:
$ letter=A; id=MYNEWIDSTRING; sed "/^$letter /s/[^ ]*/$id/2" file
A MYNEWIDSTRING EXTERNAL
B CC32480A3247F84A SYSTEM
C EC2A63F12A63B76C EXTERNAL

by the way, if you want to pass variables to sed but you need strong quoting remember you can turn quoting on and off while adding double quotes for the variables - ugly but probably best practice in general:
sed '/^'"$letter"' /s/[^ ]*/'"$id"'/2'

Comment: Oh what an anchor I am! So simple! I was almost there!
Comment: ^_^ thanks for kindly not quite getting there and thus giving me an excuse to play with `sed`
Comment: The quoting stuff is very useful too, I always feel worried about unquoted variables!
Comment: me too haha I'm sure I err on the side of overquoting
Answer: Anytime you are dealing with structured data, I'd reach for awk or perl rather than sed.
For example
awk -v letter="A" -v id="MYNEWIDSTRING" '$1 == letter {$2=id}1' file
A MYNEWIDSTRING EXTERNAL
B CC32480A3247F84A SYSTEM
C EC2A63F12A63B76C EXTERNAL

or
perl -alne '
  BEGIN{$letter = shift; $id = shift;}
  print join " ", $F[0], $F[0] eq $letter ? $id : $F[1], @F[2..$#F]
' 'A' 'MYNEWIDSTRING' file

Newer versions of GNU awk have a -i (--in-place) flag; in others you would need to use an explicit temporary file; perl should have a -i in any case.
Comment: Nice, I've been using `awk` to read the data from the file, and hadn't realised that it was useful for editing too.
Comment: I'm on 14.04, turns out my (g)awk is version 4.0.1 and this was introduced in version 4.1.0. Useful to know for future reference though.


Why does $\cos(\pi x)$ approach $0^-$, as $x\to{\frac{1}2}^-$

Question:
In problem 220, I understand the rest of the solution except that I don't know why $\cos(\pi x)$ approaches to $0$ from the left, making the solution $-\infty$. I have seen a few problems like this, where it doesn't make sense to me with the unit circle definition. Thank you!
Comment: As $x\to 0.5+$, we have $\pi x \to (\pi/2)+$.  Now look at the graph of cosine.  It is zero at $\pi/2$, and negative just to the right of $\pi/2$.  Hence $\cos(\pi x)\to 0-$.
Answer: It is actually approaching from the right. When it says ${\frac12}^+$ is means you approach $1/2$ from the right, that is with values grater than $1/2$. So you are approaching $\pi/2$ from the right; and to the right of $\pi/2$ the cosine is negative; so your denominator goes to zero from the left (i.e., with negative numbers) and so the quotient goes to $-\infty$.
Answer: Here's a plot of $\cos(\pi x)$.
We know that $\cos\left( \frac{\pi}{2}\right) = 0$.  When we are just to the right of 1/2, $\cos(\pi x)$ is a very small negative number.  A finite, positive, non-zero number $\left(\frac{x^2+1}{x}\right)$ divided by a very small negative number gives you a very large negative number.  So, as that "very small negative number" goes to zero, your result will go to negative infinity.


Extract One Set of Gene Coordinates From a File Containing Several Sets of Gene Coordinates

Question: Given the following file:
NW_022983499.1  RefSeq  CDS 6883    7503    .   +   0   ID=cds-XP_033376633.1
NW_022983500.1  RefSeq  CDS 5353    5898    .   +   0   ID=cds-XP_033376630.1
NW_022983500.1  RefSeq  CDS 6033    7994    .   +   0   ID=cds-XP_033376630.1
NW_022983502.1  RefSeq  CDS 5391    5543    .   +   0   ID=cds-XP_033376626.1
NW_022983502.1  RefSeq  CDS 5591    5673    .   +   0   ID=cds-XP_033376626.1
NW_022983502.1  RefSeq  CDS 5782    5895    .   +   1   ID=cds-XP_033376626.1
NW_022983502.1  RefSeq  CDS 5937    6424    .   +   1   ID=cds-XP_033376626.1
NW_022983502.1  RefSeq  CDS 6478    6680    .   +   2   ID=cds-XP_033376626.1
NW_022983502.1  RefSeq  CDS 6739    6858    .   +   0   ID=cds-XP_033376626.1
NW_022983502.1  RefSeq  CDS 6926    7408    .   +   0   ID=cds-XP_033376626.1
NW_022983504.1  RefSeq  CDS 5478    5513    .   -   0   ID=cds-XP_033376620.1
NW_022983504.1  RefSeq  CDS 5353    5419    .   -   0   ID=cds-XP_033376620.1
NW_022983504.1  RefSeq  CDS 5161    5297    .   -   2   ID=cds-XP_033376620.1
NW_022983504.1  RefSeq  CDS 5059    5115    .   -   0   ID=cds-XP_033376620.1
NW_022983508.1  RefSeq  CDS 4415    5392    .   -   1   ID=cds-XP_033376609.1
NW_022983508.1  RefSeq  CDS 4215    4344    .   -   1   ID=cds-XP_033376609.1
NW_022983512.1  RefSeq  CDS 2650    2831    .   +   0   ID=cds-XP_033376596.1
NW_022983512.1  RefSeq  CDS 2890    3112    .   +   1   ID=cds-XP_033376596.1
NW_022983512.1  RefSeq  CDS 3163    3267    .   +   0   ID=cds-XP_033376596.1

I would like to extract one set of coordinates (from lower to higher numerical value) corresponding to the IDs present in column 9, so as to obtain the following file:
NW_022983499.1  RefSeq  CDS 6883    7503    .   +   0   ID=cds-XP_033376633.1
NW_022983500.1  RefSeq  CDS 5353    7994    .   +   0   ID=cds-XP_033376630.1
NW_022983502.1  RefSeq  CDS 5391    7408    .   +   0   ID=cds-XP_033376626.1
NW_022983504.1  RefSeq  CDS 5059    5513    .   -   0   ID=cds-XP_033376620.1
NW_022983508.1  RefSeq  CDS 4215    5392    .   -   0   ID=cds-XP_033376609.1
NW_022983512.1  RefSeq  CDS 2650    3267    .   +   0   ID=cds-XP_033376596.1

Note that in the case of ID=cds-XP_033376630.1 who has a positive value in column 7, I need to select the value of line 2 column 4 5353 and of line 3 column 5 7994.
In contrast, if the value of column 7 is negative, as in ID=cds-XP_033376620.1, the logic gets inverted, I need to select the value of line 14, column 4 5059 and of line 11, column 5 5513
I am specially interested in using AWK (not Perl or Python), to solve this classical bioinformatics problem, and I would appreciate if anyone could point me in the right direction.
Comment: How do you determing the 8th field value to be printed? For example for `ID=cds-XP_033376620.1` 2 of the lines have `0` for the 8th field while one of them has `2` and in the output you print `... 0   ID=cds-XP_033376620.1` - why not `... 2   ID=cds-XP_033376620.1`?
Comment: That is a great question. The file format is GFF3 - a classical bioinformatics file format. Here Column 8: "phase" is strictly defined. BUT, for us, in this particular case, **it does not matter**, we can print "0". In fact it should be "0", because we are converting the file to another file format (BED - another Bioinformatics file format) later, and that column will be lost.
Answer: $ cat tst.awk
$NF != prevKey {
    if ( NR > 1 ) {
        prt()
    }
    min  = $4
    max  = $5
    line = $0
    prevKey = $NF
}
{
    min = ($4 <= min ? $4 : min)
    max = ($4 >= max ? $5 : max)
}
END { prt() }

function prt(   orig) {
    orig = $0
    $0 = line
    $4 = min
    $5 = max
    $8 = 0
    print
    $0 = orig
}

.
$ awk -f tst.awk file
NW_022983499.1 RefSeq CDS 6883 7503 . + 0 ID=cds-XP_033376633.1
NW_022983500.1 RefSeq CDS 5353 7994 . + 0 ID=cds-XP_033376630.1
NW_022983502.1 RefSeq CDS 5391 7408 . + 0 ID=cds-XP_033376626.1
NW_022983504.1 RefSeq CDS 5059 5513 . - 0 ID=cds-XP_033376620.1
NW_022983508.1 RefSeq CDS 4215 5392 . - 0 ID=cds-XP_033376609.1
NW_022983512.1 RefSeq CDS 2650 3267 . + 0 ID=cds-XP_033376596.1

Answer: $ awk 'p9!=$9{if(p0) print p0} !a[$9]++; {p9=$9; p0=$0} END{print p0}' file |
  awk 'NR%2{k=($7=="+")?4:5; v=$k; next} {$k=v}1'

NW_022983499.1 RefSeq CDS 6883 7503 . + 0 ID=cds-XP_033376633.1
NW_022983500.1 RefSeq CDS 5353 7994 . + 0 ID=cds-XP_033376630.1
NW_022983502.1 RefSeq CDS 5391 7408 . + 0 ID=cds-XP_033376626.1
NW_022983504.1 RefSeq CDS 5059 5513 . - 0 ID=cds-XP_033376620.1
NW_022983508.1 RefSeq CDS 4215 5392 . - 1 ID=cds-XP_033376609.1
NW_022983512.1 RefSeq CDS 2650 3267 . + 0 ID=cds-XP_033376596.1

two separate scripts will simplify the logic, first one prints the first and last rows for each key (duplicates if a single line is present).  Second script picks the right values based on the sign.
Answer: another awk (also added printing zeroes for $8 as commented)
> cat tst.awk
$9 == prev {
    $keep = val
    $8 = 0
    row = $0
    next
}

{
    print row
    prev = $9
    $8 = 0
    row = $0
    keep = ( $7=="+"? 4: 5 )
    val = $keep
}

END {
    print row
}

Output:
> awk -f tst.awk file

NW_022983499.1 RefSeq CDS 6883 7503 . + 0 ID=cds-XP_033376633.1
NW_022983500.1 RefSeq CDS 5353 7994 . + 0 ID=cds-XP_033376630.1
NW_022983502.1 RefSeq CDS 5391 7408 . + 0 ID=cds-XP_033376626.1
NW_022983504.1 RefSeq CDS 5059 5513 . - 0 ID=cds-XP_033376620.1
NW_022983508.1 RefSeq CDS 4215 5392 . - 0 ID=cds-XP_033376609.1
NW_022983512.1 RefSeq CDS 2650 3267 . + 0 ID=cds-XP_033376596.1


GFCI circuit for hot tub tripping after move

Question: Good day,
We had a fully functional hot tub in our garage (don't ask).
We moved it outside on to a patio of cement patio blocks.
I tapped off the sub panel in the garage that the tube used to be hooked to.
I ran 80' of #6-4 wire out to another GFCI sub panel outside the house within sight of the tub.
When I energize the breakers they both pop
I have confirmed that the common and ground are only bonded in the main panel.
If I separate them in the main panel everything works but you can get bit if you touch the water while your barefooted.
I'm attaching a diagram of what I have wired.

MyWiringDiagram
I'm stumped, I need some ideas please.!
Comment: First off, you did NOT need another GFI near the tub, just a means of disconnect. Second, you cannot use cable (your "6/4") for the outside portion of the wiring to a hot tub. You need individual insulated conductors in conduit.  The drawing looks basically correct but it's impossible to say from here why you are having a problem. Could be so many things. From your description and story I think it is in your best interest to have a professional check it out. The consequences are just too great to be messing around if you're not 100% sure of what you're doing.
Comment: Are you saying you get a shock touching the water? If so, I'd say you have a ground fault. In which case the breakers are working as designed.
Comment: "If I separate the breakers it works." You should be using a linked breaker. My best guess is that the legs (phases, aka the two incoming live wires) are reversed at some point along the line. Your tub is either broken, your grounding is faulty or some of the *many* other connections are questionable. Don't forget to check all the incoming lugs for tightness, at each sub-panel.
Answer: The correct answer is to call an electrician.....and get rid of that second GFCI.  If you are on a forum wondering why you are getting shocked when touching the water, you really shouldn't be doing that electrical youself. Call a professional and have it done right.
Comment: +1,000,000. If you're getting shocked, and you have to ask, you should not be considering trying to fix it. Stop NOW and get someone who knows what they're doing to deal with it.