Help constructing an OBB, trying to Represent a matrix with 3 vectors

Question: I am presently trying to construct an OBB (Oriented Bounding Box) using the source and math contained in the book "Real Time Collision Detection".
One problem with the code contained in this book is that it does very little to explain what the parameters mean for the methods.
I am trying to figure out what I need to feed my setOBB() method (I wrote this one). It goes like this:
void PhysicalObject::setOBB( Ogre::Vector3 centrePoint, Ogre::Vector3 localAxes[3], Ogre::Vector3 positiveHalfwidthExtents )
{
    // Ogre::Vector3    c;      // OBB center point
    // Ogre::Vector3    u[3];   // Local x-, y-, and z-axes (rotation matrix)
    // Ogre::Vector3    e;  // Positive halfwidth extents of OBB along each axis

    m_obb.c         = centrePoint;
    m_obb.u[0]      = localAxes[0];
    m_obb.u[1]      = localAxes[1];
    m_obb.u[2]      = localAxes[2];
    m_obb.e         = positiveHalfwidthExtents;
}

Looking at the parameters it wants above, the first and third parameters I believe I understand.

Pass in the centre position of the object.
This is my problem. I believe it wants a matrix represented using an array of 3 vectors? but how?
A Vector which contains magnitude for the distance between the centre point and the edge of the OBB in each x,y,z direction.

Here is what I'm doing currently:
// Build the OBB
Ogre::Vector3 rotation[3];
Ogre::Vector3 centrePoint       = sphere->getPosition();
rotation[0]         = ?
rotation[1]         = ?
rotation[2]         = ?
Ogre::Vector3 halfEdgeLengths   = Ogre::Vector3( 1,1,1 );

myObject->setOBB( centrepoint, rotation, halfEdgeLengths );

How can i represent a matrix using three vectors (which I cannot avoid doing this way). Thanks.
Comment: So is the question "how do I represent the matrix with 3 vectors?" or "why doesn't this code work?"...or both?
Comment: Sorry, I'm asking basically "how do I represent the matrix with 3 vectors?", however any additional help is appreciated.
Answer: A 3x3 matrix representing a rotation/scale in 3d space is nothing more than three vectors in row.
Each column vector is the rotated and scaled main axis. First column is the scaled and rotated x axis, second and third are y and z.
(Ogre uses column major matrices)
So, localAxes[3] simply is a rotation. And you can get it from a Quaternion.
Ogre::Vector3 rotation[3];
Ogre::Quaternion orientation = sphere->getOrientation();
orientation.ToAxes(rotation);
// Now rotation has the three axes representing the orientation of the sphere.

Comment: Well strictly speaking what you mean is that with no scaling, the 3x3 matrix rows/columns - columns in this case gives 3 orthonormal vectors such that x,y,z are orthogonal and are unit vectors ( this wouldn't work if you had a scale ). This gives you your local space and from that it's easy to construct your OBB
Answer: Ok. So another question is that this functionality requires it to be a matrix, right? I'm assuming so, or you'd just use the individual axes vectors in the places they are needed during the calculation.
That said, if you stuff these vectors into a matrix in a uniform way, then you'll either have them as the rows of the matrix or the columns of the matrix and, more or less, have a 50% chance to get it right depending on how the functions accepting the matrix expect the matrix to be formatted. So, set up the 2d array as the matrix and go forward with caution, I'd suggest. For example:
int matrix[3][3] = {     { x1, x2, x3 },
                         { y1, y2, y3 },
                         { z1, z2, z3 }
                   };

Flip if you need to go column-major.
Comment: I guess a proper disclaimer here is that I'm just showing a way to stuff some vectors into a matrix. Not making guarantees about the specific domain.
Comment: Oh i see what you mean. This does help me, I guess I will have to try either by rows or columns depending on the way it's representing them internally.
Comment: @Brock Yeah, exactly. Just make sure you are consistent with your orientation throughout and you should be fine. Good luck!
Comment: What I am still confused about however is, what does each "vector" represent for the column or row? I supposedly represents "orientation" in the OBB, but I don't fully understand how a row in a matrix can represent "orientation"?
Comment: Simply put the first column vector is the new X-Axis. when [1 0 0] is the unrotated X-Axis, and the first column is [0 1 0], then you have a rotation of 90° around Z-Axis, because this will make the X-Axis stand like the Y-Axis. (Try it with your fingers to see why ;) )


how to get button click popup values using jsoup in java

Question: I'm having trouble trying to parse the popup page values after button click of an element. Here is the case I am dealing with:
<button class="content id-view-permissions-details fake-link" data-docid="com.facebook.katana">

I am parsing the values from the endpoint: https://play.google.com/store/apps/details?id=com.facebook.katana
How to get the "Permissions" from the above button tag??
Comment: you can definitely find something useful here https://stackoverflow.com/questions/31428143/web-scraping-of-modal-windowdialogue-box-using-jsoup
Comment: the content there appears only after you click a button (ajax or something) and jsoup is basically a parser of html that you have or can GET
Answer: given that button as an Element named btn, you can go with
btn.previousElementSibling().text()


Get the size of the result of aggregate method MongoDB

Question: I have this aggregate query :
cr = db.last_response.aggregate([

{"$unwind": '$blocks'},
{"$match": {"sender_id": "1234", "page_id": "563921", "blocks.tag": "pay1"}},
{"$project": {"block": "$blocks.block"}}
])

Now i want to get the number of element it returned (is it empty cursor or not).
This is how i did :
I defined an empty array :
x = []

I iterated through the cursor and append the array x:
for i in cr :
   x.append(i['block'])
print("length of the result of aggregation cursor :",len(x))

My question is : Is there any faster way to get the number of the result of aggregate query like the count() method of the find() query ?
Thanks
Answer: The faster way is that reject operations of transfers all data from mongod to you application. To do this you may add final group stage to count docs
{"$group": {"_id": None, "count": {"$sum": 1}}},

This is mean that mongod do aggregate and get as result count of docs.
Thereis no way to get count of result without execution of aggregation pipeline.
Comment: Now you can use the [$count](https://docs.mongodb.com/manual/reference/operator/aggregation/count/#:~:text=The%20%24match%20stage%20excludes%20documents,to%20a%20field%20called%20passing_scores%20.) aggregate function.
Alternatively, perhaps the [countDocuments](https://docs.mongodb.com/manual/reference/method/db.collection.countDocuments/#mongodb-method-db.collection.countDocuments) method could help.


How to craft Champion mastery 6-7?

Question: I have a level 5 champion mastery with Morgana, and recently received my second S rank champ token with her.  Upon going to the crafting menu, I select "Upgrade with 2 champ tokens and 1 champ permanent."  When I select that, however, it shows I have the tokens, but NOT the permanent.  I clearly own Morgana, but is that not a permanent? Is this a bug or am I missing something?
Answer: A permanent is not the ownership of the champion but what you get if you have a shard of that character and already own that character.
Source: http://boards.eune.leagueoflegends.com/en/c/champions-gameplay-en/EPcciL4P-what-is-the-difference-between-champion-shard-and-champion-permanent
Comment: Ahh thanks!  That's super confusing though.
Answer: This is not a bug, it's just misunderstanding. When they says "champion permanent" they are talking about the champion shard.
So, here are the 3 choices you have :

Morgana Champion Shard
Morgana Skin Shard
500 Blue essence

I recommend you to use the Champion essence as it is quite easy to optain. You can get some by disenchanting any Champion Shard or by buying a Mystery Champion Shard at 1700 IP. From that chest you get a random Champion Shard and some Blue essence. You don't need a key to open Champion Chest.
You can find more detail about Hextech crafting here.

How to craft Champion mastery 6-7?


Is there an Indy server property equivalent to TCustomWinSocket.Data?

Question: When I work with TServerSocket I can use the property Data to store a pointer to a class for example for each client.
Now I will use Indy TIdCmdTCPServer and I'd like to know if there is an equivalent property.
Answer: Yes, there is - the TIdContext.Data property.  In TIdCmdTCPServer events that give you a TIdCommand parameter instead of a TIdContext parameter, you can access the TIdContext object from the TIdCommand.Context property. For example:
type
  TMyClass = class
    // add whatever you need...
  end;

procedure TForm1.IdCmdTCPServer1Connect(AContext: TIdContext);
var
  MyCls: TMyClass;
begin
  MyCls := TMyClass.Create;
  // initialize MyCls as needed...
  AContext.Data := MyCls;
end;

procedure TForm1.IdCmdTCPServer1Disconnect(AContext: TIdContext);
begin
  AContext.Data.Free;
  AContext.Data := nil;
end;

procedure TForm1.IdCmdTCPServer1CommandHandlerCommand(ACommand: TIdCommand);
var
  MyCls: TMyClass;
begin
  MyCls := TMyClass(ACommand.Context.Data);
  // use MyCls as needed...
end;

Indy also has another useful feature.  You can derive a custom class from TIdServerContext, add whatever you want to it, and then assign it to the server's ContextClass property before activating the server.  That way, you can simply typecast any TIdContext pointer to your class type when you need to access your custom members.  For example:
type
  TMyContext = class(TIdServerContext)
  public
    // add whatever you need...
    constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil); override;
    destructor Destroy; override;
  end;

constructor TMyContext.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil);
begin
  inherited;
  //...
end;

destructor TMyContext.Destroy;
begin
  //...
  inherited;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  IdCmdTCPServer1.ContextsClass := TMyContext;
end;

procedure TForm1.IdCmdTCPServer1Connect(AContext: TIdContext);
var
  MyCtx: TMyContext;
begin
  MyCtx := TMyClass(AContext);
  // initialize MyCtx as needed...
end;

procedure TForm1.IdCmdTCPServer1CommandHandlerCommand(ACommand: TIdCommand);
var
  MyCtx: TMyContext;
begin
  MyCtx := TMyClass(ACommand.Context);
  // use MyCtx as needed...
end;

This way, you don't need to waste time and memory allocating a separate class per client, when you can use the one that the server already creates for you.
Comment: I have added some examples.
Comment: You really shouldn't be accessing connections outside of the server's events. But if you must: `List := IdCmdTCPServer1.Contexts.LockList; try MyCls := TMyClass(TIdContext(List[index]).Data); {use MyCls as needed} finally IdCmdTCPServer1.Contexts.UnlockList end;`
Comment: What I described is how to do it with Indy. Your App command handler will have to lock the `Contexts` list, loop through the list looking for the appropriate client, send data to it, and then unlock the list.
Comment: You said: "You don't need to waste time and memory allocating a separate class per client". It's a new paradigm for me and I didn't understand. I don't want to take advantage of your willingness though I'm kind of doing it right now but... do you have an example?
Comment: Remy, based on the first example, how can I access my class outside an event generated by TIdCmdTCPServer? For example, in TSocketServer I use `SocketServer1.Socket.Connections[number_of_connection].data`. What is the equivalent in TIdCmdTCPServer?
Comment: I'm connecting an Android App with a GPRS product through my server. Both App and GPRS are clients. When a client connects, I associate it a class with informations like Index, status, etc. Both connect to the same server. When the app sends a message to the GPRS (using index), my server has to find the client with the appropriated index and send the message off the Android App to it. I used to do in this way with TSocketServer and it works. Do you know a better way?


