What are the highest level 80 armour values?

Question: Now that I've reached lv80 I'd like to pickup some lv80 armour items to round out my character. I'm currently using lv70-76 exotics and rares.
So far I can only see three viable options,
1) Orr karma vendors - save up 252k karma and buy a set.
 - Gates of Arah medium coat has 338 armour
2) Order armour - 8g8s
 - Medium coat has 299 armour
3) Craft some armour
 - This option I'm not sure of, or what armour values it has. My leatherworking is about 279 at time of writing
Please can someone show me the various 'tiers' of lv80 armour, where to get them and how much they cost?
I've been poking about on this page, but the information is sparse. http://wiki.guildwars2.com/wiki/List_of_armor_sets
Comment: www.gw2armor.com - This site does not answer your question but it may help you out a bit.
Comment: Other two options are explorable dungeons and WvW.
Comment: I forget option 4 - buy more exotics from the Trading Post.
Answer: First thing to know about items, exotic items have the highest stats possible. Crafting a legendary item won't up the stats, only change the skin (maybe something else, but it won't influence your damage output or resistance).
Considering this, all you need is to find your best way of getting an exotic set.

Farm a dungeon and exchange the dungeons tokens against items (sellers are in Lyon's Arch). The prices are given in the link you posted.
Craft it yourself, you need to be 400 in crafting and you will need lvl 400 crafting components such as Orichalcum and Ectoplams.
Buy it at the trading post. Weirdly, it is there that I have found it the least expensive. It's even cheaper than crafting it yourself (you can get most for 2 or 3 gold a piece).
Karma vendors, but I unfortunately don't know much about these. I don't know if they sell exotic items.

For non-exotic items, they will have weaker stats (rare for example is just a simpler version of the exotic item), but all the same. Two rares of the same type (heavy, medium, light) will have the same armor. So to answer your question, tiers would simply be:

Fine (blue)
Masterwork (green)
Rare (yellow)
Exotic (orange) or Legendary (red)
Comment: So an item with the maximum amount of armour value will always be exotic? So that means that 338 isn't the highest for a medium armour chest piece.
Comment: @DavidYell exotic medium chest armor is 338. Meaning it is maximum value. Rare 80 is 299 and masterwork lvl 80 is 278.
Comment: Ah okay, so Karma Armour is the same level as exotic.


jQuery - each function

Question: I currently have a list of thumbnails that is located in a ul tag as li's.
I am using the Galleria image gallery, but I have more than six images in my gallery, so am I trying to implement a page system.
What I am trying to do is the following:
I have a row of images, row1, when you click on page 2 row1 should hide using this function hide("slide"), and after all of them have hid, row2 should show using show("slide"), but these hide and show functions occur at the same time, I want the hide function to finish before the show function executes, here is my code:
$("a[href^='#']").click(function() {
    if (($(this).attr("href") == "#") && ($(this).attr("rel") != "gallery") && ($(this).attr("href").indexOf("row") < 0)) {
        return false;
    }
    else if ($(this).attr("href").indexOf("row") < 0) {
        $.scrollTo($(this).attr("href"),1000);
        return false;
    } else {
        var href = $(this).attr("href");
        href = href.replace("#","");
        $("ul.galleria li").each(function() {
            if ($(this).is(":visible")) {
                $(this).hide("slide");
            }
        }).;

        $("ul.galleria li."+href).each(function() {
            $(this).show("slide", 800);
        });
        return false;
    }
});

How can I have the hide function execute while the show function waits for a go ahead?
// edit
I have changed my code to the following:
$("ul.galleria li:visible").hide("clip", {direction : "horizontal"},function(){
    $("ul.galleria li."+href).show("clip", {direction : "horizontal"}, 800);
});

But now, the show function runs exactly the number of times as the number of li's that was visible on the previous 'page'. How can I have that function execute only once?
Answer: Use your call-backs. They run immediately after an effect is finished.
$(".item1").slideUp("fast", function(){
  // this is the callback. It will run only when .slideUp completes
  $(".item2").slideDown("fast");
});

Answer: Please try changing this:
$("ul.galleria li").each(function() {
                if ($(this).is(":visible")) {
                        $(this).hide("slide");
                }
        }).;

        $("ul.galleria li."+href).each(function() {
                $(this).show("slide", 800);
        });

to this:
    $("ul.galleria li:visible").hide("slide",function(){
            $("ul.galleria li."+href).stop().show("slide", 800)
     });

Comment: Thank you, this is exactly what I wanted, but the `show` function executes six times exactly, do you have any idea why?
Comment: you probably need to put a stop() because it builds a queue (you have six :visible elements right?)  . I'll update the code.
Answer: Solved it like so:
var counter = 0;
$("ul.galleria li:visible").hide("blind", {direction : "horizontal"},function(){
    counter++;
    if (counter <= 1) {
        $("ul.galleria li."+href).show("blind", {direction : "horizontal"}, 800);
    }
});

Thanks for all the help everyone!

jQuery - each function


Neumann series of the derivative operator

Question: Consider the Nemuann series of the $D=\frac{d}{dx}$ operator: $T = 1 + D+ D^2+...$
Applying T on $x$ yields $x+1$ (i.e., $Tx=x+1$) for $x \in R$.
I would appreciate if someone helps me to resolve the following confusion.
Since the sum above converges, we can rewrite $T$ as $\frac{1}{1-D}$. Now, lets compute $Tx$ as follows:
$Tx=(1 + D+ D^2+...)x=\frac{1}{1-D}x\equiv y \implies y - Dy = x \implies y-y^{'}=x,$
which is a first order differential equation with $y(x)=x+1-ce^{x}$ as the general solution, where $c$ is a constant.
The question: why two different solutions? I understand that the first one is a specific case of the second general solution (with $c=0$). My confusion is that I was expecting to get one solution no matter which method I use. This may sound very basic but I cannot wrap my head around it. Thanks.
Comment: What do you mean when you say "the sum above converges"?
Comment: Maybe that's the problem? $T$ cannot be written as 1/(1-D)?
Answer: When you rewrite $T$ as $T = (I-D)^{-1}$, you are assuming that $I-D$ is invertible. That statements require
(1) a space $X$ where $D$ is defined on, so that it makes sense to say that $I-D:X\to X$ is bijective, and
(2) a reason, after choosing $X$, why $I-D$ is bijective at all.
If $D : X\to X$ is just any bounded linear operator $D:X\to X$ between some Banach space $X$ with operator norm $\|D\|<1$, then the series
$$ T = I+D+D^2 + \cdots,$$
as a series in the space of bounded linear operator on $X$, converges to the inverse of $I-D$.
When $D = \frac{d}{dx}$, I guess one might choose $X$ to be any finite dimensional vector space spanned by $e^{\lambda_i x}$ with $|\lambda_i|<1$, but it might not be very interesting.
In another direction, for each $n\in \mathbb N$, your operator $T$ is defined as a linear operator on $X=P_n$, the space of polynomials in one variables of degree $\le n$. One can easily check that $I-D$ is invertible (e.g. using the standard basis $\{1, x, \cdots, x^n\}$ on $P_n$, the matrix representation of $D$ is strictly upper triangular)
Also, since $D^m = 0$ on $P_n$ whenever $m>n$,
\begin{align}
(I-D) T &= (I-D) (I + D +D^2 + \cdots +) \\
&= (I-D)(I + D + \cdots + D^n) \\
&= I- D^{n+1} = I
\end{align}
and thus $T = (I-D)^{-1}$.
Let $P$ be the space of polynomial in one variables. Since $P = \cup_n P_n$, one checks that $I-D$ is also invertible on $P$ and $T = (I-D)^{-1}$.
Now go back to your calculation, for any polynomial $p\in P$, $y=Tp$ implies
$$\tag {1} y-y' = p,$$
but you have required $y\in P$ in order that $I-D$ is invertible. So what you have proved is just that for any polynomial $p$ there is only one polynomial $y$ which satisfies $(1)$.
Answer: The sum does not converge for all $y(x)$. In particular if the sum converges, then $D^ny(x)$ goes to $0$ when $n\to\infty$. This is only the case when $c=0$ in your example.


Turning the sound off?

Question: Plain and simple question, I know.
I like playing my mobile games while listening to my own music, and having the game's music over it is quite annoying. But somehow, I see no menu option to mute this app!
I even started looking at apps that would enable me to mute specific apps, like the volume mixer in Windows... No success there either.
Comment: I imagine that there's no option in the game itself to mute it because the gameplay and patterns in the game are pretty linked to the music that plays. Based on that, I'm not sure there would ever be an update to add that option.
Comment: Well it is already implemented in the Windows version, as I can see. There is a nice "options" menu in this version, which I cannot think of any reason for it not to be available on the Android one. Plus according to [this page](http://www.edge-online.com/features/six-super-hexagon-tips-from-one-of-the-best-players-in-the-world/2/) some "pro gamers" of Hexagon actually recommend to turn the sound off. (okay, maybe not to replace it with some other music, but they mention the annoyance of the lady's voiceover)
Answer: Unfortunately, the mobile version of Super Hexagon doesn't yet have the option to turn off sound. Hopefully, the developers will update the game to include this feature.

Turning the sound off?


not able to wget a file from link

Question: I am trying to use my terminal to download the xls file from this link
https://www.tase.co.il/_layouts/Tase/ManagementPages/ExcelExport.aspx?sn=none&action=1&SubAction=0&GridId=33&CurGuid={26F9CCE6-D184-43C6-BAB9-CF7848987BFF}&ExportType=1
I made sure the link is good by open the link with chrome and the "download xls file" window shows up
I tried
wget --no-check-certificate https://www.tase.co.il/_layouts/Tase/ManagementPages/ExcelExport.aspx?sn=none&action=1&SubAction=0&GridId=33&CurGuid={26F9CCE6-D184-43C6-BAB9-CF7848987BFF}&ExportType=1
but without any success
the end point is to create cronjob that will download that latest file from this link and put it in a folder /home/vm1/"dropfilehere"
when the xls file name - has the date and time of download
Comment: Have you tried quoting the URL?
Answer: Your URL contains several characters that bash considers as "special": ?, &, '{' and '}'. You may either make these characters non-special with the \ prefix:
https://www.tase.co.il/_layouts/Tase/ManagementPages/ExcelExport.aspx\?sn=none\&action=1\&SubAction=0\&GridId=33\&CurGuid=\{26F9CCE6-D184-43C6-BAB9-CF7848987BFF\}\&ExportType=1

or, place the whole URL inside '' quotes to disable shell interpretation:
'https://www.tase.co.il/_layouts/Tase/ManagementPages/ExcelExport.aspx?sn=none&action=1&SubAction=0&GridId=33&CurGuid={26F9CCE6-D184-43C6-BAB9-CF7848987BFF}&ExportType=1'

not able to wget a file from link


Expected view to be called with a URL keyword argument named "pk"

Question: I'm writing a test for a Django Rest Framework view following closely the testing documentation
Here's my simple test:
def test_patient_detail_api_opens(self):
    factory = APIRequestFactory()
    view =PatientDetailApi.as_view()
    request = factory.get(reverse('api_pacjent', kwargs={'pk' :1}))
    force_authenticate(request, user=self.user)
    response = view(request)
    self.assertEqual(response.status_code, 200)

This test fails with the following message:
AssertionError: Expected view PatientDetailApi to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

I fail to understand why this is happening and how to fix this.

The pk kwargs is there in the URL,
according to the docs there's no need to add the lookup-field value explicitly if it defaults to pk,
the view opens correctly and yet this test fails...

Can somebody please explain why this error occurs?
Here's the relevant code:
the 'main' url.py:
urlpatterns = [
    url(r'^pacjent/', include('pacjent.urls')),
]

pacjent.urls looks like this:
url(r'^api/szczegoly/(?P<pk>\d+)/$', PatientDetailApi.as_view(), name="api_pacjent"),

And PatientDetailApi is this:
class PatientDetailApi(generics.RetrieveUpdateAPIView):
    model = Patient
    serializer_class = PatientDetailsSerializer
    queryset = Patient.objects.all()

    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

Comment: Does it work when you actually request the api outside of your test, eg via Postman? Or if you use the APIClient?
Comment: It does. It was the missing part mentioned by RemcoGerlich. Thanks for your suggestion!
Comment: @user1544500 what will be the API endpoint if you call your API from postman with named argument?
Answer: View functions are called with the request and the arguments from the URL. So pass them:
response = view(request, pk=1)

Comment: OMG, I tried to add it to the `as_view` and then the `factory.get`, then trying to fiddle with the request itself...
Answer: I encountered similar error when I made a mistake of using get_object method in perform_create. Read why this wrong from documentation
perform_create(self,instance):
      instance = self.get_object()


iOS, AFNetworking - "Clear" NSSTring with JSON response

Question: I'm using AFNetworking to get JSON from the server, but response contains a little bit more then just JSON, so I cannot parse it:
<code> array(11) {
   ["something"]=>
   string(4) "none"
   (...)
  }
  [[],{"JSONDataNow":
      (...)
  }]
</code>
Is this possible to remove other data then JSON from string?
Comment: If you can imagine it, you can code it. Yes, possible.
Answer: The server is not returning JSON. It's returning a JSON-like string. Either fix the server to return JSON or write your own custom parser based on the custom rules used by the server.
Attempting to write a pre-processor that turns non-JSON string into JSON is not a good idea. You will have all the difficulties of writing a custom parser with none of the benefits of being the master of your own syntax.


Constructing A Matrix From Know Qualities

Question: I am studying for my linear algebra final, and a question that has appeared on a few past exams is in the general form:
Create an example of a n by n matrix, with one of its eigenvalues equal to x, that is (not) diagonal, is (not) diagonalizable, and is (not) invertible.
The (not)s meaning a specific question may ask for the quality or state is must not have the quality. I'm unsure exactly how to approach this type of question. A specific example of this question type can be seen below:
e.g. Construct an example of a 2×2 matrix, with one of its eigenvalues equal to −1, that is not diagonal or diagonalizable, but is invertible.
if we take: $$\begin{bmatrix}a & b\\c & d\end{bmatrix}$$
then we can deduce both
$$ad-bc \neq 0$$
and
$$(a+1)(d+1)-bc = 0$$
On how to make it not diagonalizable I can see how one could make -1 the only eigenvalue and somehow use an equation to ensure that it's multiplicity is 1. I'm not sure how to do this or how to move on from here. Any help would be appreciated on how to solve the general set of these questions or on how to solve this particular problem.
Thank you for the help.
Answer: A general way to approach such problems is to construct a matrix out of Jordan blocks. The size and content of these blocks will be determined by the conditions of the problem: invertibility affects whether or not zero is an eigenvalue and each known eigenvalue contributes at least one Jordan block. If the matrix is diagonalizable, but not diagonal, you could first construct a diagonal matrix out of the eigenvalues then apply a change of basis to it.
To take your example, since the matrix is not diagonalizable, it must have a Jordan block of size $\ge2$. The matrix itself is only $2\times2$, so it only has room for a single such Jordan block and nothing else. You have a known eigenvalue $-1$ (and in fact it is the only eigenvalue) so the Jordan matrix is $$\left[\begin{array}{rr}-1&1\\0&-1\end{array}\right].$$ This is in a sense the most basic matrix that satisfies the conditions of your example, but any matrix similar to this one will also fit the bill.
Comment: Do you know of any good sources off-hand where I can learn about Jordan blocks? We didn't learn about them but more tools are usually better.
Comment: @ParkerWieck If you've covered eigenvalues, eigenvectors and diagonalization, then surely the Jordan normal form of a matrix came up at some point. Jordan blocks are the subunits of the Jordan normal form.
Comment: Nope, it never came up. This is the first I've ever heard of it! It sounds like something good to know based off your surprise so I'll be sure to research them.
Comment: @ParkerWieck Perhaps it's a topic to be covered in the next term ;) The basic idea is that even non-diagonalizable matrices are similar to a sort-of diagonal matrix. Instead of having just eigenvalues along the main diagonal, the diagonal elements can also be small square submatrices that represent either a simple rotation or the sum of a multiple of the identity and a nilpotent operation.
Answer: Hint:
If a matrix, $A \in \mathbb{R}^{2 \times 2}$ has $2$ distinct eigenvalues, then it must be diagonalizable. Hence both of the eigenvalues must be $-1$.
Verify that $$\begin{bmatrix} -1 & 1 \\ 0 & -1  \end{bmatrix}$$ satisfy the condition by checking that it is not diagonalizable.
Edit to response to OP's further question:
For $A\in \mathbb{R}^{4 \times 4}$, we can consider the matrix
$$\begin{bmatrix} -1 & 1  & 0 & 0\\ 0 & -1 & 0 & 0 \\ 0 & 0 & -1 & 0\\
0 & 0 & 0 & -1 \end{bmatrix}$$
If we consider the matrix $A-\lambda I$, we get
$$A-\lambda I =\begin{bmatrix} 0 & 1  & 0 & 0\\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 \end{bmatrix}$$
We can see the $$nullity(A-\lambda I)=n-1 < n,$$ hence the geometric mulitplicity corresponding to $-1$ is less than $n$.
Comment: this matrix is invertible...
Comment: huh, he wants an invertible matrix isn't it?
Comment: not clear from OP because of the *(not)*.
Comment: hmmm... I was trying to answer the part about the specific example, $-1$ as eigenvalue, not diagonalizable but invertible.
Comment: the (not)s were that the question appears in several different forms. The example I gave is a specific one in which case it must be invertible.

This is a solution as I have just confirmed, how did you get here? How would you approach a similar question that is, say, 4 by 4?
Comment: Edited my response to handle $4$ by $4$.
Comment: I'll have to research nullity, thank you for the edit!


Free & private version control hosting website

Question: Any good Git or Subversion for non-public/non-open project. I have narrowed it down to these three. Now which of the 3 would you recommend. I am looking for secure, with a good up-time, private, support for 3-4 users and 1 repository and a space of about >200-300 MB

assembla - http://offers.assembla.com/free-subversion-hosting/
unfuddle - http://unfuddle.com/about/tour/plans
xp-dev - http://xp-dev.com/pricing

I know GitHub is awesome for but it's free for public/open projects only and Google Code is only for open project. Am i right over here and what about SoundForge is it also for  public projects.
Comment: So you are looking for a hoster, not version control software? Do you need a server? i.e. are you working on multiple machines on the same time?
Comment: what about mercurial? have you considered that? bitbucket fits your needs for mercurial.
Comment: $12 a month is too much? With a free service you can never know if they are going to discontinue it at some point... besides that, you already said you like github. Anyway, if you have a server consider hosting the repository for yourself. You could install [gitorious](http://gitorious.org/gitorious) and have something github-ish for free.
Comment: @knittl I am looking specifically for version control only
Comment: @WebDeveloper: I don't understand. "Version Control only"? Version Control is a thing to do, version control systems is the software to use. And yet in your question you are listing hosting providers and ask which of them is best …
Comment: @knittl OH now i get what u mean now. I am looking for VC hosting. Do you recommend anything
Answer: I use assembla.
It's free and it's working great :) never had any problems with it.
Answer: Perhaps you will approach Mercurial and bitbucket.org? This solution very simple and has a private repo.
Comment: Since yesterday, Bitbucket supports Git repositories as well: http://blog.bitbucket.org/2011/10/03/bitbucket-now-rocks-git/ (also private in the free plan)
Comment: Yep, and it's absolutelly free =)


Can I pause SlidesJS on click?

Question: I am using SlidesJS for a slideshow and I was wondering if there is a way to pause and play the slideshow on click of a button?
Answer: I recommend grabbing the most current version from github looks like in this new version its as simple as calling stop() and play()
He has an example here showing how as well, notice the bottom left, has the option to play and stop.
http://beta.slidesjs.com/examples/standard/
Answer: Your required functionality will work in the Slides 2 beta, but not in any version below 2
you can check out how it works here : https://github.com/nathansearles/slides/
Answer: In your jquery.slides.js file do a search for _this.stop(true);
It shows about 3-4 times, next & previous click.. and you will also see it showing for paginationLink.click
The problem i was having was the slider was stop sliding after click either previous, next or pagination. I needed the slider to restart.. so what i did was add a setTimeout to play()
_this.stop(true);

setTimeout(function ()
{ _this.play(true) }, 3000);

Can I pause SlidesJS on click?


Do I have to have an exhaust fan above my stove?

Question: My stove is smack dab next to the back door (which is easy to open and close).  Do I have to have a functioning exhaust fan?  Or can I just close it off to solve a draft problem I am having?
And same question for the bathroom.
These fans were but in by a DIY enthusiast before we bought the house.  They do a lousy job of venting when they're turned on, and they're giving me horrible drafts.
Comment: Electric stove.  Upstate NY.
Comment: You don't _have_ to have one, usually, but you should want one; it keeps your whole house cleaner by sucking out greasy fumes before they settle on cabinets, counters, baseboards, even ceilings. This not only makes your place cleaner, it reduces the grease surface area which when large, attracts insects and rodents. Inside-only fans use an ineffective grease filter that doesn't help nearly as much as pumping it all outside would. Cover the openings with lids made from styrofoam insulation to avoid drafts, but don't shoot yourself in the foot by removing a very good thing.
Comment: I know that exhaust fans in bathrooms and certain other rooms with no windows are required, but not sure about the vent hood.  Is it a gas stove?  That might make a difference.  Also, what is the location?
Comment: @dandavis - Opening the back door would not give as good a result, I take it. // Can you tell me more about your styrofoam idea?
Comment: you just trace out a template of the vent opening with AL foil, then transfer to a sheet of pink house insulation or whatever. You can embed magnets into the foam if your duct grill is steel, or velcro if not. You just pop it on when you're not cooking, take it off when you are or all fall/spring as needed. Wall/Contact paper can dress it up for cheap. You can use weather stripping along the peremiter to get a good tight seal if needed. You can also buy [pre-made ones](https://www.alibaba.com/product-detail/lr003458-lr045003-insulation-engine-hood-for_60863163269.html), but that's not DIY.
Comment: @dandavis - The inspiration and the installation would be in keeping with the DIY mindset. // I don't understand how to use it.  There is a metal grill right now.  Are you saying I would put this thingie over top of the grill?  To get a tight fit, I'd have to cut away maybe 1/4 inch, over a square (the shape of the grill).  Do you use one?  A picture would be very helpful.
Comment: well i did, then i moved... Yes, it "snaps" onto the grill, and should be about the same dimesions or slightly larger. You can decorate with paper/cloth/contact/paint, or press-on tiles to match a backsplash. you can cut a lip with a box cutter or xacto. I smooshed mine onto the meta grill/filter to trace it, then drilled small shallow holes on the 4 corners of the foam and hot-glued super magnets into those holes to hold in place.
Comment: @dandavis and it's not a fire hazard?
Comment: I'd check how the fan ducting was run, make sure it's stretched out all the way and hasn't collapsed/...
Comment: @ThreePhaseEel - I haven't turned it on since I moved in in August.  How is that going to make my kitchen warmer?
Comment: @aparente001 -- a collapsed or unstretched flex duct would explain why the fans do a lousy job of venting at least...
Comment: @dandavis - I'm now ready to cover my vent as you suggested, but I'm concerned about fire safety.  I have a careless teenager.  I haven't been able to figure out if there's a type of foam insulation board that is fireproof.  Do you want me to write a Question?
Comment: some experiments: run the stove on high for 5 mins with no pot and with the fan off and feel the grill. it shouldn't be hot enough to catch anything on fire. also try burning the material you choose; it shouldn't go up like a torch. Most these days have legal fuel load considerations, some might be relatively fire-proof. Boric acid (roach powder) can treat textiles to make them flame proof. You can make a rigid foam light enough to float with concrete+soap and forced air. Rockwool, charcloth, vermiculite, perlite, and steel wool can insulate w/o fuel load.
Comment: @dandavis - My concern is my teenager.  He has Tourette Syndrome and has been known to start a harebrained kitchen project at 2 am under the effects of insomnia.  He knows he's not supposed to fry things in oil when a parent isn't handy, but he's extremely impulsive.  Imagine a three-year-old that's six foot two, eyes of brown.  May I skip the five-minute heating experiment?
Comment: You'll know best what to do. I'm just trying to offer some ideas. A lot of hoods have plastic bulb covers, so absolute fire proofness may not be required: fans are often left off after all...
Answer: Yes, the Code requires an exhaust vent capable of a minimum for 150 cfm. (See M1507.3 and Table M1507.3)
The duct shall be metal and extend to the exterior.
If the exhaust fan exceed 400 cfm, then makeup air is required. (See IMC Chapter 5)


Referencing a resource in a ResourceDictionary from a different ResourceDictionary in Silverlight

Question: I have the following set of code in my App.xaml:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Client.Common;component/Theme/Brushes.xaml"/>
            <ResourceDictionary Source="/Client.Common;component/Theme/Fonts.xaml"/>
            <ResourceDictionary Source="/Client.Common;component/Theme/CoreStyles.xaml"/>
            <ResourceDictionary Source="/Client.Common;component/Theme/SdkStyles.xaml"/>
            <ResourceDictionary Source="/Client.Common;component/Theme/MyAppName.xaml"/>

            <ResourceDictionary Source="/Client.Common;component/Controls/NavigationPanel.xaml"/>
         </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

The NavigationPanel.xaml contains a style that looks like this:

The {StaticResource DarkBackground} is defined in the Brushes.xaml file (i.e. the first resource dictionary).  It is defined as
<SolidColorBrush x:Key="DarkBackground" Color="#FF707176" />

in the resource dictionary.
At runtime, I get the following error:
Cannot find a Resource with the Name/Key DarkBackground [Line: 16 Position: 44]

The line numbers and position references the NavigationPanel.xaml resource dictionary in the app.xaml.
I can reference the brush from other controls, just not the included resource dictionary.
Why can I not reference or why does it not resolve the reference to a resource that is higher in the heirarchy of the merged resource dictionary??  What am I missing here?
Answer: Are you referencing the DarkBackground brush in any of the resources in the NavigationPanel dictionary?
If you are you might need to merge the Brushes resource dictionary into the NavigationPanel dictionary.
So in the NavigationPanel dictionary.
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Client.Common;component/Theme/Brushes.xaml" />
</ResourceDictionary.MergedDictionaries>

Comment: This does work and I understand why it resolves now but why does it not resolve when it is in the higher level dictionary?  I am marking your answer as correct, but I would love an explanation if you know why this is.
Comment: Found this in another thread. Leaving here for posterity. https://social.msdn.microsoft.com/forums/windowsapps/en-US/2be9a5f6-5313-448d-a9d9-296bac42215e/using-style-defined-in-merged-dictionary-from-another-merged-dictionary?forum=wpdevelop Thanks and credit to Kamil Nieweglowski for this.
Answer: You can include one dictionary in another (like 'using' in C#) like so:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
    xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:Controls="clr-namespace:APC.IKM.UI.SL.Controls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Brushes.xaml"/>
        <ResourceDictionary Source="Fonts.xaml"/>
        <ResourceDictionary Source="CoreStyles.xaml"/>
    </ResourceDictionary.MergedDictionaries>

Is this what you are looking for? The Cosmopolitan / Metro project template has a good example of this...
Answer: the trully answer is Eric's answer in this site: https://social.msdn.microsoft.com/forums/windowsapps/en-US/2be9a5f6-5313-448d-a9d9-296bac42215e/using-style-defined-in-merged-dictionary-from-another-merged-dictionary?forum=wpdevelop.

the Brushes.xaml and the NavigationPanel.xaml is parsed independently and then added to the merged dictionary of Application resources so they don't know anything about each other.


D3 world map jumps around when dragging

Question: I'm trying to make a world map in Vue which I can drag to move around, and zoom in. I've been trying to use D3, however I can't get it to work properly as every time I drag the map it jumps to the bottom right of the page and I can't figure out why for the life of me. The following is an example where you can see the map jump the second I start dragging.

All documentation and stackoverflow content I can find is using an older version of d3 which uses a completely different syntax and i can't find any good solutions to the problem other than someone mentioning that I need to somehow calculate the zoom.
Does anyone know what I'm doing wrong?
<template>

    <svg class="canvas" :viewBox="`0, 0, ${defaultWidth}, ${defaultHeight}`">
      <g class="graphic"></g>
    </svg>

</template>

Answer: Found the answer by looking at this post. Turns out I had to be using dx and dy instead of x, and y. The final code looked like this:
onDrag(event) {
  const graphic = this.graphic.select('g')
  const matrix = graphic.node().transform.baseVal.consolidate().matrix
  const [x, y] = [matrix.e + event.dx, matrix.f + event.dy]
  graphic.attr('transform', `translate(${x}, ${y})`)
}

D3 world map jumps around when dragging


python integral calculation without using for loop

Question: I want to implement a python program, which can calculate this integral

I know how to make it using For Loop and it will look something like this
import numpy as np;

def numint(f,alpha,beta,N,b,c):
    s = np.size(b);
    x = np.linspace(alpha,beta,N);
    h = x[1]-x[0];
    result = 0;
    result1 = 0;
    for j in range(1,N+1):
        for i in range(1,s+1):
           result1+=b[i]*f(x[j-1]+h*c[i]);
        result+=h*result1;
        result1 = 0;
    return result;

Without loop I think it should be something like this:
def numint(f,alpha,beta,N,b,c):
    s = np.size(b);
    x = np.linspace(alpha,beta,N);
    h = np.ones(N,dtype=int)*(x[1] - x[0]);
    result = 0;
    result = np.sum(h[1:N+1] * np.sum(b*(f(x[0:N]+h[0]*c))));
    return result;

But the second part of the result = np.sum ... is wrong and I dont know how to fix it . Any suggestions ?
EDIT :
def numint(f,alpha,beta,N,b,c):
    s = np.size(b);
    x = np.linspace(alpha,beta,N);
    h = np.ones(N,dtype=int)*(x[1] - x[0]);
    functionResult = f(x+h*c);
    dif = np.diff(functionResult);
    result = 0;
    result = np.sum(h[1:N+1] * np.sum(b*dif.sum()));
    return result;

As a tip : vectorize them
but I don't know how to use it
Answer: What you are looking for is the np.diff function.
Say you are looking for the integral from 0 to 10 for f(x) = x^2 with F(x) = (x^3)/3:
x = np.linspace(0, 10, 1000)
F = lambda x: x**3/3
b = F(x)

dif = np.diff(b)

sum = dif.sum()

print(sum)
333.33333333333326

Actual result is 333.3...
You can replace F by any function you want, but the key is np.diff which decreases the size of your array by one. Then, just sum the differences along your interval and you have your result.
You can improve the precision of your result by simply increasing the number of steps (1000 in my example).
Comment: Oh , sorry but I'm not sure how  exactly to use this in my code. My function should calculate the quadrature formula for the numerical integration . Can you show me how to use this diff function .
Comment: b = f(x+h*c)
dif = np.diff(b);
and then use this one ?
Comment: Can you tell me if my edit is that what you showed me ?
Comment: I am not quite sure, whether you actually got the function right that calculates the integral. Do you have any reference where you got the equation from, meaning the Latex equation.


I know my root password, so where do i type it to open this file?

Question: I have my root password, and just installed a keylogger for myself and after losing a long chunk of text i worked really hard on to a program crash. The keylogger installed just fine, using my root password in the terminal worked fine to, set the output file and started it.
Now how do i look at the output file? Under permissions, it say's that only root can read/write. How do i log in as root?
Comment: That is annoying indeed. It should ask if you want to open as administrator when you are in the admin group. Perhaps we can get it in 12.10?
Answer: I wouldn't start a file browser instance with gksu to open a file.  I would use:
gksudo gedit /the/full/path/to/the/file

Or any other text editor it's easy to copy paste multi-page text from for that matter.
Comment: No problem.  Do be careful with bouncing about as root though.  Some editors save preference files that might get re-written as root and you can have problems down the road.
Answer: Enable open as administrator in nautilus!
To get started, press Ctrl – Alt – T on your keyboard to open Terminal. When it opens, run the commands below:
enter code here
sudo apt-get install nautilus-gksu

After installing that application run copy and paste the line below and press enter.
sudo cp /usr/lib/nautilus/extensions-2.0/libnautilus-gksu.so /usr/lib/nautilus/extensions-3.0/

Finally, log out and back in then go and test it, by clicking your right mouse click on the file you want to run as Admin and your see a popup menu with the words: open as administrater.

Visit: http://www.liberiangeek.net/2011/12/add-open-as-administrator-to-nautilus-context-menu-in-ubuntu-11-10-oneiric-ocelot/ for help and from here.
Enjoy!
Answer: First, Open Terminal
Type:
gksu nautilus <location>

will help to navigate as root.
sudo gedit <location>

will help to open / edit too.
Comment: Won't Gedit automatically be run as root if you run Nautilus as root and use it to open a file?


Handling blank values from a soap webservice in SoapUI output to Excel

Question: I have a SoapUI project and test suite that reads values from Excel, puts them into a SOAP request, sends the request and gets its response, and writes the response values to another Excel spreadsheet.  So far, so good.
When the web service returns an empty value, however, SoapUI writes a namespace tag to the spreadsheet <xyz:transactionUID xmlns:xyz="http://xyz.abc.etc">.  I would like a way to have SoapUI write nothing to the cell when nothing comes back from the web service.
Anyone know how to do this?
EDIT:
Here is the XPath used to write the value to the spreadsheet:
${myRequest#Response#declare namespace xyz='http://xyz.abc.etc.service'; //xyz:MyOutputWrapper[1]/xyz:MyVerifyResponse[1]/xyz:IdMatchIndicators[1]/xyz:FrstNmMatchInd[1]}
i.e., this is the 'value' under 'name/value' in the properties for the DataSink step.
Comment: What **exactly** is the value - I assume it is going to be some XPath - that is written?
Comment: I should have thought of putting that in; I've now added it to the question.
Answer: SoapUI takes some liberties with your XPath.
First, note that for reading you can greatly simplify your XPath by dropping the namespaces:
${myRequest#Response#//*:MyOutputWrapper[1]/*:MyVerifyResponse[1]/*:IdMatchIndicators[1]/*:FrstNmMatchInd[1]}

Next, for multiple matches SoapUI will always grab the first:
${myRequest#Response#//*:MyOutputWrapper/*:MyVerifyResponse/*:IdMatchIndicators/*:FrstNmMatchInd}

Lastly, and this is the important one for your case, if the matched node has a text() node, SoapUI will use that. If there is no text() node, it will give you the whole node ... which is exactly what you are seeing. In your case, because you do not want that behaviour, you need to explicitly state that you want the text() node:
${myRequest#Response#//*:MyOutputWrapper/*:MyVerifyResponse/*:IdMatchIndicators/*:FrstNmMatchInd/text()}

Comment: Thank you very much!  I don't know much of anything about XPath, just heard of it doing this with SoapUI, and didn't enter these myself -- the XPath expression as I gave it to you is the one SoapUI enters for me when I choose the node using the SoapUI, uh, UI (including the namespaces).


Future' is not a subtype of type 'Stream>

Question: I am trying to fetch the data from API using StreamBuilder, Kindly help with this error

Future<dynamic>' is not a subtype of type 'Stream<List<dynamic>>.

Basically we are fetching data and displaying data with help of ListView.buider and StreamBuilder:
Search_product.dart
import 'dart:async';

import 'package:beauty/user.dart';
import 'package:flutter/material.dart';
import 'package:beauty/backend.dart';

class SearchProduct extends StatefulWidget {
  @override
  _SearchProductState createState() => _SearchProductState();
}

class _SearchProductState extends State<SearchProduct> {
  List<Welcome> _welcome;
  Backend backend = new Backend();
  bool waiting = true;
  Stream _stream;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Backend.getData().then((welcome) {
      setState(() {
        _welcome = welcome;
        waiting = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xFFEBEAEF),
        appBar: AppBar(
          title: Row(children: [
            SizedBox(
              width: 70.0,
            ),
            Text(
              'Search Product',
              style: TextStyle(
                color: Colors.black,
              ),
            ),
            SizedBox(
              width: 70.0,
            ),
            Flexible(
              child: CircleAvatar(
                child: Image.asset('assets/her.png'),
              ),
            ),
          ]),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.black,
            ),
            onPressed: () {},
          ),
          backgroundColor: Color(0xFFEBEAEF),
        ),
        body: Column(children: [
          Container(
            color: Colors.white70,
            child: TextField(
              decoration: InputDecoration(
                prefixIcon: Icon(
                  Icons.search,
                  color: Colors.grey,
                ),
                hintText: 'Search  for product',
                contentPadding:
                    EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.white70, width: 1.0),
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.white70, width: 2.0),
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
              ),
              style: TextStyle(color: Colors.black),
            ),
          ),
          Container(
            child: waiting
                ? SizedBox(
                    width: 50,
                    height: 50,
                    child: CircularProgressIndicator(),
                  )
                : Expanded(
                    child: StreamBuilder(
                        stream: Backend.getData(),
                        builder: (BuildContext context,
                            AsyncSnapshot<List<dynamic>> snapshot) {
                          return ListView.builder(
                              padding: EdgeInsets.all(8),
                              itemCount: null == _welcome ? 0 : _welcome.length,
                              itemBuilder: (BuildContext context, int index) {
                                Welcome welcome = _welcome[index];
                                return Card(
                                  child: Column(
                                    children: <Widget>[
                                      ListTile(
                                        leading: CircleAvatar(
                                          radius: 30,
                                          backgroundImage: NetworkImage(snapshot
                                              .data[index].welcome.image),
                                        ),
                                        title: Text(
                                            snapshot.data[index].welcome.title),
                                        subtitle: Text(snapshot
                                            .data[index].welcome.description),
                                        trailing: Text(snapshot
                                            .data[index].welcome.price
                                            .toString()),
                                      )
                                    ],
                                  ),
                                );
                              });
                        }),
                  ),
          ),
        ]));
  }
}

Backend.dart
import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:beauty/user.dart';

class Backend {
  static getData() async {
    try {
      var url = Uri.parse('https://fakestoreapi.com/products');
      var response = await http.get(url);
      if (response.statusCode == 200) {
        return welcomeFromJson(response.body);
      } else {
        List error_message = ['error'];
        return error_message;
      }
    } catch (e) {
      print(e);
    }
  }
}

user.dart
    import 'dart:convert';

    List<Welcome> welcomeFromJson(String str) =>
        List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

    String welcomeToJson(List<Welcome> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

    class Welcome {
      Welcome({
        this.id,
        this.title,
        this.price,
        this.description,
        this.category,
        this.image,
        this.rating,
      });

      int id;
      String title;
      double price;
      String description;
      Category category;
      String image;
      Rating rating;

      factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
            id: json["id"],
            title: json["title"],
            price: json["price"].toDouble(),
            description: json["description"],
            category: categoryValues.map[json["category"]],
            image: json["image"],
            rating: Rating.fromJson(json["rating"]),
          );

      Map<String, dynamic> toJson() => {
            "id": id,
            "title": title,
            "price": price,
            "description": description,
            "category": categoryValues.reverse[category],
            "image": image,
            "rating": rating.toJson(),
          };
    }

    enum Category { MEN_S_CLOTHING, JEWELERY, ELECTRONICS, WOMEN_S_CLOTHING }

    final categoryValues = EnumValues({
      "electronics": Category.ELECTRONICS,
      "jewelery": Category.JEWELERY,
      "men's clothing": Category.MEN_S_CLOTHING,
      "women's clothing": Category.WOMEN_S_CLOTHING
    });

    class Rating {
      Rating({
        this.rate,
        this.count,
      });

      double rate;
      dynamic count;

      factory Rating.fromJson(Map<String, dynamic> json) => Rating(
            rate: json["rate"].toDouble(),
            count: json["count"],
          );

      Map<String, dynamic> toJson() => {
            "rate": rate,
            "count": count,
          };
    }

    class EnumValues<T> {
      Map<String, T> map;
      Map<T, String> reverseMap;

      EnumValues(this.map);

      Map<T, String> get reverse {
        if (reverseMap == null) {
          reverseMap = map.map((k, v) => new MapEntry(v, k));
        }
        return reverseMap;
      }
    }

Answer: The response type from Backend.getData is a Future, not a Stream.
Replace
StreamBuilder(
  stream: Backend.getData(),
  builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {

with
FutureBuilder(
  future: Backend.getData(),
  builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
    //show visual loading
    if(!snapshot.hasData) return Center(child: CircularProgressIndicator());

Answer: The error occurred because of type mismatch.

Current
Expected

Expected data
List<dynamic>
List<Welcome>?

stream
Future<dynamic>
Stream<List<Welcome>?>

snapshot
AsyncSnapshot<List<dynamic>>
AsyncSnapshot<List<Welcome>?>

StreamBuilder expects a stream instead of Future<T>.
If you expect new data coming from Future, you may consider using FutureBuilder instead.
So, here's how we fix it.

Create a StreamController
Pass the stream currently controlled by StreamController to StreamBuilder so it can listen for new data event
Call getData(), wait until it completes and returns expected data List<Welcome>? (can be a list of Welcome if successful or null if failed)
Next, send the data as data event to the stream
We also have to check the event data and connectionState, then handle them accordingly, e.g. display CircularProgressIndicator() while waiting for data, or certain widget when data exists.

The revised code follows the above steps so it should be easy to understand.
search_product.dart
import 'package:flutter/material.dart';
import 'user.dart';
import 'backend.dart';

class SearchProduct extends StatefulWidget {
  @override
  _SearchProductState createState() => _SearchProductState();
}

class _SearchProductState extends State<SearchProduct> {
  Backend backend = Backend();

  @override
  void initState() {
    super.initState();
    backend.addDataToStream();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFEBEAEF),
      appBar: AppBar(
        title: Row(children: [
          SizedBox(
            width: 70.0,
          ),
          Text(
            'Search Product',
            style: TextStyle(
              color: Colors.black,
            ),
          ),
          SizedBox(
            width: 70.0,
          ),
          Flexible(
            child: CircleAvatar(
                //child: Image.asset('assets/her.png'),
                ),
          ),
        ]),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {},
        ),
        backgroundColor: Color(0xFFEBEAEF),
      ),
      body: Column(
        children: [
          Container(
            color: Colors.white70,
            child: TextField(
              decoration: InputDecoration(
                prefixIcon: Icon(
                  Icons.search,
                  color: Colors.grey,
                ),
                hintText: 'Search  for product',
                contentPadding:
                    EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.white70, width: 1.0),
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.white70, width: 2.0),
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
              ),
              style: TextStyle(color: Colors.black),
            ),
          ),
          Expanded(
            child: StreamBuilder<List<Welcome>?>(
              initialData: null,
              stream: backend.welcomeStream,
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                  case ConnectionState.none:
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  case ConnectionState.active:
                  case ConnectionState.done:
                    if (snapshot.hasError) {
                      return Text('Error happened!');
                    }
                    var data = snapshot.data;
                    if (data == null) {
                      return Text('No data!');
                    }
                    return ListView.builder(
                      padding: EdgeInsets.all(8),
                      itemCount: data.length,
                      itemBuilder: (BuildContext context, int index) {
                        Welcome? welcome = data[index];
                        return Card(
                          child: Column(
                            children: <Widget>[
                              ListTile(
                                leading: CircleAvatar(
                                  radius: 30,
                                  backgroundImage: welcome.image == null
                                      ? null
                                      : NetworkImage(welcome.image!),
                                ),
                                title: Text(welcome.title ?? ''),
                                subtitle: Text(welcome.description ?? ''),
                                trailing: Text(welcome.price.toString()),
                              )
                            ],
                          ),
                        );
                      },
                    );
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}

backend.dart
import 'dart:async';
import 'package:http/http.dart' as http;
import 'user.dart';

class Backend {
  StreamController<List<Welcome>?> _welcomeController = StreamController();

  Stream<List<Welcome>?> get welcomeStream => _welcomeController.stream;

  Future<void> addDataToStream() async {
    await getData()
        .then((List<Welcome>? value) => _welcomeController.add(value));
  }

  static Future<List<Welcome>?> getData() async {
    try {
      var url = Uri.parse('https://fakestoreapi.com/products');
      var response = await http.get(url);
      if (response.statusCode == 200) {
        return welcomeFromJson(response.body);
      } else {
        print(response.statusCode);
        return null;
      }
    } catch (e) {
      print(e);
    }
  }
}

user.dart
import 'dart:convert';

List<Welcome> welcomeFromJson(String str) =>
    List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Welcome {
  Welcome({
    this.id,
    this.title,
    this.price,
    this.description,
    this.category,
    this.image,
    this.rating,
  });

  int? id;
  String? title;
  double? price;
  String? description;
  Category? category;
  String? image;
  Rating? rating;

  factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        id: json["id"],
        title: json["title"],
        price: json["price"].toDouble(),
        description: json["description"],
        category: categoryValues.map[json["category"]],
        image: json["image"],
        rating: Rating.fromJson(json["rating"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "title": title,
        "price": price,
        "description": description,
        "category": categoryValues.reverse?[category],
        "image": image,
        "rating": rating?.toJson(),
      };
}

enum Category { MEN_S_CLOTHING, JEWELERY, ELECTRONICS, WOMEN_S_CLOTHING }

final categoryValues = EnumValues({
  "electronics": Category.ELECTRONICS,
  "jewelery": Category.JEWELERY,
  "men's clothing": Category.MEN_S_CLOTHING,
  "women's clothing": Category.WOMEN_S_CLOTHING
});

class Rating {
  Rating({
    this.rate,
    this.count,
  });

  double? rate;
  dynamic count;

  factory Rating.fromJson(Map<String, dynamic> json) => Rating(
        rate: json["rate"].toDouble(),
        count: json["count"],
      );

  Map<String, dynamic> toJson() => {
        "rate": rate,
        "count": count,
      };
}

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String>? reverseMap;

  EnumValues(this.map);

  Map<T, String>? get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}


How to save authenticated username into a database

Question: I'm just a beginner to Spring and Spring Security. Here I'm creating a Spring MVC application with Spring Security. I just want to save authenticated username into a database. Using following form I'm getting the logged username. But I don't know how to save that username using path="" attribute.
This is the form
<form:form modelAttribute="reservation">

        Name

        <sec:authentication var="user" property="principal" />
        <sec:authorize  access="isAuthenticated()">
            ${user.username}
        </sec:authorize>

        Email
        <form:input path="emailAddress"/>

Here is the controller
@RequestMapping(value="/flight-reservation", method={RequestMethod.POST})
public String doReservation(@Valid @ModelAttribute("reservation") FlightReservation reservation ,BindingResult result){
    if(result.hasErrors()){
        return "flight-reservation";
    }
    reservationService.save(reservation);
    return "redirect://flight-reservation.html?ok=true";
}

I can save email using path="emailAddress" But my question is how to save that logged username using path of something else. I appreciate your help.
Answer: Thanks to Spring security integration in Spring MVC, you directly get principal as a controller parameter:
@RequestMapping(value="/flight-reservation", method={RequestMethod.POST})
public String doReservation(@Valid @ModelAttribute("reservation") FlightReservation reservation,
        BindingResult result, @AuthenticationPrincipal Principal principal){
    // use principal (Authentication.getPrincipal) to extract user name and use it
    ....

This one is valid since Spring Security 3.2 If you use an older version, you must use the SecurityContextHolder:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Principal principal = authentication == null ? null : authentication.getPrincipal();

Assuming that your authentication object returns a UserDetails, you could use it that way:
@RequestMapping(value="/flight-reservation", method={RequestMethod.POST})
public String doReservation(@Valid @ModelAttribute("reservation")
        FlightReservation reservation ,BindingResult result,
        @AuthenticationPrincipal UserDetails details){
    if(result.hasErrors()){
        return "flight-reservation";
    }
    reservation.setUser(details.getUserName); // adapt it to your real classes...
    reservationService.save(reservation);
    return "redirect://flight-reservation.html?ok=true";
}

That mean you use ${user.username} in the JSP to display current authenticated user name, but you get it directly from Spring security in your controller, store it in your reservation object that already contains the other fields initialized via the form and pass the object containing th user name (or whatever it contains representing the authenticated user) to the service. That way, Spring security guarantees that the user written in the database is the authenticated user even it somenone tries to send a forged request.

Alternatively, Spring Framework Reference explicitely says that you can pass a Principal parameter to a @RequestMapping annotated method, and the parameter will recieve the currently authenticated user. In fact you get request.getUserPrincipal that was populated with the Spring Security Authentication
So you can simply write:
@RequestMapping(value="/flight-reservation", method={RequestMethod.POST})
public String doReservation(@Valid @ModelAttribute("reservation") FlightReservation reservation,
        BindingResult result, Principal principal){
    Authentication auth = (Authentication) principal;

or directly as Authentication implements Principal
@RequestMapping(value="/flight-reservation", method={RequestMethod.POST})
public String doReservation(@Valid @ModelAttribute("reservation") FlightReservation reservation,
        BindingResult result, Authentication auth){

and get the user name from there.
Comment: Thanks for the mention @serge , but I'm using Spring Security 4.0.1 and Spring 4.1.6. It is working that getting logged username using `${user.username}` May I know is there anyway to pass that value to the database ?
Comment: @sarge I tried as you said. I set `@AuthenticationPrincipal User user`, User is my entity for users. Then I set `reservation.setName(user.getName());` But after running this code and when I check user table, it is saving a null for `name`. Am I correct according to above corrections ?
Comment: Insted of using `@AuthenticationPrincipal` I've used `Authentication`. It works well and save the name into the database. Is it correct ? If it is correct please edit your answer then I can mark your answer as the answer for my question. Thank you
Comment: Thank you so much for your explanations. All doubts are resolved.


Boost.Filesystem create_directories mangles directory name

Question: I am trying to make a directory using Boost.Filesystem (the directory can be provided by the user, so it may be a path with nested directories; all, some, or none of the directories in that path may exist to start).  When I run the program, a directory is created, but it is not what I asked for; the string containing the path appears to be getting mangled.  I never get the same result twice, but the name of the directory always starts with a colon.
A minimal example:
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main(int argc, char* argv[]) {
    fs::path path = "junk/morejunk";
    if (!fs::create_directories(path)) {
        std::cerr << "Failed to create directory " << path << ".\n";
    }
    return(0);
}

Running that, I get directories such as :@K%C5?, :%C0)%E0?, and :%C0%E9%93?.
I had some trouble getting Boost to link correctly, but the above program compiles and runs now.  In case it's necessary, some information:
-- I'm using a Mac (OSX 10.9.4)
-- GCC and Boost both installed with MacPorts (Boost with the +gcc49 option)
-- GCC version 4.9.2_1
-- Boost version 1.57.0_1
-- my Makefile looks like
CC = /opt/local/bin/g++
FLAGS = -I/opt/local/include -L/opt/local/lib -lboost_system-mt -lboost_filesystem-mt
driver : driver.cpp
    $(CC) $(FLAGS) -o driver driver.cpp

Any suggestions welcome; it's been a while since I've used C++ much, and I'm not very experienced with Boost.
Answer: Out on a limb, make sure you save your file as ASCII, latin1 or UTF8.
Otherwise you might have undefined behaviour from incompatible library versions.
You could use DYLD_LIBRARY_PATH to get the preferred libraries for boost (the ones which you link against). See also Is it OK to use DYLD_LIBRARY_PATH on Mac OS X? And, what's the dynamic library search algorithm with it?
Comment: My file is in UTF8.  I didn't mess around with the DYLD_LIBRARY_PATH, because a lot of sites claim it's not a good idea and I haven't understood why.

It looks like it was the usual Mac OSX issue of different libraries and compilers.  When I deactivated the Macports g++ and used the pre-installed g++, suddenly the problem went away.
Comment: It's not a splendid idea to do "blindly". But it is a key mechanism to do unintrusive deployments (e.g. deploying to machines that might have conflicting versions of libraries installed). the only /better/ way is to use the distro packaged version for everything - but that is usually feasibly only for very large products/very popular opensource
Answer: I had the same problem of mangled directory names. I installed boost using brew install boost and  gcc using brew install gcc6.
It turns out that the boost was build with the Apple's version of the GCC compiler, and the source file with the original GCC compiler. When I build your source file with Apple's compiler it does work.
Alternatively, build boost yourself with your compiler of choice.
See also the answer on a related question, https://stackoverflow.com/a/4798180/2535529.


How do I switch my HUD view in tf2?

Question: On YouTube I see a lot of people whose HUD shows the whole weapon without it in their face. The weapon was a bit more away from the screen. How do I use this option?
Answer: You can change the field of view in your graphic settings. The default is 70 or 75 I think. You can set it up to 90, this will increase your field of view which gives you a better overview.
You can change it using the commands too:
<code>viewmodel_fov <yourValue>
</code>

How do I switch my HUD view in tf2?


What's the error with sql instruction?

Question: CREATE VIEW DADOSTORNEIO AS
SELECT TORNEIO.NroTorneio , TORNEIO.NomeTorneio , TORNEIO.DescTorneio ,
    TORNEIO.DataFim , TORNEIO.DataInicio , EQUIPES.CodEquipe , EQUIPES.NomeEquipe ,
    EQUIPES.DescEquipe , ATLETAS.NroAtleta , ATLETAS.NomeAtleta , ATLETAS.TelAtleta ,
    ATLETAS.SexoAtleta , ATLETAS.Modalidade
FROM TORNEIO , EQUIPES , ATLETAS
WHERE EQUIPES.NroTorneio == TORNEIO.NroTorneio
  AND ATLETAS.CodEquipe == EQUIPES.CodEquipe
  AND TO_DATE(SYSDATE()) > TORNEIO.DataFim;

The code above submitted the folowing error in Oracle Express 11g:
ORA-00936: missing expression

Which is wrong in the code?
Answer: Use = instead of == in the where clause and SYSDATE instead of SYSDATE()
Answer: Additional to the errors pointed out by @RidaBENHAMMANE, SYSDATE already is a date - it doesn't make sense to convert it with to_date, so instead of
AND TO_DATE(SYSDATE()) > TORNEIO.DataFim;

just use
AND SYSDATE > TORNEIO.DataFim;

What's the error with sql instruction?


Getting error while compiling Glib 2.36.3

Question: I've given the required environment variable which are given below answer I'm compiling it with following code:
<code>./configure --prefix="/home/qemu/support_libs/libs/glib"

 export CFLAGS="-I`pwd`/../../support_libs/libs/gettext/include"

    export LIBFFI_CFLAGS="-I`pwd`/../../support_libs/libs/libffi/lib/libffi-3.0.13/include"

    export LIBFFI_LIBS="-L`pwd`/../../support_libs/libs/libffi/lib -lffi"

    export ZLIB_CFLAGS="-I`pwd`/../../support_libs/libs/zlib/include"

    export ZLIB_LIBS="-L`pwd`/../../support_libs/libs/zlib/lib -lz"

   export LD_LIBRARY_PATH="`pwd`/../../support_libs/libs/gettext/lib:`pwd`/../..
/support_libs/libs/zlib/lib"

    LDFLAGS="-L`pwd`/../../support_libs/libs/gettext/lib"
</code>
I have taken care of necessary dependecy but I'm getting this error
<code>You must have either have gettext support in your C library, or use the
*** GNU gettext library. (http://www.gnu.org/software/gettext/gettext.htm
</code>
Answer: Make sure libintl installed, and that glib can find it.
The macro to you need to satisfy is GLIB_GNU_GETTEXT, defined at https://git.gnome.org/browse/glib/tree/m4macros/glib-gettext.m4#n308
Answer: every thing is ok .. but the binary for which gettext is looking for(msgfmt) is in the bin directory of gettext(gettext/bin). so all we need to do is to add this bin path in PATH environment variable.
After this everything works fine.


What is this screw's name / type?

Question: Seems that recently Ikea and many other menufacturers are using the screw you see in picture (classic 1.5 multi power plug, nothing fancy).
I have never seen anything similar and searching online didn't help much.
Can you please suggest its name so that I can buy a specific tool to unscrew it?
Comment: Looks like a rivet to me (not meant to be removed).
Comment: If that's the case it's likely a proprietary fastener and has no name--just a corporate part number.
Comment: I don't think it is a rivet... It is more similar to those weird hair dryer screws (normal screw but the head has two "dots") except this one has 3 dots.
Comment: I would agree but now it seems very common in similar products. This is the product (not to be specific but just to give idea, it should 100% be openable): https://www.ikea.com/nl/en/p/koppla-4-way-socket-with-2-usb-ports-white-90280826/ I went around in shops and 2 other vendors have the same identical screw... Seems like a new standard to me :/
Answer: That is one version of a security screw, there are several types.
Used to try to make items not easily opened by the masses so you have to buy another instead of fixing something simple...
Depending on how deep they are I have used needle nose pliers or made a "socket" for them - I see those as a challenge and have boxes of "ordinary" screws to replace them.
Comment: I agree with @isherwood they are a proprietary type of tamper resistant or safety / security screw I checked my big set and it is not in that.  But a left handed drill bit or needle nose pliers may be the way to remove them, I have also greased the hole and used epoxy in the past but that was a very expensive part , I had 6 locations , epoxy works but you have to have a nice thin film of grease in the bottom and on the sides or you make a really nasty plug. Once the epoxy cures the screw backs out, but with these the divot is not that big epoxy may not work.

What is this screw's name / type?


JavaFXPorts - Battery consumtion - Screen always on

Question: I've a question about JavaFXPorts' battery consumption. On both Android and IOS, the screen is always on. And the phones get quite hot...
When creating a trace dump on Android or looking at the extensive log on IOS, you can see the QuantumRenderer to be active the whole time (on IOS you can see the message setSwapInterval([0|1]) (OpenGL?) constantly - this could be a lead.
Otherwise: Is it possible, that there's a "always on" flag set? If so: How to turn it off???
Regards,
Daniel

Edit: As the image below shows, I did a trace (in fact, I did several) of the app running.

As you can see, there is this ominous Timer active. While in the App there actually is a Timer, I've completely deactivated it's usage, but this "Timer-0" thread is still active... Beside the Charm-Down BLE, there are not many threads I'd suspect. And Timer indicates, that something is active repeatedly. Is this a normal Android behaviour, maybe?
Additionally I'd like to state again: I have some JavaFX-Services in the app, but since there is only this one "Thread-1952", I assume those are not the reason...

Edit 2:
And another image: Detailed method profiling. This Timer-0 is triggering pulses to the QuantumToolkit, which I assume keeps the screen on.

The pulse is done in the big block, starting and ending with a blue small block:

And I've seen the name MonocleTimer$1.run ()V pop up... Maybe this is the culprit.

Edit 3:
Charm Down BLE-Plugin removed completely:

Edit 4:
Some time ago I made an example application for other performance issues.
It shows the exact same behaviour:
https://github.com/bgmf/example
Comment: What do you mean by battery consumption? The Down `Battery` plugin? None of the plugins set the screen always on.
Comment: At the moment, my app stays active on both IOS and Android. In my opinion without that I have done something to do so. This (probably) results in the many `QuantumRenderer` calls and in the end: The phone stays on and the battery drains...
Comment: But are you using the Down plugin?
Comment: yes, its part of the registered plugins: `plugins 'display', 'lifecycle', 'statusbar', 'storage', 'battery', 'orientation', 'settings', 'browser', 'ble'` (even if I think, I don't need it anymore...)
Comment: I have a test app with all the plugins, including the battery, and both iOS and Android don't stay on, they turn off as usual. Also, the battery relies on callbacks from the native layers, so it is not constantly polling data.
Comment: Hm. Weird. Will need to dig into the code. But I currently don't see, what could cause this. JavaFX services? Their executors? I have to admit, that I have no clue...
Comment: I've updated the question: added a trace (image). I think, I know ***why*** it is happening, but i have no idea how to solve it...
Comment: It's hard to tell without seeing the code. Do you think it is because of the BLE plugin? If you don't use it, still happens? Does this happen to you in other apps?
Comment: No. It's not BLE. Just tried it with the same result. Removed some unused plugins as well. The question is, why this MonocleTimer is called so often. As far as I can see, I have nothing that would trigger this so often. It's not open source, so I can't show you the app - sorry. :-( And this is my first JavaFXPorts app, so no: It's the first, where it's happening.
Comment: Then just try a simple app with the Gluon IDE plugin. You'll see that the app doesn't keep the device on all the time.
Comment: I believe you... So I just re-checked the Example application I created for the text rendering performance issues. It shows the same behaviour (I've added the link to the GitHub repository to the question). *_If_* you want to have a look, I'd be happy... Regardless, it's to late to start the app from sratch, so for now i have to deal with it - and will also try to look into in on the example app - because it's much smaller and better to handle...
Comment: Hm. I created a `SingleViewProject` with the *Gluon Plugin*, using *Eclipse Neon.2* - and it didn't turn off the screen. I used the `androidInstall` task, which. Maybe the debuging?
Comment: What do you mean by debugging? Are you attaching a debugger? Can you run it without it? It should turn off after a short while. Else you have a an issue with your device?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135578/discussion-between-dzim-and-jose-pereda).
Answer: After some more tests, cleaned-up build file, I was able to reproduce this reliably only on the Nexus 5. Regardless of whether it is plugin in (debug mode) or not, the display stays on.
On a Nexus 6, this behavior was not reproducible anymore.
I will close this issue, because I believe it's - once again - a device-related issue.


Get file data into a ByteArray using FileReference

Question: I am using the FileReference object. I want to be able to save the local file data into a ByteArray. I know that I can use the data property in Flash 10, but I would like a solution that works for earlier versions of Flash.
Is there a way to do that?
Comment: And how do you suppose to get content of local file with flash?
Comment: in FLash 10 i can do it easily with Filereference. I wonder how i can do that with earlier flash versions
Answer: You can't get access to file data in version of Flash Player before Flash 10.
I believe you should be able to use FileReference to upload the file to the server, and then send it back to the Flash Player as a byteArray.


What is the criteria of Secret Hats

Question: I found some hats are given to users that they call it secret hats. Is there any criteria for this or they just throw it to popular users.
PS: I am taking part for the first time so pardon me for my question.
Comment: Oh there are criteria alright ;) You might find http://meta.stackexchange.com/questions/270789/winter-bash-2015-secret-hats fun reading
Answer: Secret Hats are... secret hats: Nothing in the description let you understand why you gain those hats, not even the description you read when you get them.
If you remember what you did before getting them, you could try guessing what the hat is for. Still, keep in mind that some hats could be not be given immediately. It is like with badges: There is a cron task (to use an expression familiar to us Drupalers) that checks which users meet some criteria, and which don't run every day, or every hour, when the criteria is verified, you get the badge.
Stack Exchange doesn't give a detailed description for those hats, probably because they don't want users do something just for getting them; instead, they want users to get a prize for doing what they normally do.

What is the criteria of Secret Hats


finishWriting is deprecated: first deprecated in iOS 6.0

Question: I use AVAssetWriter to encode video from image set:
[assetWriter finishWriting];

and this method generates warning in iOS 6.
[assetWriter finishWritingWithCompletionHandler:<#^(void)handler#>];

This is the way how I should apply it in iOS 6. Could anyone help me with applying it
Answer: You don't need to check whether it's finished. The completion handler is a block. It will be called by the system when the writing is finished. Try it.
[assetWriter finishWritingWithCompletionHandler:^(){
    NSLog (@"finished writing");
}];

Comment: [assetWriter finishWritingWithCompletionHandler:^(){

        }completionHandler:^ (BOOL finished){
            if (finished) {
                NSLog (@"finished writing");}
        }
         ];   can u explain like this,this code having errors
Comment: [assetWriter finishWritingWithCompletionHandler:^(){
    NSLog (@"finished writing");
}]; this one dosen't work i try it.It crash the app please help me
Comment: Instance method '-finishWritingWithCompletionHandler:' not found (return type defaults to 'id') warning
Comment: Could you paste your code here? I can't see what you are doing wrong.
Comment: i want to know how to stop assetWriter
Answer: This is writer Start code
 NSURL *movieURL = [NSURL fileURLWithPath:myPathDocs1];
    NSError *movieError = nil;
    [assetWriter release];
    assetWriter = [[AVAssetWriter alloc] initWithURL:movieURL
                                            fileType: AVFileTypeQuickTimeMovie
                                               error: &movieError];
    NSDictionary *assetWriterInputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInt:FRAME_WIDTH], AVVideoWidthKey,
                                              [NSNumber numberWithInt:FRAME_HEIGHT], AVVideoHeightKey,
                                              nil];
    assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeVideo
                                                          outputSettings:assetWriterInputSettings];
    assetWriterInput.expectsMediaDataInRealTime = YES;
    [assetWriter addInput:assetWriterInput];

    [assetWriterPixelBufferAdaptor release];
    assetWriterPixelBufferAdaptor = [[AVAssetWriterInputPixelBufferAdaptor  alloc]
                                     initWithAssetWriterInput:assetWriterInput
                                     sourcePixelBufferAttributes:nil];
    [assetWriter startWriting];

    firstFrameWallClockTime = CFAbsoluteTimeGetCurrent();
    [assetWriter startSessionAtSourceTime: CMTimeMake(0, TIME_SCALE)];

    // start writing samples to it
    [assetWriterTimer release];
    assetWriterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f
                                                        target:self
                                                      selector:@selector (writeSample:)
                                                      userInfo:nil
                                                       repeats:YES] ;

This is writer stop code
  if (isRecording) {
        isRecording = NO;
        [_session stopRunning];
        [assetWriterTimer invalidate];
        assetWriterTimer = nil;

        [assetWriter finishWritingWithCompletionHandler:^(){
            NSLog (@"finished writing");
        }];

        [self loadOvelay];

    }


What's the correct markup for stacked fontawesome icons as a bulleted list?

Question: I want to use fontawesome icons in a bulleted list. The guide provides the markup below:

Bulleted lists (like this one)

Buttons

Button groups

Navigation

Prepended form inputs

…and many more with custom CSS

Simples. Eh? However, instead of plain old icons, I want to use a font awesome stack. Comme ca:

Question is; how can I combine the two? Sticking icon-li in the stack span class doesn't work.
Answer: Is this what you are looking for?

      Buttons

      …and many more with custom CSS

Answer: On the newer version of font awesome (4.0.3), you can use bootstrap's list-unstyled class to get the same effect.

Answer: I've been struggling with the same issue. I want to use a stacked icon as a bullet for a li. More than this, I've been trying to combine stacked and normal icons in the same ul which has proven to be a nightmare.
I managed to solve the problem, sort of. I'm building a new site, busycreator.com, and if you visit you will see the second column in the footer which has social media links. The Dribbble icon is actually a stack (the Dribbble logo and a solid circle). Here's what I did:

            pinterest

            dribbble#

As you can see, there's a fair amount of inline styling, which is never idea. There's some manual positioning using margins/padding AND relative positioning, but this is the only thing that worked. I have the feeling that a number of external style sheets competing with one another, so inline styling is the only way I managed to get it to work.
There's one side effect which is that the link name — the stuff between  and  —cannot contain a space. Otherwise, each word will break onto its own line, forming a list within a list.
Feel free to build on this silliness and get it to work properly. I'll be grateful.


Is there a way to disable message boxes in MFC?

Question: I have an MFC application (using a legacy library that I can't change). When the application starts, it loads a couple of drivers and shows message boxes if some drivers couldn't be loaded. The loading of the drivers and the showing of the message boxes is done by a method inside the library that can't be changed (let's call this method Init). I would like to disable those message boxes (preventing them from "popping"). Is there something I could call before calling Init to disable Message Boxes temporarily and then re-enable them after?
(Note that if it is impossible to re-enable them after, I can very well live with that, I mostly want to disable them)
Thanks to all,
Note: If someone wonders about why I would like to do that, it is because my application exposes a COM interface and will be used by other applications. The only reason it is an application is that the library I use is much more easy to use when creating an MFC application (and not a dll). When it is called by my other applications, I don't want the message boxes to show, I just want to get the errors if something goes wrong.
Answer: I am not sure whether this could work. I use it for subclassing some messageboxes not to preven them to popup and they are not from a dll.
I set a hook to capture message boxes before poping up:
HHOK hMessageBoxHook_ = SetWindowsHookEx(WH_CBT,
                                         &CbtHookProc,
                                         ::GetModuleHandle(NULL),
                                         GetCurrentThreadId());

The new hook procedure (CbtHookProc) would be like this:
LRESULT CALLBACK CbtHookProc(   int nCode,
                                            WPARAM wParam,
                                            LPARAM lParam)
{
    if(nCode < 0)
    {
        return ::CallNextHookEx(    hMessageBoxHook_,
                                    nCode,
                                    wParam,
                                    lParam);
    }

    switch(nCode)
    {
        case HCBT_CREATEWND: // a window is about to be created
            return -1;
    }

    return ::CallNextHookEx(    hMessageBoxHook_,
                                nCode,
                                wParam,
                                lParam);
}

From microsoft documentation for HCBT_CREATEWND:

If the hook procedure returns a
  nonzero value, the system destroys the
  window

Then after calling Init you can remove the hook and message boxes will pop up again:
            ::UnhookWindowsHookEx(hMessageBoxHook_);
            hMessageBoxHook_ = 0;

As I told you I can't assure it works but give it a try.
Answer: One way to do this would be to hook/unhook the calls to MessageBox/MessageBoxEx/etc. and just do nothing when these calls are made. Check this guide for details on hooking API calls. In your case, I would specifically look at Import Address Table method, which is quite easy to implement and allows you to achieve the functionality you want.
You may also want to check Microsoft's own Detours library, but I'm not sure on whether it supports replacing API calls functionality.
Hope it helps.
Answer: I had the same problem when using ODBC with MFC.  Everytime there was an error, a message box would pop up showing the error, which was fine if I wanted one.
However, if I didn't, I only needed to surround it with:
TRY
{
    // Call error-prone method
}
CATCH ( CException, pEx )
{
    // Free resources
}
END_CATCH

The message box comes from the framework not knowing how to handle the exception.  Simply catch it and do as you wish with it.
Comment: thanks for the help but this doesn't solve my problem. The message boxes don't come from unhandled exceptions, they come from the library that itself catches the errors and shows message boxes. If it is possible, I want to disable or hide any future message box so that the library can't show them.


Ubuntu server routing table

Question: i've a ubuntu server (13.04) with 3 NICs.
This is my routing table:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         vodafone.statio 0.0.0.0         UG    0      0        0 p1p1
192.168.8.0     *               255.255.255.0   U     0      0        0 p2p2
192.168.17.0    *               255.255.255.0   U     0      0        0 p2p1

The server is on the interet and sees the 2 subnets.
My PC is on subnet 17.xxx, i can ping all PCs on the subnet 8.xxx but i can't go on the internet.
How can i configure the routing table to redirect my request on the web?
Answer: If you can ping from one subnet to another, there's no problem in your routing table. Probably packets from local networks are being sent to Internet unmodified. The problem is that private network addresses are not routable through Internet.
Private network addresses must be NAT'ed before sent to Internet. Try running:
sudo iptables -t nat -A POSTROUTING -o p1p1 -j MASQUERADE

Ubuntu server routing table


Can't get length of array/object in an Object of Javascript

Question:

box = {
  curBox: 0,
  boxes: document.getElementsByClassName('box'),
  size: this.boxes.length, //this one won't work
  orSize: Object.keys(this.boxes).length, //as well as this one
  preBox: function() {
    curBox -= 1
  },
  nexBox: function() {
    curBox += 1
  }
}

console.log(box.boxes.length); //This one works well!!!

  <meta name='title' content='Overview' /> ...

  <meta name='title' content='Career' /> ...

  <meta name='title' content='Skills' /> ...

  <meta name='title' content='Hobbies' /> ...

I tried to get the length of an array returned from getElementsByClassName. If I put it outside the object range, it work. But inside the object range, it won't. Right now, I would like to know a reason how come. I've test on other site (such as Mozilla) code editor but it only return the same result.
Comment: because `this` doesn't point to the `box` object. `this` points to the window object
Answer: this in javascript has only function scope, i.e, it points to the object where the currently executing function resides. If you do not have such an object, i.e. you are at the top level, then this, in a browser, generally points to the window object.
So, while your object is being constructed, this is not actually your object, but something else.
Code like this will work:
const person = {
  name: "Wekoslav",
  surname: "Stefanovski",
  getName: function(){
    return this.name + " " + this.surname;
  }
}

console.log(person.getName());

because I'm calling the getName function only after I've defined it, and within that function, this is bound to person. However, this code:
const person = {
  name: "Wekoslav",
  surname: "Stefanovski",
  fullName: this.name + " " + this.surname;
}

console.log(person.fullName);

won't work, because this is bound to whatever it was before the const person line got executed.
Answer: document.getElementsByClassName('box') is incorrect and return null in this case. That function returns elements which have all of the classes specified in the first argument as a space-separated string. You can use document.querySelectorAll('.box').
Comment: dude, it returns an HTML collection and it's an object, so there's nothing wrong with what he's doing, only that he's calling `this` inside the object initialization
Comment: @Roljhon Did you test `document.getElementsByClassName('box')` in console? It returns null.
Comment: dude, it didn't :) probably you're executing the code outside of the iframe if you're testing it from the fiddle above.
Answer: main reson is you are still initializing you Box object hence you can't access this. In other words your object is not fully formed at the time you are using this.
what you can do is create a function and return it.
boxes: function() {
  return function() { return this.boxes.length; },
}

I created a jsfiddle with improvements. https://jsfiddle.net/jz1thu26/.
also note that you need to run your method when DOM is ready.
Comment: Yes, you will need a regular function, as the fat arrow does not define its own `this`
Comment: this is not going to work. again `this` will not point to the box object, it will likely be undefined or the Window object, if you tried it then you will know
Edited: Sweko was right
Comment: @SWeko forgot about that :) awesome!


For an operator $\hat A$, if $\langle \hat A\rangle=0$, does this mean that $\langle \hat A\rangle\langle\hat A\rangle=0\,?$

Question: Consider an arbitrary operator $\hat A$, let's suppose that $\langle \hat A\rangle=0$.
Does this mean that I conclude that $$\langle \hat A^2\rangle=0\,?$$
I used to think that the answer to this was no, we cannot conclude that the expectation value of the operator squared is zero just because the expectation value of the operator is zero.
However, $\hat A^2=\hat A\hat A$, now since $\langle \hat A\rangle=0$ does this mean that $$\langle \hat A\rangle\langle\hat A\rangle=0\,?$$
Answer: You are right that $\langle \hat A \rangle = 0$ does not imply $\langle \hat A^2 \rangle = 0$ but it of course implies $\langle \hat A \rangle^2 = \langle \hat A \rangle\langle \hat A \rangle= 0.$


How to add null value to field Many2one from data file Odoo

Question: I want to add a new category of Salary Structure by data file. Here is my current code
   <record id="MEALS" model="hr.salary.rule.category">
        <field name="name">Meals</field>
        <field name="code">MEALS</field>
        <field name="parent_id" eval=""></field>
    </record>

All I need is a category with no parent category but with these code parent category of it is Base for new structures. I've tried with evals="0", evals = " " or remove field parent_id out of .How can I add null value into this field ?
Answer: This behaviour is a little weird .AFAIK If you don't include the parent_id field, it should work and have a null value because that field doesn't have a default value on it. (Except you've extended the model and added a default on that field).
The only fields where null values don't work in the Odoo ORM are Integer and float fields. (That's the reason they always have an initial value of 0 or 0.0 in a form view).
quoting the docs:

field
Each record can be composed of field tags, defining values to
  set when creating the record. A record with no field will use all
  default values (creation) or do nothing (update).
A field has a mandatory name attribute, the name of the field to set,
  and various methods to define the value itself:
Nothing
if no value is provided for the field, an implicit False will
  be set on the field. Can be used to clear a field, or avoid using a
  default value for the field.

Try this <field name="parent_id" /> or <field name="parent_id" eval="False" />
If the above don't work then double check your codebase and make sure you're not setting any default value on the field.
Comment: you 're right, it has default value for parent_id field, I changed it by inherit model hr.payroll.structure and change default value to False :
`parent_id = fields.Many2one(default=False)`


Is $\mathbb Z$ a submanifold of $\mathbb R$?

Question: Is $\mathbb Z$ a sub-manifold of $\mathbb R$? If yes, what kind of sub-manifold it is?
Thanks
Answer: It's a $0$-dimensional manifold but is not compact or even bounded. We retain Hausdorffness and second countability for obvious reasons. (Note every $0$-dimensional manifold is a disjoint union of points - that is they are discrete spaces classified topologically by their cardinality.)


Can you max out your level in World of Xeen without cheating?

Question: Simply put, is there enough gold natively in the game to allow your characters to train to the maximum level (IIRC, 200)? Even counting bank interest accrual, I was never able to do it.
I have maxed out the levels before, but it always involved hex-editing the gold in my party. (I never hex-edited experience, though; I just have a fondness for killing the Mega Dragon.)
Answer: It's actually very easy to have more than enough money to get your characters to 200 via the "Inheritance" trick.  I did this on Cloud-side.  It's a bit complicated, but very possible.  First, with the default party (DO NOT yet make your actual party) go to the magic mirror and go to Rivercity.  Save, fight, and load if you ever get overwhelmed or killed.
You start near the bank, which will turn out to be convenient, for right now deposit all your gems.  Take the back road south of the bank to the River City labor board, where you should work for the money to buy Lloyd's Beacon.  Go to the portal and go to Shangri-la.  Get the free guild membership, and then at the magic guild buy Lloyd's beacon.  Use Mr. Wizard to get back to Vertigo.
In Vertigo, go to the bank and withdraw enough gems to cast Lloyd's beacon at least twice, go to the portal, set your Lloyd's beacon there and go to Count du Money.  There you will see a pedestal and 2 piles of money, what hasn't already been robbed from the back door to the dragons lair.  Take them and cast Lloyd's Beacon, returning to Vertigo's portal.
Almost done, go to Rivercity via the portal, deposit the 1,000 gems and 50,000 gold.  Then go to the labor board, and work until you're 100 years old, it won't take long.  Check your bank, you should have around 160 million and 2 million gems.  More than enough.   Now, go to the inn, make your real party, and you are funded.
Answer: I really don't think so, at a certain point the gold exponent simply becomes too high. I can't recall however if enemies respawn in WoX (as they did in For Blood and Honor) if they did then the answer shifts to 'technically' yes. But I'd hardly consider it reasonable.
Comment: Enemies don't respawn, sadly. OK, just have to remember to keep a hex editor around then ... :)
Answer: Most monsters in WoX do not respawn. However, there are certain locations where monsters can, for farming purposes.
1. Nightshadow. Enter the town at night, and the female vampires respawn (low XP per kill though)
2. Castle Xeen. Do not destroy the guard making machine and the Xeen guards will keep appearing every time you ascend or descend the stairs. Use the side towers to farm xp.
3. Sky Bandits (3x cloud dragons). Though the positions where they appear are fixed, the probability of them appearing is random.
4. Sandro if you do not get his heart from the sewers. +100 gems too.
I'm not sure if the monsters in Asp regenerates if you do not destroy the machine, the same for Lord Xeens in Dungeon of Death. I'm also not sure if you can keep ringing the gong in Darkstone Tower to generate Onyx Golems. Those are tough though.

Instead of using the bank/inheritance technique, I am grinding out gold in another fashion, which takes less game time, but a lot more of player's time. I use Sandro to make gems (by this time, I can easily kill him before he attacks me), and then mine out the Gemstone Mines (rolling only for gemstones, reload if gems are obtaineed). I roll for Plate Armour/Mail (for higher profits) at the smiths and then sell. Rinse and repeat. This way, in less than 2 game years, I can get enough gold to train to 200. The XP from killing Sandro is also useful in having the required XP for training. Use the remaining level raising items/awards (Clouds + Darkside, all untouched to date) to reach 255.
It's boring, but you can simply use your current characters for it. I inter-spaced these gold grinding operations b/w stages of Darkside, once I have the ability to safely grind gems from Sandro. This helps preventing it from becoming too boring.
All you need is to have 250k gold for the initial Gemstone Mine replenishment, Sandro's quest uncompleted (and not having his heart in your quest inventory!), sufficient stats to kill him before he attacks (you can use the Day of XXX spells at 5AM to maximize efficiency. You can even cheese it with the Xeen Slayer Sword, which bypass all physical attack resistance). Needless to say, you will have the Merchant's skill a long time ago for everyone in the party.
Comment: Forgot to mention: Warzone. I do not know if there is a limit to the number of times it can be used, but it can be used for XP farming. The downside is that the monsters are Cloudside only, which are a joke for a party which has romped all over the Darkside.
Comment: XP farming is easy, if you're patient and strong enough -- The MegaDragon. It's the money that's the real problem. Your techniques and the others show that it can be done, though -- and without the hex editing of gold I'd always resorted to. (For what it's worth, I *earned* the XP. Just not the money. :)
Answer: When maxing characters, the two concerns are gold and exp. Gold can be obtained through the inheritance trick. On the exp side, my favorite solution is the Sky Bandits on the skyroad of darkside. Walk around the skyroad until you encounter bandits, and pick the fight dialogue choice. You will fight three cloud dragons. Then spin in a circle and they will attack again. You can repeat as long as you want. And you can set a beacon at the spot and come back later to get more exp. Having high speed on three characters that can each one shot a dragon with default attack will be ideal there.


Do I have to complete all weapon upgrades in one playthrough to get Man-At-Arms?

Question: I'm still on my first playthrough of Bastion.
If I want the Man-at-arms achievement, can I finish it up at leisure in New Game+ or do I have to upgrade every weapon before I go in for the final mission in this playthrough?
Answer: The upgrades you have done will carry over to your new Forge in your New Game+, so you will be able to collect items and such to upgrade your weapons. You can even upgrade weapons you don't have yet in your NG+ playthrough (I was able to upgrade the Dueling Pistols, for example, at the beginning of the game).
So yes, you can complete the game and still have the ability to finish up that achievement in a NG+.