Can I control static or dynamic library linking while compiling? Does each create diff. binary sizes?

Question: In one of the Go seminars, the lecturer said that when he compiled the Go application, statically linked, the size of the resulting binary was about 600 MB big, but when he compiled the same app with dynamic linking, the resulting binary turned into 10 MB.
I'm not sure what he is talking about, can dynamic vs. static linking during compilation make that difference in space of binary, and do I have control over that?
Answer: By default Go uses static linking so everything (your code and packages sources) compiles in one big binary.
Since Go 1.5 released you can compile Go shared library using -buildmode=shared option for go build or go install. Then you can compile your app binary with -linkshared flag. Details can be found here.
Ofcourse, if you link packages dynamically your binary size will be less than with static linking, but total application size will not be reduced because you just "put your code in other place".
So dynamic linking makes sense only if you need to share the same packages between different apps.


Assignments in Scala

Question: I've been shown a weird snippet in Scala which I don't quite understand. To me, assignments in Scala return Unit, unlike in Java where it returns the type of the variable which has been affected a value. However, let's consider this class :
case class C(i: Int) {
  def f = C(i = i + 10)
}

This compiles completely fine, which is pretty weird ! The factory method C.apply expects an Int, whereas I pass it what seems to be an assignment, of type Unit. By the way if I remove the assignment to just let the expression, it seems to have the exact same behaviour.
Let's try this now :
case class C(i: Int) {
   def f = {
     i = i + 10
     C(i = i + 10)
   }
}

Ok now this is the world I know : i is a val, then you cannot mutate it so i = i + 10 does not compile. However, C(i = i + 10) still compiles without complaining. What is this weirdness ? Is there a reason for thatto exist ?
Answer: This is because, in the case of C(i = i + 10) the left-hand i is not the field C#i but a named parameter.  No assignment is being done at all.
C(i = i + 10)
  ^   ^
  +---|-------- Parameter name
      |
      +- - - - - - - - - - - - - - Reference to the field `i`
                                   in the instance of the class `C`

Some places where named parameters make sense:

Avoiding the "what does this {boolean, integer} mean" moment:
someMethod(anObject, flagName=true)
// As opposed to someMethod(anObject, true) ... what's `true` for?

anotherMethod(arg1, arg2, totalMagic=33)

When using default values for parameters (to invoke the right constructor):
def withDefaults(i: Int, flag: Boolean = true, wrapper: Option[String] = None) = {
  wrapper.fold(s"$i with $flag")(_.format(i, flag))
}

withDefaults(3, Some("stuff %s around %s"))
// won't compile
// error: type mismatch;
//  found   : Some[String]
//  required: Boolean

withDefaults(3, wrapper = Some("stuff %s around %s"))
// works (returns "stuff 3 around true")

Comment: Oh, right I did not know this syntax. Is there any advantage to do this ? I just tried using it and it allows, for example, to pass the parameters in a random order which I don't find really good as quite often the order of the parameters has some semantic
Comment: @Dici - updated with some examples of why you might use it

Assignments in Scala


how to iterate over entries in a file making a dictionary with unique values and calculate an average for each value that can occur multiple times?

Question: I have a table that looks like this:
id  value
AGA 0.211
AGA 0.433
AGA 0.123
AGH 0.002
DHI 0.063
DHI 0.193
DHI 0.004
KHI 0.543
KHI 0.064
HID 0.234

For each id there are sometimes different values. I want to count how many entrances there are for each id, the average and the sum of the values for each id so the outcome would be something like this:
id      cnt   sum   av
AGA     3     0.76  0.25
AGH     1     0.002 0.002
DHI     3     0.26  0.008
KHI     2     0.607 0.304
HID     1     0.234 0.234

I thouht it would be best to first make a dictionary where I count each entry, but got stuck after that, not knowing if it is best to have the value of the dictionary as an array (with the cnt, sum and av) and by then using the range of the Cnt to calculate, but could not think of ways to do that! This is how far I got:
idDict = {}
for line in file:
    line = line.rstrip()
    f = line.split()
    id = f[0]
    idDict[id] = idDict.get(id, 0) + 1

