Theorem of Arzelà-Ascoli

Question: The more general version of this theorem in Munkres' 'Topology' (p. 290 - 2nd edition) states that
Given a locally compact Hausdorff space $X$ and a metric space $(Y,d)$; a family $\mathcal F$ of continuous functions has compact closure in $\mathcal C (X,Y)$ (topology of compact convergence) if and only if it is equicontinuous under $d$ and the sets
$$ \mathcal F _a = \{f(a) | f \in \mathcal F\} \qquad a \in X$$
have compact closure in $Y$.
Now I do not see why the Hausdorff condition on $X$ should be necessary? Why include it then? Am I maybe even missing something here (and there are counterexamples)?
btw if you are looking up the proof: Hausdorffness is needed for the evaluation map $e: X \times \mathcal C(X,Y) \to Y, \, e(x,f) = f(x)$ to be continuous. But the only thing really used in the proof is the continuity of $e_a: \mathcal C(X,Y) \to Y, \, e_a(f) = f(a)$ for fixed $a \in X$.
Cheers, S.L.
Comment: If we omit Hausdorff, what is the definition of local compactness? Every point has a compact neighbourhood, every point has an open neighbourhood with compact closure, every point has a neighbourhood base of open sets with compact closure? , etc. These are the same for Hausdorff spaces, not in general. This makes the combination locally compact + Hausdorff very common, and it also implies Tychonoff (completely regular), ensuring that  there are continuous functions to $\mathbb{R}$ (e.g.) at all. If looking for counterexamples, I think indiscrete spaces will work, if you allow those as loc.cpt.
Comment: @t.b. When you look carefully at Dugundji proof, you notice that it used the compact-open topology where compact subspaces are all suppose to be Hausdorff by definition ...
Comment: @Henno: By Munkres' definition a space is locally compact if for every point $x$ there is a compact set containing a neighborhood of $x$. (which is a bit strange for a local property) Assuming the space to be Hausdorff, this condition indeed gets much nicer. @Theo: Thanks for the reference. I'll have a look at it.
Comment: The Hausdorff condition is not necessary, you can also drop local compactness altogether. A proof can be found e.g. in Dugundji, Topology, p.267. I removed my previous comment because I managed to confuse myself.
Comment: @Theo: Dugundji only seems to proof one direction. I don't believe local compactness can be dropped for the other implication (would be very strange). Munkres original statement is something like: X a space, Y metric then the two condiditions on the family imply compactness. The converse is true if X is loc. cpt. H'dorff.
Comment: You're right. On the other hand, the direction proved by Dugundji is the more important one and it's good to know that no local compactness is needed for that.
Comment: While looking up something else in Kelley's *General Topology* I stumbled over his section on Arzelà-Ascoli. He proves converses in various degrees of generality (e.g. replacing Hausdorff by regularity & equicontinuity by something he calls *even continuity*). E.g. Theorem 21 on p. 236 states that a family of continuous functions from a regular locally compact space to a regular Hausdorff space is compact in the compact-open topology if and only if 1. it is closed, 2. the pointwise evalutations have compact closure and 3. it is evenly continuous. Maybe that helps answering your question.
Comment: @Theo: Thank you for this reference. I will make sure to have a look at it! :)
Answer: I think this question has been already been answered through the helpful comments. So thanks to Henno Brandsma and t.b.! This is just to finally tick it off.
My conclusion: It seems that $X$ being Hausdorff is rather a matter of convenience (maybe to avoid issues with the definition of local compactness for non-Hausdorff spaces, as pointed out in the comments), than a necessary condition.
Also this version of the theorem seems quite general enough for most uses.

Theorem of Arzelà-Ascoli


onActivityResult only called once

Question: I have the following Activity sequence in a folder picker part of an app:
Activity A starts B. B then starts instances of itself that stack as the user goes deeper into the folder tree. Whenever an instance of B is completed (folder chosen), it and all the preceding Bs should finish and A should be shown again, with the propagated result. If the user backtracks, the preceding Bs should not finish, since the user should be able to go back and forth between folder subtrees.
I'm trying to accomplish this by using startActivityForResult, both from A to B and then for each new instance of B. When the user finishes an instance B, I use setResult and want to check it in each preceding instance's onActivityResult method. If it's RESULT_OK, I set the result again and finish that instance, until all of them are finished in a cascading sequence and A is shown again with the result.
The sequence works as long as I go A => B(1) => B(2) => B(3) and finish, without backtracking in the B part.
However, if I go A => B(1) => B(2) => back to B(1) => B(3) and finish, onActivityResult is only called in B(1) when going back from B(2) the first time, not when I later go back to it when finishing from B(3). B(1) is simply resumed when going back from B(3) in this sequence. This breaks the cascading finish sequence.
Why is onActivityResult only called once for instance B(1)? Shouldn't it be called each time a child activity sets a result and finishes?
Here's some code:
=== Activity A:
Starting the first B instance:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivityForResult(intent, RequestCodes.ActivityB);

Receiving the final B result:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if(resultCode == RESULT_OK){
    ...
  }
}

=== Activity B:
Starting new child B from itself:
Intent intent = new Intent(ActivityB.this, ActivityB.class);
startActivityForResult(intent, RequestCodes.ActivityB);

Setting the result when choosing a folder:
Intent result = new Intent();
result.putExtra(...);
setResult(Activity.RESULT_OK, result);
finish();

Receiving the child B result in each parent B instance (which is only called the first time in B(1) for some reason):
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if(resultCode == RESULT_OK){
    setResult(Activity.RESULT_OK, data);
    finish();
  }
}

Thanks in advance.
Comment: In the last method you should instead `setResult(..., data)` Is that a typo or a bug?
Comment: That's a typo here, yeah, it's data in the code. Thanks.
Answer: This is a horrible architecture! You shouldn't create multiple instances of B when traversing a tree. Eventually you will run out of memory! You should use a single instance of your Activity and when the user moves up or down in the tree you should just change the data that you display in the Activity. You should have an internal data model that describes the tree and you only need to remember what node in the tree you are currently displaying. If you also want to support the user going back (by using the BACK button), you can create your own stack (not a stack of activities, but just a stack of tree node references) that you can use to determine which node of the tree to go back to from the current node. This is a simple data management problem and your architecture has forced this to become a View management problem.
Comment: Thanks for your answer, you're absolutely correct. I will choose another architecture in the final app. Though I'm still interested to know why onActivityResult is only called once in the sequence.

onActivityResult only called once


How to push a UI update to the mean thread in Objective-C

Question: I have a class called "Test" that has a property named "counter". When I create an instant of Test, I use CACurrentMediaTime() to update counter on an alternative queue using NSOperationQueue.
Here is my viewController:
<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTimerLabel) name:@"timerLabelUpdate" object:nil];

- (void) updateTimerLabel {
        [self->_timerLabel setIntValue:[self->_test counter]];
    });
</code>
The problem is .. on my viewController I keep getting this error message:

-[NSControl setIntValue:] must be used from main thread only

Does anyone know what I should do here?
Answer: The error message is telling you that the UI must be updated on the main thread.
You simply need to push the update method updateTimerLabel to the main thread:
<code>dispatch_async(dispatch_get_main_queue(), ^{
        [self->_timerLabel setIntValue:[self->_test counter]];
    });
</code>
Let me know if this helps.


converting a string to a class

Question: I'm trying to move between one Activity to another based upon some user input.
I'm trying to use:
String myClass = "some_user_input.class"
Intent myIntent = new Intent(getApplicationContext(), myClass);
startActivity(myIntent);

