text:
Q: Does Naruto use Flying Raijin Jutsu? This technique is used by Minato Namikaze, but does Naruto use it as well? As far as I remember, he dodged a punch from Raikage who said that he has surpassed his father.
Is this technique something else?

A: Naruto does not use the Flying Thunder God technique at any point in the series.
Notable similarities:

*

*Gaining partial mastery over Kurama got him fast enough to be on par with the Third Raikage, who was said to be the fastest shinobi alive (Second only to Minato, when he was alive)

*Gaining full mastery over Kurama (and becoming friends with him) increased his speed even further, shown to be able to nearly instantly create a shadow clone and fly to the other side of the battlefield to stop two simultaneous attacks on his friends.

 - During his time as Hokage we've seen him use the Body Flicker technique, which is a rather general name for "moving really really faster so that it looks like teleportation", but the distinction between Body Flicker and Flying Thunder God was made several times in the series.

To summerize: Naruto is very fast, however, he cannot use the Flying Thunder God technique.

A: I think Naruto may have some knowledge of the Flying Thunder God technique, but has never showcased it in live combat. However referring back to the scene where Naruto dodges the Raikage's punch; Naruto does not use the 'FTG' technique but instead uses his brute speed, in the nine tails chakra mode, to match that of the speed of the 'FTG' technique.
On an important note it is crucial to remember that, after Naruto received the Six Paths Sage Power and entered the Six Paths Sage mode; his speed has enhanced immensely when compared to that of the Nine tails chakra mode. So the question is not whether Naruto knows the 'FTG' technique, but  whether is it really necessary for Naruto? as he has already surpassed the speed of the 'FTG' technique using his acquired powers.

A: He used it in the movies, im not sure if that's canon or not.

A: The movie was Road to Ninja, where Naruto and Sakura where trapped in a tskyuomi. Even Obito says "The last time I got hit by that Jutsu was 16 years ago." referring to when Minato used Rasengan combined with Flying Thunder God and hit Obito/Menma on the back before he could dematerialize that part of his body using close range Kamui.
The scene I am talking about occurs about 14 minutes or so before the end of the movie.
Not sure if it's Canon or not, I would assume it is since the plot of the movie was Obito wanting to test out a limited version of the Infinite Tsukuyomi which would have some relevance to the storyline.

A: In chapter 700 of the manga, the final chapter which takes place years after the events of the series, an adult Hokage Naruto uses Flying Raijin to stop his son, Boruto, from vandalizing the Hokage monument.
Naruto does not use the technique during the War, and in fact had never seen it until encountering the resurrected Minato at the end.

A: He uses Flying Raijin 2 times: against Menma in the movie and to stop Boruto from vandalizing the Great Stone Faces.
Note- He shares his and Kurama's chakra with his reanimated father to teleport the entire allied shinobi forces out of the barrier erected by Obito Uchiha during the Fourth Great Ninja War

A: *

*used on Kisame right after achieving Kurama chakra form for the first time inside the sealing cave (referred to by Bee as Teleportation technique and seeing a yellow flash)

*used in the very last chapter of Naruto to stop Boruto from painting in the stone mural (Borito calls out the name of the technique)

*used in the movie "road to ninja" against Obito (referred to as the same Technique Minato hit him with 16 years ago)

So, yes. Naruto knows that Jutsu and uses it. But very rarely. Reason probably being that he just learnt it during the Ninja war and still had trouble with controlling it and incorporating it into his fighting style seamlessly.

A: Naruto is shown using Flying Raijin Or Flying Thunder God Technique in one of Naruto Shippuden Movies Against Menma

A: I think he did use it once to stop Boruto from vandalizing the Hokages's faces.


text:
Q: Django form submits, but won't save to database I'm using a ModelForm, but not using Django's auth system.  I am also trying to set a random password, but have commented out that bit because I'm not sure if it is causing issues.
Currently, the following will return 'success', but will not save to the database.
def registration(request):
if request.POST:
    data = request.POST.copy()
    data['date_joined'] = datetime.date.today()
    data['last_login'] = datetime.datetime.now()
    form = UserForm(data)
    if form.is_valid():
        try:
            User.objects.get(username=form.cleaned_data['username'])
        except User.DoesNotExist:
            #ran_pw = User.objects.make_random_password(length=12)
            #user.set_password(ran_pw)
            user = User()
            user.username = form.cleaned_data['username']
            user.first_name = form.cleaned_data['first_name']
            user.m_init = form.cleaned_data['m_init']
            user.last_name = form.cleaned_data['last_name']
            user.institution = form.cleaned_data['institution']
            user.department = form.cleaned_data['department']
            user.phone = form.cleaned_data['phone']
            user.email = form.cleaned_data['email']
            user.save()
            return HttpResponse('success')
    else:
        return HttpResponse(form.errors)
else:
    form = UserForm()
    return HttpResponse(form.non_field_errors)

A: Presumably this happens when the user already exists in the database. That's because you only actually set the data when the user doesn't exist. Move all the field setting code back one indentation level.
Actually, you shouldn't set the fields manually at all - the whole point of using a ModelForm is that you do form = UserForm(data, instance=user) and then if the form is valid you just do form.save().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change to andReturn() breaks C++ compilation Commit https://github.com/erikdoe/ocmock/commit/a13a464b8d1c42b6526abfd968fba77f0687c8ac breaks compilation with C++ by making using of __typeof__(_val). The error is:
expected '(' for function-style cast or type construction
It would seem to satisfy the same condition (the value is an ObjC object) by using the runtime, rather than the compiler with:
#define andReturn(aValue) _andReturn(({
  __typeof__(aValue) _val = (aValue);
  NSValue *_nsval = [NSValue value:&_val withObjCType:@encode(__typeof__(_val))];
  if (strcmp(@encode(__typeof(_val)), "@") == 0) {
      objc_setAssociatedObject(_nsval, "OCMAssociatedBoxedValue", *(__unsafe_unretained id *) (void *) &_val, OBJC_ASSOCIATION_RETAIN);
  }
  _nsval;
}))

It seems the intention is to retain the object value inside the passed NSValue. I would submit a patch, but it doesn't appear that pull requests are accepted over Github.
Anyway, thanks!


text:
Q: Differences between heavy tail and fat tail distributions I thought heavy tail = fat tail, but some articles I read gave me a sense that they aren't.
One of them says: heavy tail means the distribution have infinite jth moment for some integer j. Additionally all the dfs in the pot-domain of attraction of a Pareto df are heavy-tailed.
If the density has a high central peak and long tails, then the kurtosis is typically large. A df with kurtosis larger than 3 is fat-tailed or leptokurtic.
I still don't have a concrete distinction between these two (heavy tail vs. fat tail). Any thoughts or pointers to relevant articles would be appreciated.

A: I would say that the usual definition in applied probability theory is that a right heavy tailed distribution is one with infinite moment generating function on $(0, \infty)$, that is, $X$ has right heavy tail if
$$E(e^{tX}) = \infty, \quad t > 0.$$
This is in agreement with Wikipedia, which does mention other used definitions such as the one you have (some moment is infinite). There are also important subclasses such as the long-tailed distributions and the subexponential distributions. The standard example of a heavy-tailed distribution, according to the definition above, with all moments finite is the log-normal distribution.
It may very well be that some authors use fat tailed and heavy tailed interchangeably, and others distinguish between fat tailed and heavy tailed. I would say that fat tailed can be used more vaguely to indicate fatter than normal tails and is sometimes used in the sense of leptokurtic (positive kurtosis) as you indicate. One example of such a distribution, which is not heavy tailed according to the definition above, is the logistic distribution. However, this is not in agreement with e.g. Wikipedia, which is much more restrictive and requires that the (right) tail has a power law decay. The Wikipedia article also suggests that fat tail and heavy tail are equivalent concepts, even though power law decay is much stronger than the definition of heavy tails given above.
To avoid confusions, I would recommend to use the definition of a (right) heavy tail above and forget about fat tails whatever that is. The primary reason behind the definition above is that in the analysis of rare events there is a qualitative difference between distributions with finite moment generating function on a positive interval and those with infinite moment generating function on $(0, \infty)$.

A: NN Taleb, P Cirillo (2019) address this directly in Branching epistemic uncertainty and thickness of tails where they state:
From the point of view of extreme value statistics, both
the Gamma and the Lognormal are heavy-tailed distributions,
meaning that their right tail goes to zero slower than an
exponential function, but not "true" fat-tailed, i.e. their tail
decreases faster than a power law [31]. From the point of view
of extreme value theory, both distributions are in the maximum
domain of attraction of the Gumbel case of the Generalized
Extreme Value distribution [9], [14], and not of the Fréchet
one, i.e. the proper fat-tailed case. As a consequence, the
moments of these distributions will always be finite.

A: First there can be left tails and right tails, then long tails and short tails. A short-tailed distribution can be thought of a having a finite range, called its support. And a long tail has semi-infinite support in that direction. For right-tail heaviness one does a comparison of either survival functions (RVs) or complimentary cumulative density functions (1-CDF), typically by examining the logarithm of ratio of two different distributions. In general, heavy tailed means heavier than the exponential distribution, and light tailed means lighter than that. A subset of heavier-tailed distributions are called "fat-tailed." From a historical perspective it is most likely that the concept of a fat tail relates to the type I Pareto distribution, i.e.,
\begin{equation}\label{eq:PD}
\text{PD}(t; \alpha, \beta)=
 \dfrac{\alpha}{t} \left(\dfrac{\beta}{t}\right) ^{\alpha } \theta(t-\beta)\;,
 \end{equation}
