text:
Q: Why did the word, "shellac" come to mean "to defeat completely" as a U.S. slang? There were clamorous arguments about the appropriateness or inappropriateness of Mr. Donald Trump's comment, "Hillary Clinton – former first lady, former U.S. senator, former secretary of state, woman got schlonged by then-senator Barack Obama in her 2008 primary run." at a campaign stop in Michigan on December 21, 2015.
I suspect that Mr. Trump's phrase in question "(Mrs. Clinton) got schlonged" is a malapropism of "got shellacked," after reading the following paragraph in the article under the title of "Donald Trump's 'shlonged': A linguistic investigation" in The Washington Post (December 22, 2015).

And headline writers often ransack the language for onomatopoeic synonyms for 'defeat' such as drub, whomp, thump, wallop, whack, trounce, clobber, smash, trample, and Obama's own favorite, shellac (which in fact sounds a bit like shlong).
[emphasis added]

Collins English Dictionary defines "shellac" as:

verb.

*

*to coat or treat an article with a shellac varnish

*(U.S. slang) to defeat completely

besides the noun meaning a natural varnish.
So much for a long preamble and apart from right or wrongness of my guess, how did "shellac" come to mean "complete defeat"?

A: Getting drunk and getting 'shellacked' in the early decades of the 20th century link directly...almost. So also getting 'shellacked' in the sense of being "completely defeated", "beaten thoroughly", to or near to death, in the later decades of the 19th century, then also in the second decade of the 20th, is...close to...a direct link. For the second sense, that is, getting 'shellacked' in the sense of being defeated or beaten thoroughly, the connection between that slang use of 'shellacked' and the first, the slang use in the sense of getting drunk, seems likely to have cemented the adoption of the sense, supposing it did not sponsor it.
The evidence for the suggested connections is straightforward. For the first case, where getting drunk became known as getting shellacked, the use developed from the circumstances represented in these examples:

*

*From The Baltimore Sun, 24 May 1900 (paywall; emphasis mine):

Another instance of alleged insubordination as reported cites 16 of [the crew of the battleship Texas] as drinking alcohol used for shellacking the decks. This made them so unruly, it is asserted, that the marines found it necessary to level their guns at the sailors before they could induce them to obey.

*From the Fitchburg Sentinel (Fitchburg, Massachusetts), 14 May 1903 (paywall; emphasis mine):

If Major Dwinnell [the "keeper" of the jail in Fitchburg] would tell some of his peculiar experiences with prisoners during the past three decades, they would prove mighty interesting. A short time ago a man was set to work shellacking some woodwork. Later the major found the man in a "hazy" condition, and calling him by name, said, "What's the matter with you?" "Nothing, sir." "I know better," replied the major, getting a whiff of his breath, "what have you been drinking?" "Nothing, sir." "Take ---- to solitary confinement until he is willing to tell what he has had and where he got it," was his order, .... The man was conducted to the solitary cell and on reaching it he said, "Wait a moment, Major, I'll tell you what I've had. I drank the alcohol in the shellac. When the turnkey mixed the alcohol I turned some water into the tin. That separated the alcohol from the shellac and I drank it." Major Dwinnell did not believe the statement, but the man offered to demonstrate that it could be done and the experiment was made. It acted just as he said, the alcohol floating on top.

At least among sailors and prisoners in the early decades of the 20th century, getting 'shellacked' had close to a literal meaning; they got drunk not on the shellac itself, but on the alcohol used as the vehicle in applying shellac. This association is explained more technically in the 13 Jan 1921 Wichita Beacon (Wichita, Kansas; paywall):

As alcohol readily evaporates, shellac and varnishes are dissolved in it in order to apply a smooth surface coating to articles.

In part, the further development from prisoner and shipboard slang, and the more general use of the slang 'getting shellacked' to mean "getting drunk" is owed to US national prohibition, otherwise known as the "dry law" or, more technically, the Volstead Act, which took effect in January of 1920. For example, these subtitles over a 17 Jan 1921 New York Herald article reviewing the effects of the "dry law" after a year on the books:

BAD STUFF EVERYWHERE
Shoe Polish, Hair Tonic, Shellac
  and Other Dangerous
  Concoctions Drunk in
  Charleston.

Similarly, this fanciful recipe from a 20 Jan 1921 filler piece in The Manhattan Republic (Manhattan, Kansas; paywall; emphasis mine):

A little information on how to make forty gallons of home brew. Follow directions carefully: Capture a wild bullfrog and pen him up for three days and feed him on hair springs; turn him loose and chase him three miles; then go back on the route taken by the frog and gather the hops; to said hops add ten pounds of tan bark, three pounds of glue, one of soap, and one pint of shellac; boil for thirty-six hours and strain through a sock. This does not conflict with the Volstead Act.

By 15 May 1922, the use of 'shellacked' to mean "drunk" was well-enough established for it to appear as a synonym of 'jammed' in an article in the Wilkes-Barre Times Leader (Wilkes-Barre, Pennsylvania; paywall; emphasis mine):

  ....
  JAMMED — Intoxicated, pickled, shellacked, canned, out like a light, potted, shined, drunk.

The comparatively light-hearted use of 'shellacked' to mean "drunk" also developed from rather more somber circumstances. Those circumstances, in concert with the adoption of the "drunk" slang sense, probably sponsored the parallel development of 'shellacked' in the slang sense "thoroughly beaten, completely defeated". The connection in this case, while a bit more marginal, is nonetheless quite close to direct — and gruesome.
At about the same time that sailors and prisoners were getting 'shellacked' by drinking the shellac's alcohol vehicle, a number of serious accidents from the late 1800's were being revisited in the popular press. Those accidents were caused by the hazards of shellacking the interiors of brewery casks and vats; one of the greatest hazards of shellacking the casks and vats was being overcome and crippled, if not outright killed, by the fumes.
For example, a short article in the 29 Jan 1898 Logansport Pharos-Tribune (Logansport, Indiana; paywalled) describes one such incident:

Died from Inhaling Noxious Fumes
  Michael Gelhaus and Aloise Metter, who were employed in shellacing the large beer vats in the Pabst brewery, died last night from inhaling the fumes of charcoal and shellac.

Another example, from the 18 Jan 1900 Alton Telegraph (Alton, Illinois; paywalled), a few months before the drunken sailor incident aboard the battleship Texas, describes a man allegedly blinded by fumes from the alcohol in the shellac:

John Grant has begun suit...for the loss of his eyesight. While in the employ of the brewing company he was set to work shellacking barrels and kegs. In the shellac was an amount of wood alcohol. From this, it is asserted, fumes arose which acted on the nerves of the eye till he became blind.

Then, in the 7 Feb 1903 Eau Claire Leader (Eau Claire, Wisconsin; paywalled; emphasis mine), a couple of months before the enterprising prisoner in Fitchburg revealed his secret for getting drunk to the jail "keeper", a doctor detailed his opinion that the fumes of the wood alcohol in the shellac killed the two men mentioned in the 1898 Logansport Pharos-Tribune article:

"In 1898 two men met death while shellacking vats at the Pabst brewery. It was thought to be from the carbonic gases from the charcoal fires. However, I contended and have so said to the American Medical society, that the fumes of the wood alcohol killed the men by inhalation...."

The problem is mentioned again in a general article about painters' problems in the 13 Jan 1907 Chicago Tribune (paywalled; emphasis mine):

Chemicals Hurt the Eyes.
  Another kind of work that painters try to avoid is where they have to use wood alcohol in closed rooms and shellacking the interior of tanks in breweries. The odor is so strong that it is impossible for them to work more than fifteen minutes without needing fresh air. There are a number of cases where painters have lost their eyesight doing this kind of work....

Four years later, Health Commissioner Francis E. Fronczak submitted a letter to the editor printed in the 13 Mar 1911 issue of The Buffalo Enquirer (Buffalo, New York; paywall; emphasis mine):

Dear Sir — I noticed in The Enquirer your editorial on "Wood Alcohol." Permit me to inform you that some two weeks ago, following the deaths of men who were employed shellacking vats in a brewery, I ordered an investigation by physicians and City Chemist, to determine what effect the fumes of wood alcohol would have along this line. Examinations are being made at present with a view of preparing suitable ordinances to regulate the use of wood alcohol in the various industries.

While the newspaper articles I found do not go into graphic detail, the effects of shellacking brewery vats were well known. Men (and boys) charged with the task came staggering out of the vats after a very few minutes, then collapsed and, in many cases, died, or went on to suffer grievous disabling injury. The unfortunates had received a thorough shellacking.
These circumstances in combination, the alcohol to be had from working with shellac along with the disabling effects of working with shellac in closed spaces, quite possibly sponsored the development of both slang senses of 'shellacked' and 'shellacking' — the sense of 'staggering drunk' and the sense of 'completely defeated'.
Although the earliest use of 'a shellacking' in the sense of "a thorough beating, a complete defeat" that I found was in a syndicated 17 Nov 1923 article in the Star Tribune (Minneapolis, MN; paywalled; emphasis mine), the context is such as to suggest the slang sense was extant at least a few years, if not decades, prior. In that article, by Damon Runyon (known for his use of colorful vernacular), about the defeat of the Princeton football team by Yale, Runyon describes the event thus:

However, no one expected Yale to rub it in. No one expected Princeton to get such a "pasting" as the thing would be inelegantly termed in more professional circles, such a "shellacking."

la connexion française
The verb, 'to shellac', in all its senses, derives from the noun 'shellac', which itself translates French laque en écailles, "lac in thin plates". An article in the 23 Jan 1921 issue of The Fort Wayne Journal-Gazette (Fort Wayne, Indiana; paywalled) described its production in detail:

SHELLAC is the product of a tiny insect which infests certain trees in the East Indies. The term lac is the same as the Hindu numeral lac — a hundred thousand — and indicates the countless myriads of insects which make their appearance each spring on the young, tender shoots of the infested trees. These feed upon the sap in the bark, and after passing it through their bodies exude it in the form of a crimson-colored resin, which in course of time hardens into a tiny semi-transparent cocoon or shell.
    It is these cocoons which, after being melted in boiling water and poured out on a cold surface, constitute the shellac of commerce.

Although the connection is based more on speculation than evidence, I suspect a tradition transplanted to the US from French and London exhibitions in the early 1920s may also have contributed to the adoption of 'shellacked' in the slang sense of 'very drunk'. That tradition is sketchily described in the 21 May 1922 issue of The Cincinnati Enquirer (Cincinnati, Ohio; paywalled):

One of the most gala of these occasions, however, is yet to come — "Varnishing Day," instituted a year or two ago, one of the few known to the United States and which this season will open the spring exhibit of American art.... "Varnishing Day" is by the highest tradition of the spring salons of Paris and London, for the intimate elect...only the life and annual members of the Museum and the exhibitors themselves will be bidden to this private view....

"Varnishing Day at the Royal Academy" is illustrated by George Du Maurier in Punch, 19 June 1877:

