text:
Q: Ordering flex items in different containers My desktop design has 2 textboxes in the left column and one textarea in the right column. The order of desktop is as follows:

*

*Field 1

*Field 2

*Field 3

On mobile however, the order should change to:

*

*Field 1

*Field 3

*Field 2

My HTML structure is as follows:
<form>

        Field 1
        <input type="text">

        Field 2
        <select>
        </select>

    Field 3
    <textarea></textarea>

</form>

I've been able to do the desktop design however I'm struggling to re-order it correctly for mobile. My 2 questions are:

*

*Is it possible to use flex order to re-order elements which are inside separate containers?

*Is it possible to change my html structure to allow both the design & ordering of the desktop and mobile design?

A: If you use grid-template-areas and media queries you can do like this. Should be noted, this solution gets you all the way for browsers supporting grid (not counting ie11), if you do need to support ie check for a fallback solution.

.form-layout {
  display: grid;
  grid-template-areas: "field-1" "field-3" "field-2";
  gap: 1rem;
}

@media (min-width: 767px) {
  .form-layout {
    grid-template-areas: "field-1 field-3" "field-2 field-3";
  }
}

.field-1 {
  grid-area: field-1;
}

.field-2 {
  grid-area: field-2;
}

.field-3 {
  grid-area: field-3;
}
<form class="form-layout">

    Field 1
    <input type="text">

    Field 2
    <select>
    </select>

    Field 3
    <textarea></textarea>

</form>


text:
Q: Disable Drag-drop from TextBox I have a WPF textBox that is declared as ReadOnly
<TextBox IsReadOnly="True" IsTabStop="False" Width="200" />

So, User can not write anything into the TextBox or delete the content but it still allows user to drag the text from this textbox and drop it in any other textbox that caused the text removed from the first textbox(the read-only one) and thats unexpected. Is it a bug?
how can I get rid of this?

A: I tried the following code :
<StackPanel>
    <TextBox IsReadOnly="True">Hello</TextBox>
    <TextBox></TextBox>
</StackPanel>