where $\alpha$ is the shape parameter, $\beta$ is a scale parameter and $\theta(\cdot)$ is the unit step function such that $\theta(t-\beta)$ is the unit step function time-delayed by $\beta$, and is used to make a product that is non-zero only when $t> \beta$.
From Juran, "The Pareto Principle (Sic, 80-20 rule) gets its name from the Italian-born economist Vilfredo Pareto (1848-1923), who observed that a relative few people held the majority of the wealth (20%) – back in 1895. Pareto developed logarithmic mathematical models to describe this non-uniform distribution of wealth and the mathematician M.O. Lorenz developed graphs to illustrate it."
Next, let us consider the attitude toward wealth at that time. Renzaho quotes Grivetti saying "At the turn of the 20th century in North America obesity  was  admired;  wealthy  consumers  exhibited their  wealth  around  their  waist.  Fat  cheeks  and ample  stomachs  were  visual  cues  that  individuals were  healthy,  not  infected  with  the  dreaded  slim tuberculosis.  Photographs  of  American  executives taken during the late 19th and early 20th centuries reveal  that  dietary  intakes  of  wealthy  gentlemen regularly exceeded calories expended."
The history of those times lends considerable weight to those words. From the US 1910 census, tuberculosis, A.K.A, "consumption," which literally eats the body from the inside out, had been endemic for decades and was responsible for approximately 15 deaths per 1,000 inhabitants per year, or, if you wish, approximately 30 times the annual death rate from SARS-CoV-2. Thus, the more modern concept of slimness being healthy was not plausibly in vogue.
Next, the term "fat cats" came to describe wealthy political donors in approximately 1920 or earlier and Pareto's work was first translated into English in 1916. Wesolowski et al. summarize the prevailing attitudes of those times in a footnote, "Ironically, the fat-tailed distribution of wealth inspired Karl Marx's [49], as well as Benito Mussolini's economic policies as diametrically opposite and extreme reactions to the same statistics [50]." and attribute the meaning of fat tails as follows, "The statistical form for a power law is the Pareto distribution (PD), which like the Cauchy distribution, has tails so heavy they confer unusual statistical properties and have been given the name fat-tailed distributions. Power laws are scale independent and intrinsically fractal."
In that paper, [49] refers to Of Fat Cats and Fat Tails: From the Financial Crisis to the 'New' Probabilistic Marxism and [50] refers to Pareto and Fascism Reconsidered by Zanden. That Vilfredo Pareto had Benito Mussolini as his most well known student should be lost on no one.


text:
Q: .Net Threading Bidirectional I have a C# windows forms application.
The application has a single windows form.
I would like a button click event on the form to kick off a worker thread that manages a third party library.
I also have a C# asp.net web application.
The application has a single web page (for the purpose of this question).
I would like a button click on the web page to kick off a worker thread that manages the same third party library.
My worker thread does the following
1. Sets a callback function on the third party library so it can call me back when certain events occur
2. Initiates an operation (not async) in the third party library (that will ultimately call my callback).
I would like the callback (my callback called by the third party library) to send a message to the UI (whether windows forms or web).
I cannot exit the stack frame in which my callback is running, so I need the callback to notify another thread that the callback
requires data.  That other thread can then determine whether it wants to callback to the windows UI or to the web client (for this
question, I am not interested in how to callback to the web client)
When the UI receives the message, I would like the UI to display a dialog asking the user for information.  Once the user has answered
the questions and dismissed the dialog, I would like the data captured in the dialog to be returned to the callback function (which was
waiting, since it cannot progress without the data).
Both the web UI and the windows form UI can be waiting as well, though my preference is they would not be, and I would handle the
requests from the worker thread in an independent portion of the user interface that remains visible regardless of what other work
the user might be doing.
So, the basic architecture looks like this.

Given the current feature set of C# as of 2016, what is the best way to accomplish this task?
Bascially, I require two-way communication between threads, and I need to ensure I don't violate the SynchronizationContext (in the winforms case).
I have viewed a number of answers, some using Progress. None of the answers show the callback waiting for an answer from the UI, and the UI handling multiple callbacks. I could fashion this using old style threading primitives, but I would like to use Task, and maybe async/await. This is surely a common pattern, but I could not seem to find it.  What is the present day best practice for having a background thread callback to a UI thread, having the UI thread display something, collect a result, and then return that result to the background thread?


text:
Q: How to use xsl:sort to sort images NOT based on position() EDITED: ADDITIONAL INFO BELOW
I am trying to sort images in ascending order using <xsl:sort> without having to use the "position() function.
I am experiencing an issue using the <xsl:sort> function to sort images in ascending order.
This is my XML input code that links to the product ASAMSCM195265783.jpg:
             <objectImage code="ASAMSCM195265783" name="NX1000 Compact System Camera in White with 20-50mm Lens Product Image (Primary)" imageTypeName="Product Image" imageTypeCode="PRODUCT" objectTypeImageCode="PRIMARY_PRODUCT" objectTypeImageName="Primary Product Image" displayOrder="7">
                 <imageVersions>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_SM" width="15" height="15" path="PRODUCT/PRODUCT_THUMB_SM/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_M" width="32" height="32" path="PRODUCT/PRODUCT_THUMB_M/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_REGULAR" width="170" height="170" path="PRODUCT/PRODUCT_REGULAR/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_ENLARGED" width="500" height="500" path="PRODUCT/PRODUCT_ENLARGED/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_L" width="36" height="36" path="PRODUCT/PRODUCT_THUMB_L/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_XL" width="150" height="150" path="PRODUCT/PRODUCT_THUMB_XL/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_110" width="110" height="110" path="PRODUCT/PRODUCT_THUMB_110/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_LARGE" width="300" height="300" path="PRODUCT/PRODUCT_LARGE/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_50x50" width="50" height="50" path="PRODUCT/PRODUCT_THUMB_50x50/ASAMSCM195265783.jpg" link=""/>
                    <imageVersion versionTypeCode="PRODUCT_THUMB_75x75" width="75" height="75" path="PRODUCT/PRODUCT_THUMB_75x75/ASAMSCM195265783.jpg" link=""/>
                  </imageVersions>
             </objectImage>

My other XML examples for the other ASAMSCM195265783.jpg products are exactly the same as above but only differences are that objectTypeImageCode="OTHER_PRODUCT" instead of PRIMARY_PRODUCT and the displayOrder="8" and "9".
This is my current XSLT code:
<xsl:sort select="displayOrder" data-type="number" order="descending"/>

                <xsl:attribute name="id">
                  <xsl:text>thumb</xsl:text>
                  <xsl:value-of select="position()" />

Here is the result in HTML:

Notice in the second line of my HTML result the product image ASAMSCM195265783.jpg is in the wrong place? I am trying to display that image in the third line of my HTML result. So basically the 2nd and 3rd html line needs to be swapped around so that the name of the product images can be sorted out properly in descending order.
Whenenver I use:
<xsl:sort select="position()" data-type="number" order="descending"/>

            <xsl:attribute name="id">
              <xsl:text>thumb</xsl:text>
              <xsl:value-of select="position()" />

It does the job but only based on position() (the number of the product), I am trying do this based on the product name not the number within the product name (if that makes sense).
Any help would be appreciated, thanks in advance (if you need further clarification or any further questions please let me
This is my desired result in HTML:

If there are anymore additional info that you would think is more relevant to post here to clarify further this issue please let me know, thanks.

A: I think the problem is that displayOrder is an attribute on the objectImage element, but your current sort is treating it as an element. You probably need to change it to the following
<xsl:sort select="@displayOrder" data-type="number" order="descending"/>

Also note, and this may just be a typo in your question, you state you want to "sort images in ascending order". If this is the case, you will obviously have to change "descending" to "ascending" in the above xsl:sort


text:
Q: is - select * from empty table possible? On my website I am trying to select 2 tables - tableB of which might be empty, so its not returning any results at all when tableB is empty. I hope I am explaining this properly. Any suggestions?
    curatio.webdb.getAllTodoItems = function(renderFunc) {
        var db = curatio.webdb.db;
        db.transaction(function(tx) {
            tx.executeSql("SELECT * FROM tableA, tableB", [], renderFunc,
                curatio.webdb.onError);
        });
    }

basically TableA has e.g. Name and Surname columns and TableB has e.g. Address details. But sometimes there is no address, and then I cannot get anything to display.
I need to basically ignore tableB if it's empty.

A: If tableA and tableB have the same schema, you can do something like this:
SELECT * FROM tableA
UNION
SELECT * FROM tableB

However, if they don't have the same schema, you will have to do something smarter to get the union to work.

A: What you are performing there is called a Cross-Product of those two tables.  A cross-product is essentially every row of tableA with every row of tableB.  Since tableB has no rows, the cross-product has no rows.  If you want all rows of both tables, use 2 queries.  I would recommend reading a basic SQL tutorial.

A: curatio.webdb.getAllTodoItems = function(renderFunc) {
    var db = curatio.webdb.db;
    db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM tableA UNION ALL SELECT * FROM tableB", [], renderFunc,
            curatio.webdb.onError);
    });
}

It will best to explicitly use the column names in both select rather then using the *.

A: Although your query doesn't hint at this, I still think you are probably looking for a LEFT JOIN, because I'm assuming you want to link data from two tables by a common value in a column from table B (known as the foreign key).
This query selects values of the first table, even when there's no matching data in the join table:
SELECT *
FROM `tableA` `a`
LEFT JOIN `tableB` `b`
  ON `b`.`someReferenceColumnToTableA` = `a`.`theReferredColumn`

Again, this assumes you meant to join two tables by some common value, for instance:
person (table A):
- id
- name

phonenumber (table B):
- id
- person_id // this is the foreign key to table A that "links" the data
- phonenumber

If you were to use a regular JOIN (also known as INNER JOIN) then only rows are returned for when both tables have matching data.
What your original query did, however, was (implicitly) CROSS JOIN all data from both tables. Given your question edit, I hardly think this is what you were actually after.


text:
Q: A suitable corpus for training skip-though vectors For training a variant of the notion of skip-though vectors, I need a long corpus of consecutive (related) sentences. The original skip-thought paper has used BookCorpus, but it is no longer available. Is there a similar dataset available online? I know Gutenberg project, but unfortunately its data is notoriously difficult to pre-process, and I'd also prefer more contemporary texts.
Thanks

A: *

*Common Crawl corpus: consists of 145 TB of data from 1.81 billion webpages as of August 2015

*http://www.lrec-conf.org/proceedings/lrec2018/pdf/889.pdf: see Table 1 for several summarization corpora, which consist of texts with consecutive (related) sentences.


