assembly heap...trying to study for a test

Question: I have an exam coming up where we have to study heaps and stacks. The stacks part I understand, but the heap is giving me trouble.
Our book gives us both in C and in Assembly. But I am having difficulty understanding both of these concepts.
I will just put up a screenshot of the book so it looks nicer.
Questions:

How does Heap_Init work?
How does Heap_Allocate work?
How does Heap_Release work?

Thank you all for your time and effort.
Comment: -1. Sorry, you need to show some good effort and ask specific questions related to the problems you're facing.
Answer: The heap in this sense of the word is an area of memory not on the stack which the program can use to store larger amounts of data.
However, during the lifetime of the program, that program must track its own memory usage. Specifically, the program cannot write to its entire virtual address space on a whim; if the address to which it tries to write is not mapped by the operating system that will trigger an access violation, which will result in your program receiving a segmentation fault and being terminated.
So, the program being run must ask the operating system to allocate some space. If it can, the operating system will do this, and will map that space into the virtual address space.
However, if you need to release a portion of the memory, you need to know where it is and what you are doing with it. Also, you need to know, as the program given a particular size of memory where to store it. See, things get complicated very quickly - if you're doing a lot of memory allocating from say C, and then frequently freeing again, it doesn't make sense to have a 1-1 map between allocations and frees and system calls to the same effect. Instead, it would be better if the memory allocator just pulled  a bigish chunk of memory from the operating system and then kept track of that.
Enter the need for a storage structure to track what of the allocated space is currently in use, and what ranges in the virtual address space are marked out for use.
So,

Heap_Init sets up this structure and probably, in any modern allocator, initialises some memory.
Heap_Allocate uses this structure and returns a pointer to a free space when given a request. This might, or might not, require the program to request more space from the OS.
Heap_Free uses the structure to free memory previously allocated.

That's the theory of what these functions will do. If you look at the code, you should be able to work out what your specific implementation is doing.
Comment: Thank youuuuuuu... Can I ask you for a small favor? If you can edit your answer with a line by line explanation of Heap_Init (which is only like 10 lines) it would great cuz I am totally confused on what it is trying to do.
Comment: @bluejamesbond I could - but that'd kinda spoil the point of your learning exercise, wouldn't it? ;)
Comment: It really isn't an excercise. It is just studying for a test. I dont want to send an email to prof just yet without trying to learn.
Comment: To be more specific. it is the pshx and puly that I am confused about in Heap_iniT
Comment: @bluejamesbond they translate to push x and pull y (from the stack).
Comment: so its just switching contents of RegX and RegY?


is there a trick or a function to insert elements in a php string?

Question: I want to modify the syntax of a SQL query dynamically
eg:
<code>$var = SELECT * FROM schools WHERE teacher = 1 OR teacher = 2 AND student = 1 OR student = 2 OR student = 3 AND classroomId = 12
</code>
So in the above example I want to group the OR in a parenthesis otherwise the query results will not be correct.
I want to dynamically transform via a function or script that query to this:
<code>$var = SELECT * FROM schools WHERE (teacher = 1 OR teacher = 2 ) AND (student = 1 OR student = 2 OR student = 3) AND classroomId = 12
</code>
is it possible ?
Comment: What are you trying to do?
Comment: Don't forget your quotes around the value of var: `$var = "..."`
Comment: I want to modify the content of  a variable once there's OR condition
Answer: You can do it something so
<code>$arr = array (
   "teacher" => array(1,2),
   "student" => array(1,2,3),
   "classroomId" => array(1)
   );

function mylist ($array) {
    foreach ($array as $name => $arr) {
      foreach ($arr as &$item)
        $item = $name . '=' . $item;
      $or[] =  '(' . implode(' OR ', $arr) . ')';
    }
    return implode(' AND ', $or);
}

echo 'SELECT * FROM schools WHERE '. mylist($arr);
</code>
resuде
<code>SELECT * FROM schools WHERE (teacher=1 OR teacher=2) AND (student=1 OR student=2 OR student=3) AND (classroomId=1)
</code>


Is there a way to sprite raster images within an SVG element?

Question: I have the following SVG elements containing markers to be displayed on a map in a web page. The markers are composed of the <image> elements referencing to various small PNG images:
<svg id="OL_105_svgRoot" width="1246" height="373" viewBox="0 0 1246 373">
 <g id="OL_105_root" style="visibility: visible;" transform="">
  <g id="OL_vroot">
   <image id="P115" cx="843" cy="203" r="1" x="827" y="188" width="32" height="32" href="spider.png" ...>
   <image id="P119" cx="453" cy="269" r="1" x="437" y="254" width="32" height="32" href="zoo.png" ...>
   <image id="P123" cx="628" cy="82" r="1" x="612" y="67" width="32" height="32" href="wild.png" ...>
   <image id="P131" cx="10495" cy="69" r="1" x="1034" y="53" width="32" height="32" href="export.png" ...>
...
  </g>
 </g>
</svg>

Is there any way I can replace those images with a single large image file and use something similar to CSS background-position property to specify the viewing window for each image?
Answer: Wrapping the <image> elements into inner <svg> elements, specifying a certain width and height on the <svg> element and the "background-position" on the <image> element using the x and y attributes might be a solution:
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
  <svg width="17" height="19">
    <image xlink:href="http://s14.postimage.org/f66u116ap/rainbow_Hello_World4.png" width="188" height="19"/>
  </svg>
  <svg width="17" height="19" x="12" y="19">
    <image xlink:href="http://s14.postimage.org/f66u116ap/rainbow_Hello_World4.png" width="188" height="19" x="-17"/>
  </svg>
  <svg width="17" height="19" x="35" y="6">
    <image xlink:href="http://s14.postimage.org/f66u116ap/rainbow_Hello_World4.png" width="188" height="19" x="-34"/>
  </svg>
  <svg width="17" height="19" x="46" y="14">
    <image xlink:href="http://s14.postimage.org/f66u116ap/rainbow_Hello_World4.png" width="188" height="19" x="-51"/>
  </svg>
  <svg width="17" height="19" x="60" y="24">
    <image xlink:href="http://s14.postimage.org/f66u116ap/rainbow_Hello_World4.png" width="188" height="19" x="-68"/>
  </svg>
</svg>

(See a test on Tinkerbin.)
You could also use the clip-path attribute, but I guess this is even more tedious than the above solution.
Comment: I can't change the document structure as the `` elements are automatically generated by the map API. Could this be done by altering the attributes of the image elements?
Comment: Yes, it could be done using the `clip-path` attribute, but I'm very sorry I can't elaborate more about this right now.
Comment: Thanks so much for this! This can also be used for sprite animations: http://jsfiddle.net/syyvp700/


What areas of 1st floor sheetrock sould be replaced subsequnet to a major 2nd floor water leak?

Question: In our apartment, the ceiling began leaking in 2 places. One of the places, the water was brownish and had multiple droplets, the other the water was clear. We called maintenance at 8 am and no one showed. As time went, the leak went from 2 spots to 6 places in the ceiling, water also began running down the wall in 4 places and began pooling around the toilet, about 1 inch. At some point the paint on the wall fell away and water began running like a faucet.
Finally at 4pm maintenance shows and cuts 2 large holes in the ceiling. 30 mins later, he was done and said they would come replace only the places where he cut away. My concern is that they didn't cut into the wall, where we have heard water running in the past, but was told that it was just the pipes. If that much water was running and pooling in the walls, shouldn't the wall and whole ceiling be replaced ? What about mold? They left no dryers and said they would be back in 2 days to close everything up.
What should I do? Should the floor be replaced too since the water was pooled for so long?
Comment: This is a potential health hazard,brown water cannot be a good sign,
in a communal setting/apt complex,you could be getting everybody's waste in your flooring and carpeting!This requires removing the sheetrock and carpeting,the flooring is likely wet under whatever is on it now, this is a big deal and is not being addressed correctly,
call the emergency # for your complex and get a Motel6 and keep the receipt.It will take days to rectify this condition properly.
Comment: This is what scares me most in my house. Very bad situation :/
Answer: To answer the specific question, you should replace any sheetrock that has mold.  A one-time leak for a day won't cause this -- significant mold arrives when an organic material stays wet for an extended period of time (weeks or more, usually) so you should make sure it's dry before it's repaired.
The bigger problem is what is being covered up.  You need to know what was the cause of the leak and be convinced that it has been corrected properly.  You need to check what you can see for any blackness (i.e. mold).  If you find more than a couple dots, then there are moisture problems beyond this one major leak and the ceiling and walls need to be removed until the full extent of the problem is known and removed.  Don't do this yourself!  Contact a professional remediation company.
Same for the floor.  A one-time thing, even this big, won't cause mold as long as it is fully cleaned up and allowed to dry out completely.  This can be difficult if the water has gotten beneath the surface as it certainly will with carpet, hardwood, etc.; you may have to remove everything down to the subfloor, let it dry, and re-install.
The brown water is a concern.  If it was waste water, then you may have a health hazard and you'll need an environmental assessment.
I understand that this is not property you own, which makes getting this done difficult.  I suggest you do what investigation you can, consult with an unbiased professional, and talk politely with the landlord about your concerns.  If you're not satisfied with the answer, you can take your concerns to the government (mold and waste water are health hazards) and find a new place to live.


Some questions in STL map and list using in c++

Question: Hello I would like to ask about:
I have map and list
Questions:
Is the following implementation of distructor right :
   for (map<string,SymbolTableNode*>::iterator i = symbolTable.begin();
                         i != symbolTable.end(); ++i)
   {
       delete i;
   }
   symbolTable.clear();

or I miss some memory?
About list:
   list<MyClass2*> mylist;
   mylist.push_front(new MyClass());
   mylist.pop_front();

does pop invoke delete? or I have memory leakage in this case? If there is the leakage problem then what can I do to avoid it?
Thank you.
Comment: I think you should delete value of iterator i, not itself.
Comment: Thank you very much Andreas and all others it helped me a lot
Answer: No pop_front won't invoke delete. You'll have to delete the pointer yourself before you pop it.:
list<MyClass2*> mylist;
mylist.push_front(new MyClass());
delete mylist.front();
mylist.pop_front();

And the destructor should probably be:
delete i->second;