...to move from one activity to another.
I can do this ok where I reference my new activity directly in the hard code and don't try to compile it from text, (i.e. classA.class), however I want to be able to build my Intent by passing it some string compiled by the user.
For example if the user inputs B in an edittext, I want to go to classB.class
If the user inputs Z, I want to go to classZ.class.
Is there any way I can compile the class I want to go to using strings which I then convert to a class?
Thanks in advance!
Comment: Try [Classloader.loadClass](http://d.android.com/reference/java/lang/ClassLoader.html)
Comment: do you have multiple packages
Answer: The reflection mechanism allows you to do it:
String myClass = "some_user_input";
Class<?> clazz = Class.forName(myClass);
Intent myIntent = new Intent(getApplicationContext(), clazz);

Note that those classes should be included in the android manifest XML.
Also note that I didn't handle the exception in this example :)
Comment: I tried your code. Its throwing classnotfoundexception. Any idea why?
Comment: It throws an exception because you need to add the full package to the String like `us.foobar.package.some_user_input`
Answer: This is my solution using  Class.forName() method:
String myClass = "foo.class";
Intent i = new Intent(getApplicationContext(), Class.forName(myClass));
startActivity(i);

converting a string to a class


Append tr in table in IE

Question: I have a table structure:

   id	name

I am adding new row with simple Javascript like this:
var itemsContainer = dojo.byId('tbodyId');
itemCount++; //it will give id to tr i.e. trId2

var newItemNode = document.createElement('tr');
newItemNode.setAttribute("id", 'trId' + itemCount);
newItemNode.innerHTML ='id	anotherName	';

itemsContainer.appendChild(newItemNode);

All works fine in Firefox but row is not appended in IE. New table after it in Firefox becomes:

   id	name

   id	anotherName

I saw other codes and help. I only want one tbody in this table with simple Javascript no jQuery.
Answer: There are special functions for creating table cells ( and rows ) eg - insertRow for rows and insertCell for cells - it works in all browsers
var newItemNode = itemsContainer.insertRow( itemsContainer.rows.length - 1 );
newItemNode.setAttribute("id", 'trId' + itemCount);

var cell = newItemNode.insertCell( 0 );
cell.innerHTML = 'id';

...
PS. I think DOJO Framework have something for inserting rows and cells
Comment: you are right insertRow for rows and insertCel works for all browsers.
Answer: First off, this jsfiddle works fine in FF6 & IE8
Make sure that your real html has the proper markup. Your example shows a closing tbody element without the slash

   id	anotherName

IE is inconsistant with its acceptance of bad markup.
In addition, code like this:
var newItemNode = document.createElement('tr');
newItemNode.setAttribute("id", 'trId' + itemCount);
newItemNode.innerHTML ='id	anotherName	';

Is exactly the sort of code that toolkits like dojo (and its smarter cousin, jQuery) are built to avoid. I suspect the code for creating a new row are different in the version of IE you're testing on.
Comment:  is closed in my code. It was a typo in question. Code I am checking is same.
Answer: try this

   id	name

<input type="button" value = "heihei" onclick = "kk();"></input>

Append tr in table in IE


Can a (directed) tree contain crossing lines?

Question: Is the graph below a (directed) tree in the mathematical sense, and if it is, is there any precise definition that distinguishes crossing from non-crossig trees?

I think it should be a tree since it is acyclic and connected, but the crossing edges $B - F$ and $C - E$ make me unsure about it - it doesn't look like a "classical" tree, intuitively (presumably because by "classical" tree, I have directed and rooted trees in mind, although I am aware that undirected trees exist, too), and I can not recall having seen such a graph referred to as 'tree' ever before.
Which graph-theoretical classification would apply to this object? Are the distinctions directed vs. undirected, and ordered vs. unordered of relevance here?
Edit:
I am thinking that ordering might be of relevance because if you were to "untangle" the lines and align the nodes in such a way that node $F$ is right next to $D$ and $E$ is right next to $G$, the linear order of nodes would be a different one, and that this would make it different tree. Is this correct?
Answer: As a graph this is the same as the graph where you "uncross" the vertices. Recall the definition of a graph as a set of nodes and a set of edges - it says nothing about the embedding, or the way you draw it.
Your picture is of a tree that is not embedded in the plane. (Though in fact your picture is ambiguous, because the lines connecting vertices do not need to be straight, unless you insist on a piecewise linear embedding into the plane). Trees are always planar, however, which means it is possible to "fix" the drawing so that it is an embedding.
The upshot is that your drawing reflects something about the "embedding" of (the geometric realization) of the graph into the plane. It is not a property of the graph. (The geometric realization refers to the construction by which you build a topological space from a graph - recall, a set of nodes and a set describing the edges - by putting a point for each node and connecting them with intervals if there is an edge between them...)
Comment: What will be useful is the result " that trees are always planar."
Comment: This is helpful. So if I understand correctly, the "crossing" is not something that happens on the level of the graph itself but only on the level of its geometrical realization? Is there any terminology or classification which addresses this way of planar embedding, or is the crossing something that can not really be captured by precise definitions? I'm curious whethere there is any formal distinction between non-crossing and crossing geometrical realization.
Comment: @lemontree No, the crossing doesn't happen on the level of the geometric realization. It happens when you map the realization to the plane. Graph (Vertices, Edges) -> Geometric Realization (Topological Space X) -> Drawing in plane (continuous map from f : X to R^2). For a well drawn graph, $f$ must be a topological embedding (meaning, injective and homeomorphic onto its image). You can detect crossings by studying $f$, for example, in your picture there is a point $p \in R^2$ with $f^{-1}(p)$ consisting of two points in the interior of distinct edges...


Creating cron jobs for different services in app engine

Question: I am trying to create cron jobs for App Engine in Google Cloud Platform. But unfortunately, whenever I try to deploy a cron job, it is also overwriting the other job. Also, they are present in different directories. Please find the CRON.yaml below
cron:
 - description: "sample1"
   url: /
   target: sample1
   schedule: everyday 08:10
   timezone: Asia/Singapore

cron:
 - description: "sample2"
   url: /
   target: sample2
   schedule: everyday 08:00
   timezone: Asia/Singapore

Both are different cron.yaml files. But when I deploy using
gcloud app deploy --project <<project>> cron.yaml , it is overwriting.
Please advise.
Answer: You have 2 solutions

Use only one file. Indeed, when you upload CRON description, it overrides all the existing. It's not possible to perform an append. Cron is a yaml list, do this

cron:
 - description: "sample1"
   url: /
   target: sample1
   schedule: everyday 08:10
   timezone: Asia/Singapore
 - description: "sample2"
   url: /
   target: sample2
   schedule: everyday 08:00
   timezone: Asia/Singapore

Currently, AppEngine feature are extracted to be available for all other Google Cloud product. By the way, Memcache is became MemoryStore and Cron is became Scheduler (Endpoint is under work for being extracting). So, you can use Cloud Scheduler for performing your cron. You don't have a YAML file to define, you have to set up a new Google Cloud service by GUI or command line. Be careful, retry policies aren't available by GUI, only with CLI
Comment: Wow thanks :) it worked...but looks so strange, that separate yaml file overwrites the other. But combining in one yaml works like a charm


Get Status Code from an Ajax request on the site in PhantomJS

Question: We are using PhantomJS to access a internal website of our company and take a screenshot.
The script is basically one of the official examples of PhantomJS with an added waitTime variable
(https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js)
var page = require('webpage').create(),
    system = require('system'),
    address, output, size;

//waitTime is how long to to wait for kibana and the data to load in millis.
//Increase this if your queries appear incomplete in your PDFs. 10s seems to work for me.
var waitTime = 10 * 1000;

if (system.args.length < 3 || system.args.length > 5) {
    console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
    console.log('  paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
    console.log('  image (png/jpg output) examples: "1920px" entire page, window width 1920px');
    console.log('                                   "800px*600px" window, clipped to 800x600');
    phantom.exit(1);
} else {
    address = system.args[1];
    output = system.args[2];
    // Uncomment the following line to login. Replace user:pass with your username and password.
    //page.customHeaders={'Authorization': 'Basic '+btoa('user:pass')};
    page.viewportSize = { width: 1280, height: 720 };
    if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") {
        size = system.args[3].split('*');
        page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' }
                                           : { format: system.args[3], orientation: 'portrait', margin: '1cm' };
    } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") {
        size = system.args[3].split('*');
        if (size.length === 2) {
            pageWidth = parseInt(size[0], 10);
            pageHeight = parseInt(size[1], 10);
            page.viewportSize = { width: pageWidth, height: pageHeight };
            page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
        } else {
            console.log("size:", system.args[3]);
            pageWidth = parseInt(system.args[3], 10);
            pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
            console.log ("pageHeight:",pageHeight);
            page.viewportSize = { width: pageWidth, height: pageHeight };
        }
    }
    if (system.args.length > 4) {
        page.zoomFactor = system.args[4];
    }
    page.open(address, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            window.setTimeout(function () {
                page.render(output);
                phantom.exit();
            }, waitTime);
        }
    });
}

The website we are accessing is running a JavaScript, that is doing a request to a database. However this request can, based on the given query, take very long (up to 10 minutes).
So what we want to do is instead of providing a static 10 minute wait time, we want to extract the status code from the JavaScript that is run on the accessed website and if it goes to 200 , the script should take the "screenshot".
Our problem is that we don't know how to get information from the website itself. (How can we overcome that "bridge" between the used PhantomJS script and accessed website?)
Answer: That is what page.onResourceReceived is for.
page.onResourceReceived = function(response) {
    if (response.stage === "end" && response.url.indexOf("/longrunningrequest") !== -1) {
        setTimeout(function(){
            if ("200" === (""+response.status)) {
                page.render("screenshot_200.png");
            } else {
                page.render("screenshot_other.png");
            }
            phantom.exit();
        }, 1000);
    }
};
page.open(address);

You can determine the specific response that should trigger a screenshot from the URL. I've used a simple string match, but you can also use Regular Expressions and whatnot.
Of course, this would look different if you're using PhantomJS through one of the available bridges from node.js.


Analyze data using python

Question: I have a csv file in the following format:
30  1964    1   1
30  1962    3   1
30  1965    0   1
31  1959    2   1
31  1965    4   1
33  1958    10  1
33  1960    0   1
34  1959    0   2
34  1966    9   2
34  1958    30  1
34  1960    1   1
34  1961    10  1
34  1967    7   1
34  1960    0   1
35  1964    13  1
35  1963    0   1

The first column denotes the age and the last column denotes the survival rate(1 if patient survives 5 years or longer;2 if patient died within 5 years)
I have to calculate which age has the highest survival rate. I am new to python and I cannot figure out how to proceed. I was able to calculate the most repeated age using the mode function but I cannot figure out how to check one column and print the corresponding other column. Please help.
I was able to find an answer where I had to analyze just the first row.
import csv
import matplotlib.pyplot as plt
import numpy as np

df = open('Dataset.csv')
csv_df=csv.reader(df)
a=[]
b=[]

for row in csv_df:
    a.append(row[0])
    b.append(row[3])

print('The age that has maximum reported incidents of cancer is '+ mode(a))

Comment: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
Comment: Do some research on CSV scraping with Python, write some code, and come back if you have issues.
Comment: Thank you  Łukasz Rogalski and  jacob-on-stackoverflow
Comment: @Aniket, what is the logic behind determining the survival rate for a age? is it the age with the most number of 1s?
Answer: I am not entirely sure whether I understood your logic clearly for determining the age with the maximum survival rate. Assuming that the age that has the heighest number of 1s have the heighest survival rate the following code is written
I have done the reading part a little differently as the data set acted wired when I used csv. If the csv module works fine in your environment, use it. The idea is, to retrieve each element of value in each row; we are interested in the 0th and 3rd columns.
In the following code, we maintain a dictionary, survival_map, and count the frequency of a particular age being associated with a 1.
import operator

survival_map = {}