But if I have already created the dictionary here with the cnt, I dont know how to iterate over each id to do the sum and av calculations :(
Answer: Here is a way starting out with defaultdict:
from collections import defaultdict

mylist=[('AGA' ,0.211), ('AGA' ,0.433), ('AGA' ,0.123), ('AGH' ,0.002),
        ('DHI', 0.063), ('DHI' ,0.193), ('DHI' ,0.004), ('KHI' ,0.543),
        ('KHI' ,0.064), ('HID' ,0.234)]

mydict = defaultdict(list)
for key, val in mylist:
    mydict[key].append(val)

summary = {}
for key, val in mydict.items():
    summary[key] = len(val), sum(val), sum(val)/len(val)

print summary
#Output:
{'KHI': (2, 0.60699999999999998, 0.30349999999999999),
 'HID': (1, 0.23400000000000001, 0.23400000000000001),
 'AGA': (3, 0.76700000000000002, 0.25566666666666665),
 'DHI': (3, 0.26000000000000001, 0.08666666666666667),
 'AGH': (1, 0.002, 0.002)}

Answer: Since the data in you table seems to be sorted, there is actually no need to first put everything in a dictionary, but it might make things clearer. But I guess your table could get quite big, so storing everything a second time is a resource killer...
def sum_up(id, list):
    counted = len(list)
    summed = sum(list)
    avrg = summed/counted
    # print, insert or do whatever needed with the lines:
    print counted, summed, avrg

last_id = None
current = []
for line in file:
    (id, value) = line.split()
    if last_id != id:
        if last_id is not None:
            # evaluate last id
            sum_up(last_id, current)
            current = []
        # remember id
        last_id = id
    # append to current ids entries
    current.append(value)

# do the last id, if there is any:
if len(current) > 0:
    sum_up(last_id, current)

i didn't test that code, but you should get the idea. It looks a little complicated, but when you have >100k lines or so, you should be feeling a difference to first loading everything in memory and then working on it


Taylor expansion about candidate point $x^*$: $f(x^∗ + h) = f(x^∗) + hf'(x^∗) + O(h^2)$?

Question: My textbook, Algorithms for Optimization, by Kochenderfer and Wheeler, says the following:

A point can also be at a local minimum if it has a zero derivative and the second derivative is merely nonnegative:

$f'(x^∗) = 0$, the first-order necessary condition (FONC)
$f''(x^∗) \ge 0$, the second-order necessary condition (SONC)

These conditions are referred to as necessary because all local minima obey these two rules. Unfortunately, not all points with a zero derivative and a zero second derivative are local minima, as demonstrated in figure 1.7.
The first necessary condition can be derived using the Taylor expansion about our candidate point $x^*$:
$$f(x^∗ + h) = f(x^∗) + hf'(x^∗) + O(h^2)$$
$$f(x^∗ − h) = f(x^∗) − hf'(x^∗) + O(h^2)$$
$$f(x^∗ + h) \ge f(x^∗) \Rightarrow hf'(x^∗) \ge 0$$
$$f(x^∗ − h) \ge f(x^∗) \Rightarrow hf'(x^∗) \le 0$$
$$\Rightarrow f'(x^∗)=0$$

Appendix C states the Taylor expansion about $a$ as

$$f(x) \approx f(a) + f'(a)(x - a) + \dfrac{1}{2} f''(a)(x - a)^2$$

So if we want the Taylor expansion about our candidate point $x^*$, as the textbook states, then we have
$$f(x) \approx f(x^*) + f'(x^*)(x - x^*) + \dfrac{1}{2} f''(x^*)(x - x^*)^2,$$
which is not $f(x^∗ + h) = f(x^∗) + hf'(x^∗) + O(h^2)$.
Or if we set $x = x^* + h$, we get
$$f(x^* + h) \approx f(a) + f'(a)(x^* + h - a) + \dfrac{1}{2} f''(a)(x^* + h - a)^2,$$
which is not $f(x^∗ + h) = f(x^∗) + hf'(x^∗) + O(h^2)$.
Or if we set $x = x^* + h$ and take the Taylor expansion about $h$ (rather than $x^*$ as was stated), we get
$$f(x^* + h) \approx f(h) + f'(h)(x^*) + \dfrac{1}{2} f''(h)(x^*)^2,$$
which is not $f(x^∗ + h) = f(x^∗) + hf'(x^∗) + O(h^2)$.
So I'm confused as to how the authors' result makes sense? I would greatly appreciate it if someone would please take the time to clarify this.
Answer: Have you tried
$$x=x^*+h, a=x^*$$?
Comment: Ahh, that's it. Thanks for the clarification.


Can we simplify this matrix using Vandermonde?

Question: The background has a close practical reference to (computer aided) 3D visualization techniques. It is about "melting" spheres using so-called Blinn objects (shortly "Blobs"):

For this we need a Gaussian function $g(q)=\frac{1}{\sigma\sqrt{2\pi}}e^{\frac{-|q-c|^2}{2\sigma^2}}$, $q,c\in\mathbb{R}^3,\sigma\in\mathbb{R}^+$. The Blobs are given by the set: $B_g=\{q\in\mathbb{R}^3|g_{\sigma,c}(q)=k\}$. The variable $c$ is the center of a Blob. Varying $\sigma$ adjusts the radius of a Blob. Composing these Blobs leads to a "Blobby Surface" in which the Blobs $B_i$ are melted together. For this we use the implicit functions $g_i$ and constants $k_i$:
$$
f(q)=-k+\sum_{i=1}^ng_i(q)~~\text{where}~~k=\sum_{i=1}^nk_i
$$
The challenge is to replace the Gaussian function by a polynom to make calculations more efficient. This can be done by approximating $g$ using a polynomial $p(x)=a_0+a_2x^2+a_4x^4+\ldots+a_{2n}x^{2n}$, where we set $p(0)=g(0)=a_0$ and $\frac{\partial}{\partial x}p(x)=\frac{\partial}{\partial x}g(x)$ for $x_1=t,x_2=2t,\ldots,x_n=nt$, $t\in\mathbb{R}^+$.
The question is: Using Vandermonde (or some similar tricks), can we simplify the resulting matrix equation that solves the coefficients of our polynomial:
$$
\begin{pmatrix}
    a_2\\
    a_4\\
    \vdots\\
    a_{2n}
\end{pmatrix}
=
\begin{pmatrix}
    2\cdot(1t) & 4\cdot(1t)^3 & \cdots & 2n\cdot(1t)^{2n-1}\\
    2\cdot(2t) & 4\cdot(2t)^3 & \cdots & 2n\cdot(2t)^{2n-1}\\
    \vdots & \vdots & \ddots & \vdots \\
    2\cdot(nt) & 4\cdot(nt)^3 & \cdots & 2n\cdot(nt)^{2n-1}&
\end{pmatrix}
\begin{pmatrix}
    g'(1t)\\
    g'(2t)\\
    \vdots\\
    g'(nt)
\end{pmatrix}
$$
I see that the matrix structure looks a little bit like it would allow simplification using Vandermonde. Maybe there exist some tricks that enable us to benefit from Vandermonde.
For those who are interested in the approximation result (in 3D):
The original "Blobby Surface" is depicted on the left and the approximated surface on the right:
$\require{HTML}
\newcommand{\mypic}[4][]{
\style{
display: inline-block;
background: url(https://i.stack.imgur.com/#4) no-repeat center;
 #1
}{\phantom{\Rule{#2}{#3}{0px}}}}$
$$\begin{array}{cc}
\mypic{280px}{300px}{4lD4xm.png}&
\mypic{280px}{300px}{cmNLWm.png}
\end{array}$$
The approximation of the Gaussian curve (red) by the polynomial (blue) looks as follows:
Answer: The coefficient matrix $M$ of entries
$$
M_{ij}=(2j)(it)^{2j-1},\qquad i,j=1,\dots,n,
$$
can be factorized as
$$
M=diag(2,4,\dots,2n)V(1,4,\dots,n^2)diag(2t,(2t)^3,\dots,t^{2n-1})
$$
where $V(x_1,\dots,x_n)$ is the Vandermonde matrix, with entries $V(x_1,\dots,x_n)_{i,j} = x_i^{j-1}$.
Thus to invert $M$ it is enough to invert the particular Vandermonde matrix $V(1,4,\dots,n^2)$. There are general formulae for the inverse of $V(x_1,\dots,x_n)$, though I do not know if they give anything explicit in this case.
Comment: Thank you very much for working out this. I will try this.
Answer: This is more a comment, but I lack the reputation to comment; intended to help find pertinent background information and understanding.
The generalization of Blinn objects are metaballs, where the Gaussian function $g()$ is replaced by an arbitrary real function; most typically a function of the distance to the center of each metaball component.
The most generic form for a metaball is
$$\sum_k g(x, y, z, x_k, y_k, z_k, w_k) \le C \tag{1}\label{BtV1}$$
where $x_k, y_k, z_k$ is a vector referring to the center of metaball component $k$, $w_k$ is the weight factor of said component, and $C$ is the isosurface threshold.  ($\eqref{BtV1}$ is true for the volume within the metaball; for the isosurface, the sum equals $C$.)
Typical form used in computer graphics is
$$\begin{aligned} g(x, y, z, x_k, y_k, z_k, w_k) &= w_k f(r_k^2) \\
r_k^2 &= (x - x_k)^2 + (y - y_k)^2 + (z - z_k)^2 \\
\end{aligned}$$
with $f(r_k^2) = r_k^{-4}$ (i.e. $f(x) = 1/x^2$) being a common choice.
Sometimes different support functions $f$ are used, so that the metaball equation used is actually
$$\sum_k w_k f_k(r_k^2) \le C$$
The reason squared distance is used, is that the square root operation is computationally relatively expensive, and using integer powers of distance squared avoids that, yielding a computationally more efficient (faster) object evaluation.
Comment: @EldarSultanow: Thank you! One of the reasons different support functions $f_k()$ are used, is when the metaball components themselves are animated/modified: different widths of the support function curve changes the apparent behaviour (consider e.g. narrow/tight $f()$ for "eyes" the metaball can "produce" to its surface).  I also forgot that many programmers use them but call them "blobs", so if looking for tips on *implementing* them efficiently in computer code, "blob" is also a term to look for.
Comment: First of all, welcome to the community! And thank you for your comment on generalizing Blobs using metaballs, which is very useful here.


Monster taxonomy in the Witcher 2 (for blade oil usage)

Question: There are several different blade oils available that cause more damage to certain classes of monsters, e.g. spectre oil, arachnid oil, necrophage oil and insectoid oil.
Most of the monster classifications are pretty straightforward, but I don't know the correct classification for every monster for sure.
So, which monsters belong into which monster class?
Comment: I was just about to post an answer here when I realized there are more oils available than listed in the manual alone. So further research is required.
Answer: If you press "C" for Character, then select Attributes at the bottom right, then Knowledge is the middle of three icons.  Under that knowledge panel it lists the knowledge you'll find more detailed descriptions (if Geralt knows them, via reading books or experience fighting).
It will sometimes reference specific blade oils to use (for example Wraiths mention Specter Oil) but unfortunately still no clear categorization - I'm pretty sure Endragas are Insectoid, but their entry doesn't say so, and Necrophages is listed as a single entry, with mention of Rotfiends in the description rather than the name/category.
Answer: Oils are specifically named after they monsters they are useful for. So use necrophage oil for necrophages (lesser and greater), spectre/wraith oil against spectres and wraiths and so on. Alternatively you can use the +10% damage oil which applies to all types of enemies.
It's not a major thing though.
Comment: I'm asking specifically which monsters belong to each group, e.g. what monster type are Nekkers?
Comment: I haven't found an oil that can be specifically used for nekkers however Brown Oil and Falka's Blood work well. I do not think the game bestiary is large enough to have generic types of monsters with particular subspecies hence the oils were named after specific types.
Answer: You could simply use a whetstone for +20% sword damage always. Add a +10% Damage Potion (Rook i think) and get it on.
AFAIK $Oil + Whetstone does not stack , so if the "+20% against specific" for Oils is correct i do not see a point using them at all. Or is the specific targeting effect greater?
Dmg-Potion + Dmg-Oil/Whetstone do stack, so youll can run around with +30% trough buffs alone. :)
Comment: Whetstones? I haven't seen any whetstones in the game, yet.
Comment: @Raven-Dreamer 10 oder 20 are included in the Swordsman Preorder DLC. But im sure i've seen the recipe somewhere, too. Didnt even think about them being possibly nowhere else because i was used to this item from TW1. ill check again and get back here.


How are the winners of ties determined in Capture the Flag?

Question: In Battlefield 3's Capture the Flag game mode, ties happen quite a lot, with neither team reaching the requisite 3 captures and ending up with the same amount as the other team (Sometimes 0-0). But there doesn't seem to be consistency on who is the "winner" in these cases.
It does not appear to be whoever is closer to gaining another flag, as I lost a match when our flag carrier was only feet from scoring the final flag when time ran out.
It does not appear to be who was ahead for longer, as I've played matches where my team was up 2-0 for most of the game, then the other team tied it up near the end of the match.
Is there any official word on how this winner is determined? Barring that, is there any good explanation for one reason or another?
Comment: Flagged as too flaggy.
Answer: From my own experience (and I play it a lot), when the flag captures are tied, the team with the higher score wins (total points of all players of the team).
More specific from the Battlefield 3 Wikia

In the event of a tie by equal number of flags captured by both teams, there is a winner, this is determined by the team with the highest cumulative score. In the rare occasion that both teams have an equal cumulative score, the victor will be the US team by default.

Additional sources:

https://twitter.com/gustavhalling/status/311736490830991360


How do I read weapon / armor stats in ADOM?

Question: For example, I know that:

Armors: [+dv, +pv].
Weapons: (+hc, dmg) where dmg is something like 1d4.

How about missile weapon and missiles?
Where can I find a information about these? I can't find them in the manual / guidebook / wiki because I don't know what they're called.
Answer: They are the same as melee weapons. The projectile itself will list the accuracy and die damage, while a launcher (e.g. bow) provides to-hit and damage bonuses, displayed in that order.


How do I disable my search box if the user hasn't entered any characters?

Question: Basically my WordPress theme's search results page doesn't return a "normal" looking page when no characters are submitted. When you use the search tool properly though and actually type something in, it works just fine.
So instead of looking deeper into this, is there a way to simply disable the search box so it doesn't submit anything unless something has actually been typed in?
Thanks.
Comment: If you disable the search box, they can't type any characters in (because it is disabled). You want to disable the submit button as AlienArrays is suggesting.
Comment: but if you go straight to the search page anyway...
Comment: Just use a default search string if nothing is entered that shows what you want to highlight on your site.
Answer: Check this: jquery-placeholder
Answer: This is just a basic form validation thing.
Add something like this to your javascript to prevent submits on empty.
Note: this is incomplete, you'd want to message them with something at this point.
<code>jQuery(document).ready(function($){
    $('#searchform').submit(function _validate(){
        if($('#s').val() == ""){
            return false;
            }
        });
});
</code>


Uses for extra science packs

Question: I recently demolished my base because it had grown into a knotted mess (and I wanted an excuse to set up a roboport network).
I realized post-demolition that I have around 100k green and red science packs, and that I only need another 32k of each to finish all the remaining research (I still need ~20k of the blue and purples though).
Is there any use for my remaining ~70k red and green packs? Can I get materials back from them? Are they worth keeping for anything?
Answer: If you intend to continue playing post 0.15 release, then you can just wait and use them for Infinite Research, but beware of Research Revolution.
Comment: Ohh, good find. Part 2 of my question (which I neglected to include for some reason) is "should I rebuild my red/green factories?". I take this as I should.
Comment: @Carcigenicate Note that the research costs are [planned to change as well](https://www.factorio.com/blog/post/fff-159). So you would probably have to rebuild the rest of your factory...
Comment: @Tim I ended up remaking the red and greens. Just in case.
Comment: 0.15 will disrupt all research anyway, not just cost  Really, I think only red and green will be the same (I think, but I might be wrong on green).  Kovarex posted about this in a recent FFF.  Which you should read if you don't.
Comment: @JürgenA.Erhard, which FFF exactly?
Comment: Here, let me google that for you ;-)  https://www.factorio.com/blog/post/fff-159
Answer: Without the use of mods, its not possible to recycle materials of any sort.  I found a Steam forum post discussing this matter.  You can destroy them by placing them in a chest and then destroying the chest, but that's not really a "use."
I also found a Reddit post that discusses the same topic.
There aren't any other uses for science packs besides using them for research.
Comment: http://gaming.stackexchange.com/questions/257009/is-there-a-trashcan-function relevant question

Uses for extra science packs


Permission to take photo OR get image from library not shown in iOS9 (Xcode 7beta, Swift2)

Question: The code below shows an example for my access to the image lib. No matter where I call the code (view) I do not see the permission dialog from the phone popping up and therefore cannot allow my app to access either camera or library.
Also, the privacy settings do not show my app either. Any thoughts? I'm going nuts.
<code>       let imgPicker = UIImagePickerController()
        imgPicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        imgPicker.modalPresentationStyle = UIModalPresentationStyle.Popover
        self.presentViewController(imgPicker, animated: true, completion: nil)
</code>

another way I tried
<code>            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
                let imagePicker:UIImagePickerController = self.imagePickerController

                imagePicker.allowsEditing       =   true
                imagePicker.sourceType          =   UIImagePickerControllerSourceType.Camera
                imagePicker.cameraCaptureMode   =   UIImagePickerControllerCameraCaptureMode.Photo
                imagePicker.cameraDevice        =   UIImagePickerControllerCameraDevice.Rear
                imagePicker.showsCameraControls =   true
                imagePicker.navigationBarHidden =   true
                imagePicker.toolbarHidden       =   true
                imagePicker.delegate = self

            self.presentViewController(imagePicker, animated: true, completion: nil)
            }
</code>
Answer: You need to set a new pair of Info.plist values, same as the String for Location Services would be in iOS8:
Just set your description string for those.
Comment: This is not the solution.
Answer: Check info.plist.
if "Bundle display name" set as nothing,
At iOS 8.1 will popup permission window like this

"" Would Like to Access Your Photos

But at iOS 9, there is no popup permission at all.
Also, no permission setting, at Setting > Privacy > Photos > Your app name.
To solve this,

Remove "Bundle display name" in your info.plist.
Comment: Mine did not have Bundle display name to begin with and has this issue. What to do then?
Comment: I cant comment on if removing it all together is the correct method, BUT i just filled in the 'string' area with the actual name of the app, works.
Comment: This is definitely a wrong answer. The correct answer is what @longbow said, you have to fill in the appropriate info.plist strings.
Answer: Apparently this appears to be an issue with iOS9. For some reason the permission access dialog does not pop up. I have successfully tested on iOS8, using the same code.
Comment: Do you have a fix for this yet?
Comment: No. I went back to iOS 8 for now. No time to mess with these issues. Sorry.
Comment: @DirkLX Did you get a fix for this yet?


Are there Rare Drops in Captain Scarlett?

Question: After completing the DLC I've become aware that the new rarity level items can only be purchased (with a special currency). I didn't notice any oranges (period) while playing, particularly new oranges, though I noticed a few unique (probably common) drops from bosses.
Are there any rare (legendary/orange) drops in the Captain Scarlett DLC or are Seraph weapons and the new blue Uniques the only new equipment?
Answer: There is no new legendary items unique to the DLC, only some blue and purple rarity items.
And regarding the Seraph crystals, they no longer drop on normal/TVHM, only on UVHM.
Both raid bosses hyperius and master gee have chance to drop variety of legendaries from the main campaign and some seraph items.
Generally the Sandhawk and Rapier are the only worthwhile items on the DLC and they are both easily obtainable by just playing through the dlc.
Leviathan's lair has a pretty good chance to drop great relics and mods.
Answer: What i can tell for sure about the Captain Scarlett DLC loot is the following:
Quests rewards:
SMG which shoots bullets in a flying bird pattern
Sniper rifle from which bullets explode into shock bombs upon impact
I found a legendary nade mod "Rolling Thunder" in one the chests.
You can read more info about the loot table in this post B2 Pirate DLC Treasures
Hope this helps :)
Comment: [Rolling thunder](http://borderlands.wikia.com/wiki/Rolling_Thunder) is actually from the main game (of course main game items show up in the DLC too)
Answer: Did not notice any oranges, though they can theoretically drop from anyone.
Comment: Have to correct myself: Just found an orange one during the second take at the Leviathan.
Answer: There is a lot of new loot in this DLC. There are new unique items, the seraph (pink) items, a lot of white, green, blue, and purple items, and new e-tech items. There are no new orange items that I've seen. However, the raid bosses do drop some of the old orange weapons. The armory at the end of the game also has a pretty high drop rate for orange items.


How can I store compound data in a struct without copying?

Question: The following program tries to store a Thing in a Holder:
struct Holder:
    var thing: Thing
    fn __init__(inout self, owned thing: Thing):
        self.thing = thing
        pass

struct Thing:
    fn __init__(inout self):

thing = Thing()
Holder(thing^)

When I run the program, I get the following error message:
error: Expression [59]:8:22: value of type 'Thing' cannot be copied into its destination
        self.thing = thing

Here's why I expected this code to run without errors:

The ^ transfers ownership, so the module scope no longer owns thing
__init__ takes Thing as owned

I know I can make the code run by implementing a __copyinit__ but is there a way to avoid the copy?
When I translate to Rust the program compiles and runs:
struct Holder {
    thing: Thing
}

struct Thing {}

fn main() {
    Holder { thing: Thing {} };
}

rust playground
Answer: You need to implement the Thing.__moveinit__ function and also pass the ownership between varibales inside the __init__ function: from thing argument variable to self.thing member variable
struct Thing:
    fn __init__(inout self):
        ...

    fn __moveinit__(inout self, owned other: Self):
        ...

struct Holder:
    var thing: Thing
    fn __init__(inout self, owned thing_arg: Thing):
        self.thing = thing_arg^ # <--- see the transfer operator (^) here

fn main():
    let thing = Thing()
    let holder = Holder(thing^)

It's a bit confusing but there are 3 variables instead of 2, if you name all of them thing it's easy to miss it:

varible thing
argument thing_arg
field self.thing


how to plot histogram and bar chart using for loop and display them together?

Question: I want to plot histogram for numerical data and bar chart for categorical data. I have classified the data type already stored in types.
I'm not sure how to put the plt.hist() and plt.bar() into my for loop so that there will be 2 histogram (one for age and another for saving) displayed together side by side. Same goes to the categorical data, I want the 2 bar chart for 2 categorical data (gender and job). The code able to count the frequency of data also in order to plot histogram.
Which means at the end, I will have 4 chart, 2 are histogram and 2 are bar chart will show out all together side by side.
import numpy as np
from scipy import stats

# first data is age
# 2nd data is gender
# third data is saving
# 4th data is job

data = np.array([[11, "male",1222,"teacher"],[23,"female",333,"student"],
                 [15,"male",542,"security"],[23,"male",4422,"farmer"],[25,"female",553,"farmer"],
                 [22, "male", 221, "teacher"],[27, "male", 333, "agent"],[11, "female", 33, "farmer"]])

# type of the data above
types = ["num","cat","num","cat"]
idx1 = []
idx2 = []
for index, _type in enumerate(types):
    if _type == 'num':
        idx1.append(index)
    else:
        idx2.append(index)

mean = []
std = []
for i in idx1:
    mean.append(np.mean(data[:,i].astype("float32")))
    std.append(np.std(data[:,i].astype("float32")))

print("mean: {}".format(mean))
print("std: {}".format(std))

mode = []
for i in idx2:
    mode.append(stats.mode(data[:,i]))
print("mode: {}".format([sub[0][0] for sub in mode]))

Answer: I will let you figure out the details of the plot as well as how to customize them, but my suggestion would be to turn it into a DataFrame object instead.
data = pd.DataFrame({'Age': [11, 23, 15, 23, 25, 22, 27,11],
                     'Gender': ['M', 'F', 'M', 'M', 'F', 'M', 'M', 'F'],
                     'Saving': [1222, 333, 542, 4422, 553, 221, 333, 333],
                     'Occupation': ['teacher', 'student', 'security', 'farmer', 'farmer', 'teacher', 'agent', 'farmer']})

fig, ax = plt.subplots(nrows = 2, ncols = 2, figsize=(10, 5))

# Plot Data
plt.subplot(1,2,1)
plt.hist(data['Age'], edgecolor = 'k')
plt.subplot(1,2,2)
plt.hist(data['Saving'], edgecolor = 'k')
plt.show()
plt.subplot(2, 1, 1)
data['Gender'].value_counts().plot(kind = 'bar')
plt.show()
plt.subplot(2, 2, 2)
data['Occupation'].value_counts().plot(kind = 'bar')
plt.show()

Comment: Hi, thanks for the reply! However, I want to simplify the coding (plot in the loop), that's why I didn't use the code above. I hope the code able to create the graph inside the for loop because if the amount of data is big, then it doesn't make sense to plot one by one. Any ideas how to do that?
Comment: Seems like a lot of looping to me. How much data are we talking about?
Comment: The actual data consist of 16 features with 11700 samples. So there are a lot if I want to generate bar chart and histogram for 16 features one by one.


No audio no matter what device I connect!

Question: My sound is not working... Internal audio? Nope! Headphones? Nope... Nothing! I have looked through all the audio settings and nothing has worked! I cant watch YouTube videos without audio! However, There is one sound that works... And that's the volume up and down sound!
Kubuntu 20.04 LTS
Answer: I have fixed this! I forgot that the specific app I was using was muted... For some reason!


Data Binding Issue text in label is not displaying data

Question: The following Label does not show data while running it <Label Text="{Binding Firstname}"/> if I run code in Debug mode and if I change Label to Editor or something else it shows data.
Please let me know why is that and how can I solve it.
Code Behind
Private fields
    private string email;
    private string phone;
    private string firstname;
    private string lastname;

Method calling data from FirebaseFirestore
        public async Task GetDataAsync()
    {
       var user = await DependencyService.Get<IAccountService>().GetUserAsync();

        phone = user.Phone;
        email = user.Email;
        firstname = user.Firstname;
        lastname = user.Lastname;
    }

Public properties
     public string Firstname
    {
        get { return firstname; }
        set
        {
            firstname = value;
            OnPropertyChanged(nameof(Firstname));
        }
    }
    public string Lastname
    {
        get {return lastname;}
        set
        {
            lastname = value;
            OnPropertyChanged(nameof(Lastname));

        }
    }

    public string Email
    {
        set
        {
            if (email != value)
            {
                email = value;
                OnPropertyChanged("Email");
            }
        }
        get
        {
            return email;
        }
    }
    public string Phone
    {
        set
        {
            if (phone != value)
            {
                phone = value;
                OnPropertyChanged("Phone");
            }
        }
        get
        {
            return phone;
        }
    }

Comment: How do you do the binding? And how do you use this label? In listView? If yes, have you reset the ItemsSource?
Comment: Thanks for the reply its a separate label only as you can see I am putting value on the backend property of the label.
Answer: This line:
firstname = user.Firstname;

Must be changed to:
Firstname = user.Firstname;

Explanation:
If you don't use the Firstname property setter, then OnPropertyChanged(nameof(Firstname)); never gets called.
So XAML does not know that the property's value has changed.
Comment: Thanks Steve it solved my issue.


How do I enable PHP 7.3 in Apache2

Question: I followed the instructions in https://idroot.us/install-php-7-3-ubuntu-18-04/ to install PHP 7.3 and then, as instructed, ran
a2enmod proxy_fcgi setenvif

a2enconf php7.3-fpm

to enable it in Apache2.
systemctl status php7.3-fpm

confirms that php7.3 is installed and running and I did restart Apache2 using
systemctl restart apache2

php -v reports PHP 7.3.6-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: May 31 2019 11:06:48) ( NTS )
However, phpinfo(); reports PHP 7.2: PHP Version 7.2.17-0ubuntu0.18.04.1
What have I missed? Any guidance would be appreciated as I'm totally new to Ubuntu.
Thanks
Answer: You have to disable the older version of PHP (a2dismod [oldversion]) and then enable the new version with
sudo a2enmod php7.3

Then restart apache2
Comment: That means you haven't installed libapache2-mod-php7.3 yet.
Comment: `a2dismod php7.2` got rid of 7.2 and 7.3 appeared but 'a2enmod php7.3' failed, saying `ERROR: Module php7.3 does not exist!`.
While that means I have a working 7.3 it looks like I have still messed up somewhere.
How do I totally remove 7.2 (once I am happy 7.3 is fine)?
Comment: Be aware that you've got to get 7.3 working in apache, AND mysql (probably 5.7.27 as of this post) working in php 7.3 - so the `php7.3-mysql` package is very important.  When you do `phpinfo()` from the browser, make sure it's showing mysql support as well.
Answer: In my case I had to do the following
sudo add-apt-repository ppa:ondrej/php

sudo apt-get install php7.3 php7.3-cli php7.3-mysql php7.3-gd php7.3-imagick php7.3-recode php7.3-tidy php7.3-xmlrpc php7.3-common php7.3-curl php7.3-mbstring php7.3-xml php7.3-bcmath php7.3-bz2 php7.3-intl php7.3-json php7.3-readline php7.3-zip

sudo apt install libapache2-mod-php7.3

sudo a2enmod php7.3

After install apache still used php7.0, so I had to remove 7.0 configs manually:
cd /etc/apache2/mods-enabled
ls -la | grep php
sudo rm php7.0.conf

And finally
sudo service apache2 restart

Comment: Terrible idea, don't add a ppa for php. Also don't rm the conf files, the command is a2dismod.
Comment: @Nobody Why is it a terrible idea to add a PPA for PHP?
Comment: @slhck Because PPAs lower stability and security and in this case for no benefit at all.
Comment: @Nobody The benefit is that you get PHP 7.3 instead of 7.2. The PPA seems to be used a lot, so if anything you have more eyes on it.

How do I enable PHP 7.3 in Apache2


How to install Tor hardened using terminal

Question: I'm using Kubuntu 16.10 and I'd like to install tor browser bundle. I saw that there is a tor hardened version and sandboxed version.
I downloaded packages but just extracting them doesn't work for me. So I need now to know how can i install both of them using terminal.
Answer: There is a "Linux Instructions" section in the download page.
Take the hardened version for example, just decompress the file: tar -xvJf tor-browser-linux64-6.5a6-hardened_ALL.tar.xz
And change the working directory: cd tor-browser/
Start the browser: ./start-tor-browser.desktop
One note on the instruction page is that not to unpack or run TBB as root.


Why was the Regalia Type-D reverted in chapter 7?

Question: At some early point in the game (think chapter 3) I upgraded the Regalia to Type-D. All good.
However, in the end of chapter 6 there was a message saying the Regalia has been reverted back to its original form, and indeed, the Type-D is gone, and I can't go off-road anymore.
Why did it happen? Is there some official/logical explanation for this?
Note: as part of the main quest, I can't go back to Hammerhead in order to try changing it back.
Comment: Were you able to go back to Cindy and change it back to Regalia Type D?
Comment: @Wondercricket not yet, I'm now "stuck" between two blockades and can't go back to the pre-chapter 7 places. I assume that in the next chapter the Type-D will be back, either automatically or by changing manually again, but wonder why I can't use it in 7.
Comment: Are you looking for something that makes sense in terms of story, or in terms of gameplay (or both)? A common example of the latter is "we needed to keep the player within X area".
Comment: @ChrisHayes both, thanks. (though the later might be considered opinion based)
Answer: The later half of the story is significantly more railroaded (both literally and figuratively) than the first, which is basically a true open-world game. After you embark on the boat, the Regalia can't even be used again (only returns in a single driving scene / minigame, if I remember correctly) until you get to the post-game content, where the modification becomes available again.


Is it a good idea to place an electric boiler on the warm water line?

Question: I have a condensing gas boiler (tank-less) at one end of my house. I have a bathroom at the the other end of my house, at a higher level.
In the morning if I open the hot water tap it takes about 15L (~4 gallons) of water, and 60-70 seconds to get hot water because the water line is very long and the cold water needs to be displaced before the actual warm water "arrives". The gas boiler is powerful and produces hot water very fast and very hot. But the cold-water-displacement part is the problem.
Obviously this is annoying and I was thinking to install a (classic) electric boiler (small, 30L / 8 gallons) to use as a buffer MOUNTED ON THE WARM WATER LINE AND NOT ON THE COLD ONE. This would hold a buffer of warm water by using electrical energy. In the morning when I open the hot water tap I would get warm water from the electric boiler which, in turn, would refill from the warm water line which for the first 60-70 seconds would get quite cold water.
This would be, IMO, an acceptable trade-off of space, electric bill etc. in exchange for the convenience of having warm water anytime.
My CONCERN is if I keep using it after the cold water "finished" and fresh, hot water is fed in the electric boiler, would it hurt it? Or would it hurt me (by serving too hot water) or some other disadvantage that I cannot think of?
Comment: I have read of the re-circulation method but as far as I could understand this would not work with a tank-less boiler...
Comment: I have a Navian on demand HW heater and it does support re-circ. But the OP should weigh the costs of keeping a hot water supply up to temp constantly vs. the cost of running the water until the hot water "arrives".....there is also the convenience factor to be considered...    who wants to wait for up to a minute to get hot water???  Everything is a tradeoff.
Comment: @AndreiRînea   The on demand WH w/re-circ does not keep the flame going all the time, it only fires up when the temp in the re-circ line drops to a certain set point, and then only for a minute or two.   But and here's the big BUT, unless the WH re-circ can be put on a timer, like "don't do this a night" it will do this 24/7 and will consume additional fuel.  Re-circs are very nice for large houses with spread out bathrooms, etc. but they come with the price of keeping the hot water lines hot all time as well as running the re-circ pump.  Comes down to personal preference.
Comment: Think most people go with pipe insulation and a small circulating  pump to keep warm water near where it is needed.
Comment: @GeorgeAnderson: Wow, I thought re-circ is not suitable for on-demand/instant/tank-less heaters! On the other hand, it would keep the flame going and consuming potentially lots of gas. Oh, the 60-70 seconds of waiting for the water to reach the faucet (sorry for using "arriving" - English is not my native language) is only the first usage in the morning, the pipes get "primed" and subsequent usages are far more decent from a waiting time point of view.
Comment: Congratulations, we see many very stupid plans to combine tanked and tankless heaters. This is the first that isn't stupid.
Comment: But.... your numbers make no sense. A 3/8" water pipe has 1.57 cc per cm, so would need to be 95m long (over 300') to hold 15 litres.  A 1/2" water pipe is 2.5cc/cm, so 60m (200'). A 3/4" water pipe (foolish choice for a hot water line because of the wait) would be 34m long to contain 15l of water.   A house that big ought to have a satellite hot water system.  Also, purging 15l in 60s means a rather high shower flow (about 4 GPM), very luxurious but also very costly to heat.  Perhaps you can address those things.  A 1.5 GPM (6 l/m) shower is fine. The British electric showers are less.
Comment: @George I could see a re-circ being triggered by a 2 minute timer in the bathroom. Flip the timer as you're getting undressed. It runs for 2 minutes. It's done.  No burdensome 24x7 heating load.
Comment: @Harper-ReinstateMonica  might work, but only if the on-demand tankless supports remote switches.  A lot depends upon the exact model of the tankless  If there is a separate re-circ  pump that could be wired to a switch it could work.  In my case it's built into the Navian unit so that's a no-go for a timer.  It's in a vacation home so I simply turn the on-demand WH off when I'm not there.
Answer: Point of use water heaters are a common solution to the problem you are trying to solve. Most operate on 120 Volt and can plug into a standard outlet and take about 12 amps. You can set the temperature a degree or two lower on it so when the water from the main heater gets to it, the smaller unit will turn off. This will not hurt your smaller unit. Just a safety note, both heaters should be set so the water won't seriously burn you.
Comment: @Andrei Setting a storage heater at much less than 60C (140F) is a plan to breed very nasty bacteria that will send you to the hospital.  This was exposed after Flint, Michigan made changes to their water supply and had a rash of these cases at once. This has been happening all along, but as random isolated incidents, so a pattern was never observed until Flint.   *Of course this advice contradicts "don't use scalding temperatures", and the cure for that is a thermostatic mixing valve.*
Comment: Thanks @George Anderson
Comment: that is a good idea, I would set the main heater to 104F (40C) degres and the small electric one to 107F (42C)!
Comment: @Harper-ReinstateMonica It seems what happened in Flint was much more complicated than people not heating their water hot enough. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5353852/  If it weren't for all the other problems there would have been enough chlorine in the water to avoid the bacterical contamination https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5828617/
Comment: @DDuck Well that would be great if your goal was to rationalize away any need to deal with the issue.  "Just don't live in Flint! Solved!"  But I would follow the advice of my national health department, I think.
Comment: In most locations the water wasted waiting for hot water for a shower could be considered negligible compared to the amount used for the shower. The lavatory is different. Often only a small amount of water is to be dispensed and it is relatively wasteful to dump 5 or 10 times the amount of water one needs to get to warm water. In this case a 120 V point-of-use tankless WH or very small tank would remedy this. The most efficient way to do this would be to plumb the lavatory with cold water only and divert some of the cold through a point-of-use WH.
Comment: Generally there is not a 120 V receptacle under the bathroom lavatory so installing an electric point of use WH in a bathroom would require installing that. We have a gas fired tankless central WH and I don't like the thought of the waste water and wear on the WH in dispensing small amounts of hot or warm water from the lavatory. For shaving I put a pint of warm water in a small pitcher. I use the cold water to wash the razor. I fill the pitcher with warm water from the shower at the end of my shower. When I am shaving without showering I warm water on the stove and take it into the bathroom.
Comment: To wash your face decant some hot water from an electric kettle into a bowl with some cold water in it and you have warm water without having to cycle your central gas fired water heater. For washing dishes I do not use hot water from the tap. (We do not have a dishwasher.) Next to the kitchen sink I have an 1800 W standalone induction heater and a 4 L kettle. We use our Bosch central tankless WH for showering and clothes washing. At the bathroom lavatory we dispense only cold water. We have not placed a small electric kettle in either bathroom, but this is always an option.
Comment: @JimStewart  Do you take a horse drawn wagon into town to go shopping?  :-) .....  i thought I was the only one without a dishwasher...
Comment: At a formative age I was in the Peace Corps in Fiji. Our quarters had cold running water, but not not a water heater. Cold showers were fine for most of the year but not winter. In winter we took a 4 L kettle of boiling water into the shower stall and mixed it with cold water in a bucket. Poured warm water over ourselves with a metal cup.
Answer: First, I would actually measure your numbers. Because I find 15l of water in the pipe to be non-believable.  That's 100m (300'+) if the pipe is 3/8" trade size, 60m (200') if 1/2" pipe, and 35m (100+') of 3/4" pipe, but 3/4" would be a dumb choice because it has a huge inventory of water, which means a ridiculous wait for hot water.
If your house really is that big, a single water heater for the whole house is impracticable.
Your tank needs to be pretty big, though.
Here's the thing.  As your tank refills, it's going to be filling with cold water. Hot water tanks are specifically designed to separate flow.  So for the first 2/3 (20 lit34s) of water, you'll take that off the top of the tank and it'll be tank temperature.  But with only 10 liters of old water left, what's in the tank? 15 liters of cold water from the pipe, and 5 liters of actually hot water that has finally made it through.  Let's say the pipe lives at 10C and you want the water at 40C.  Half the water in the tank will be 40C, and the other half 10C, now mixed together because the separation is no longer working.  What temperature will that water be?  That's right, 25C. Barely tepid.
And it will be like that for the next 20 liters of usage. Then for the following 30 litres or so, it will slowly blend to warm up bit by bit.
This will result in an annoying "mid-shower cold lump" that will probably just motivate you to take Navy showers lol.
But let's do it again with a 120 liter tank.  Now your first 80 liters are fine, and the first 15 liters of cold water will have plenty of time to diffuse into the last 40 liters remaining.
Temperature will also help.
You seem to want to run the hot water system at very close to desired final shower temperature.  That is dumb. You want to mix significantly hotter water with cold water, so you have some headroom for variances in hot water temperature.  (This might be a big part of why you need to run 15 liters of water to be comfortable).
Ideally, you want an automatic mixing valve, which will automatically adjust out these hot water temp variances, and also provide anti-scald protection.  Anti-scald protection in turn allows you to run the tank hotter still, which further stabilizes spigot temperature.
But much more importantly, hotter tank water allows the tank to stop dangerous bacteria growth - a phenomenon only recently understood, because fatalities from it happened sporadically and randomly.  When Flint, Michigan made abrupt changes to their water supply, among other things it triggered a large enough cluster of cases to become detectable! Investigation ensued and found low-temperature water tanks festooned with legionella and other bacteria. Before that, no one knew!
Now if you don't want a clunky "hotel style" valve, I hear you. They make much better thermostatic mixing valves which allow 2-dimensional control of flow and temperature - like a joystick. Sometimes flow is an ungainly push/pull, but temp is a fine control knob that can be simply left in the desired position.
But if you really like two valves, thermostatic mixing valves can be plumbed in right before the hot water tap.  This will mix in cold water as necessary to keep the the hot water tap right on target temperature. (and prevent scalding, of course).
Comment: As for pipe distance between WH and faucet it is about 25-30m indeed.
Comment: @AndreiRînea That seems roughly equivalent to 3/4" NPT, so yeah. Obviously someone thought bigger pipes were more deluxe... true on cold, but hot causes this.
Comment: The pipe is 1 inch in diameter. Even thicker than the 3/4 you mentioned..
Comment: Outer diameter, that is.. Polypropylene : https://www.leroymerlin.ro/produse/teava/662/teava-ppr-alba-cu-insertie-de-fibra-compozita-25-x-3.5-mm-l-4-m/1556
Comment: @Harper according to the instruction manual of my Bosch tankless WH operating it at a relatively low output temperature reduces the formation of boiler scale in the heat exchanger. It makes sense to operate the WH at the lowest temperature that will meet the demand. We set the gas flow to the burner to the lowest that will provide hot enough water for showering. So at the shower 90 % of the water is from the hot line and 10 % from the cold line. This means that the water at the kitchen sink is not hot enough to kill bacteria on flatware so we mix in scalding water from a kettle.
Comment: @Andrei someone wanted an upscale house in our neighborhood of 1970 built tract houses on 10,000 ft^2 lots. They demolished a 2000 ft^2 single story house and built a modern 3000 ft^2 2-story first quality custom house. For hot water they installed TWO first quality tankless water heaters on separate branches each I think about 180 kBTU / h. I think the conversion factor makes each WH about 50 kW so they have a total water heating capacity of 100 kW.  I suppose they don't have to wait long for hot water to arrive at a point of use.
Comment: @Andrei what country is this house in?
Comment: @Andrei is your water piping polypropylene or is it PEX? (PEX is polyethylene cross linked.) Do you know what is the recommended upper temperature limit for your house piping?
Comment: @JimStewart that makes sense for tankless.  For tanked, you have to address the elephant in the room, or rather, the bacteria in the tank. I agree 170k BTU/hr = 50 kW = 205 amps or so.  So they're talking over 400A just for that if they're doing it electric.  I would've gone for a 12 kW heater per bathroom myself, so you can lean more into load diversity.
Comment: Modern gas fired tankless water heaters have electronic controls that vary the gas flow to achieve a set output water temperature as the flow rate varies. Our primitive Bosch has no electronic controls. The gas flow is varied by a valve operated by a slider on the front. I am sure the OP's WH has electronic controls.
Comment: @JimStewart: The house is in Romania (see my profile). The water piping is Polypropylene (which is rated for -10..+95 Celsius / 14..203 Fahrenheit). I wish it was copper but I've bought the house already built..
Comment: We have had pinhole leaks in some of our 50 year old copper tubing; copper is definitely not perfect. I do not hear of polypropylene being used here in the US currently. Polybutylene was used at one time, but it had some failures. The least expensive piping used here now is PEX although some expensive builds do use copper. In some cheaper builds in the medium past PVC and CPVC were used for water distribution piping. Is your building a slab on grade, a basement, or a crawl space? Are the hot water lines (from water heater to point of use) in soil contact or in air under floors or in walls?
Comment: I believe the building is 'slab on grade' or close to that. I have little idea on how the hot water lines traverse the floor horizontally, I only found out vertical sections of the hot/cold pipes which have vents and visiting (small) doors. I do not think the pipes are in contact with the soil or slab.
Answer: One method is to run the hot water supply as a "loop" and each faucet is a small tee off the loop.
Then a small pump that drives the flow from and back to the tank will have water to each faucet quickly.
This is done in larger houses and buildings due to the waste of water that you describe.
Comment: my boiler does not have a tank, it is a tank-less boiler
Comment: @JimStewart: Immergas Victrix Tera 38 kW. Here's a general presentation: https://www.immergas.com/en/product?title=VICTRIX%20TERA%2038%201 and here's the user/installer manual: https://www.immergas.com/imp/0106G/Victrix-Tera-28-1_32-1-38-1-1040295_007.pdf
Comment: Water isn't metered, it's from a well..
Comment: @JimStewart I don't have any problem washing my face.
Comment: @JimStewart just wondered how your rant has anything to do with my answer?
Comment: @JimStewart then comment on the OP's post, which is at the top normally, not on my answer.


Geodesics on a manifold

Question:
Let $M$ be a manifold and $\gamma$ a curve in $M$. Geodesic curves are curves, for which $\ddot y(t)$ is orthogonal to $T_{y(t)}$
Proof that $\vert\dot \gamma \vert =\text{constant}$

Would appreciate any help.
Answer: Hint: given a Riemannian metric $\langle \cdot, \cdot \rangle$ on a manifold $M$, and letting $\frac{D}{dt}$ be the covariant derivative (i.e. parallel transport) with respect to a curve $\gamma: (-\epsilon, \epsilon) \to M$, then we have that
$$
\frac{d}{dt} \langle V, W \rangle \;\; =\;\; \left \langle \frac{DV}{dt}, W\right \rangle + \left \langle V, \frac{DW}{dt} \right \rangle.
$$
If $\gamma$ is a geodesic, what do you know about $\frac{D\dot{\gamma}}{dt}$?

Geodesics on a manifold


How do I get to the secret mission in Wings of Liberty?

Question: How do I reach the secret mission in Starcraft 2: Wings of Liberty?
Answer: In the Media Blitz mission, in the lower right area of the map (by the mineral fields), you will see a semi-hidden path. Go to the end and destroy the Science Facility building at the end of this path. You should pick up some secret documents that will give you the secret mission. This mission must be played while you're still on the Hyperion.
Comment: @DaveK You can unlock the mission after finishing the campaign, but there is no way to play it at that point. Sadly you need to start a new campaign (or load an old save) in order to play the secret mission.
Comment: Does the game allow you to go back after you complete the campaign and pick is up?
Answer: Check out this video:


Twin Battery issues after Ubuntu 22.04 install (ThinkPad)

Question: Lenovo ThinkPad X270, Ubuntu 20.04, everything worked OK.
Then I installed 22.04.
Now (on adapter) the top panel indicator shows battery at about 70%, not charging. In Power settings: built-in battery at 30%, adapter on, not charging. Swappable battery at 99%, adapter on, not charging.
When I unplug the laptop, top panel indicator tells me the estimated time remaining. In Power settings the built-in battery remains unchanged - 30%, adapter on (green color, lightning bolt), not charging. Swappable battery correctly stops showing the lightning bolt icon and green color.
When I work unplugged, the laptop never shows a low battery warning or in any way reacts to the battery being low. It just turns off out of nowhere. Also it does not wake from suspend when the battery is low. Now I live in constant fear of losing my work and wrecking my batteries (probably already wrecked).
$> sudo tlp-stat -b

--- TLP 1.5.0 --------------------------------------------

+++ Battery Care
Plugin: thinkpad
Supported features: charge thresholds
Driver usage:
* natacpi (thinkpad_acpi) = active (charge thresholds)
* tpacpi-bat (acpi_call)  = inactive (kernel module 'acpi_call' load error)
Parameter value ranges:
* START_CHARGE_THRESH_BAT0/1:  0(off)..96(default)..99
* STOP_CHARGE_THRESH_BAT0/1:   1..100(default)

+++ ThinkPad Battery Status: BAT0 (Main / Internal)
/sys/class/power_supply/BAT0/manufacturer                   = SONY
/sys/class/power_supply/BAT0/model_name                     = 45N1111
/sys/class/power_supply/BAT0/cycle_count                    =    503
/sys/class/power_supply/BAT0/energy_full_design             =  23200 [mWh]
/sys/class/power_supply/BAT0/energy_full                    =  12510 [mWh]
/sys/class/power_supply/BAT0/energy_now                     =   3810 [mWh]
/sys/class/power_supply/BAT0/power_now                      =      0 [mW]
/sys/class/power_supply/BAT0/status                         = Not charging

/sys/class/power_supply/BAT0/charge_control_start_threshold =      0 [%]
/sys/class/power_supply/BAT0/charge_control_end_threshold   =    100 [%]

Charge                                                      =   30.5 [%]
Capacity                                                    =   53.9 [%]

+++ ThinkPad Battery Status: BAT1 (Ultrabay / Slice / Replaceable)
/sys/class/power_supply/BAT1/manufacturer                   = LGC
/sys/class/power_supply/BAT1/model_name                     = 45N1127
/sys/class/power_supply/BAT1/cycle_count                    =    370
/sys/class/power_supply/BAT1/energy_full_design             =  23480 [mWh]
/sys/class/power_supply/BAT1/energy_full                    =  19480 [mWh]
/sys/class/power_supply/BAT1/energy_now                     =  19360 [mWh]
/sys/class/power_supply/BAT1/power_now                      =      0 [mW]
/sys/class/power_supply/BAT1/status                         = Not charging

/sys/class/power_supply/BAT1/charge_control_start_threshold =      0 [%]
/sys/class/power_supply/BAT1/charge_control_end_threshold   =    100 [%]

Charge                                                      =   99.4 [%]
Capacity                                                    =   83.0 [%]

+++ Charge total                                            =   72.4 [%]

UPDATE: sudo tlp fullcharge BAT0 does not start charging.
UPDATE: Tried 20.04 live from USB. Internal battery behavior is identical.
UPDATE: Tried pressing the emergency reset button at the bottom of the laptop, it changed nothing. The builtin battery is shown as connected to adapter but not charging all the time. When the laptop was unplugged yesterday, I actually saw the battery level go down a few percent. When it is connected, the level does not seem to go back up. When external battery and adapter is removed, the laptop does not start (if running, dies immediately).
Comment: Charging is controlled by the embedded controller (EC). The X270 has an emergency reset hole on the bottom. Pressing the button (turn off ThinkPad before) also resets the EC which might solve your problem. https://support.lenovo.com/us/en/solutions/pd104655-bottom-view-thinkpad-x270
Comment: @linrunner Thanks for the tip. Sadly it changed nothing.
Answer: So this is quite obviously a hardware problem. It is probably just a strange coincidence that it came up at the same time when I installed the newer Ubuntu version.


How to set specific Date to the DateTimePicker in Pascal(Lazarus) ? I need set a 01.01.1991 for example? Can't find info about it

Question: Certain date into DateTimePicker (Pascal)
How to add a certain and specific date into DateTimePicker in the Pascal/Lazarus ?
Comment: Lazarus *or* Delphi?
Comment: @AndreasRejbrand: TItle says Lazarus.
Answer: Delphi's TDateTimePicker and FPC's TDateTimePicker both have Date and DateTime properties, which you can set to a specific date, eg:
DateTimePicker1.Date := EncodeDate(1991, 1, 1);

Comment: Exactly the same code works also in FPC.


Does Pokemon Go take into account STAB in gym battles?

Question: In the main series games, there is a concept of STAB (same type attack bonus), where a pokemon of a certain type will get an additional attack bonus (+50%) when using a move that has the same type. This bonus is in addition to any modifiers caused by the target pokemon's resistances.
For example, a Fire type pokemon using a Fire type move would do additional damage, compared to a non-Fire type pokemon using a Fire attack, or a Fire type using a non-Fire type attack.
Comment: You're welcome :) There's also a [related question](http://gaming.stackexchange.com/questions/273484/which-generation-does-pokemon-go-base-its-move-type-effectiveness-on).
Comment: Sure, I've not flagged it as a dupe. I meant that you may find the info you're looking for if someone answers that question.
Comment: I saw that, but it was a tertiary question, and didn't seem to be answered definitively, so I thought it deserved its own specific question.
Answer: Yes, it does. But only at 1.25x. Here is the decoded protobuf file. In it is this:
<code>Items {
  TemplateId: "BATTLE_SETTINGS"
  BattleSettings {
    RetargetSeconds: 0.5
    EnemyAttackInterval: 1.5
    AttackServerInterval: 5
    RoundDurationSeconds: 99
    BonusTimePerAllySeconds: 10
    MaximumAttackersPerBattle: 20
    SameTypeAttackBonusMultiplier: 1.25
    MaximumEnergy: 100
    EnergyDeltaPerHealthLost: 0.5
    DodgeDurationMs: 500
    MinimumPlayerLevel: 5
    SwapDurationMs: 1000
  }
}
</code>
Comment: @Lope This is not a config file. I'm a bit out of my depth here so maybe someone else can step in. But my understanding is that messages are passed between server and client in protobuf format. By itself, this data isn't very meaningful. But someone has obtained the schema (the structure) of the messages (possibly by decompiling the apk). By applying the schema to the protobuf encoded message, we have the above decoded structures. In this particular structure, the server is telling the client to use a 1.25 as the `SameTypeAttackBonusMultiplier`.
Comment: I see, if it's indeed protobuf, than it is quite likely it's actually used, but still not 100% sure :) you can send data that you don't use, it might be there for some future use or fragment of old code, but that's not very likely since they would want to optimize the hell out of their traffic as they have so much troubles keeping servers up and running. Thanks for clarification
Comment: Considering the sheer quantity of players, it is extremely unlikely NIantic are not optimizing the data transfer here and are still sending unused data.  They already cut out the pokemon maps for captured pokemon because their servers couldn't handle the load.  This is pretty close to confirming that STAB exists.
Comment: The fact that the value is in the config file does not mean it is being used when calculating total damage. This need to be confirmed by some other means (decompile or playtesting and writing down exact damage dealt)
Answer: Since there has been posted proof now, the STAB modifier is indeed in the game, just not as high as it used to be in the other games.
The exact calculations are

super effective: x1.25
not very effective: x0.75
STAB: x1.25
Comment: Just note that STAB hitting a Not Very Effective = x1, so having STAB basically offsets a bad matchup, unless the other opponent is STAB with super effective.. then you'll be hurting still :)
Comment: I might be wrong, but I think that if those modifiers applied as you said, the result of 1 x 1.25 x 0.75 might be <1 (0.9275). So it wouldn't really offset it completely.
Comment: I don't believe the formula is that simple. I think it's somewhat like (Atk*1.25 + Atk*0.75) / 2, which would be Atk * 1.


Determinant of matrix product

Question: The determinant of matrix product follows the following property unlike it's sum.
$$
    \det (AB) = \det A\det B
$$
Why is this true? What's the easiest proof?
Comment: Once you've studied elementary row operations, the easiest way is probably based on the effect of multiplying by corresponding elementary matrices on the determinant (of a square matrix).
Comment: 'unlike it's sum'?
Answer: One definition of the determinant of an $n\times n$ matrix $M$ is that it is the only $n$-linear alternating form on $M_n(K)$ which takes the value $1$ on $I_n$.
Now the map  $\;\begin{aligned}[t]
M_n(K)&\longrightarrow K\\
M&\longmapsto\det(AM)\end{aligned}$ is an $n$-linear alternating form w.r.t. the columns of $M$. Thus it is equal to $\lambda \det M$ for some $\lambda$.  If you take $M=I_n$, you get
$$\det(AI_n)=\lambda \det I_n=\det A, \quad\text{so}\quad\det(AM)=\det A\cdot\det M.$$

Determinant of matrix product


SourceTree how to reset on a already pushed commit

Question: How can I reset a project to a commit which is already pushend onto the remote Server?
If I do a usual reset, source tree wont push it onto the server because the server has a "newer" version?
How can I solve this problem?
Is it even possible to overrite a branch?
Answer: If (and ONLY if) you are the only person who uses this repository, you can do a "force push" by opening the git command prompt by clicking on the Terminal icon, and then typing git push -f.
However, if other people use the repository, you really, really don't want to do that, as they may have already pulled the commits you are trying to "undo" with your reset, and doing a force push will just screw up the history. In this case, the best way to undo those commits (or at least undo the effects of those commits) is to simply git revert them.


find z such that $\vec{u}$ and $\vec{v}$ are linearly independent

Question: The problem is given as, "Determine the values of z such that the vectors $\vec{u} = \pmatrix{-1\\z}$ and $\vec{u} = \pmatrix{z\\-1 + z}$ are linearly independent.
Here is my work...
$\pmatrix{-1 & z& \\ z& (-1 + z)& }$
$\pmatrix{-1 & z& \\ 0& (z^2+z-1)& }$
therefore, $z^2+z-1 \neq 0$
$z \neq \frac{1}{2}(-1-\sqrt{5})$
$z \neq \frac{1}{2}(\sqrt{5} + 1)$
Does that seem right?
Comment: Looks good to me.
Comment: @mbaitoff, he multiplied first row to $z$ and added it to 2nd row.
Comment: It is good except you mess up the quadratic formula slightly. The answer is $z\neq \frac{1}{2}(-1\pm\sqrt{5})$. Note the $1$ does not change signs.
Comment: I don't get how you get to your second parenthesis from the first. Linear independency means non-zero determinant, and you got it right.
Answer: $$
z^2 + z - 1 \ne 0 \Rightarrow \\
z^2 + z +\frac{1}{4} \ne \frac{5}{4} \Rightarrow \\
\left(z+\frac{1}{2}\right)^2 \ne \frac{5}{4} \Rightarrow\\
z \ne -\frac{1}{2} + \frac{\sqrt{5}}{2}, z \ne -\frac{1}{2} - \frac{\sqrt{5}}{2}
$$


Can electrical wires break?

Question: For starters I know nothing about electrical stuff, please keep that in mind.
We had a very strange occurrence where (no breaker was tripped) one of our electrical lines behind one of the breakers no longer receives electricity. This happened at the very same time as our stove top stopped working, which is on its own line.
I took the stove top apart and took a look, measured electrical flow. Our house doesn't seem to have a Phase 3, because that cable is just cut, so it uses L1 and L2 in its cable, however when I measure the presence at the end of the cable (which is connected straight to the stove top), only one of the veins actually carries a current (It was either L1 or L2)
Now I'm thinking that somehow the cable broke. Aren't they both supposed to carry a current? The connection on the stove top surely assumes that they should.
Comment: *"For starters I know nothing about electrical stuff, please keep that in mind"* Honestly you need to call an electrician. Sticking your hands into 120/220V devices looking for "current" may get you seriously injured or killed.
Comment: Is the stove top the only device not working? Check your heaters, ac unit, water heater, clothes dryer, etc.
Comment: Where are you on this planet?
Comment: As 3 phase asked where are you since you are talking 3 phase , what brand of panel do you have? There are some out there that may have this issue Zinsco being one brand and federal pacific, stablock.  Both known for problems in North America.
Comment: @ThreePhaseEel In Sweden - getting an electrician here is hard and takes times, which is why I'm seeing if there's something I can do myelf.
Comment: @RonBeyer - I'm being careful, we're doing home renovations. We've done everything ourselves. Plumbing, floors, walls, insulation. The only thing we had a professional for so far is electricity. It just takes so long to get someone here.
Comment: @EdBeal the fuse box brand is Hager
Answer: So what actually happened was that one of the main fuses tripped in the main electricity line. When I got a hold of an electrician via phone, their recommendation was to check those, along with a description of what they actually were and looked like.
Also an important thing I wanted to share that I hadn't seen here that those main breakers can often be replaced with different/wrong fuses, which can be a fire hazard. So I made sure to replace them with the same specs.
Answer: Yes, electrical wires can break, or connections can break or come loose, or transformers can fail, there are many ways part of your circuit could be dead. But if it were to happen inside or ahead of your panel, ALL circuits connected to that line would be dead, not just the stove. The stove may be your most obvious one, but anything that takes 240V, like your water heater, A/C unit, Heat Pump, and any 120V circuits connected to that bus in the panel will be dead too.
But if it is only a break or disconnection of a wire in your stove, that would not affect anything else.
Comment: Actually a bad connection to the buss at the breaker is not unheard of and 2 old brand that it was common. I have even seen this with current name brands like square D and Siemens and cutler hammer.
Comment: @JRaef our heat hump is also malfunctioning with an error. I thought that's on a different breaker since the stovetop is supposed to be on its own. Do you know what could've happened?
Comment: @EdBeal The house is old, I'm assuming so it the fuse box, and the electricity lines. The last time we had an electrician over he upgraded the one for the stove, because the old one wasn't strong enough to take all the electricity.

I'm really trying to troubleshoot what's wrong, because if it's possible that one of the veins is dead my first step would be to get a new cable, connected that to the stovetop, see if the  problem was the cable to the stovetop.

If that fails I'm thinking it could be in one of the cables between box and outlet. Does that sound reasonable as an approach?
Comment: Sir Rogers you should invest in a volt meter even an inexpensive one can help troubleshoot problems like this. Other than Hager fuse blocks I have limited experience with that brand. Prior to replacing the wiring verify at the source or you may end up throwing $ and time at the problem with no change.
Comment: @EdBeal So I managed to reach an electrician via phone. Turns out one of the main fuses tripped, but since I'd never seen a fuse like that I didn't know it was one. A quick stop to the general store, and a replacement later everything is fine :-) Thanks for the help!
Comment: Those are nice as when you pull out the top the fuses can be safely removed. I am lucky mine have indicators that light up when the fuse blows.
You mentioned your heat pump having errors if you blow another fuse, have your capacitor checked on the heat pump. When caps fail or start to fail they don't do there hop and the motor draws more amperage trying to start. This begins with only one every now an then in some cases but gets worse until the cap must be replaced. This is hard on the electrical system and something to keep an eye on. Diy or have it serviced and ask them to change it.

Can electrical wires break?


What should be done if a SPAM post appears under Close Votes Review?

Question: I found a SPAM post under Close Votes review saying 'This question has been flagged as: unclear what you're asking'.
When I was going to close the post as SPAM, I didn't find an option for that.
Do I need to skip the review? or voting to close the post as 'unclear what you're asking' is fine?
I know this is a rare case. But what should be done if it happens again?
Here is the screenshot for that
Answer: When you review a post, you have a link link that takes you to the post; there you can flag the post as spam.

I would not vote to vote to close the question, since it is going to be deleted. As you are going to flag it as spam, other users will see it the review queue.
Comment: In addition, the flag as "unclear" is invalid, and a mod should really dismiss is a such.  Only use the spam flag for spam, and only flag spam with the spam flag.


How to call simple expressions in a paper which do not need any proof?

Question: I am using an expression in a paper which doesnt need a proof at all such as
$$\sum_{i=k}^K\binom{K}{i}p^i(1-p)^{K-i}$$
is a decreasing function of $k$ and
$$\sum_{i=0}^{k-1}\binom{K}{i}p^{K-i}(1-p)^i$$
is an increasing function of $k$. However I connot write it in the text. Because I refer to this property in a non trivial proposition.
Question: How should I put this thing in a format? should I call it as a statement or definition or corollary?
Thank you very much.
Comment: You may not need to make a clearly separated statement, unless it is something that you use a lot.  Simply saying, for example, "As $\sum \cdots$ is decreasing wrt $K$..." at the appropriate point(s) will probably suffice.  It you do refer to it quite often, either _Fact_ or _Observation_ would work.
Comment: It certainly is not a definition.
Comment: @Joel Reyes Noche and Arthur Fischer thank you very much for your comments.
Answer: I suggest you use the term Remark.


$\left \lfloor \log_bx \right \rfloor = \left \lfloor \log_b\left \lfloor x \right \rfloor \right \rfloor$

Question: What conditions on real number  $ \;\; b > 1\;\;$ is necessary and sufficient to guarantee that $\left \lfloor \log_bx \right \rfloor = \left \lfloor \log_b\left \lfloor x \right \rfloor \right \rfloor$ for any real number $x \geq 1$.
If we assume $\;\; b = m+f\;\;$ where $m$ is an integer and fraction $f$ $< 1$.
Setting $x = b$,
$LHS = 1$
$RHS = \left \lfloor \log_{m+f}m \right \rfloor = 0$
$\Rightarrow b $ must be an integer $\geq 2$
How to prove further that for any integer $\;\;b \geq 2 \;\; $ and for any real $x$ above identity holds?
Thanks !
Answer: Suppose that
$$\lfloor \log_b x\rfloor>\lfloor\log_b\lfloor x\rfloor\rfloor$$
Then there is some integer $n$ such that
$$\lfloor x\rfloor <b^n\le x$$
This can not happen, for example, if $b$, or $x$, is a positive integer. But making $b=2.5$, $x=6.3$ we have
$$\lfloor\log_bx\rfloor=2$$
$$\lfloor\log_b\lfloor x\rfloor\rfloor=1$$
Comment: I'm not native speaker so I don't know if "is" in "is a positive integer" should be "are". Please feel free to fix it.
Comment: and there is no possibility of LHS < RHS , so this completes the proof? Am I right?
Comment: Oh, yes, of course.


Confusion: nil in Ruby

Question: I am working on iOS app and usually use Objective C and little ruby. So suppose I have the below code in Objective C:
if ([!propertyA isEqual:propertyB])
{
// Execute logic in here.
}

If my propertyA is nil, my condition for if would be nil and logic inside the it would not be executed.
However I am trying to check similar thing in ruby and this time the logic inside if gets executed when while my first parameter is nil.
Ruby Code:
if params[:some_param] != params[:other_param]
# Execute this logic
end

In my parameters list, I don't have 'some_param' and hence when the above if code is executed it's more like:
if nil != params[:other_name]

This condition comes out to be true and logic inside if is executed. However if I add a check for params[:some_param] before comparing the two, then logic inside if is not executed which is what I want.
So will I always have to check if the param is present or not? Shouldn't nil != params[:other_name] result into nil and avoid the execution inside if?
I am just trying to avoid the extra param check here.
Comment: I think you can't avoid double check in Ruby.
Comment: I'm assuming that Objective-C example is meant to be `if (![propertyA isEqual:propertyB])`. If so, the code inside the brackets *will* execute if `propertyA` is nil, because `[nil isEqual:propertyB]` gives 0, and `!0` is 1. (The code as written here is not actually valid with `propertyA` as nil, because negating NULL doesn't yield a valid pointer.)
Answer: You  are using a boolean so it won't evaluate to nil
You could do this
if params.fetch(:some_param, params[:other_param]) != params[:other_param]

fetch returns a default if :some_param is nil, this way you'd get equality and the logic would be skipped, not sure it's expressive in this case.
that way you'd be comparing apples to apples
Generally, it's good to use fetch with sensible defaults instead of nil checking

Confusion: nil in Ruby


Does the proposed bathroom circuit solution meet code?

Question: I intend to replace an old bathroom fan with a Panasonic WhisperGreen Select model that includes a fan, a light, and a nightlight.  I have several questions.
The setup:

The existing fan is on a 20amp circuit, but the lines between the switches and the fan (light and fan are separate switches) are 14 gauge, not 12.  There is nothing else on this circuit.
The bathroom has mirror vanity lights on a different 15amp circuit.  It also has a GFCI outlet on this circuit.  This circuit also powers a few overhead lights in another room (not in the bathroom).

The simplest thing for me would be to move the outlet to the 20amp, and everything else (mirror lights, fan, and fan lights) to the 15amp.  Would this be allowed?
Some related questions:

By code, am I even allowed to power the fan from either of the two circuits?  i.e. could it share with the outlet circuit (my understanding is outlets in baths can't share) or could it be placed on the lighting circuit (again, I believe the answer is no...but this I'm not sure about.  The fan draws only 0.27A)?
Am I allowed to power the WhisperGreen's lights with the shared 15amp lighting circuit?
If the fan remains on the 20amp circuit, I assume I am required to upgrade the 14/3 between switch and unit with 12/3?
Can this situation be wired with just the existing circuits, or is a third going to be required to do it fully by the book?

I suspect that a simple fan replacement would be grandfathered and wouldn't require updating to code, but my preference would be to make it right while it has my attention.
What would you suggest doing if you were in my shoes?  One thing I would particularly like to do is get the 14ga wire out of the 20amp circuit...powering the fan and lights with the 15amp lighting circuit would accomplish this.
Comment: Because you've seen 14ga wire on the circuit, you really need to change out the breaker to a 15A.  Unless you can inspect all the wire back to the panel you kind of have to assume there's more 14ga.
Comment: What country are you in?
Comment: 14 gauge can't be on 20 amp breaker, that's a no-no.  Doubt very much if the fan and light even comes close to needing a 20 amp breaker, so a 15 amp breaker should work, if code allows.  Do think the outlets must be 20amp circuit with 12 gauge wire and GFCI protected.
Comment: @JPhi1618 - I am 95% sure that the romex goes from breaker directly to the existing fan, with no junctions in between.  Good point though - if I cannot confirm this, I need to change to 15A breaker
Comment: @Harper-ReinstateMonica  - I am in USA
Answer: It seems like your plan will work to bring up to current code. Some details in communication can be missed, so here are the most relevant current (2020) NEC code sections that I think are relevant. When reading these sections keep in mind that in NEC terminology an "outlet" is any equipment connection point including hard wired connections, and a "receptacle" is a specific type of outlet.

210.11(C)(3) Bathroom Branch Circuits. In addition to the number of branch circuits required by other parts of this section, one or more
120-volt, 20-ampere branch circuit shall be provided to supply
bathroom(s) receptacle outlet(s) required by 210.52(D) and any
countertop and similar work surface receptacle outlets. Such circuits
shall have no other outlets.
Exception: Where the 20-ampere circuit supplies a single bathroom,
outlets for other equipment within the same bathroom shall be
permitted to be supplied in accordance with 210.23(A)(1) and (A)(2).
210.52(D) In dwelling units, at least one receptacle outlet shall be installed in bathrooms within 36 in. of the outside edge of each
basin. The receptacle outlet shall be located on a wall or partition
that is adjacent to the basin or basin countertop. These receptacles
shall have GFCI protection as required by section 210.8(A)(1).

The words "work surface" in 210.11 is a recent addition, it used to apply/allow all bathroom receptacles. There is no section that says fans or lights in a bathroom require 20A circuits.
210.23(A)(1) says cord and plug connected equipment not fastened in can't use more than 80% of the branch circuit rating and (2) says fastened in place equipment other than lights cant use more than  50% of a circuit when circuit is shared with receptacles.
Comment: Yes, if supplying one bathroom the exception allows fans, and it is commonly done that way.
Comment: Thank you very much - I have accepted this as the answer.  I am glad to learn that I was incorrect in my thinking that bathroom lighting circuits could not be shared elsewhere.  I think I was confusing them with the rule for bathroom outlet receptacles.
Comment: It is normal for bathroom lights to share with other lights.
Comment: So, bathroom lighting circuit does not need to be confined solely to bathroom (it can also provide power to lights in other rooms?)?
Comment: I am sorry to be dense about this - does the Exception to 210.11(C)(3) mean that the 20A circuit that supplies receptacle outlets could ALSO supply my fan (which is an "outlet" if I am understanding correctly?)?  (this 20A circuit supplies only this bathroom).  I don't think I will go this route if I can run fan from 15A circuit instead, but I'd like to know for sure.  Who knows what I'll find when I get started...  :)


error via using .map to create grouping age (dataframe)

Question: I just have data that have different age and I want to group them in new column in order to plot a graph
I try df2["Aging Group"] = df2["Aging Group"].map({"20-39":0,"40-59":1,"60-79":2,"80+":3})
but the error orrured, any know what wrong? , thx
Answer: Loks like you are looking for Pandas Apply
 dictionary = {"20-39":0,"40-59":1,"60-79":2,"80+":3}
 df2["Aging Group"] = df2["Aging Group"].apply(lambda x: dictionary.get(x))


Using DB2 Spatial Types in .Net

Question: Is there any support for DB2 spatial types as parameters in .Net? I can't see any mention of any geo-spatial types in the documentation and no mention of it anywhere else. I could probably roll my own if someone knows the parameter format that would be used to pass the values in.
Answer: For anyone finding this, there is next to no information. You can query for geospatial types and the provider returns them as Well Known Text strings, which isn't terrible, but the SRID is missing. Some creative use of ST_SRID and ST_GeomToText should help but it's kinda wild west to get this working.

Using DB2 Spatial Types in .Net


How to keep a mushroom placed even when it is exposed to high light level?

Question: In Minecraft, there is a problem with creating a map containing Mushrooms. When placing the Mushrooms, they don't stay on the ground as a block, instead they turn back into items because of high light level. The problem is that I don't wish to have a lower light level - this makes the map looking badly.
Does someone know how to preserve the Mushrooms as a block in a highly lit place?
Answer: If you place the mushroom on Mycelium, the light rules do not apply. From the docs:

Mushrooms can remain on mycelium blocks in any light level, unlike the situation on other blocks, where mushrooms are broken (dropping as items) during block updates in high light.

If you are making a downloadable map, and you don't like the look of Mycelium, you could create a resource pack with that texture replaced with one you want, and recommend it to be downloaded and used with the map.
Answer: You can make the map low light and effect everyone with night vision.
You can also try surrounding the mushroom with barriers so no light can get in it.
Comment: Rookie, barriers are transparent to light
Comment: I also thought about the night vision solution, but that would mean that there will be no sunlight. I need the sunlight for daylight sensors, because otherwise the redstone circuit will not work.
Comment: My bad. Sorry about the barriers
Comment: use the setblock command. /setblock ~ ~ ~ red_mushroom    i haven't tested it tho


bind listbox to index C#

Question: I dont know if it  possible but what I want is something like that
In WinForm listbox1 has a list of lines(copied from file)
In another Thread and class I run on a List that contains the same lines each line I parse and DoSomething
once I finish with that line I want the index in the listbox to change
from my basic and limited understanding my approach was with an Event to fire in form and than maybe using Invoke (for not to cross thread )
Is there is a way to somehow bind to index of the listbox somehow with my for/foreach loop ?
class form
{
    listBoxScript.SetSelected(ScriptCounter, true);<--bind the ScriptCounter?
}

in another Class
class RunScript
{
//..

    public void RunScriptList()
    {
        ScriptCounter = 0 ;
        foreach ( var cell in ScriptList)
        {
        ScriptCounter ++;
        //DoSomething
        }
    }

}

Comment: What do you meant by bind o index of the listbox somehow with my for/foreach loop? What does loops has to do with binding? Posting some code would help.
Comment: I'll Add some code to make it more clear
Comment: Also mention which technology. Winforms or WPF? I presume it is winforms
Comment: @SriramSakthivel Done == winform
Answer: Make sure you implement INotifyPropertyChanged in RunScript class. Here's a complete sample:
class RunScript : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int scriptCounter;

    private ISynchronizeInvoke invoker;
    public RunScript(ISynchronizeInvoke invoker)
    {
        if (invoker == null) throw new ArgumentNullException("invoker");
        this.invoker = invoker;
    }

    public async void RunScriptList()
    {
        ScriptCounter = 0;
        foreach (var cell in Enumerable.Range(1, 15))
        {
            ScriptCounter++;
            await Task.Delay(1000);
            //DoSomething
        }
    }

    public int ScriptCounter
    {
        get { return scriptCounter; }
        set
        {
            scriptCounter = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            Action action = () => handler(this, new PropertyChangedEventArgs(propertyName));
            invoker.Invoke(action, null);
        }
    }
}