Deriving $\|Du\|_{L^\infty(U)}\le C(\|Du\|_{L^\infty(\partial U)}+\|u\|_{L^\infty(\partial U)})$ with $u$ being the smooth solution to an elliptic PDE

Question:

Let $u$ be a smooth solution of the uniformly elliptic equation $Lu=-\sum_{i,j=1}^n a^{ij}(x)u_{x_i x_j}$ in $U$. Assume that the coefficients have bounded derivatives.
Set $v:=|Du|^2+\lambda u^2$ and show that $$Lv \le 0 \quad \text{in }U$$ if $\lambda$ is large enough. Deduce $$\|Du\|_{L^\infty(U)}\le C(\|Du\|_{L^\infty(\partial U)}+\|u\|_{L^\infty(\partial U)}).$$

This is PDE Evans, 2nd edition: Chapter 6, Exercise 8.
I believe I was able to show $Lv \le 0$ for large enough $\lambda$ already. Specifically, given $v$, we obtain $$v_{x_i x_j} = 2[(Du_{x_j}\cdot Du_{x_i}+Du \cdot Du_{x_i x_j})+(\lambda u_{x_j}u_{x_i}+\lambda uu_{x_i x_j})],$$ which means, for large enough $\lambda$, $$Lv=-2\sum_{i,j=1}^n a^{ij}(x) Du_{x_j}\cdot Du_{x_i}-2\lambda\sum_{i,j=1}^n a^{ij}(x)  u_{x_j} u_{x_i} \le 0.$$
But how can I get started on deriving the estimate $$\|Du\|_{L^\infty(U)}\le C(\|Du\|_{L^\infty(\partial U)}+\|u\|_{L^\infty(\partial U)})$$
Any hints on this part would be helpful.
Comment: The calculation in the line for getting $Lv\leq 0$ is wrong.
Comment: Well, [this post](https://math.stackexchange.com/questions/1051618/two-exercises-on-evans-pde-book) answers my question.
Comment: Apply the maximum principle to $v$ and translate that information into a bound for $u$.
Comment: @Jack and Cookie. The expression of $v_{x_ix_j}$ has four terms. The first and the third terms yield the terms in the line of $Lv$ (which is wrong according to Jack). The last term yields zero because $Lu=0$. Could you explain how the second term is estimated (and what is wrong in the said line)?
Answer: I believe this can indeed be handled by the maximum principle.  Since $Lu,Lv\leq0$, it tells us that
$$\max_{\partial U}u=\max_{\overline{U}}u\quad\text{and}\quad\max_{\partial U}v=\max_{\overline{U}}v.$$
It helps considerably to rewrite this in terms of the infinity norm and the definition of $v$, which reads
$$\left\|u^2\right\|_{L^\infty(\partial U)}=\left\|u^2\right\|_{L^\infty(U)}\quad\text{and}\quad\left\||Du|^2+\lambda u^2\right\|_{L^\infty(\partial U)}=\left\||Du|^2+\lambda u^2\right\|_{L^\infty(U)}.$$
Applying the triangle inequality to both sides of the right equation gives
$$\left\||Du|^2\right\|_{L^\infty(\partial U)}+\left\|\lambda u^2\right\|_{L^\infty(\partial U)}\geq\left\||Du|^2\right\|_{L^\infty(U)}-\left\|\lambda u^2\right\|_{L^\infty(U)}$$
So we can then add $\lambda$ times the left equation to this, which gives
$$\left\||Du|^2\right\|_{L^\infty(\partial U)}+2\left\|\lambda u^2\right\|_{L^\infty(\partial U)}\geq\left\||Du|^2\right\|_{L^\infty(U)}$$
We can then add the appropriate terms to the left side (which are all positive, of course) to allow us to complete the square.  Taking square roots then gives exactly the desired estimate.
Comment: When I apply the triangle inequality on the left side and the reverse triangle inequality on the right side of your second equation, then I get $$\|Du\|^2_{L^\infty(\partial U)} + |\lambda| \|u\|^2_{L^\infty(\partial U)}\ge \|Du\|^2_{L^\infty(U)} - |\lambda| \|u\|^2_{L^\infty(U)},$$ and after employing the first equality, I obtain actually $$\|Du\|_{L^\infty(\partial U)} \ge \|Du\|^2_{L^\infty(U)} - 2|\lambda| \|u\|^2_{L^\infty(\partial U)}.$$ This result is different from what you deduced, but the desired result follows anyway (if I'm not mistaken).


Can I play Dead Island over a LAN?

Question: Tomorrow I'm going to go to visit my friend, I will bring my laptop.
He has Dead Island, and If there is any way we can play on LAN, I will also buy it.
Does it have LAN?
Answer: Yes you can, in fact you can specifically set it (in options) to allow only LAN, or both (I think it's both, it might just be internet), or neither. Just go into:

Options > Online > Gametype - Co-operative > Game Visibility - LAN

Can I play Dead Island over a LAN?


Jquery slider entered keyboard value works but though slider its not taking value

Question: Here is my code below...

and my html code ..
<input id='border_me' class='border_width' value='66' />

Iam using the above slider to display some data from server page...well if i enter value using keyboard and hit enter or mouse click it works fine but its not taking the value from slider i see it in the value field slider value is getting updated unfortunately nothing happens if i press enter or mouse click.....what could be the issue?
Answer: You were changing the value in the input, but weren't actually applying that value. You need to listen for the value changing in the input then apply it.
jsFiddle
HTML
<input id='border_me' class='border_width' value='66' />

JavaScript
$("#slider").slider({
    value: 10,
    min: 1,
    max: 400,
    step: 1,
    slide: function (event, ui) {
        //Its setting the slider value to the element with id "amount"
        $("#border_me").val(ui.value);
    }
});

$("#border_me").on('change', function () {
    $("#slider").slider("value", this.value);
});


How do I pass struts2  with a Map

Question: I have an bean placed on my action Event.java, the action is Called ManageEvents.  I would like the user to be able to add to a struts2 multiple select form field and create a list or map of items (in this case Map where the data would be .
<struts2:select name="event.dj_map" label="Add DJs To Your Event" list="event.dj_map" listsize="5" multiple="true" headerKey="headerKey" required="true" headerValue="--- Please Select ---">

So ultimately I would like to know how to pass a mult. select field (e.g. Events.dj_map) as a map of name,value pairs to an object (e.g. Event.java) set on the action (e.g. ManageEvents.java).
Answer: I've never done it as Map, and I'm not sure you can, but if you have this code in your Events class, it will be retreived on page load and populated with a List on submit:
public class Events {

   private List dj_map = new ArrayList();

   public List getDj_map(){
      return dj_map;
   }

   public void setDj_map(List dj_map){
      this.dj_map = dj_map;
   }
}

Once you get the above working, you could always try changing the type of dj_map to Map to see if Struts populates it properly.
And as a style note, the name of the variable should really be djMap, but hey, the code will still work just fine with the underscore.
Answer: The http request which is generated from a select with multiple=true will look like: name=option1&name=option2&name=option3 etc.
The Struts2 ParametersInterceptor will then pick this up an try to set your property either with String[] or any kind Collection.
In order to submit it onto a Map, it would have to know what to use for keys/values in that map (which isn't really possible) given the above request.
So I don't think you can directly have Struts2 submit your multiple options onto a Map.
Answer: 1) Define a Map in your action, e.g.:
public class Events {

   private Map<Integer,Integer> dj_map = new HashMap<Integer,Integer>();

   public Map<Integer,Integer> getDj_map(){
      return dj_map;
   }

   public void setDj_map(Map<Integer,Integer> dj_map){
      this.dj_map = dj_map;
   }
}

2) Pass parameters using map notations.
<input type="text" name="dj_map[#anyIntegerValue]" />
<input type="text" name="dj_map[#anyIntegerValue]" />

Here #anyIntegerValue can be any value that you want to use as key.
Answer: The select tag is filled with a map & it has to be submitted via an ArrayList/Array
<s:select list="myMap" name="myArrayList" multiple="true"/>

Action will look like
private Map<Integer,String> myMap;
private List<Integer> myArrayList;

Above is just a sample on how it's going to work. Let me know if any confusion.

How do I pass struts2  with a Map


Is API key needed when making a request for Google Directions and Geocode?

Question: I'm developing an application for both Android and iOS which is using Google Maps API, Google Directions API and Google Geocode API. The maps can't run without the API key so I got one from Google Console. There are API keys for Directions and Geocode too but I haven't requested them. In the documentations for Geocode and Directions it's written that API key should be added in the URL request and I haven't added them when I request from them and it is still working perfectly.
My question is: Do I need to request API keys for them? The app will be commercialized in the future.
Answer: https://developers.google.com/maps/documentation/directions/#api_key

All Directions API applications should use an API key.
Comment: https://developers.google.com/maps/faq#keysystem - Here Google says that the keys are just recommended.
Comment: 'The Google Maps JavaScript API v3 and the Maps Image APIs previously did not require an API console key. This is still supported for legacy applications to ensure backwards compatibility, but is no longer recommended for new applications.' - I think this isn't true when we talk about Android, because they want to limit max requests to 2500 / day when you are using free version.


Find the Fourier series of $\sin^3(x)$ on $[-\pi,\pi]$

Question: I'm having trouble integrating $B_{n}=\frac{1}{\pi}\int_{-\pi}^{\pi}\sin^{3}t \,\sin(nt)\,dt$.
Answer: I suggest using trig identities to rewrite $\sin^3(x)$ as $A\sin(x)+B\sin(2x)+C\sin(3x)$. Then there's your series right there.
Answer: Hint: Use: 1) $4\sin^3(t)=3 \sin(t)-\sin(3t)$
2) Use the formula for $\sin(a)\sin(b)$
Comment: There is nothing more to compute, the Fourier series is nothing more nor less than that sum of sine terms (divided by 4).
Comment: I see $B_1=\frac34$ and $B_3=-\frac14$, your function is already represented as trigonometric polynomial?
Comment: After using that identity, I get that $B_n=0$. Isn't this suppose to be non-zero since $sin^3(\theta)$ is an odd function?
Comment: @LutzL, But then $A_0=0$, so is $B_n$, then how do we represent the function as a trigonometric polynomial?
Comment: @LutzL, Don't we get 0/0 for $n=1,3$?
Comment: Where, why? As was said multiple times, there are no integrals to evaluate, the final result is already in the formula of the answer. Note also that $\cos(0\cdot x)=1$ and the integral of $1$ is $x$.
Comment: @LutzL, I tried that way now. I get that $f(x)$~$(1/2)[sinx+sin3x]$. But that isn't the formula for $sin^3t$. I evaluated $\int(cos(o))dt$ from $-\pi$ to $\pi$.
Comment: This should give the value $2π$, and since you have to divide by $2π$ to get the coefficient, $b_1=1$.


Why do my range hood's lights and fan only work properly when there's load elsewhere on the circuit?

Question: We have a Broan Allure III hood range that was installed in 2003. It has a three-level light system and a five-level blower speed. Both are controlled by front mounted push-buttons. It is wired into a 20amp wall circuit that also includes one kitchen receptacle and three garage receptacles. It is an un-grounded circuit. The house was built in 1957.
Since the hood was installed, it has exhibited the following odd behavior: With no load elsewhere on the circuit, the light has only two levels, low and high. No mid-range. Further, when starting the blowers, at any speed, the lights go off and the blowers do not work. Nor do the blowers start even without the lights on. However, (and this is the good part!) if there is a high load elsewhere on the circuit, both lights and blower work perfectly. We've gotten around this by turning on the toaster that's plugged into the kitchen receptacle. Once the blower is on, we turn off the toaster and both blower and lights work fine - Three light levels, all blower speeds. Only a high load seems to affect this. A light won't work but the toaster or an espresso maker will. Both pull over 1000 watts.
We thought the circuit board in the hood was bad so just recently had it replaced. Same problem. Electricians are stumped. Any ideas as to where to troubleshoot next are appreciated. Barring a solution I guess I can get another brand, but my wife likes this one and it works in our kitchen design.
Comment: Actual model number or link to it? If you remove the grids, isn't there a cover over its integral j-box? You need to 'hard wire' that thing and that thing only - to test that thing; you still have house wire in the equation. If it works fine then, then you're running a new line all the back to the load center and defuncting this one, because wtf is going on, IDK, and it ain't the thing. - If it's the thing, then ... obviously get a new thing.
Comment: @Mazura Which is why I came up with the extension cord test. But so far still has one segment of house wiring in the middle.
Comment: "the hood will have a junction box *built in to it* which will have short wires or screw connections. *That* is where you need to connect the extension cord (might mean taking down the hood) to rule out any 'house wiring'". - don't forget to disconnect the house wire when you put the cord on, otherwise it doesn't count. And take pictures of the wires so you don't mess it up putting it back
Comment: Are the push buttons real physical switches, or are they touch-sensitive pads? I wonder if the touch sensitivity was designed with certain assumptions and your lack of a ground changes those. I'm still trying to figure out how turning on the toaster helps though.
Answer: TL;DR DANGER! Something's seriously wired wrong
None of this fits with a problem in the hood itself. It all points to a problem elsewhere. I can't think of an exact scenario, but possibilities include a miswired MWBC, a loose connection that heats up under high load making other stuff work better, something wired in series instead of in a tree configuration, etc.
I would start with the hood connection. Disconnect it and check voltage hot-to-neutral, hot-to-ground, neutral-to-ground. I know you said "no ground", but many houses of that vintage (like mine) actually have ground in a lot of places just no (or few) 3-wire receptacles. If you have a metal cable and/or metal boxes they will often be ground. You're looking for 120V (+/- a few is OK, consistency is what matters, will treat as 120V for the rest of this) hot-neutral and (if you have ground) hot-ground and 0V neutral-ground. Check it (carefully) with lights, toaster, etc. off, with lights on, with toaster on. Report any change in the voltage as that is an important clue.
The next step is to check every junction box on this circuit. Which may not be so easy, so start with the easiest - the known kitchen and garage receptacles. In addition to checking for loose connections (and redoing/tightening them) and backstabs (move to screws) and replacing any receptacles that appear burnt up or broken in any way, note if there are any locations with extra wires - e.g., black/red/white instead of just black/white, as that would be an indication of an MWBC. An MWBC miswired can cause all sorts of problems.
Probably unrelated, but extremely important for safety: GFCI. Even if you do not have ground available (and you may have it, even if you don't think you do), you can and should install GFCI to protect kitchen and garage receptacles. Especially kitchen - the risk around water is simply too high to ignore when GFCI provides a huge increase in safety at a very low price. But that requires understanding Line vs. Load, so pictures and details will be helpful before attacking that part of the problem. In addition to safety, GFCI can often help narrow down certain other types of wiring problems because it will only work if many (not all) aspects of the circuit are properly wired.
Another thing to (carefully) try:
Take an extension cord, chop the socket (female) end off, wire it up to the hood and plug it in to a regular receptacle (GFCI or not doesn't matter, that's not the issue) that is on a different circuit. If that works (lights, fan) normally, plug it into the same circuit (i.e., where the toaster plugs in) and see if that works normally.
If it works on a different circuit, then the problem is in the wiring of the bad circuit. If it works on the same circuit in a regular receptacle (but not in the usual permanent wiring) then the problem is with that wiring - i.e., box it connects to, box in attic, etc.
Comment: Did it work **the day the electrician installed it**? Because if it didn't then he should be figuring it out - or determine that it truly is a hood problem.
Comment: The plot thickens. 122 -> 118 is reasonable for a large load on a 20A circuit. What voltage does it show at the hood (i.e., disconnect the hood and use a tester on the wires as if it were a receptacle) with toaster on/off?
Comment: Sorry, meant to add this: The voltage in the j-box going to the hood is 122. Nothing else in that j-box except the connection from the attic to the hood.  I'll next check any j-box in the attic and, if possible, run a ground connection to the line going down to the hood. With the toaster on, 118.
Comment: An open neutral or series device is what came to mind for me as well.
Comment: Is that 5' wire from the j-box into the hood "part of the hood" or "part of the house"? Typically (but not always) the hood will have a junction box *built in to it* which will have short wires or screw connections. *That* is where you need to connect the extension cord (might mean taking down the hood) to rule out any "house wiring". A pain, but need to narrow this down. Very, very strange.
Comment: In brief, it didn't work that day either. As I hired him to install the circuit board only, I didn't feel it was his responsibility to solve the original problem that day. The old board had developed unresponsive buttons (push buttons) and that was my main purpose in replacing it. The new buttons work fine.  Connecting a ground wire will be next.
Comment: An update: I ground the circuit but it made no difference. Ran a ground from the oven cable to the hood. Also tried a ground to the oven frame to the hood but that probably was redundant. I tested the wire from the jbox to the hood connection. All seemed solid. However, I replaced it with a piece of 14/2 cable just to be sure. No difference.
Comment: OK. I'll run the hood to a different circuit completely. One that I didn't use for the extension cord test earlier.   Bit of work, but this puzzle Needs resolution.
Comment: Thanks. First, all receptacles in the kitchen are GFCI, on three separate circuits. One of the garage receptacles on the circuit in question has a GFCI receptacle, the other three do not. All look OK re wear, shorts, etc. The voltage in the toaster receptacle is 122. With the toaster on, it drops to 118.
Comment: Thanks. Using an extension cord, I connected the 12/2 wire from the j-box in the cabinet just above the hood into the female end of the cord. I then plugged the ext. cord into a receptacle on a different circuit. The problem was the same: no load, no fan, just two light settings. I plugged the toaster into that same receptacle. Fan worked. So, it's either in the Broan control board or in the 5' wire from the j-box into the hood connection.
Comment: I also spoke with Broan, who were equally puzzled. They said maybe bad neutral or ground. I told him there was no ground, but he thought that should be ok, not ideal. As the hood is now (with this temporary workaround) on a different circuit, I'm not sure it can be a bad neutral.
Comment: That's a part of the house wire, not part of the hood. And yes, taking down the hood might need to be next. But when the electrician installed the new circuit board in the hood last November he connected things properly from what I could see. I even talked to him about this but he too shrugged. I suspect he thought it was in the house wire and wasn't in his purview that day.
Comment: Aha. I got confused. I thought you meant the original install, but that was in 2003. Has it had the problem for 18 years with no fix? Because that's the lifetime (often less) of a hood to begin with. And a *very* long time to go with it working so strangely.
Comment: It's almost certainly in the hood, either another bad control board or, possibly, the Heat Sensor. I'm not sure where that is, whether it's in the control board or elsewhere. The toaster solution still works though.
Comment: It makes no sense. If the circuit (external to the hood itself) is wired properly then the only effect of turning on something else should be a very small voltage drop.
Comment: It absolutely makes no sense, I agree. You asked for voltage readings earlier. Maybe the electronics is so sensitive that it registers the drop from 122 to 118.
Comment: Modern appliances built for nominal 120V should do absolutely fine between 110V and 125V, and many have a much wider range than that.
Comment: It's been a while but here's the last. Moved the hood to another circuit and insured it was grounded. The hood continues to exhibit the same failures. However, turning on the toaster did not resolve it this time. So it's in the hood alone. Apparently.


Interacting with view makes toolbar & title disappear

Question: I'm developing a Watch app that needs to receive images from iPhone. Users of the app need their hands free, which is why they will have to inspect those images on Watch. Thus, I added a rudimentary image viewer, allowing them to zoom in on images and pan around.
As soon as the user pans or zooms, toolbar and title will disappear. I observed this behavior on simulator and my colleague's Watch (A2376), but not on mine (A2356). Tested both on watchOS 9.6.2 and 10.0.1.
Why is this happening?
Here's some exemplar code:
// View is presented on a sheet

TabView(selection: $viewing) {
    ForEach(images) { reference in
        reference.img
            .resizable()
            .aspectRatio(contentMode: .fit)
            .scaleEffect(scale)
            .offset(offset + draggingOffset)
            .frame(width: screenSize.width, height: screenSize.height-1)
            .clipped()
            .id(reference.id)
            .gesture(panGesture, including: .gesture)
            .gesture(tapZoomGesture)
            .navigationTitle(viewerTitle)
            .focusable()
            .digitalCrownRotation(detent: $scale,
                                  from: 0.5,
                                  through: scaleMax,
                                  by: 0.1,
                                  sensitivity: .low,
                                  isContinuous: false,
                                  isHapticFeedbackEnabled: false,
                                  onIdle: { offset = stickyEdgeOffset })
    }
}

Answer: The solution was lifting out navigationTitle and toolbar. I really got lucky guessing.. can't imagine it's supposed to work like this.
someView
  .sheet(isPresented: $isShowingViewer, content: {
    imageViewer
      .navigationTitle("Image viewer")
      .toolbar(content: {
          ToolbarItem(placement: .confirmationAction, content: {
              imageViewerToolbar
        })
    })
})


Endomorphism ring of an abelian variety and its reduction mod $\mathfrak{p}$

Question: Let $A$ be an abelian variety defined over a number field $K$. Let $\mathfrak{p}$ be a prime of $K$ for which $A$ has good reduction and let $k=\mathcal{O}_{K,\mathfrak{p}}/\mathfrak{p}$. Let $\mathcal{A}$ be a Neron model for $A$ over $\mathcal{O}_{K,\mathfrak{p}}$. Then I have seen it mentioned that the following composition is an injection:
$$\operatorname{End}_K(A)= \operatorname{End}_{\mathcal{O}_{K,\mathfrak{p}}} (A)\to \operatorname{End}_k(\mathcal{A}\otimes k).$$
I cannot however seem to prove this. It seems like it should be easy though. Any help or direction is appreciated.
Answer: One may assume that $A$ is simple over $K$. Then $\mathrm{End}_K(A)$ is a division ring. Since the morphism into $\mathrm{End}_k(A\otimes k)$ is not zero, the kernel is $0$.


Find all positive integers $n \le 6$, such that the equation $a^n+b^n=c^n+n$ has solutions over the integers.

Question: Find all positive integers $n \le 6$, such that the equation $a^n+b^n=c^n+n$ has solutions over the integers.
My attempt:
For $n=1$, trivially there are integer solutions.
For $n=2$, we have the solutions
$$a=b=\pm 1, c=0.$$
For $n=3$, we have the solution
$$a=b=1, c = -1.$$
Anyone can complete the proof for $n=4,5,6$?
Comment: You have a (small, closable) gap for $n=4,6$ because youonly *supposed* that $|c|$ is not the smallest.
Comment: Yes, almost forgot. Will fix it! Thanks!
Comment: The gap seems not so small to me--you are actually supposing $|c|$ is not the largest, rather than that $|c|$ is not the smallest.  And the case that $|c|$ is the largest looks quite nontrivial.
Comment: @EricWofsey Yes, you are right. Thanks! Edited my question.
Comment: You have answered your question yourself [here](https://math.stackexchange.com/questions/2309674/find-all-positive-integers#comment4752467_2309674), and then deleted it. Why?
Comment: Because I found my answer is wrong.
Answer: $n=4$:
fourth powers are $\equiv 0$ or $1\pmod{8}$. There is no way to have $(0\text{ or }1)+(0\text{ or }1)\equiv (0\text{ or }1)+4\pmod 8$.
$n=5$:
Fifth powers are $\equiv 0$ or $1$ or $-1\pmod{11}$. Three such numbers combined cannot produce $5$, i.e., $a^5+b^5-c^5\equiv -3,-2,-1,0,1,2,3\not\equiv 5\pmod {11}$.
$n=6$:
Sixth powers are $\equiv 0$ or $1$ or $-1\pmod{13}$. Three such numbers combined cannot produce $6$, i.e., $a^6+b^6-c^6\equiv -3,-2,-1,0,1,2,3\not\equiv 6\pmod {13}$.
Answer: If $n$ is such that $2n+1$ is prime, then the only $n$th powers mod $2n+1$ are $0$ and $\pm 1$ (since the group of units mod $2n+1$ is cyclic of order $2n$).  It follows easily that $a^n+b^n=c^n+n$ has no solutions mod $2n+1$ if $n>3$.  In particular, this handles the cases $n=5$ and $n=6$ (as well as infinitely many other larger values of $n$).
For $n=4$, you need a more ad hoc argument, since $2n+1$ is not prime.  Working mod $8$ does the trick, since the only $4$th powers (in fact, the only squares) mod $8$ are $0$ and $1$.
Comment: Thank you for the answer. But I need to learn more about group theory first to fully understand it! :)


Arduino inline ASM not working as expected

Question: I'm trying to build a clock, so I'm working with ASM and an arduino. For most parts, plain C will be fine, but for preparing the time to be output to BCD to Decimal converters I decided to go with ASM. I wrote the following code in 8086 C++/ASM and it runs fine on my computer:
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
    for(int num = 0; num < 16; num++) {
        int bin[4];
        bin[0] = bin[1] = bin[2] = bin[3] = 0;
        asm("movl %%ebx, %%eax;"
            "andl $8, %%eax;"
            "cmp $0, %%eax;"
            "je a;"
            "movl $1, %0;"
            "jmp b;"
            "a: movl $0, %0;"
            "b: movl %%ebx, %%eax;"
            "andl $4, %%eax;"
            "cmp $0, %%eax;"
            "je c;"
            "movl $1, %1;"
            "jmp d;"
            "c: movl $0, %1;"
            "d: movl %%ebx, %%eax;"
            "andl $2, %%eax;"
            "cmp $0, %%eax;"
            "je e;"
            "movl $1, %2;"
            "jmp f;"
            "e: movl $0, %2;"
            "f: movl %%ebx, %%eax;"
            "andl $1, %%eax;"
            "cmp $0, %%eax;"
            "je g;"
            "movl $1, %3;"
            "jmp h;"
            "g: movl $0, %3;"
            "h: nop"
            : "=r" (bin[0]), "=r" (bin[1]), "=r" (bin[2]), "=b" (bin[3])
            : "b" (num)
            : "%eax"
            );
        cout << num << ": ";
        for(int i = 0; i < 4; i++) {
            cout << bin[i];
        }
        cout << endl;
    }
    return 0;
}

However, when I modified it to run on the Arduino, things stop working entirely:
  for(uint8_t num = 0; num < 16; num++) {
  uint8_t bin[4];
  bin[0] = bin[1] = bin[2] = bin[3] = 0;
  asm("mov __tmp_reg__, %[val];"
    "and __tmp_reg__, $8;"
    "cmp __tmp_reg__, $0;"
    "je a;"
    "mov %[bit8], $1;"
    "rjmp b;"
    "a: mov $0, %[bit8];"
    "b: mov %[val], __tmp_reg__;"
    "and __tmp_reg__, $4;"
    "cmp __tmp_reg__, $0;"
    "je c;"
    "mov %[bit4], $1;"
    "rjmp d;"
    "c: mov $0, %[bit4];"
    "d: mov %[val], __tmp_reg__;"
    "and __tmp_reg__, $2;"
    "cmp __tmp_reg__, $0;"
    "je e;"
    "mov %[bit2], $1;"
    "rjmp f;"
    "e: mov $0, %[bit2];"
    "f: mov %[val], __tmp_reg__;"
    "and __tmp_reg__, $1;"
    "cmp __tmp_reg__, $0;"
    "je g;"
    "mov %[bit1], $1;"
    "rjmp h;"
    "g: mov $0, %[bit1];"
    "h: nop"
    : [bit8] "=r" (bin[0]), [bit4] "=r" (bin[1]), [bit2] "=r" (bin[2]), [bit1] "=r" (bin[3])
    : [val] "r" (num)
    : "r0"
    );

The 8086 code gives the output you'd expect:

0: 0000
  1: 0001
  2: 0010
  3: 0011
  ...
  13: 1101
  14: 1110
  15: 1111

But the code run on the Arduino gives a different output:

0: 5000
  1: 0000
  2: 0000
  3: 0000
  ... (zeros continue)
  13: 0000
  14: 0000
  15: 0000

As you can imagine, the code becomes useless if it returns... five. And I'm clueless as to how it could return 5 when nothing is anywhere close to 5 in the source. I'm at a loss as to what to do here, so I could really use some help.
I'm using the Arduino Leonardo, which has an ATMega32U processor. I've tried disassembling the executable generated by the Arduino software (which compiles it with AVR-GCC), but I can't seem to get anywhere in my efforts to find the code I put in.
Thanks for your time, Stack Overflow.
Answer: The code you have can EASILY be written in C++, like this:
 int bin[4] = {};

 bin[0] = !!(num & 8);
 bin[1] = !!(num & 4);
 bin[2] = !!(num & 2);
 bin[3] = !!(num & 1);

or:
int bin[4];
int bit = 8;
for(int i = 0; i < 4; i++)
{
    bin[i] = !!(num & bit);
    bit >>= 1;
}

If you don't like !! (which makes "take the next value and make it either 0 [if it's false] or 1 [if it's true]), you could replace it with:
for(int i = 0; i < 4; i++)
{
    bin[i] = (num >> 3 - i) & 1;
}

I take it you intentionally want the highest bit in the lowest bin index, rather than the usual case of highest bit in the highest index.
Comment: Since this is just for my own use, it doesn't really matter to me which bit is in which index. I just wrote it the way I'd read it, with the highest bit first and the lowest bit last.


TextView not displaying text

Question: I am trying to get text from getText method from database and display the string in the TextView. But I have no idea why it is not working.
Database:
 public String getType(String search){

        String type="";

        String searchTypeQuery="SELECT * FROM "+ DatabaseData.TABLE_NAME + " WHERE "+ DatabaseData.NAME+ " LIKE '%" +search +"%'";
        SQLiteDatabase db=this.getWritableDatabase();

        Cursor cursor=db.rawQuery(searchTypeQuery,null);
        // looping through all rows
        if (cursor.moveToFirst()) {
            do {

                String objectName = cursor.getString(cursor.getColumnIndex(DatabaseData.TYPE));
                type=objectName;

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();

        // return the list of records
        return type;
    }

Main:
if (database.getType("Sample")=="A"){
                textview.setText("Type");
            }

I tried this "textview.setText(database.getType("Sample"));" and it worked. But when i try the above code it doesn't work.
Answer: Try database.getType("Sample").equals("A") as the if-condition. And here is explanation.
Comment: Please flag or comment as a duplicate. This problem is so frequent, no need to answer, really
Answer: You have to use equals method when you are comparing Strings. Remember that Strings are objects.
You can read this to know more info about comparing Strings: https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html
Comment: Please flag or comment as a duplicate. This problem is so frequent, no need to answer, really

TextView not displaying text


Rudin Theorem 2.41 - Heine-Borel Theorem

Question: When proving Theorem 2.41 in Principles of Mathematical Analysis:

Let $E \subset \mathbb{R}^k$. If every infinite subset of $E$ has a limit point in $E$, then $E$ is closed and bounded.

Rudin says,
"If $E$ is not bounded then $E$ contains points $x_n$ with
$$\vert x_n \vert > n \hspace{2cm} (n = 1,2,3,...).$$
The set $S$ consisting of these points $x_n$ is infinite and clearly has no limit point in $\mathbb{R}^k$, hence has none in $E$."
My first reaction to this was that it is indeed obvious as $S$ is composed of discrete points so I could find a ball around any given point not containing a point of $S$. So, if $p \in \mathbb{R}^k$ is the point I'm constructing a ball around, taking the radius of the ball as $r = \min_{x_n \neq p \in S} \{ \vert x_n - p \vert \}$ should work and as $p$ was arbitrary $S$ doesn't have a limit point. However, I'm not sure if I can take the minimum over an infinite set? I honestly don't know why I shouldn't be able to, but nonetheless I decided to try another proof:
Suppose that $S$ has a limit point $p \in \mathbb{R}^k$. Then for any $r > 0$ $B_r(p)$ has infinitely many points of $S$. So in particular, $B_{\frac{1}{2}}(p)$ contains infinitely many points of $S$. Therefore, there exists a point $y_m \in B_{\frac{1}{2}}(p)$ with $\vert y_m \vert > m > \vert p \vert + 1$ (as otherwise, there would be only finitely many points of $S$ in $B_{\frac{1}{2}}(p)$). Therefore, we have
$$\vert y_m - p \vert \geq \big\vert \vert y_m \vert - \vert p \vert \big\vert > 1 $$
However, this is a contradition as we also have $\vert y_m - p \vert < \frac{1}{2}$. Therefore, as $p$ was arbitrary, $S$ has no limit point in $\mathbb{R}^k$.
My questions:
Can I take the min over an infinite set as in my first argument? Is my second argument okay?
I appreciate any answers. Thanks.
Comment: Hint:  In a general set of positive real numbers, there might not be a minimum. (Or if you take the "infimum," the infimum will exist but might be zero.) But in this specific case, due to the properties of the $x_n$, you only need to take the minimum for finitely $n$.
Comment: @ThomasAndrews Thanks for your comment! It essentially answered both of my questions. Thanks.
Answer: Fix an arbitrary point $p\in{\mathbb R}^k$. Put $n_p:=\bigl\lceil|p|\bigr\rceil+1$. All $x_n\in S$  with $n\geq n_p$ satisfy
$$|x_n|>n\geq n_p\geq|p|+1\ .$$ Therefore all these $x_n$ are outside  the ball of radius $1$ around $p$. It follows that the chosen $p$ cannot be a limit point of $S$, and since $p$ was arbitrary the set $S$ cannot have a limit point in ${\mathbb R}^k$ whatsoever.
Comment: Thanks for this answer. It ties in nicely with Thomas Andrews comment and I prefer direct proofs rather than indirect proofs so its very instructive! Thanks!


After trying to decode Base64, reciving E/AndroidRuntime: FATAL EXCEPTION: main

Question: I´m building a simple app for android 4.4 and up, i have a method to decode base64 string using the apache-commons-codec library.
import org.apache.commons.codec.binary.Base64;

public static String decodeBase64(String toDecode) {
    byte[] decoded = Base64.decodeBase64(toDecode);

    return new String(decoded);
}

but when i call this static method from the main (like className.decodeBase64(VAR)) I receive the following error.
error log
i'm currently using jdk 8 and the last version of android studio.
I know that the jdk8 implements a base64 encoder/decoder but i can´t use it, because I was limited to programming to more recent android versions at 8.0
Answer: It may be an issue with the library version. Which version of commons-codec do you use in your build.gradle file?
Try updating it to the latest, which is 1.13.
Also this may be the solution for your issue:
Apache Commons Codec with Android: could not find method
Comment: Thanks for the response, i already try it. not working neither. the second option that i try was importing the jar file from Comms to the project. but dont work
Answer: After two days looking for it, i find a nice solution.
Just need to replace the apache.commons with android.util.Base64, who'd say...
the method would look like the following:
import android.util.Base64;

public static String DecodeBase64(String toDecode){
    byte[] decodeValue = Base64.decode(toDecode, Base64.DEFAULT);
    return new String(decodeValue);
}

also, if someone knows how to solve the original error and please explain me why that happen, it would be helpful


smeg refrigerator not cooling

Question: My smeg refrigerator (SIL 566 H) is not cooling. The lower freezer is frozen and filling with ice, and the upper part is warm. After disonnecting the refrigerator for a few hours to let the ice melt, it starts working again for some days/weeks, and then gets warm again, while beeping and flashing a red !sr led.
This has been going on for some years, getting worse lately.
I've tried to find blockages or stuck fans, but couldn't find any. I also took down the inside panels and I can feel cool air flowing from the air tunnel, but it feels not cold enough.
Do I have to call a technician, or is there anything else I can try by myself?
Comment: Just a guess, but !sr = "service required?" Our GE fridge behaves similarly if the kids leave the door ajar for too long. When that happens, I go into service mode and force a defrost cycle. It seems like the tunnel between the lower freezer and upper fridge ices up and blocks the air flow.
Comment: I wanted to buy a smeg, I really liked their retro design. Unfortunately, most reviews showed poor reliability.  Could be a bad evap fan?  Or your freezer is simply over stuffed. You probably need a technician on this one.
Comment: Would be nice to know what !sr means.  I couldn't find a product manual.
Comment: I would like to know that as well...
Answer: It sounds like the defrost cycle is not working. Ice builds up on the evaporator and eventually blocks the air flow to the refer section. Defrost is set to occur usually once or twice a day. Most common failures are the defrost timer or the defrost heater. Sometimes though, it is the defrost termination sensor that is found strapped to the refrigerant return line. If you can locate the timer, check that the timer motor is turning . Some timers can be advanced with a flat blade screwdriver in order to start the defrost cycle.
The heater will be found embedded in the fins of the evaporator coil. (good luck trying to replace the heater) When the defrost is working you should be able to see some of the water from the melted ice. The water drains from the evaporator into a catch pan located under the unit where it evaporates. Squido
Comment: Good info here.  Welcome to the site, hope to see you around.

smeg refrigerator not cooling


What does the red X mean?

Question: I was playing some quick match multiplayer and I noticed one of the players (who was not ready, and was taking a long time) had a red X on his display.
What does it mean?
Comment: btw, the X, arrow and box was all red, even when I had a different player selected.
Comment: Should the [tag:multiplayer] tag be added here?
Answer: That's the "Vote to Kick" icon.
It's a very literal case of "Three strikes and you're out".
Comment: To kick someone press the y button incase you didn't know that. Sometimes people join games just to troll people by not being ready.

What does the red X mean?


Grounding chandelier in old pan junction box

Question: I recently removed a crossbar from one of my ceiling pan junction boxes and replaced it with a hickey. As I understand it, having the crossbar was a bit odd since a mounting stud was already available. But, I wonder if the crossbar was there specifically for the sake of grounding.

I replaced the crossbar with a hickey attached to the mounting stud/bolt/screw in the ceiling as illustrated in these depictions.

This worked great. However...
The crossbar had a green 10-32 ground screw in it. There is no such ground screw in the junction box now that the crossbar is gone and the hickey is in place. The ground wire from the chandelier was connected/fastened to the ground screw on the crossbar. There are no ground wires at all in the junction box. There is no place for a ground screw in the junction box.
It seems common in Chicago (where I live) to find that the junction boxes in a home don't have ground wires. It seems most likely that the box is grounded through the metal conduit.
What would be an ideal way to handle this chandelier ground wire now that I have no obvious place to connect it?
Coil it up and tuck it away in the junction box, or otherwise leave the wire disconnected (though keeping in mind that this could be a safety risk or illegal)? Drill/tap a hole for a ground screw in the junction box?
This and this lead me to believe that although the mounting hardware may have seemed redundant, the mounting strap was indeed performing a necessary function before, and that a saftey risk is now present without that ground wire being connected.

Yes, metal-metal contact between parts is acceptable grounding if all these are true:

the mounting bracket is bottomed out "hard" against the metal junction box (not dangling by the screws or floating on drywall ears, as is usually the case with receptacles and switches)
and both are clean bare metal (not contaminated with paint, rust etc.)
and there are no insulators in the way (those little squares that outlets use to capture screws).

These conditions ^ were present with the previous crossbar assembly.
Comment: Is there not already a 10-32 hole in the back of the existing box?
Comment: Correct. There is *not* a 10-32 hole in the back of the existing box.
Comment: In my junk box I found a hickey like the first one shown above, but with a threaded 10-32 hole in the side. I've never seen such a thing for sale. I think someone invented his own idea of how to ground a pendant lamp. I guess screw there would make sense if grounding lugs did not exist.
Answer: You want a grounding lug of the proper size to fit over the nipple, between the hickey and the lock nut. These are sometimes available with a grounding wire already attached.

Trim the grounding wire to about 6" and attach to the lamp ground wire with a wire nut.


Correct use of flexi-coupling

Question: What's the correct way of using flexible tap connectors with normal UK domestic plumbing?
They're sold at most plumbers as a convenient way of connecting bath taps, ball-valves and showers etc. The normally come with one end that looks like this....

Which can be screwed straight onto a normal 1/2 inch or 3/4 inch connector on the underside of the tap. Like this.....

Sometimes this works fine, but often the threaded brass connector on the tap doesn't really seem to be designed to fit the flexi-connector. The end (of the tap) is often quite sharp and jagged, and unless I spend five minutes beforehand filing and sanding it smooth then the rough metal on the tap cuts into the rubber seal in the flexi coupling causing the joint to leak.
The taps seem to have been perfectly designed for connection to 15 or 22mm copper pipe using an olive, a nut and a length of PTFE tape but they don't appear well suited for flexi-connectors. Am I really supposed to file them smooth by hand before connecting to them? or am I missing something? Is there an extra washer I'm supposed to fit instead?
Any help appreciated.
Update following comments - I have measured the width of the flattened end of the tap tails of an old bath-tap. It's hard to be accurate but it's about  0.3mm. This is pretty narrow, it doesn't seems to take much over-tightening before it starts to cut into the rubber. My technique is normally to tighten finger-tight, then turn the mains water supply back on, then repeatedly tighten quarter-of-a-turn till the dripping stops. Then after a while i realise I've cut into the rubber of the washer.
Comment: That end is designed to just tighten on like a shower hose, 1/2" or 3/4" BSP. The other end is a proper compression joint to fix to standard 15mm copper pipe. I've not seen tap tails that weren't smooth enough to just do this, like the ones in your 2nd pic, but I don't do this for a living so my sample set is small.
Comment: We use the same compression fitting in US plumbing, but the compression fitting is on the wall fitting side, not the fixture. Could this also be the case for UK?
Answer: The flexi coupling should thread easily on any fixture of the same size.
Do NOT use any type of tape product (PTFE or similar) This can only be more of a problem. The flexi is made to be used without any other sealer, but if you must use a small amount of Teflon paste to lubricate the threads.
My experience with these leaking is caused by either under or over tightening.
If you are cutting the rubber seal you are over tightening.
These are not made to be tightened like a compression coupling.
They should be tightened by hand until firm.  Then another 1/4 to 1/2 turn only.

Correct use of flexi-coupling


Hatcher $1.2.17$: Fundamental group of $\mathbb R^2 - \mathbb Q^2$

Question:
Show that $\pi_1(\Bbb R^2 - \Bbb Q^2)$ is uncountable.

Since $\Bbb Q^2$ is countable we can enumerate the elements as $q_1, \dots, q_k$ and now $\Bbb R^2 - \{q_1, \dots, q_k\}$ is essentially the plane with countable many holes. Now $$\Bbb R^2 - \{q_1, \dots, q_k\} \simeq \bigvee_{i=1}^k S^{1}$$ so by Van-Kampen's theorem $$\pi_1(\Bbb R^2 - \Bbb Q^2) \cong \pi_1\left(\bigvee_{i=1}^k S^{1}\right) \cong \Bbb Z \ast \dots \ast \Bbb Z \text{ (k times)}$$
so this would be the same thing as showing that the free product of the integers $k$ times is an uncountable set? However I think this is a false statement as the countable free product of countable sets is countable so what is going on here?
Comment: Just because $\mathbb{Q}$ is *countable* does not mean $\mathbb{Q}$ is *finite*. There is no enumeration of $\mathbb{Q}$ that consists of only $k$ elements.
Answer: $\Bbb Q^2$ is countably infinite.
So you actually get the so-called Hawaiian earring for the homotopy type of $\Bbb R^2-Q^2$.
Its fundamental group is uncountable.
The group is called the Hawaiian earring group.  $\Bbb Z^\Bbb N$ can be embedded in it, which proves it's uncountable.
Comment: Why would $\mathbb{R}^2-\mathbb{Q}^2\simeq\bigvee_{k\in\mathbb{N}}S^1$? Doesn't sound right.
Comment: Sorry,  you get the Hawaiian earring.  @Thorgott


Authentication microservice decoupling

Question: I want to make a simple project with a couple of microservices.
I have User microservice, which controls the all user related staff like user creation, update information about the user, etc.
And now I need to do the authentication for my project. And I stuck a bit.
I want to implement simple JWT authentication with refresh tokens. I know how to do that but I don't know where to do that.
So my question is: do I need to do authentication logic on the User microservice, or I need to keep it separate and create the Auth microservice?
If I choose the second option with separate Auth microservice, in which way should I handle the creation of the user? Create it firstly in Auth service and then call the User service from it? Or create it on User service then create it on auth service?
Answer: You can do it in user microservice as long as it's independent and can issue token. I would advise to use federated identity providers rather writing your own. e
g. azure ad or auth0.com . They are generally better secured and follow the best practices.  You get many out of box features using federated identity providers e.g. login with fb google etc.

Authentication microservice decoupling


X11 with window decorations on ubuntu mini distro

Question: Goal: To display an application in the middle of the screen on a solid colour background. This means nothing else showing no gnome-desktop nothing apart from the application and the solid colour background.
Currently I'm using X11 for the background xstart -solid Grey which is great however as a test application I'm running firefox which I see has no window decorations ie: max, min title or boarder neither for that matter does xterm. I was wondering if it is possible to show the decorations without installing gnome possibly by installing just the themes eg: gnome-themes which I have done but have been unable to make the connection, or weather just running X isn't going to work without more gnome modules. I'm new to delving into the inner workings of linux as I've never had to deal with it before. I did ask a question previously which led me to xstart and xsetroot and I've been playing around with them for a bit trying to familiarise myself.
I do recognise that it is possible that I have gone about this all wrong, but if we don't try we don't learn.
If anyone knows of any tutorials or documentation that could help or if anyone has any tips I'd be grateful for the pointers.
Cheers
Chris
SOLUTION
Just thought I'd mention that I solved my issue after installing an ubuntu server distro I added xinit via apt-get then added metacity Then I edited the gconf files using gconf-editor then removed the Gnome-panels from /usr/bin However as I may possibly require them in the future I have made a copy of them before I deleted them. Thanks again for the help it was much appreciated.
Comment: Are you asking how to do this in programming, or in the application?
Answer: The window decorations are created/managed by the window manager. If you don't have one running, you won't get window decorations.
Comment: cheers for that I'll look into it, sounds obvious really, maybe its just been a long day lol
Answer: Ok... I think I understand what you are asking. Gnome is a "Desktop", and includes with it one of many "Window Managers" called Metacity if I remember correctly. That is the part that adds the title and borders etc. There are many pure window managers(not desktops). A common and popular "Window Manager" is fluxbox although there are many others. Fluxbox does allow you to "undecroate" a window when you launch it. I'm not sure if this is what you are asking. Hopefully it is of some help.


How much experience does the enemy get when we deny a creep

Question: How much experience does the enemy get when we deny a creep? (if any)
And How much do we get? (if any)
Comment: Why do you want to know about a past version?
Comment: I want to know the most recent one, but according to this https://dota2.gamepedia.com/Denying 7.06 has the latest changes in the denying mechanic right?
Comment: No, that's not right.
Answer: Patch 7.07
Denied XP granted to the enemy (the player being denied) reduced from 70% to 25%.
Denied XP gained by the denier reduced from 30% to 25%.
Neutrals killing lane creeps is now considered the same as the enemy creeps killing them—it's not a deny, and gives full XP. You must deny the creep yourself to deny its XP.
Comment: this means both of us get 25% ?
Comment: Yes, if the enemy is in experience range (1500 as of 7.07)
Answer: As of Patch 7.07c (current)
<code>             | Normal | Denier | Enemy |
----------------------------------------
       Melee |     57 |     14 |    14 |
      Ranged |     69 |     17 |    17 |
       Siege |     88 |     22 |    22 |
 Any player- |    100%|      0%|     0%|
  controlled |        |        |       |
</code>
Source: Gamepedia


JSON Parser in C (Prints JSON)

Question: Let me start off by saying that I am not an expert in C. I have been reviewing the code of a JSON parser.
I am trying to understand this piece of code.
/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr(const char *str)
{
    const char *ptr;
    char *ptr2,*out;
    int len=0;
    unsigned char token;

    if (!str)
        return cJSON_strdup("");
    ptr = str;
    while ((token = *ptr) && ++len) {
        if (strchr("\"\\\b\f\n\r\t", token))
            len++;
        else if (token < 32)
            len += 5;
        ptr++;
    }

    out = (char*)cJSON_malloc(len + 3);
    if (!out)
      return 0;

    ptr2 = out;
    ptr = str;
    *ptr2++ = '\"';
    while (*ptr) {
        if ((unsigned char)*ptr > 31 && *ptr != '\"' && *ptr != '\\')
            *ptr2++ = *ptr++;
        else {
            *ptr2++ = '\\';
            switch (token = *ptr++) {
                case '\\':      *ptr2++='\\';   break;
                case '\"':      *ptr2++='\"';   break;
                case '\b':      *ptr2++='b';    break;
                case '\f':      *ptr2++='f';    break;
                case '\n':      *ptr2++='n';    break;
                case '\r':      *ptr2++='r';    break;
                case '\t':      *ptr2++='t';    break;
                default:
                    /* escape and print */
                    sprintf(ptr2, "u%04x", token);
                    ptr2 += 5;
                    break;
            }
        }
    }
    *ptr2++ = '\"';
    *ptr2++ = 0;
    return out;
}

A really general summary of how this code actually works would be really great, my impression has been that it is "beautifying" the JSON string, is that correct?
At first glance it appears to be replacing \r with r, but what would the point of this be?
I have been researching the functionality of sprintf, but for simple things such as printing out currency values or other formatting issues. But I haven't got a clue what the sprintf function is doing here:
sprintf(ptr2,"u%04x",token);ptr2+=5;

And what is the purpose of the ptr2+=5 ?
Any insight into this would really be helpful.
Answer: What it's doing is turning control characters into the escape sequences you'd normally use in C source code.
if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\')
    *ptr2++=*ptr++;

This is basically saying "if we have a normal character like a letter, digit, etc., just copy it directly from input to output."
 else
 {
     *ptr2++='\\';

Otherwise, we're going to produce an escape sequence in the output, which will start with a backslash.
     switch (token=*ptr++)
     {
         case '\\':      *ptr2++='\\';   break;
         case '\"':      *ptr2++='\"';   break;
         case '\b':      *ptr2++='b';    break;

Then, depending on which control character it finds, it generates the second character of the escape sequence, so an actual 'backspace' character in the input (which will compare equal to '\b') will produce the two characters `\' and 'b' in the output.
          case '\f':      *ptr2++='f';    break;
          case '\n':      *ptr2++='n';    break;
          case '\r':      *ptr2++='r';    break;
          case '\t':      *ptr2++='t';    break;

and the same for form-feed, new-line, carriage return and tab.
          default: sprintf(ptr2,"u%04x",token);ptr2+=5;   break;

Otherwise, render the control character in hexadecimal, so it becomes something like \1234.
Comment: Very well explained, ty for the time it took!
Answer: What this code is doing is replacing non-printable characters such as U+000A (line feed) with escape sequences in the string such as \n (two characters, \\ and n).
The variable ptr2 points to the current point in the output, and the variable ptr points to the current point in the string that is being written to the output.
// Write "u" followed by a 4-digit hexadecimal number to the output
sprintf(ptr2,"u%04x",token);
// Advance the output pointer by five spaces
ptr2 += 5;

By comparison,
*ptr2++ = 'r';

Is the same as,
// Write "r" to the output
*ptr = 'r';
// Advance the output pointer one space
ptr++;

Answer: The function is escaping the string content, not beautifying it - for example it converts a carriage return character (ASCII code 13) into the string \r, it converts other non-printable characters in their code ect.
sprintf(ptr2,"u%04x",token);

places into ptr2 the hexadecimal representation of token (the x), padded with 0s to be four character in lenght (the 04), and prefixed with u - the following
ptr2+=5;

moves the ptr2 pointer right after the string that has been just generated by sprintf - that is 5 characters long.

JSON Parser in C (Prints JSON)


Selenium: Two different browsers giving back two different xpaths

Question: Two different pages are returning two different xpaths. In google chrome, there is a button on the webpage that says 'search'. In Firefox, however, this same button says 'search query' and the pages are structured a bit differently. How should I resolve this if tests are run by either chrome and Firefox to receive consistent results.
Comment: They should have either consistent ids or class names across browsers, right? Why can't you just use that to get the button?
Comment: can u paste the link?
Comment: Please post the HTML markups from Chrome and Firefox.
Comment: just kidding. html is the same but the text of the button is different
Answer: If you insist on using button's text to locate it:
<code>//button[. = "search" or . = "search query"]
</code>
or:
<code>//button[contains(., "search")]
</code>
Answer: Go with OR Condition in Xpath.Replace * with tagName
<code>//*[@value='search' or @value='search query']

//*[text()='search' or text()='search query']

//*[starts-with(@value,'search')]

//*[starts-with(text(),'search')]
</code>


Can we extend the Rep points out to visualize their true value?

Question: Earlier this evening I had a post answered by a prominent member of the SE community. Despite it being a meta.drupal question, I think it applies to all of the SE community out there.
This person had more than 30,000 points attributed to their profile. Yet, when I saw how it was represented XXk, I thought how unfair that was.
In the US military commissioned officers are given visual badges of their achievements:  http://en.wikipedia.org/wiki/General_%28United_States%29
Can we do something similar here? Why does a person with 9000 get to be shown as longer than someone with 40000? 9000 and 40k and visually unequal.
If you had 100k points, would you want it simply represented as 100k? or 100,000? Let's give credit where credit is due. Let's give these guys rep point values they can be proud of, especially when compared against their lower ranking officers!
Although the post is a bit tongue in cheek and playful, there is, I hope, some value here. Let's create a badge system that, without having to second-glance at it immediately gives credit to those who have sacrificed more time than others for the benefit of the community.
Comment: Just as an FYI in case you didn't know - votes work differently on meta sites, so the fact you have a down vote doesn't mean it's a bad question - just that someone disagrees :)
Answer: I do not think this will make it any better than worse (wondering what clive and other multi-thousand reputed users would say).
These units are made to avoid what you are trying to get back.
8 GB is, in my opinion looks decent than 8192 MB.
Answer: That's kind of what badges are for.
Comment: The OP is asking to always show all the digits of the reputation. Reputation and badges are two different things, as most badges are not directly linked to the reputation. For example, [ermannob](http://drupal.stackexchange.com/users/11884/ermannob) has 11 bronze badges, but his reputation is 354; [David Thomas](http://drupal.stackexchange.com/users/7153/david-thomas) has 8 bronze badges, but his reputation is 2689, and he is the user who gained more reputation this year.
Answer: Once you become a 10K user, it doesn't matter so much if the user's reputation is shown as 34,492 or 34.5K. The reputation is written using all the digits in the user profile page (in my case, https://drupal.stackexchange.com/users/199/kiamlaluno).


Matching panel data at time t-1 and time t Python Pandas

Question: I am currently working on a project involving financial data. I have a data frame containing a number of fundamental variables as well as stock returns for many different companies, just like this:
           year     ticker      tot_assets      return
0          1999       AAPL          10.345      0.1294
1          2000       AAPL          10.988      0.1577
2          2001       AAPL          12.003      0.0782
..          ...        ...             ...         ...
34521      2017       GMBO           0.893      0.2209
34522      2018       GMBO           1.206      0.1001
..          ...        ...             ...         ...
200344     2012         ZZ           3.789      0.0032
200344     2013         ZZ           3.021     -0.0346

What I have been trying to do without success is, to match each company ticker with another one in the df based on the closest tot_assets value on year t-1. Thus create two new columns, where one has the ticker of the matched company as well as its returns at time t. So we are doing the matching at time t-1 but the reported returns are for time t.
So it should look like something like this:
           year     ticker   tot_assets   return   m_ticker   m_return
0          1999       AAPL       10.345   0.1294         AA     0.0890
1          2000       AAPL       10.988   0.1577         AA     0.1666
2          2001       AAPL       12.003   0.0782       TSLA     0.3470
..          ...        ...          ...      ...        ...        ...
34521      2017       GMBO        0.893   0.2209        AIR     0.0032
34522      2018       GMBO        1.206   0.1001       CECE     0.1123
..          ...        ...          ...      ...        ...        ...
200344     2012         ZZ        3.789   0.0032       ASKI     0.0432
200344     2013         ZZ        3.021  -0.0346       ASKI     0.0339

I hope I was clear enough in my explanation :P Maybe that's the reason why I have been having troubles! I cannot show you the df because it has more 200'000 observations - but I hope that the concepts above help :)
Thank you in advance!
Comment: What did you try to solve this?
Comment: So you want to find the divergence between last years closest match to this years current result? I feel like including the second tickers data in the original set would be beneficial.
Comment: @BjörnB Yeah i did but its not the right result, I can only get a match year to year - I don't know how match at t-1 but then get return for t
Comment: @LuckBox I am trying to do kind of an event analysis, so i need to match the firms on total assets value at time t-1 but then compare their returns at time t
Comment: I feel being able to pass a number of test cases is key to providing the most succinct answer. I feel it would be even more beneficial to provide the 2nd most closest ticker in the original dataframe as well as the closest to confirm the code works as intended. Providing your most recent attempt would also be appreciated.
Comment: @LuckBox I am following another paper's methodology and they have done this way, so thank you for your suggestion, but just to keep things simple we should keep it to the closest
Comment: this was the code for my attempt, but I repeat, it is not correct:
df = df.merge(df, on='year', suffixes=['', '_closest']).query('ticker != ticker_closest')
df['diff'] = (df['tot_assets'] - df['tot_assets_closest']).abs()
df = df.sort_values('diff').drop_duplicates(['year', 'ticker'])
Comment: Can you explain how it is not correct? Can you do this by editing your post with your code and the result and explain why the result is incorrect?
Answer: This should get you the ticker of the firm with the closest match of tot_assets in year - 1. Hopefully, you only need to run it once to create the dataset. Otherwise, you'll have to investigate faster alternatives.
import numpy as np

def closest_match(row, df):
    '''Uses absolute values and argmin to find closest match'''
    try:
        last_year = df.loc[df.year == row.year - 1, :]
        absvals = np.abs(last_year['tot_assets'] - row.tot_assets)
        return last_year.iloc[absvals.argmin(), last_year.columns.get_loc('ticker')]
    except Exception as e:
        return None

df['ticker_closest_tot_assets'] = df.apply(closest_match, args=(df,), axis=1)
# then look up return based on year, ticker_closest_tot_assets

Comment: Hey! Thanks for your code, unfortunately it doesn't really do the job as it only creates a column with 'None' variables :P
Comment: Sorry - should've been ```last_year.columns.get_loc``` instead of ```last_year.get_loc```.


Can you have a nontrivial automorphism of an elliptic curve $E/S$ which when restricted to a geometric fiber is the identity?

Question: Ie, let $E/S$ be an elliptic curve over some scheme $S$. Is it possible to have an automorphism $\alpha$ of $E$ over $S$ such that for some geometric point $s\in S$ its pullback to $E_s$ is the identity?
Answer: Obviously, the answer is yes if $S$ is not connected.
If $S$ is connected, the answer is NO because Grothedieck's Rigidity Lemma (GRL) implies that
$$
\text{End}_S(E)\longrightarrow\text{End}_s(E)
$$
is injective for every geometric point $s\in S$. Unfortunately, I could find no link to a GRL page. The reference I know is to the book of Mumford, Fogarty and Kirwan on Geometric Invariant Theory (Proposition 6.1 there)


Is there a "quickload" function in Eschalon: Book I?

Question: Eschalon: Book I has a "quicksave" function (bound to F2), but is there a "quickload"?
Answer: Sadly no, but if you're playing on Windows you can use Autohotkey. Here's an example script that binds Control+L to "quickload", assuming you're playing fullscreen 800x600:
<code>#NoEnv
^l::
Send {Esc}
MouseMove, 500, 370
Sleep, 200
Click
MouseMove, 500, 250
Sleep, 200
Click
</code>


How to convert integer to string and get length of string

Question: In my database there is a field last_id of type integer. The table contains several rows. Let's say the maximum value of last_id is 104050. Now I want to know the length of this integer.
As this is not possible I am trying to convert it into a string.
SELECT to_char(MAX(last_id),'99') FROM xxxx

I would expect this to yield 10 with type = text, but instead it returns ## type = text.
Afterwards I would use SELECT char_length(to_char(MAX(last_id),'99')) FROM xxx which should return 2 ...
What is going wrong here?
Comment: Why would you accept rjhdby's answer? Mine is shorter, better, earlier and actually correct.
Comment: The reason is the "fill mode" of the `to_char()` function. Using `to_char(last_id, 'FM99')` would probably solve your problem.
Comment: @ErwinBrandstetter you're right, I have fixed this now as it helped solve my problem first place
Answer: Cast the integer value to text:
SELECT length(max(last_id)::text) FROM xxx;

Comment: @user3387124 Sure, pad right or left? But ask a *new question* please. This one was about finding out the length of an integer in text representation.
Comment: Great, that works perfectly. AS a next step I would like to to do the following: Add spaces to the field last_id so that the length of that field is 10 instead of 6. So if it only has a length of 5 I want to add 5 spaces to it, if it is 4 I want to add 6. Is that possible?
Answer: Since you are dealing with integers you can actually find the length of the number (or number of digits in the number) directly. Mathematically, the number of digits in an integer is one more than the floor of the log base 10 of the number.
You could use the following to find the length directly:
SELECT FLOOR(LOG(MAX(last_id))) + 1 FROM xxxx

Comment: Needless to say, this only works with positive integers.  Since in most systems, an id would be a positive integer, this wouldn't be a great limitation.  SELECT FLOOR(LOG(MAX(abs(last_id) ))) + 1 FROM xxxx should always work for the numeric part, though one might  want to add logic to increase the answer (in character-count) for negative numbers.  Example:   for -1000, as is, the formula I have in this comment would give 4 instead of 5, so the string conversion in others  answers would handle this case better.
Answer: Don't work with postgresql, but after documentation read... Somthign like this.
SELECT character_length(cast(last_id as varchar(20))) from table


How do I get android NDK detail crash reports?

Question: I am debugging a huge NDK project in Android Studio, the app crashes at semingly random times with message similar to
A/libc: Fatal Signal 11 (SIGSEGV), code 1, fault addr 0x30 in fid 22993 (Thread-99505)

The numbers are different at times but the error is similar, and sometimes the Run tab in Android studio doesn't even show any error at all and the program just crashes with the message Application terminated
By looking around I have found that android should generate some kind of crash log similar to ones shown here
https://source.android.com/devices/tech/debug/native-crash
But I do not understand how to get them, or whether there is some setting in Android Studio that allows me to view them
How do I get crash reports like these from Android Studio?
Android Studio version 3.0.1 in Apple macbook
Answer: Instead of the Run tab, look at the Logcat. Don't set the filter to your app only. There is a good chance that you will see a stack trace, like
I/DEBUG   (   31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
I/DEBUG   (   31): Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF91/43546:eng/test-keys'
I/DEBUG   (   31): pid: 351, tid: 351  >>> /data/local/ndk-tests/crasher <<<
I/DEBUG   (   31): signal 11 (SIGSEGV), fault addr 0d9f00d8
I/DEBUG   (   31):  r0 0000af88  r1 0000a008  r2 baadf00d  r3 0d9f00d8
I/DEBUG   (   31):  r4 00000004  r5 0000a008  r6 0000af88  r7 00013c44
I/DEBUG   (   31):  r8 00000000  r9 00000000  10 00000000  fp 00000000
I/DEBUG   (   31):  ip 0000959c  sp be956cc8  lr 00008403  pc 0000841e  cpsr 60000030
I/DEBUG   (   31):          #00  pc 0000841e  /data/local/ndk-tests/crasher
I/DEBUG   (   31):          #01  pc 000083fe  /data/local/ndk-tests/crasher
I/DEBUG   (   31):          #02  pc 000083f6  /data/local/ndk-tests/crasher
I/DEBUG   (   31):          #03  pc 000191ac  /system/lib/libc.so
I/DEBUG   (   31):          #04  pc 000083ea  /data/local/ndk-tests/crasher
I/DEBUG   (   31):          #05  pc 00008458  /data/local/ndk-tests/crasher
I/DEBUG   (   31):          #06  pc 0000d362  /system/lib/libc.so
I/DEBUG   (   31):

Android NDK includes a command ndk-stack that can help match the addresses with actual source files of your code, which is based on the addr2line utility in NDK toolchain.
Further instructions for understanding the stack trace: https://developer.android.com/studio/debug/stacktraces
From comments:
You may find the 'unstripped' libraries under app/build/intermediates/transforms/mergeJniLibs
Comment: You may find the 'unstripped' libraries under `app/build/intermediates/transforms/mergeJniLibs`
Comment: Hi I managed to view log messages similar to the ones you posted here after I removed all filters, and they come after the application crash message as expected. I am trying to use the ndk-stack tool now, and the page you linked to talks about $PROJECT_PATH/obj... .What is $PROJECT_PATH? I assumed it was where I made my android project (the folder that contains the app folder, build.gradle, project_name.iml, etc) , but the "obj" folder is not there. Do I need to do something to make this obj folder myself or is android studio supposed to make it?
Comment: @user13267 It might depend on your project structure, but in my projects the obj folder is typically located in app/src/main.
Comment: it's not there in my project folder. Do I need to enable some settings in android studio to get this folder created?


The relationship between $\alpha^i\otimes \alpha^j$ and $v^iw^j$

Question: In the book An introduction to manifolds by Tu, Loring W, there's an exercise:

Let $e_{1}, \ldots, e_{n}$ be a basis for a vector space $V$ and let $\alpha^{1}, \ldots, \alpha^{n}$ be its dual basis in $V^{\vee}$. Suppose $\left[g_{i j}\right] \in \mathbb{R}^{n \times n}$ is an $n \times n$ matrix. Define a bilinear function $f: V \times V \rightarrow \mathbb{R}$ by
$$
f(v, w)=\sum_{1 \leq i, j \leq n} g_{i j} v^{i} w^{j}
$$
for $v=\sum v^{i} e_{i}$ and $w=\sum w^{j} e_{j}$ in $V$. Describe $f$ in terms of the tensor products of $\alpha^{i}$ and $\alpha^{j}$, $1 \leq i, j \leq n$

And the answer says
$$
f=\sum g_{ij}\alpha^i\otimes \alpha^j
$$
I am getting confused about these notations. What is the relationship between $\alpha ^i \otimes \alpha ^j$ and $v^i w^j$? Is  $\alpha ^i \otimes \alpha ^j$ equal to $v^i w^j$? Hope someone could help me with clarifying these notations.
Answer: For two linear functions $\gamma_1,\gamma_2 : V \to \mathbb R$ we define the bilinear map $\gamma_1 \otimes \gamma_2 : V \times V \to \mathbb R$ such that $(\gamma_1 \otimes \gamma_2)(v,w) = \gamma_1(v)\gamma_2(w)$. So, for any $(v,w) \in V \times V$ we have
$$f(v,w) = \sum_{1 \leq i, j \leq n} g_{ij} v^{i} w^{j} = \sum_{1 \leq i, j \leq n} g_{ij} (\alpha^i \otimes \alpha^j)(v,w) = \bigg( \sum_{1 \leq i, j \leq n} g_{ij} \alpha^i \otimes \alpha^j \bigg)(v,w)$$ and then $$f = \sum_{1 \leq i, j \leq n} g_{ij} \alpha^i \otimes \alpha^j.$$
Comment: I see. Thanks a lot!


How to display/mask part of an Image without scaling - QtQuick/QML

Question: I'm trying to make a simple audio meter with QtQuick. The meter graphic comes from a PNG file, and when the level changes, I want to change the height of the displayed part of the image, without scaling it at all. I simply want to mask some of the image off without changing it.
I have tried the following code:
import QtQuick 2.0

Rectangle {
    width: 360
    height: 482
    Image {
        x: 165
        source: "meter.png"
        fillMode: Image.Pad
        anchors.bottom: parent.bottom
        height: 482
    }
    Image {
        x: 175
        source: "meter.png"
        fillMode: Image.Pad
        anchors.bottom: parent.bottom
        height: 440
    }
    Image {
        x: 185
        source: "meter.png"
        fillMode: Image.Pad
        anchors.bottom: parent.bottom
        height: 400
    }
}

But this gives the following undesried results, with some kind of scaling happening. I want where the yellow and green meet in all 3 images to be identical.
Answer: The Image component fills from top to bottom by default, but instead of wrapping Image in an outer Item, and using clip which is bad for performance, just add to all your Image items :
width: sourceSize.width; // to be sure the width is the exact same as the source
verticalAlignment: Image.AlignBottom; // to force image to start from the bottom

So the content will not be scaled and aligned to the bottom of your Image.
Answer: The Image Item fills its content top-down, so if you want to anchor it to the bottom you will need an additional container Item to clip out the Image's top portion:
Item {
  x: 165
  width: childrenRect.width
  height: 482

  clip: true  // This is the key

  Image {
      source: "meter.png"
      anchors.bottom: parent.bottom
  }
}

Comment: I consider this not to be the best answer possible :
- childrenRect is not fast, and clip drops down drawing perf too
- it adds a needless nesting level in the code

Take a look at my answer for the minimal code for this ;-)
Comment: I do agree. Didn't know about that `verticalAlignment` property applied to an `Image` Item.


Rendering .Net controls through Handler for Ajax

Question: I have an ASP.Net application that has a UserControl that needs to be rendered on an ASPX page (as normal), but also via Ajax using a Handler.
One solution to this is to get the UserControl to simply build up a HTML string, rather than rendering controls as it would normally.
That way, the ASPX page can simply populate a Literal control with the output, while the Handler can write the output to the Response object for Ajax to pick up.
Is this the ideal solution? are there any drawbacks of this approach?
Answer: If you do that, you have to recreate the user control every time from the client-side when a postback to the server happens.  However, performance wise, that may be better.  However, I don't think the UC can then participate with viewstate and the ASP.NET object model as a typical user control would.  You would have to account that all actions within the UC are handled appropriately, to react to the web.
If you have a large amount of content to render, the UC approach is just fine.  We're talking rendering markup and injecting it into the UI, and so that does pan out and can make it easier.  If it's not that much markup, any alternative would do.
If all you need to do is push data to the client, an alternative could be that you push JSON to the client through a web service, and build the UI on the client.  That's efficient too.
HTH.
Comment: Thanks - my thoughts too.  Looking at a JSON option for the Ajax part, though it probably won't offer a huge difference in download size, because most of the HTML is database-drawn anyway.
Comment: In that case,I agree, direct JSON transfer isn't going to be a huge savings.  But it still may be a good alternative.
Answer: There are a number of JS templating tools available now that will solve this problem.  Take a look at mustache js, which can allow the same template to be rendered in client side JS and in C#.Net.
You can then create on template file and either render the HTML in JS via Ajax or render in .Net and simply output during page load.


Properties of adjoints of linear maps

Question: I am studying linear algebra by myself, and I came across the need to prove the following, for adjoints of linear maps:
($f^\dagger)^\dagger=f$
$(f\circ g)^\dagger=g^\dagger\circ f^\dagger$
$\langle v|fw\rangle=\langle f^\dagger v|w\rangle$
Thank you very much!
Comment: The third is usually the *definition* of the adjoint. What is your definition?
Comment: Do you know the definition of the adjoint? I strongly recommend that you do these yourself, because they're very easy. If you still can't do them, tell us what you have tried.
Comment: Thank you. Off course, the first 2 are obvious if I accept the third. But if I don't, I don't know where to start.
Answer: Meanwhile this was asked on MO and has an accepted answer: https://mathoverflow.net/questions/110739/

Properties of adjoints of linear maps


I am trying to display specific data by passing a parameter to a fetch call

Question: I have a component that is a select box, i added an onChange to the select box to "capture" its data and set it to a variable in state. I then try to pass it as props to another component [i.e the "display component"] then i use this.props at the end of a new fetch call in the display component to display the data.........it doesn't work. Please Help.
class Test extends Component {
  constructor(props) {
    super(props)
    this.state = {
        routes: [],
        vessel: ''
    }
    this.makeChange = this.makeChange.bind(this)
  }

  componentDidMount() {

    fetch(`http://localhost:5000/routes`)
        .then(res => res.json())
        .then(data => this.setState({
            routes: data
        }))
  }

makeChange(event) {
    this.setState({
        vessel: event.target.value
    })
}
render() {

    let { routes } = this.state
    return (
        <>
            <select onChange={this.makeChange}>
                <option>Select A Vessel</option>
                {routes.map(vessel => {
                    return (
                        <option key={uuidv4()}>{vessel.vessel}</option>
                    )
                })}
            </select>

            <VRoute vessel={this.state.vessel} />
        </>
    )
}

}
}
-----------------------DISPLAY COMPONENT BELOW-------------------------------
class VRoute extends Component {
  constructor(props) {
    super(props)
    this.state = {
        routes: [],
    }
}

componentDidMount() {

    fetch(`http://localhost:5000/routes/${this.props.vessel}`)
        .then(res => res.json())
        .then(data => this.setState({
            routes: data
        }))
}

render() {
    let { routes } = this.state;
    return (

                        {routes.map(value => {
                            return (

                                    {value.departure_port}
                                    {value.arrival_port}
                                    {value.departure_time}
                                    {value.arrival_time}
                                    {value.date_stamp}
                                    {value.price}
                                    <button className='delete-btn'>x</button>

                            )
                        })}

Comment: Should `{vessel.vessel}` not be `{vessel.vessel}`?
Comment: When Vroute is mounted the user still not select anything and then when select changes, display component will not fire CDM because is already mounted. To fix this change it to ComponentWillUpdate
Comment: Each child in a list should have a unique "key" prop..... hence "key" in option
Answer: Try this:
<select onChange={this.makeChange}>
                <option>Select A Vessel</option>
                {routes.map(vessel => {
                    return (
                        <option key={uuidv4()} value={vessel.vessel}>{vessel.vessel}</option>
                    )
                })}
            </select>
            <VRoute vessel={this.state.vessel} />
        </>

Display component..
componentWillUpdate(nextProps) {
  if (nextProps.vessel !== this.state.vessel) {
    this.setState({vessel: nextProps.vessel}, () => {
      fetch(`http://localhost:5000/routes/${this.state.vessel}`)
        .then(res => res.json())
        .then(data => this.setState({
           routes: data
        }))
    })
  }
}

Comment: Thanks Adolfo, this does work but it's returning empty arrays, i think it's something with the database...not sure
Comment: Do .then(data => { console.log(data) this.setState({ routes: data }) }. You should see in console the data received from database and check if it's correct.


Moving surfaceView (with camera preview) to the left of the screen

Question: I'm currently developing an Android application that uses the device camera for both taking photos and recording videos. This application must work on API level >= 8  (Froyo).
Until now, I have implemented the camera code based on Android samples. It can be found in <ADT folder>/sdk/samples/<android_version>/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.java - I'm following the "android 11" example to switch between cameras and "android 8" for the rest. This means that my camera preview is held by a SurfaceView which is contained in a ViewGroup (CameraPreview class) which is in turn attached as the content view in the main activity.
The problem is that I don't want the camera preview to be shown as Android does. I mean: I want the preview to fit one of the screen dimensions and overflow the other. Android samples fit one of the screen dimensions and keep the other inside the screen boundaries.
For example: let's take an Android device whose screen dimensions are 480x800. We select a preview size of 480x640. Android would keep this preview size as it fits within the device's screen: it would exactly fit the screen width, while it would show two black rectangles up and down (letterbox). In my case, I'd upscale that preview by 1.25, so as to resize it to 600x800 (that is, making the longest side of both the preview and the camera 800 long). Then I try to center this preview by moving that preview surface (surfaceView) slightly to the left. In this case, the leftmost horizontal coordinate would be -60 and topmost 0.
My problem is that I'm not able to correctly move the SurfaceView. It is correctly resized but I cannot move it to the left (out of the screen). Searching on SO, I've found lots of possible solutions but none worked for me. I'm sure that this shouldn't be so difficult and I must be doing something wrong.
Until now, I've tried some solutions such as:

Following the Android example , I changed it's resizing code - onMeasure function - to:

if (width * previewHeight < height * previewWidth) {

    final int scaledChildWidth = previewWidth * height / previewHeight;

    child.layout( (width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height);

} else {

    final int scaledChildHeight = previewHeight * width / previewWidth;

    child.layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2);

}

This correctly resizes the preview to the dimensions I look for but, although leftmost coordinate is supposed to be -60, it continues to be rendered from the upper left corner of the screen. I'm just pasting here the change in onMeasure function as it the rest of the code is the same as the one in the Android sample folder I said before.

Changing the parent container of the SurfaceView into a ScrollView and scrolling the preview.
Using negative margins or paddings with ViewGroup/RelativeLayout/FrameLayout/LinearLayout/etc. In this case, I was able to move some interface elements (other button I added to the layout) but not the SurfaceView.
Trying to set clipChildren and clipToPadding to false.
Trying to play with centerInParent option.
Creating a new parent layout whose size is the same as that of the SurfaceView (scaled preview size) and centering it. It also resizes correctly but doesn't center on the screen.
Using AbsoluteLayout (yes, I know it's deprecated ;)  )

I can't remember now other solutions I tried, but I think these are the main ones.
It seems that I could not prevent elements from starting at the upper left corner of the screen.
Of course, any further details needed can be requested and I'll try to answer ASAP. I got really stuck at this point and I'd be very grateful for any help provided. Thanks to all for spending time on reading this :)
Edit 1
I am testing this application in Android 2.3.6.
Comment: Have you tried [Fitting a Camera Preview to a SurfaceView larger than the display](http://stackoverflow.com/questions/11321251/fitting-a-camera-preview-to-a-surfaceview-larger-than-the-display)?
Comment: Hi Alex. Yes, I have tried that solution. Now I have that code implemented (the solution one). Coordinates passed to `child.layout(...)` call are correct. For example, the initial x value is -60, but `SurfaceView` doesn't resize to that coordinates. It's still limited by screen boundaries.
Comment: Anyone more with the same issue? :-)
Answer: Answer after a long time, but I spent lot of time figuring this out.
The SurfaceView on some android devices (see below) just cannot extend beyond the display boundaries. If it does, it shifted and centered, if it's too big to fit. If the chosen resolution does not match your display size, you either have to add padding or stretch the image. That's a fact.
Secondly, be sure to choose a picture size with the same aspect ratio as your preview size, or you will not get the exactly same viewport in the picture as you saw in preview. This might not matter in your case, if the difference is not big, but it does in mine.
Note on some devices: I experienced this behavior on my old HTC Desire S (with Android 2.3). It works as expected with Samsung S5 with Android 5.1. I will be glad if someone improves the answer with information what is this related to (android version, or just some models...).