As noted at The Victorian Web, "the Academy originally created Varnishing Day to permit artists to bring in freshly painted canvases and then later apply protective varnish."
The day was marked not only by the artists and 'elite' patrons getting thoroughly drunk on wine and other spirits; it was also marked by those in close quarters with their pots of shellac suffering some of the same disorienting effects experienced by the painters in brewery vats in the late 19th and early 20th centuries.

A: Not an exhaustive  answer to this question,  I wonder if there may be one, but other possible origins of the slang sense of shallac in the sense of defeating.
Curiously World Wide Words, unlike Etymonline predates  the slang  sense of drunk to that of defeated, and suggests as a possible origin the phonetic strengh and relevance of the combined usage of "shelling with whacking":

Within a couple of years, shellacked had evolved from being drunk to being soundly defeated in various sports, including baseball and boxing:
  Giants beat Reds in ninth; Cubs shellac Boston Braves
  A headline in the Hartford Courant, 26 May 1924.

*

*The smart Mr. Shevlin was biding his time, however, and when the opportunity came in the third he took full advantage of it and shellacked Norton plenty, ripping both hands to the mid-section with much power behind each drive.
  Evening Tribune (Providence, RI), 3 Jun. 1924.

  How that second shift happened is guesswork. If the only sport involved were boxing, we might try to make a link through punch-drunk, but that doesn't work for baseball. Several writers have plausibly suggested that the word, with its strong consonants, suggests some sort of violent action, perhaps a combined shelling and whacking.
  Whatever the exact chain of development, any mental link with the lacquer is now tenuous at best.

This same theory is suggested also in the Johnson language blog  column in The Economist:

But as The Economist's language blog, "Johnson," noted, in a post playfully titled "I'll give you a good varnishing," furnituremaking is an odd source of metaphor here. And how did shellac, and not some related word from the world of cabinetry, get tied up with crushing defeat, at the ballot box or on the ball field? The fellow in the Beeb's photo does not, after all, look very scary.
"Johnson" offers an explanation
I'm going to hazard a guess that it owes its new meaning to some kind of loose free-associative aural adaptation: it sounds like both "shelling" and "whacking," or even more loosely, it contains a satisfying rhythm of sharp-sounding consonants, and thus wound up being used in the sense of destruction because it "sounded right."
After all, one can be "soundly beaten," or, to use President George W. Bush's term under similar circumstances, "thumped," and still rebound. That's not possible to whatever gets literally shellacked. A tree cut down and made into a piece of furniture is not going to start growing again.

Also the following source suggest that the  usage of "drank" comes earlier than "defeated, beaten", and just from this former  meaning might come the latter:

To see what happened, you have to know the intermediate stage in the development of this word. The original meaning of the verb 'to varnish with shellac' (a type of resin) is known from the late 19th century. Anything that had been 'shellacked' would have a nice rosy tinge. By the 1920s, in the USA, this effect had evidently been enough to motivate a slang use of the word meaning 'drunk'. Rosey, illuminated, and plastered show similar developments - all early 20th-century slang.
At the same time, drunks were also being described using such words as busted, bombed, crashed, and thrashed. So it's not surprising to see these words sharing their associations. The connotations of thrashing transferred to shellac, which then developed its later slang sense of 'badly beaten'. I've only every heard this used in US English - but all that is about to change. I predict it will turn up in the House of Commons within the next few days.

Green's Dictionary of Slang offers its view on this issue:
shellack v.:

[SE shellac, to coat or varnish with shellac; note Dennis Wilson on American Dialect Society List (Internet, 14/11/02: 'Here are my guesses; I find any of them plausible, or a combination.
(1) Derivative of German "schlagen" (= "strike") or equivalent. Cf. supposed etymology of "schlock" (from Yiddish). Cf. "Our team really got clobbered", "I really got hammered on schnapps last night", "They really gave him a pounding".
(2) Onomatopoeic (cf. "smack", "whack" etc).
(3) [The books seem to favor this one] Shellacking being the last step in finishing something; thus something shellacked is something completed, something which has been "finished off"']
[1920s+] to beat, to thrash, to punish; thus shellacker n.

A: One possibility is that shellacking involves a color change to a redder or darker hue. That, at any rate, appears to be the sense of the word in this advertisement for the "Princess Theater: Home of the Fotoplayer and Clean Moral Pictures," in the Oak Creek [Colorado] Times (March 17, 1923):

"Fools of Fortune"
Starring Marguerite De La Mott and a large cast
It's a laugh every inch of the way from the ranch out Montana way where Chuck reads of Millionaire De Puyster's search for  long lost heir—through feverish preparations for the trip East—including the shellacking of Ike Harper into an Indian who has to grunt confirmation of Chuck's wild tale—Comic adventure on a Pullman, and the surprise that awaits the four old scamps in the effete East

The shellacking here almost certainly refers to painting the character (who, presumably, is white) so that he looks as though he is Native American. The advertisement later appeared in newspapers in Perth, West Australia (November 9, 1923) and in L'Anse, Michigan (September 19, 1924).
The first occurrence of shellacking in the sense of "beating" that an Elephind search returns is from "Greb's Slam-Banging," in the [Sydney, New South Wales] Referee (March 3, 1926):

The king of the middleweights [Harry Greb] has lots of fancy punches, some allowable in fair rules, and some not. But regardless of referee, or oral objections from the crowd, he used them one and all in handing Mr. [Ted] Moore a pretty severe shellacking. Holding the other fellow securely around the neck, and hammering away with the free member is one of his pet theories. His punches are liable to start from anywhere and finish likewise. He mixes the fastest kind of two-handed punching in with slapping and mauling.

Less than six weeks later (April 14, 1926), The Referee is back with an account of Mr. Greb taking "a frightful shellacking" at the hands of Tiger Flowers, a black man. And 11 months after that, a Honolulu, Hawaii newspaper, the Nippu Jiji, refers to another prize fight as "the McTigue-Sharkey shellacking bee." According to the color-change theory of shellacking, the term would be most appropriate when used to describe someone who is bruised from head to toe from a beating, as though covered with a darkening shellac.
Another possibility is that shellacking refers to the practice in medical schools of the early 1900s of preserving body parts by coating them with shellac. An example of this sense of the word appears in "Thought It Was Murder: Patrolman Finds Human Arm and Leg in Ash Barrel," in the [Philadelphia, Pennsylvania] Evening Ledger (January 30, 1920):

[Patrolman] Curry thought someone was hiding in the barrel, and grabbed the hand. It cam away, and an arm with it. The patrolman delved deeper in the barrel and found a human foot. It was attached to a perfectly good leg.
"Murder." said Curry to himself, and trotted off to the station house with the members under his arm. There examination disclosed that they had been neatly severed, carefully preserved and shellacked thoroughly.
The police believe the leg and arm belonged to a medical student, who didn't want them any longer. He can get them, if he has changed his mind about his property, by applying at the morgue.

So if this practice is the source of the slang expression, a shellacking is a final step in preserving a (metaphorically) dead body.
Yet another early slang use of shellacked seems to refer to drunkenness, as KarlG's answer notes. Elephind fetches examples of this usage from as early as 1922. From "Police Court," in the [Roanaoke, Virginia] World News (March 14, 1922):

E. J. Smith was let down with an assessment of five berries this morning. He was up for drunkenness. "But the next time you come in this court room for being drunk, you can just begin counting sixty days," quoth his honor.
Then came M. C. MacFerguson, and his fine for getting shellacked was five boffos. "I Just want to tell you that thirty days awaits your return," the court warned.

And from "Younger Generation Lingo," in the next day's [Roanaoke, Virginia] World News (March 15, 1922), originally printed in the New York World:

The Mother: "Well, dear, did you have a good time last night?"
The Daughter: "Oh, Mom, it was perfectly blaah—nobody there but a lot of cake-eaters and grease-balls. There was one wally I was goofy about, but while I was necking with him, Harry caught a tomato, so he says, 'let's blouse,' and we left and crashed in at the Plaza. A friend of Harry's we met there was the darbs, and after that we drifted to a couple of the clubs, and both tho boys got beautifully shellacked."
Mother: "Shellacked! I don't understand."
Daughter: "Jammed, both of them, and at one place we were in I got my glimmers on. Tommie Smith. He had a dumb-otis with him that looked like a scandal-walker, but somebody said he was a Pittsburgher out on parole. Anyhow he was making the boffos fairly fly."

The Kalgoorlie [West Australia] Miner (Aprl 27, 1922) very conveniently explains all of the terms in that excerpt in an article titled "The American Language: 'Cake Eaters' and 'Grease Balls'," where we learn that shellacked means exactly what you think it means:

Shellacked.—Jammed or intoxicated.
...
Overdose of Shellac.—Description of a girl who has on too much powder.

Conclusions
So the chronology looks like this:

*

*January 30, 1920: A Philadelphia newspaper describes the shellacking of dismembered human body parts and implies that this is standard medical school practice.

*By March 14, 1922: A New York City newspaper identifies shellacked in the sense of drunk as part of youth slang.

*By March 17, 1923: A movie ad that appears in various newspapers in the United States and Australia, refers to shellacking as a way to transform a white person "into an Indian."

*By May 26, 1924, and then June 3, 1924 (according to user159691's sources), and February 27, 1925, and then March 1, 1925 (according to KarlG's sources), and by March 3, 1926 (according to Elephind): A Connecticut newspaper (talking about baseball game), and a Rhode Island newspaper, a Pennsylvania newspaper, a Los Angeles magazine, and a Sydney newspaper (referring in each case to a boxing match) use shellacking in the sense of a severe beating.
From this record, it appears (at least provisionally)  that shellacking may have originated in slang as a way of describing getting quite drunk, from which it may have migrated to the ring to describe someone getting "punch drunk." Even so, it isn't out of the question that the youth slang usage might owe its origin to awareness of the use of shellac to preserve dead bodies (or body parts). After all, referring to someone as getting "shellacked" with alcohol is not much different from referring to him or her as getting "embalmed."

A: A folk etymology that I heard long ago says that it is an indirect reference to coffins. These (allegedly) require varnish - shellac - so a heavily defeated enemy in battle would need to order extra supplies of Shellac to varnish all the coffins they would need. It is almost certainly not true, a story created later to explain the unknown.
According to the BBC the term comes from 1930 gangster lingo, with no particular reason, and parallels the BrE pasted or plastered (though in my Yorkshire dialect that means 'very drunk').
The Online Etymology Dictionary says:
The slang sense of "beat soundly" is 1920s, perhaps from the notion of shellac as a "finish." Shellacked "drunk" is from 1922 (compare plastered).
The possible notion of finish aligns with the finishing coffins story. The reference to shellacked as being drunk is interesting. Maybe both terms are meant to raise an image of an individual staggering around like a drunkard and unable to function properly as a result of a shocking defeat. Of course, that speculation simply moves the question: why use 'shellacked' for a drunk person?

A:
Question: How did "shellac" come to mean "complete defeat"?

My answer: The apparent meaning is in the sense of shellac being a common furniture or wood finish (the idiomatic use being figurative in this case), which requires comparatively little effort to apply and is fast-drying.
So: To shellac (verb) someone in the competitive sense, is to finish them off quickly and easily. To get the job done in an efficient manner that provides almost instant gratification and a pleasurable sense of satisfaction. In a way that rewards the ego and boosts the subject's self-esteem.
And adding insult to injury is the subtle insinuation that the loser may be objectified by comparing them with inanimate wood or furniture needing maintenance or repair.

~Easy to use – Shellac is user-friendly and virtually goof-proof. It can be applied with a brush, pad, sprayer, or wiping cloth.
~Super-fast dry time – Shellac dries to the touch in MINUTES and, in most cases, can be sanded or recoated in a little over half an hour.
The Story of Shellac (from a circa 1913 merchandising brochure)

Now, with regard to the use of shellac as an adjective, "shellacked", you said:

I suspect that Mr. Trump's phrase in question "(Mrs. Clinton) got schlonged" is a malapropism of "got shellacked,"

I would have to agree, since both terms have similar connotations. So, to have been shellacked means to have been finished off rather briskly or brusquely.

A: Shellac is a natural resin, which dissolved in alcohol results in a hard, glossy finish when dry. Since modern synthetics like polyurethane have largely replaced it, most people today, never having worked with shellac before, are no longer familiar with its characteristics or means of application.
Ben Zimmer's 2010 article on Obama's shellacking points out that the first slang use, from the 1920s, was a euphemism for "extremely drunk," suggesting an analogy from another finish in the building trades: plastered. The idea is that like plastered walls or shellacked panelling, a drunk person is "finished," i. e. completely and totally drunk. Neither Zimmer nor another author he cites, however, mentions the most salient feature shared by shellac and the soundly inebriated: they both stink of alcohol.
Zimmer traces the next slang use of shellacking to the boxing ring:

At the end of the third round the Tiger was giving his man a thorough shellacking against the ropes.
  —Indiana (Penn.) Evening Gazette, Feb. 27, 1925
As long as I live I shall never forget the beating I received at the hands of Joe Rivers... What a shellacking I got.
  —Los Angeles Times, Mar. 1, 1925 ("My Hardest Fight" by Johnny Dundee, originally in Ring Magazine)

The rather fanciful rationale for this usage comes again from the notion of shellac as being a finish, with overtones of a defeated boxer being covered in shellac à la Han Solo in whatever that black gunk was.
Shellac was used most often on large surfaces — panelling, cabinetwork — and even had a number of marine uses. As the vehicle of the finish was alcohol, shellac had to be applied quickly, often using a large brush, then smoothed before the alcohol evaporated. If we still say "slap on a coat of paint," then that slapping — the sound of a loaded brush hitting a surface — would go double for shellacking, which has to be done far more quickly than with an oil- or water-based finish. An opposing sports team, a disobedient child, and apparently an incumbent president were thus liable to a series of rapid slaps like someone shellacking a boat or panelled room. In this usage, it really is the process of shellacking that gave rise to its metaphorical slang use, not, as with the 1920 drunks, some quality of shellac itself.

An 8" shellac brush.


text:
Q: WebView loadDataWithBaseURL on finished loading listener I'm loading data in a webview using loadDataWithBaseURL from a string. I want to implement a listener which tells me when the data is loaded completely so that i may proceed with my code.
I've searched a lot but could not find any relevant topic
if (new String(rowData.getResource().getData()) != null) webView.loadDataWithBaseURL("", new String(rowData.getResource().getData()), "text/html", "UTF-8", "about:blank");

A: Use WebViewClient and implement onPageStarted,onPageFinished to know the status of the webview.
ProgressDialog progressDialog = new ProgressDialog.show(this);
progressDialog.setMessage("Loading WebPage...");

class CustomWebViewClient extends WebViewClient {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progressDialog.dismiss();
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        progressDialog.show();
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return super.shouldOverrideUrlLoading(view, url);
    }

}

webview.setWebViewClient(new CustomWebViewClient());

A: Try this Tested working demo.
public class URLActivity extends Activity {

    private ProgressDialog progress;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        WebView webView = (WebView) findViewById(R.id.webView);
        webView.setInitialScale(0);
        webView.setWebViewClient(new WebViewClient());

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadsImagesAutomatically(true);

        webView.loadDataWithBaseURL("", new String(rowData.getResource().getData()), "text/html", "UTF-8", "about:blank");

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 0) {
                    showProgressDialog("Please Wait");
                }
                if (newProgress >= 100) {
                    hideProgressDialog();

                    // data load successfully. you can go further.
                }
            }
        });

    }

    public void showProgressDialog(final String msg) {

        runOnUiThread(new Runnable() {
            public void run() {
                if (progress == null || !progress.isShowing()) {
                    progress = ProgressDialog.show(URLActivity.this, "", msg);
                }
            }
        });
    }

    public void hideProgressDialog() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                try {
                    if (progress.isShowing())
                        progress.dismiss();
                } catch (Throwable e) {

                }
            }
        });
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handle two Queue in Background I am new in Iphone Development and i am working on Threading.
I have created two Queue like this:
dispatch_queue_t **Queue1** = dispatch_queue_create("Queue1", NULL);