text:
Q: Creating a one-digit scoreboard using logic circuits I'm creating a one-digit scoreboard on a breadboard. Naturally, I have a BCD to 7-segment decoder and a 7-segment display. But I don't know how to automatically increment the display. (It's for a game, you see, and when someone wins, the score should automatically increment). I'm thinking of using a 74293 4-bit binary counter but I'm stumped as to how I input to it. I understand how the output is encoded but not the input. What kind of input (DC/AC, something else entirely?) does it expect? How is it encoded with the two input pins?
BTW, a pinout can be found at http://www.datasheetdir.com/SN74293+Counters .
Thanks to anyone who'll take the bother. (--,)

A: Usually 'A "counter"advances one count when it's clock input makes an active transition'.
Translated into people-speak that means that there is an input pin usually named "CLOCK" or "CLK". When this changes from low to high (or sometimes from high to low) the counter steps one count.
This COULD be done as easily as connecting the Clock pin to ground with a resistor and pulling it high with a pushbutton etc to cause a count to occur. BUT you will rapidly learn about debounce. A switch makes many open/close actions as it closes or open. One easy way to address this is to us  capacitor to slow things down and eliminate spurious changes. There are more formal and properly defined ways of doing this.
Counte ICs typically have pins with some or all of these functions

*

*Clock / Clk - as above

*Reset - When "asserted" the counter resets to zero.
Asserted may mean set to high or low level depending on the device.

*Enable. When active the counter can be controlled by the clock.
When inactive the counter does not count.
May be high or low depending on counter IC.
Some have several.

*Set/Preset/ Load -  SOME counters may have a value loaded from external pins. Rare.

*Carry out - sends a signal to a following stage to allow a multi IC counter to be made.

*

*Carry in - accepts carry out from a previous stage.

*More ...

Below is the logic diagram of the 74293 counter that you mentioned.
 This is a very old IC using a technology (called "TTL") that is essentially obsolete for casual amateur use. They still work as well as ever and are find to learn with, but you will probably want to use a more modern equivalent for anything serious in due course.
The counter consists of 4 x "JK flipflops". They are wired so that a falling edge on cle CK (- CLK = Clock) line causes a flip flop to "toggle". That is if Q is high it goes low and if Q is low it goes high. The IC has two parts - a divide by 2 part controlled by input A and a divide by 8 part controlled by input B. To make a divide by 16 ( = 2 x 8) you connect input B to QA and use input A only. This then become a 4 stage counter that will divide by 2 x 2 x 2 x 2 = 2^4 = 16.

Looking at the diagram:

*

*CK A and B on pins 10 & 11 are the clock lines mentioned above.

*Ro(1) and R0(2) combine to provide a reset function.
When R0(1) and R0(2) are both high at the same time the counter rests so all x outputs are low.
When either or both the R0 lines are low the counter is free to count when clocked.
The following is what happens when you connecy input B to Qa and clock Input A. (Clocking input A consiss of lowering its level from high to low.
 A full clock cycle consists if high/low change, pause, low/high change, pause.

*

*QA QB QC QD are the outputs.

*

*QA is the LSb or least significant bit of the output.
It "toggles" on each high to low clock transition.
It's state on each clock goes: 010101010101...

*Qb is the next most significant output bit. It toggles every second clock.
Its state goes 0011001100110011...

*Qc - you should get the picture by now
Toggles every 4 clocks
Sate goes 0000111100001111...

*Qd - most significant bit = MSb.
Changes every 8 clocks.
State goes 00000000111111110000000011111111...
Diagram repeated

SO now you have a counter which counts each time input B is lowered.
 BUT how do you convert the 4 outputs to a 7 segment display drive?
 There are a number of ways. The simplest uses diodes and a few transistors!
 You could use a binary to 7 segment decoder IC.
I'm not recommending you use it but an SN7447 BDC to 7 segment decoder will do the job up to a count of 9.
What I would recommend is that you look at the [74C925 / 926 / 927 / 928 family(http://media.digikey.com/pdf/Data%20Sheets/Fairchild%20PDFs/MM74C925-28.pdf) OR any of the many other ICs that do a similar job. This will drive up to 4 digits and get you to a practical solution much more quickly
but still teach you quite a lot along the way.
When you are ready you can go BACK to the 74293 to learn the lower level lessons that it can teach you.


text:
Q: retrieve text value from an element with jQuery If I have an HTML element with a value in it:
23

How can I retrieve this value (23) and use it? I've tried something like:
var num = $("#mySpan").text();

Does not seem to work... Will I be able to use it as a number to add other numbers to it?

A: Make sure the DOM is loaded before your code runs:
$(function() {
    var num = +$("#mySpan").text();
    alert( num );
});

A: You want parseInt. You should also make sure that the selector is returning the DOM elements you expect it to.
var num = parseInt($("#myspan").text(), 10);


text:
Q: jQuery Click Event Not Working in Mozilla (Working in Chrome) I know that this has been asked here before, because I remember reading various posts on this topic when I first attempted to recreate this effect on my personal website. That being said, I cannot find those posts for the life of me this time around. I should have saved them >:/
So, I apologize for the duplicate, but I am attempting to do one of those "click anywhere BUT here to close element overlay" things. Works beautifully in Chrome, but not so much in Mozilla. To top it off, other elements that I have used this for are working perfectly (in both Mozilla and Chrome), just not this one.
jQuery
function closeProductOverlay() {
    if (!$(event.target).closest('#clickControl').length) {
        $('#productOverlay').toggle('fast', 'linear');
    }
}

HTML

As I've said, I've applied this concept to many features throughout the same project/website, and they all work flawlessly. I'm at my wits end trying to diagnose this.
I've tried a few messy "fixes," but none of them function the way they are intended. The closest I've gotten is if remove the if statement like so:
jQuery
function closeProductOverlay() {
    $('#productOverlay').toggle('fast', 'linear');
}

But then, obviously, if you click ANYWHERE, the overlay goes away. (Even if you are clicking buttons, or attempting to copy text). It's very annoying, and doesn't work as I need it to.

A: event is not global in Firefox like it is in IE or Chrome.
One solution is to change your function to pass the event into it:
function closeProductOverlay(event) {

And change the binding:


text:
Q: issues with concurrent update in titan graph database public class a {
    private static TitanGraph titanGraph = null;
    static GraphTraversalSource traversalSource = null;
public static void main(String a[])
{
    titanGraph = TitanFunctions.getTitanGraph();
    traversalSource = titanGraph.traversal();
    // Task to be executed by each thread
    Runnable r = new Runnable() {
        public void run() {

            long ab = traversalSource.V().has("RequestJob", "RequestId", 203)
                    .has("JobLockStatus","F")
                    .property("JobLockStatus", "B").count().next();
            titanGraph.tx().commit();
            System.out.println("value: "+ab+" : " +Thread.currentThread().getName());
        }
    };
    Thread t1 = new Thread(r, "T1");
    Thread t2 = new Thread(r, "T2");
    t1.start();
    t2.start();
    }}

In the above program, Two concurrent threads are trying to update the  value..from "F" to "B" for the same RequestId=203.
It seems like both threads are getting the  status value as "F" and updating it to B.
But I want only one thread should change the value from "F" to "B". After updating the value , I have used commit() also to save the changes.
If any thread changed the status from "(F)ree" to "(B)usy"..and other thread should see the changed value..("B").
Kindly help me to resolve this.

A: You could use a mutex or a synchronized() block to ensure only one thread can perform that operation at any given time. Something like the following may work:
titanGraph = TitanFunctions.getTitanGraph();
traversalSource = titanGraph.traversal();
Runnable r = new Runnable() {
    public void run() {
        synchronized(titanGraph){
            long ab = traversalSource.V().has("RequestJob", "RequestId", 203)
                .has("JobLockStatus","F")
                .property("JobLockStatus", "B").count().next();
            titanGraph.tx().commit();
        }
    }
};
Thread t1 = new Thread(r, "T1");
Thread t2 = new Thread(r, "T2");
t1.start();
t2.start();

So the above block synchronized(titanGraph) is basically stating that for whatever is inside that block it can only executed by a thread that has the lock on the object within the brackets. In this case the titanGraph. If a thread does not have the lock then it waits for the lock to become available.
Here is a really nice tutorial on using synchronized


text:
Q: Newspaper python cache issue, every call same output I use this module: https://github.com/codelucas/newspaper to download bitcoin articles from https://news.bitcoin.com/. But when I try to get next articles from next page 'https://news.bitcoin.com/page/2/page' I get same output. Same for any other page.
I have tried with different sites and different starting pages. The articles from first link I used were displayed on all other links.
import newspaper

url = 'https://news.bitcoin.com/page/2'
btc_articles = newspaper.build(url, memoize_articles = False)

for article in btc_articles.articles:
    print(article.url)

A: The newspaper library tries to scrape the whole website, not just the link you input. This means that you shouldn't have to loop through all pages to the get the articles.
However, as you might have noted the lib doesn't find all articles anyway.
The reason for this seems to be that it doesn't identify all pages as categories (and doesn't find the feed), see below (the output was the same regardless of page):
import newspaper

url = 'https://news.bitcoin.com/'
btc_paper = newspaper.build(url, memoize_articles = False)

print('Categories:', [category.url for category in btc_paper.categories])
print('Feeds:', [feed.url for feed in btc_paper.feeds])

Output:
Categories: ['https://news.bitcoin.com/page/2', 'https://news.bitcoin.com']
Feeds: []

This is seems to be a bug in the code (or bad website design on bitcoins part depending on how you look at it), just as you have noted in your trouble report https://github.com/codelucas/newspaper/issues/670.


text:
Q: Extracting data from nested dicts and lists Say I have a dict that looks like this:
dic = {'outer_key_1': {'inner_key_1': [1, 2, 3],
                       'inner_key_2': [4, 5, 6],
                       'inner_key_3': [7, 8, 9]},
       'outer_key_2': {'inner_key_1': [11, 12, 13],
                       'inner_key_2': [14, 15, 16],
                       'inner_key_3': [17, 18, 19]}}

My goal is to extract the first element of every inner dict, ending up with a nested list:
[[1, 4, 7], [11, 14, 17]]

Or, alternatively, a dict like this:
{'outer_key_1': [1, 4, 7], 'outer_key_2': [11, 14, 17]}

I have tried getting there with nested list comprehensions, but the best I could come up with is a non-nested list of the result values (more or less [1, 4, 7, 11, 14, 17] except that the values get mixed up, which should be easy to fix by using an OrderedDict instead). Here is a rather ugly solution using for loops, but I'm sure someone here can come up with something better.
# TODO: find a better way to do this
result = []
for inner_dict in dic.values():
    result.append([l[0] for l in inner_dict.values()])
print(result)

which prints (once again, values are mixed up, but that's not the problem at hand):
[[14, 17, 11], [4, 7, 1]]

What would be the most elegant way to solve that? I'm pretty new to python, so any hints on how to approach that problem are appreciated. I have also tried experimenting with zip, which I think should be a pretty nice way to do it, but I still need to wrap my head around how to use that together with list comprehensions, so... Any suggestions?

A: Here is one way:
>>> {outerKey: [innerVal[0] for innerVal in outerVal.itervalues()] for outerKey, outerVal in dic.iteritems()}
{'outer_key_1': [4, 7, 1], 'outer_key_2': [14, 17, 11]}

That is a dictionary comprehension with a list comprehension inside.  The outer dict comprehension iterates over the key-alue pairs of the outer dict.  The inner list comprehension makes a list of the first item in each inner value (i.e., each list in the inner dict).
If you want a list instead just make the dict comprehension into a list comprehension (removing the reference to the outer key):
>>> [[innerVal[0] for innerVal in outerVal.itervalues()] for outerKey, outerVal in dic.iteritems()]
[[14, 17, 11], [4, 7, 1]]

Note that you cannot control the order of the lists, because the original dict is unordered.

A: Dictionaries in Python are not sorted by default. If the order is important, you can sort before  you get the values.
result = []
for inner_dict in sorted(dic.values()):
    res = []
    for l in sorted(inner_dict.values()):
        res.append(l[0])
    result.append(res)

print(result)
# Output: [[1, 4, 7], [11, 14, 17]]

If you need to use the dictionaries as sorted entities beyond this, it might be a good idea to look into using an OrderedDict, which keeps them in order by default.

A: You could use zip to transpose the values:
[ (list(zip(*d.values())[0])) for d in dic.values()]
[[14, 17, 11], [4, 7, 1]]

If you want sorted output:
[(list(zip(*sorted(d.values()))[0])) for d in sorted(dic.values())]

A: It depends what you mean by elegance, but to me, the following is quite elegant if you understand functional programming well
[zip(*e)[0] for e in map(dict.values, dic.values())]

So what it does

*

*dic.values() returns a list of values in the dictionary

*map(dict.values, dic.values()) returns a second level nested values in the dictionary

*finally for each list of nested values, transpose it using zip and fetch the first row, which infact is the first column in the deeply nested dict.

If you want to optimize further

*

*Replace map with itertools.imap

*If you are still in Python 2.X, replace dict.values with dict.itervalues


text:
Q: Recursive sum of values in an hierarchical table in Oracle 10g Assuming I have this table:
CREATE TABLE MY_EXAMPLE ( ID NUMBER , PARENT NUMBER , VALUE NUMBER );

Insert into MY_EXAMPLE (ID,PARENT,VALUE) values (1,null,100);
Insert into MY_EXAMPLE (ID,PARENT,VALUE) values (2,1,50);
Insert into MY_EXAMPLE (ID,PARENT,VALUE) values (3,null,0);
Insert into MY_EXAMPLE (ID,PARENT,VALUE) values (4,2,1000);
Insert into MY_EXAMPLE (ID,PARENT,VALUE) values (5,1,1);

|id   |parent   |value   |
|1    |null     |100     |
|2    |1        |50      |
|3    |null     |0       |
|4    |2        |1000    |
|5    |1        |1       |

I need to create a view (which should perform well) with the same number of rows but giving the row's plus the children's value summed. Many levels are possible as well as many children.
|id   |parent   |value   |
|1    |null     |1151    | (sum of 1 + 2 + 4 + 5)
|2    |1        |1050    | (sum of 2 + 4)
|3    |null     |0       | (only 3 because has no children)
|4    |2        |1000    | (only 4 because has no children)
|5    |1        |1       | (only 5 because has no children)

ps.: I tried something like this but it didn't work in Oracle 10g first because the keyword RECURSIVE is not supported and second because it won't allow recursive WITH ("forward or recursive reference of a query name in WITH clause is not allowed").
Also I couldn't figure out a way to do it with CONNECT BY that includes the id and parent columns and gives me the whole table (in my attempts I always had to use START WITH).

A: You will have to create a recursive function:
CREATE FUNCTION RECURSIVE_ADD(
    ROOT_ID IN NUMBER)
  RETURN NUMBER
IS
  TOTAL NUMBER;
BEGIN
  SELECT   SUM(VALUE)
    INTO TOTAL
    FROM (
      (
        SELECT VALUE FROM MY_EXAMPLE WHERE ID = ROOT_ID
      )
    UNION
        (
          SELECT recursive_add(id) FROM my_example WHERE parent = root_id
        ));
  RETURN total;
END;

select id, parent, value, RECURSIVE_ADD(id) from my_example;

Make sure you don't have a cycle in your data (for example, if you set the parent of 1 to 2) otherwise this will never terminate. There are other ways to do this in newer versions of Oracle, but this will work in 10g.


text:
Q: How to impose Google App Engine's DeadlineExceededException? I'd like to take the attitude that if my server-side is too slow, just throw an exception and send back a meaningful error message to the client. I am arbitrarily setting this time limit to 5 seconds and will tweak it as needed.
I see that App Engine has ApiProxy.getCurrentEnvironment().getRemainingMillis() which gives us the number of milliseconds we have left before it throws a DeadlineExceedException and times us out.
I'd like to do something similar, but imposing my own 5-second restriction over GAE's 60-second restriction (again, for right now doesn't matter if I pick 5-seconds or 40-seconds, as long as they are stricter than what GAE imposes). I'd like to write a server-side handler/servlet that starts a 5-second timer. If the request does not return inside that amount of time it throws an exception and returns to the client:
public class MyTimedServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        // Start 5-second timer
        Timer timer = new Timer(5000);

        try {
            timer.start();
            response = handleRequest(request);
        }
        catch(TimeException timerException) {
            response = ResponseFactory.newTimeExceededResponse();
        }
    }
}

Unfortunately, I don't see anything in the GAE API that resembles the Timer object that I'm looking for.
I'm already planning on making use of multihthreading every request via ThreadManager.currentRequestThreadFactory().newRequestThread(...), so I don't want to waste one of these (I only get 10 at a time!) threads to create a background "Timer Thread" unless I absolutely have to.
So I ask: does GAE have something like this out of the box, and if I have to roll my own, how do I go about doing so? Thanks in advance!

A: Any asynchronous task (that don't follow the normal flow) in your code involves a new thread execution, in this case this task is to count the time.
However you can use the classes Timer & TimerTask both of them included in the App-Engine JRE white list.
Example code: not tested just a guide.
public class YourServlet extends HttpServlet {

    Timer timer;
    HttpServletResponse response;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)...{
        int seconds = 5;
        timer = new Timer();
        timer.schedule(new DeadLine(), seconds * 1000);

        /* the rest of your code here */
    }

    class DeadLine extends TimerTask {
        public void run() {
            response.getWriter().print("Error: deadline reached.");
        }
      }
}

Read this article about job scheduling in Java, for more info.


text:
Q: Allow sessions on multiple domains with www and without www I have multiple domains pointing to one Web application. Here are a few, just as an examples, so that I can reference them in my examples.

*

*www.mydomain.com

*sub.mydomain.com

*www.affiliatedomain.com
ASP.NET allows for a web.config setting to accomplish this:
<httpCookies httpOnlyCookies="true" domain=".mydomain.com" />
This allows me to share sessions between the www.mydomain.com and mydomain.com domains. Perfect! Except it only works for one domain.
Another avenue I explored was url rewriting. I could insert a rewrite rule to ensure that only www urls are being accessed but doing so (at least the one I write) works for the domains, but appends a www. to the sub.mydomain.com resulting in a failed www.sub.mydomain.com - which won't work. Perhaps this option could still work if someone knows how to formulate url rewrite urls better than me.
Finally, to be clear, I don't need to share sessions across all domains (I know this is not possible). I just would like to share domains across the same domain with and without www.
For example: www.mydomain.com and mydomain.com
Or www.affiliatedomain.com and affiliatedomain.com
The sub.mydomain.com can live on its own so long as it never has a www. in front of it.

A: I think the rewrite option is best for your case, something like this should fix the sub domain rewrite issue.
<rewrite>
    <rules>
        <rule name="Redirect domain.com to www" patternSyntax="Wildcard" stopProcessing="true">
            <match url="*" />
            <conditions>
                <add input="{HTTP_HOST}" pattern="^domain.com$" />
            </conditions>
            <action type="Redirect" url="http://www.domain.com/{R:0}" />
        </rule>
    </rules>
</rewrite>


text:
Q: How can I find Saturdays and Sundays in A given month? I want find all Saturdays and Sundays in A given month. How can I do so?

A: Try this:
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Sundays {
    public static void main(String[] args) {
        int year = 2012;

        // put the month you want
        int month = Calendar.JANUARY;

        Calendar cal = new GregorianCalendar(year, month, 1);
        do {
            int day = cal.get(Calendar.DAY_OF_WEEK);
            if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
                System.out.println(cal.get(Calendar.DAY_OF_MONTH));
            }
            cal.add(Calendar.DAY_OF_YEAR, 1);
        }  while (cal.get(Calendar.MONTH) == month);
    }
}

A: The simplest way is to just iterate over all the days in the month, and check the day of week for each of them. For example:
// This takes a 1-based month, e.g. January=1. If you want to use a 0-based
// month, remove the "- 1" later on.
public int countWeekendDays(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    // Note that month is 0-based in calendar, bizarrely.
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month - 1, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY || dayOfweek == Calendar.SATURDAY) {
            count++;
            // Or do whatever you need to with the result.
        }
    }
    return count;
}

I'm absolutely sure there are far more efficient ways of doing this - but that's what I'd start with, and optimize when I'd found it's too slow.
Note that if you're able to use Joda Time that would make your life a lot easier...

A: Base on the previous answer, I have a small modification
When u find the first Saturday and Sunday, you can simply add 7 days to it until the month is changed.

A: The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice at the Home Page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getWeekends(2));// All weekends of Feb in the current year
        System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
    }

    /*
     * All weekends (Sat & Sun) of the given month in the current year
     */
    static List<LocalDate> getWeekends(int month) {
        LocalDate firstDateOfTheMonth = LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());

        return firstDateOfTheMonth
                .datesUntil(firstDateOfTheMonth.plusMonths(1))
                .filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                .collect(Collectors.toList());
    }

    /*
     * All weekends (Sat & Sun) of the given year and the month
     */
    static List<LocalDate> getWeekends(int year, int month) {
        LocalDate firstDateOfTheMonth = YearMonth.of(year, month).atDay(1);

        return firstDateOfTheMonth
                .datesUntil(firstDateOfTheMonth.plusMonths(1))
                .filter(date -> date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                .collect(Collectors.toList());
    }
}