When I drag-and-drop the text (after selection) from the first TexbtBox to the second one, the text is copied, but not removed from the first TextBox. I tried it under .NET 3.5 and .NET 4.0 targets.
If you want to get rid of your bug without trying to understand it (since it shouldn't happen), you can just put an empty control (Canvas will be ok) on top of your TextBox, with its Background property set to transparent.
<Grid>
    <TextBox IsReadOnly="True" IsTabStop="False" Width="200" />
    <Canvas Background="Transparent"/>
</Grid>

But the text won't be selectable anymore...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Existential theory We have that a formula $\alpha(x_1,x_2,\dots, x_k)$ is existential if it is of the form $$\exists t_1\exists t_2\cdots \exists t_l\beta(x_1,\dots,x_k, t_1,\dots,t_l)$$
where the formula $\beta(x_1,\dots,x_k, t_1,\dots,t_l)$ is quantifier-free, i.e., it doesn't contain the quantifiers $\exists$ and $\forall$.
If the formula $\beta(x_1,\dots,x_k, t_1,\dots,t_l)$ doesn't contain negation, it is called positive existential.
Which is the definition of an (positive) existential sentence?
Is the (positive) existential theory the set of all the (positive) existential formulas or the set of all (positive) existential sentences? Or is the definition of the (positive) existential theory entire different?
P.S. I have posted this question also here.

A: Disclaimer: Definitions may vary from person to person, book to book or article to article. Thus if you are reading a book or taking a course, you should refer to that litterature for the definition they mean. The bellow explanations are based on what I percieve as the most common definition.
A sentence is a formula without free variables. Thus a (positive) existential sentence is just a sentence on the form:
$ \exists t_1...\exists t_l\beta(t_1,...,t_l) $ where $\beta$ is quantifier free.
There is no The (positive) existential theory, but rather we say that a theory is existensial if it is a set of (positive) existensial sentences (or possibly possible to axiomatize using such sentences). If we would take the set of all existential sentences it would include things such as $\exists x (P(x) \wedge \neg P(x))$ and thus would be inconsistent.


text:
Q: cumulative sum dataframe by date I have a pandas dataframe and I need to work out the cumulative sum for every last 20 days.
User       Date      A    B
User1   01/10/2020   1    0
User1   10/10/2020   0    1
User1   15/10/2020   1    1
User1   21/10/2020   0    0
User2   10/10/2020   0    0
User2   21/10/2020   1    0
User2   03/11/2020   1    0

so for every row sum only rows in the last 20 days.
User       Date      A    B
User1   01/10/2020   1    0
User1   10/10/2020   1    1
User1   15/10/2020   2    2
User1   21/10/2020   1    2
User2   10/10/2020   0    0
User2   21/10/2020   1    0
User2   03/11/2020   2    0

i used cumsum
df.groupby("user").cumsum()

but i dont know how to check date and sum cumulative only for last 20 days.

A: Use rolling with a fixed window:
tmp = (
    df.groupby('User')
        .apply(lambda group: group.rolling('20d', on='Date').sum())
)
df[['A_cumsum', 'B_cumsum']] = tmp[['A','B']]

Output:
    User       Date  A  B  A_cumsum  B_cumsum
0  User1 2020-10-01  1  0       1.0       0.0
1  User1 2020-10-10  0  1       1.0       1.0
2  User1 2020-10-15  1  1       2.0       2.0
3  User1 2020-10-21  0  0       1.0       2.0
4  User2 2020-10-10  0  0       0.0       0.0
5  User2 2020-10-21  1  0       1.0       0.0
6  User2 2020-11-03  1  0       2.0       0.0


text:
Q: Earliest I can run xrandr? Every time I boot my laptop I go blind. I can use xrandr to set the brightness but it becomes a rather impractical. I also use LUKS so when I boot the computer I am always greeted with (from what I think) cryptsetup.
Is there a way to run my desired xrandr command when I am asked for the encryption password? Otherwise, when is the earliest (from turning on the laptop) that I can do this and where/how should I configure this?
Amongst other stuff I have tried rc.local, /etc/gdm3/Init/Display, /etc/X11/xinit/xinitrc but nothing seems to work. I am running Ubuntu 16.10 with Gnome and the command I try to run is xrandr --output eDP-1 --brightness 0.3.
Some updates:
Some more info on my hardware and what I have tried.

*

*I have the XPS 15 9550 which comes with Intel Skylake and a dedicated Nvidia graphics card. I have disabled the Nvidia card from the Nvidia X Server Settings GUI tool.

*I have only intel_backlight in /sys/class/backlight by default. I can edit the brightness from there between 0 and 12 but the brightness at 1 is still too bright.

*I have tried altering the /etc/default/grub to include acpi_backlight=vendor. That creates the entry /sys/class/backlight/dell_backlight. This gives some more control but it's very unstable (brightness jumping here and there and freezes).

*I have tried altering the /etc/default/grub to include acpi_backlight=video. That creates the entry /sys/class/backlight/acpi_video0 which permits more granularity (0-66). However the monitor still uses the intel_backlight. I tried to solve this by explicitly configuring the xorg.conf to use the ACPI backlight but to no vail.


text:
Q: How different are inductively ordered set from posets that satisfy the ascending chain condition? I'd like to show that posets that satisfy the ascending chain condition (ACC) have maximal elements.  I noticed this statement looks much like Zorn's lemma which holds for inductively ordered sets.  Posets satisfying the ACC themselves look like inductively ordered sets: in the former every chain should terminate, while in the latter every chain has an upper bound.
The question is:

*

*How different are inductively ordered set from posets that satisfy the ACC?

*How different is the proof of posets that satisfy the ACC having maximal elements from that of Zorn's lemma?  Does it require the Axiom of Choice?

A: The principle of Dependent Choice, a strictly weaker version of the axiom of choice, is sufficient to prove that every poset with the ACC has maximal elements. To see this, pick any element $p_0$ of your poset. If it is not maximal, pick $p_1$ above it. Continuing in this way, pick $p_{n+1}$ above $p_n$, unless it was maximal. By the ACC, we must eventually reach a maximal element. The choice principle used in this argument is exactly what DC allows: one can successively make countably many choices.
Meanwhile, it is consistent with ZF that there are posets having the ACC, but having no maximal elements. For example, suppose that $A$ is an infinite Dedekind finite set of reals, which is known to be relatively consistent with ZF. Thus, $A$ is infinite and has no countable subset. Let $P$ be the partial order consisting of all finite subsets of $A$, ordered by inclusion. This partial order clearly has no maximal elements, but it does have the ACC, since any infinite increasing chain of finite subsets of $A$ would give rise to a countable subset of $A$, a contradiction.
A more striking way to put it is that consistently with ZF there can be a tree $T$, in which every node has finite height and at least two immediate successors, but there is no infinite branch. This tree, as a partial order, has the ACC since any infinite chain would determine an infinite branch. But it has no maximal elements, by the successor condition. The situation with this tree is that one can always continue any finite branch a little more, but the model of set theory is too impoverished to provide a way to climb all the way up, and there is no set of choices that coherently makes infinitely many of the choices.
One can build such a tree using the infinite Dedekind finite set $A$, by considering the finite subsets of $A$, enumerated in the order of the real line. Thus, $a\leq b$ if both are finite subsets of $A$, and $a$ is an initial segment of $b$ in the $\mathbb{R}$-order.
Theorem. DC is equivalent to the assertion that every ACC poset has a maximal element.
Proof. Above we showed that DC suffices for that conclusion. Conversely, consider a relation $R$ for which we would like to establish an instance of DC. So every $a$ has at least one $b$ with $a\mathrel{R}b$. Let $P$ be the partial order consisting of all finite chains through $R$, that is, finite sequences $\langle a_0,\ldots,a_n\rangle$ with $a_i\mathrel{R} a_{i+1}$, and we order them by extension. If there is no infinite chain, then this set has the ACC. But it has no maximal elements.QED
Meanwhile, in the context of set theory with the axiom of choice, the ACC condition is much more severe than the inductive hypothesis of Zorn's lemma, and there are numerous inductive posets without the ACC.


text:
Q: Calculate size for a form containing a control that may vary in size? I need to display a MonthCalendar, in a separate dialog, like the following:

The problem is that the display of this calendar depends on the system the application is running on, resulting in variations such as this (from the same application, on a different PC):

As I understand it, this depends on the visual style or theme the application happens to be running under. The question is, how can I calculate the appropriate size of the form the calendar needs to be placed in, or in some other way make this look elegant on several systems with different themes?
I'm far from satisfied with the current code, which places a calendar in a form (container), which is given a (hard-coded) size appropriate for one specific theme (the first pic):
private static Form SetUpCalendar()
{
    var calendar = new MonthCalendar
                {
                    MaxSelectionCount = maxSelectionCount,
                    BackColor = SystemColors.Info,
                    CalendarDimensions = new Size(1, 1),
                    // (..etc...)
                };

    var container = new Form
                {
                    FormBorderStyle = FormBorderStyle.FixedDialog,
                    Size = new Size(calendar.Width + 74, calendar.Height + 47)
                };

    container.Controls.AddRange(new Control[] {calendar});

    return container;
}

I've not been able to find a way to adjust the size of the form better to the calendar automatically, and would be grateful for any tips on how to improve this.

A: Why not set the form's AutoSize property = true, and AutoSizeMode to GrowAndShrink? You also need to set the margin property if you want to eliminate the space around the control.


text:
Q: Learning FreeBSD What is the average time that it would take a complete novice, whose background is mostly Windows XP, to go through the FreeBSD handbook and get sufficient mastery to setup a server from the ground up?

A: It would depend on how much knowledge you have of unix, and from the sounds of things, you probably do not have a whole lot.
Assuming you have little knowledge of unix at all, I would say that it will probably take a few days to get a grasp of what is going on, and possibly a week to have something working.
The FreeBSD handbook is pretty detailed though, and does provide you with a good grounding of everything you need to do to get things to work.
I know that this sounds like an awful lot of time, but in my experience, they really are quite different OS paradigms.

A: It's impossible to say.  Not only is it highly dependent upon what sort of person you are, but it also depends on what exactly you are doing and how you define "sufficient mastery".  Being able to get Apache operational is a simple matter of following step-by-step tutorials, you could do that in a matter of hours.  Being able to run a multi-user server competently takes a hell of a lot longer, and the handbook isn't nearly enough.

A: You could start with PC BSD (an easy to use distro) to get a feeling of BSD and then move to more advanced stuff like setting up servers.
As others have noted, configuring a service to do a couple of things isn't very hard, you just have to follow some steps (which any monkey could do), but if you want more, you'll need extra time. A competent sysadmin does not know only the how, but also the why. Grandma can click all day in Windows and even if Windows Server has a GUI for server administration, it doesn't mean she can configure IIS or the DHCP service. By the way, it would be a good thing if you could learn an (Unix) editor, preferably vi, since it's the standard on BSDs; emacs, joe, pico are nice too, but they aren't so popular.
As for the time, it took about two days for me to configure a server. But I had previous Linux experience and the server didn't do anything fancy.

A: Look if you've never touched a Unix platform, you should learn a lot of things, basically a different philosophy. The FreeBSD Handbook and the community is simply wonderful, but a reference book like the FBSD handbook contains a lot of information that you must develop yourself.
Also, the BSD platform is not easiest of the Unix family to begin from zero.
Good sources to learn:

*

*Absolute BSD book.

*The Complete BSD book (this is for Release 5, it's good for learning also).

*Man pages. The BSDs man pages are a LOT better than the Linux ones.

*FreeBSD Handbook.

*FreeBSD forums: forums.freebsd.org and daemonforums.

*Any Unix/Linux resource you can get your hands on. Many things are compatible (or near-compatible). e.g, if your friend tells you "I've found an old SGI IRIX / HPUX or (insert unix here) manual that I will throw in the thrashcan" stop it and see what you can learn from it.

Keep in mind that you've a long road ahead. But you'll enjoy it.

A: Depends on your reading speed :-)
Depends on your needs (I mean: what kind of server).
Once upon a time I did this - installing a FreeBSD on x86- (although I had some Linux knowledge already at that time), and it took me 3 hours, mainly that much time, because I was working on another machine in parallel.

A: Depends on your background: Did you ever use power shell or other command line "applications" (like batches ;-). For me one of  the greatest challenges to switch from a completely GUI'd operating system to an operating system that works best with a shell (something a little bit like the DOS prompt). But the moment you get the hang of it you'll be fine again.

A: Another aspect is the availability of a second computer beside the one you are setting up.  If you can do web searches for additional information while in the midst of doing an install, it can save a lot of time.
As for the original topic, I've used Linux and Unix extensively, but have yet to get FreeBSD working after several tries over many years.  I'd always get frustrated before I could get it fully installed and configured for a nice graphical desktop.  (So personality obviously matters.)  But it has been about two years since I've tried, and it may be simple now...
Please do not consider this a flame against FreeBSD... just a true story that for some reason I couldn't seem to make it work.  If it were not a good OS, I wouldn't have attempted so many times.

A: If you're coming from a primarily Windows background, I think FreeBSD would be a great way to dive into UNIX, but you may also want to check out Ubuntu Linux-- specifically, Ubuntu Server.
Got a spare Pentium 4-based system laying around at home?    Burn yourself a CD and go to it.
As a fan of FreeBSD myself, I have to second the recommendation for the "Absolute FreeBSD" book above--  another book worth a look is "Building a Server with FreeBSD 7."
My original rationale for choosing FreeBSD was getting better control over what gets installed-- I was really tired of installing RedHat and/or SuSE and having a few gigabytes of stuff I wasn't going to use installed as part of the base install that wasn't easily removed after the fact.   I've grown rather enamored with the BSD way of doing things, but it isn't necessarily for everyone.
Something to consider--   if you have the hardware, run VMWare or VirtualBox, and set up a few virtual machines to get used to various distributions before making the commitment to install a particular one on bare hardware.


text:
Q: jShowOff Slide Show Can't Click in Center of Slide See the "Re-styled Thumbnail Demo" (bottom right) on the home page for this,
http://ekallevig.com/jshowoff/
Put your cursor at the top middle of the slide and you can can click.
Put your cursor at the middle and there is no click available.
I believe the prev/next arrows are to blame. Both are enclosed in the same < p > tag. I tried adding a z-index without success.
This is a problem because our linked slides are not large, and there is not much clickable area above and below the prev and next arrows. Besides, most people would click in the middle of the slide.
Can you tell me how to fix that?
Thank you!

A: Root cause
CSS line 448 - 449
.thumbFeatures p.jshowoff-controls {
    background: none;
    height: 0px; /* I am the cause */
    overflow: visible;
    padding: 0;
    position: absolute;
    top: 100px;
    width: 100%;
    z-index: 150;
    }

Hope this helps.


text:
Q: Sampling diverse binary strings What would be a good way to sample N binary strings of length that maximizes their 'diversity'?
Easiest way to generate a binary string of length d is to set each bit independently uniformly to 0 or 1. But this would be equivalent to sampling from the space {0,1}^d with replacement: some of the sampled strings might be the same.
I would like to pick binary string so that the similarity between strings is small. For example, by maximizing the sum of all Hamming distances, or by maximizing the minimum Hamming distance, etc.
Sampling without replacement will increase the diversity. (For example minimal possible Hamming distance will go from 0 to 1)
How to increase diversity further?


text:
Q: Origin of 'Dutch Courage' I was wondering if anyone could shed some more definite light on the origin of the phrase 'Dutch Courage.'
I have found two, almost certainly apocryphal, origins:

1: From the Thirty Years War in the 17th Century, where British soldiers drank a Dutch Gin for it's warming/calming effects.2

and

2: Deriving "from the disparaging idea that Johnny Foreigner, whether sailing up the Medway or facing down the locals in the East Indies, needed a few drinks before a fight."3

However, the phrase only seems to begin appearing in print from the mid- to late-19th Century - some 200 years after its supposed coinage. Which makes me suspect there is another story behind this.
Unfortunately, as with many popular folk etymologies they swamp any other potential sources, so I look to EL&U for some help.

A: Dutch courage:

*

*False courage acquired by drinking liquor, as in He had a quick drink to give him Dutch courage. This idiom alludes to the reputed heavy drinking of the Dutch, and was first referred to in Edmund Waller's Instructions to a Painter (1665):

*

*"The Dutch their wine, and all their brandy lose, Disarm'd of that from which their courage grows.".

(The American Heritage® Idioms Dictionary)
The following source cites two possible origins, but the "gin" related one appear to support the above assumption:

*

*In many ways, the Dutch used to be Britain's closest neighbours. From the rise of the United Provinces during the reign of Elizabeth I until the eclipse of the Netherlands as a major power in the Napoleonic wars, they were sometimes enemies but more usually co-religionist allies, important trading partners and occasional colonial rivals. And, of course a Dutchman, William, became king of England in 1689.

*These connections are evident in our language: slang dictionaries are full of expressions such as 'going Dutch', 'Dutch auction' and 'Dutch uncle'.
'Dutch courage' has two possible origins:

*

*The first derives from the disparaging idea that Johnny Foreigner, whether sailing up the Medway or facing down the locals in the East Indies,  needed a few drinks before a fight.

*The second theory relates more directly to the use of a specific drink – gin – to bolster one's courage.

*Gin in its modern form was reputedly invented by the Dutch physician Franz de le Boë (Franciscus Sylvius) in the 17th century.  British troops fighting Louis XIV alongside their allies in the Low Countries appreciated the calming effects of Jenever (Dutch gin) before heading into battle. Cheap gin was widely available in London by the early 18th century.

*Whether or not it specifically referred to gin, 'Dutch courage' as an English colloquialism tended to mean using spirits, not just beer, to stiffen resolve.

(www.historyextra.com)

A: The answer posted by user66974 correctly notes that an allusion to Dutch courage as flowing from a bottle of spirits appears in the course of a lengthy poem by Edmund Waller, "Instructions to a Painter for the Drawing of a Picture of the State and Posture of the English Forces at Sea, Under the Command of His Royal Highness in the Conclusion of the Year 1664" (1665), which reads, in part, as follows:

Our first success in War, make Bacchus crown, / And half the Vintage of the year our own; / The Dutch their Wine, and all their Brandy lose, / Dis-arm'd of that from which their Courage grows. / While the glad English to relieve their Toyl, / In Healths to their great Leader drink the spoyl.

The description here seems to involve the capture of Dutch ships loaded with wine and brandy—but the suggestion, unmistakably, is that the Dutch sailors relied on drinking alcohol to bolster their bravery.
Nevertheless, the earliest Google Books match for the exact phrase "Dutch courage" in connection with imbibing alcohol is from more than a century later. From "Interesting Particulars of the Late Engagement Between Admirals Hyde Parker and Zoutman" in The Political Magazine and Parliamentary, Naval, Military, and Literary Journal (September 1781):

In another part of the same letter [from Captain Decker of the Bellona to the Amsterdam Gazette, published on August 17, 1781], the writer in the true stile of rhodomontade says, "our Captain showed himself a hero and a lion in the midst of the fire ; and the crew were so full of zeal, that it was with great difficulty they were kept from firing, in their fury, into our own vessels. If this story is true, it is very probable the Dutch sailors were drunk. Dutch courage has been long proverbial.

The word rhodomontade derives from the character Rodomonte in Matteo Boiardo's Orlando Innamorato (1612) and means (according Merriam-Webster's Eleventh Collegiate Dictionary (2003) "a bragging speech" or "vain boasting or bluster: rant." So, on the one hand, we have a surprisingly late first confirmed print occurrence of the expression "Dutch courage" in the sense of "alcohol-fueled bravery" and, on the other, an assertion in that very same occurrence that the expression "has been long proverbial" in English.
Instances of "Dutch courage" in the relevant sense become much more frequent from the early 1800s onward.
From Thomas Trotter, An Essay, Medical, Philosophical, and Chemical, on Drunkenness and Its Effects on the Human Body, second edition (1804):

It is well known that the modern armies of France are much addicted to drinking spirits; and many of their greatest victories are said to have been obtained under the fury inspired by dram-drinking; the spirits being supplied to the soldiers while engaged, by women who attended them for that service. This is a species of prowess which our tars call Dutch courage; and which, I hope, will never be resorted to by Britons in the present contest with France.

From Diedrich Knickerbocker [Washington Irving], A History of New York (1809):

The bewildered Swede [Risingh] staggered with the blow [from Peter Stuyvesant's wooden leg], and in the mean time the wary Peter, espying a pocket pistol lying hard by (which had dropped from the wallet of his faithful squire and trumpeter Van Corlear during his furious encounter with the drummer) discharged it full at the head of the reeling Risingh—Let not my reader mistake—it was not a murderous weapon loaded with powder and ball, but a little sturdy stone pottle, charged to the muzzle with a double dram of true dutch courage, which the knowing Van Corlear always cried about with him by way of replenishing his valour.

And from "Supplemental Journal" (April 1, 1812) in The Debates and Proceedings in the Congress of the United States, volume 2 (1853):

Mr. RANDOLPH then said, that the step we are about taking is too high a price to pay for the consistency of gentlemen who think they have gone too far to recede; it is too expensive to bolster them up in this way. He asked what will be the situation of this people in sixty days? Put your note into the bank, and see how soon it will be out. What will be the sitution of this unhappy, misguided country? What would it have been for sixty, one hundred, or three hundred and sixty-five days past? He had hoped not to have seen the old story of the dog worrying the cat, &c., realized. Are the majority, in consequence of having been goaded by the presses, to plunge the people into war by bringing them first to the whipping post and then by exciting their spirit? He would assure the House the spirit of the people is not up to it at this time; if so there would be no necessity of those provocations to excite this false spirit—this kind of Dutch courage. If you mean war, if the spirit of the country is up to it, why have you been spending five months in idle debate?

Here, "Dutch courage" is used figuratively for "false bravado," with little or no literal connection to alcohol consumption.
And from David Porter, Journal of a Cruise Made to the Pacific Ocean in the United States Frigate Essex (1815):

This vessel proved to be the British letter of marque ship Greenwich, of ten guns, a prime sailer, employed in the whale fishery. Her captain had taken in a good stock of Dutch courage, and, from the preparations that were made on board his vessel, there could be no doubt of his intentions to have fired into us, had he not been intimidated by the shot e fired between his masts.

The captain of the Greenwich (John Shuttleworth) is later described as "so much intoxicated, and his language so insulting, that it was with difficulty I [Captain Porter] could refrain from turning him out of my cabin"—so it is clear that Captain Shuttleworth "had taken in a good stock of Dutch courage" internally—and not merely as a provision on board his vessel.

Conclusions
It is by no means implausible that "Dutch courage" as a fixed phrase may date to the seventeenth century, given the claim in the earliest confirmed match that I could find for it in the relevant sense (from 1781) that as of that date it had already long been proverbial. However, the existence of a popular opinion among British sailors that Dutch seamen took their courage from a bottle, even to the extent of its being viewed as "proverbial," does not require the existence of the exact phrase "Dutch courage" for alcohol-fueled fortitude.
On the basis of the print record that I have seen, it seems quite possible that the precise figurative expression "Dutch courage" arose in the second half of the eighteenth century and that it did not become widespread among English speakers in Britain and North America until the early nineteenth century.

A: On a tour in London 2012 our guide stated that Durch Courage came about in the rat plague when only Dutch vessels still traded and berthed in the Thames.
The British Government issued  barrell of rum to each Dutch ship that continued to trade, for their Dutch Courage.


text:
Q: Query about Entity Framework caching Lets say I have these three methods:
public Customer GetCustomerByCustomerGuid(Guid customerGuid)
{
    return GetCustomers().FirstOrDefault(c => c.CustomerGuid.Equals(customerGuid));
}

public Customer GetCustomerByEmailAddress(string emailAddress)
{
    return GetCustomers().FirstOrDefault(c => c.EmailAddress.Equals(emailAddress, StringComparison.OrdinalIgnoreCase));
}

public IEnumerable<Customer> GetCustomers()
{
    return from r in _customerRepository.Table select r;
}

//_customerRepository.Table is this:
public IQueryable<T> Table
{
    get { return Entities; }
}

Would this cause a query to the database each time I make a call to GetCustomerByEmailAddress() / GetCustomerByCustomerGuid() or would EF cache the results of GetCustomer() and query that for my information?
On the other hand, would it just cache the result of each call to GetCustomerByEmailAddress() / GetCustomerByCustomerGuid()
I am trying to establish the level of manual caching I should go to, I really dislike running more SQL queries than are absolutely necessary.

A: Yes, it'll query the database every time.
Your concern should be to optimize your code so that it only queries for and returns the record you need. Right now it's pulling back the entire table and then you're filtering it with FirstOrDefault().
Change public IEnumerable<Customer> GetCustomers() to public IQueryable<Customer> GetCustomers() to make it more efficient.

A: It will result in a call to the database every time. I actually asked a similar question earlier today and you can see more here: Why does Entity Framework 6.x not cache results?


text:
Q: Trigger wont release locks I am working on a project that will be replacing an existing older project. On one side I am taking data from external views and on the other I am taking the existing production data. The data between the two systems was supposed to have been in-sync, but they werent at any meaningful level. For the most part this has not been a huge issue as I have largely merged them where possible. In some cases the rows were matched on employee id's, and in others using only surname and birthdate.
The external view data always has two pieces of distinct information, an employee ID and another identifier. The Production data will always have one distinct ID and thats file_number. Sometimes production will have the external view keys, but this is not normal. These keys are the primary keys on either side, not surname and birthdate.
Its this last comparison which has caused the issue as we have several requirements where we are only allowed to join on this criteria, such as when the employee exists in the production side gets an entry on the external views. As surname and birthdate are not particularly distinct, I created an exclusion table for these records that would otherwise cause issues but are valid (twins for example). The exclusion table takes all of the offending records from both sides.
As I was unable to figure out a way to get some kind of constraint where these duplicate records would automatically get entered into the exclusion table (have poor control over data entry), I turned to triggers.
Error

Error report -
      SQL Error: ORA-04021: timeout occurred while waiting to lock object
      ORA-06512: at "USER.EXCLUSION_TRG", line 4
      ORA-04088: error during execution of trigger 'USER.EXCLUSION_TRG'
      ORA-06512: at "USER.VIEW_DUPLICATE_TRG", line 4
      ORA-04088: error during execution of trigger 'USER.VIEW_DUPLICATE_TRG'
      04021. 00000 -  "timeout occurred while waiting to lock object %s%s%s%s%s"
      *Cause:    While waiting to lock a library object, a timeout is occurred.
      *Action:   Retry the operation later.

First trigger for VIEW Table
CREATE OR REPLACE TRIGGER VIEW_DUPLICATE_TRG
AFTER INSERT OR UPDATE ON VIEW_PERSON
BEGIN

INSERT INTO VIEW_EXCLUSION_PERSON (EMPLID, PRI, COMMENTS)
select  emplid, PRI, 'VIEW CREATED '||SYSDATE from (
select upper(CONVERT(last_name, 'US7ASCII')) LAST_NAME, birthdate,first_name,emplid, pri,  count(*) over (partition by upper(CONVERT(last_name, 'US7ASCII')), birthdate) duplicate_count from VIEW_PERSON
) K where duplicate_count > 1
and NOT EXISTS (select emplid from exclusion_person Z WHERE K.EMPLID=Z.EMPLID);
END;

Second trigger for Prod table
CREATE OR REPLACE TRIGGER PROD_DUPLICATE_TRG
AFTER INSERT OR UPDATE ON BACKGROUND_INFO
BEGIN
INSERT INTO EXCLUSION_PERSON (FILE_NUMBER, COMMENTS)
SELECT FILE_NUMBER, 'PROD CREATED '||SYSDATE
FROM BACKGROUND_INFO
WHERE (SURNAME, BIRTHDATE) IN
    (SELECT SURNAME, BIRTHDATE
    FROM BACKGROUND_INFO
    GROUP BY SURNAME, BIRTHDATE
    HAVING COUNT(*) > 1
    )
    AND FILE_NUMBER NOT IN (SELECT FILE_NUMBER FROM exclusion_person WHERE FILE_NUMBER IS NOT NULL);
END;

Third trigger for Exclusion table
CREATE OR REPLACE TRIGGER EXCLUSION_TRG
AFTER INSERT ON EXCLUSION_PERSON
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
EXECUTE IMMEDIATE 'ALTER TRIGGER EXCLUSION_TRG DISABLE';

merge into EXCLUSION_PERSON E
using (select file_number, DECODE(TRIM(PRI), '99999999', NULL, PRI) PRI from administrative_info) A
on (E.PRI=A.PRI)
when matched then update set E.file_number = A.file_number, E.COMMENTS = E.COMMENTS||', MATCHED ON PRI ON '||SYSDATE
WHERE E.FILE_NUMBER IS NULL AND E.PRI IS NOT NULL AND A.PRI IS NOT NULL;

MERGE INTO VIEW_EXCLUSION_PERSON E
USING (SELECT FILE_NUMBER, EMPLID FROM VIEW_PERSON) P
ON (P.EMPLID = E.EMPLID)
WHEN MATCHED THEN UPDATE SET
    E.FILE_NUMBER = P.FILE_NUMBER,
    E.COMMENTS = E.COMMENTS||' MATCHED FROM PERSON '||SYSDATE
WHERE E.FILE_NUMBER IS NULL AND E.EMPLID IS NOT NULL AND P.FILE_NUMBER IS NOT NULL;

EXECUTE IMMEDIATE 'ALTER TRIGGER VIEW_DUPLICATE_TRG DISABLE';

MERGE INTO VIEW_PERSON P
USING (SELECT FILE_NUMBER, EMPLID FROM EXCLUSION_PERSON ) E
ON (P.EMPLID = E.EMPLID)
WHEN MATCHED THEN UPDATE SET P.FILE_NUMBER = E.FILE_NUMBER
WHERE P.FILE_NUMBER IS NULL AND E.EMPLID IS NOT NULL AND E.FILE_NUMBER IS NOT NULL;

EXECUTE IMMEDIATE 'ALTER TRIGGER VIEW_DUPLICATE_TRG ENABLE';
EXECUTE IMMEDIATE 'ALTER TRIGGER EXCLUSION_TRG ENABLE';
END;

So the issue seems to be that the first trigger VIEW_DUPLICATER_TRG is locking something and not releasing that lock when EXCLUSION_TRG is attempting to run. When I go looking for this %S%S%S%S%S object, I just cant find it, and none of my code is calling this object.

A: The major issue is here:
EXECUTE IMMEDIATE 'ALTER TRIGGER EXCLUSION_TRG DISABLE';

This tries to disable the trigger while the trigger itself is executing!
This will never work: you can't disable a trigger while it's executing. So to try to change its state from within its own execution will be blocked.
You can see this with the following:
create table t (
  c1 int
);

create or replace trigger trg
after insert on t
declare
  pragma autonomous_transaction;
begin
  execute immediate 'alter trigger trg disable';
end;
/

insert into t values ( 1 );

The insert will be stuck, waiting to try and disable the trigger. But the trigger is executing. So you can't disable it. AAAAARGGGH!
This whole process needs redesigning. Ideally without any triggers!


text:
Q: Extract a key from a Base64 decoded string I am trying to decode a base 64 format string in JMeter, with a BeanSheel PostProcessor, and extract the nameid from the string, which (nameid) I am further going to use in sending another request.
I tried the following code but it doesn't work.
import org.apache.commons.codec.binary.Base64;

String decoded_response = new String(Base64.decodeBase64(data));
String memberId = decoded_response.nameid;
log.info("memberid", memberId)

It is giving me errors as:
ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.apache.commons.codec.binary.Base64;  String decoded_response = new St . . . '' : Typed variable declaration : Cannot access field: nameid, on object: iDzÏí¢G§{"typ":"JWT","alg":"HS256"}{"nameid":"1862","unique_name":"user1@mywebsite.com","iss":"http://mywebsite-app.azurewebsites.net/","aud":"414e1927a3884f68abc79f7283837fd1","exp":1635435731,"nbf":1635349331}$S'vC‡öRé™v"2xÉr}ïK…u®KŸäpÏƯ-¢G§þÜ©y·šêÞƘ«zÏâŸÎ·÷Ö¬rXžžßâvx

Basically here I want to decode the token and get some of the id fields to be used in further requests. What is a good way of doing this? Is there any alternative to store the nameid in another variable and use it further in another request?

A: *

*You need to decode Base64URL, not Base64

*If it succeeds you will get JSON which needs to be parsed

*Since JMeter 3.1 you're supposed to use JSR223 Test Elements and Groovy language for scripting

So I think you need to change your code to something like:
def response = prev.getResponseDataAsString()

def parts = response.split('\\.')

def part2 = org.codehaus.groovy.runtime.EncodingGroovyMethods.decodeBase64Url(parts[1])

def nameid = new groovy.json.JsonSlurper().parse(part2).nameid

More information:

*

*EncodingGroovyMethods

*Apache Groovy - Parsing and producing JSON

*Apache Groovy - Why and How You Should Use It


text:
Q: WebView number of matches I am using "findAll" on a webview, it works correctly, but do not know how I can retrieve the number of matches for if greater than 0 to show a button in that case.

A: Refer this

Returns
  : the number of occurances of the String "find" that were found

So if you use
int count = mWebView.findAll(searchString);

then count will hold occurrence of a searchString text in webview.
Hope this helps.

A: Since findAll has this nasty bug returning 0 even if it matches and the function is deprecated:
findAllAsync Seems to be the way to go.
Its a little more work though since you need to implement a WebView.FindListener
The results returned through that are also structured a bit differently and more difficult to handle.
webView.setFindListener(yourFindListener);
webView.findAllAsync("some string")

What also can be tricky is delaying the search until the site is fully rendered which is another tricky topic on its own. (depending on the page and its JS usage)


text:
Q: Add cordova plugin from GitLab private repo cordova plugin add http://gitlab.com/<user>/<private-repo>.git

I am unable to add a cordova plugin from a private repo in GitLab. When I run the above command it throws me the following error:
Error: Failed to fetch plugin http://gitlab.com/<user>/<private-repo>.git via registry.
    Probably this is either a connection problem, or plugin spec is incorrect.
    Check your connection and plugin name/version/URL.
    Error: npm: Command failed with exit code 1 Error output:
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 401
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 401
    npm ERR! fetch failed http://gitlab.com/<user>/<private-repo>.git
    npm ERR! Darwin 16.7.0
    npm ERR! argv "~/.nvm/versions/node/v6.4.0/bin/node"
    "~/.nvm/versions/node/v6.4.0/bin/npm" "install"
    "http://gitlab.com/<user>/<private-repo>.git" "--save"
    npm ERR! node v6.4.0
    npm ERR! npm  v3.10.3

    npm ERR! fetch failed with status code 401
    npm ERR!
    npm ERR! If you need help, you may report this error at:
    npm ERR!     <https://github.com/npm/npm/issues>

    npm ERR! Please include the following file with any support request:

Note: I am using cordova 7.0.1
I can see that status code is 401. I was accepting a password prompt for fetching from the private repo but unfortunately thats not the case.
similar question was asked but I don't want to clone the repo and add via local folder. Any kind of help will be appreciated. Thanks :)

A: The problem with the --no-fetch work-around is... that the plugin is not fetched.
There are related open issues referenced in Cordova issue tracker for versions 7.x and 8.x:

*

*https://issues.apache.org/jira/browse/CB-13507

*https://issues.apache.org/jira/browse/CB-12756
I found two work-around:

*

*clone the repo and add the plugin referring to the local path (see comment in CB-13507)

*downgrade to Cordova v6.x to add your plugin then rollback to latest version

A: Try the following to add a plugin from a private GitLab repository using the latest version of Cordova.
cordova plugin add git+ssh://git@gitlab.example.com:<group|user>/<repo>#<branch>

A: you need to no-fetch this plugin. So, you need to run that command:
sudo cordova plugin add http://gitlab.com/<user>/<private-repo>.git --save --nofetch

Regards


text:
Q: search on a table and linked tables with fulltext I have a simple database like this:
table "contents":
--------------------------
CID | contentName
  1 | Watermelon

table "tags":
--------------------------
TID | tagName | tagKeywords
 77 | Fruit   | Fruit, fruits
 99 | Nature  | nature, green, mother earth

table "associations":
--------------------------
CID | TID
  1 | 77
  1 | 99

how should I write a select that searches in the table "contents" with every row inheriting any associated tag's keywords?
for instance if i search "fruit" and "green" the fulltext search should result more relevant because matches two tags

A: I think this is more what you're looking for:
SELECT c.contentName, GROUP_CONCAT(tagkeywords separator ',')
FROM contents c
INNER JOIN associations a ON a.CID = c.CID
INNER JOIN tags t ON t.TID = a.TID
GROUP BY c.contentName;

I just tested it, and got the following:
contentName    GROUP_CONCAT(tagkeywords separator ',')
-----------    ---------------------------------------
Watermelon     Fruit, fruits,nature,green,mother earth


text:
Q: FlywayDB: Migration fails with "Error executing statement", but manually running migration SQL code works I have a play framework 2.2.2 scala application and use play-flyway 1.0.3.
The following migration should be run by flyway:
ALTER TABLE  `user_visits` ADD  `FirstSiteRequestTime` DATETIME NOT NULL ;
UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1) ;

So I add a column to a table and then programatically fill it using an update statement.
The first line executes fine, but the update statemens fails with
FlywaySqlScriptException: Error executing statement at line 2: UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1)
com.googlecode.flyway.core.command.FlywaySqlScriptException: Error executing statement at line 2: UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1)
com.googlecode.flyway.core.dbsupport.SqlScript.execute(SqlScript.java:92)
com.googlecode.flyway.core.resolver.sql.SqlMigrationExecutor.execute(SqlMigrationExecutor.java:72)
com.googlecode.flyway.core.command.DbMigrate$2.doInTransaction(DbMigrate.java:243)
com.googlecode.flyway.core.command.DbMigrate$2.doInTransaction(DbMigrate.java:241)
com.googlecode.flyway.core.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:72)