dispatch_queue_t **Queue2** = dispatch_queue_create("Queue2", NULL);

I have added task in Queue1 like this:
dispatch_async(**Queue1**, ^{

[self HandleDownloadResponse];

});

dispatch_async(**Queue1**, ^{
    dispatch_async(dispatch_get_main_queue(), ^{

});

});

When I will get a response of my web service, Queue1 is executed and it is using Sqllite3 database.
When My data transfer from my device, Queue2 is executed and it is also used sqllite3.
My Issue is: When I got a web service response first before My data transfer start, I got a database lock error.
So i want to pause(sleep) my Queue1 when my Queue2 becomes active.How can i do this?

A: you can try this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // response from webservice
     dispatch_async(dispatch_get_main_queue(), ^{
     //insert into database

    }
    }


text:
Q: background-image on container element doesn't show all the sections of the container I am new to CSS and learning everyday. I am stuck at understanding something which could be trivial but I am not sure about the right term to research the problem.
So, I have a container  with class "background" inside which there are three sections with class "package" followed by the footer. The sections inside the container are tall enough needing the reader to scroll down to view them all:

Our PLUS Plan

The most popular choice of our customers.

Benefit from increased storage and faster support to ensure that your mission-critical data and applications
                    are always available!

Our FREE Plan

An extremely solid start into our hosting world.

Get started immediately at zero cost!

Our PREMIUM Plan

All your enterprise needs. Instant support, guaranteed uptime.

The best solution for small to large enterprises. Because hosting shouldn't be in the way!

     ....

It looks like:

I wanted a background image to cover the entire page so that it lays behind all the section till when the footer starts. I thought, I could target  and tried:


text:
Q: How to replace specific entries of a Numpy array based on its content So lets say I have a simple matrix made out of ndarrays (just an example of how  part of the data might look like):
import numpy as np
a = np.asarray([['1.0', 'Miami'],
   ['2.0', 'Boston'],
   ['1.4', 'Miami']])

I want to do data analisys in this complex data set ;) - I want to transform 'Miami' in 0 and Boston in 1 in order to use a really fancy ML algorithm. What is a good way to accomplish this in Python. (I am not asking for the obvious one of iterating and using a dictionary / if sentence to replace the entry) but more if there's a better way using Numpy or  native Python to do this.

A: pandas is a good tool for this.
First convert the array to a DataFrame:
In [11]: import pandas as pd

In [12]: df = pd.DataFrame(a, columns=['value', 'city'])

and then replace entries from the city column:
In [13]: df.city = df.city.replace({'Miami': 0, 'Boston': 1})

In [14]: df
Out[14]:
  value city
0   1.0    0
1   2.0    1
2   1.4    0


text:
Q: Droid base and iPhone cable for charging? I just got an iPhone 5c.  I had a Droid.  I have several Droid charging cables.  The Lightening charging cable I got with my iPhone detaches on the other end to a USB port.  The Droid charging "bases"/wall outlets have USB ports.  Can I recharge my iPhone 5 by plugging the Apple Lightning cable into a Droid base?

A: In most cases yes you can.
But if the charger is too weak (less than 1 amps), it will charge your iPhone more slowly than the original charger.


text:
Q: How can I improve CPU usage in Skyrim? My system specs are as follows:
CPU: AMD Phenom X4 - 2.4GHz
GPU: Nvidia GeForce GTX 550 Ti (ASUS, Fermi)
RAM: 8GB DDR2
OS: Windows 7 Ultimate, 64-bit
The issue I'm experiencing is that whenever I play Skyrim, after only a few minutes, regardless of my in-game location, my CPU usage skyrockets all the way to 100% and stays there. The fan, of course, also runs at 100% when this happens. When I press Escape and leave the menu open for about 5 seconds, the CPU calms down. It seems the graphic settings are not my issue, as I've lowered my resolution as well as setting the game's settings to 'Low', with no change. I've also uninstalled all of my mods, and unchecked the Dawnguard DLC in the Data Files menu. No change. I also tried uninstalling patches all the way back to 1.1, and still nothing.
What can I do to fix this issue? It's keeping me from playing the game, as I'm 1) annoyed at the noise of the CPU fan when this occurs, 2) concerned about overheating my CPU and causing it damage.

A: As Serge Bekenkamp already mentioned, the shadows in Skyrim are processed by the CPU, and not the GPU. This is a game engine limitation. Lowering Skyrim's shadow settings will help lessen CPU load.
Other tips that could help CPU performance:
Try cleaning dust out of your PC. See these Super User posts about that:

*

*Is it safe to get dust out of a PC with an air blower?

*Suck or blow? What's better for dust?
Also, try the HiAlgoBoost mod. It claims to improve FPS by lowering system resource usage when the player character is in motion. It should help lighten the load for your CPU when playing Skyrim.

HiAlgoBoost dynamically modifies internal rendering resolution in order to increase frame rate, and utilizes various additional approaches to make the game more responsive and smoothly controllable. It does not affect game contents.
HiAlgoBoost features:

*

*Significantly improves responsiveness and gameplay experience.

*Significantly reduces in-game loading times.

*Increases framerate during character motion by momentarily reducing the resolution.


text: Q: spring mvc rest service, view request and response xml I am trying to write a simple application using spring mvc as a restful webservice. How do i view the input xml/text received by the webservice and the output xml/text produced. Is it some settings in the logs?


text:
Q: How do you take an user input? How do you take an user input as integer or string?