Output:
[2021-02-06, 2021-02-07, 2021-02-13, 2021-02-14, 2021-02-20, 2021-02-21, 2021-02-27, 2021-02-28]
[2020-02-01, 2020-02-02, 2020-02-08, 2020-02-09, 2020-02-15, 2020-02-16, 2020-02-22, 2020-02-23, 2020-02-29]

ONLINE DEMO
Non-Stream solution:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getWeekends(2));// All weekends of Feb in the current year
        System.out.println(getWeekends(2020, 2));// All weekends of Feb 2020
    }

    /*
     * All weekends (Sat & Sun) of the given month in the current year
     */
    static List<LocalDate> getWeekends(int month) {
        LocalDate firstDateOfTheMonth = LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth());
        List<LocalDate> list = new ArrayList<>();

        for (LocalDate date = firstDateOfTheMonth; !date
                .isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
            if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                list.add(date);

        return list;
    }

    /*
     * All weekends (Sat & Sun) of the given year and the month
     */
    static List<LocalDate> getWeekends(int year, int month) {
        LocalDate firstDateOfTheMonth = YearMonth.of(year, month).atDay(1);
        List<LocalDate> list = new ArrayList<>();

        for (LocalDate date = firstDateOfTheMonth; !date
                .isAfter(firstDateOfTheMonth.with(TemporalAdjusters.lastDayOfMonth())); date = date.plusDays(1))
            if (date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                list.add(date);

        return list;
    }
}

ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