However, when I take the migration SQL code and run it using phpmyadmin, it works fine (although it takes 2-5 seconds to run, the tables are quite big).
My mysql.log looks like
                  128 Query SET autocommit=0
                  128 Query ALTER TABLE  `user_visits` ADD  `FirstSiteRequestTime` DATETIME NOT NULL
140412  4:40:43   128 Query UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1)
140412  4:40:44   128 Query rollback
                  128 Query SET autocommit=1

Is flyway having some kind of timeout? The log file shows it sends the query to the mysql server but then rolls back. Why? As stated before, the query is correct. It works when I run it manually.
edit:
After running the migration, the ALTER TABLE statement was executed and committed (the table is altered), although the mysql.log says it was rolled back. The second command was really rolled back.
I also tried splitting the two SQL commands in two migrations. Then the first one (ALTER TABLE) runs fine and the second one fails.
edit2:
It might be some kind of timeout problem. Making it execute faster (by only updating some of the rows)
ALTER TABLE  `user_visits` ADD  `FirstSiteRequestTime` DATETIME NOT NULL ;
UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1) WHERE user_visits.id<1000;

runs correctly, also in flyway.

A: MySQL documentation says that as of MySQL 5.5.3, "most statements" that cause an implicit commit before executing also do so after executing. This seems to include the ALTER TABLE statement (in MySQL 5.5.3 and later).
Notice that in the log shown in the question, autocommit is disable. To be sure, either use an explicit COMMIT between the statements like this:
ALTER TABLE  `user_visits` ADD  `FirstSiteRequestTime` DATETIME NOT NULL ;
COMMIT ;
UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1) ;