A: You can do this as part of a Main method in your C# or Python driver code, or you could use the new support for Q# command-line executables called out in the recent release (0.11.2004.2825). If you follow the link for the quantum random number generator sample and scroll down, you'll see an example there for using @EntryPoint() to denote the Q# operation that should be used to generate the entry point code. It will also cause any arguments to that operation to automatically become command-line parameters for the built executable. You can try this in the sample by updating the code to take max as an argument, like this:
@EntryPoint()
operation SampleRandomNumber(max : Int) : Int {
    Message($"Sampling a random number between 0 and {max}: ");
    return SampleRandomNumberInRange(max);
}

Then when you run the sample via dotnet run you'll see that it now requires --max as a command line parameter, and handles the translation into the correct input type for the Q# operation. You can then pass the param like this to get the same behavior as the original sample: dotnet run --max 50
Hope that helps!


text:
Q: Read select list input from external source in Shiny app (pickerInput) I have a simple Shiny app (see below).
I need to read possible selection for  pickerInput widget from an external file (it updates frequently).
How can I do this?
The example below is obviously wrong but I have run out of all ideas.
Example & what I tried
library("shiny")
library("shinyWidgets")

# Actual data: my_choices <- c("2018Q1","2018Q2","2018Q3", "2018Q4", "2019Q1", "2019Q2")

ui <- fluidPage(

  pickerInput(
    inputId = "id",
    label = "SELECT PERIOD:",
    choices = openxlsx::read.xlsx(xlsxFile =
              "C:/Users/MyName/OneDrive/data.xlsx")$selection, # my_choices
    selected = NULL,
    multiple = TRUE,
    options = list(
      `actions-box` = TRUE, size = 15, `selected-text-format` = "count > 3"
    ),
    choicesOpt = list(
      content = stringr::str_trunc(my_choices, width = 75)
    )
  ),
  verbatimTextOutput(outputId = "res")
)

server <- function(input, output, session) {
  output$res <- renderPrint(input$id)
}

shinyApp(ui = ui, server = server)

A: Here might be one approach. You could use reactiveFileReader to periodically load the data file that is updated frequently (you can specify how often to poll). Then use updatePickerInput to update your input when the data changes.
I didn't have access to my_choices so I commented that out.
library("shiny")
library("shinyWidgets")
library("openxlsx")

# my_choices <- c("2018Q1","2018Q2","2018Q3", "2018Q4", "2019Q1", "2019Q2")

ui <- fluidPage(

  pickerInput(
    inputId = "id",
    label = "SELECT PERIOD:",
    choices = NULL,
    selected = NULL,
    multiple = TRUE,
    options = list(
      `actions-box` = TRUE, size = 15, `selected-text-format` = "count > 3"
    )#,
    #choicesOpt = list(
    #  content = stringr::str_trunc(my_choices, width = 75)
    #)
  ),
  verbatimTextOutput(outputId = "res")
)

server <- function(input, output, session) {

  fileData <- reactiveFileReader(1000,
                                 session,
                                 filePath = 'C:/Users/MyName/OneDrive/data.xlsx',
                                 readFunc = read.xlsx)

  output$res <- renderPrint(input$id)

  observe({
    updatePickerInput(session, "id", choices = fileData()$selection)
  })
}

shinyApp(ui = ui, server = server)

Edit
If you only need to load the file upon launching the app, you would not need the reactiveFileReader:
observe({
  updatePickerInput(session, "id", choices = openxlsx::read.xlsx(xlsxFile =
    "C:/Users/MyName/OneDrive/data.xlsx")$selection)
})

Alternatively, you can load the file into a dataframe outside of ui and reference the dataframe selection column in your pickerInput.


text:
Q: Is there any possibility to get datatable row value from xhtml to javabean class I have a data table like below
<p:dataTable style="height:600px; width: 100%;border: none;" var="timelineData" value="#{timelineBean.timelineActivities}"   paginator="true"  rows="10" resizableColumns="true" liveResize="true"
                                         paginatorPosition="bottom" paginatorTemplate="{FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
                                         scrollable="true"  rowsPerPageTemplate="10 20 30">

Is there any possibility to get row (rows = "10") value in my bean class.So i can use that value like offset and pass to DB


text:
Q: How to get the next working day, excluding weekends and holidays I have a requirement where I need to work on a date field, so the requirement is some thing like this
I will call the field as minimum possible date

*

*Add +1 to the date

*If the minimum possible date happens to fall on a weekend(Sat or Sun) after adding 1 day, Display the next working day i.e Monday

*If the minimum possible date happens to fall on a Holiday, display the next working day. (Holidays 1.1 , 1.5 , 3.10 , 25.12 , 26.12)

*If the minimum possible date happens to fall on a weekend(Sat or Sun) after adding 1 day, and the day after that is a holiday then show the next working day. Eg: After +1 day if min possible day is Saturday, we will have to display Monday. But if Monday happens to be a Holiday then we have to display Tuesday.
I have tried a solution to the above problem by having multiple if and else cases, but just wondering if there is any generic and graceful way of doing it?
I have tried
var holidays = new List<DateTime>();
holidays.Add(new DateTime(DateTime.Now.Year,1,1));
holidays.Add(new DateTime(DateTime.Now.Year,1,5));
holidays.Add(new DateTime(DateTime.Now.Year,3,10));
holidays.Add(new DateTime(DateTime.Now.Year,12,25));

if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
{
     //Logic to add +1 and again some logic to check for weekends and weekdays
}
else if (holidays.Contain(date))
{
   //Logic to add +1 and again some logic to check for weekends and weekdays
}

A: A fixed list of dates is a somewhat limited way to express holidays.
Consider that your list only contains dates for the current year, so if today is December 30th 2015, then the next holiday would be Jan 1, 2016 - which you wouldn't find in your list.
Also consider that many holidays do not fall on the same date every year.  Often they are tied to the day of the week, and sometimes they are determined by religious calendars, or arbitrarily.
A more robust system should handle a variety of different types of holidays.  Here's one possible implementation:
public abstract class Holiday
{
    public abstract DateTime? GetDate(int year);
}

public class MonthDayBasedHoliday : Holiday
{
    private readonly int _month;
    private readonly int _day;

    public MonthDayBasedHoliday(int month, int day)
    {
        _month = month;
        _day = day;
    }

    public override DateTime? GetDate(int year)
    {
        return new DateTime(year, _month, _day);
    }
}

public class DayOfWeekBasedHoliday : Holiday
{
    private readonly int _occurrence;
    private readonly DayOfWeek _dayOfWeek;
    private readonly int _month;

    public DayOfWeekBasedHoliday(int occurrence, DayOfWeek dayOfWeek, int month)
    {
        _occurrence = occurrence;
        _dayOfWeek = dayOfWeek;
        _month = month;
    }

    public override DateTime? GetDate(int year)
    {
        if (_occurrence <= 4)
        {
            DateTime dt = new DateTime(year, _month, 1);
            int delta = (_dayOfWeek - dt.DayOfWeek + 7) % 7;
            delta += 7 * (_occurrence - 1);
            return dt.AddDays(delta);
        }
        else  // last occurrence in month
        {
            int daysInMonth = DateTime.DaysInMonth(year, _month);
            DateTime dt = new DateTime(year, _month, daysInMonth);
            int delta = (dt.DayOfWeek - _dayOfWeek + 7) % 7;
            return dt.AddDays(-delta);
        }
    }
}

public class FixedDateBasedHoliday : Holiday
{
    private readonly IDictionary<int, DateTime> _dates;

    public FixedDateBasedHoliday(params DateTime[] dates)
    {
        _dates = dates.ToDictionary(x => x.Year, x => x);
    }

    public override DateTime? GetDate(int year)
    {
        if (_dates.ContainsKey(year))
            return _dates[year];

        // fixed date not established for year
        return null;
    }
}

With these defined, we can now define holidays much more robustly, such as:
var holidays = new List<Holiday>();

// New Year's Day
holidays.Add(new MonthDayBasedHoliday(1, 1));

// President's Day (US)
holidays.Add(new DayOfWeekBasedHoliday(3, DayOfWeek.Monday, 2));

// Easter (Western Observance)
holidays.Add(new FixedDateBasedHoliday(new DateTime(2015, 4, 5), new DateTime(2016, 3, 27)));

// Memorial Day (US)
holidays.Add(new DayOfWeekBasedHoliday(5, DayOfWeek.Monday, 5));

// Christmas Day
holidays.Add(new MonthDayBasedHoliday(12, 25));

And now, we can create a method that checks for the next working day, as you requested:
public static DateTime GetNextNonHolidayWeekDay(DateTime date, IList<Holiday> holidays, IList<DayOfWeek> weekendDays)
{
    // always start with tomorrow, and truncate time to be safe
    date = date.Date.AddDays(1);

    // calculate holidays for both this year and next year
    var holidayDates = holidays.Select(x => x.GetDate(date.Year))
        .Union(holidays.Select(x => x.GetDate(date.Year + 1)))
        .Where(x=> x != null)
        .Select(x=> x.Value)
        .OrderBy(x => x).ToArray();

    // increment until we get a non-weekend and non-holiday date
    while (true)
    {
        if (weekendDays.Contains(date.DayOfWeek) || holidayDates.Contains(date))
            date = date.AddDays(1);
        else
            return date;
    }
}

That method could go on the abstract Holiday class, or it could go anywhere really.
Example usage (with above definition for holidays):
var weekendDays = new[] { DayOfWeek.Saturday, DayOfWeek.Sunday };

DateTime workDay = GetNextNonHolidayWeekDay(new DateTime(2015, 12, 31), holidays, weekendDays);
// returns 2016-01-04

This is still not quite a complete solution though.  Many holidays have more complex calculation rules.  As an exercise left to the reader, try implementing a class that derives from Holiday for the second day in the US Thanksgiving holiday. The first day will always fall on the 4th Thursday in November, but the second day is always "the Friday following the 4th Thursday in November", rather than just "the 4th Friday in November" (see November 2019 for an example of where this matters).

A: Basically you want to get the next working day. So you could loop on this condition adding 1 day to the current date
do {
  date = date.AddDays(1);
} while(IsHoliday(date) || IsWeekend(date));

In the previous code IsHoliday is a predicate telling if a date is holiday. For instance, shamelessly reusing your code:
class Program
{
    private static readonly HashSet<DateTime> Holidays = new HashSet<DateTime>();

    private static bool IsHoliday(DateTime date)
    {
        return Holidays.Contains(date);
    }

    private static bool IsWeekend(DateTime date)
    {
        return date.DayOfWeek == DayOfWeek.Saturday
            || date.DayOfWeek == DayOfWeek.Sunday;
    }

    private static DateTime GetNextWorkingDay(DateTime date)
    {
        do
        {
            date = date.AddDays(1);
        } while (IsHoliday(date) || IsWeekend(date));
        return date;
    }

    static void Main(string[] args)
    {
        Holidays.Add(new DateTime(DateTime.Now.Year, 1, 1));
        Holidays.Add(new DateTime(DateTime.Now.Year, 1, 5));
        Holidays.Add(new DateTime(DateTime.Now.Year, 3, 10));
        Holidays.Add(new DateTime(DateTime.Now.Year, 12, 25));

        var dt = GetNextWorkingDay(DateTime.Parse(@"2015-10-31"));

        Console.WriteLine(dt);

        Console.ReadKey();
    }
}