Answer: you have a leak. See smart pointers (http://en.wikipedia.org/wiki/Smart_pointer)
More explicitely:
list<boost::shared_ptr<MyClass2> > mylist;

mylist.pop(); // now it will invoke delete

Answer: Do you really need to have a list of pointers ? Can't you have a plain list ?
list<MyClass> mylist;
mylist.push_front(MyClass());

It will save you the pain of memory management.
If you need pointers, then use smart pointers or pointer containers from boost : http://www.boost.org/doc/libs/1_46_1/libs/ptr_container/doc/ptr_container.html
Comment: Yes I need pointers because i would like to change the elements in the list
Comment: That has nothing to do, you can change objects that are in the list. You can do my_list.back().value = 42;
Comment: Tried it it works it means that my_list.back() returns reference to value , and I thought that if it holds the element by value then it returns it the same way.
Answer: delete i;

Wrong.
This should be this:
delete i->second;

Because i points to a pair.
Comment: Also, because `i` is not a pointer, but an iterator (so `delete i` shouldn't even compile).
Answer: Nawaz - You are wrong.
Iterator element for a map is a pair so proper delete call is:
delete (*i).second;

P.S.
Ok - now I see You have fixed this :)
Comment: what's the difference between (i*).second and i->second when i is an iterator on the map ?
Comment: -1 for saying that `delete i->second` doesn't do what `delete (*i).second` does and for not knowing that they're exactly same!
Comment: Same code generated for STL pair, but worth mentioning is that the -> operator can be overloaded in C++ (though the . cannot) so there could be a difference for other classes.
Comment: Nawaz! I wrote, that You were wrong in Your FIRST answer.
Look at my "P.S" added later.


how to create animation of sparkling effect for iphone using cocos2d or Quartz core

Question: I am creating one application in that i want to give background effect like there are number of starts and something like we are in universe and some starts are getting lighted for few seconds then some other starts etc.
I got one open gles animation of Explosion , but I want that kind of effect using quartz core or Cocos2d so that I can implement other things easily.
if any one do have any idea or any sample for the sample please suggest me.
Thanks in advance
Answer: If I understand you question correctly (that is not quite clear) you can use some particle effect to simulate most of the "cosmic" lighting, starts, comets even galaxy.
Answer: Please have a look at http://www.cocos2d-iphone.org/archives/926 , it is particle tutorial


Is there any way to buy Dive items from the normal shops?

Question: I know you get Dive's and Mr. Gency Exit's from beating bosses every 10 floors and they are available in the Item Worlder's shop in her Mystery Room but is there any point where you will be able to purchase them straight from the Pocket Netherworld Shops?
Answer: You cannot purchase either of the items from the Pocket Netherworld Shops, but they can be made through the Alchemist Shop in PostGame.
Pocket Netherworld Shops are really just meant to be the bare minimum items.  In this case, you have to beat the game first to be able to make them, and then each item (up to 3) will progress depending on how many stages/floors you clear.
Edit: Changed the post to include more information, without all the extra information.
Comment: Yea that makes sense. I figured if at all they would be the VERY last thing added to the shops anyway. I had just never gotten far enough to check
Comment: Yeah, the Diver items are new, but it makes sense considering skipping floors no longer gives levels and you can go past floor 100.


Prove that a group of infinite order must have a proper subgroup

Question: Assume that the group of infinite order is also cylic. How would one prove that? I am quite stuck.
Comment: If it is cyclic and generated by $x$, consider $x^2$.
Comment: Possible duplicate of [An infinite cyclic group has a unique subgroup of index $m$ for any integer $m \geq 1$.](http://math.stackexchange.com/questions/292131/an-infinite-cyclic-group-has-a-unique-subgroup-of-index-m-for-any-integer-m)
Comment: Note that any cyclic group of infinite order is actually isomorphic to $\mathbb{Z}$, which is known to have proper subgroups.
Comment: The title and the question are quite different. Which one do you mean? Besides, the group generated by 1 is always a subgroup of any group, so...
Answer: Take any $x\in G$.
If $|x|<\infty$, then $x$ generates a finite subgroup $\langle x\rangle$. Since $G$ is infinite, the subgroup generated by $x$ is proper.
If $|x|=\infty$, then $\langle x\rangle \cong \mathbb{Z}$. Take any proper subgroup of $\mathbb{Z}$ and use the isomorphism. For $n\geq 2$, $\langle x^n\rangle$ will be a proper subgroup of $\langle x\rangle$, and of $G$.


Galois group and the fixed field of $L(\sqrt[6]{2})|L$ for $L=\mathbb{Q}(e^{2πi/3} )$

Question: I have my Algebra I exam coming up soon and I want to make sure I have understood the concepts well. I would therefore like you to check my answer to the following exercise:
Let $L = \mathbb{Q}(e^{2πi/3} )$ be an extension of $K=\mathbb{Q}$.
(a) Calculate the Galois group $G = Gal(L, K)$ and the fixed field $L^G$$. Is the extension Galois?
(b) Calculate the Galois group and the fixed field of $L(\sqrt[6]{2})|L$. Is it Galois?
For a) we have that the minimal polynomial of $e^{2πi/3}$ is the third cyclotomic polynomial $f(x)=x^2+x+1$. Since we have a field extension over $ \mathbb{Q}$ and $ \mathbb{Q}$ has $char( \mathbb{Q})=0$ the field extension is separable.
Since the two roots of $f$ are $ \xi=e^{2πi/3}$ and $\xi^2 \in L$ we have a normal field extension. Since the field extension is normal and separable we have a galois field extension.
We have only $2$ Automorphisms, namely: $\phi_1: \xi \rightarrow \xi$ and $\phi_2: \xi \rightarrow \xi^2$.
Since $\phi_2^2=\phi_1$ $Gal(L/K)\simeq \mathbb{Z}_2$
I don't know a direct method to find the fixed fields (so if you have one let me know), but going according to the definition $L^G=\{ a \in L| \forall g \in G, g(a)=a \}$ we have only $\mathbb{Q}=L^G$, right?
For the second problem b) I have some difficulty finding the minimal polynomial over $L$. Can someone help me?
Comment: @JyrkiLahtonen: I interpreted the second problem as being similar to first one so that what we need is the group $G$ of automorphisms of $L(\sqrt[6]{2})$ which fix $L$ (a proper notation should be like $G=\text{Aut} (L(\sqrt[6]{2}),L)$) and then finding the fixed field $L(\sqrt[6]{2})^G$. But yes it would be nice if this is explicitly mentioned in the question.
Comment: Why not $x^6-2$?
Comment: But is it the minimal polynomial over $L$? @GerryMyerson
Comment: Eisenstein over $L$?
Comment: What is the meaning of *the fixed field of $L(\root6\of2)/L$?* In this context I am only aware of the fixed field of *a group of automorphisms*??
Comment: That makes sense @ParamanandSingh
Answer: Let us observe that if $K$ is of characteristic $0$ then any extension $L/K$ is separable and hence we only need to check normality of the extensions. However a much simpler approach to verify whether an extension is Galois is to show that $L$ is a splitting field of some non-constant polynomial $f(x) \in K[x] $. And further when the extension $L/K$ is Galois then the fixed field $L^{G} =K$ where $G=\text{Gal} (L, K) $. Another ingredient which helps a bit in finding Galois groups is that the order of Galois group $G$ is same as the degree of extension ie $[L:K] $ if the extension is Galois.
With these ideas in mind one can handle the first problem easily by noting that $L$ is the splitting field of $f(x) =x^2+x+1\in K[x] $ and the extension is therefore Galois with the Galois group $G$ being of order $2$. Your solution presented in the question is fine. And since the extension is Galois the fixed field $L^G=K$.
Next for the second problem we need to deal with extension $L(a) /L$ where $a=\sqrt [6]{2}$. Another answer here gives us the degree of this extension $[L(a) :L] =6$. Now $a$ is a root of $g(x)=x^6-2\in L[x] $. The complete set of the roots of this polynomial is $$\pm a, \pm a\omega, \pm a\omega^2$$ where $\omega =e^{2\pi i/3}$. Since $\omega \in L$ it follows that $L(a) $ contains all roots of $g(x) $ and it is the smallest such field. Thus $L(a) $ is the splitting field of $g(x) $ over $L$ and the extension $L(a) /L$ is Galois and the order of the Galois group $H=\text{Gal}(L(a),L) $ is $6$ and the fixed field $L(a)^H=L$.
To find the Galois group we can observe that an automorphism $\sigma$ of $L(a) $ is entirely determined by its action on $a$ and further the image of $a$ ie $\sigma(a) $ must be a root of $g(x) $. So we clearly have two choices here and thus two obvious automorphisms $\sigma, \tau$ given by $$\sigma(a) =-a, \tau(a) =a\omega$$ and the group $H$ is generated by $ \sigma \tau$ and is the cyclic group of order $6 $.
Answer: Small disclaimer: This answer only deals with the minimal polynomial portion, it's more of a comment that couldn't quite fit.
Gerry mentions the Eisenstein criterion but you'd have to choose something other than $L$ itself since that's a field, which means it does not have any prime elements to check Eisenstein with.
Eisenstein could still work but only if you apply it to $\mathbb{Z}(e^{i2\pi/3})$ I'm fairly sure, at which point you'd probably have to know what prime elements look like in there... Though my algebra and Galois theory are a bit rusty so maybe someone will correct me on that.
Instead, here is a way to do it that only uses elementary properties of the degrees of field extensions.
Let me set $j := e^{i2\pi/3}$ (standard name for that number). We have:
$$\begin{cases}\left[\mathbb{Q}(j,\sqrt[6]{2}) : \mathbb{Q}\right] = \left[\mathbb{Q}(\sqrt[6]{2})(j) : \mathbb{Q}(\sqrt[6]{2})\right] \cdot \left[\mathbb{Q}(\sqrt[6]{2}) : \mathbb{Q}\right]\\ \left[\mathbb{Q}(j,\sqrt[6]{2}) : \mathbb{Q}\right] = \left[\mathbb{Q}(j)(\sqrt[6]{2}) : \mathbb{Q}(j)\right] \cdot \left[\mathbb{Q}(j) : \mathbb{Q}\right]\end{cases}$$
The degrees $\left[\mathbb{Q}(\sqrt[6]{2})(j) : \mathbb{Q}(\sqrt[6]{2})\right]$, $\left[\mathbb{Q}(\sqrt[6]{2}) : \mathbb{Q}\right]$ and $ \left[\mathbb{Q}(j) : \mathbb{Q}\right]$ are easy to calculate, since $j$ is a root of $X^2 + X + 1$ but doesn't belong to $\mathbb{R} \supset \mathbb{Q}(\sqrt[6]{2})$ and we can use Eisenstein on $\mathbb{Z}$ to get that $\sqrt[6]{2}$'s minimal polynomial over $\mathbb{Q}$ is $X^6 - 2$ of degree $6$. Hence:
$$\begin{cases}\left[\mathbb{Q}(j,\sqrt[6]{2}) : \mathbb{Q}\right] = 2 \cdot 6 = 12\\ 12 = \left[\mathbb{Q}(j)(\sqrt[6]{2}) : \mathbb{Q}(j)\right] \cdot 2\end{cases}$$
thus we obtain $\left[\mathbb{Q}(j)(\sqrt[6]{2}) : \mathbb{Q}(j)\right] = 6$, but $\sqrt[6]{2}$ is a root of $X^6 - 2 \in L[X]$ which is of degree $6$, therefore $X^6 - 2$ is the minimal polynomial of $\sqrt[6]{2}$ over $L$.
Comment: While I understand your argument, there are a few typos, particularly at some places you need to write $j$ instead of $\sqrt[6]{2}$. It would be best to use a symbol say $a=\sqrt [6]{2}$ instead of typing all those square roots.
Comment: @ParamanandSingh Thanks for pointing out that there were typos! I could have done what you suggested but it's not like it does much. (If you were worried about me typing it all out, I just copy-pasted it.)