or place them in separate and contiguous migration files, like this:
File V1__alter_table.sql:
ALTER TABLE  `user_visits` ADD  `FirstSiteRequestTime` DATETIME NOT NULL ;

File V2__update_table.sql:
UPDATE `user_visits` SET `FirstSiteRequestTime`=(SELECT `Time` FROM `user_siterequests` WHERE `user_siterequests`.`Visit`=`user_visits`.`ID` ORDER BY `Time` ASC LIMIT 1) ;


text:
Q: GroupBy then sum in separate expressions in Entity Framework Usually when we do GroupBy and Sum in Entity Framework, we have something like this:
var query = from q in db
            group q by q.Gender into g
            select new
                {
                  name = g.Key,
                  value = g.Sum(a => a.saving_amount)
                };

If I want to separate the above queries and build GroupBy and select to Sum step by step, I have:
var q1 = from q in db
         group q by q.Gender

var q2 = q1.Select (g=> new{
    name = g.Key
    value = g.Sum(a => a.saving_amount)
});

However if I do this, I get an error message

'object' does not contain a definition for 'saving_amount' and no accessible extension method 'saving amount'...

To make sure I do have the 'saving_amount' I output my result as so
var q1 = from q in db
         group q by pc.Gender

var q2 = q1.Select (g=> new{
    name = g.Key
    value = g.ToList()
});