A: Please go through this method, I faced a lot finally I created my own.
public static int getDayDiff(String dateFrom, String dateTo){ // DD/MM/YYYY
    Timestamp tDtF = getTimestampDDmmYYYY(dateFrom);//returning timestamp from / DD/MM/YYYY
    Timestamp tDtT = getTimestampDDmmYYYY(dateTo);
    Calendar dtF = new GregorianCalendar();
    Calendar dtT = new GregorianCalendar();
    dtF.setTimeInMillis(tDtF.getTime());
    dtT.setTimeInMillis(tDtT.getTime());
    int count = 0;
    while(dtF.before(dtT)){
        count++;
        dtF.add(Calendar.DAY_OF_YEAR, 1);
    }
    return count;
}

public static int countDateSatOrSun(String dateFrom, String dateTo){//DD/MM/YYYY
    Timestamp tDtF = getTimestampDDmmYYYY(dateFrom);//returning timestamp from / DD/MM/YYYY
    Timestamp tDtT = getTimestampDDmmYYYY(dateTo);
    Calendar dtF = new GregorianCalendar();
    Calendar dtT = new GregorianCalendar();
    dtF.setTimeInMillis(tDtF.getTime());
    dtT.setTimeInMillis(tDtT.getTime());
    int count = 0;
    while(dtF.before(dtT)){
        if((dtF.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY| dtF.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY))
                count++;
        dtF.add(Calendar.DAY_OF_YEAR, 1);
    }
    return count;
}

It will give you exact result.


text:
Q: Integrate two docker apps - Docker compose and Docker run I am trying to integrate two apps. Currently I have a docker-compose file with two services and another docker - run command to start another service. Based on my configuration below, I expect OHIF Viewer running at port 3030 and Orthanc running at 8042 to be interconnected. I mean if I upload an image in Orthanc, I should be able to see them in OHIF viewer. Currently I am able to view both Orthanc and OHIF viewer in their respective ports but I don't see any interaction between them. ex: I don't see my image (uploaded in Orthanc) in OHIF Viewer.
I thought the dockersupport-app.json file is responsible for this interaction as it has info regarding port 8042 and being used in "Volumes" section of docker-compose.yml file.
Here is my docker-compose file
version: '3.6'
  services:
     mongo:
   image: "mongo:latest"
   container_name: ohif-mongo
   ports:
     - "27017:27017"

  viewer:
     image: ohif/viewer:latest
     container_name: ohif-viewer
     ports:
       - "3030:80"
     environment:
       - MONGO_URL=mongodb://mongo:27017/ohif
     extra_hosts:
      - "pacsIP:172.xx.xxx.xxx"
     volumes:
      - ./dockersupport-app.json:/app/app.json

The dockersupport-app.json looks like as shown below
  {
 "apps" : [{
 "name"        : "ohif-viewer",
  "script"      : "main.js",
  "watch"       : true,
  "merge_logs"  : true,
  "cwd"         : "/app/bundle/",
  "env": {
  "METEOR_SETTINGS": {
          "servers": {
            "dicomWeb": [
                                {
                "name": "Orthanc",
                "wadoUriRoot": "http://pacsIP:8042/wado", # these ports
                "qidoRoot": "http://pacsIP:8042/dicom-web", #these ports
                "wadoRoot": "http://pacsIP:8042/dicom-web", #these ports
                "qidoSupportsIncludeField": false,
                "imageRendering": "wadouri",
                "thumbnailRendering": "wadouri",
                "requestOptions": {
                  "auth": "orthanc:orthanc",
                  "logRequests": true,
                  "logResponses": false,
                                 "logTiming": true
                    }
                  }
                ]
              },
              "defaultServiceType": "dicomWeb",
              "public": {
                            "ui": {
                                    "studyListDateFilterNumDays": 1
                            }
                    },
              "proxy": {
                "enabled": true
              }
            }
              }
           }]
    }

My docker run command to start Orthanc in port 8042 looks like as shown below
docker run -p 4242:4242 -p 8042:8042 --rm --name orthanc -v
 $(pwd)/orthanc/config/orthanc.json:/etc/orthanc/orthanc.json -v
 $(pwd)/orthanc/config/orthanc-db:/var/lib/orthanc/orthanc-db
  jodogne/orthanc-
   plugins /etc/orthanc --verbose

Can you please help me as to how can I integrate these two? The above all files/codes is the info I have.

A: The configuration is not working mainly because dockersupport-app.json is not read by the application. Below is a working example based on the online documentation of the project.
Also another problem is the access to the dicomWeb server. You are using pacsIP:8042, which would be ok if the request was initiated from inside the container. But this is a javascript application and the request is initiated by the browser on the host. For this reason "localhost" should be used.
This is a working configuration:
version: '3.6'

services:
  mongo:
   image: "mongo:latest"
   container_name: ohif-mongo
   ports:
     - "27017:27017"

  viewer:
     image: ohif/viewer:latest
     container_name: ohif-viewer
     ports:
       - "3030:80"
     environment:
       - MONGO_URL=mongodb://mongo:27017/ohif
     volumes:
      - ./config/default.js:/usr/share/nginx/html/config/default.js
     depends_on:
      - mongo
      - proxy

  orthanc:
    image: jodogne/orthanc-plugins
    ports:
      - "4242:4242"
      - "8042:8042"
    volumes:
      # Config
      - ./config/orthanc.json:/etc/orthanc/orthanc.json:ro
      # Persist data
      - ./volumes/orthanc-db/:/var/lib/orthanc/db/
    command: "/etc/orthanc --verbose"

  proxy:
    image: nginx:1.15-alpine
    ports:
      - 8899:80
    volumes:
      - ./config/nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - orthanc
    restart: unless-stopped

In the config folder place the files:
default.js
window.config = {
    // default: '/'
    routerBasename: '/',
    // default: ''
    relativeWebWorkerScriptsPath: '',
    servers: {
      dicomWeb: [
        {
          name: 'DCM4CHEE',
          wadoUriRoot: 'http://localhost:8899/wado',
          qidoRoot: 'http://localhost:8899/dicom-web',
          wadoRoot: 'http://localhost:8899/dicom-web',
          qidoSupportsIncludeField: true,
          imageRendering: 'wadouri',
          thumbnailRendering: 'wadouri',
          requestOptions: {
            requestFromBrowser: true,
            auth: "orthanc:orthanc",
            "logRequests": true,
            "logResponses": true,
             "logTiming": true
          },
        },
      ],
    },
    // Extensions should be able to suggest default values for these?
    // Or we can require that these be explicitly set
    hotkeys: [
      // ~ Global
      {
        commandName: 'incrementActiveViewport',
        label: 'Next Image Viewport',
        keys: ['right'],
      },
      {
        commandName: 'decrementActiveViewport',
        label: 'Previous Image Viewport',
        keys: ['left'],
      },
      // Supported Keys: https://craig.is/killing/mice
      // ~ Cornerstone Extension
      { commandName: 'rotateViewportCW', label: 'Rotate Right', keys: ['r'] },
      { commandName: 'rotateViewportCCW', label: 'Rotate Left', keys: ['l'] },
      { commandName: 'invertViewport', label: 'Invert', keys: ['i'] },
      {
        commandName: 'flipViewportVertical',
        label: 'Flip Horizontally',
        keys: ['h'],
      },
      {
        commandName: 'flipViewportHorizontal',
        label: 'Flip Vertically',
        keys: ['v'],
      },
      { commandName: 'scaleUpViewport', label: 'Zoom In', keys: ['+'] },
      { commandName: 'scaleDownViewport', label: 'Zoom Out', keys: ['-'] },
      { commandName: 'fitViewportToWindow', label: 'Zoom to Fit', keys: ['='] },
      { commandName: 'resetViewport', label: 'Reset', keys: ['space'] },
      // clearAnnotations
      // nextImage
      // previousImage
      // firstImage
      // lastImage
      {
        commandName: 'nextViewportDisplaySet',
        label: 'Previous Series',
        keys: ['pagedown'],
      },
      {
        commandName: 'previousViewportDisplaySet',
        label: 'Next Series',
        keys: ['pageup'],
      },
      // ~ Cornerstone Tools
      { commandName: 'setZoomTool', label: 'Zoom', keys: ['z'] },
    ],
  };

nginx.conf
worker_processes 1;

events { worker_connections 1024; }

http {

    upstream orthanc-server {
        server orthanc:8042;
    }

    server {
        listen [::]:80 default_server;
        listen 80;

        # CORS Magic
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow_Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

        location / {

            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow_Credentials' 'true';
                add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
                add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }

            proxy_pass         http://orthanc:8042;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;

            # CORS Magic
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow_Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
        }
    }
}

orthanc.json
{
  "Name": "Orthanc inside Docker",
  "StorageDirectory": "/var/lib/orthanc/db",
  "IndexDirectory": "/var/lib/orthanc/db",
  "StorageCompression": false,
  "MaximumStorageSize": 0,
  "MaximumPatientCount": 0,
  "LuaScripts": [],
  "Plugins": ["/usr/share/orthanc/plugins", "/usr/local/share/orthanc/plugins"],
  "ConcurrentJobs": 2,
  "HttpServerEnabled": true,
  "HttpPort": 8042,
  "HttpDescribeErrors": true,
  "HttpCompressionEnabled": true,
  "DicomServerEnabled": true,
  "DicomAet": "ORTHANC",
  "DicomCheckCalledAet": false,
  "DicomPort": 4242,
  "DefaultEncoding": "Latin1",
  "DeflatedTransferSyntaxAccepted": true,
  "JpegTransferSyntaxAccepted": true,
  "Jpeg2000TransferSyntaxAccepted": true,
  "JpegLosslessTransferSyntaxAccepted": true,
  "JpipTransferSyntaxAccepted": true,
  "Mpeg2TransferSyntaxAccepted": true,
  "RleTransferSyntaxAccepted": true,
  "UnknownSopClassAccepted": false,
  "DicomScpTimeout": 30,

  "RemoteAccessAllowed": true,
  "SslEnabled": false,
  "SslCertificate": "certificate.pem",
  "AuthenticationEnabled": false,
  "RegisteredUsers": {
    "test": "test"
  },
  "DicomModalities": {},
  "DicomModalitiesInDatabase": false,
  "DicomAlwaysAllowEcho": true,
  "DicomAlwaysAllowStore": true,
  "DicomCheckModalityHost": false,
  "DicomScuTimeout": 10,
  "OrthancPeers": {},
  "OrthancPeersInDatabase": false,
  "HttpProxy": "",

  "HttpVerbose": true,

  "HttpTimeout": 10,
  "HttpsVerifyPeers": true,
  "HttpsCACertificates": "",
  "UserMetadata": {},
  "UserContentType": {},
  "StableAge": 60,
  "StrictAetComparison": false,
  "StoreMD5ForAttachments": true,
  "LimitFindResults": 0,
  "LimitFindInstances": 0,
  "LimitJobs": 10,
  "LogExportedResources": false,
  "KeepAlive": true,
  "TcpNoDelay": true,
  "HttpThreadsCount": 50,
  "StoreDicom": true,
  "DicomAssociationCloseDelay": 5,
  "QueryRetrieveSize": 10,
  "CaseSensitivePN": false,
  "LoadPrivateDictionary": true,
  "Dictionary": {},
  "SynchronousCMove": true,
  "JobsHistorySize": 10,
  "SaveJobs": true,
  "OverwriteInstances": false,
  "MediaArchiveSize": 1,
  "StorageAccessOnFind": "Always",
  "MetricsEnabled": true,

  "DicomWeb": {
    "Enable": true,
    "Root": "/dicom-web/",
    "EnableWado": true,
    "WadoRoot": "/wado",
    "Host": "127.0.0.1",
    "Ssl": false,
    "StowMaxInstances": 10,
    "StowMaxSize": 10,
    "QidoCaseSensitive": false
  }
}