iPhone App: Dynamic Height of UITextView and elements under it

Question: I have a view that has some labels in it with some info and textviews. I know a way to resize the textviews height that's not a problem.
I just want to know if there is some simple way to move down all elements that are under the resized textview. Of course if I don't move them down, part of the resized textview is hidden under elements under it.
I was hoping to find some property in the interface builder for position of each element like in css for websites, but couldn't find anything.
Thanks for any help :).
Answer: Did you try - (void)setNeedsLayout on the superview?
Comment: I'm noob in this iphone programming so no I didn't :), I'll check it out thanks!


Can my house support a bathroom addition?

Question: When I bought the house, it was a 4 bedroom, 1 bath rancher with basement laundry.  We have since "converted" the smallest of the 4 bedrooms to an upstairs laundry, and took the closet out to accomodate a larger master bath on the other side of the wall.
In the very near future, we would like to split the current laundry room into a second bathroom, with tub, and a small laundry space.  I am confident in doing all of the work DIY, but am unsure about the structural side of things.  My floor joists are 2x8 beams 16 inches on center.  What do I need to consider from a structural standpoint before proceeding with this plan?
Thanks in advance.
Comment: 2x8 is a small joist by modern standards but should still support a standard tub. What's the span?
Comment: Is the added weight your main concern?  Do you have other worries?  Can you add additional support in the basement?
Comment: It changes the load on the joists.  Instead of the 300 lb - 500 lb+ weight of a filled tub being carried by 4 or 5 joists, it will be carried by at most 3.  Understand the issues trying to put a full-size bath + laundry into a 12x12 area.  You should be able to calculate the total load on your joists carrying the tub.  Then go to a span table using 2x8 for your joist size and 15' for the span and see where your are.  I think the design standard is 40 lbs/sq ft.
Comment: Added weight is my main concern.  A tub full of water, with one or two kids in it has to be several hundred pounds at least lol.  The basement ceiling is entirely opened up from a current re-wire project, so I can do whatever needs done there fairly easily.
Comment: I think you're OK with your 2x8's, especially if the tub is going to sit across 4 joists (assuming the tub is 5 ft long).  But like isherwood said, need to know the span of the joists to make a better guess,
Comment: Do you have a septic system or municipal sewerage?
Comment: @mikes having more bathrooms does not correlate to  increased water usage as much as having more bedrooms does.
Comment: Consider adding some bridging and/ or blocking. Pretty easy to do and should help distribute the load to adjacent joists
Comment: Some local requirements do require increasing septic capacity with additional bathrooms. As this is a DIY project I asked so the prospect may be considered before construction starts.
Comment: I am on city sewage. I can measure the span this evening, but I'm going to say roughly 15 feet from the outside wall to the center beam running parallel with the front and back of the house.
Comment: @stevesh the way I had considered laying it out would actually have the tub running parallel with the joists, not across them. Does that change anything? I can rework the plan if necessary, just trying to shoehorn a full sized bathroom and a laundry space in a 12x12 room.
Answer: It should be fine as-is, after-all a bath full of water weighs about as much as a waterbed, and there are no special requirements for framing under bathrooms. (unless you want to lower the floor)
Answer: Structurally, in a word, you need to consider support. The joists alone will likely not be enough to support the added weight over time. They will start to sag. You may be able to get away with a single pillar support, and double up the spans. Or you may be able to put in two or even three supports in the area. It is hard to say without seeing the layout.
One way to consider it is this: how much weight will there be with both tubs full of water and the washer going? Doubtful that scenario would happen but it is what you need to plan for. Also, the floor under the washer needs to be very solid so that it doesn't vibrate a lot when it's running.
Comment: It really depends on span. Most homes from the 1950s to the 1980s had 2x8 or 2x10 joists, and they aren't all sway-backed. I'd consider 2x8s fine out to about 10 feet.
Comment: Also depends on the joist spacing.  Part of our house has 2x8 joists 12 foot span, but they are on 12" centres.  16" is more common.  I did one house with 4 foot span -- wanted the look for the main room below:  But I did the floor with 2" T&G pine.
Comment: over time?  most tubs spend 90% of the time empty.
Comment: @isherwood and crew, I was mistaken when I said 2x8s.  I just measured them and they are 2x10s, spanning 14 feet.  If the bathtub is laid parallel with the joists, so that it is being supported by only two, do you feel that is acceptable?
Comment: You'd think the tub is only being supported by two until you realize that the subfloor (and any X-bracing below) help transfer load to the adjacent joists, too.
Comment: 2x10's will definitely make a difference, but you still need to calculate the load based on both tubs being full at the same time, to be on the safe side. Also you need to consider deflection if you are going to be laying tiles. Take a look at the discussion here: https://forums.jlconline.com/forums/forum/jlc-online-expert-forums/rough-framing/38210-calculating-live-loads


No action when shutdown pressed

Question: My system: Ubuntu 11.10 latest updates with custom gtk3 theme
This is the output of .xsession-errors:

WARN  2012-01-15 21:44:04 glib.glib-gobject :0 invalid uninstantiatable type (null)' in cast toBamfView'
WARN  2012-01-15 21:44:05 glib :0 Unable to fetch children: Method "Children" with signature "" on interface "org.ayatana.bamf.view" doesn't exist

What can I do now to enable shutdown button?
If I press shutdown nothing happens.
Answer: Ok - I don't know if You like it, but it is a somewhat solution:
create a text file PowerOff.sh (with gedit for example) and write there (if Your default shell is bash - if other You'll probably know what to do):
#!/bin/bash
sudo shutdown -h now

Click it with Your right mouse button and in proerties: allow to execute as program.
It would be comfy to copy this file in some hidden location (i mean not to leave it on desktop).
After that You need to modify a file /etc/sudoers:
sudo gedit /etc/sudoers

at the end of this file add:
user ALL = NOPASSWD: /sbin/shutdown

where user is Your user name f.ex. thonixx if that is how you log in Ubuntu
OK, now create an activator on Your panel, click it with right mouse button, and choose:add to panel ->  add activator -> your own activator -> type: program in terminal and choose Your created file PowerOff.sh
Now it should be possible to shutdown Your PC by clicking the activator on Your panel. if You wish You could even give it an icon of Your choice
In that manner You could possibly make other commands. Or even write a simple python wrapper to show a form letting You to choose if You want to reboot, shutdown, logout etc.
I gave You the solution without poping out the shutdown dialog, because You didn't really mention which shutdown button makes this errors. You could make identical solution using the command:
gnome-session-save --shutdown-dialog

in bash file instead shutdown. In such case You would probably not need to edit /etc/sudoers
Regards
PS: for now it looks like a bug in Unity. try to google: org.ayatana.bamf.view
a few links:
using logout dialog from terminal or bash script
how to logout
how to edit permissions
how to write scripts in python
Comment: UPDATE: i have created a .desktop file which opens terminal and now there is the shutdown desktop launcher in unity and instead of clicking in the dialog i can click on launcher. its ok for me
Comment: wow thanks misery for this professional answer. i cant logoff and shutdown computer from the gnome dialog with the option to logout, shutdown and whatever you can choose there.

one question:
you mentioned "my panel" which panel you mean? unity launcher panel on the side? i cant right click there to create a launcher and i have unity, not gnome classic or gnome 3 ;)
Comment: I used Unity only for a while, but as I remember You can add an activator to any panel (this left side panel, or the default panel appearing on the upper and lower screen borders). I found a tutorial about this (however in polish) and it seems a bit complicated. How about trying to make an activator on the desktop and dragging it on the panel? Will that work?

No action when shutdown pressed


While loop for checking grades is invalid is not working for some reason