and confirmed my 'saving_amount' is a property in the list of objects. (below is a sample output through an API using Postman)

[{"name":"Female","value":[{"id":"xxxxxxxx","version":"R","issue_date":"2021-01-26T00:00:00","saving_amount":100000.0000,...

My question is how can I sum the 'saving_amount' under the separated query?
Thank you.

A: Looks like I've resolved it by using below instead
var q1 = from q in db
         group q by q.Gender

var q2 = q1.Select (g=> new{
    name = g.Key
    value = g.Select(a => a.saving_amount).Sum()
});


text:
Q: How to replace a sting using python I want to replace a string ('None') with NULL without quote.
For example:
data  = ('a','None','1','None')

And desired result:
result = "'a', NULL, '1', NULL"

Is there a way to get the expected result? Thanks in advance!!

A: NULL is not a valid keyword in Python. Instead, you use None. In addition, you cannot modify a Tuple.
If you are using a list, however;
data[1] = None

A: You can use join to build the resulting string:
data  = ('a','None','1','None')
t = ', '.join('NULL' if t == 'None' else repr(t) for t in data)

t is then the string "'a', NULL, '1', NULL".
But I really cannot imagine a real world use case for that...

A: Use a generator comprehension along with the tuple() function:
data = ('a', 'None', '1', 'None')

# For NULL without quotes
result = tuple(el if el is not 'None' else NULL for el in data)

# 'NULL' with quotes
result = tuple(el if el is not 'None' else 'NULL' for el in data)

If you want your final result to be a comma-seperated string of values, use this:
# Replace 'NULL' with NULL if you want to reference the variable
new_result = ', '.join(el if el is not 'None' else 'NULL' for el in data)


text:
Q: glGenBuffers function usage For each buffer type, there a special function to generate names for it like glGenFramebuffers for framebuffers, glGenRenderbuffers for render buffers, and glGenTextures for textures.
But there is a function called glGenBuffers. What types of buffers does this function generate? & how these buffers can be used in my program?

A: glGenBuffers allocates a name for a "Buffer Object". An OpenGL Buffer Object represents a block of memory which can be accessed by both the application and the GPU (though typically not by both at the same time). OpenGL can use the contents of a buffer object for a variety of purposes, and a single buffer object may be used for more than one purpose over its lifetime, though in practice buffer objects are often created exclusively for one type of data.
You can get an idea for the uses that a buffer object has by looking at the list of binding points to which you can attach a buffer object (using the glBindBuffer function). For example:

*

*GL_ARRAY_BUFFER - OpenGL will read vertex data from the buffer object.

*GL_ELEMENT_ARRAY_BUFFER - OpenGL will read vertex indices (e.g., for glDrawElements) from the buffer object.

*GL_PIXEL_UNPACK_BUFFER - Functions that read pixel data (e.g., glTexImage2D) will read that data from the buffer object.

And many more.
For more information, see the OpenGL wiki page for Buffer Object.


text:
Q: How do you use Python's Noise 1.1.1 for Coordinates? I've looked around and it seems most use it for textures and I find myself stuck trying to figure out how to implement Perlin/Simplex Noise to a set of 2 dimensional coordinates x and y.
All I'm trying to do is input 2 random coordinates, x & y and then it returns an altered x & y, or is this not possible?
I'm using pythons noise to allow me to create the coordinates,  but I find myself that perlin noise is quite complex to understand and cannot fully comprehend how it works.

A: It is possible to use Perlin Noise for adding some uncertainty to a collection of  2D coordinates (if the collection is a single pair, that is fine too). You can consider the returned noise value (in the range [-1, 1] for the pointed library) together with some factor to determine how much it affects your input coordinates. The larger the factor, the greater impact the noise has over your data. Here is one of the simplest possible examples:
from noise import snoise2 # Simplex noise for 2D points

x, y = 0.5, 0.3
factor = 0.1
n = snoise2(x, y)
print x + n * factor, y + n * factor

We can also consider a much larger factor and apply the same idea to images. Considering factor = 15 and rounding the resulting coordinates to the nearest neighbor, we go from the image at left to the image at right:

The complete code for obtaining the image follows. The factors n1 and n2 were used to obtain a "less boring" image.
import sys
from noise import snoise2
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')
result = Image.new('L', img.size)
width, height = img.size

factor = 15
res = result.load()
im = img.load()
for x in xrange(width):
    for y in xrange(height):
        n1 = snoise2(x, y)
        n2 = snoise2(y, x)
        pt = [int(round(x + n1 * factor)), int(round(y + n2 * factor))]
        pt[0] = min(max(0, pt[0]), width - 1)
        pt[1] = min(max(0, pt[1]), height - 1)
        res[x, y] = im[tuple(pt)]
result.save(sys.argv[2])

Of course this isn't even scratching how Perlin Noise can be used. As another example, given a certain function, you can "noisify" the inputs and combine with the mentioned factor to create different outputs. For instance, here is the result of doing that on some function based on cosine:


text:
Q: How to read data from multiple Firestore collections at the same time? My home screen contains different kinds of data: slideshow, popular products, discount products, featured brands, nearby shops, ... which are stored in different Firestore collections (some are in the same collection but different queries).
If we develop with Web API, we can respond to those data to a single endpoint request.
Rather than loading those data separately in Firestore, do we have another option that can load from a single task just like we do with Web API?

A: Are you using Firebase Client SDKs? If yes, then you'll have to make a different request for each collection. You can just use Promise.all() to run them simultaneously in a function.
Even if you write an API endpoint on your server to get everything in a single response, you'll be making different requests for each collection just using the server side SDKs.


text:
Q: is Swift generic protocol injection possible? I am trying to use generic protocols and inject a concrete implementation but I get the following error: Protocol 'Repo' can only be used as a generic constraint because it has Self or associated type requirements at let repo: Repo
My code
protocol Repo{
    associatedtype T

    func doSomething() -> T

}

class MyRepo: Repo{

    func doSomething() -> String{
        return "hi"
    }
}

class SomeClass {
    let repo: Repo
    init(repo: Repo) {
        self.repo = repo
        repo.doSomething()
    }
}

class EntryPoint{
    let someClass: SomeClass
    init(){
        someClass = SomeClass(repo: MyRepo)
    }
}

Entry point is called first and sets up the dependency tree.

A: I think what you are looking for is something like this:
    protocol Repo {
      associatedtype T

      func doSomething() -> T

    }

    class MyRepo: Repo{
      func doSomething() -> String{
        return "hi"
      }
    }

    class SomeClass<A: Repo> {
      let repo: A
      init(repo: A) {
        self.repo = repo
        _ = repo.doSomething()
      }
    }

    class EntryPoint{
      let someClass: SomeClass<MyRepo>
      init(){
        someClass = SomeClass<MyRepo>(repo: MyRepo())
      }
    }


text:
Q: Initializing google maps with multiple markers from an array I'm passing 2 arrays into google maps, one for a location (which is geocoded) and another for that location's info window.
Is there any way I can initialize the map and plot all these points at once, or will I have to make a second function to plot more points? Since there are multiple points, I'm not sure how else to do it other than plotting one point, and then making an addition function which loops through the array and plots the rest.
Here's the code.
The two arrays(which I didn't include the code for) are $cityArray and $title
function initialize() {
        geocoder = new google.maps.Geocoder();
        latlang = geocoder.geocode( { 'address':
                                    '<?php echo json_encode($cityArray); ?>'},
                                       function(results, status) {
        //use latlang to enter city instead of coordinates
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
               google.maps.event.addListener(marker, 'click',
                                             (function(marker, i) {
                return function() {
                    infowindow.setContent(
                        '<?php echo json_encode($title); ?>'
                    );
                    infowindow.open(map, marker);
                }
            })(marker, i));
            markersArray.push(marker);
        }
        else{
            alert("Geocode was not successful for the following reason: "
                  + status);
        }
    });
    var myOptions = {
        center: latlang, zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };

    var gm = google.maps;
    map = new google.maps.Map(document.getElementById("main_Content"),
                              myOptions);
    plotMarkers();

} //end of initialization function

var infowindow = new google.maps.InfoWindow();

A: Please refer the following Sample which i have used for the above.,
Step1 : Include the Three script Files in header of your page.,like
(i). <scrip type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<scrip type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<scrip type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>

Step2 : Scripts On Page

//To Create a XML For Markers and Information Windows
<?php
function mapMarker($center_lat,$center_lng,$radius)
    {
    $mysqli = $this->_getMySqlConnection();
    // Start XML file, create parent node
    $dom        =   new DOMDocument("1.0");
    $node       =   $dom->createElement("markers");
    $parnode    =   $dom->appendChild($node);

    // Search the rows in the markers table
    $query      =   sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
    $mysqli->real_escape_string($center_lat),
    $mysqli->real_escape_string($center_lng),
    $mysqli->real_escape_string($center_lat),
    $mysqli->real_escape_string($radius));

    $result = $mysqli->query($query);

    header("Content-type: text/xml");
    header('Access-Control-Allow-Origin: *');

    $avoid_duplicate="";
    // Iterate through the rows, adding XML nodes for each
        while ($row = @$result->fetch_assoc())
        {
            if($avoid_duplicate!=$row['store_name'])
            {
            $node = $dom->createElement("marker");
            $newnode = $parnode->appendChild($node);
            $newnode->setAttribute("name", $row['store_name']);
            $newnode->setAttribute("address", $row['street_address_1']);
            $newnode->setAttribute("lat", $row['lat']);
            $newnode->setAttribute("lng", $row['lng']);
            $newnode->setAttribute("distance", $row['distance']);
            $newnode->setAttribute("phonenumber", $row['phone']);
            $avoid_duplicate=$row['store_name'];
            }
        }

    $outXML=$dom->saveXML();
    $result->close();
    $mysqli->close();
    return $outXML;
    }
?>

HTML Part :

    <input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
    <input type="hidden" id="radiusSelect" value="50" />
    <input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
    <input type="hidden" id="radiusSelect_temp" value="50" />
    <input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />

<input type="hidden" id="loc_count" value="1" />

These are the things which will produce the great out comes.


text:
Q: Javascript Regular Expression to add dash after every 3rd and 4th characters The following regex:
x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, "-");

adds dash after each 3rd character so entered 123456789 turns into 123-456-789.
Im trying to use this regex to format phone number. The problem arises on the 10th character. So entered 1234567890 turns into 1-234-567-890.
How would I modify the above regex to turn strings that have 10 digits into 123-456-7890. I use this regex because this happens as user is typing in uses keyup event.
If you know easier or better way of doing this please help me out, dashes has to be added while user is typing in. No other characters allowed.
Notes:

*

*Cant use Jquery Masked input plugin (because if editing the middle character it's focus gets messed up)

A: If you ALREADY have the complete number or string
var x = "329193914";
console.log(x.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3"));

If you WANT AS someone is typing...
$('#locAcct').keyup(function () {
    var foo = $(this).val().split("-").join(""); // remove hyphens
    if (foo.length > 0) {
        foo = foo.match(new RegExp('.{1,3}', 'g')).join("-");
    }
    $(this).val(foo);
});

A: How about
> "12345678".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-78"
> "123456789".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-789"
> "1234567890".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-7890"

A: Do you need to use regular expressions for everything or would maybe something like this also help you out?
function convertToValidPhoneNumber(text) {
    var result = [];
    text = text.replace(/[^\d]/g,"");
    while (text.length >= 6) {
        result.push(text.substring(0, 3));
        text = text.substring(3);
    }
    if(text.length > 0) result.push(text);
    return result.join("-");
}

You could use this function everytime the text in your inputfield changes. It will produce the following results:
"12345678" -> "123-45678"
"123d456789" -> "123-456-789"
"123-4567-89" -> "123-456-789"

A: I believe the simplest way would be to add dash after every n digits would be like

var a = $('#result');
var x = "
asiija kasdjflaksd jflka asdkhflakjshdfk jasd flaksjdhfklasd f

12345678912345678912345678912312344545545456789
"

a.html(x.replace(/(\d{15})/g, "$1-"));

A: Most easiest way is the following using simple javascript onkey and function... it will put dash hyphen after every 3 characters you input / type.
<input type="text" class="form-control" name="sector" id="sector" onkeyup="addDash(this)" required>

add the following script


text:
Q: Type mismatch error on multicell entry in Workseet_SelectionChange I want to call a macro if the value of any cell in that column is "T", but every time there will be a run-time error: Type Mismatch for the line of If Target.Value = "T" Then. Can anyone please help me with this?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

     If Target.Column = 36 Then
        ThisRow = Target.Row
        If Target.Value = "T" Then
            Range("AJ" & ThisRow).Select
            Call mail_outlook
        End If
    End If

End Sub

Thanks a lot.

A: You probably have a cell that has an error in it... You can check for that condition like this:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   If Not IsError(Target) Then
     If Target.Column = 36 Then ' AJ
        ThisRow = Target.Row
        If Target.Value = "T" Then
            Range("AJ" & ThisRow).Select
            Call mail_outlook
        End If
     End If
  End If
End Sub

Also, you can check Target to see if the selection is more than one cell (if that helps)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   If Target.Cells.Count = 1 Then
     If Target.Column = 36 Then ' AJ
        ThisRow = Target.Row
        If Target.Value = "T" Then
            Range("AJ" & ThisRow).Select
            Call mail_outlook
        End If
     End If
  End If
End Sub


text:
Q: Pywin32 COM not able to set attribute keyerror I'm trying to automate something using its com interface. There are some problems which I can't get my head around.
app = DispatchEx('CANoe.Application')
configs = app.Configuration.TestConfigurations
config = configs.Item(1)
unit = config.TestUnits.Item(1)
unit.Name
unit.Enabled

Until here it is fine, name and enabled will print out a string and a bool value. But as soon when I want to set the enabled to false or true I get the following:
>>> unit.Enabled = False
Traceback (most recent call last):
  File "C:\Python\Python310\lib\site-packages\win32com\client\__init__.py", line 590, in __setattr__
    args, defArgs = self._prop_map_put_[attr]
KeyError: 'Enabled'

During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Python\Python310\lib\site-packages\win32com\client\__init__.py", line 592, in __setattr__
        raise AttributeError(
    AttributeError: '<win32com.gen_py.CANoe 12.0 Type Library.ITestUnit instance at 0x1977650030784>' object has no attribute 'Enabled'

Which is odd because in VBS it works without any problem (I need to port these to Python). Also it looks like that some attributes are not there like "Elements" when I print the internals of the unit object:
>>> print(dir(unit))
['Application', 'CLSID', 'Enabled', 'Name', 'Parent', 'Report', 'Verdict', '_ApplyTypes_', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', '_prop_map_get_', '_prop_map_put_', 'coclass_clsid']
>>>

When I do a "prop_map_put"
>>> print(unit._prop_map_put_)
{}
>>>

I tried to use setattr to set Enabled on true, it didn't throw an exception but after that I was not able to call unit.Enabled because I need to do something with ApplyTypes.

A: To solve this issue I had to cast the tu variable to an ITestUnit3. That way i'm able to set enable.
unit = win32com.client.CastTo(unit, 'ITestUnit3')


text:
Q: Depth API supported devices I'd really like to develop some ARCore apps which use the new Google ARCore Depth API. But I realize that there are only couple of devices that support this new feature. So, is there any information about updates in the future which to support devices that are today supported by ARCore but not for Depth API?
For example:
The Pocophone F1 is officially supported for the Depth API. It uses MIUI as Operating System and run with a Snapdragon 845.
Now is the question: why nearly exactly the same devices as Xiaomi Mi Mix 2s or Xiaomi Mi 8 are not supported?
These three devices all use MIUI same Camera and same CPU so would these devices Support Depth API in the future?

A: Firstly: there is a long list of devices that have ToF sensor and support Raw Depth API as well as Full Depth API for ARCore 1.24 at the moment. And I firmly believe there will be much more of them in the nearest future. You can see it in ARCore supported devices table.

*

*Google Pixel 2/3/4/5

*Huawei Honor 10/Nova 3,4/Mate 20,Lite,X/P20/P30/Pro

*LG ThinQ/G8X/V35/V50S/V60

*OnePlus OnePlus 6/T/7/Pro

*Samsung Galaxy A80/S8/S9/S10/S20/Note 8,9,10

*Sony Xperia XZ2/Compact/Premium/XZ3

*Xiaomi Pocophone F1

Secondly: ARCore's Depth API unsupported devices, seemingly don't have ToF sensor, or don't have powerful CPU/GPU for retrieving Depth data from Motion, or even don't have a gyroscope. Or in some case (like Huawei case) it's just Google's policy. OS and its UI don't matter.
For additional info on both ARCore Depth APIs, please look at this post.

A: google said single rgb camera is enough for depth api to work


text:
Q: C#/ASP.NET Short code Translation I have some data I'm showing in a few repeaters. I'm displaying the various fields using Eval(), and it's displaying correctly, but the data is using short codes for certain things.
For example:
db1 = Diabetes Type 1
db2 = Diabetes Type 2
tb  = Tuberculosis

etc etc
What I want to know is, if the Eval() is pulling up one of these short codes, how do I setup a conditional that will read the field, and adjust it to its proper long name?

A: So, you need to replace the Eval by a method that translates it, such as:
<%# Translate(Eval("SomeField")) %>

And in Translate:
public string Translate(object value)
{
    if (value is int)
    {
        int intVal = (int) value;
        switch (intVal)
        {
            case db1:
                return "Diabetes Type 1";

            //etc
        }
    }

    return "";
}

Beware that the bound value is prototyped as object, so you need to cast it to what you know is inside.


text:
Q: How do I find the $\sup\{s_{n+1}-s_n|n\geq 1\}$? Let $\{s_n\}$ be a sequence in $[0,1]$. Assume that $2s_n\leq s_{n-1}+s_{n+1}, n\geq 1.$ Then

*

*$\lim_{n\to \infty}s_{n+1}-s_n=\text{doesn't exist}$

*$\lim_{n\to \infty}s_{n+1}-s_n=0$

*$\lim_{n\to \infty}s_{n+1}-s_n=\frac{1}{2}$

*$\lim_{n\to \infty}s_{n+1}-s_n=1$
My attempt:-
$$2s_n\leq s_{n-1}+s_{n+1}$$
$$\implies s_n-s_{n-1}\leq s_{n+1}-s_n$$
$$\implies (s_2-s_1)  \leq...(s_{n-1}-s_{n-2})\leq (s_n- s_{n-1}) \leq ( s_{n+1}-s_{n}) $$
Hence the sequence $\{s_{n+1}-s_n \}$ increasing and bounded above. Hence $\lim_{n\to \infty}s_{n+1}-s_n=\sup\{s_{n+1}-s_n|n\geq 1\}$
So, option(1) is wrong.
How do I find the supremum of $\sup\{s_{n+1}-s_n|n\geq 1\}$?

A:

*is true. Here is a hint; If $l=\lim (s_{n+1}-s_n) >0$ then $s_{n+1} >s_n+\frac l 2$ for $n$ sufficiently large. Iterate this to get the contradiction that $s_n >1$ for $n$ large enough. Similarly, $l <0$ would give $s_n <0$ for $n$ large enough.


text:
Q: Rails 4.2 routing to ignore part of a URL My first SO question... Please be gentle :)
I have a specific routing requirement for a Rails 4.2 application but I'm struggling to accomplish it. My client offers it's members a website to sell the company's products and earn a commission on sales (kind of like Amway does)... Basically a glorified affiliate program. The pattern of their URL's is https://www.company.com/membername/products/something-you-can-buy. The requirement is that they keep this pattern in the new application I am building for them.
The membername part could be anything, and this application will not have access to the existing user database... We need rails to ignore the membername part of the url and process routing based on the rest of the URL. So if the URL is https://www.company.com/hephalump/products/hamburger we need routing to ignore the hephalump bit, but still keep it in the URL, and process the routing based on the products/hamburger portion. The client also needs the hephalump bit to stay in there throughout the entire application and we need to be able to capture it as a param at the point of purchase (that's easy enough).
I've been bashing my head against the wall with this for two days with no luck... Any help would be greatly appreciated.

A: There are many ways to do that. Here's one:
 get '/:_member/products/:product_name' => 'products#show'

Substitute the correct controller name prefix for products in products#show and the correct action name for show. In that controller  params will have both :_member and :product_name keys, and you can just ignore the :_member key.
You can also add constraints on what pattern can represent a member or a product name, e.g.:
 get '/:_member/products/:product_name' => 'products#show',
   contraint: { _member: /\w+/ }


text:
Q: Fourier transform in polar coordinates I have this formula that should be the Fourier transform for a generic coordinate system in the plane:
$\vec E(\vec k)=\int \vec E(\vec x) e^{-i \vec k \cdot \vec x} dx^2$

*

*However I don't understand on which interval should I integer?

*How should I write it for polar coordinates?


text:
Q: How to overcome app not installed error when building from Android Studio 3.0? For giving build for a debug Android app from Android Studio 3.0, it's not installing in Mobile having Marshmallow and up (in Lollipop not tested).
I have used many solutions from Stack overflow but it's still not working.
It's always showing App Not Installed on mobile phone.

A: Well the original question doesn´t have enough information, but we can have some info getting some comments:

*

*Android studio 3.0 and compileSdkVersion 26, buildToolsVersion '26.0.2',minSdkVersion 15, targetSdkVersion 26

*virtual debugging option also on.

*I am facing same issue after upgrading android studio from 2.3 to 3.0

Ok the message "App Not Installed" will refer to multiple causes, and please returning to Android Studio 2.3. from 3.0 is not an option!
When we upgrade from Android Studio 2.3 to 3.0  we can find some configuration issues caused mainly by the support libraries, that will cause that our application could not be installed.
To avoid this problem we need to invalidate cache in Android Studio 3.0+ and the problem will be solved.

Please try this option.

A: First try to generate the debug apk by below steps:

*

*Goto Run

*Edit Configurations

*select + icon on the left side

*Select Gradle

*Click the Configuration tab if it is not selected in the right side

*In Gradle project add your app as  a gradle project

*From the tasks select/set "assemble"

*Press ok

Now run that configuration.
you will have the debug apk ready in build/outputs/apk/app-debug.apk.
Now install that apk in any device. It should work.

A: As of Android Studio 3 the Run-Button builds test-only apks. See documentation

Note: The Run  button builds an APK with testOnly="true", which means the APK can only be installed via adb (which Android Studio uses). If you want a debuggable APK that people can install without adb, select your debug variant and click Build > Build APK(s).

This solved my issue:
https://stackoverflow.com/a/46661987/7756799

A: None of the other answers solved the issue. The build and install was going fine when it's triggered from android studio with a device connected to the computer or with an emulator, the only issue was when sending the apk via email or hockey app.
How I could fix it (and this might not be the solution for everybody), I enabled the multidex support by adding this to the default config:
// Enabling multidex support.
    multiDexEnabled true

PS: Usually Android Studio build would fail if the multidex support has to be enabled, in this new version this didn't happen, but my Jenkins build was broken and this is how I could solve it.

A: Ohh this is exactly we have to do:

*

*Go to Build

*Build Apk

*Locate Apk

A: In Android studio goto build menu and then Build Aps(s). Its work fine for me.

A: There are 2 type of APK Signature #1 JAR signature (aka v1) and #2full APK sign (aka v2): Not all the devices recognize it ,so make sure you anable both V1 and V2.

A: In my case my debug apk worked fine but when I tried to install Signed apk then following error shows
"APP not Installed"
then I haved added
multiDexEnabled true

in gradle fine then its work fine

A: Android Studio -> Build -> Build Bundle(s) / APK(s) -> Build APK(s) -> Reinstall new APK on mobile phone


text:
Q: USB drive stuck on read only So my usb drive is stuck on read only and I have tried many different options which I have gotten from different websites.
I have tried to restore/erase in disk utility but the options are greyed out. I have also tried entering recovery mode and erasing the USB drive from there but with no luck. I have also tried using macfuse (with NTFS-3g installed)however without any success, but I am happy to try this option again if anyone has some ideas on how to do it as I wasn't to sure what I was doing  and I was really just copy and pasting codes.
The USB is formatted as a MS-DOS (FAT32) if that helps.
Its really annoying because I cannot erase or edit or delete or do anything with any of the files. I do not mind if fixing it means I lose all the data.
Sorry if this is on the wrong stack exchange website, i'm pretty new to it all.
I have also tried turning my computer on and off again if that helps.
Thank you very much guys.

A: Plug the USB drive into any Windows computer.
Navigate to "My Computer" in Windows Explorer (click Start->My Computer[near the top right of the window]).
Right-click on the USB drive:

*

*Windows 7:

*

*Should be listed under "Devices with Removable Storage"

*Windows XP and older:

*

*Should just be listed in a list of all drives installed on the computer

Click "Format".
Choose options you want to format as, make sure the "Read Only" button is deselected, and make sure the "Hidden" button is also deselected, and click "OK".
Congratulations! Your USB drive has now been re-formatted. You (should) now be able to format it using Mac OSX.

A: You can format from a startup disk
Read this and try first:
http://support.apple.com/kb/ts2176
Or format from the terminal (warning you better know which drive you are working with before  you do this)
Try this if the first thing doesn't work:
https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man8/diskutil.8.html


text:
Q: image onerror not registering in ie7? so i have this script:
<script type="text/javascript">
        $(window).load(function () {
            var imagePath = new String($('.give').css("background-image").toString());
            if (imagePath == "none") {
                $('.give').css("text-indent", "0px");
            }
            else if (imagePath != null) {
                var tempImage = new Image();
                tempImage.onerror = function () {
                    if (!tempImage.complete) {
                        $('.give').css("text-indent", "0px");
                    }
                }
                imagePath = imagePath.split("images/")[1];
                imagePath = "images/" + imagePath.split(")")[0];
                imagePath = imagePath.split('"')[0];
                tempImage.src = imagePath;
            }
        });
    </script>

i need to check if images are disabled in the browser, if they are i need to bring the text back on the screen so the app can be used without images. the first if statement handles chrome and firefox because for some reason if images are disabled they return "none" for the background css property. not the case for ie7. the second if statement attempts to handle the case for ie but for some reason neither .onload or .onerror are getting fired.
has anyone encountered this that can help? or point me in the right direction? i have tried alot ways to do this. but i just cant seem to get it to work.

A: This is my solution:
<script type="text/javascript">
    detectImageEnabledMode({
        onDetectImageIsDisabled:function(){
            alert('disabled');
        },
        onDetectImageIsEnabled:function(){
            alert('enabled');
        }
    });
    function detectImageEnabledMode(options){
        /* define disabled/enabled actions */
        var actionCounter = 0;
        var enabledAction = (options.onDetectImageIsEnabled && typeof(options.onDetectImageIsEnabled)=='function')?options.onDetectImageIsEnabled:function(){};
        var enaledActionRun = function(){
            if(actionCounter) return;
            actionCounter++;
            enabledAction();
        }
        var disabledAction = (options.onDetectImageIsDisabled && typeof(options.onDetectImageIsDisabled)=='function')?options.onDetectImageIsDisabled:function(){};
        var disabledActionRun = function(){
            if(actionCounter) return;
            actionCounter++;
            disabledAction();
        }
        /* create image */
        var img = new Image();
        var currentTime = (new Date()).getTime();
        if(navigator.appName.indexOf('Microsoft Internet Explorer') != -1){// ie
            img.onload = enaledActionRun;
            img.onabort = enaledActionRun;
            img.onerror = enaledActionRun;
            img.src = currentTime+'.'+currentTime+'?time='+currentTime;
            setTimeout(function(){
                disabledActionRun();
            }, 0);
        }else if (navigator.appName.indexOf('Opera') != -1) {// opera
            img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="+'?time='+(new Date()).getTime();
            if(img.complete){
                enaledActionRun();
            }else{
                disabledActionRun();
            }
        }else{// other
            img.src = currentTime+'.'+currentTime+'?time='+currentTime;
            if(img.complete){
                disabledActionRun();
            }else{
                enaledActionRun();
            }
        }
    }
    // tested in: ff 2+, opera 9+, chrome, safari 4+, ie 6+
</script>

Live demo.
The only problem - the minimum asynchronous in ie:
setTimeout(function(){
 disabledActionRun();
}, 0);


text:
Q: Coherent States of Coupled Oscillators I am given the following coupled Hamiltonian
$$H=\hbar\omega[a_x^\dagger a_x+a_y^\dagger a_y+1+K(a_x^\dagger a_y+a_y^\dagger a_x)]$$
Which I can decouple into two different oscillators
$$H_u=\frac 12 \hbar \omega(1+K)(a_u^\dagger a_u+1)$$
$$H_v=\frac 12 \hbar \omega(1-K)(a_v^\dagger a_v+1)$$
I am then given that the system is prepared in a state $|\psi(0)\rangle=|0\rangle_x|\alpha(0)\rangle_y$ is a coherent state such that
$$\langle\psi(0)|y|\psi(0)\rangle=y_0$$
$$\langle\psi(0)|p_y|\psi(0)\rangle=0$$
I find that
$$\alpha(0)=y_0\sqrt{\frac{m\omega}{2\hbar}}$$
Finally, I am asked to show that each of the oscillators is in a coherent state for all time and that $\langle x(t)\rangle$ and $\langle y(t)\rangle$ act as coupled classical oscillators.  I am not sure how to show that they act as coherent states.  Showing the expectation values seems simple enough once I can find x and y as functions of time.

A: Prove your answer in two steps.

*

*Show that the initial state is a (tensor product of) coherent state for the new oscillator modes i.e., it is also an eigen vector of both $a_u$ and $a_v$.

*Next, show that any coherent state continues to remain a coherent state under time evolution, possibly with a time-dependent $\alpha$, where $\alpha$ is the parameter associated with the coherent state.
You are done.


text:
Q: Invalid use of template name ' ' without an argument list I'm trying to create simple stack using linked lists in C++. Suddenly I encountered the problem which is (I think) connected with templates. I lack knowledge in that structures thats why I tried to create something and learn with it.
My problem is with node * top; what should I change ? any idea?
My code is :
#include <iostream>
#include <cstdlib>

using namespace std;

template<typename T>

class node {
public:
  T object;
  node * next;
};

node *top = NULL;

template<typename T>
class Stack{

public:
  void push(T obj);
  void pop();
  void display(ostream & out) const;
};

void Stack :: push(T obj){

  node * tempNode = new node;
  tempNode->object = obj;
  tempNode->next = top;
  top = tempNode;
}

void Stack :: display(ostream & out) const{

    if(top == NULL){
      cout << "Stack is Empty"<<endl;
      return;
     }
     else{

       node *temp = top;
       while(temp!=NULL){

         cout << "Here is your elements :"<<"\n";
         cout << temp->object<<endl;
         temp = temp->next;
       }
       cout <<endl;
     }
}

void Stack :: pop(){

  if (top = NULL){
    cout << "List is Empty"<<endl;
    return;
  }

  cout << "Your object: "<<top->object << " is removed"<<endl;
  top = top->next;
}

ostream & operator << (ostream & out, const Stack & s){
  s.display(out);
  return out;
}

A: I'm guessing top should be a member of Stack not a global variable? You also need to specify the template type of node:
template<typename T>
class Stack{
  node<T> *top = NULL;

public:
  void push(T obj);
  void pop();
  void display(ostream & out) const;
};

When defining methods of templated classes out of line you need to specify the template type for the class:
template<typename T>
void Stack<T> :: push(T obj){

Your << operator also needs to be a template:
template<typename T>
ostream & operator << (ostream & out, const Stack<T> & s){
  s.display(out);
  return out;
}


text:
Q: Erro ao executar ReportViewer Eu coloquei o que ele pede no web.config.
Web.Config:
 <system.web>
    <globalization culture="pt-BR" uiCulture="pt-BR" />
    <compilation debug="true" targetFramework="4.5">
      <buildProviders>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
      </buildProviders>
      <assemblies>
        <add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Windows" />
    <customErrors mode="RemoteOnly">
      <error statusCode="401" redirect="/CustomErrors/401.htm" />
      <error statusCode="404" redirect="/CustomErrors/404.htm" />
    </customErrors>
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </httpHandlers>
  </system.web>
system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      <remove name="ReportViewerWebControlHandler" />
    </handlers>
  </system.webServer>

Dá a seguinte mensagem:
Report Viewer Configuration Error
The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file. Add

<add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

to the system.web/httpHandlers section of the web.config file, or add

<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

to the system.webServer/handlers section for Internet Information Services 7 or later.

Como arrumar isso?

A: Bom, o erro é bastante claro e te diz exatamente o que fazer. Basicamente, é colocar o seguinte no seu web.config:
<configuration>
  ...
  <system.web>
    ...
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      ...
    </httpHandlers>
    ...
  </system.web>
  ...
</configuration>

EDIT
O erro está aqui:
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      <!-- Retire a declaração abaixo -->
      <!-- remove name="ReportViewerWebControlHandler" /-->
    </handlers>
  </system.webServer>


text:
Q: Java JTextArea not displaying in GUI I am trying to create a simple swing GUI for a Java application that I'm writing, but I'm having a bit of trouble getting things to display on the JPanel, and I was wondering if anyone could point out what I'm doing wrong?
I have the following code in my Gui.java class:
package openDIS;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Gui extends JFrame{

public Gui(){
    setTitle("DIS Filter");
    setSize(1000, 500);
    setLocation (10, 10);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    initGui();
}

/*public quitButton(){
    initGui();
} */

private void initGui(){
    //JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    this.getContentPane().add(panel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("DIS Filter");
    this.setSize(1000, 500);

    panel.setLayout(null);
    /*Add a JTextArea to display the output DIS information */
    JTextArea displayOutput = new JTextArea();
    panel.add(displayOutput);

    //String data = EspduReceiver.espdu;
    int n = EspduReceiver.entitySite.size();
    for (int i = 0; i < n; i++){
        EspduReceiver.receivePdu();
        System.out.println(EspduReceiver.entitySite.get(i));
        System.out.println(EspduReceiver.entityApplication.get(i));
        System.out.println(EspduReceiver.entity.get(i));
        displayOutput.append(EspduReceiver.entitySite.get(i).toString());
        displayOutput.append(EspduReceiver.entityApplication.get(i).toString());
        displayOutput.append(EspduReceiver.entity.get(i).toString());
    }

    JButton quitButton = new JButton("Quit");
    panel.add(quitButton);
    quitButton.setBounds(875, 400, 80, 30); /*Set the location of the button in the window, and its size */

    quitButton.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            System.exit(0);
        }
    });

    panel.add(quitButton);
    //setTitle("Quit");
    //setSize(60,30); /*This line was overwriting the previously set values for the size of the window */
    setLocationRelativeTo(null);
    panel.repaint();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args){ /* I probably don't need a main method here- I have one in EspduReceiver.java */
    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            Gui gui = new Gui();
            gui.setVisible(true);
        }
    });
}

}

Currently, when I run the class, a window opens up that's titled "DIS Filter", and has a 'Quit' button in the bottom right hand corner- the quit button functions correctly.
However, no matter what I try, I can't seem to get the JTextArea to display... can anyone point out what I'm doing wrong here?
Thanks!

A: You still need a layout, use FlowLayout as a simplest one. Also you have to set JTextArea size.
panel.setLayout(new FlowLayout());

/* Add a JTextArea to display the output DIS information */
JTextArea displayOutput = new JTextArea(50, 50);
panel.add(displayOutput);

A: Don't use a null layout; give the text area a preferred size, and pack() the enclosing Window.
JTextArea displayOutput = new JTextArea(3, 16);

A: try this:
displayOutput.setRows(20);
displayOutput.setColumns(5);
displayOutput.setVisible(true);


text:
Q: How can I delete QSharedPointer from container the right way I have QVector<QSharedPointer<SomeData> > DataVec as a field of one class in a big objected-oriented project. Program gets memory overflow during cycled execution of code part, where large memory is allocated, controlled by QSharedPointers.
During program run cycle, DataVec is filled with
DataVec.push_back(QSharedPointer<SomeData>(new SomeData()));

Will QSharedPointer be deleted (released) after calling DataVec.pop.back() or DataVec.clear()?
I think: no. We must call explicitly destructor for QSharedPointer (I cannot see also the method like boost::shared_ptr::reset() in Qt). Than, SomeData default destructor (SomeData have only standard Qt containers as fields) will be called if we have no more QSharedPointers that point to SomeData instance concerned, and the memory will be released. Now, I only do pop_back(): it seems, I just loose pointers to unreleased data (after execution, valgrind indicates I have definitely lost blocks, and I suppose they originate from here).
So, finally, am I right? And how can I delete QSharedPointer from container the right way?
EDIT 1:
The method like boost::shared_ptr::reset() in Qt is QSharedPointer::clear().

A: QVector will call the destructor of its item when the item is removed from it using pop_back, clear or any other way.
If there is a shared pointer to an object in the vector and there is no more shared pointers to this object anywhere in the program, removing a shared pointer from the vector will definitely cause object deleting.
If there are shared pointers to this object somewhere else, the object will not be deleted until all references are removed.


text:
Q: Creating shortcut inside windows start menu I can't create a shortcut or even create a folder inside C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\ and get an "Access is denied" error in both cases. I am using C++(WinAPI) and am interested in creating a shortcut inside that folder. Code for creating shortcut is working perfectly for other locations(for example for creating shortcuts on Desktop). How can I workaround this error?

A: Writing to the All-users start menu requires UAC rights. So, you'll need to run your application as administrator. Or just use the current-user start menu
"C:\Users\[CurrentUser]\AppData\Roaming\Microsoft\Windows\Start Menu"
#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
    string StartMenuLocation=
    (string)getenv("HOMEDRIVE")+"\\Users\\"+(string)getenv("USERNAME")+"\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu";
    cout<<StartMenuLocation;
    cin.get();
}