With this configuration in place run:
docker-compose up -d viewer

Upload images: http://localhost:8899
View the images in the viewer: http://localhost:3030


text:
Q: Unknown size compile error when defining generic trait Being a beginner in Rust programming I'm a bit confused by the Size trait in conjunction with generic traits.
My custom trait defines a single method that takes two objects and combines them into a new one. Because the original objects expire after combination, the method should take ownership of the parameters.
I also return a result with a custom error type because the combination might fail and I want to give the caller the reason for the failure.
The trait in question is:
pub trait Combinable<T> {
    fn combine(self, other: T) -> CombinationResult<T>;
}
struct CombinationError;

type CombinationResult<T> = std::result::Result<dyn Combinable<T>, CombinationError>

When compiling this code I get the following error:
error[E0277]: the size for values of type `(dyn Combinable<T> + 'static)` cannot be known at compilation time
    |
7   |     fn combine(self, other: T) -> CombinationResult<T>;
    |                                   ^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time

    |
241 | pub enum Result<T, E> {
    |                 - required by this bound in `std::result::Result`
    |
    = help: the trait `Sized` is not implemented for `(dyn Combinable<T> + 'static)`

I tried constraining the generic type parameter T to Sized (i.e. pub trait Combinable<T: Sized>) but that didn't work. I also tried the same at the type alias declaration, also to no avail.
Am I missing/overlooking something?

A: dyn Combinable<T> can only be used behind a reference (&, Box, Rc…). Since you want to transfer ownership of the combined items, you have two options:

*

*Easiest is to just box the result: type CombinationResult<T> = std::result::Result<Box<dyn Combinable<T>>, CombinationError>; but this adds some overhead in the form of memory allocation and indirection.

*Or you can use a generic type to avoid the indirection:
pub trait Combinable<T> {
    type Combined;
    fn combine(self, other: T) -> CombinationResult<Self::Combined>;
}
pub struct CombinationError;

type CombinationResult<T> = std::result::Result<T, CombinationError>;

Playground
The second solution works by moving the combined items into the returned value. Here's how we would do it without generics, traits nor error handling:
struct ItemA {}
struct ItemB {}
impl ItemA {
    fn combine (self, other: ItemB) -> CombinedAB {
        CombinedAB { a: self, b: other }
    }
}

struct CombinedAB {
    a: ItemA,
    b: ItemB,
}

Playground
Notice that the type returned by the combine method depends on the type of the inputs. If we want to abstract the combine method into a trait, we can't fix the return type when we declare the trait since we don't yet know the types that will be used in the implementation. For this reason we use an associated type, which is a way of saying: "this type will be specified by the implementation". Here's the same example using traits and generics:
pub trait Combinable<T> {
    type Combined;
    fn combine(self, other: T) -> Self::Combined;
}

struct ItemA {}
struct ItemB {}

struct CombinedAB {
    a: ItemA,
    b: ItemB,
}

impl Combinable<ItemB> for ItemA {
    type Combined = CombinedAB;
    fn combine (self, other: ItemB) -> CombinedAB {
        CombinedAB { a: self, b: other }
    }
}

Playground
Note that I used a generic type for the parameter and an associated type for the returned value. This question gives more details and explains when to use one or the other.
Of course if the combine method should return the same concrete type for all inputs, then you can dispense with the associated type altogether:
struct Combined {}
pub trait Combinable<T> {
    fn combine(self, other: T) -> Combined;
}

A: The dyn Combinable<T> is an unsized type (since traits can be implemented by any manner of types, the size of the value is not known at compile time). This in turn means that Result<dyn Combinable<T>, ...> is also unsized. Unsized types are fairly limited with one of those limitations being they cannot be returned by value. You can only meaningfully handle unsized types through some kind of indirection (reference, pointer, etc.)
The usual fix is to box them:
type CombinationResult<T> = std::result::Result<Box<dyn Combinable<T>>, CombinationError>
                                             // ^^^


text:
Q: Prevent focus on Expand More button after content is inserted in React I need to list out a long name list inside my page while showing all names at first is not desirable.
So I try to add an expand more button on it.

However, using a button will keep the browser focus on that button after it's pressed, left the button position unchanged on the screen while the name was inserted before that button.
On the other hand, using any, not focusable element (eg. div with onclick function) will do the desired behavior but lost the accessibility at all. Making the "button" only clickable but not focusable.
How do I make the button flushed to list bottom like the snippet div block does? Or is there a better choice to expand the existing list?

const myArray = [
  'Alex',
  'Bob',
  'Charlie',
  'Dennis',
  'Evan',
  'Floron',
  'Gorgious',
  'Harris',
  'Ivan',
  'Jennis',
  'Kurber',
  'Lowrance',
]
const ExpandList = (props) => {
  const [idx, setIdx] = React.useState(8)
  const handleExpand = e => {
    setIdx(idx + 1)
  }
  return

Name List

    {myArray.slice(0,idx).map(
      name =>
{name}

    )}

      <button onClick={handleExpand} children='Button Expand' className='pointer' />

Div Expand

}

ReactDOM.render(<ExpandList/>, document.getElementById('root'))
.demo>p {
  display: block;
  padding: 20px;
  color: #666;
  background: #3331;
}

.demo>div>div {
  display: flex;
  padding: 15px;
  margin-left: auto;
  color: #666;
  background: #3331;
}

.pointer {
  cursor: pointer;
}

.pointer:hover {
  background-color: #6663;
}

hello

A: Removing focus from the button in the click handler is probably the most elegant approach: e.target.blur(). It will work on any HTML element, whether it is focusable or not (as with the div in your case).

const myArray = [
  'Alex',
  'Bob',
  'Charlie',
  'Dennis',
  'Evan',
  'Floron',
  'Gorgious',
  'Harris',
  'Ivan',
  'Jennis',
  'Kurber',
  'Lowrance',
]
const ExpandList = (props) => {
  const [idx, setIdx] = React.useState(8)
  const handleExpand = e => {
    e.target.blur()
    setIdx(idx + 1)
  }
  return

Name List

    {myArray.slice(0,idx).map(
      name =>
{name}

    )}

      <button onClick={handleExpand} children='Button Expand' className='pointer' />

Div Expand

}

ReactDOM.render(<ExpandList/>, document.getElementById('root'))
.demo>p {
  display: block;
  padding: 20px;
  color: #666;
  background: #3331;
}

.demo>div>div {
  display: flex;
  padding: 15px;
  margin-left: auto;
  color: #666;
  background: #3331;
}

.pointer {
  cursor: pointer;
}

.pointer:hover {
  background-color: #6663;
}

hello

A: Inspired by @MiKo, temporally unmount the button after click and set a timeout to add it back seems to do the work. Since browser lose the focus on original expand button, this will keep content flush down without focusing the original button:
const ExpandList = (props) => {
  const [idx, setIdx] = React.useState(8)
  const [showBtn, setShowBtn] = React.useState(true)
  const handleExpand = e => {
    setShowBtn(false)
    setIdx(idx + 1)
    setTimeout(() => setShowBtn(true), 10)
  }
  return

Name List

    {myArray.slice(0,idx).map(
      name =>
{name}

    )}
    {showBtn?

        <button onClick={handleExpand} children='Button Expand' className='pointer' />

Div Expand

 :

    }

}

But I'm still looking a method that doesn't need to 'unmount' a thing which should be there all time.


text:
Q: Estimating Assembly costs II This is a continuation of Estimating Assembly Cost which has addressed some approximations in estimating between North American and Asian assembly houses as price per pin.
The question does not address number of items in BOM and how significant / insignificant a reduction in a BOM might be.
For instance, if I have a BJT that costs $0.03  and a diode that costs $0.03, I could (if allowed) replace the diode with the BJT and my parts cost would more or less be the same. But now I'll have one less item on my BOM.
For each item on a BOM, what rules of thumbs can be applied to estimate cost ?
or
For each item removed from a BOM, what rules of thumb can be applied to estimate cost ?

A: It's not easy to have one answer.
There are several factors to take into account.
Imagine you have 4 A components in your BOM and one B component. If you replace B by A then you'll end up with 5 A and 0 B. The less component you have the higher unit price, so you optimized the unit price by removing B and adding 1 unit to A so A unit price should decrease.
But it's difficult to estimate the optimized quantity. Component price will follow kind of log curve. So if you have already 100 A units and add one instead of B, you'll only save on B price. A price won't decrease much.
Also if you can remove a significant number of reference, assembly house will need less round to place components as placing machine have limited slots for component reels.
So you need to discuss with the assembly house how many reels and tray they can have in placing machine.
Price optimization is also dependent of overall quantity: if you're doing a 500 board production with around 200 components/board then overall quantity is not that much and it will be difficult to negociate prices.
But if you're making consumer electronics, then BOM optimization is dependent of purchasing department, as they will put coefficient on components regarding their price.


text:
Q: Simple program with std::string is not working I am learning std::string and I want to :

*

*Input string

*Every second letter make Uppercase

*Output new string
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string myStr;
    getline(cin,myStr);
    if (myStr.begin() != myStr.end())
    {
        for (auto it = myStr.begin(); it != myStr.end() ; it += 2)
            *it = toupper(*it);
    }
    cout << myStr;
    system("pause");
    return 0;
}

But after input I am getting error here:

A: it += 2 leads you out of bounds, if the loop ending condition is it != myStr.end(). Thus dereferencing
*it = toupper(*it);

is undefined behavior.
it += 2 will never give you an exact iterator value of myStr.end() as you have for your loops termination condition.

As for your comment:

So how can i fix it ?

Just keep it simple and understandable, like e.g. using something like
for (size_t i = 0; i < myStr.length() ; ++i) {
    if(i % 2) { // Every second letter ...
        myStr[i] = toupper(myStr[i]);
    }
}


text:
Q: React native animation for fading one word into another I'm trying to find a way to fade "word1" into "word2" when a button is clicked using react native animation.
The way I'm approaching it now is by using absolute positioning word1 and word2 in the same location, and via an animation reducing/increasing opacity of each word. I increase opacity of word1 while simulataneously decrease opacity of word2, and vice versa.
This works great on IOS, but theres an issue on Android - it seems like Pressable don't really work in android when using absolute positioning: https://github.com/facebook/react-native/issues/27232

  const englishTextAnim = useRef(
    new Animated.Value(deviceLanguage === "en" ? 1 : 0)
  ).current;
  const spanishTextAnim = useRef(
    new Animated.Value(deviceLanguage == "es" ? 1 : 0)
  ).current;

...

            <Pressable
              onPress={() => {
              }}
              style={styles.nextButton}
            >
              <Animated.Text
                style={[styles.nextButtonText, { opacity: englishTextAnim }]}
              >
                Next
              </Animated.Text>
              <Animated.Text
                style={[styles.nextButtonText, { opacity: spanishTextAnim }]}
              >
                Siguiente
              </Animated.Text>
            </Pressable>

...

  nextButton: {
    alignSelf: "center",
    flex: 1,
    justifyContent: "center",
  },
  nextButtonText: {
    textAlign: "center",
    position: "absolute",
    alignSelf: "center",
  },

Are there any other ways of getting the same effect (fading one word into another when a button is clicked)?


text:
Q: How to wait for completion of asynchronous function c# winrt I have code which gets the photo from a web camera. I need to write a mechanism that would be expected to complete this process. How do I do this? I have the following code:
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var memStream3 = new Windows.Storage.Streams.InMemoryRandomAccessStream();
var mediaCaptureMgr1 = new MediaCapture();
await mediaCaptureMgr1.InitializeAsync();
mediaCaptureMgr1.SetPreviewMirroring(true);
await mediaCaptureMgr1.CapturePhotoToStreamAsync(imageProperties, memStream3);
await memStream3.FlushAsync();
memStream3.Seek(0);
WriteableBitmap wb1 = new WriteableBitmap(320, 240);
wb1.SetSource(memStream3);
//1
while (true)
{
    await Task.Delay(TimeSpan.FromSeconds(0.1));
    //if CapturePhotoToStreamAsync finished? OR memStream3 not null?
    //break;
}
//2

If I start to do anything with wb1 at //1, I will not work because wb1 = null. If I start doing it at //2 the wb1! = null because I waited until all the async function are completed.

A: Instead of wb1.SetSource(memStream3); you should call await wb1.SetSourceAsync(memStream3); and all should be good. Otherwise you could set var wb1 = new WriteableBitmap(1, 1); and wait until wb1.PixelWidth grows bigger than 1 when SetSource is done, but this method with Task.Delay polling is suboptimal.