A: Based on the answer from @fjardon, you can use my project Nager.Date It contains the public holidays and weekends for more than 100 countries.
nuget
PM> install-package Nager.Date

Code snippet
//usings
using Nager.Date;
using Nager.Date.Extensions;

//logic
var date = DateTime.Today; //Set start date
var countryCode = CountryCode.US; //Set country

do
{
    date = date.AddDays(1);
} while (DateSystem.IsPublicHoliday(date, countryCode) || date.IsWeekend(countryCode));

A: var Holidays = new List<DateTime>();
Holidays.Add(new DateTime(DateTime.Now.Year, 1, 1));
Holidays.Add(new DateTime(DateTime.Now.Year, 1, 5));
Holidays.Add(new DateTime(DateTime.Now.Year, 3, 10));
Holidays.Add(new DateTime(DateTime.Now.Year, 12, 25));

var exclude = new List<DayOfWeek> {DayOfWeek.Saturday, DayOfWeek.Sunday};

var targetDate = new DateTime(2015, 12, 24);

var myDate = Enumerable.Range(1, 30)
  .Select( i => targetDate.AddDays(i) )
  .First(a =>
  !( exclude.Contains( a.DayOfWeek ) ||
     Holidays.Contains(a)) );

A: I had similar requirement in my project , and i retrieved by using SQl Server.
If you can do in SQL server , we have very simple query which returns the next business day.
DECLARE @dt datetime='20150113'
SELECT DATEADD(dd,CASE WHEN DATEDIFF(dd,0,@dt)%7 > 3 THEN 7-DATEDIFF(dd,0,@dt)%7 ELSE 1 END,@dt)

Explanation :
    Always base date is '1900 jan 1 st ' As per DB
    19000101 --> Monday --> -- So result is THEN VALUE =1 day
    19000102 --> Tuesday -->  -- So result is THEN VALUE =1 day
    19000103 --> Wednesday --> -- So result is THEN VALUE =1 day
    19000104 --> Thursday -->  -- So result is THEN VALUE =1 day
    19000105 --> Friday -->  -- So result is  7-@number = 3 days
    19000106 --> Saturday --> -- So result is 7-@number =2 days
    19000107 --> Sunday -->  -- So result is 7-@number =1 day


text:
Q: How can I implement Deleting files to the Recycle bin rather than Permanently deleting? I have a server that continues to close the gap on our D: Storage. So, from time to time I go into the location and manually delete files to free some space "Yuck". I have created a simple Powershell script that allows me to configure which files specifically and the dates (this is important) that need to be removed. Unfortunately during my testing, I soon realized the files are permanently deleted and I would rather have them sent to the Trash bin.
Here is the code:
   Get-ChildItem -Recurse C:\Temp\TWLogTest\*.* | Where-Object {$_.CreationTime -gt (get-date "12-03- 2016 01:00AM") -and $_.
   CreationTime -lt (get-date "10-10-2019 14:00PM")} | Where-Object {$_.name -match "tomcat"} | Remove-Items

Any help, guidance or ideas with implementing a Delete into this specific script would be greatly appreciated. I have looked at Module-Recycle, but still not sure how to add it here.
Thanks,
Matt

A: Based on here:  How do I move a file to the Recycle Bin using PowerShell?
using assembly microsoft.visualbasic
using namespace microsoft.visualbasic

[FileIO.FileSystem]::DeleteFile('foo.txt', 'OnlyErrorDialogs', 'SendToRecycleBin')

Something like this should match your code.  That method only works on files.  When comparing dates, the 2nd argument will get cast to [datetime] anyway.
using assembly microsoft.visualbasic
using namespace microsoft.visualbasic

Dir -File -R C:\Temp\TWLogTest | Where {
  $_.CreationTime -gt '12/3/16 1AM' -and
  $_.CreationTime -lt '10/10/19 2PM' -and
  $_.name -match 'tomcat' } |
foreach { [FileIO.FileSystem]::DeleteFile($_.fullname, 'OnlyErrorDialogs',
  'SendToRecycleBin') }


text:
Q: Invalid Identifier programming error in snowflake I am running the following query in snowflake and it runs fine.
set id ='TEST_TABLE1';
set time_s = '2021-03-31 06:52:51+00:00';

merge into TEST_STATUS using (select column1 AS TABLENAME,
                              column2 AS LASTUPDATED from values ($id,$time_s)) tt
                              on TEST_STATUS.TABLE_NAME = tt.TABLENAME
                              when matched then update set TEST_STATUS.LAST_UPDATED = tt.LASTUPDATED
                              when not matched then insert (TABLE_NAME, LAST_UPDATED) values (tt.TABLENAME, tt.LASTUPDATED)

But when I try to run it via python code as following:

self.table = 'TEST_TABLE1'

self.timestamp='2021-03-31 06:52:51+00:00';

cmd = f"set id ={self.table};"
cmd2 = f"set time_s = str({timestamp});"

merge_cmd = f"merge into {self.table} using (select column1 AS TABLENAME, column2 AS LASTUPDATED from " \
f"values ($id,$time_s)) tt on {self.table}.TABLE_NAME = tt.TABLENAME when " \
f"matched then update set {self.status_tbl}.LAST_UPDATED = tt.LASTUPDATED when not matched then " \
f"insert (TABLE_NAME, LAST_UPDATED) values (tt.TABLENAME, tt.LASTUPDATED) "

self.snowflake_client.run(cmd)
self.snowflake_client.run(cmd2)
self.snowflake_client.run(merge_cmd)

I am getting exception as:
snowflake.connector.errors.ProgrammingError: 000904 (42000): SQL compilation error: error line 1 at position 14
invalid identifier 'TEST_TABLE1'

A: Can you add single quotation marks when assigning to variables?
self.table = 'TEST_TABLE1'

self.timestamp='2021-03-31 06:52:51+00:00'

cmd = f"set id = '{self.table}';"
cmd2 = f"set time_s = 'str({timestamp})';"

merge_cmd = f"merge into {self.table} using (select column1 AS TABLENAME, column2 AS LASTUPDATED from " \
f"values ('$id','$time_s')) tt on {self.table}.TABLE_NAME = tt.TABLENAME when " \
f"matched then update set {self.status_tbl}.LAST_UPDATED = tt.LASTUPDATED when not matched then " \
f"insert (TABLE_NAME, LAST_UPDATED) values (tt.TABLENAME, tt.LASTUPDATED) "

self.snowflake_client.run(cmd)
self.snowflake_client.run(cmd2)
self.snowflake_client.run(merge_cmd)


text:
Q: How does "Reference to an object" plays a role in Dynamic method dispatch in a case where a method in Parent class is Protected? I'm confused with the behavior of java run time polymorphism in conjunction with protected access modifier. I have a class named A in package Pack1 as follows:
package Pack1;
public class A{
    protected void m1(){
        System.out.println("A's implementation");
    }
}

and a child class named C in package Pack2 as follows:
package Pack2;
import Pack1.*;

class C extends A{
    public void m1(){
        System.out.println("C's implementation");
    }
    public static void main(String[] args){
        A a1 = new C();
        a1.m1();
    }
}

Now, if m1() was public in parent class it would not give any error calling m1() with parent's reference from within child class, but in this particular case where m1() is protected it gives error saying:

m1() has protected access in A.(after all being Protected, m1() should be accessible in class C)

Could someone kindly help me to grasp the logic involved here ?