with open('Dataset.csv', 'rb') as in_f:
    for row in in_f:
        row = row.rstrip() #to remove the end line character
        items = row.split(',') #I converted the tab space to a comma, had a problem otherwise

        age = int(items[0])
        survival_rate = int(items[3])

        if survival_rate == 1:
            if age in survival_map:
                survival_map[age] += 1
            else:
                survival_map[age] = 1

Once we build the dictionary, {33: 2, 34: 5, 35: 2, 30: 3, 31: 2}, it is sorted in reverse by the key:
sorted_survival_map = sorted(survival_map.items(), key=operator.itemgetter(1), reverse = True)
max_survival = sorted_survival_map[0]

UPDATE:
For a single max value, OP's suggestion (in a comment) is preferred. Posting it here:
maximum = max(dict, key=dict.get)
print(maximum, dict[maximum])

For multiple max values
max_keys = []
max_value = 0
for k,v in survival_map.items():
    if v > max_value:
        max_keys = [k]
        max_value = v
    elif v == max_value:
        max_keys.append(k)

print [(x, max_value) for x in max_keys]

Of course, this could be achieved by a dictionary comprehension; however for readability, I am proposing this. Also, this is done through one pass through the objects in the dictionary without going through it multiple times. Therefore, the solution has O(n) time complexity and would be the fastest.
Comment: Surely, your approach is better. If you have only one maximum, you should use that. If you have multiple max values however, use the code in my latest update.
Comment: Well, you could use count in a similar approach (without importing collections.Counter), however, it will be very inefficient. Look at this answer and comments: http://stackoverflow.com/a/9744274/557022
Comment: I used the following to sort my dictionary:

maximum = max(dict, key=dict.get)
print(maximum, dict[maximum])

However, I have two keys having the same highest values. But the above code is printing just one. How can I print both of them?
Comment: Thanks, I tried and it worked. Is there another way/logic to print the age which occurs the maximum times in the list, without using the 'import counter' statement.
Currently I am using :
counter = Counter(a)
max_count = max(counter.values())
print(list(counter.keys())[list(counter.values()).index(max_count)])

Where 'a' is a list having the first column(age) of the table

Analyze data using python


Linear contraction on a Banach space

Question: Let $X$ be a Banach space with a norm $\|\cdot\|_1$ and $A$ be a linear operator on $X$ such that

$\|A\|_1\leq 1$;
$\|A^m\|_1<1$ for some $m\in \mathbb N$.