text:
Q: Subtract Seconds from a User Inputted Time I have a calculator that calculates the time needed to heat water given the temperature of the water, desired temperature, water volume, energy applied, and thermal loss.  The output is in seconds.  I also have a field where the user can input a time.  How can I take that time and subtract the seconds from it?
JavaScript:
    function calculate() {
       var liters = document.getElementById("liters").value;
       var currentTemp = document.getElementById("currentTemp").value;
       var desiredTemp = document.getElementById("desiredTemp").value;
       var elementWattage = document.getElementById("elementWattage").value;
       var thermalLoss = document.getElementById("thermalLoss").value;
       var mashInTime = document.getElementById("mashInTime").value;

       var secondsToHeat = ((4186 * liters ((desiredTemp - currentTemp) * thermalLoss) / elementWattage);

}

HTML:

Liters:
    <input id="liters" onkeyup="calculate()" value="22">

Water Temperature °C:
    <input id="currentTemp" onkeyup="calculate()" value="15">

Desired Temperature °C:
    <input id="desiredTemp" onkeyup="calculate()" value="77">

Watts of Heating Element:
    <input id="elementWattage" onkeyup="calculate()" value="1000">

Thermal Loss (1.05 insulated, 1.1+ uninsulated):
    <input id="thermalLoss" onkeyup="calculate()" value="1.11">

Mash In Time:
    <input id="mashInTime" onkeyup="calculate()" value="">

Do I need to parse out the time entered?  Or do I need to convert the seconds into hours/minutes and then subtract?
Thanks!

A: You're on the right track using jQuery to simplify form validation. Once you get the time, I would convert it to seconds, that way the subtraction is fairly straightforward.
Once you have the start time in seconds, converting it back to the format you want displayed could be made easy with Moment.js. That link is to a Stack Overflow question dealing with time-formatting.


text:
Q: Android google map api 2 - click on map pin to launch external intent for driving direction I would like to add a button to the map pin's snippet to launch an external intent for driving direction to the pin.
I am thinking I can implement something that listens to long click the snippet box, brings up a pop-up to see if user would like to see driving direction and then launches the external activity.
Not sure there is an easy way to do it or the best UX design. Open up to suggestions!
This is my current setup map function:
private void maybeSetUpMapPin() {
  mMap.setMyLocationEnabled(true);
  CameraUpdate cameraUpdate;

  for (Location location : mLocations) {
    MarkerOptions markerOptions = new MarkerOptions()
      .position(new LatLng(location.getLatitude(), location.getLongitude()))
      .title(location.getName())
      .snippet(location.getDescription());
    Marker marker = mMap.addMarker(markerOptions);
  }
  CameraUpdate cameraUpdate = CameraUpdateFactory
      .newLatLngZoom(new LatLng(DEFAULT_LATITUDE, DEFAULT_LONGITUDE), 10.0f);
  mMap.moveCamera(cameraUpdate);
}

A: You can do it this by using Custom Marker Window implementation in Google Map V2 API.
An info window allows you to display information to the user when they tap on a marker. Only one info window is displayed at a time. If a user clicks on another marker, the current info window will be hidden and the new info window will be displayed.
An info window is drawn oriented against the device's screen, centered above its associated marker. The default info window contains the title in bold, with the (optional) snippet text below the title
Here i saw some link given below

*

*custom info window adapter with custom data in map v2

*Android Google maps APIv2 InfoWindow and Markers

*https://developers.google.com/maps/documentation/android/infowindows
What i achieved by using this?

and another is

hope this help you.


text:
Q: Does LLVM ever care about the difference between opaque types? According to https://llvm.org/docs/LangRef.html#opaque-structure-types

Opaque structure types are used to represent structure types that do not have a body specified. This corresponds (for example) to the C notion of a forward declared structure. They can be named (%X) or unnamed (%52).

Seems straightforward enough, but one thing I'm trying to figure out is this. Suppose we have two opaque types:
%X = type opaque
%Y = type opaque

Does LLVM ever care about the fact that these are two different types? Is there any scenario in which substituting X for Y would cause different code to be generated? One possibility that comes to mind is type-based alias analysis, but then, it is not possible to dereference an opaque type, so it looks like there is no way for it to make a difference. Am I missing anything?


text:
Q: Integration tests with Embedded Mongo or the installed instance The application I am working on is a Velocity/Spring MVC/Mongo on tomcat kind of webapp.
I am able to run my integration tests on Embedded Mongo, using EmbedMongo which takes longer to run all the tests, say around 1 minutes but on the test database on installed Mongo, it takes around 15 secs.
Is there really any benefit in using Embedded databases for integration tests when creating a new db, (in this case a test db within the same instance) is a negligible effort ? In fact, the tests can themselves create the DB and required Collection.
Other than using Embedded Mongo on a CI box where the regular installation is not required, I don't see any great benefit in it.
Can anyone share any ideas please.
Thanks
Gaurav

A: Look at that link:
https://stackoverflow.com/a/9830861/82609
It seems nice but the MongoDB is started and shutdown between each test.
What you may want to do, to increase speed, is to startup and shut down once for the whole test suite.
I mean: keep the MongoDB instance up between tests.

But you don't want your tests to be dependant of each others. So what you could do is to use a different database name (UUID) so that in the end you have one MongoDB instance running, with many distinct databases, one for each test.
Or you can clean your database between each test.

A: With a separate installed instance you have the process setup and teardown costs involved which you would want to minimize for your test suite hence the benefit of using Embedded DB.


text:
Q: MongoDB return array of values instead of json I have a following document with json as value:
.
But mongodb returns array values instead.

I am using jenssegers plugin for laravel.
How can I get json value as it is from the table, instead of arrays.
I tried json_encode() for this case, but there are other similar issues and I want to retrieve the json value itself.
Fetching query:
$query = \DB::table('v2_reports')
                 ->select('input_controls')
                 ->where('report_key', $report_key)
                 ->first();


text:
Q: Contour integration of $\int_{|z| = 1} \frac{\sin z}{z}$ I am asked to evaluate the contour integral $\int_{|z| = 1} \frac{\sin z}{z}$ around the unit circle counter clockwise. My method is to use the Taylor Expansion of $\sin z$, which then leads to the integral of the sum of powers of $z$, so the integral is 0. Similarly I evaluate $\int_{|z| = 1} \frac{\cos(z^2)}{z}$ and conclude that it's equal to $2\pi i$ as the powers of $z$ vanish.
Am I correct?


text:
Q: change direction mtext x label I've found plenty of posts about changing the direction of x labels using las(), but I haven't found much about how to manipulate mtext(). I've used mtext to supplement a figure using the following code:
arrows(3.85, 0.5, 3.85, 0.05,lwd=3, length=.1, xpd = TRUE)
mtext(side=4, "Increasing precipitation", font=2,line=2)

I'm placing it on the y axis of right side of the figure but the text still reads from bottom to top and looks strange. Is there a way to flip this text so it reads top to bottom? Using las() and others only seems to allow me to change it from parallel to perpendicular. Thanks.

A: I think text would be easier. If you use mtext, you'd have to use side = 2 and mess with the line argument unless there is a way to rotate the mtext labels that I don't know of.
plot(0, bty = 'l')
p <- par('usr')
text(p[2], mean(p[3:4]), labels = 'Some text', xpd = NA, srt = -90)


text:
Q: How much current draw from an inverter? If I have a 12 V car battery and I connect it to a 3 kW 10 A 220 V AC inverter, how much would be the current draw? 250 A?

A:
If I have a 12v car battery and I connect it to a 3kW 10A 220v AC
invertor, how much would be the current draw? 250 amps?

It may be more than 250 amps and it could be a lot less depending on how much load power you are taking.
If the inverter is rated at 3 kW this will be the maximum output power it can deliver. Given that an inverter might only be 90% efficient, the input power could be as high as 3.333 kW and then the current from a 12 volt battery would be 278 amps.
Of course, the inverter may have a surge power rating of 4 kW and then the surge current taken from the 12 volt battery might be as high as 370 amps.
But, largely speaking, the input current is determined by the load connected to the output of the inverter.

A: If there were no losses, then 250A. In reality it will be around 20% higher assuming a 80% conversion efficiency.
It would want to be a big car battery methinks. The average car battery is not designed to deliver such high Amps for an extended amount of time.


text:
Q: Rookie questions for ViewState and Html Control I just get start to learn about ASP.Net. I try to figure out the principle of page process. And I get some questions about ViewState and Html Control.
<input type="text" id="FirstName" />
<br />
<input type="text" id="LastName" runat="server" />

Here is my HTML. I filled two text box, and click submit. The control that running at server kept the value and the other did not.
I check the class HtmlInputText, and find it implemented the interface IPostBackDataHandler, so it will not influenced by ViewState? (I know it through someone`s blog, is that right?)
My idea about ViewState is the one that keep the changing message of every control. The controls in page will be initialized according the default settings and ViewState.
But I still can`t figure out something :
Does ViewState keep the changing message of "FirstName"? The Web Control just like  or the HTML Control running at server, they all implemented the interface IPostBackDataHandler, so the ViewState is useless?
Please help me to understand the use of ViewState or something... (I messed up...)

A: A ViewPage inherits from the Page class. So it's a "WebForm", and it has a code-behind, so you can basicaly request the page directly. If you use a control that will perform a normal postback, a postback will take place, in this case you have added the WebForm behavior, this is not what we shoulde do (mix them both), you should make sure an action method of the Controller is executed instead. There will be some controls in the final version that will instead of doing a "postback", make sure an Action method will be excuted. You can't access the ViewState from the Controller so in that way it will not on a controller level. If you have a control that uses ViewState, and press on a "button" or "Link" which will make sure a Action method is executed, the ViewState will not be posted and in that case when the controls will get data form the ViewState it's empty. So the controls will not work if they need ViewState.
Hope this helps
source:<Link>


text:
Q: Wrong ImportError when trying to import a broken package twice I noticed a strange behavior while trying to import a broken package twice. Let's consider the following package:
| package
|--| __init__.py
|--| module1.py

with module1.py empty and __init__.py containing:
from package import module1
from package import module2

On the first try to import package, an ImportError is raised because module2 is missing:
>>> import package
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/package/__init__.py", line 2, in <module>
    from package import module2
ImportError: cannot import name 'module2'

But on the second try, the ImportError complains about module1:
>>> import package
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/package/__init__.py", line 1, in <module>
    from package import module1
ImportError: cannot import name 'module1'

even though module1 has been successfully imported before. It is even available in sys.modules:
>>> import sys
>>> sys.modules["package.module1"]
<module 'package.module1' from '/tmp/package/module1.py'>

However, this seems to be fixed in Python 3.5, maybe because circular imports involving relative imports are now supported.
What is going on exactly?

A: The first time around, package.module1 is imported and from then on exists in sys.modules. However, due to the import error on package.module2, the import of package itself doesn't succeed and so, package does not end up in sys.modules.
The second attempt to import package will handle the import of package.module1 differently as it already exists in sys.modules. The code path this time around assumes at some point that if a module with a dotted name exists in sys.modules, all parents do as well. This assumption is, however, not fulfilled after the failed import of package at the first attempt.
In short, importing a package, which may cause more packages and modules to be imported, is not atomic with respect to filling sys.modules, while Python up to 3.4 made some assumptions that would require atomicity.


text:
Q: Azure DevOps API: Update query with clauses I'm trying to read a query, and add a new clause, and save it elsewhere, using the C# Azure DevOps SDK. I was able to do this by updating the new query's .Wiql directly and modifying the string. However I would rather do this by updating the .Clauses field directly. Unfortunately, using the .Clauses field ends up doing nothing - the Wiql takes precedence. If I set the Wiql to be empty, the Clauses also don't seem to take effect either.
I'm using GetQueryAsync() to get the query, and UpdateQueryAsync() to save it. For example:
await workItemTrackingClient.UpdateQueryAsync(outputQuery, c_projectName, outputQueryId);

Any input appreciated.


text:
Q: I need help to determine the $\lim_{x\to0^-} \frac{x^2\sin(1/x)}{\sin(x)}$? I need help determining the following limit:
$$\lim_{x\to0^-} \frac{x^2\sin(1/x)}{\sin(x)}$$

A: Write the function as
$$
    \frac{x^2 \sin(1/x)}{\sin x} = \frac{x}{\sin x} \cdot x \sin\frac{1}{x}
$$
and take the limit of each factor.

A: $$\lim\limits_{x\to0}\frac{x}{\sin x}=1, \ \lim\limits_{x\to0}x\sin\left(\frac{1}{x}\right)=0$$

A: Notice that $$\begin{align}\lim\limits_{x\to 0^-}\dfrac{x^2\sin{1/x}}{\sin x}=\lim\limits_{x\to 0^-}\dfrac{\sin{1/x}}{1/x}\cdot\lim\limits_{x\to 0^-}\dfrac{x}{\sin{x}}\\
=\lim\limits_{x\to 0^+}\dfrac{\sin{1/x}}{1/x}\cdot\lim\limits_{x\to 0^+}\dfrac{x}{\sin{x}}\end{align}$$
Let $y=1/x$. Then $x\to 0^+$ iff $ y\to \infty$ and we have $\lim\limits_{x\to 0^+}\dfrac{\sin{1/x}}{1/x}=\lim\limits_{y\to\infty}\dfrac{\sin y}{y}=0.$ Since
$$\lim\limits_{x\to 0^+}\dfrac{x}{\sin{x}}=\lim\limits_{x\to 0^+}\dfrac{1}{\frac{\sin x}{x}}=1,$$ the desired limit is $0.$


text:
Q: xDebug shows up in command line "php -m" , but not in phpinfo() I am on windows 7, 64bit, with xampp 3.2.1 installed . I got my xdebug dll file through the xdebug.org wizard, and put it where the wizard told me to, C:\xampp\php\etc. Then I made sure to modify the correct (and as far as I'm aware only) php.ini file at C:\xampp\php\php.ini. This is the same ini that phpinfo() reports.
When I run php -m , I can see the xDebug extension listed twice, just as it should be. But going back to a phpinfo() output, the extension is not listed.
I've tried restarting my computer, apache. If I try to run this script to test if xdebug is working, it gives me a error

socket_bind(): unable to bind address [10048]:Only one usage of each socket address (protocol/network address/port) is normally permitted

A: After hours of hair pulling... and a nap, I came across this config code and it somehow worked. Now that the extension is on firm ground, I can start carefully adding or removing features one at a time.
zend_extension = "C:\xampp\php\ext\php_xdebug-2.2.5-5.5-vc11.dll" // whatever your file name is
xdebug.remote_autostart=on
xdebug.remote_enable=on
xdebug.remote_enable=1
xdebug.remote_handler="dbgp"
xdebug.remote_host= "localhost"
xdebug.remote_port=9000
xdebug.remote_mode=req
xdebug.idekey="netbeans-xdebug"

The root problem was a messed up php.ini file. The problem is that xampp's php.ini has some defaults listed there that we are told to uncomment by xdebug,netbeans, other online guides. Unfortunately, given the certain combinations of values, that just didn't work. This list of parameters definitely worked for me though.


text:
Q: 2D Heat equation: inconsistent boundary and initial conditions I'm attempting to use NDSolve on a 2D boundary value problem with initial conditions. Upon running my code, I get the following message:
"NDSolve::ibcinc: Warning: Boundary and initial conditions are inconsistent."
After much head-scratching, I can't seem to find my mistake. It seems to me that my initial condition is consistent with my boundary conditions:
k = 1 / (5*(Pi^2));
soln = NDSolve[
  {
  (* PDE *)
  D[u[x, y, t], t] == k*(D[u[x, y, t], x, x] + D[u[x, y, t], y, y]),

  (* initial condition *)
  u[x, y, 0] == y + Cos[Pi*x] Sin[2*Pi*y],

  (* boundary conditions *)
  u[x, 0, t] == 0,
  u[x, 1, t] == 1,
  (D[u[x, y, t], x] /. x -> 0) == 0,
  (D[u[x, y, t], x] /. x -> 1) == 0
  },
 u,
 {x, 0, 1},
 {y, 0, 1},
 {t, 0, 1}
 ]

Any advice is greatly appreciated,
Rick

A: The documentation has a full section dedicated to inconsistent boundary conditions in PDEs.
Quoting it,

Occasionally, NDSolve will issue the NDSolve::ibcinc message warning
  about inconsistent boundary conditions when they are actually
  consistent. This happens due to discretization error in approximating
  Neumann boundary conditions or any boundary condition that involves a
  spatial derivative. The reason this happens is that spatial error
  estimates (see "Spatial Error Estimates") used to determine how many
  points to discretize with are based on the PDE and the initial
  condition, but not the boundary conditions. The one-sided finite
  difference formulas that are used to approximate the boundary
  conditions also have larger error than a centered formula of the same
  order, leading to additional discretization error at the boundary.
  Typically this is not a problem, but it is possible to construct
  examples where it does occur.

Then an example follows, and a possible solution using the Method option's "TensorProductGrid" suboption, which we can also apply to your problem.

When the boundary conditions are consistent, a way to correct this
  error is to specify that NDSolve use a finer spatial discretization.

k = 1/(5*(Pi^2));
soln = NDSolve[{
   D[u[x, y, t], t] == k*(D[u[x, y, t], x, x] + D[u[x, y, t], y, y]),
   u[x, y, 0] == y + Cos[Pi*x] Sin[2*Pi*y],
   u[x, 0, t] == 0,
   u[x, 1, t] == 1,
   (D[u[x, y, t], x] /. x -> 0) == 0,
   (D[u[x, y, t], x] /. x -> 1) == 0},

  u, {x, 0, 1}, {y, 0, 1}, {t, 0, 1},

  Method -> {"MethodOfLines",
               "SpatialDiscretization" -> {"TensorProductGrid", "MinPoints" -> 20}}]

In this instance "MinPoints" -> 20 was sufficient to make the problem go away.

The same problem was discussed here.  I vaguely remembered it, but it took me a while to find it again ...