private RunScript rs;
public Form1()
{
    InitializeComponent();

    rs = new RunScript(this)

    var binding = new Binding("SelectedIndex", rs, "ScriptCounter", false, DataSourceUpdateMode.OnPropertyChanged);
    listBox1.DataBindings.Add(binding);
}

private void button1_Click(object sender, EventArgs e)
{
    rs.RunScriptList();
}

Note I have used async/await in RunScriptList, If you do it in another thread you need to fire PropertyChanged event in main thread to avoid cross thread exception.
Comment: Updated my code to use `Invoke`, You need to pass `ISynchronizeInvoke` to `RunScript` class, If `ISynchronizeInvoke` is new to you, don't be afraid `Form` implements that interface. Strictly speaking you can pass any `Control`. and... You're welcome :)
Comment: Thank you very Much !
If I use Invoke to fire OnPropertyChanged in Main thread (where Form is running ) It would be fine ? or I need to do it with an Event ?
Comment: Yes, Invoke inside `OnPropertyChanged` is fine, or else you can use [SynchronizationContext](http://msdn.microsoft.com/en-us/library/System.Threading.SynchronizationContext%28v=vs.110%29.aspx) `Send` or `Post` method
Comment: I'm afraid I'm in too deep for 'SynchronizationContext' ,Is it will be too much to ask you to post How would you implement the Invoke ?
I'm going to mark it as an answer in a few moments
Comment: sadly I get "Cannot bind to the property 'ScriptListBox' on the target control." when putting the code ...
Comment: I guess you don't have the property named `ScriptListBox` or both are of incompatible types. That's indeed another question, I suggest you to ask new question with all necessary information with relevant code if problem is not solved.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58351/discussion-between-lordtitikaka-and-sriram-sakthivel).