Is that true that there is an equivalent norm $\|\cdot\|_2$ on $X$ such that $\|A\|_2<1$? If there exists such a norm, how can it be constructed?
Here for operator we use associated (induced norm): given a norm $\|\cdot\|$ on $X,$
$$
\|B\| :=\sup\limits_{\|x\|=1}\|Bx\|
$$
for any linear operator $B$.
Comment: I can't check it right now, but this paper seems to be addressing related questions: http://www.springerlink.com/content/171683521510x846/
Comment: I'm most likely missing something, but $\| \cdot \|_2 = \frac{1}{2} \| \cdot \|_1 $ seems to be an equivalent norm such that $\| A \|_2 < 1 .$
Comment: @RagibZaman: the norms are given on $X$, so your example gives the same associated operator norm
Comment: Is $A$ invertible?
Comment: @copper.hat not necessary, all the assumptions are in OP
Answer: Let $\|x\|_2 = \|x\|_1+\|Ax\|_1+\dots+\|A^{m-1}x\|_1$, then $\|Ax\|_2 = \|Ax\|_1+\dots+\|A^{m}x\|_1=\|x\|_2+(\|A^{m}x\|_1-\|x\|_1)\le \|x\|_2-\epsilon\|x\|_1\le (1-\epsilon')\|x\|_2$.
Comment: That should be true, thanks!
Comment: Very nice construction.

Linear contraction on a Banach space


gnome-shell has high CPU usage after 18.04 upgrade

Question: Upgraded from 17.10 to 18.04. The gnome shell constantly spikes to >200% cpu usage and is especially bad when heavy interaction with the Xorg window manager occurs (web browsers, vlc media player, etc.). GPU is fine at <2% (GTX 1070 with Nvidia 390 drivers).
Restarting gnome-shell temporarily fixes the issue, but it resumes sporadic behavior after several minutes. When this occurs, the system is barely usable as frame rate dips to <5 fps.
Also tried updating BIOS. No effect.
Any ideas for a solution for restoring system stability?
Comment: Facing the same issue, yet the accepted answer did not solve it, unfortunately. Any other ideas? Is it maybe because I have nvidia AND Intel HD graphics?
Answer: I have updated from 17.10 as well, and I started getting those crazy 5 fps interface lags and high CPU usage by gnome-shell - it helped me to run ubuntu-drivers autoinstall, which fetched and updated nvidia drivers
Comment: That worked like a charm! It appears that for whatever reason the gpu was not being utilized by `gnome-shell` as now gnome stays <=25% cpu and gpu is at a nice 5% avg utilization. Additionally, running `nvidia-smi` shows that `gnome-shell` is actually utilizing the gpu as opposed to before when it just showed Xorg.

Any thoughts on why this fixed it? I already had the 390 drivers installed before (directly from Nvidia's website).
Comment: Yeah, same situation - had 390 drivers installed before (on 17.10), but they didn't work properly with gnome-shell before this command. Don't know why


How do I add a snippet programmatically?

Question: We have some custom snippets we provide as part of our VS Code extension via key bindings and a snippets json file:
{
  "key": "ctrl+shift+i",
  "mac": "cmd+shift+i",
  "command": "editor.action.insertSnippet"
},

...
"snippets": [
  {
    "language": "xml",
    "path": "./snippets/xml.json"
  }
]

We would like a button to add one particular snippet to the editor at the current cursor position.
How do I programmatically I invoke the part of "editor.action.insertSnippet" after the user has selected the snippet?
Answer: I posted this issue on the vscode repo.
jrieken responded with the following reply:

The insertSnippet-command accepts an argument which is either the name of a snippet or a snippet itself. So, either { snippet: "console.log($1)$0"} for an inline snippet or { langId: "csharp", name: "myFavSnippet" } referencing an existing snippet.
Comment: So it's been over a year now, and the docs aren't updated with that information. I tried with the `{langId: 'blah', name: 'mySnippet'}` and either I'm doing something wrong (entirely possible), or it doesn't actually support that option. Also that conversation got locked so I couldn't comment there.
Comment: @joshea As I understand it, the language identifiers need to be from this [list](https://code.visualstudio.com/docs/languages/identifiers#_known-language-identifiers). Also, you might want to make sure _mySnippet_ is already defined. If it is not, [this](https://code.visualstudio.com/api/language-extensions/snippet-guide) might be helpful in understanding how to create it.
Comment: Yeah I have all that, and the actual `langId` I had was `javascriptreact`, which is on that list. I'll just triple check that the snippet is defined. Knowing me I probably have a typo in the name or something.
Comment: @joshea I also had no luck inserting an existing snippet programmatically using e.g. `editor.insertSnippet({ langId: "javascript", name: "module_exports" }` - though I might have the syntax wrong. It seems a string is required like the doco says. Sure, the `"editor.action.insertSnippet"` keybinding command takes those fancy `"langId"` and `"name"` args but not `editor.insertSnippet`. However, as @Mike-Lischke suggested, I managed to programmatically do it using e.g. `vscode.commands.executeCommand("editor.action.insertSnippet", { langId: "javascript", name: "For Loop" })`.
Answer: You can run any registered command via vscode.commands.executeCommand. See also the vscode namespace API.
Comment: Thank you, Mike. What is the command for inserting a _selected_ snippet (that does not involve the user picking one)?


What are the pros and cons with an overflowing horizontal scrollable nav bar?

Question: On the team with designers and coders at my office, we're currently having a discussion about horizontal navigation bars when they overflow on mobile. This is not a discussion about using cards that are scrollable, like in the Netflix app, but rather in a menu/sub menu.
We took a look at what Google is doing and they fade out other options that are not visible.

But what happens when the screen size is smaller than that?

Suddenly, there's no indication whatsoever that there are more options.
That's my biggest concern with these types of solutions. Other things I'm worried about are accidental edge swipes and back navigation. Wouldn't a "More" menu be a better solution?
What are your thoughts? Are people used to this type of navigation? Do they actually use it? What are the options?
Comment: Put the overflowing options into a new menu, which can be opened by clicking on the ellipsis ... at the end of the horizontal options list. Never require horizontal scrolling.
Comment: Google may have made the decision that it's distracting to make that horizontally scrolling bar more noticeably scrollable, when the vast majority of users who use that page only care about the first couple menu items, and those who care about others are likely to figure out how to get there.
Answer: Although a bit older, this article mentions:

Our research found that even strong cues such as arrows frequently remain unnoticed. People expect to scroll vertically for additional content, but they don't expect to scroll sideways. Horizontal scrolling works against their preexisting mental model of a web page.

If you must, always provide a visual cue. Might be a bit tedious for the google example, but finding a way to always have a label peeking might work.
A "more" menu or "contextual menu" usually triggers relevant actions for the selected item. Its implementation on a menu may seem unfamiliar to users. It might be interpreted as "actions I can do with the current page", rather than "more menu items".
Here is a primer for mobile navigation patterns. Each pattern has its deficiencies and the decision depends on minimizing downside for your users.
Answer: The Priority+ pattern is an option to deal with overflow of elements in place of a horizontal scroll.
You'll see an example of this in sites with lots of top level (and also secondary categories). The Guardian UK is one example. They have potentially overflows at both levels.

It looks like the Guardian has a couple of tradeoffs: because they have so many nodes, the top level gets a 'hamburger' menu on mobile, so there's not 2 'more' links.
SB Nation also uses this pattern, adding a dropdown or menu signifier depending on the viewport width:

From Revisiting the priority+ pattern

This ability to scan these labels left-to-right and feed right into the overflow "more" link feels like a more natural discovery flow compared to everything hiding beneath an ambiguous icon. The Priority+ pattern simply gives a much better scent for the user to follow.

Try testing this pattern, as it might be a possible solution for your domain and what your users expect.
Answer: you never take google as best UX or reference unless your working on something similar Browser project
personally i prefer overflowing horizontal scroll specially on mobile projects based on my states and A/B testing 98% user think horizontal scroll is a swipe,
mobile i prefer burger menu, or bottom fixed menu on the web project i have large menu i use to MORE solution that the guy just mentioned
there is other solution like categories in different way and use MEGA menu (submenu)
Answer: When I worked at a large streaming media and broadcast TV company, we required having a peek of the other options on side-scrolling menus so viewers would know the options were there.  The psychology is slightly different when navigating a smart TV UI or using an AppleTV remote, but there was a drop-off in side-scrolling when the peek wasn't available.
On the flip side, I would imagine Google would have tested that significantly before pushing an update to their search results page.


How do I determine why all outlets on a breaker stopped working, but the hot-grounds are still 120V?

Question: Edit: Is there a way to find an open neutral between the working breaker and the first nonworking outlet without cutting open the wall. It is a pretty straight shot between the 2 with no junction boxes or known splices between.
3 outlets on 1 breaker,  all hot-ground = 120V, neutral-hot and neutral-ground register nothing using a Sperry voltage tester ET6204. Using Ideal circuit tester 61-035, all 3 lights light up in all 3 outlets (top and bottom).
I identified which outlet is first. Breaker hot-neutral is 120V.
A window was recently replaced near the first outlet in the line. Electrical line runs barely under window in wall. Window attachment screws are in wall very near outlet.
What am I looking for and could a window screw have caused the issue?
Answer: Sounds like you have an open (i.e. broken or loose/disconnected) neutral wire.
Comment: Am I looking for an actual broken neutral wire? It has to be between the breaker and the first outlet then, correct?
Comment: Broken between since you postulate screw damage, or possibly disconnected  AT the first outlet (disconnected wire from outlet, outlet used backstabs and they failed, etc.), yes. Possibly a junction box connection failed between, if there IS a junction box between.
Comment: Thanks. I rewired the outlets (was backstabs). That is actually one of the less complicated outlets. Didn't find any junction boxes between.
Comment: Worth turning the breaker off and checking that the neutral screws are tight on that outlet. Probably not the problem but quick and easy if it is.
Comment: Checked screws. Checked under outlet box where wire goes in, no issue screw doesn't enter wall that far. I guess that means the problem is somewhere in the 20 feet between that outlet and the breaker box.


how do you find a file's location?

Question: Noob here. OK, I

Open the Dash.
Type "file". An app appears, called "files", icon looks like ta 2-drawer file cabinet. I click that, the app opens
I click the "Search button". I type the file name in the box and hit Enter.
The program thinks for a while, then displays a result. Great! the program found the file I was looking for! IT knows where myfile.foo is, BUT I DON'T! IT DOESN'T SAY WHERE IT IS!!!!

How do I find out where it is, please?
I hate to say this, but is there an app that works like Windows Explorer (but doesn't crash every 2 minutes)?
Comment: You move the cursor over the file, right click, select properties and then you should be able to see it under **File location**
Comment: Not quite sure why you've been down-voted for a sensible noob question
Answer: yes, this should be easier than that for search results, I agree. There's apparently a lot of work been done on search from within the "Files" app. (aka Nautilus) but that's not out yet.
There's the way suggested by Uri Herrera in the comment (right-click → properties → see the Location bit).
Also, it may be handy to know that you can just Copy the file (right-click → Copy) as if you actually wanted a copy of it, and if you press paste somewhere like a text box, you'll actually paste the filepath itself.
So let's say your search threw up a file called foo.pdf and you wanted to view other files in the same folder as it.

Right-click foo.pdf and select Copy.
Press Ctrl-L (or if you prefer menus, Go → Location...)
Now press Paste (which is Ctrl-V, or right-click and choose Paste) and press Enter.

The Files app will now open the folder with that file in it, and select the file.
So if you like keyboard shortcuts like me, you can just select the file, hold Ctrl down and type C L V, let go of Ctrl, press Enter and voilá!

how do you find a file's location?


water filter for shower boiler

Question: In a shared garden, I have access to a pipe where the water comes from a well. the water is already pre-filtered but still contains (small amount) particles.
I would like to install a shower, the few particles would not be an issue for the shower, but I need to install a water boiler and I am concerned that the particles would then drastically reduce the life of the boiler.
I could find lot of water filters on-line but they are all focused on making the water more drinkable which is not my goal.
Is my worry justified, and a water filter is definitely required?
if yes what type filter should I better use for an economical and quality shower? (I do not have to make the water drinkable)
Comment: Also be sure to flush your water heater bi annually it will extend its life and efficiency.
Answer: What you want is typically referred to as a "whole home water filter".  The name isn't the best description of what it is, but basically they are high-volume water filters that only filter out sediment and relatively large particulate.  They do not bring water to a "drinking water" quality but do filter out anything that would be harmful to appliances.
The good news for you is that they can be cheap enough for a simple installation like yours:

Image from:
http://www.homedepot.com/p/GE-Whole-Home-Water-Filtration-System-GXWH04F/100471282
Only $20, which is a low enough price to put it into the "why not" category.  If you have any reason to believe the water might have some sediment it in, that's enough justification to use one.
To replace the filter, the whole bottom part screws off and a new filter cartridge is put in.  This model says to replace the filter every 3 months, but with your low volume it would probably last much longer.
Comment: The type of filter really has more to do with what your expected incoming water quality is.  Read what each filter type claims to do, and choose based on what you expect.  They will get more expensive and may be more restrictive based on how much they filter out.  Since you are only driving one shower from it, more restrictive should matter.  Cost is probably your most important consideration because it sounds like your water quality needs are not very demanding either.
Comment: Very useful! But there are a few choices for the corresponding filters I can chose. Do you maybe have some recommendation for it?

water filter for shower boiler


Visual Studio C++ - Unable to output a preprocessed file

Question: I am trying to visualize my source code preprocessed in Visual Studio, but I can't get to output anything. No error, but not any .i file in the end either.
I have seen these options for cl.exe here: How do I see a C/C++ source file after preprocessing in Visual Studio?
used /P, but after compile, their is nothing more in my project directory or subfolders.
also tried this: "preprocess current file" addin for Visual Studio? (C++ )
I have adapted the path to devenv.exe to match with my install, but I get a warning from Visual Studio, basically an help man.
Am I completely missing something? How get the preprocessed .i files?
Comment: "basically an help man" What's that suppoused to mean? Additionally, in English question marks don't have a space before them in sentences.
Comment: @tambre yes that is probably because I am french, and we prepend a space before them, but I knew that ^^ It means it gives me a prompt explaining how to use the command with all the available options, like an help man.
Comment: I've never heard of whatever you're calling "an help man" - might be a concept exclusive to the French language (Google doesn't give me any results either). You probably mean a "help prompt", which is usually displayed by command-line tools if your command syntax is invalid.
Comment: Go to `Project Properties` ➡ `C/C++` ➡ `Preprocessor` and set `Preprocess to a file` to `Yes`. Rebuild project. Preprocessed files should be saved in `Output directory`.
Comment: @tambre https://en.m.wikipedia.org/wiki/Man_page
Comment: @VTT yes that is what I have done, no .i file generated anywhere
Comment: @hymced Oh, you simply meant a man page.
Comment: They should be in `Output directory`, that path to output directory can be found at `Project Properties` ➡ `General` tab.
Comment: @VTT yes here `\$(SolutionDir)$(Configuration)`, but they are not, neither Release not Debug :(
Comment: So what is in there instead? Compilation should produce either .obj files (normal) or .i files (preprocessed) for each translation unit.
Comment: I have got 1 .obj for each one of my .cpp, 1 .idb, 1 .pdb, 1 .log
Comment: -_- Please add comments with downvotes
Comment: @hymced - Didn't downvote, but can guess that it comes from the fact that VTT's solution works for everyone else. Change one option to Yes, click Compile, done.
Comment: @Bo I am sorry but it does not work for me. I have a clean install, just made the last update, it does not work, that it. So the spirit here is to downvote when a provided solution does not work ??  that's just great...
Comment: @hymced - Your problem here is that you claim that it doesn't work, but everyone else can easily test the solution (like in my comment) and see that it in fact *does* work. A question with a non-reproducible problem can of course get a few downvotes.
Answer: I have not been able to make the preprocessed .i file using the built in option of Visual Studio 2017, but using the command line method it works:

open a command prompt of the Developer Command Prompt for Visual
Studio
use cd to navigate to this location: $(SolutionDir)$(ProjectName). In my case it is something like that: C:\Users\UserName\Source\Repos\Project1\Project1
use this command: CL /P /C Source1.cpp

Now I get my Source1.i next to my source. Thanks all for your very helpful inputs. I will report this on the Visual Studio developer community instead.
Comment: Once you do report it, make sure to link the report in your answer.
Comment: the report is here: https://developercommunity.visualstudio.com/content/problem/159405/c-unable-to-output-a-preprocessed-file-using-the-p.html
Comment: @hymced Did you faced this error LNK 1104...cannot open file /Debug.xxx.obj like that?


Is it possible to implement mixins in C#?

Question: I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.
Thanks!
Answer: It really depends on what you mean by "mixin" - everyone seems to have a slightly different idea. The kind of mixin I'd like to see (but which isn't available in C#) is making implementation-through-composition simple:
public class Mixin : ISomeInterface
{
    private SomeImplementation impl implements ISomeInterface;

    public void OneMethod()
    {
        // Specialise just this method
    }
}

The compiler would implement ISomeInterface just by proxying every member to "impl" unless there was another implementation in the class directly.
None of this is possible at the moment though :)
Comment: I find it annoying that C++ experts make statements like "Prefer composition to inheritance" yet the language (C++ or C#) offers precious little help to do the "right thing".
Comment: Anders please add this to C# 5!!
Comment: @JonSkeet: I am not the downvoter, but since the question requests a specific example, I expect downvoter was nonplussed that the provided answer is a "Wouldn't it be nice?" rather than a presently-practical solution.
Comment: @ConspicuousCompiler: If the OP had given a specific meaning for what he understood by the term "mix-in" it would have been easier to give a specific example of how it could be achieved. All we've got is "I've heard that it's possible" which doesn't really give much information. *I* don't really regard extension methods as mix-ins, but maybe the OP does. This is a classic case of the more effort the questioner puts into the question, the more they're likely to get out of the answers.
Comment: Just saw a [connect open on this on the VS Feedback rss feed](https://connect.microsoft.com/VisualStudio/feedback/details/627979/).  Go and vote if you likes.
Comment: I've started [implementing roles in C#](http://codecrafter.blogspot.com/2011/05/nroles-experiment-with-roles-in-c.html). Take a look. They can implement interfaces and bring these implementations to composing classes.
Comment: I'd love that, implementing complex interfaces (i.e. more than 2 or 3 members) by composition is a pain...
Comment: yet another delphi concept to be used in c# ... Anders for sure still does know the gotchas :)
Comment: The Oxygene language has that. But [I don't think](http://codecrafter.blogspot.com/2010/11/interface-implementation-through_09.html) that's a good solution for the problem. We need a higher level concept, like traits, or [roles](http://codecrafter.blogspot.com/2010/10/roles-in-c.html).
Comment: +1 This is something I'd really like to see also.  It could be especially handy if the generic system could do it with generic types (e.g. have a type which could wrap any interface type, passing through all of the interface members directly to the wrapped object, but could have its own members separate from those of the interface).  This could be helpful for making finalizers work in scenarios where some references should protect an object from finalization but others should not.
Comment: You can do something really close to this with [re-mix](http://remix.codeplex.com/). I've used it successfully in the past.
Answer: I usually employ this pattern:
public interface IColor
{
    byte Red   {get;}
    byte Green {get;}
    byte Blue  {get;}
}

public static class ColorExtensions
{
    public static byte Luminance(this IColor c)
    {
        return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);
    }
}

I have the two definitions in the same source file/namespace.
That way the extensions are always available when the interface is used (with 'using').
This gives you a limited mixin as described in CMS' first link.
Limitations:

no data fields
no properties (you'll have to call myColor.Luminance() with parentheses, extension properties anyone?)

It's still sufficient for many situations.
It would be nice if they (MS) could add some compiler magic to auto-generate the extension class:
public interface IColor
{
    byte Red   {get;}
    byte Green {get;}
    byte Blue  {get;}

    // compiler generates anonymous extension class
    public static byte Luminance(this IColor c)
    {
        return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);
    }
}

Although Jon's proposed compiler trick would be even nicer.
Comment: I use the same . Extension methods on interfaces. I see this from wikpedia on mixins in c#.  "...Extension Methods provide additional functionality on an existing class without modifying the class. It then becomes possible to create a static helper class for specific functionality that defines the extension methods...."
Comment: As risky as this is, this may be the only way to, without downloading any third party stuff, do what mixins are supposed to do -- keep things separate while allowing them to optionally be merged together at runtime. For reasons why this may be risky, for one, it's easy to accidentally override an existing method of the underlying object
Answer: There is an open source framework that enables you to implement mixins via C#. Have a look on http://remix.codeplex.com/.
It is very easy to implement mixins with this framework. Just have a look on the samples and the "Additional Information" links given on the page.
Answer: LinFu and Castle's DynamicProxy implement mixins. COP (Composite Oriented Programming) could be considered as making a whole paradigm out of mixins. This post from Anders Noras has useful informations and links.
EDIT: This is all possible with C# 2.0, without extension methods
Answer: I needed something similar so I came up with the following using Reflection.Emit. In the following code a new type is dynamically generated which has a private member of type 'mixin'. All the calls to methods of 'mixin' interface are forwarded to this private member. A single parameter constructor is defined that takes an instance which implements the 'mixin' interface. Basically, it is equal to writing the following code for a given concrete type T and interface I:
class Z : T, I
{
    I impl;

    public Z(I impl)
    {
        this.impl = impl;
    }

    // Implement all methods of I by proxying them through this.impl
    // as follows:
    //
    // I.Foo()
    // {
    //    return this.impl.Foo();
    // }
}

This is the class:
public class MixinGenerator
{
    public static Type CreateMixin(Type @base, Type mixin)
    {
        // Mixin must be an interface
        if (!mixin.IsInterface)
            throw new ArgumentException("mixin not an interface");

        TypeBuilder typeBuilder = DefineType(@base, new Type[]{mixin});

        FieldBuilder fb = typeBuilder.DefineField("impl", mixin, FieldAttributes.Private);

        DefineConstructor(typeBuilder, fb);

        DefineInterfaceMethods(typeBuilder, mixin, fb);

        Type t = typeBuilder.CreateType();

        return t;
    }

    static AssemblyBuilder assemblyBuilder;
    private static TypeBuilder DefineType(Type @base, Type [] interfaces)
    {
        assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
            new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(Guid.NewGuid().ToString());

        TypeBuilder b = moduleBuilder.DefineType(Guid.NewGuid().ToString(),
            @base.Attributes,
            @base,
            interfaces);

        return b;
    }
    private static void DefineConstructor(TypeBuilder typeBuilder, FieldBuilder fieldBuilder)
    {
        ConstructorBuilder ctor = typeBuilder.DefineConstructor(
            MethodAttributes.Public, CallingConventions.Standard, new Type[] { fieldBuilder.FieldType });

        ILGenerator il = ctor.GetILGenerator();

        // Call base constructor
        ConstructorInfo baseCtorInfo =  typeBuilder.BaseType.GetConstructor(new Type[]{});
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Call, typeBuilder.BaseType.GetConstructor(new Type[0]));

        // Store type parameter in private field
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Stfld, fieldBuilder);
        il.Emit(OpCodes.Ret);
    }

    private static void DefineInterfaceMethods(TypeBuilder typeBuilder, Type mixin, FieldInfo instanceField)
    {
        MethodInfo[] methods = mixin.GetMethods();

        foreach (MethodInfo method in methods)
        {
            MethodInfo fwdMethod = instanceField.FieldType.GetMethod(method.Name,
                method.GetParameters().Select((pi) => { return pi.ParameterType; }).ToArray<Type>());

            MethodBuilder methodBuilder = typeBuilder.DefineMethod(
                                            fwdMethod.Name,
                                            // Could not call absract method, so remove flag
                                            fwdMethod.Attributes & (~MethodAttributes.Abstract),
                                            fwdMethod.ReturnType,
                                            fwdMethod.GetParameters().Select(p => p.ParameterType).ToArray());

            methodBuilder.SetReturnType(method.ReturnType);
            typeBuilder.DefineMethodOverride(methodBuilder, method);

            // Emit method body
            ILGenerator il = methodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, instanceField);

            // Call with same parameters
            for (int i = 0; i < method.GetParameters().Length; i++)
            {
                il.Emit(OpCodes.Ldarg, i + 1);
            }
            il.Emit(OpCodes.Call, fwdMethod);
            il.Emit(OpCodes.Ret);
        }
    }
}

This is the usage:
public interface ISum
{
    int Sum(int x, int y);
}

public class SumImpl : ISum
{
    public int Sum(int x, int y)
    {
        return x + y;
    }
}

public class Multiply
{
    public int Mul(int x, int y)
    {
        return x * y;
    }
}

// Generate a type that does multiply and sum
Type newType = MixinGenerator.CreateMixin(typeof(Multiply), typeof(ISum));

object instance = Activator.CreateInstance(newType, new object[] { new SumImpl() });

int res = ((Multiply)instance).Mul(2, 4);
Console.WriteLine(res);
res = ((ISum)instance).Sum(1, 4);
Console.WriteLine(res);

Comment: Some people, when confronted with a problem, think "I know, I'll use Reflection.Emit." Now they re-compile Problem to include Solution opcodes and have attained programming nirvana.
Answer: You could also augment the extension method approach to incorporate state, in a pattern not unlike WPF's attached properties.
Here is an example with minimum boilerplate. Note that no modification are required on the target classes, including adding interfaces, unless you need to deal with the target class polymorphically - in which case you end up with something very close to actual Multiple Inheritance.
// Mixin class: mixin infrastructure and mixin component definitions
public static class Mixin
{
    // =====================================
    // ComponentFoo: Sample mixin component
    // =====================================

    //  ComponentFooState: ComponentFoo contents
    class ComponentFooState
    {
        public ComponentFooState() {
            // initialize as you like
            this.Name = "default name";
        }

        public string Name { get; set; }
    }

    // ComponentFoo methods

    // if you like, replace T with some interface
    // implemented by your target class(es)

    public static void
    SetName<T>(this T obj, string name) {
        var state = GetState(component_foo_states, obj);

        // do something with "obj" and "state"
        // for example:

        state.Name = name + " the " + obj.GetType();

    }
    public static string
    GetName<T>(this T obj) {
        var state = GetState(component_foo_states, obj);

        return state.Name;
    }

    // =====================================
    // boilerplate
    // =====================================

    //  instances of ComponentFoo's state container class,
    //  indexed by target object
    static readonly Dictionary<object, ComponentFooState>
    component_foo_states = new Dictionary<object, ComponentFooState>();

    // get a target class object's associated state
    // note lazy instantiation
    static TState
    GetState<TState>(Dictionary<object, TState> dict, object obj)
    where TState : new() {
        TState ret;
        if(!dict.TryGet(obj, out ret))
            dict[obj] = ret = new TState();

        return ret;
    }

}

Usage:
var some_obj = new SomeClass();
some_obj.SetName("Johny");
Console.WriteLine(some_obj.GetName()); // "Johny the SomeClass"

Note that it also works with null instances, since extension methods naturally do.
You might also consider using a WeakDictionary implementation to avoid memory leaks caused by the collection's holding on to target class references as keys.
Comment: The signature of GetState only has one Type Arg, but the calls to GetState by GetName and SetName pass in two. How is this really supposed to work?
Comment: @Thick_propheT, you're right of course. I made a few simplifications after the original post, but seem to have missed this bit. Thanks!
Answer: I've found a workaround here, which while not entirely elegant, allows you to achieve fully observable mixin behavior. Additionally, IntelliSense still works!
using System;
using System.Runtime.CompilerServices; //needed for ConditionalWeakTable
public interface MAgeProvider // use 'M' prefix to indicate mixin interface
{
    // nothing needed in here, it's just a 'marker' interface
}
public static class AgeProvider // implements the mixin using extensions methods
{
    static ConditionalWeakTable<MAgeProvider, Fields> table;
    static AgeProvider()
    {
        table = new ConditionalWeakTable<MAgeProvider, Fields>();
    }
    private sealed class Fields // mixin's fields held in private nested class
    {
        internal DateTime BirthDate = DateTime.UtcNow;
    }
    public static int GetAge(this MAgeProvider map)
    {
        DateTime dtNow = DateTime.UtcNow;
        DateTime dtBorn = table.GetOrCreateValue(map).BirthDate;
        int age = ((dtNow.Year - dtBorn.Year) * 372
                   + (dtNow.Month - dtBorn.Month) * 31
                   + (dtNow.Day - dtBorn.Day)) / 372;
        return age;
    }
    public static void SetBirthDate(this MAgeProvider map, DateTime birthDate)
    {
        table.GetOrCreateValue(map).BirthDate = birthDate;
    }
}

public abstract class Animal
{
    // contents unimportant
}
public class Human : Animal, MAgeProvider
{
    public string Name;
    public Human(string name)
    {
        Name = name;
    }
    // nothing needed in here to implement MAgeProvider
}
static class Test
{
    static void Main()
    {
        Human h = new Human("Jim");
        h.SetBirthDate(new DateTime(1980, 1, 1));
        Console.WriteLine("Name {0}, Age = {1}", h.Name, h.GetAge());
        Human h2 = new Human("Fred");
        h2.SetBirthDate(new DateTime(1960, 6, 1));
        Console.WriteLine("Name {0}, Age = {1}", h2.Name, h2.GetAge());
        Console.ReadKey();
    }
}

Answer: If you have a base class that can store data you can enforce compiler safety and use marker interfaces.
That's more or less what "Mixins in C# 3.0" from the accepted answer proposes.
public static class ModelBaseMixins
{
    public interface IHasStuff{ }

    public static void AddStuff<TObjectBase>(this TObjectBase objectBase, Stuff stuff) where TObjectBase: ObjectBase, IHasStuff
    {
        var stuffStore = objectBase.Get<IList<Stuff>>("stuffStore");
        stuffStore.Add(stuff);
    }
}

The ObjectBase:
public abstract class ObjectBase
{
    protected ModelBase()
    {
        _objects = new Dictionary<string, object>();
    }

    private readonly Dictionary<string, object> _objects;

    internal void Add<T>(T thing, string name)
    {
        _objects[name] = thing;
    }

    internal T Get<T>(string name)
    {
        T thing = null;
        _objects.TryGetValue(name, out thing);

        return (T) thing;
    }

So if you have a Class you can inherit from 'ObjectBase' and decorate with IHasStuff you can add sutff now
Answer: Here is a mixin implementation I've just come up with. I'll probably use it with a library of mine.
It's probably been done before, somewhere.
It's all statically typed, with no dictionaries or something. It requires a little bit of extra code per type, you don't need any storage per instance. On the other hand, it also gives you the flexibility of changing the mixin implementation on the fly, if you so desire. No post-build, pre-build, mid-build tools.
It has some limitations, but it does allow things like overriding and so on.
We begin by defining a marker interface. Perhaps something will be added to it later:
public interface Mixin {}

This interface is implemented by mixins. Mixins are regular classes. Types do not inherit or implement mixins directly. They instead just expose an instance of the mixin using the interface:
public interface HasMixins {}

public interface Has<TMixin> : HasMixins
    where TMixin : Mixin {
    TMixin Mixin { get; }
}

Implementing this interface means supporting the mixin. It's important that it's implemented explicitly, since we're going to have several of these per type.
Now for a little trick using extension methods. We define:
public static class MixinUtils {
    public static TMixin Mixout<TMixin>(this Has<TMixin> what)
        where TMixin : Mixin {
        return what.Mixin;
    }
}

Mixout exposes the mixin of the appropriate type. Now, to test this out, let's define:
public abstract class Mixin1 : Mixin {}

public abstract class Mixin2 : Mixin {}

public abstract class Mixin3 : Mixin {}

public class Test : Has<Mixin1>, Has<Mixin2> {

    private class Mixin1Impl : Mixin1 {
        public static readonly Mixin1Impl Instance = new Mixin1Impl();
    }

    private class Mixin2Impl : Mixin2 {
        public static readonly Mixin2Impl Instance = new Mixin2Impl();
    }

    Mixin1 Has<Mixin1>.Mixin => Mixin1Impl.Instance;

    Mixin2 Has<Mixin2>.Mixin => Mixin2Impl.Instance;
}

static class TestThis {
    public static void run() {
        var t = new Test();
        var a = t.Mixout<Mixin1>();
        var b = t.Mixout<Mixin2>();
    }
}

Rather amusingly (though in retrospect, it does make sense), IntelliSense does not detect that the extension method Mixout applies to Test, but the compiler does accept it, as long as Test actually has the mixin. If you try,
t.Mixout<Mixin3>();

It gives you a compilation error.
You can go a bit fancy, and define the following method too:
[Obsolete("The object does not have this mixin.", true)]
public static TSome Mixout<TSome>(this HasMixins something) where TSome : Mixin {
    return default(TSome);
}

What this does is, a) display a method called Mixout in IntelliSense, reminding you of its existence, and b) provide a somewhat more descriptive error message (generated by the Obsolete attribute).
Answer: There are, fundamentally, several techniques to getting Mixin behavior in your classes:

Behavioral mixins that hold no state are easily done using extension methods
Behavioral mixins for interfaces that use duck typing (currently, IEnumerable and IDisposable) can use default interface members with explicit implementation of said interface. Then, then new interface behaves as a mixin where concrete behavior can be added and leveraged without using extension methods, and can support constructs such as using and foreach.
Mixins that need state can be implemented very roughly by using extension methods and a static ConditionalWeakTable to hold data.
Multiple inheritance mechanics can be crudely synthesized at compile-time (T4, source generators) or runtime (Reflection.Emit).
Answer: Default implementation of interfaces have pretty much enabled mixins to be possible with a bit of creativity.
Here's a demo:
using System;

public class Program {
  public static void Main(string[] args) {
      var inst = new Baseline();
      Console.WriteLine("Baseline.Method() returns " + inst.Method());
      Console.WriteLine("Baseline.Method() returns " + inst.Method());
  }
}

public struct MixinImpl {
    public static MixinImpl Create() => new MixinImpl(); // Idiom to provide the mixin constructor
    private int counter;
    public int Method() => ++counter;
}

public interface Mixin {
    ref MixinImpl Impl { get; }
    int Method() => Impl.Method();
}

public class Baseline : Mixin {
    private MixinImpl mixinImpl = MixinImpl.Create();
    ref MixinImpl Mixin.Impl => ref mixinImpl;
}

So this works by defining a mixin as a struct and a corresponding interface; where the interface contains the mixin default implementation and the struct contains the state. This implementation has the benefit of not breaking the ABI when you add either state or methods to the mixin.
The only real downside is there's no way to do protected access qualifier. Your only protection choices are public and private. You can kind of fake protected by not providing the forwarder but it doesn't really work because half of the callers will be via variables of the interface type, which can see the Impl member and access members of the struct.
Here's the overhead in the user of the mixin isolated so you can see it alone:
: Mixin {
    private MixinImpl mixinImpl = MixinImpl.Create();
    ref MixinImpl Mixin.Impl => ref mixinImpl;

That's it. One interface declaration and two lines of code. The first line declares and creates the mixin state and the second line provides the glue that ties everything together. There's no limit to the number of mixins you can have either.
The overhead on the mixin provider is as follows:
    int Method() => Impl.Method();

Every public property and method that accesses anything private needs a forwarder from the interface to the struct.
Mixins done this way don't have inheritance; however you can fake it with composition and implementing the base interface in the derived struct. The interface forwarding provides capacity to do virtual methods while you're at it. This also means mixins can have mixins, but what are you doing if you need that.
Apologies; TIO's compiler is out of date and doesn't support default implementations.


How well would a hydronic furnace work with a gas tankless water heater?

Question: My current heating system (in Ontario) is an oil hot water tank in a closed loop with a hydronic forced-air furnace (Enerzone XAH 68). The water circulates through what is basically a heat exchanger across which a blower blows air. I also have an electric tank for tap hot water.
How well would such a furnace work with a gas tankless water heater? If I add a second tankless for household hot water, is there any use for the electric tank alongside a tankless heater?
Answer: You can use a tankless boiler with your air handler. The fact that the heat is being distributed using forced air doesn't really affect how you generate the heat, and you should be able to retain most of the benefits of a tankless (i.e. you are not constantly holding a bunch of water at a high temperature) in this configuration.
If you add a tankless heater for domestic hot water, there will not be much use for your electric tank. There is only one use I can imagine: positioning the electric heater after the tankless (in terms of water flow) so that when you turn on the hot water tap you initially draw from the electric tank. This is done sometimes in order to supply hot water faster, as tankless water heaters can require some time to warm up. This sort of application generally calls for a very small water heater, so if your current water heater is designed to serve your entire home,using it with a tankless would probably be very inefficient.
One option you might consider is a combined heat/hot water tankless. I have a Navien CH-240, which provides both heat (via radiators) and hot water. It's small, quiet, and way less expensive to operate than the old oil boiler it replaced. The equipment cost of a combined heat/HW tankless will probably be less than two individual tankless units.


How do I remove hard deposits from my glass shower door?

Question: I have a problem with regards to my frameless glass shower door because I don't usually clean it regularly. What happens is that the lower edge of the glass door is already very cloudy and is very coarse in texture. I tried to use some vinegar and water dipped with newspaper since I prefer using natural cleaners but it just won't work. Maybe it has accumulated too much that it can hardly be removed.
Do you have any other idea on what natural method to use for removing it? If possible,  I don't want to use the common glass cleaners sold on the market. That's the last choice for me.
Comment: It's probably limescale. Once you have removed it with appropriate limescale remover, the key is to wipe the door down with a cloth or a squeegee every time after a shower. This will prevent it building up again.
Answer: Try using straight vinegar, right from a spray bottle.  It may work better if it's heated first.  Then try wiping with a used dryer sheet.
If that doesn't work, then you'll probably have to resort to something like CLR, at least for the initial cleaning.
Answer: For major buildup of insoluble calcium and magnesium salts, including soap scum, citric acid is a better choice than acetic acid.
Unlike acetic acid, citrate is a pretty good chelator. It binds tightly to metal ions, and remains soluble. That allows the counterion of your soap scum complex free to dissolve too.
However, unlike vinegar, citric acid dries to a powder, so you have to clean that up after you clean up the soap scum. Also unlike vinegar, citric acid doesn't stink.
I use vinegar for light work, and citric acid for when things get nasty.
Citric acid is sold in the gricery store as coffee maker cleaner (check the label) and in coops and health food stores that sell bulk spices etc.
Answer: I've found that the Mr. Clean Magic Erasers work well on this.
I am in no way associated with this product, I've just had good experiences using it
Answer: Wayfaring Stranger has the right of it. Citric acid is far better at dissolving the calcium-magnesium-soap scum mix than vinegar.
Here in Dallas we have the worst limescale/soap scum buildup I've experienced. Having tried CLR, vinegar, and several other remedies, I was not prepared for how effective, easy, and odorless citric acid could be.
My suggestion for a cheap and ready source is a bathroom cleaner in a spray bottle (not the dry abrasive mix) that includes Citric Acid as the active ingredient (preferably 6% or more).
Answer: I HAVE TRIED ALL OF THE REMEDIES AND THEY PROVIDE TERRIBLE RESULTS. The following recipe WILL absolutely work on the worst of all soap scum on shower glass doors & hard water spots & stains . You must go to the store and buy a new BAR OF LAVA HAND SOAP - not any other thing or  brand except LAVA BAR SOAP..
 Get the glass wet and proceed to rub that bar of soap on an area with a little bit of pressure until small amount of lather occurs. Wipe for about 30-60 seconds while keeping it wet. After 30-60 seconds of rubbing in one spot, stop and wipe it clean & dry and LOOK at it !
 It and say wow that guy knows all about this stuff!
It will not scratch the glass. After you're done the entire door wipe it down with water , isopropyl alcohol or glass cleaner and then dry it . Now proceed to use a automobile wax of your choice to wax the shower glass door 2 times in a row .  If you want the absolute longest . Of time that this will last  you will have to buy a ceramic paint sealant located in the automotive wax section  wherever you shop  for  car products. You will love the long lasting results & you can thank me later about this bcuz  its the ONLY thing that works for soap scum on glass. This is one of the only ways to remove "etched in" water spots on automotive glass also.
Comment: Lava bar soap contains actual pumice which will almost certainly scratch the glass and any metal you use it on. It's not always apparent until you use it several times.
Answer: Had this same problem for a long time and now I've solved it.

Always squeegee the door after showering and:
When a film develops spray the wet door with Ka-Boom, lightly wiping it with a plastic kitchen scrub pad. The pad won't scratch the glass and easily removes the lime-scale. You can buy it in most stores.
Answer: Mix a combination of water, white vinegar, and dish soap (not dishwashing detergent) in equal parts into a spray bottle.
Gently shake it before use.
Spray it on the surfaces that you want to clean and let it sit for at least 10 minutes. The longer it sits, the less elbow grease you will have to use.
After sitting for the stated time, wipe and rinse off the surface.


Use of Generics is a subclass

Question: I have this class [1] that I try to use with my class [2]. But, the generics of MyIdentityMapper are wrong. I want to create a generic class that when I use it (MyIdentityMapper), I passes the correct types. How should I use generics in  MyIdentityMapper here?
[1] Mapper class:
public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT> {...}

[2] Identity class:
public class MyIdentityMapper extends Mapper<K,V,K,V> {
  public void map(K key, V value, Context context) throws IOException, InterruptedException {
    context.write(key, value);
  }
}

Answer: You need to declare your K and V type parameters on MyIdentityMapper so they can be referenced in the rest of the class.
public class MyIdentityMapper<K, V> // ... rest doesn't change

Answer: You have to tell java what is your generics, something like that
class Mapper<K, V, X, M> {

}

class MyIdentityMapper<K,V,X,M> extends Mapper<K,V,X,M> {
    public void map(K key, V value, Context context) throws IOException, InterruptedException {
        System.out.println(k);
        System.out.println(v);
        System.out.println(x);
        System.out.println(m);
    }
}

Use of Generics is a subclass


Why is the output remaining the same?

Question: import java.io.*;

public class TestCaseAbcd {
    public static void main(String args[]) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader stdin = new BufferedReader(
        float x0;
        float a, c, mod;
        int num, ch = 0;
        double[] rNumbers;
        double[] rTemp;

        System.out.println("Enter the SEED value: ");
        System.out.println("x0 ");
        x0 = Float.parseFloat(stdin.readLine());

        System.out.println("Enter the multiplier's value:");
        System.out.println("a: ");
        a = Float.parseFloat(stdin.readLine());

        System.out.println("Enter the value of increment c and modulus m: ");
        System.out.println("c: ");
        c = Float.parseFloat(stdin.readLine());

        System.out.println("m: ");
        mod = Integer.parseInt(stdin.readLine());

        System.out.println("How many random nunbers u need? ");
        num = Integer.parseInt(stdin.readLine());

        rNUmbers = new double[num];
        rTemp = new double[rNumbers.length];
        rTemp[0] = x0;

        for (int i = 0; i < num; i++)
        {
            if(i + 1 != num)
            {
                rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
            }
            else
            {
                break;
            }
        }
        for (int i = 0; i < rNumbers.length; i++)
        {
            if (i + 1 != num)
            {
                rNumbers[i] = rTemp[i] / mod;
            }
            else
            {
                break;
            }
        }

        System.out.println("The PSEUDO random numbers are: ");
        for (int i = 0; i < rNumbers.length; i++)
        {
            System.out.println(rNumbers[i]);
        }

        double firstNum = rNumbers[0];

        System.out.println("1. Select Mutant 1 ");
        System.out.println("2. Select Mutant 2 ");
        System.out.println("3. Exit ");
    }
}

In the above code, the expected output should start from: 0.68.
But, instead it started from:
0.37.
In fact, even after I changed the following code:
 rTemp[i+1] = ( ( (rTemp[i]*a) + c ) % mod);

to:
 rTemp[i+1] = ( ( (rTemp[i]/a) + c ) % mod);

The output still started from 0.37.
The input values are:
x0 = 37
a = 7
c = 9
m = 100

Please help me in analyzing the code so as that the output shouldn't start with 0.37.
Summary of the problem: the code is producing the same number i.e. 0.37 no matter what the equation stated above in the code is modified to.
Comment: Please format your code properly.
Comment: In addition to the formatting issue, your code doesn't compile: where is isr declared, what are the arguments of BufferedReader constructor (in stdin declaration)...? Could you please fix it?
Comment: Are you running this from the command line?  Did you re-run `javac`?
Comment: Sorry guys, I am new to this. I can upload a .txt file containing this code. Should I upload it??
Comment: What are the values in your array `x`?
Comment: Dude, I am so sorry...that's x0 and not x[0]
Comment: Guys, I have edited it!!.Hope you'll get it??
Comment: @arshajii..I've done what you said!!!
Comment: @C.Champagne I'v used the following: `BufferedReader stdin = new BufferedReader(isr);`
Answer: You're setting the first value in rTemp to 37, then you start printing from the first value. It only makes sense that the first value printed would be 0.37.
x0 = 37
mod = 100
...
rTemp[0] = x0;
...
rNumbers[i] = rTemp[i] / mod;
...
System.out.println(rNumbers[i]);

To achieve the output you're looking for, change this:
rTemp[0] = x0;

for (int i = 0; i < num; i++)
{
    if(i + 1 != num)
    {
        rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
    }
    else
    {
        break;
    }
}

to this:
rTemp[0] = (((x0 * a) + c) % mod);

for (int i = 0; i < num-1; i++)
{
    rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}

On a side note, if all you really want is an array of psudo-random doubles, it's easier to do something like this:
Random rnd = new Random(seed);
double[] rNumbers = new double[num];
for(int i = 0; i < num; i++)
    rNumbers[i] = (double)rnd.nextInt(100) / 100;

For any given seed, you'll get the same array of doubles every time.
Comment: @Syon... **thanks a lot!!!!**  It worked!!!..mahn!! i m noob!!!lol anyways...thanks a lot...can we meet on facebook?? I mean, I might need more tips from you.. :)

Why is the output remaining the same?


Solving a set of coupled ODEs

Question: I have a set of coupled ODEs:
\begin{align}
\dot{x} &= -A x^4 + B_1 y^4, \\
\dot{y} &=  A x^4 - (B_1 + B_2) y^4 + C z^4, \\
\dot{z} &=  B_2 y^4 - C z^4
\end{align}
Without having to use the first one, I've managed to decouple them to get an expression involving only z and x: I rearranged the third equation to get another expression for $\dot{y}$. Subbing this into the middle equation gives
$$
\dot{y} = \frac{1}{4} \left[ \frac{\dot{z} + Cz^4}{B_2} \right]^{-\frac{3}{4}}
\left[  \frac{\ddot{z} + 4Cz^3\dot{z}}{B_2}  \right]
=
Ax^4 - \frac{B_1 + B_2}{B_2} ( \dot{z} + Cz^4 ) + Cz^4
$$
However this is a horrible looking nonlinear ODE that I have no idea how to tackle.
Is there a better approach that I'm missing, or will I have to resort to numerical approaches?
Tagged physics since this is a model of heat transfer by radiation between three objects (x,y,z are temperatures).
Comment: Maybe it will help that $x+y+z = {\rm const}$ for this system?
Comment: Hmm possible. That's conservation of energy by the way
Comment: Also after that you can go from $\dot{x} = \dots, \; \dot{y} = \dots$ to $\frac{dy}{dx} = f(\frac{y}{x})$ and this in theory can be solved by usual methods (this is homogeneous equation).
Comment: I like that approach but I'm not sure it's homogeneous unfortunately. That gives (I've eliminated y instead of z, since I'm actually interested in z): $\frac{dx}{dz} = \frac{-Ax^4 + B_1(S - x - z)^4}{B_2(S-x-z)^4 - Cz^4}$, defining $S = x + y + z$
Comment: But according to my understanding, that's not homogeneous because the quotient is not insensitive to a multiplication of $x$ and $z$.
Comment: Sorry, my bad, I forgot about that $S$.
Comment: Thanks a lot for your help with this, I've learnt a bit about ODEs reading around for this one! But as a lowly phycisist, I think I'm going to just go with the numerical solution which serves my purposes fine.
Comment: By the way, if your goal is not to obtain the exact analytical solution, but to understand the long-term behaviour, we probably can do better than numerics :)
Comment: It's the frequency response of $z$ w.r.t. changes in $x$ (or better, another layer outside $x$, as shown in my answer) that I'm really looking for. However, this forms such a small part of my thesis that, sadly, I think it's time for me to force myself to move on from it and say "that's good enough"!
Comment: Seems legit! okay then :)
Answer: Answering my own question, although I'd love to be proved wrong!
I've ended up just going for a numerical approach with this one. In case anyone is interested, this was a model for radiative heat transfer betwen three isolated objects with temperatures x, y and z. x and z only couple to y, whereas y couples to both the other.
As for a solution, I ended up adding a fourth layer which I held constant as a perfect heat-sink. Here's what happens if you step the perfect heat-sink's temperature. In the following plot x,y,z have become "chamber," "shield" and "cavity" respectivly.

And in the frequency domain:

So there you go. I'd still love to see an analytic solution if you fancy having a try!

Solving a set of coupled ODEs


Converting Main Panel to Subpanel

Question: Okay, I have a main panel that is a 1978 2-wire system with combined neutral/ground bar and a 100amp main disconnect breaker. I'm Replacing it with new 200-amp service and all load wiring has been updated and includes ground wiring. The easiest transformation is to add a room and convert the exterior wall where the old panel is to an interior wall and simply put the new panel facing the new room to meet code and avoid a j-box. The old panel is also in a kitchen cabinet. The meter box is on the exterior opposite the original panel box but is being relocated to a new ext. location.
I installed a temporary power pole main disconnect with 2-2-2-4 SER to run 25' in schedule 40 from the disconnect to the old panel until the room is built. To convert it to a subpanel, do I remove one of the existing ground/neutral bars and replace it with an insulated neutral bar and put all load neutrals on the insulated bar plus the #2 neutral wire from the disconnect and all grounds to the ground bar? I'm assuming the 2-2-2-4 SER Al is rated to enter the house to the panel.
Other than the #4 ground wire from the new disconnect to the old panel, does the subpanel also need a #6 bare copper ground from the ground bar to a copper ground rod? I already have 2 ground rods at the main disconnect on the temp pole.
Lastly, there is already a 4-wire subpanel that I had previously wired from the original panel to a workshop and put a ground to a copper rod at that subpanel. If I have my wiring description above correct, is any of this going to affect the wiring arrangement at the existing subpanel of the workshop?
Thanks for any advice/recommendations.
Comment: What make and model is the existing panel? In many cases, the neutral bar is part of the panelboard interior assembly and *can't* be "removed and replaced" the way you describe....
Answer: Your plan sounds right. Separating the grounds.  And 4-wire from main to any subpanel.  Using aluminum wire for service and feeder is also wise.
You actually need two ground rods at each building. Unless the one passes the magic test for 25 ohms. But you can't test it, and the cost of hiring it done is more than a second rod.  End of the day ground rods are for protecting you and yours, so they're cheap insurance.
You still need the ground wire; that's for returning human-generated current, which is much lower voltage than lightning and ESD, but far too high current for dirt to carry.
Answer: I believe you are very close to being in good shape.  Yes, to do it properly, the existing 100 amp panel must have the neutral "floated" (insulated) and not bonded to the ground. All neutrals must go to the neutral busbar and all grounds must be connected to the grounding busbar.  Since you have 4 wire from the temporary service, you no longer need the ground rods for the 100 amp service. In fact, I think it's probably not even allowed anymore. Your connection assumptions are correct. Will you be gutting the old panel and basically turn it into a big j-box?   That's what I've done in the past and inspectors are fine with it.   Being in a cabinet may force the issue going forward.
Regarding the other sub-panel in your workshop, if you have 4 wire feed to it, it's the same drill as your other soon-to-be subpanel...float the neutral and use separate wires for neutral and ground.  You shouldn't need a local grounding rod there either anymore.  I understand the code, and the rationale for not sharing neutral and grounding in a sub-panel, but not why you can't have local grounding. Maybe someone with more knowledge than me can answer that.
Comment: If it's a separate building, the OP still needs a grounding electrode system there....
Comment: "Will you be gutting the old panel and basically turn it into a big j-box?" I'm building a garage and the new meter box, riser and weatherhead will end up there, with new wiring buried in sch. 80 and returning to the new room 200 amp panel. I will simply gut the original panel box and remove it completely. The new panel will take its place facing into the new room instead of the cabinet and the wiring will be long enough without having to use a j-box.
Comment: Will you be gutting the old panel and basically turn it into a big j-box?  I plan to gut it and replace it with the new 200amp panel facing into the new room. The wiring will be plenty long enough that I won't need a j-box at all. That should satisfy the code of getting the panel out of the kitchen cabinet and having the required free space in the new room surrounding the new panel with all new breakers. The new panel naturally has the isolated neutral and separate ground, with a new 200amp main breaker. Thanks for the help from everyone.
Comment: OK, I get it now. The new panel is replacing the existing one in the same place, but opening on the other side of the wall.  Great solution.  When you get your new panel, I strongly suggest the "plug on neutral" (PON) panels.   With those, you don't need all the pig tails for GFCI & AFCI breakers because there are neutral bus bars that clip on the breaker, just like the hots. ... makes for a much neater panel. Check with your local code/inspectors to see what will need to be GFCI & esp. AFCI protected in your remodel/addition. The rules are complicated.
Comment: Question for ThreePhaseEel:    In my neck of the woods (Washington State), they really want outbuildings serviced by 4-wire without a local grounding system.  At least I think that.  I know that sub-panels in the same building must be 4 wire. I'm going to call the inspector to clarify.  I've never seen the logic in  not allowing local grounding for sub-panels as long as the neutral is floated.   I might be wrong, I'll let you know.
Comment: Meh, plug-on-neutral is convenient, but I'm not willing to stoop to a *worse* panel brand to get it, e.g. HOMeline.  Especially if other considerations (generator interlock; Eaton remote throw breakers) are dragging me in a different direction.  4-wire to all subpanels has been code for  years.  That's surprising about Washington not requiring outbuilding electrodes; maybe it's a regional soil thing (good conductivity).
Comment: @GeorgeAnderson -- 4-wire feeders to new subpanels have been Code-required for some time now; it's odd that your local code doesn't require local grounding electrodes for panels in outbuildings though.  I suspect it may have to do with Washington State having one of the lowest incidences of lightning strikes in the US though? (Outbuilding earth electrodes are primarily there to discharge induced currents from lightning and other such natural sources back to the Earth they came from.)
Comment: @GeorgeAnderson -- re: PoN: there are two different configurations for that.  BR and QO use split busbars, where the PoN breakers land their neutral jaws on a dedicated busbar section, with the neutral wires going onto a different busbar section.  HOM and CH use a combination busbar setup, where the PoN breaker neutral jaws land on a neutral busbar that also has screws for wire terminations on it, which has the advantage that hot and neutral go to the same place, no matter what sort of breaker is there; it also means you have more neutral holes, which is helpful when using multi-circuit cables
Comment: Harper, the PoN panel is Square D QO, not Homeline (I'd never use Homeline).    Mr. ThreePhase, Yes, we have VERY LITTLE lightning strikes here. I still think a floated neutral in a sub panel and local electrode grounding is a good way to go.  But I don't make the rules, I just try to follow them.

Converting Main Panel to Subpanel