Question: So here is the question that I am working on
Grades with input validation (C++). Modify grade programs with arrays and functions. (the program should minimally have functions for average, min, max, # above average, etc. total of 4 functions) Add logic (to the main) so that if the user enters an invalid grade (lower than zero, higher than 100), the user will be issued an error message and then be allowed to reenter the grade. This will repeat as long as the user enters invalid grades. You will need a While loop.
When I enter a number lower than 0, it is not executing the code in the while loop for some reason, Also my minimum function is not working either
Here's the code that I have for the main function and the minimum function
<code>#include <iostream>
using namespace std;

double average(double x[], int n);
double maximum(double x[], int n);
double minimum(double x[], int n);
int nAboveAvg(double x[], int n);

int main()
{
   double grades[50];
   int ngrades;

   cout<<"How many grades? (max = 50) ";
   cin>>ngrades;

   //create for loop to get grades from user
   for(int i = 0; i<ngrades; i++)
   {
          cout<<"Enter grade ";
      cin>> grades[i];
      while(grades[i]< 0 || grades[i] > 100)
      {
          cout<<"Invalid grade- please enter again"<<endl;
          cin>>grades[i];
      }
  }

  //call the functions
  double avg = average(grades, ngrades);
  double max = maximum(grades, ngrades);
  double min = minimum(grades, ngrades);
  int nAbove = nAboveAvg(grades, ngrades);
  //display results

  cout << "Average = " << avg << endl;
  cout << "# above average = " << nAbove << endl;
  cout<<"Max value is = "<<max<<endl;
  cout<<"Min value is = "<<min<<endl;

}
//Minimum function

double minimum(double x[], int npts)
{

  double min = x[0];

  for(int i = 0; i < npts; i++)
  {
        if(x[i] < min)
        {

            min = x[i];
        }
    }
  return min;
}
</code>
Comment: Your code is fine. Whats your problem?
Comment: "less than 0" - how is your actual input look like?
Comment: Your minimum function is fine.Make sure you are entering the value less then 0 for `grades[i]` not for  `ngrades` :p ..just wanted to make sure..
Answer: Your code seems to work for me.
Did you try to rebuild it?
https://i.stack.imgur.com/X8XiX.png
Comment: Hmm that is weird I complied also but it still doesn't work for me
Comment: How many grades? (max = 50) 3
Enter grade -1
Enter grade 2
Enter grade 4
Average = 1.66667
# above average = 2
Max value is = 4

--------------------------------
Process exited after 7.955 seconds with return value 0
Press any key to continue . . .
Comment: How many grades? (max = 50) 3
Enter grade -1
Enter grade 2
Enter grade 4
Average = 1.66667
# above average = 2
Max value is = 4

--------------------------------
Process exited after 7.955 seconds with return value 0
Press any key to continue . . .
Comment: this is how my output looks like
Comment: Ok nevermind I got it too work but its not printing the minimum value
Comment: I mean i commented out calling not implemented max, avg and nAbove functions to make this screen.


Exacutable looks like a file in ubuntu 18.04

Question: I am compiling a FORTRAN code using gfortran (gfortram -o code.f code) and preparing an executable (code). It is compiled but the executable (code) looks like a file.
How to solve this problem.
Comment: Are you sure you're using it correctly; the `-o` option is where to output the compiled code & it's normally not given a `code.f` type of name, that's usually used for the input you've used the name `code` for.... ie. `[-o outfile] infile...` is from `man gfortran`; you appear to have file order reversed.
Comment: I have also tried this way.. but the problem is same. it is compiled and executable say output is working using ./output. but this executable looks like a file.
Comment: Can you post a screenshot?
Comment: shared for your consideration
Answer: Assuming your source is called source.f and the output is output, the syntax is
gfortran -o output source.f

Comment: I have also tried this way.. but the problem is same. it is compiled and executable say output is working using ./output. but this executable looks like a file.


OSGi Bundles for Spring and other Applications

Question: if I develop modules with the OSGi framework (bundles), can I integrate them in any OSGI based application such as Spring, right?
On what do I have to take care? What about the context or different data model?
Answer: You could ask the same thing for programming languages: if you develop something in Java, will you be able to integrate it in every Java based framework? The answer is: it depends.

If you mean by integrate "develop functionality once and deploy it without changes in all applications", you're out of luck. Although OSGi is standardized, you should see the modules and services you develop as low-level constructs: any application framework, such as Spring, builds upon the low-level constructs in its own way.
If, on the other hand you mean "deploy them and start using them from your own code", yes, you can generally mix & match bundles and services in any way you like, provided that you are willing to write some 'glue code'.

In general, yes, you can take your bundle, and integrate, but it's not free. It will, probably, make it easier to integrate your functionality if you package it up nicely in a bundle.
Comment: I guess my situation is rather good because we start from scratch with both applications.
Answer: In theory, yes. You'll have to take care if the target OSGi application is a different version of the OSGi spec (3, 4, 4.2, etc). You'll have to watch out if you're using an platform specific API as well.
Comment: Yep, makes sence. Do you know if OSGi is backward compatible?


React count array in API and reset / start again

Question: Hi Everyone I have been trying to create a Rota in React that uses a API of staff members below is the code I have been using. At the moment this reads the array and then adds a random number to the state every 3s.
What I want it to do is count from 0 to the value of the array and then reset. Any ideas?
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import { once, every, daily } from 'bella-scheduler';

class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
          data: [0]
      }
  }

  componentDidMount() {
      axios.get('http://localhost:3333/staff')
      .then((response) => {
          this.successShow(response);
      })
      .catch((error) => {
          this.successShow('error');
      });
  }

  successShow(response) {
        console.log(response.data);

        every('3s', () => {

            var i = Math.floor(Math.random()*(response.data.length))
            this.setState({person: response.data[i].name});
            console.log('Resolved task.');

        });

    }

  render() {
      return (

Rota

{this.state.person}

      );
  }
}

export default App;

Answer: You have to add a counter instead of the random() indexer to show the names after each other.
So add a cnt or counter variable to your state then increase the number every 3s but use it with % like below to prevent indexing problem.
for the constructor:
constructor(props) {
      super(props);
      this.state = {
          data: [0],
          cnt:0
      }
  }

and for the successShow function:
successShow(response) {
        console.log(response.data);

        every('3s', () => {

            var i = this.state.cnt++;
            this.setState({person: response.data[i%response.data.lenght].name});
            console.log('Resolved task.');

        });

    }

Comment: Thanks for this, I have added this in but I was getting the error "Cannot read property 'name' of undefined"

I changed "var i = this,state.cnt++;" to "var i = response.data.length.cnt++;" but then get a error of Cannot create property 'cnt' on number '5'

The reason for this is that the object does have 5 values but it counts from 0 - 4 not 1 - 5
Comment: every thing is current, but you have to initialize the first value for the parameter cnt in the constructor. I added the constructor changes to.
Comment: Thanks so much for this! I have it working now just in your comments above length has a typo.

Do you have any links to support this method? so I know where to look next time?
Comment: these are algorithm skills, you have to understand % for above example. look at this: https://www.w3schools.com/js/js_arithmetic.asp


How to create multiline tooltip text in GWT

Question: I need to show tool tip text in multiple lines, but setTitle() method in gwt is simply ignoring the \n character?
Is this possible to achieve?
Answer: If you are using the title property then it is not possible to have multi line tooltip. This is not a GWT problem, but a browser tooltip implementation/handling issue. If you really need to have a multi line tooltip then use Popup panel or DecoratedPopupPanel.
This will involve a little extra coding than just making a call to setTitle, but as a benefit you get complete control over how the tooltip is presented.
Comment: Yes! Once to show and once again to hide the tooltip, ie. if you are not using autohide. You can use Mouse[Over/Out]Handler for this.

Sounds like a lot of work :) But, If like me, you subclass input Widgets in your project and use these subclasses instead of GWT input widgets directly, then you can work out an elegant one time solution.
Comment: For this we have to add event handlers for every widget ..right?
Comment: an alternative using css: http://stackoverflow.com/questions/5641304/tooltips-for-gwt-tree-adding-mouseovers-to-nodes/18058618#18058618
Answer: setTitle worked for me if I included a \n as a line separator.
Comment: Which component are you using in your tooltip panel. Try using a text area in your tooltip: you will be able to \n your text regardless of the GWT version.


How do I make mutiple icons go to different url's

Question: I have my app which has some icons, the problem is that I set the icons as extensions/parents of one icon, so when I set an icon to go to a url all other icons go to that url too. But that is not what I want, I want each icon to go to a separate url.
The code for the extended icons is:
`
 Row(
                children: [
                  Expanded(
                      child: TaskCard(
                    label: "Teachers",
                  )),
                  Expanded(
                      child: TaskCard(
                    imageUrl: "assets/school-bag.png",
                    label: "EduPage",
                    pageUrl: "https://willowcosta.edupage.org",
                  )),

`
error displayed:

and the code for the parent icon is:
 SizedBox(
                height: 20.0,
              ),
              Text(
                "Sections",
                style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    fontFamily: "SpaceGrotesk",
                    color: Colors.black),
              ),

              //Here we set the "Shortcuts"

              //If you click Teachers it will take you the page where you can see the Teachers -
              //names a nd availabity alongs side the subject they teach
              //If you click EduPage it takes you to edupage
              //If you click Timetable it takes you to the Timetable generator
              //If you click Messages it asks you to join a messenger Gc of Students of your class
              Row(
                children: [
                  Expanded(
                      child: TaskCard(
                    label: "Teachers",
                  )),
                  Expanded(
                      child: TaskCard(
                    imageUrl: "assets/school-bag.png",
                    label: "EduPage",
                    pageUrl: "https://willowcosta.edupage.org",
                  )),
                  Expanded(
                      child: TaskCard(
                    imageUrl: "assets/timetable.png",
                    label: "Timetable",
                  )),
                  Expanded(
                      child: TaskCard(
                    imageUrl: "assets/message.png",
                    label: "Messages",
                  )),
                ],
              ),

              //Here we set the tasks that we have
              const SizedBox(
                height: 20.0,
              ),
              const Text(
                "You have 6 tasks for this week",
                style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    fontFamily: "SpaceGrotesk",
                    color: Colors.black),
              ),
              const TaskContainer(),
              const TaskContainer(),
              const TaskContainer(),
              const TaskContainer(),
              const TaskContainer(),
              const TaskContainer(),
              const SizedBox(
                height: 100.0,
              ),
            ],
          ),
        ),
      ),
      bottomSheet: const BottomSheetCard(),
    );
  }
}

//hier the first class ends

class TaskCard extends StatelessWidget {
  final String? imageUrl;
  final String? label;
  const TaskCard({Key? key, this.imageUrl, this.label}) : super(key: key);

//Function to  launch the selected url

  Future<void> goToWebPage(String urlString) async {
    final Uri _url = Uri.parse(urlString);
    if (!await launchUrl(_url)) {
      throw 'Could not launch $_url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      //Here we set the properties of our Sections (Teachers etc)
      padding: const EdgeInsets.all(8.0),
      child: Column(
        children: [
          Container(
            height: 80.0,
            width: 76.1,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.0),
                boxShadow: [
                  BoxShadow(
                      color: Colors.grey, blurRadius: 2.0, spreadRadius: 0.5),
                ]),
            child: IconButton(
              onPressed: () async {
                await goToWebPage(pageUrl);
              },
              icon: Image.asset(
                imageUrl ?? "assets/teacher.png",
                height: 75.0,
                width: 70.0,
              ),
            ),
          ),
          SizedBox(
            height: 10.0,
          ),
          Text(
            label ?? "",
            style: TextStyle(fontSize: 16.0),
          )
        ],
      ),
    );
  }
}

error 2 displayed:

My app looks like this:

I want each icon to take me to a different website
Comment: Just like you are passing an `imageUrl`, you can pass your link in a variable and use that in your method `goToWebPage`
Answer: In your parent icon you can define new string variable in constructor and name it pageUrl like two other variable imageUrl, label, now use it lie this:
onPressed: () async {
   await goToWebPage(pageUrl);
},

then pass it like this:
Expanded(
   child: TaskCard(
        imageUrl: "assets/school-bag.png",
        label: "EduPage",
        pageUrl: "https://willowcosta.edupage.org",

   ),
),

Full Example of TaskCard calss:
class TaskCard extends StatelessWidget {
  final String imageUrl;
  final String label;
  final String pageUrl;//<-- add this
  const TaskCard(
      {Key? key,
      required this.imageUrl,
      required this.label,
      required this.pageUrl})//<-- add this
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        children: [
          Container(
            height: 80.0,
            width: 76.1,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.0),
                boxShadow: [
                  BoxShadow(
                      color: Colors.grey, blurRadius: 2.0, spreadRadius: 0.5),
                ]),
            child: IconButton(
              onPressed: () async {
                await goToWebPage(pageUrl);//<-- add this
              },
              icon: Image.asset(
                imageUrl ?? "assets/teacher.png",
                height: 75.0,
                width: 70.0,
              ),
            ),
          ),
          SizedBox(
            height: 10.0,
          ),
          Text(
            label ?? "",
            style: TextStyle(fontSize: 16.0),
          )
        ],
      ),
    );
  }
}