bind listbox to index C#


How can I open this locked door?

Question: The Outbreak Update added ruins, which contain interesting or unique items hidden behind locked, DNA doors. The door itself requests a DNA sample when inspected, but I have yet to find one.

In all the cases I've found, there's another way to dig into the room and bypass the door. Are the doors simply for flavour and always possible to bypass, or is there a way to open them?
Comment: What's that thing under the ruin? Don't think I've ever stumbled upon anything like that... o.0
Answer: Click on the door. Choose the 'Submit Sample' option. To speed things up, set the priority of the door to 9. A dupe should head straight there, press its hand to the door and it opens up!
Comment: First: Build a ladder to reach the left entrance. Then do the steps written by EFH.
Answer: It opens automatically just send a duplicant to open it.

How can I open this locked door?


Download Code - Linq C#

Question: I have this code working, it uploads a PDF document to SQL Server express, and shows it to DataGridView.  How can I download or view (by default pdf reader) the uploaded file?
Most codes snippets I found were for ASP.NET; this is Winforms.  Thank you.
private void btnSave_Click(object sender, EventArgs e)
{
    if (docnoTextBox.Text == "" && docfromTextBox.Text == "")
    {
        MessageBox.Show("Cannot save empty strings");
    }
    else
    {
        try
        {
            iteisDataContext das_db = new iteisDataContext();
            Document newDoc = new Document();
            newDoc.docid = docnoTextBox.Text;
            newDoc.docdate = docdateDateTimePicker.Value;
            newDoc.postdate = DateTime.Now;
            newDoc.doctype = cboDocType.Text;
            newDoc.docfrom = docfromTextBox.Text;

            //Convert string to linq.binary
            Binary pdfFile = new ASCIIEncoding().GetBytes(ofdMain.FileName);

            // And back to string - dae pa ini confirmado!
            //string fileUpload = Encoding.ASCII.GetString(pdfFile.ToArray());

            newDoc.docupload = pdfFile;
            newDoc.docsubject = docsubjectTextBox.Text;
            newDoc.notes = notesTextBox.Text;

            // Update database
            das_db.Documents.InsertOnSubmit(newDoc);
            das_db.SubmitChanges();

            MessageBox.Show("Document Saved.", "Success",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

Comment: What's LINQ got to do with this?
Answer: In WinForms you could use the Acrobat reader ActiveX control (Add Reference -> COM Components -> AcroPDF.PDF) to display the PDF file directly inside your application. This requires Adobe Reader to be installed on the client computer:
var pdf = new AxAcroPDF();
pdf.LoadFile(@"c:\test.pdf");

Another possibility is to open the PDF with the default program on the client computer using the Process.Start method:
Process.Start(@"c:\test.pdf");

In both cases you need to store the PDF in a temporary file after reading it from your database.
Comment: Beat me by a sec. +1 from me.
Comment: Hello Darin, Please post an example how to use this line of code to view or download file from sql server. "string fileUpload = Encoding.ASCII.GetString(pdfFile.ToArray());
" And this "Process p = new Process();". Thank you, I'm still learning

Download Code - Linq C#