Hope this helps.


text:
Q: How to add app source code to xcode after downloading as a zip file from github Can anyone tell me how to add and open the moodle mobile app to Xcode?  I have downloaded the latest open source moodle mobile app as a zip file but not sure how to import or open this in xcode?
Basically want to open this in xcode, edit images and then be able to publish to the app store.
I have seen youtube videos showing github with a button called "open in xcode" but i don't see this in github as an option. The options that i get is to open in github desktop or download as zip.
https://github.com/moodlehq/moodleapp.git
Any help would be appreciated.
Thanks


text:
Q: How Can I stream AAC format from http://ipaddress:port? I am looking for a free flash player (not windows media player) to stream AAC audio from a website which has a link of this type: ipaddress:port, whith.
What player can I utilise?
I tried to use JWplayer, but I could not able to set it.

A: Use the shoutcast player, as in the jwplayer example below or this one: http://www.wavestreaming.com/player/free-shoutcast-flash-player
Basically your source is an shoutcast stream, so you can use any flash based shoutcast audio player.

A: I suggest to use ViaStreaming services, they offer free for clients aac+, aac, mp3 stream flash player without any transcoder or additional server, direct from SHOUTcast server.
Example: http://s1.viastreaming.net/8100


text:
Q: In bash, how can I export/set a global variable from a read funtion inside a script, for use in a second script and a config file later on? For example. I have 2 discrete scripts, which I want to remain and run separately. Script 1 utilizes a read function asking for a desired filename lets just say name1, does it's thing, and outputs the file with name1.
I need the second script to utilize name1 as part of an input, as well as a configuration file separate from the script that is able to point to name1 [assuming directory is fixed, but file name is variable.]
To do this, I imagine I'd need a way to export a global variable The way I have it now looks something like this:
read -p "What do you want this file to be called?: " name1
export name1=$name1

running the following as
. script1.sh

and then
echo $name1

yields the correct results, but how can I replicate this behaviour without having to specify run the script in the current shell with . - assuming that the next person would just run ./script1.sh or something, is there a way to export globally? This way I could use the variable $name1 in both the config file as well as script2.
Many thanks in advance.

A: You can't really. A script can not set an environment variable in the parent shell's environment.
One solution would obviously be to create a third script that runs the two other scripts in the particular way that they need to be run. It would source the first script and then run the second script.
Alternatively, combine the two scripts into one script.  If you split them up to "keep things separate", then you can do the same with functions in one and the same script if you wish.
Also,
export name1=$name1

may be shortened to
export name1