Comment: I updated my answer. Check it out. @CivaaBTW
Comment: Stupid question but how can I define pageUrl?


magento 2 how to get the product object in product detail tab

Question: can anyone guide me on how I can load or get the product object on the detail tab
https://prnt.sc/t1dpay
I want to display the data on a detail page by loading the product object from
vendor/magento/module-catalog/view/frontend/templates/product/view/details.phtml
Thanks in advance
Comment: What code have you written already? Please have a read of [this guide on producing code for a good quality question](https://stackoverflow.com/help/minimal-reproducible-example), then include and mark up your code in your question. Cheers!
Answer: In Magento there is the Magento\Framework\Registry class which contains (among other things) the "current product", in case of the product detail page that would be the product shown on the page.
Magento\Framework\Registry is deprecated but I've not yet found a good alternative. Because it's deprecated most of the time I create a class which does only one thing, get the desired value from the registry. It's a middle ground between using the deprecated class itself directly or "rewriting it", it encapsulates the deprecated class and can be very easily swapped out if necessary in the future (either the whole class or specifically the implementation of get()).
use Magento\Framework\Registry;

class MyCurrentProduct {
    protected $registry;

    public function get(): ProductInterface {
        return $registry->get('current_product');
    }
}

I left some things out of the example because I don't like posting a copy-pastable answer.
Answer: Rather than using the registry, a much better option is to use the product repository.
Since you wish to grab the current product from the product detail page, that product id is available as a parameter from the URL:

You can then use the RequestInterface to grab an instance of the request object, and grab that specific parameter with:
$productId = $this->request->getParam('id');
$product = $this->productRepository->getById($productId);

Here's the full code of doing this with a ViewModel:
<?php declare(strict_types=1);

namespace Macademy\ProductInfo\ViewModel;

use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Block\ArgumentInterface;

class MyViewModel implements ArgumentInterface
{
    public function __construct(
        private RequestInterface $request,
        private ProductRepository $productRepository,
    ) {}

    /**
     * @throws NoSuchEntityException
     */
    public function getProduct()
    {
        $productId = $this->request->getParam('id');
        return $this->productRepository->getById($productId);
    }
}


Diffing and Synchronizing 2 tables MySQL

Question: I have 2 tables, One with new data, and another with old data.
I need to find the diff between the two tables and push only the changes into the table with the old data as it will be in production.
Both the tables are identical in terms of columns, only the data varies.
EDIT:
I am looking for only one way sync
EDIT 2
The table may have foreign keys.
Here are the constraints

I can't use shell utilities like mk-table-sync
I can't use gui tools,because they cannot be automated, like suggested here.
This needs to be done programmatically, or in the db.
I am working in python on Google App-engine.

Currently I am doing things like

OUTER JOINs and WHERE [NOT] EXISTS to compare each record in SQL queries and pushing the results.

My questions are

Is there a  better way to do this ?
Is it better to do this in python rather than in the db ?
Comment: Assuming you want only a one-way sync: why don't you just wipe the old table completely and fill all data from the new one? Too much data?
Comment: Yes I want only one way Sync.
As I said before since It will be in production I can't just drop the table and replace it, Yes It may have thousands of rows
Answer: According to your comment to my question, you could simply do:
DELETE FROM OldTable;

INSERT INTO OldTable (field1, field2, ...) SELECT * FROM NewTable;

As I pointed out above, there might be reasons not to do this, e.g., data size.
Comment: This is a bad Idea on a production database with thousands of records, and especially considering that it may have foreign keys.
Comment: O.k. your original reply to my question didn't state this. Thus my solution is not possible.


How to benchmark performance before jumping into match

Question: I'd like to make the game look as good as possible, but also dont want to drop to 10FPS in the middle on a match.
Any way to tryout a high CPU consuming scenario before jumping into a game? (So I can try to maximize performance but keep it over 30 FPS)
Comment: Unless your CPU is very old (like Core2Duo-old or older) or very low end, chances are Overwatch's performance is bottlenecked by your GPU instead. Besides, is there a reason why you think the Training mode isn't good enough as benchmark?
Answer: There is no video benchmark in overwatch to test your hardware capabilities.
But you can either play a regular game vs. AI. This would fill up your team with random players.
Or you can create a custom game and fill both teams with AI.
You can't really simulate the most demanding situations but you get an idea about where you are in terms of frame drops. In case of the 30 FPS as your lower limit, better make sure you don't drop below 35 FPS while testing.
Comment: Good answer.  The training mode itself is too clean of debris and multiple targets using flashy ults. A solo bot match would provide better results.
Comment: Thanks for the answer. That was my plan B, but it seems the plan A doesn't exist. My Plan A was something like in the Tomb Raider Reboot that would try to render things that are hard for computers to run to be able to see the dip in the FPS. But seems that this doesn't exist.


Java classes reflection in scala

Question: I'm trying to use java's reflection API on scala. I have a KDTree class loaded from bytecode using a ClassLoader. Here's it's methods:
public class KDTree
{
public KDTree(int k)
public void insert(double[] key, Object value) throws Exception
public Object[] range(double[] lowk, double[] uppk) throws Exception
}

And here's my wrapper scala class:
class KDTree( dimentions: Int )
    //wrapper!
    {
    private val kd= Loader.loadClass("KDTree")
    private val constructor= kd.getConstructor(java.lang.Class.forName("java.lang.Integer"))
    val wrapped= constructor.newInstance("1")
    def insert( key:Array[Double], element:Object)=
        kd.getDeclaredMethod("insert", classOf[Array[Double]])
            .invoke(key, element)
    def range( lowkey:Array[Double], highkey:Array[Double])=
        kd.getDeclaredMethod("range", classOf[Array[Double]])
            .invoke(lowkey, highkey)
    }

When I try to initialize I get an error:
java.lang.NoSuchMethodException: KDTree.<init>(java.lang.Integer)

However, the constructor's only argument is indeed a integer!
Also, I can't simply do java.lang.Integer.class, since scala complains of the syntax: error: identifier expected but 'class' found.
Does anyone have any tips?
EDIT
Here is my finished code, in case someone has a use for it:
class KDTreeWrapper[T]( dimentions: Int )
{
private val kd= Loader.loadClass("KDTree")
private val constructor= kd.getConstructor(classOf[Int])
private val wrapped= constructor.newInstance(dimentions:java.lang.Integer)
    .asInstanceOf[Object]
private val insert_method= kd.
    getMethod("insert", classOf[Array[Double]], classOf[Object])
private val range_method=
    kd.getMethod("range", classOf[Array[Double]], classOf[Array[Double]])
def insert( key:Iterable[Double], element:T)=
    insert_method.invoke(wrapped, key.toArray, element.
        asInstanceOf[Object])
def range( lowkey:Iterable[Double], highkey:Iterable[Double]):Array[T]=
    range_method.invoke(wrapped, lowkey.toArray, highkey.toArray).
        asInstanceOf[Array[T]]
}

Comment: why exactly is reflection needed here?
Comment: @Arjan because [I need to have a single scala file with all my code](http://stackoverflow.com/questions/13554617), and KDTree is part of a Java library
Answer: Your problem is that you try to load a constructor with a type parameter java.lang.Integer. Try it with int.class.
Also it is shorter to write kd.getConstructor(int.class).
Comment: Use `classOf[Integer]` or `classOf[int]` ans described [here](http://stackoverflow.com/questions/1135248/scala-equivalent-of-java-java-lang-classt-object).
Comment: as I mentioned, in scala `anything.class` complains
Answer: I think my example is a lot simpler, but that could be because I wrote it:
class Config {
  val c = "some config"
}

class Moo(c: Config) {
  val x = "yow!"
}

class Loo(c: Config)  extends Moo(c) {
  override val x = c.c + " yodel!"
}

object CallMe {
  def main(args: Array[String]) {
    val cn = new Config

    // val m: Moo = new Loo(cn)

    val c = Class.forName("Loo")
    val ars = c.getConstructor(classOf[Config])
    val m: Moo = ars.newInstance(cn).asInstanceOf[Moo]

    println(m.x)
  }
}

prints out
some config yodel!

Java classes reflection in scala


Use of an integer code in URIMatcher class in Android

Question: According to the Android Documentation, we have to provide int code for every URI we match.
addURI(String authority, String path, int code)

and as the documentation explains:

Add a URI to match, and the code to return when this URI is matched.

What role does the "code" play?
I understand in the case of UriMatcher.NO_MATCH that returns -1, for invalid matches!, but what for the other codes like 1, 20, 14 etc?
For example,
private static final int PEOPLE = 1;
private static final int PEOPLE_ID = 2;
private static final int PEOPLE_PHONES = 3;
private static final int PEOPLE_PHONES_ID = 4;
private static final int PEOPLE_CONTACTMETHODS = 7;

or
    private static final int DELETED_PEOPLE = 20;
The above code has been taken from here.
Answer: This code will be returned by UriMatcher.match(). Then you can use a switch statement to take action based on the type of the URI which was matched. Here is an example from my own project.
Comment: @AshishKrishnan Java has always supported switching on `char` variables. I assume you mean the new `String` switching. But to answer your actual question...I don't know why this particular mechanism was chosen. Even with String switching available, an `int` seems like a better identifier because it has less memory overhead.
Comment: Okay is this due to the reason that Java did not support String based switching prior to Java 7? or just a feasible way of doing this?
Comment: Yeah. Sorry, I meant `String` .! Thanks! Looks convincing to me!


INI directive 'mbstring.func_overload' is deprecated since PHP 7.2

Question: Using PHP Compatibility Checker, got this warning
INI directive 'mbstring.func_overload' is deprecated since PHP 7.2

is there any way to handle this warning?
Answer: It all might depend on how your code is using this. PHP.net highly discourages using this feature. If you are using an older library that uses this value, then you should look at updating the library and see if they've fixed it. If that library or your code is accessing this value (for example with ini_get('mbstring.func_overload')), then that's not really a problem, though the compatibility parser will still call it out as an issue. This was called out to the Symfony maintainers, and they just dismissed it.

INI directive ‘mbstring.func_overload’ is deprecated since PHP 7.2


Why are stringify'd moment.js dates returning different values when parsed back

Question: I have a moment that I want to store in local storage and compare against at a later date using isBefore().
When I stringify this moment it converts it to ISO8601 format, fine. However when I try to bring this string back into play by turning it into a new moment it has a different value. The hour is getting offset by a timezone conversion.
It goes like this:
moment().hour(); = 21
JSON.stringify(moment()); = "2013-05-20T21:38:31.819Z"`
moment("2013-05-20T21:38:31.819Z").hour(); = 22
Obviously the issue here is related to the fact ISO8601 is in UTC format but no matter how I try to use the moment utc() function it doesn't change the fact the fundamental values underneath are different.
How can I stringify a moment and then parse it again with the value remaining contant?
Comment: Hope solution in this link helps ?
Comment: Hope solution in this link helps https://stackoverflow.com/a/31104671/10265076
Answer: The workaround I have for this is to force moment to not use utc when converting the string. So, where foobar is the object sotred in local storage, if:
foobar.expires = 2013-05-22T15:30:23.834Z
then the statement:
moment(foobar.expires, "YYYY-MM-DDTHH:MM:SS.SSS")
will return the same moment that was originally stringify'd when it was stored in local storage.
Messy hack though.
Comment: The correct format string would be: "YYYY-MM-DDTHH:mm:ss.SSS"


Does the cost of reviving a dweller ever change? If so, how much?

Question: Yesterday I sent an explorer out to the wastes and he died at the end of the day. I paid 300 caps to revive him and brought him back to the vault.
Today I sent him again and almost certainly he will die once more (brilliant overseeing, eh?). Should I expect to fork over even more caps today? If so, how much?
In case it matters (as per Rapitor's comments), he will probably level up a few times before he dies today. He was revived at level 19 and he will probably be 20 or 21 today.
More generally, is the cost of revival related to anything at all? Is it related to any of those factors:

the dweller's level or their SPECIAL attributes?
the number of times that particular dweller has already been revived?
the overall number of times dwellers have been revived?

I have had a few dwellers dying in my vault, but I just didn't keep track of the cost trend. I've searched the Internet, but I couldn't find anything about it either.
Comment: I think it costs more to revive them the higher level they are, but I haven't really been having to deal with too much death to confirm
Comment: I paid 1000 for a level 50 which stats weren't that much better than before, so it seems level is the main or only factor.
Answer: The price for reviving a dweller inside your vault is based on the level of the dweller.
The higher the level of the dweller the more expensive.
But it caps out at 1000 caps.
According to this wiki the formula is as following:

their revive cost scales to the level starting at 100 CAPS for level
  1, and increases an additional +20 CAPS for each level afterwards.

That would mean the cap is reached when the dweller hits level 46.
For dwellers in the wasteland it is a bit different.
As you can see it will cost 1000 caps to revive this level 29:

I am unsure the exact math for this, but the cost is still capped at 1000 caps for dwellers.
Comment: Mr Handy is always 2000 caps, and I don't think he levels up.
Comment: I think the exception is Mr Handy, as I recall him being low level, high cost.
Comment: While this is useful, and has a nice picture, the death referred to in the question was while exploring the wasteland. At least we know the cap, I guess.


Tomcat Current thread count

Question: Tomcat and appache2 are connected through AJP. I have these configurations for tomcat and apache:
<Connector port="8009" protocol="AJP/1.3"
           URIEncoding="UTF-8"
           redirectPort="8443"
           connectionTimeout="20000"
           maxThreads="512" />

<IfModule mpm_event_module>
    StartServers          5
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    ServerLimit        1024
    MaxClients          512
    MaxRequestsPerChild   0
</IfModule>

When I go to tomcat manager, I see :
"ajp-bio-8009"
Max threads: 512 Current thread count: 256 Current thread busy: 231

The current thread busy sometimes reaches 256. Why isn't the current thread count set to 512?
Answer: The current thread is dynamically managed by apache.
from worker.c in apache's source code:
thread is started as needed.  following is the main flow to start worker thread.
static int worker_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
  startup_children(remaining_children_to_start);  //server/mpm/worker/worker.c
     if (make_child(ap_server_conf, i) < 0) {     //server/mpm/worker/worker.c
       child_main(slot);                          //server/mpm/worker/worker.c
         rv = apr_thread_create(&start_thread_id, thread_attr, start_threads
         rv = apr_thread_create(&threads[i], thread_attr, worker_thread, my_info, pchild);

And when idle thread > max_spare_threads, apache will try to reduce the spare thread by kill child process/thread to reduce the idle threads count.
if (idle_thread_count > max_spare_threads) {
    /* Kill off one child */
    ap_worker_pod_signal(pod, TRUE);
    retained->idle_spawn_rate = 1;
}

internally apache manage these child process, and using signal to communicate with child process to adjust threads as needed.
all threads are managed in ap_scoreboard_image->servers[i][j];
apache will monitor the thread count, and using socket send out to let infoCollector know.
roughly by following code (unrelated line were deleted)
./httpd/modules/cluster/mod_heartbeat.c
    for (i = 0; i < ctx->server_limit; i++) {
         ....
            for (j = 0; j < ctx->thread_limit; j++) {
                ws = &ap_scoreboard_image->servers[i][j];
                if (res == SERVER_READY && ps->generation == mpm_generation) {
                    ready++;
                }
            }
        }

    len = apr_snprintf(buf, sizeof(buf), "v=%u&ready=%u&busy=%u", MSG_VERSION, ready, busy);
    ...
    rv = apr_socket_sendto(sock, ctx->mcast_addr, 0, buf, &len);

In Tomcat:
these thread info are received by:
./tomcat/java/org/apache/catalina/ha/backend/CollectedInfo.java
and displayed by:
/Users/twer/lab/tomcat/java/org/apache/catalina/manager/StatusTransformer.java
writer.write(" currentThreadCount=\"" + mBeanServer.getAttribute(tpName, "currentThreadCount") + "\"");

most of the code show here are main flow, unrelated line are deleted. download the source to find out more.
download apache src: http://www.apache.org/dist/httpd/?C=S;O=A
download tomcat src: http://tomcat.apache.org/download-70.cgi
Comment: Thanks for the reply, but this doesn't answer my question.
I'm scaling up my server. I used to have max threads = 128, and most of them were busy. I changed it to max threads = 256. With this number, I was having 200 threads busy. Now I'm getting more hits. I guess that 400 threads should be busy, so I doubled the number of max threads to 512. But the server is only serving a max of 256 threads at a time.
So my question is: What should I do to have my server use more threads?
Comment: try using some web load test tool , let the server receive more request, to see if it can up to 512. http://stackoverflow.com/questions/5139953/web-server-load-testing-tool

Tomcat Current thread count


Interchanging class & struct keyword in C++

Question: I was reading about one of the strange C++ feature called Injected class name here.
I tried following simple program
#include <iostream>
class test
{
    int s{3};
    public:
    int get_s()
    { return s; }
};
int main() {
    class test::test s;  // struct test::test s; also allowed. Why???
    std::cout<<s.get_s();
}

If I replace class keyword with struct in first line of main() program still compiles & runs fine. See live demo here. Why? Shouldn't I get compiler error? Why it compiles fine?
Comment: actually an interesting question, but unfortunately the title is misleading, your actual question has nothing to do with "injected class names".
Comment: What compiler error do you expect?
Answer: I believe the relevant verse is in 188.8.131.52/3 (highlighting mine, quoted here from a draft of the C++17 Standard):

Thus, in any elaborated-type-specifier, the enum keyword shall be used to refer to an enumeration (7.2), the union class-key shall be used to refer to a union (Clause 9), and either the class or struct class-key shall be used to refer to a class (Clause 9) declared using the class or struct class-key.

So either keyword can be used to stipulate the scope within which the injected class name exists, irrespective of which was used to declare/define test.
Answer: struct and class are almost identical in C++. The only difference is, that members of structs are public by default while member of classes are private by default.
see complete answer here: C/C++ Struct vs Class
Answer: class test s;
or
struct test s; works too.
Classes and structs in C++ are virtually the same thing.
The difference is:
struct A{
};

is like
class A{
public:
};

and
class B{
};

is like
struct B{
private:
};

Allowing you to use the struct prefix is for C compatibility and I guess it extends to class because "why not?".
Answer: I'm sorry, maybe I have misunderstood your post but there is no big differences between class and struct in C++.
The main differences that I know is that by default, a struct have all field public.
There is a post talking about differences between struct and class :
What are the differences between struct and class in C++?


How do you do alegbra correctly in Lua?

Question: So i have recently been attempting to do alegbra in lua and this was the closet way i could come up with of doing it is this how you are even supposed to do it correctly? An other problem that i find with doing alegbra in  lua is that in alegbra there is both a constant and a variable beside eachother well the problem with that is that lua does not like both a Number and a letter beside eachother so it errors is there any way how i could go about doing alegbra inside lua without getting errors?
local a = 5

-- ALEGBRA?
print(((a * 2) / 10) + 15 - 20)

-- 5 * 2 = 10
--  10/10 = 1
--   1 + 15 = 16
-- 16 - 20 = -4

-- The Problem lies right here when there is a Variable and a constant together lua does not like that :/
local x = 10

print(5x + 5)

Answer: print(5x + 5) will trigger a syntax error; Lua does not allow implicit multiplication. The fix is trivial: Explicitly use the multiplication operator as in your first example: print(5*x + 5) works just fine.

How do you do alegbra correctly in Lua?


How to modify dictionary values based on an array having key information

Question: dict ={'A':{'x':'123','y':'322','z':'432'},'B':{'x':'24','y':'622','z':'5652'},'C':{'x':'424','y':'682','z':'52'},'D':{'x':'32','y':'96','z':'3'}}

arr1 = ['A','B','D']
values of key to changed: y,z
I want to change dict value(x,y) based on arr1 such that value of 'y' should be equal to 'z'
Required Dict
dict ={'A':{'x':'123','y':'322','z':'322'},'B':{'x':'24','y':'622','z':'622'},'C':{'x':'424','y':'682','z':'52'},'D':{'x':'32','y':'96','z':'96'}}
Comment: Do you have any code that didn't work as you wanted?
Answer: Try:
You can you can iterate over the elements of arr1 then set the value of the z key.
dict1 ={'A':{'x':'123','y':'322','z':'432'},'B':{'x':'24','y':'622','z':'5652'},'C':{'x':'424','y':'682','z':'52'},'D':{'x':'32','y':'96','z':'3'}}
arr1 = ['A','B','D']

for i in arr1:
    dict1[i]['z']=dict1[i]['y']
print(dict1)

PS: Don't use keywords like dict as variables because they shadow the inbuilt functions
Answer: Don't use dict as the name for your dictionary, it is a reserved built-in function name.
Where d is your dictionary:
for k in arr1:
    d[k]['z'] = d[k]['y']

This simply copies the 'z' value of each inner dictionary for each 'y' value.


Uniform Convergence.

Question: If a sequence of functions $f_j$ on a domain $S \subseteq \mathbb{R}$ has the property that $f_j \rightarrow f$ uniformly on $S$ then does it follow that $(f_j)^2 \rightarrow f^2$ uniformly on $S$?
I know this to be false. Suppose $f_j(x) = x + (1/j)$ for example.
But what would make this statement true? What if $f$ is bounded? Does anyone have a proof to show that if $f$ is bounded then the above is true?
Comment: Well it would certainly be true for $S$ compact, as on a compact set convergence $\implies$ uniform convergence. The same proof should work for bounded.
Answer: It is sufficient to assume that $f$ is bounded. Suppose $f_j\to f$ uniformly and that $|f|$ is bounded by $M\geq 1/2$. Then for any $\epsilon>0$, we have some $N\in \mathbb N$ such that
$$n\geq N\implies |f_n(x)-f(x)|<\frac{\epsilon}{2M+\epsilon},\forall x\in S$$
thus for $x\in S,n\geq N$ we have
$$\begin{eqnarray}
|f_n^2(x)-f^2(x)|&=&|f_n(x)-f(x)||f_n(x)+f(x)|\\
&\leq& |f_n(x)-f(x)|(|f_n(x)-f(x)|+2|f(x)|)\\
&<&\frac{\epsilon}{2M+\epsilon}(2M+\epsilon)=\epsilon\\
\end{eqnarray}$$
so $f_j^2\to f^2$ uniformly.
As a partial converse, if $|f_n(x)-f(x)||f(x)|$ is unbounded for infinitely many $n$ then
$$\begin{eqnarray}
|f_n^2(x)-f^2(x)|&=&|f_n(x)-f(x)||f_n(x)+f(x)|\\
&\geq& |f_n(x)-f(x)|(2|f(x)|-|f_n(x)-f(x)|)\\
&\geq& 2|f_n(x)-f(x)||f(x)|-|f_n(x)-f(x)|^2\\
\end{eqnarray}$$
can be made arbitrarily large for arbitrarily large $n$ by choosing $n$ such that $|f_n(x)-f(x)|<1$ for all $x$ and $|f_n(x)-f(x)||f(x)|$ is unbounded. Thus in this case $(f_j^2)$ does not converge uniformly to $f^2$.
Note that if $S$ is closed and bounded and $f$ is continuous then since $S$ is compact $f$ will be bounded, giving us another sufficient hypothesis.
Comment: The example $S = (0,1)$, $f_n(x) = \frac{1}{x} + \frac{1}{n}$ shows that some kind of hypothesis (e.g. "$|f|$ is bounded by $M$") is needed, even for continuous functions on bounded intervals.  Clearly this sequence $f_n$ converges uniformly to $f(x) = \frac{1}{x}$ on $S$, but the fact that $|f_n(n^{-2})^2 - f(n^{-2})^2| = \frac{2n^3 + 1}{n^2} > 1$ holds for all $n$ shows that the sequence $f_n^2$ does not converge uniformly to $f^2$.
Comment: Yes, that was mentioned in the OP and is why I required that $f$ be bounded. Note that $S$ closed and bounded and $f$ continuous implies $f$ bounded, as $S$ is then compact.
Comment: I don't quite follow why...

$$\begin{eqnarray}
|f_n(x)-f(x)|(|f_n(x)-f(x)|+2|f(x)|)&<&\frac{\epsilon}{2M+\epsilon}(2M+\epsilon)=\epsilon\\
\end{eqnarray}$$

Shouldn't it be...

$$\begin{eqnarray}
|f_n(x)-f(x)|(|f_n(x)-f(x)|+2|f(x)|)
&<&\frac{\epsilon}{2M+\epsilon}(\frac{\epsilon}{2M+\epsilon} + 2M)
\end{eqnarray}$$

Am I missing something obvious?
Comment: @JasonP. I implicitly assumed that $M$ is chosen to be at least $1/2$. I've now made that explicit.
Comment: The hypothesis that $f$ be bounded is not actually necessary for $f_n^2$ to converge uniformly to $f^2$. The silliest example is $f_n(x) = f(x) = x$ for all $x \in \mathbb{R}$, and there are many variations on this theme (e.g. nothing prevents all of the differences $|f(x) - f_n(x)|$ from being supported on the same compact set, even if $f$ is unbounded).  The point of my example was mainly that boundedness of the *function* is definitely much more relevant to making the squares converge than boundedness of the *domain* (the OP's counterexample is on an unbounded domain).
Comment: @leslietownes Note that I edited my question already to fix that.
Comment: And I should add that I mean "uniformly eventually constant".
Comment: The condition that $f$ is bounded on the set where $(f_n)$ is not eventually constant is **not necessary** for $(f_n^2)$ to converge uniformly to $f^2$. Consider $f_n(x)=x+(n(x^2+1))^{-1}$.
Comment: @DidierPiau Thanks for pointing that out, corrected.

Uniform Convergence.


Making of durable plywood frame

Question: I am making a custom camera rig for the kite aerial photography and I need a ┏┓-shaped frame like this:

(depth × width × height = 40 × 200 × 100 mm, thickness ~5 mm).
I cannot use bent aluminum as it is pretty dense (2.7 g/cm³) and I do not have any bending machines.
I cannot use 3D-printing as I don't have an easy access to a 3D printer. The plastic seems to be dense too: 1 – 1.4 g/cm³.
So, my choice is old-school wood. Plywood. As a bonus, it is very lightweight: about 0.6 g/cm³!
I could probably cut tree ▌-shaped plates and glue them together at 90°. But I am afraid that the whole frame would not be rigid enough if forces applied to like this:

Just get me right: I am pretty sure that it would not break, but I am just uncomfortable with that feeling.
Moreover, as the plywood is pretty thin, I would probably need extra plinths to glue the surfaces:

So, I am thinking about CNC-cutting ~ten ┏┓-shaped parts and gluing them together:

It seems for me, that the resulting frame would be much stronger to forces applied in all the directions, compared to the three plates versions above.
Question is: am I right? Or should I just make the frame of three plywood plates? Any nuances in assembling together such a stack of parts?
Comment: How much squeezing force will you have? None of the designs will be very resistant to being squeezed at the bottom, the wood will bend.
Comment: I don't expect any squeezing in normal conditions. But if something goes wrong with the kite or wind the frame (loaded with 200g of electronics) can fall from 3-10 meters. I hope it won't happen.
Answer: Of all your designs, the last one certainly has much to its credit. If you use sheets of plywood to create the individual inverted-U shapes, you'll gain that much more strength. Consider a combination of the design previous (with the gussets) and cut your shapes to include an arc to the inside of each leg. This provides for contiguous transfer of forces as well as looking good.
Alignment is unlikely to be critical in your application, but you'd want to have as clean alignment as possible. Drilling holes in each plate in the same location, then pinning the layers with a dowel rod will make for ease of assembly. Once glued together, you can glue the dowels in place or remove them as you like.
If your plywood source is recycled skateboard planks, your work will resemble the last image that much more!
Comment: Thank you for quick answer! There will be another frame inside this frame. Two frames provide rotations in vertical and horizontal axes. Gussets will force me to make frames bigger, so I'd like not to have them. A small arc, though, seems to be a good idea!
Answer: I agree with fred_dot_u, and I'd add a few points:

The grade and type of plywood is important. CDX will have 3-4 plies, gaps, knots, etc. that could dramatically weaken the critical corner areas of your piece. Better plywood has no voids, many thin plies, and higher-quality veneer.
A bias might be the best approach. If you cut square with the sheet, half of the plies will be aligned in the weak direction. If you were to go with a 45 degree bias, every ply would lend strength (though none would provide full-length grain).
Cutting a series of fairly large circles out of the center area of the panels could dramatically lighten the structure without undue weakening.

All that said, a few pine boards with a small block inside each corner (cut from the same boards, in lieu of the plinths) and high-quality adhesive would save you a whole lot of cutting.
<code>____________________________________________
|  *     *                                   <-- top board
|
|___________________________________________
|     |     |
| *   |     | <-- block
|     |_____|                  * screw locations
|     |
|     | <-- side board
|     |
</code>
Comment: Yes, solid wood with blocks running parallel to the corner on the inside. A few drywall screws and some urethane glue and you're done.
Comment: Thanks. I thought about the bias and I'll try to cut the parts with different angles. And what do you mean by "pine boards"? Solid wood?
Answer: If you CNC cut 10 U-shaped pieces from 1/2" plywood then glue it up, as you show in your last image, you essentially have one U-shape cut from a piece of 5" thick plywood, except that you don't have the pressure and heat used in manufacturing plywood.
By cutting flat shapes, you would have some increased strength on the corners, but I'd still want to have corner braces on them.
If you're going to the trouble of cutting & gluing all those pieces and adding the corner braces, you may as well go with 3 flat pieces glued & screwed with corner braces added. It would be much simpler construction, and likely just as strong. I'd go with solid wood instead of plywood in this case, since solid wood will take and hold screws much better than the edge of a piece of plywood will.
Comment: Thanks. I meant ~⅒ inch plywood (3-3.5 mm, three layered plywood). I think it's difficult to use screws with that thickness without the risk of tearing the material apart. And gussets will "steal" the space: there is another similar but smaller frame with a camera inside this one and it needs to rotate freely.
Comment: @madhead I picked 1/2" (~12.5 mm) as an example. However, the analogy still stands - you're building a new sheet of plywood `10x` thick where `x = 3mm` instead of `x=12mm`. You may consider simply buying one sheet of 25-30 mm plywood and cutting one single U-shape out of that instead of laminating multiple individual sheets to come up with that thickness. As mentioned by fred_dot_u, a rounded corner instead of sharply square should give you added strength without loosing too much space for your inner frame.

Making of durable plywood frame


Could not parse the remainder: 'slug=blog.slug' from ''blog_details'slug=blog.slug'

Question: i am using slug field in my blogs. here's how i am creating slugs
views.py
def Creating_blog(request):
    form=BlogForm()
    if User.is_authenticated:
        if request.method=='POST':
                form=BlogForm(request.POST,request.FILES)
                if form.is_valid:
                    blog_obj=form.save(commit=False)
                    blog_obj.author=request.user
                    title=blog_obj.blog_title
                    blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4())
                    blog_obj.save()
                    return redirect('index')
    return render(request,'blogs/creatingblog.html',context={'form':form})

Using slug to lead to the blog details page
Read More

but whenever i click on that it shows me
raise TemplateSyntaxError("Could not parse the remainder: '%s' "
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: 'slug=blog.slug' from ''blog_details'slug=blog.slug'

i have tried with slugify too
Read More

but it remains the same
help me out please.
Comment: Don't need to mention two times slug
```
Read More
````
Answer: As @Dev already mentions, you can simply do:
Read More

Don't need to 'slugify' it either, as its already a slug.
Additionally, but unrelated, I'd recommend using Django's class-based views.


Picking a hymn with a minimum numbers of clicks from main menu

Question: I am building an android app (hymn book). Users need to pick a particular hymn with a minimum number of clicks from the main menu.
The problem is that the hymns are around 800+ and will keep increasing.
I am considering the faceted navigation list pattern where the user can type either the hymn number or part of the words in the hymn's title and the app will show matching hymns.
Is this the best pattern available for such use-case, do you have effective solution to solve this problem? Can you suggest any interaction patterns that will work?
Thanks
Comment: [UX Myth #2: All pages should be accessible in 3 clicks](http://uxmyths.com/post/654026581/myth-all-pages-should-be-accessible-in-3-clicks)
Comment: @JonW. I read the article you linked to. Great article but it isn't really relevant in this case. The user **must** open the hymn within a narrow time-space( i.e. before the others start singing the hymn). So, if i can beat the three-click rule, then awesome.
Comment: In that case your question should state that it is a speed issue, not a click one. For instance I could do a 3-clicks system that could take 5 minutes to use! (I'd be a bad UX designer if I did that, but still...)
Answer: That pattern is a good start, both accessing a hymn by number or via a few words from its title or any of its verses.  I would also suggest that include a "favorites list" and maybe something to facilitate pre-service preparation.  By that, I mean that prior to a service beginning, a user could enter all of the hymns for the up coming service, then operate from a simple list thereafter.
If you are trying to address the needs of ministers/service-organizers, you might want to add in a calendar so that hymn selections can be entered for multiple services across multiple days or weeks.
If you are trying to address the needs of a hymnest, you might want to have the user interface warn them when they choose the same pre or post service hymn for multiple ajacent services.
Comment: Since, the app will be mainly for users, i will implement the favourites list idea. I will go a long way in alleviating the hymn search issue. Thanks
Answer: I love your idea, and it is used in other examples as well. (The LDS has a Gospel Library app, with a digital hymn book, that functions in a similar fashion.) But I have a few ideas to add, if they sound decent.
This first idea is related to Google's Instant Results. Pretend I'm looking for hymn... #314, let's go with that. What if you made it so when I write 3, it lists hymns 3, 30-39, and 300-399? Then, I write 31, so it lists 31, and 310-319. I don't know what it's called, but that's one idea. It lists everything that starts with what was written. In this case, if I wanted 314, I'd write 3, 1, and see the link to 314. 3 clicks, done.
Another idea is to count how many times each hymn file was opened this month, and delete counts more than a month old. (Change this as applicable. How often should it be used?) Then, on the main page, have a "sort by commonly used" or "sort by popular" or whatever button. List the ones with highest count first, and if there's a tie, fallback to numerical.
Also, categories are a MUST with huge indexes, especially if exploration is involved. Why not provide filters based on topic?
Comment: Thanks. The Google's Instant Results process you described is the same as faceted navigation list pattern. But i like the idea of keeping tabs of opened hymns and ranking accordingly


How to gray out SwiftUI's keyboard return key

Question: I'm trying to disable the send key in SwiftUI when there is no text in the textfield. Does anyone knows how to achieve this effect in SwiftUI using Textfield?
 TextField("", text: $text)

Comment: Unfortunately in SwiftUI we have to do things the way it wants them to be done ;-)
Answer: In UIKit we could've used this modifier to disable return key for a textfield it it's text was empty - read here :
https://developer.apple.com/documentation/uikit/uitextinputtraits/1624432-enablesreturnkeyautomatically
However in SwiftUI there is no such modifier at present, instead you could do something like this:
@State private var istextInputted = false
@State private var text = ""

    TextField("Type Here", text: $text)
        .onChange(of: text, perform: { value in
            istextInputted = value.count > 0
        })
        .submitLabel(.done)
        .onSubmit {
            if !istextInputted {
                return
            }
        }
        .foregroundColor(.black)
        .padding()

if your text is empty then on submit it will just return void.


Using Input Type Submit Or Button

Question: I have to use a submit button to submit one of my forms on a website. Is it possible to use the <button> element as a submit button? Do I also add the type="submit" attribute to the <button> element? i.e.
<button type="submit">Go</button>

Answer: Yes, it's possible!
In fact, the <button>'s default behavior is to act as a submit button, so:
<button>Go</button>

Will do what you expect it to! Buttons are also slightly easier to style, and you can keep them consistent with other types of buttons without adding extra rules or selectors in your CSS.

It's worth noting that IE 7 and 6 have some pretty horrible bugs when using <button value="whatever">Something Else</button>. If you want lower IE compatibility and to use the value= attribute, don't use <button>
Comment: According to the specs, *`submit`: Creates a submit button. **This is the default value.*** Emphasis mine. If you want, we can [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29074/html-css-webdesign)
Comment: *"If not go and have a try so you'll learn a lot."*. For an experienced user this sounds exactly as *"I don't know what I'm speaking about"*
Comment: Wrong, [`type=submit` is the default type value](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button). Also see [the specs](http://www.w3.org/TR/html401/interact/forms.html#h-17.5)
Comment: If you use  as a submit you need to add type=submit as well. Otherwise, it is a type=button by default.
Comment: Have you tried put  inside a form element? If not go and have a try so you'll learn a lot.
Comment: [Yes, I have](http://jsfiddle.net/nYgag/1/). Note that the form submits, but Google rejects the request due to same origin policies. See your console and network tab for more details
Comment: It depends then? By the way according to the specs. It needs to declare the type of button anyway "type = submit|button|reset".
Comment: Alright, my experiences tells me that none of the button tag without "type" always act like "button".
Comment: There's something I need to pay a little attention here. According to my experiences - there's a hole in there. This is a prove that with or without type="submit". A  also acts like "SUBMIT". http://fiddle.jshell.net/qqQax/ Thanks for a lesson then.
Comment: This does not work in Firefox.  Button type=submit value is not posted at all when clicked.  Works fine in Chrome.
Comment: @Triynko: I cannot reproduce that. Can you [ask](https://stackoverflow.com/questions/ask) a different question and include an example?
Answer: Following are also 2 types to submit forms

<input type="submit">
The following script

<form id="formid" action="abc.php">
<input type="button" onclick="SubmitFunction()" value="Submit">
</form>

Answer: yes
    You can use but I have heard that If you use the <button> element in an HTML form,
    different browsers may submit different values. Use <input> to create buttons in an HTML form.
Comment: OK, so some information from [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button): "IE7 has a bug where when submitting a form with Click me, the POST data sent will result in myButton=Click me instead of myButton=foo. IE6 has an even worse bug where submitting a form through a button will submit ALL buttons of the form, with the same bug as IE7. This bug has been fixed in IE8". So, to be specific - if you want IE7 compatibility, and want the button to pass a value, don't use it.
Comment: FYI - you should "check it", as it's your answer!
Comment: You've heard? Heard where?
Comment: http://www.w3schools.com/tags/tag_button.asp
Read this link, Hope this satisfies u
Comment: Firefox does not submit the button's value at all.  Same exact page works fine in Chrome and submits the buttons value when clicked.  Standards my ass.

Using Input Type Submit Or Button


Is a PTHP an HVAC option for a super or well insulated structure?

Question: Is a Packaged Terminal Heat Pump a good  HVAC system for a structure that is super insulated or passively insulated assuming the unit is sized and fitted to meet the needs of the structure.
There is not really much mentioned about PTHP and very well insulated buildings. Every publication out there dealing with well insulated structures seems to be all mini split ductless or small duct high velocity hvac systems. Are PTHPs worth considering in place of the other just mentioned options? Below is a potential list of advantages and disadvantages that I came up with for considering a PTHP system, it seems to have some pretty good advantages. Why are we not seeing more of these in well insulated building projects, am I missing something, sans the larger whole in the wall I would think these units would work well where a mini split wall unit would go?

Advantages

more reasonable pricing than ductless split systems
Usually offer inlet fresh air vent, that could be worked into a low cost fresh air vent with a exhaust vent wired into the fan thermostat circuit.
Ususally offer standard 24VAC thermostat control, perfect for smart home integration.
Reasonably efficient depending on which models selected with a range of 10-13 EER.
Usually has back up electrical resistance heat as a 2nd stage heat option for colder climates
Available in under 1 TON sizes as small as 7000 BTUs

Disadvantages

Potential an issue since it will require a large about 43" x 16" hole to be placed in the wall, not sure if this would be a massive air / thermal transfer leak surface area even if a air tight seal is accomplished around the unit
Usually do not have a dedicated de-humidification / dry  mode like many mini ductless systems do
Is not a efficient as mini ductless systems
Answer: The point of a super insulated home or a Passive house is that they rely on the body heat of the occupants plus the heat from the various gadgets in the home to keep them warm, with the insulation slowing the heat loss.
A home built to Passive house standard will usually be fitted with hydronic heating (probably as the new owners are not sure that it will do what it says on the tin.) And the heating may never be used.
Of the 37, 000 Passive houses in the world, 20, 000 or so are in Germany where 92% of the owners are satisfied with their economy.
A true Passive house is almost air tight, with a heat recovery ventilation system, fitted with a in duct heating coil to warm the incoming cold winter air, should it be 3.5C or more lower than the room temperature.
You can see from the above that having a large hole in a wall, albeit sealed with a steel sheet, where a vast amount of heat can escape will defeat the whole point of carefully installed insulation.
Answer: After narrowing my focus from PTAC to PTHP I found an answer. PTHP can be a  practical option for well insulated structures, it really depends on the intended use and the size of building. For smaller open space plan like offices studios, this kind of system appears to work effectively as noted from some answers on Green Building Advisory to a similar question of Heating a small house with a PTHP

I'm planning on doing this. I only found one other guy who has done it, but he's happy:
"Because the house is so compact and highly insulated, we eliminated the central heating system. The air source heat pump, which is like one found in a hotel room both heats and cools. Heat in the lower level is provided by small baseboards in the bedrooms and an electric heater with a fan in the bathroom.
We tracked the performance of one unit from February 1st 2009 to February 1st 2010. The cost to heat the unit came to $185.24 which averages to $30.87/month or $1.03/day. The square footage of the unit is 1150. A separate meter which tracks electric used by the heaters showed 2795.5 kilowatts used during the six month heating season of mid-October to mid-April."
Mini-splits will cost $2500 and up installed, but a PTHP is only about $700. That amount will take a long time to recoup with just a 30-50% better COP.
Yes, it is a "hole in the wall", but so is a window. So, if installed properly, the added heat loss is about like a 26" x 14" window.
A small, superinsulated house is a perfect application since the output of a PTHP is 12,000 btuh, and that should match the house pretty well.
What about when the outside temperature is below 25F? PTHPs have backup resistance heat if necessary, but we ran a yearly simulation that showed that resistance heat was needed for only 4 hours for the entire year in a 1200sq.ft. house.
A PTHP also has a "fresh air" option, that just might save you another $500-$3000 on an HRV
More discussion at http://greenbuildingindenver.blogspot.com/2009/08/mini-splits-or-ptacs-a...
Answered by Kevin Dickson, MSME
  Posted Fri, 10/22/2010 - 10:32
Comment: Sounds like we're also dropping "super" from the equation and focusing on "well".