A: By making the type of a1 A you can only access members of the A class, unless they are overridden in the child class as in:
class C extends A{
    @Override
    public void m1(){
        System.out.println("C's implementation");
    }

This would cause the m1 method in class C to be called when an instance of C is accessed as an A.
You can make the access modifiers equal to or less restrictive as the base. As shown in your example where it changes from protected to public.

A: The runtime system is following the restrictions you've given it, going with that it knows based on the type you're actually operating with. Polymorphism and access modifiers are really fairly separate. So if you have an 'A', and you're not in 'A''s package, then you can't call its 'm1' method. But, if you can cast an 'A' to a 'C', because it really is a 'C', then you can call the same 'm1' method after casting to a 'C', because 'C''s definition says that 'm1' is public.
Think about it the other way...if it mattered what the access level was of A.m1 when calling it through a C reference, then the JVM wouldn't be able to know if it could make that call or not because it can't know in general what is behind that C reference. It can only work with what instructions it has on C's versions of the method.
This is why you can't go the other way around. It can't be that C's m1 is private and yet A's m1 is public. That would let you call call C's m1 through a reference to an A, even though C doesn't want you to do that, since the JVM can't know better. So this has to be disallowed at compile time.


text:
Q: Is there a language for defining restful web services? I'm implementing a restful service automation tool for client applications. Basically, the tool takes a config file that defines restful resources, and creates some DTOs and resource classes for client to use. But I need a standard for this config file. WSDL seems well known, but it was intended to use with soap, and for me it seems clunky. I, on the other hand, could invent my own standard, but it reminds me of this situation:

So, maybe there is an existing nice standard that covers my use-case? Or should I implement my own?


text:
Q: Convert geojson polygons into points with node using query-overpass and turf.js I use the node module "query-overpass" for a query to get farmshops from openstreetmaps. I would like to convert all polygons to points inside this script. I use turf.js to get the centroids of theese polygons, but I am not able to change the objects in a permanent way. This is my code so far:
const query_overpass = require("query-overpass");
const turf = require ("turf");
const fs = require("fs")
let test
let filename = "data/test.js"
let bbox = "48.91821286473131,8.309097290039062,49.0610446187357,8.520584106445312";
console.log('starting query for ' +filename)
console.log('bbox: ' +bbox)
let query = `
  [out:json][timeout:250];
  // gather results
  (
  // query part for: "vending=milk"
  node["vending"="milk"](${bbox});
  way["vending"="milk"](${bbox});
  relation["vending"="milk"](${bbox});
  // query part for: "shop=farm"
  node["shop"="farm"](${bbox});
  way["shop"="farm"](${bbox});
  relation["shop"="farm"](${bbox});
  // query part for: "vending=food"
  node["vending"="food"](${bbox});
  way["vending"="food"](${bbox});
  relation["vending"="food"](${bbox});
  );
  // print results
  out body;
  >;
  out skel qt;
`;

// query overpass, write result to file
query_overpass(query, (error, data)  => {
    data = JSON.stringify(data , null, 1)
    console.log(data)
    test = JSON.parse(data)

//create centroids for every polyon and save them as a point
    for (var i = 0; i < test.features.length; i++) {
      console.log("Log: " +test.features[i].geometry.type)
      console.log("Log: " +test.features[i].properties.name)
      if (test.features[i].geometry.type === "Polygon"){
        console.log("polygon detected")
        var centroid = turf.centroid(test.features[i]);
            var lon = centroid.geometry.coordinates[0];
            var lat = centroid.geometry.coordinates[1];
            console.log(" lon: " +lon +" lat: " +lat)

            test.features[i].geometry.type = 'Point'
            //delete Polygon structure and insert centroids as new points here
            console.log("polygon deleted and changed to point")
      }

  }
  console.log(test)
   fs.writeFile(filename, `var file = ${test};` , ["utf-8"], (error, data) => {if (error) {console.log(error)}})
 }, {flatProperties: true}
)

It seems like I can change things inside of the for loop, but they do not appear when the data is saved later. It is basically a question of how to edit json objects properly, but I can't figure out why this doesnt work here at all.
So there are basically two questions:

*

*Why cant I override geometry.type in the example above?

*How can I delete the old polygon and add a new point to a feature?

Thanks for any help.

A: That's quite complicated... Why don't you let Overpass API do this job and use out center; instead of out body;>;out skel qt; to return the center points of all nodes, ways and relations. You can use overpass-turbo.eu to try this out first.


text:
Q: How to show errors in angularjs resource? I try to show a dialog error when the a web api fails. I am using bootbox for this purpose.
The code is:
OrderService.get(function(response) {
    $scope.newOrder = response;
}, function(error) {
    $bootbox.alert(error.statusText);
});

OrderService is a service:
app.factory('OrderService', [
   '$resource', function($resource) {
   return $resource('http://myweb/api/orders/neworder', {});
}]);

The first time that I open the web page, it works fine and the error message is displayed.
If I refresh the page, then the bootbox disable the entire screen and I cannot close the bootbox popup dialog.
If I replace   $bootbox.alert(error.statusText);  by  alert(error.statusText);, then everything works fine.

A: If you are using some module to implement bootbox, 'cos $bootbox must injected
If not then, you can simple use without $:
OrderService.get(function(response) {
    $scope.newOrder = response;
}, function(error) {
    bootbox.alert(error.statusText);
});

from bootboxjs page:

Once you've got your dependencies sorted, usage is fairly
  straightforward and much like any other JavaScript library you've ever
  used. The library creates a single global instance of a bootbox object


text:
Q: How to use multiple database connections in the same \DB::statement() I'm trying to build a Laravel console command to copy the table schema from a remote database and create the table in my local database. Effectively, just to copy and paste the table.
I have multiple database connections set up already in config/database.php and I use this in other parts of the projects, e.g. for model connections etc. That side of it is all fine.
I know I can do \DB::connection('connection_name') to specify the connection for that query, but I need to work across two connections at the same time.
I've tried putting this in in various places in the code, but I haven't been able to make it work.
Below is the function that gets called. First we drop the local table, then recreate it with the schema from the remote database. That's the bit I'm stuck on - how to get the query to look at the remote table.
public function handle()
{
    $this->table = $this->argument('table');

     //drop the local table first
        \DB::statement('DROP TABLE IF EXISTS ' . $this->table . ';');

        \DB::statement('CREATE TABLE ' . $this->table . ' LIKE        ??remote_db_connection??.'. $this->table . ';');
}

A: You can do this like this way, using connection method , you have to manually declare the connection if different from default,
DB::connection('pgsql')->statement('your statement here...');

A: Thanks to ceejayoz pointing me in the right direction - here is what i have which now works, although i sure this can be improved:
public function handle()
{
    $this->table = $this->argument('table');

    \DB::statement('DROP TABLE IF EXISTS ' . $this->table . ';');

    $stmt = \DB::connection('remote')->select('SHOW CREATE TABLE ' . $this->table);

    $stmt = ((array) $stmt[0]);

    \DB::statement($stmt['Create Table']);

}


text:
Q: How to display/control breadcrumbs of a VSCode virtual document? I'm working on an extension that registers a TextDocumentContentProvider to provide a read-only viewer for certain Azure resources in JSON format. When I display the JSON for these resources, I'd like the editor to show the JSON breadcrumbs. For some reason, when displaying the content via my virtual document URL, the breadcrumbs don't get displayed. The editor displays breadcrumbs fine when the same document content is pulled using file:// scheme.
Does anyone know how to set up breadcrumb support for a virtual document?

A: Breadcrumbs use the info returned from the DocumentSymbolProvider. Implement an own symbol provider that returns the info you wish and register it as described on the VS Code API page.
The document provider itself is pretty simple.
export class MySymbolProvider implements DocumentSymbolProvider {
    constructor() {}

    provideDocumentSymbols(document: TextDocument, token: CancellationToken): ProviderResult<SymbolInformation[]> {
        var symbols = ... // get your symbols from somewhere

        var symbolsList = [];
        for (let symbol of symbols) {
            // Construct location information here (for go-to feature).
            let startRow = ...;
            let endRow = ...;
            let startColumn = ...;
            let endColumn = ...;
            let range = new Range(startRow, startColumn, endRow, endColumn);
            let location = new Location(Uri.file(symbol.source), range);
            var description = ...;
            const kind = translateSymbolKind(symbol.kind);
            let info = new SymbolInformation(symbol.name, kind, description, location);
            symbolsList.push(info);
        }

        return symbolsList;
    };
};

A: Seems like this is currently not possible as the only file schemes that support breadcrumbs are file and untitled according to this comment.


text:
Q: How can I build a CSV file from a GridView in Visual Basic? I have a report I'm generating in VB.Net that is being displayed in a GridView. The data is pulled from SQL based on some constraints the user enters and can be any size, depending on these. I would like to be able to take these values from the grid and put them into a CSV for a downloadable report without rerunning my SQL select (I know how to build one that way), preferably in a generic fashion so this can be easily reused.
Here's what I have currently. It makes a CSV, but only the headers are present.
Protected Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
    Dim strOutput As New StringBuilder

    Response.ContentType = "application/csv"
    ' Remove the charset from the Content-Type header.
    Response.Charset = ""
    ' Turn off the view state.
    Me.EnableViewState = False
    Response.AddHeader("Content-Disposition", "filename=report.csv;")

    strOutput.AppendLine(GetCSVLine(grid.HeaderRow.Cells))
    For Each row As GridViewRow In grid.Rows
        strOutput.AppendLine(GetCSVLine(row.Cells))
    Next

    Response.Write(strOutput)

    Response.Flush()

    Response.End()
End Sub

Private Function GetCSVLine(cells As TableCellCollection) As String
    Dim returnValue As String = ""

    For Each cell As TableCell In cells
        returnValue += cell.Text + ","
    Next

    Return returnValue
End Function

And the aspx page
    <asp:GridView ID="grid" runat="server" EnableModelValidation="True" AutoGenerateColumns = "false">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'/>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Location">
                            <ItemTemplate>
                                <asp:Label ID="lblLocation" runat="server" Text='<%# Bind("Location")%>'/>
                            </ItemTemplate>
                        </asp:TemplateField>
<!-- There are a few more fields after this, using the same structure -->

A: Sorry, running off the top of my head here but I think that because each row contains a set of Label controls which have the text inside of them, you can't use a straight cell.Text against the table cells to get the contents out.
What you may have to do is use the FindControl method against each row to get the relevant control out and then access the properties of each control that you retrieve to get the data which you need to push out in the CSV. Something like:
For Each row As GridViewRow In grid.Rows
    'In each row, find the control which contains the data and then get the text of the control
    Dim nameLabel As Label = CType(row.FindControl("lblName"), Label)
    Dim nameValue As String = nameLabel.Text

    'Once you have all the values, write out the StringBuilder like you are doing already
Next


text:
Q: locking an element at the center of the screen for y amount of scroll I want to create a scroll animation on my webpage.
And my plan is to have the user scroll down the page and a word coming into view from the bottom of the page. (basically just a decently sized margin-top)
The issue is that I don't want the user to be able to "just" scroll past this word.
I want the word to "stop" moving together with the scroll for a certain scroll distance when the word hits the center of the screen.
I can probably code some js to get this effect by checking the scroll position and changing the top value of some element. But I am afraid of it stuttering, so is it possible to do something like this in pure css, or if not: is there any way of doing it in js and making sure that it is smooth?


text:
Q: Monitoring application usage of a computer with many users? I have a server running Windows in a domain which is accessed by many users and acts as a PC. It has more than 10 sessions at the same time.
I'm hoping to figure out what applications are most used by the users, and get rid of some we rarely use.
Are you familiar with a way to gather application usage information of all the users connected?

A: I would recommend configuring Windows 7 Parential controls - This can be setup to log what is being used on the machine.
http://www.techtalkz.com/windows-7/516005-how-configure-parental-controls-windows-7-a.html
There are packages for Windows XP as well - but you have not defined what OS version you are using.


text:
Q: Model Theory Question for Predicate Logic in van Dalen's Logic and Structure Let L be a language without identity and with at least one constant.
Let  σ = ∃x1 ··· xnϕ(x1,...,xn), where σ is a formula in predicate logic.
Let Σ = {ϕ(t1,...,tn)|tᵢ closed in L}, where ϕ
is quantifier free.
I want to show that:
(i) ⊨ σ ⇔ each structure A is a model of at least one sentence in Σ. (Hint: for each
A, look at the substructure generated by ∅.)
(ii) Consider Σ as a set of propositions. Show that for each valuation
v (in the sense of propositional logic) there is a model A such that
v(ϕ(t1,...,tn)) = the interpretation of ϕ(t1,...,tn) in A, for all ϕ(t1,...tn) ∈ Σ.
This question is pg.134 #16 of Logic and Structure by Van Dalen.
My attempt to answer:
For (i), I know that ⊨ σ iff every structure A is a model of ϕ(t1,...,tn) for some t1,...,tn in A's domain. But how do I show that this means each structure A is a model of at least one sentence in Σ? I followed the hint and constructed the substructure generated by ∅, which is just a structure with its domain consisting of the constants of A and terms involving the constants (definition of substructure generated by a set in this linked image). This substructure satisfy σ. I also know that ϕ(t1,...,tn) is true independent of what t1,...,tn are. I don't know how these facts relate to L and how to continue from here.
For (ii), I'm thinking ϕ implies ϕ, so it is consistent and has a model but I feel this is wrong and I'm not sure where to correctly begin.
Help is appreciated.

A: (i) Given a model $A$, the substructure $A^0$ generated by $\emptyset$ is the set of (the $A$-interpretations of) all terms that only involve constant symbols (these are the 'closed terms' occuring in the definition of $\Sigma$).
For example, if the language contains $1$ as a constant symbol and $+$ as a binary operation symbol, then $((1+1)+1)+(1+1)$ is a closed term. In the usual model on $\Bbb N$, this term is interpreted as $5\in\Bbb N$.
By hypothesis, $A^0$ satisfies $\sigma$, so there are elements $t_i'\in A^0$ such that $\varphi(t_1',\dots,t_n')$ is true.
But the elements of $A^0$ all belong to some closed terms, i.e. there are closed terms $t_i$ that are interpreted exactly as $t_i'$. Note that the interpretation of constants and operations on $A^0$ is inherited from $A$, hence
$$A\models\varphi(t_1,\dots,t_n)\,.$$

(ii) Here we introduce a propositional variable $P_\sigma$ for each $\sigma\in\Sigma$.
Let's assume that a valuation $v:\{P_\sigma:\sigma\in\Sigma\}\to\{\top,\bot\}$ is given.
We need a first order model $A$ such that $A\models\sigma\iff v(P_\sigma)=\top$.
The trick is that we can naturally define the constants and operations on the syntactic set $C$ of closed terms.
We still need to interpret the relation symbols on $C$ to obtain a model.
Since the language contains no $=$ sign, its quantifier-free formulas are built up by the relation symbols of the language and Boolean connectives.
One typically proceeds by formula induction on $\varphi$.
If $\varphi=R(t_1,\dots,t_n)$ with $t_i\in C$ and $R$ an $n$-ary relation symbol, then we can simply interpret $R$ in $C$ according to the given valuation $v$.
Can you continue with the Boolean connectives part of the formula induction?


text:
Q: Detalles de productos con javaScript pregunta: estoy intentando avanzar con mi e-commerce y lo estoy realizando con javaScript, hice la generación automática de mis productos mediante el uso del dom, los datos son tomados mediante un Json y genera todos los productos, lo que estoy intentando ahora es que al tocar en un botón de uno de los productos en particular tome su id y genere los datos completos del producto en otro html el cual seria para la descripción de productos, que también se generaría con el uso del dom, intente realizando varios códigos y ninguno me funciono, además me surge la duda de si en caso de conseguirlo, que pasaría si el cliente toca para ver la descripción de otro producto también, ya que la descripción se generaría en un solo html por ende se generarían dos? no encuentro realmente la forma correcta de realizar esto si me pueden guiar y ayudar lo agradecería! muchas gracias
el código hasta el momento es este
// lleno mi html con los objetos de forma dinamica

function Products(data) {
    //llena todo lo de la lista
        var dataProduct = data[0].dataProduct
    this.dataProduct = [];

    this.init = function(dataProduct) {
        this.dataProduct = dataProduct;
    }

    this.getById = function(id) {
        return this.dataProduct.filter(product => product.id === id);
    }

    this.buildHtmlProduct = function(product) {

        return `

${product.name}

$${product.price}

                                Ver Detalle
                                Comprar!

            `
    }

    this.buildList = function(containerId, sourceProduct) {
        var container = document.getElementById(containerId);
        container.innerHTML = "";
        var html = '';

        this[sourceProduct].forEach((product) => {
            html += this.buildHtmlProduct(product);
        });

        container.innerHTML = html;
    }
}

y el Json esta tal que asi:

    [
    {
        "dataProduct":
        [
            {
                "id" : 1,
                "cat": "mates",
                "name" : "Mate 1",
                "img" : "img/EquipoMateroNegroT.png",
                "price" : 999,
                "cantidad": 1,
                "descripcion": "verde"
            },
            {
                "cat": "mates",
                "name" : "Mate 2",
                "id" : 2,
                "img" : "img/EquipoMateroNegroT.png",
                "price" : 1995,
                "cantidad": 1,
                "descripcion": "verde"
            },
            {
                "cat": "mates",
                "name" : "Mate 3",
                "id" : 3,
                "img" : "img/EquipoMateroNegroT.png",
                "price" : 2999,
                "cantidad": 1,
                "descripcion": "verde"
            }
        ]
    }
]


text:
Q: How to zoom out in DOTA2, spectator and SFX animator tool I was working on a new short film project, and I was wondering if there is any way of capturing video of the whole DOTA map, then slowly zooming in to a lane?
This would be in spectator/replay mode. I want to be able to zoom out completely for a bird's eye view of the whole playing arena.
I tried using dota_camera_distance 5000 but that "wraps the map in clouds" and I can't see any aspect of the map.
Additionally, is there a way of hiding the top bar with hero icons, and the HUD?

A: For hiding the bars I remember that I could use the following commands:
dota_hud_hide_topbar
dota_hud_hide_mainhud
dota_hud_hide_minimap

For removing any unnecessary graphic, you can override vpk and create the files you want to override. More info on how you can do that can be found here.
I have tried this a while back when trying to optimize the fps and it worked. I'm not sure now.
Good luck with your movie!

A: I am not sure if it's possible to do that within DOTA
but if dota_camera_distance 5000 does

wraps the map in clouds

which is the fog of war, then you can try disabling it. Try these commands
 allvision
 normalvision -allvision
 normalvision dota_allvision_enable
 dota_allvision_disable Gives vision for both teams. Use -normalvision to undo this change.

On the other side, the approach I have seen done to achieve this effect is with SFM (Source film maker)
which I recommend you use to make your movie
Yes, you kinda have to learn something new, but you get more artistic control and better graphic results


text:
Q: React.js : How to fix Syntax error : unexpected token < in React.js React.js -> Syntax error : Unexpected token and I can't seem to find a solution, all my (.babelrc)presets , webpack.config and package.json seems to be right.
I have been stuck on this from past 1 week and i am not able to find a problem please help I am a beginner
here is my webpack.config.js , package.json and .babelrc respectively
webpack.config.js :- i have checked this out , I cant really seem to find a problem in it , do i have to create more loaders or something please help i am a beginner
const WEBPACK = require('webpack');
const PATH = require('path');

module.exports = {
mode: "none",
resolve: {
    extensions: ['.js', '.jsx']
},
context: __dirname,
entry: {
    app: ['./src/index.jsx'],
},
output : {
    path: PATH.join(__dirname, '/MY_FOLDER_OUTPUT'),
    filename: 'bundle.js'
},
module: {
    rules: [
        {
            test: /\.jsx$/,
            exclude: /node_modules/,
            loader: "babel-loader",
        }
    ]
},

};

package.json
{
  "name": "newReact",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "babel": "babel",
    "webpack": "webpack",
    "build": "webpack-dev-server --mode development --open",
    "prod_build": "webpack --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/preset-react": "^7.0.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.0.15",
    "copy-webpack-plugin": "^4.6.0",
    "es6-promise": "^4.2.5",
    "extract-text-webpack-plugin": "^3.0.2",
    "html-webpack-plugin": "^3.2.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "@babel/preset-stage-0": "^7.0.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.5",
    "babel-preset-es2015": "^6.24.1",
    "webpack": "^4.29.0",
    "webpack-cli": "^3.2.1"
  }
}

babelrc
{
    "presets": ["es2015","react"],
   "plugins": ["transform-react-jsx"]
}

this is index.jsx
import React from "react"
import ReactDOM from "react-dom"

ReactDOM.render(
      <h1>
        Hello World
      </h1>,
      document.getElementById('app')
);


text:
Q: If an Object allocates dynamic memory from the heap, is it automatically de-allocated when the object is out of scope or do I need a destructor? Being a noob to OOP and dynamic allocation, I am not sure if I am framing the question correctly. Anyway, here is the code. Note the constructor and destructor.
class Queue
{
    int *array;
    unsigned int siz;//Indicates how many elements are there right now
    public:
    void push(int);
    void clear();
    void print() const;
    Queue(unsigned int len):array(new int[len]), siz(0) {} /*Constructor
    indicating the maximum length*/
    ~Queue(){delete[] array;}   //Destructor to free the memory
    };
/*End of class definition */
    void somefunction()
    {
        Queue sample(10);  //Allocates memory from heap
        .........
    }
}

The Queue class contains an array and an unsigned integer indicating how many elements are there. The constructor takes an integer argument (indicating the maximum number of elements) and allocates space in the memory. The code works for my purpose whether I write the destructor or not, but I want to understand a bit of what is going on behind the scene when somefunction creates a queue.
sample itself is a local object, but it takes memory from the heap. So when sample goes out of scope at the end of somefunctionwhat happens to the allocated memory if I

*

*write the destructor

*do not write the destructor

Do I need to write the destructor to avoid a memory leak? Also, if I do write it, does it get called automatically or do I need to somehow call it to ensure the memory is not leaked?
Also, what would be the role of the destructor if the class contained, for example, int array[10]; instead of int *array? Could I just skip writing it then?

A:
Do I need to write the destructor to avoid a memory leak?

Dynamic allocation uses Heap memory and it is not freed unless you have a destructor that clears that memory. So Yes, you do need to write a destructor when you use heap memory.

if I do write it, does it get called automatically or do I need to
  somehow call it to ensure the memory is not leaked?

Destructor is automatically called when the object goes out of the scope.

what happens to the allocated memory if I write the destructor

When you have a destructor in your code, the dynamically allocated memory is cleared and made available to the operating system as soon as the object goes out of the scope.

what happens to the allocated memory if I do not write the destructor

When you don't have a destructor in your code, the dynamically allocated memory is not cleared and is not available to the operating system until you close the program.

A: Look out, we have a leak!  For every new, a program needs a delete.  Good work on knowing to use the array delete!
The short course answer is that classes are assigned a default destructor if you do not take action.  The compiler just slip one in there on you when you are looking the other way.  The same is true for constructors and copy assignment operators ... and with C++11 this is also true for move assignment operators too.  In this case, the default destructor does not deallocate the array and so there is a leak ... bad news, right?!
This type of code is largely obsolete but you are asking exactly the right questions to dig deep and learn more!  Good for you and keep working at it.  There are reams of excellent reference material on the subject and if you want to learn the depths of C++ you should definitely get your hands on a copy of any and all of Scott Meyers' Effective C++ series.  These books cover loads of territory but definitely cover default constructors/destructor, delete vs array delete, and I'm guessing that Effective C++11 covers the reference counting techniques in std::unique_ptr and std::shared_ptr.


text:
Q: How can i send messages or files to discord without client triggers? i want the send files to my discord channel.
But i want the send this file depend of some conditions and this conditions is not related with discord messages.
def run_discord_bot():
    TOKEN = '111111111111111111111'
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)

    @client.event
    async def on_ready():
        print(f'{client.user} is now running!')

    @client.event
    async def on_message(message):

        if message.author == client.user:
            return

        await send_message(message, user_message)

    client.run(TOKEN)

on_message and on_ready methods are trigged with discord client.
I don't want the trigger function with channel messages or any client event.
Can i create a function here and can i trigger this function from another script ?
Just like an API.
I tried something like this:
import discord

intents = discord.Intents.default()
client = discord.Client(intents=intents)

client.login(TOKEN)

channel = client.get_channel(1111111111111)

channel.send('Hello Discord!')

but its returning error
RuntimeWarning: coroutine 'Client.login' was never awaited
  client.login(TOKEN)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

A: The easiest way would be to filter your on_message with for example a user id.
If you don't want to do that you could theoretically have a flask api and a discord bot run from the same script like this:
def flask_loop():
    app.run(port=26389, host="0.0.0.0")

if __name__ == "__main__":
    t2 = threading.Thread(target=flask_loop)
    t2.start()
    bot.run(DCB_TOKEN)

This would allow you to call discord commands from an api endpoint.


text:
Q: Angular 12 upgrade: [Violation] 'load' handler took 238ms I have upgraded the version of the angular application to version 12 using the below.
npx @angular/cli@12 update @angular/core@12 @angular/cli@12
npx @angular/cli@12 update @angular/material@12
ng update

I am using leaflet 1.7.1 for interactive maps.
But while running the application I am getting below warnings in the console and my leaflet map is loading properly but not clickable(zoom in/out, pop up) until I resize the window. These warnings were not there before the upgrade. This is a very weird issue and I am not getting the exact reason behind the map issue.
[Violation] 'load' handler took 248ms zone.js:1607
[Violation] 'load' handler took 423ms zone.js:2536
[Violation] 'requestAnimationFrame' handler took 559ms
[Violation] Forced reflow while executing JavaScript took 43ms zone.js:2536
[Violation] 'requestAnimationFrame' handler took 56ms


text:
Q: Extracting data from sublinks I am kinda new to Python and im trying to extract information from a webpage (http://findanrd.eatright.org/listing/search?zipCode=page=1).
It works to get all the links from "information page", but I fail to extract those information.

26850 Providence Parkway, Suite 425

Novi, MI 48374

Email: info@aartibatavia.com

Website:
www.aartibatavia.com/

I want to extract the above information, like the street, the email address and the webpage. My code looks like this:
import requests
from bs4 import BeautifulSoup

def nutrispider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://findanrd.eatright.org/listing/search?zipCode=&page=' + str(page)
        source_code = requests.get(url)
        text = source_code.text
        soup = BeautifulSoup(text)
        x = 0
        while x<=19:
            rows = soup.findAll('tr', {'data-index':x})
            for row in rows:
                link_elm = row.find('div', {'class':'search-address-list-address'}).a
                link = 'http://findanrd.eatright.org' + link_elm['href']

                users = soup.findAll('div', {'class': 'user-info-box clearfix'})
                for user in users:
                    information = user.find('dd')
                    text = information.get_Text()
                    print(text)
                print(link)
            x += 1
        page += 1

nutrispider(1)

At the moment there is no error, but it just prints the links to the subpages where the information sit.

A: import requests, bs4

url = 'http://findanrd.eatright.org/listing/search?zipCode=page=1'
r = requests.get(url)
soup = bs4.BeautifulSoup(r.text, 'lxml')

for tr in soup.table('tr'):
    address = tr.find(class_='search-address-list-address').get_text(strip=True).strip('View details')
    name = tr.find(class_='search-address-list-name').get_text(strip=True)
    link = tr.p.a['href']
    print(name, address, link)

out:
Aarti Batavia, MS  RD  IFMCP 26850 Providence Parkway, Suite 425Novi, MI 48374 http://maps.google.com/maps?saddr=&daddr=26850 Providence Parkway, Suite 425 Novi, MI 48374
Aarti Batavia, MS  RD  IFMCP 26850 Providence Parkway, Suite 425Novi, MI 48374 http://maps.google.com/maps?saddr=&daddr=26850 Providence Parkway, Suite 425 Novi, MI 48374
Abbey Carlson, RD 3935 N 75 WHyde Park, UT 84318 http://maps.google.com/maps?saddr=&daddr=3935 N 75 W Hyde Park, UT 84318
Abbi Kifer, MED  RDN  LD PO Box 120Mount Storm, WV 26739 http://maps.google.com/maps?saddr=&daddr=PO Box 120 Mount Storm, WV 26739
Abbie Scott, RD  LD Hy-Vee, Inc.3221 SE 14th StreetDes Moines, IA 50320 http://maps.google.com/maps?saddr=&daddr=3221 SE 14th Street Des Moines, IA 50320


text:
Q: Api routes of next js working in local server but not in production I'm trying to create a comment section for my web.
Every thing is working fine in local server
but in production, when I submit give me this error
Error
After reload
Api in next js:
    export default async function CreateComment(req, res){

        const { name, comment, _id } = JSON.parse(req.body)
        await client.config({
            token: process.env.SANITY_AUTH_TOKEN
        }).create({
            _type: "comment",
            name,
            comment,
            blog:{
                _type: "reference",
                _ref: _id
            },
        })
        return res.status(200)
    }

Form from which I submit the data:
    const notify = () => {
        setTimeout(() => {
            location.reload()
        }, 3000);
    }
    function Form({ _id }) {
        const {
            register,
            handleSubmit,
            formState: { errors },
        } = useForm();
        const onSubmit = async (data) => {
                    fetch('/api/CreateComment', {
                    method: "POST",
                    body: JSON.stringify({ ...data, _id })
                })
                console.log(data)
            }
        return (<>
        <form id='my-form' onSubmit={handleSubmit(onSubmit)}>

                    <input {...register('name', { required: true })} type="text" id="name" minLength={3} />
                    {errors.name}

                        Your comment
                        <textarea {...register('comment', { required: true })} id="comment" rows="4" minLength={5}></textarea>
                        {errors.comment}

                        <button onClick={notify} type="submit">
                            Post comment
                        </button>

            </form>
        </>
        );

I'm getting the _id from my slug.js
Edit:
In local server if i go to my api route i get this error

But still it works in local server


text:
Q: Erro Requisição Ajax e versões jQuery Estou com um problema para entender e resolver um problema com uma requisição Ajax que preciso fazer. Segue abaixo uma lista de sequência do assunto que irei dizer:

*

*Explicar o que eu preciso;

*Explicar o que quero fazer;

*Mostrar como está atualmente;

*Apresentar as soluções que já tentei;

Primeiro:
Estou desenvolvendo um site de viagens, onde este site possui uma navbar, nesta navbar há um menu chamado 'Informações'.
Acontece que tenho uma plataforma/sistema que o usuário acessa e cria um artigo que é inserido como um item do Menu Dropdown toda vez que ele cria um artigo novo (o menu possui um while).
O que eu preciso e quero fazer é: toda vez  que o visitante clicar em um desses itens/menus do Menu Drop, ele abra um modal do Bootstrap com a informação do artigo feito pelo cliente.
Certo?
Essa é a ideia.
Bom, o que eu preciso é apenas pegar do banco de dados essa informação (o que já fiz) e apresenta-lo em uma página .php (o que também já fiz, chame-se response.php). Essa página apenas exibe o texto escrito pelo usuário sem estilo nenhum (feito já no modal ou na hora da criação do artigo). O que me resta fazer é chamar essa página via Javascript com o jQuery e Ajax (que é o que eu quero fazer). No entanto esse é o meu problema e eu não sei ao certo onde preciso ver. Segue abaixo
Ponto de Problema:
1º: a versão do jQuery utilizada é 2.1.4 (outro dev trabalhou antes e ficou com esse), e eu testei usar uma versão mais atual. O resultado foi que funcionou a requisição só que outros plugins que usam jQuery pararam de funcionar ou não eram reconhecidos.
2º: Há 2 tipos de links para o site: 1 é com o domínio proprio aqui (www.dominioproprio.com/). Quando é assim, a requisição aparece normalmente, no entanto quando acesso o site real do cliente (www.sitedocliente.com.br), a requisição quando é feita, ela trava e não vai para o Success.
3º: Quando tento usar o link manualmente da requisição:
www.sitedocliente.com.br/response?page_id=123
o resultado é:

The requested URL /response was not found on this server.

Isso já está me tirando do serio e já comparei com outras utilizações de ajax minha e está ok.
Segue abaixo algumas informações da requisição no JS:
$("[data-page-id]").click(function(){
let page_id=$(this).attr("data-page-id");
let response=$(".response-content");
response.html("
");
setTimeout(function(){
    $.ajax({
        url:link+"/response?page_id="+page_id,
        type:'GET',
        success:function(data){
        $(response).html(data);
        }
    });
},200);
});

E agora temos também como está no  HTML a exibição desse atributo data-page-id:
Eu coloquei de forma bem rudimentar porque não estou com acesso ao server mas reescrevi para entenderem:

        <?php
            while($pagina = $paginas->fetch_object()){

                    <a href="#" data-toggle="modal" data-target="#modal_response" data-page-id="<?= $pagina->id ?>">

            }
        ?>

Esta variável $pagina recebe os resultados da tabela PAGINAS que contém os artigos escritos pelo cliente (artigo soa forte, é mais uma mensagem num modal ^^ ).
Além disso, $pagina->id está no data-page-id pois essa será a referencia de cada LI criada.
Infos:
link é uma variável javascript que está recebendo  o site atual;
Essa é o código da pagina response que apresenta o artigo no modal
<?php
    $_GET = $db->Escapar($_GET);

    if(!isset($_GET['page_id']))
        die("ID não encontrado");

    $page_id = $_GET['page_id'];

    $pagina = $db->Executar("SELECT * FROM paginas WHERE adm_id=$adm_id AND id=$page_id");

    if($pagina->num_rows == 0) die("ID não encontrado");
        $pagina = $pagina->fetch_object();

?>

<?=$pagina->pagina; ?>

Essas informações são suficientes? Me digam o que acham e como posso corrigir.
Grato!
EDIT 1: Antes que me perguntem ou não haha... O URI /response?page_id=01 nao tem o .php por causa dessa gracinha aqui:
if($url[0] == "response") {
    include "response.php";
    exit();
}

EDIT 2: Agora que já informei o suficiente para entender o funcionamento e que ao meu ver está correto, preciso saber porque a requisição não consegue acessar a partir do site do cliente, apenas do meu servidor, sendo que está tudo igual e carregado lá?


text:
Q: ionic add ngCordova not working
I have tried both command to install ionic-platform-web-client but i am not able to install it, it gives me an error kindly refer attached image for same
commands:
ionic add ionic-platform-web-client

and
bower install ionic-platform-web-client

I wanted to install following plugins.
ionic add ngCordova
ionic add ionic-service-core
ionic add ionic-service-push
ionic add angular-websocket

A: Download ngCordova File from here and Include ng-cordova.js or ng-cordova.min.js in your index.html file before cordova.js and after your AngularJS / Ionic file
Then, include ngCordova as a dependency in your angular module
angular.module('myApp', ['ngCordova'])

A: You can try this
bower install ngCordova --save
bower install ionic-service-core --save
bower install ionic-service-push --save
bower install angular-websocket --save


text:
Q: Arcgis javascript TOC with secure services I have secured map services with AGS. I also have the proxy.config, proxy.ashx, and web.config in my application. My map layers display OK using the proxy. When I try to display my legend using the proxy map layers, a login dialog shows up and the legend does not display. If I enter my username and password the legend displays. When I use unsecured services from an AGS server the legend displays fine.
Has anyone experienced this?

A: Looks like the problem is with you proxy, check if it is getting the legend request. If not, you could configure the proxy url in esriConfig properties to always use proxy.
 esriConfig.defaults.io.proxyUrl = "<url_to_proxy>"
 esriConfig.defaults.io.alwaysUseProxy = true;

Hope this helps