text:
Q: why doesn't MPMoviePlayerController play in simulator but not in device if the format is valid for the device? Yes, I research what is going on but in my case I am sure the format of the audio is valid because it is m4a file from itunes store preview, which my 4s device plays without any problem.
any tips are appreciated
-(IBAction)StartMusic
{
    NSLog(@"start");

    NSURL *songUrl = [NSURL URLWithString:@"http://a1804.phobos.apple.com/us/r1000/064/Music/v4/9b/b3/c7/9bb3c7dc-a06f-f18c-3e41-2ce1e36f73b4/mzaf_7432104896053262141.aac.m4a"];

    MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] initWithContentURL:songUrl];

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(moviePlayBackDidFinish:)

                                                 name:MPMoviePlayerPlaybackDidFinishNotification

                                               object:nil];

    [mp setControlStyle:MPMovieControlStyleFullscreen];
    [mp setMovieSourceType:MPMovieSourceTypeStreaming];

    [mp setFullscreen:YES];
    [mp.view setFrame: self.view.bounds];

    [self.view addSubview:[mp view]];

    [mp prepareToPlay];
    [mp play];

    NSLog(@"start 2");
}

A: Solved!
I am forcing it playing even if the mute is on,
moviePlayer.useApplicationAudioSession = NO;
[self presentMoviePlayerViewControllerAnimated:moviePlayer];

that's what itunes store does if the mute is on for the preview songs when you tap it


text:
Q: MySQL: select diverse statistics I have a following setup:
-------------------------
| reference |   t_stamp |
-------------------------
|         1 | 2016-07-08|
|         1 | 2016-06-10|
|         1 | 2016-06-01|
|         2 | 2016-05-23|
-------------------------

I need to select unique reference rows with 1) the overall count by reference and 2) a separate count of last month from t_stamp.
The result should be:
------------------------------------
| reference | overall | last_month |
------------------------------------
|         1 |        3|          2 |
|         2 |        1|          0 |
------------------------------------

The first one is easy with
select reference, count(reference) overall from tbl1 group by reference
How can I accomplish the second one in the same statement?
Thanks

A: You can implement this kind of conditional count using sum:
sum(month(current_date - interval 1 month) = month(t_stamp))

Which can be null, in case there are no rows for the previous month. If you want to fetch 0 instead, you can use coalesce(<...>, 0).

A: With conditional counting using an if() function or case statement within a sum() or count():
select reference,
       count(reference) overall,
       count(if(curdate() - interval 1 month>=t_stamp,1,null)) last_month
from tbl1 group by reference

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to derive a formula with interacting variables (with example problem)? Imagine you are an enterprising child: and instead of starting a lemonade stand, you open a lemonade bank.
People can deposit lemons or sugar. In return, they get credit at your bank which they can used to withdraw either lemons or sugar.
Your mom gives you 1 lemon and your dad gives you 1 ounce of sugar. You issue each of them 1 unit of credit in return. Your bank has been seeded.
You decide you wish to maintain a 1:1 ratio between lemons and sugar. You decide you will do so by issuing more credit for deposits of what you have less of while charging more credits to withdraw what you have less of, and vice versa.
If your mom gives you another lemon and you issue her another full unit of credit then lemons will account for 67% of all credit issued, while lemons would be worth the same amount of credit as sugar (so 50%). If sugar is more valuable to the external market your mom could deposit lemons and extract sugar cheaply.
This will not do. This is why you must have a dynamically adjusting credit issuance which depends on the resulting internal ratio after any transaction.
So your mom says she would like to deposit another lemon into your bank. You currently have 1 lemon, 1 ounce of sugar, and 2 credits issued (in circulation). You must give your mom an amount of credit in return for her lemon, but how much? Giving her a full credit could result in an imbalance, so you must give her less than a full credit, but how much less?
You decide to guess. You think, "if I give a full credit, then all credits in circulation (3) will be backed by 2 lemons and 1 ounce of sugar, so 67% backed by lemons. So instead of 1 full credit, I'll give her .67 credits in return for the second lemon."
You realize this is a good guess because now 2.67 credits will be backed by 2 lemons at .67 credits apiece, totaling 1.34 credits; exactly half of 2.67. You have maintained 1:1 ratio in the value of lemons to sugar regardless of their count. But that makes you realize, now the 1 ounce of sugar in the bank is worth 1.34 credits instead of 1. Sugar's price has increased, in fact, in terms of lemons, it's now twice as valuable.
This dramatic change doesn't quite sit well with you so you tell your mom you'll have to get back to her about the amount of credit you will issue to her for her second lemon deposit.
You decide to do a comparison of scenarios just to recap. If you paid out 1 credit for the lemon then your bank credit would be backed by 67% lemons and 33% sugar, and lemons would cost the same as sugar or you could say lemons would account for 50% of the cost. If instead, you paid out .67 credits for the lemon then your bank credit would be backed by 50% lemons and 50% sugar, but lemons would account for 33% of the cost.

You already ruled out the first scenario, but the second scenario seems to push the imbalance into the price, rather than the backing of your credit. The second scenario seems like an over-correction. So you want to strike a balance somewhere between .67 and 1 credit. But where?
It seems you want to balance the two concerns so that they are mirror images of one another: the backing % for lemons should equal 1 - the unit cost % for lemons. But you don't know the formula to achieve such a balance. So again, you guess. Perhaps smack dab in the middle: .67+((1-.67)/2)~.83334 You give that a try:

Turns out that's really close: you compare 58.8% backing for lemons to 58.3% unit cost for ounces of sugar. It's almost a perfect match. But you're kind of a little psycho and you want the exact formula to balance the two concerns.
Why didn't the middle of 2/3rds and 1 give you the perfect balance you were looking for?
How would you create such a formula? What if your mother wanted to deposit 2 more lemons into your bank or withdraw .5 lemons?
Given this kind of input to the formula, what is the credit cost per lemon you should charge or pay?
EDIT (follow up):
Turns out the exact balance is 0.82842712474619. Which was arrived at iteratively. My question is, can a function be derived that computes this number? If so, how? and what is the function?

EDIT:

How are you calculating the backing?

Backing is calculated by multiplying the cost (or how many credits you're willing to mint) by the number of that asset, for each asset.
Continuing with the above example, imagine you go to your mom and accept her 2nd lemon deposit in exchange for the 0.82842712474619 credits. Once the transaction is carried out you would be in the situation outlined by the last spreadsheet image above; namely, you would have 2 lemons and 1 ounce of sugar in your bank, and you would have issued 2.82842712474619 credits in total.
So 2 lemons * 0.82842712474619 credits = 1.65685424949238 credits are backed by lemons and since there are 2.82842712474619 credits in circulation then we know 2 things: A) 1.65685424949238 / 2.82842712474619 = ~58.6 % so what we really mean is that each unit of credit in circulation is backed 58.6% by lemons and ~41.4% by sugar, B) which means we know the implied updated sugar price even though no sugar transaction has occurred: 2.82842712474619 credits in circulation - 1.65685424949238 credits accounted for by lemons = 1.17157287525381 credits accounted for by sugar (aka backed by sugar). To get the price of sugar we merely divide the total number of credits backed by sugar by the number of ounces of sugar: 1.17157287525381 credits / 1 sugar ounce = 1.17157287525381 credits.

How are you calculating the cost?

That is explained above, but to get the percentage, of course, we simply add up how much each asset costs and divide by the total. Thus 1.17157287525381 sugar cost + 0.82842712474619 lemon cost = 2 total cost so 0.82842712474619 / 2 ~ 41.4 % and 1.17157287525381 / 2 = 58.6 %
Again, notice the cost percentages per asset are the inverse of the backing percentages. That's what I mean by balanced. Finding the right cost for the number of units proposed to be traded that produces this inverse mirrored relationship is the entire goal of the quadratic function we're trying to deduce.
That means if your mom had wanted to deposit 3 or 40 lemons the number of credits you would have issued her per lemon would have been lower than 0.82842712474619. If she had wanted to withdraw the number of credits you would have required of her would have been higher (withdrawing might actually be more nuanced because there's a limit to how many you can withdraw, let's not go down that rabbit hole). I just wanted to say that the relationship between how much someone wants to deposit and the price you will pay per unit has a curve to it, not sure what that curve looks like but I imagine it's something like this:

I'll make additional edits to answer your questions later, but I hope this is sufficient in the meantime to show how backing % and costs % are calculated.
EDIT:
I hope you have enough to define the problem but I'll try to explicitly answer the other questions too:

*

*you say credit can be used to withdraw "either lemons or sugar."
What do you mean by this? Do you mean 1 unit of credit can be used to
withdraw 1 lemon or 1 ounce of sugar? Or are you setting prices
dynamically?

dynamically, in fact, the whole point is to map an amount of any asset someone has to deposit to an amount of issued credit that will balance the two concerns listed above. the amount of credit that is issued must be dynamic.

*What do you mean by "lemons will account for 67% of all credit
issued"" in paragraph 5? What implicit relationship between deposits
and credit is being tracked here?

"If your mom gives you another lemon and you issue her another full unit of credit then lemons will account for 67%" because you would have 2 lemons and you would have issued 3 credits and the price of lemons would be 1 credit. so 2 lemons * 1 credit = 2 credits and 2 credits (for lemons) / 3 total credits

*What do you mean by "while lemons would be worth the same amount of
credit as sugar" in paragraph 5? This seems to imply that you don't
have the freedom to set prices dynamically; is that right? If so, how
are the prices being set?

"If your mom gives you another lemon and you issue her another full unit of credit then lemons will account for 67% of all credit issued, while lemons would be worth the same amount of credit as sugar" means if you paid 1 credit for another lemon, lemons, and sugar would be the same price. it doesn't mean prices are not dynamic. At this point in the word-problem, I'm trying to show why prices must be dynamic by showing what would happen if you treated them as static.

*In paragraph 8 you say "all credits in circulation (3) will be backed by 2
lemons and 1 ounce of sugar, so 67% backed by lemons" which seems to imply that
each deposit backs each credit proportionately. But in paragraph 9 you say "now
2.67 credits will be backed by 2 lemons at .67 credits apiece, totaling 1.34
credits"; why?

If you pay 1 full credit the number of credits in circulation would be 3. if you pay .67 credits the number of credits in circulations would be 2.67. I hope that helps.

*cont.: specifically, why does the .67 credit number also apply to
the first lemon, which was deposited for 1 credit? Why isn't the
backing calculation being done as follows: 2.67 credits are backed by
2 lemons and 1 ounce of sugar, so 2.67 / 3 = 0.89 credits apiece for
each of the 2 lemons and the ounce of sugar? Or: each deposit backs
the credit it was exchanged for, so 1 credit for the sugar, 1 credit
for the first lemon, 0.67 for the second lemon?

Because the current price of lemons is the latest price they transacted for. We don't care what lemons went for in the past, they are priced as of now. the system has (or would have, after the transaction is completed) 2 lemons, whatever price is chosen in the transaction is the value that the system thinks lemons are worth - all lemons.

*In paragraph 11, what do you mean by "but lemons would account for
33% of the cost"? The cost of what? You seem to have calculated this
number by dividing 0.67 by 2. But what does the 2 represent here?

I'm dividing by 2 because you can add up all the prices of the assets and you come up with 2. so this asset's (lemon's) price represents a certain % of the total of all prices of assets in the system. That what it is, but technically price of sugar which makes up the rest of the number 2 is actually implied by the total credits in circulation as explained in the 3rd paragraph of my previous EDIT.
FINAL EDIT:
Here is the generalized solution (see comments of the answer below):
e = existing lemons (1)(1) (state)
d = deposit lemons (1)(2) (input variable)
s = existing sugar (1)(1)(state)
c = existing credits (2)(2) (state)
x = cost of lemons (.8284...)(.73...) (output)

(the second equation is for a deposit, not sure how to apply the first one, perhaps to withdrawals.)

A: Here's a neat feature I didn't realize existed; you can ask WolframAlpha if it thinks a constant has a closed form and it will spit out suggestions. For your $0.8284 \dots$ it suggests
$$2 \sqrt{2} - 2 = \frac{2}{\sqrt{2} + 1} \approx 0.82842712474619 \dots $$
which is an exact match to all of your digits.
I don't understand your problem statement (I put a long list of questions into the comments) but fortunately the mathematical content can be reverse-engineered from the spreadsheet screenshots alone, together with the big hint that it should all come down to solving a quadratic equation. It looks like if you pay out $x$ credits for the third lemon then the spreadsheet reads
$$\begin{array}{cccc}
  \text{assets} & \text{units} & \text{backing} & \text{cost} \\
  \text{lemons} & 2 & 2x & x \\
  \text{sugar} & 1 & 2 - x & 2 - x \\
 \text{total} & 3 & 2 + x & 2 \\
\end{array}$$
(I don't understand this, especially the backing calculations) and the condition you want appears to be that the fraction of the cost (I don't understand what this means) made up by the lemons, which is $\frac{x}{2}$, is equal to the fraction of the backing (I don't understand why you're calculating this the way you are) made up by the sugar, which is $\frac{2 - x}{2 + x}$, so
$$\frac{x}{2} = \frac{2 - x}{2 + x}.$$
Clearing denominators gives a quadratic equation
$$x^2 + 4x - 4 = 0$$
which has unique positive real solution $x = 2 \sqrt{2} - 2$. But given the lack of precision in the problem statement I am not at all confident that this is the number you actually wanted.
Edit: Here is my current understanding of how this calculation generalizes to arbitrary numbers. Suppose we have $L$ lemons, $S$ ounces of sugar, and $C$ credits in circulation, and Mom wants to deposit $L'$ new lemons and we want to determine how many credits $x$ to give her. If I've understood everything correctly, the spreadsheet should now read
$$\begin{array}{cccc}
  \text{assets} & \text{units} & \text{backing} & \text{cost} \\
  \text{lemons} & L + L' & (L + L')x & x \\
  \text{sugar} & S & C + (1 - L - L')x & \frac{C + (1 - L - L')x}{S} \\
 \text{total} & L + L' + S & C + x & \frac{C + (1 - L - L' + S)x}{S} \\
\end{array}$$
(this shouldn't be telling you anything you didn't already know because you must already have formulas equivalent to these in your spreadsheet if I've correctly understood the problem). The fraction of the cost made up by lemons is now $\frac{Sx}{C + (1 - L - L' + S)x}$, while the fraction of the backing made up by sugar is now $\frac{C + (1 - L - L')x}{C + x}$, and the condition that these are equal is
$$\frac{Sx}{C + (1 - L - L' + S)x} = \frac{C + (1 - L - L')x}{C + x}$$
which is again, after clearing denominators, a quadratic equation in $x$.


text:
Q: Moving Jtable in Java, Swing, Flowlayout I have this code so far:
public class Table extends JFrame {

    JTable table;

    public Table()
    {
        setLayout (new FlowLayout());   //Default layout

        String[] columnNames = {"Fly model", "Fly kode",
                "Destination", "Tidspunkt"};

        Object[][] data = {
            {"Boeing 737", "Ab79SO", "Oslo", "22:00"},
            {"MD125", "Tb682O", "Stockholm", "15:21"},
            {"Boeing 737", "HJ72SR", "Reikjavic", "08:13"},
        };
        table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 50));
        table.setFillsViewportHeight(true);
        setVisible(true);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    public JTable returnJTable()
    {
        setVisible(false);
        return table;
    }
}

I am not used to use FlowLayout, and I therefore don't know how to move this object around in the JFrame that I am using. I know that when you use a null (absolute) layout, you can use setBounds() to tell the JFrame where to position the elements. But how do I do that in FlowLayout?

A: You can't do that with FlowLayout. You can add new components horizontally or vertically one by another, but you can't to add component to specific position. You can try to use some tricks with blank panels or labels for spaces before/after your JTable, but better to use another layout.
Try to use BorderLayout, it's simple and with help of that, you can positioning your JTable in different places. Read tutorial for that.
Or you can use another LayoutManager, read about them and choose.

A: With FlowLayout you can't move the object around. All objects are placed in one line.
Try to use the BorderLayout or GridBagLayout.
Here's a visual guide to Layout Managers.
Panel myTable = new Panel(new GridBagLayout());
GridBagConstraints c1 = new GridBagConstraints();

c1.fill = GridBagConstraints.HORIZONTAL;    //area
c1.ipadx = 0;                               //spacing
c1.ipady = 0;                               //spacing
c1.weightx = 1.0;                           //horizontal
c1.weighty = 1.0;                           //vertical
c1.anchor = GridBagConstraints.CENTER;      //orientation
c1.insets = new Insets(10,10,10,10);        //padding
c1.gridx = 0;                               //column
c1.gridy = 0;                               //line
c1.gridheight = 1;                          //number of lines
c1.gridwidth = 1;                           //number of columns

myTable.add(new JScrollPane(table),c1);

You can move your table if you change the orientation.


text:
Q: OfficeJs `Cannot read property 'Version' of null` Zone.js error We are developing an OfficeJs add-in for use in the Outlook Web App (OWA) using Angular (V6.x atm.)
Angular depends on the zone.js Javascript library which we include in our polyfills.ts file.
It seems that OfficeJs uses a method (or álso depends on zone.js) that is causing the following error (which we comfortably have been ignoring for months together with the many other warnings and errors the OWA generates):

polyfills.js:4888 Uncaught TypeError: Cannot read property 'Version' of null
      at Object.callback (outlook-web-16.01.js:9)
      at rt (outlook-web-16.01.js:9)
      at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:5117)
      at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (polyfills.js:4884)
      at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (polyfills.js:5192)
      at invokeTask (polyfills.js:6236)
      at globalZoneAwareCallback (polyfills.js:6262)

in outlook-web-16.01.js:9, this is the line where this error originates:
OSF.DDA.WAC.Delegate.version=i.Version;r=i.Error
I was not able to reverse engineer what OfficeJs is trying to do, but it seems that the method where this goes wrong is located on this line:
`https://github.com/OfficeDev/office-js/blob/release/dist/office.debug.js#L1594
This happens deterministically when we use the Office.ui.messageParent method to send stringified JSON data from a dialog back to the parent add-in.
Unfortunately the stack trace does not give us anything more to investigate:


text:
Q: Query optimization (Netezza) I am trying to solve a problem in Netezza for a friend of mine.
My friend is trying to do something really simple in Netezza:
select *
from
test
where
ID1 = 12345
and date >= 12/1/2012 and event date <= 12/31/2012
and ID2 in
(x1, x2, ..., x150000)

This query never returns.
In Oracle, we could have tried something like this:
/*******************************************************************/
/*To reduce the size of the table...*/

create table t_test as
select *
from
test
where
ID1 = 12345
and date >= 12/1/2012 and event date <= 12/31/2012;

/*To make the search on ID2 faster...*/
create index i_ID2 on t_test (ID2);

select *
from
t_test
where
ID2 in
(x1, x2, ..., x150000)

/*Alternative: People say "IN" may be very inefficient at times...*/

select *
from
t_test
where
ID2 = x1
or ID2 = x2
.
.
.
or ID2 = x150000
/*******************************************************************/

However, this is not possible in Netezza, since it does not have any index concept.
How do I solve this problem?
Thanks and regards,

A: Exactly how is the line "and date >= 12/1/2012 and event date <= 12/31/2012" coded when you run it? Do you really have a column named "DATE"? Is an underscore missing in "event date"?

12/1/2012 evaluates to integer zero, not a date. Use:
date '2012-12-01'
date '2012-12-31'

or to_date('12/1/2012', 'mm/dd/yyyy') like Oracle

A: Try this way
select *
from
test
where
ID1 = 12345
and eventdate BETWEEN DATE('12/1/2012') DATE('12/31/2012')
and ID2 in
(x1, x2, ..., x150000)


text:
Q: Finding the 'proper time' frame of reference My textbook says roughly the following in then context of the invariant spacetime interval:

The proper time $\Delta \tau$ between two events is the time interval as observed in a coordinate system where the two events take place at the same position. This is not always possible. The invariant interval between two events equals c times the proper time, or $c\Delta \tau= \Delta S^2$. The proper time is the time interval measured by an observer who doesn't move relative to this position. The proper time is the time as for the observer himself; it is his own time. If the interval is positive, there will always be a coordinate system where the position of the two events is the same. This is true because a positive interval implies $|c\Delta t|>|\Delta r|$, so a reference frame that moves with velocity $\vec{v} = (\Delta \vec{r})/(\Delta t)$ will transform the events to the same position. And this speed is always smaller than the speed of light.

Alright, I understand that a positive spacetime interval implies that we could find an observer that measures two events at the same position, because even thought $\Delta x= 0$, we still have a positive time-interval $c\Delta t$. It makes sense that a time-interval is positive, so this seems to be about right to me.
However, I don't see how they come up with $\vec{v} = (\Delta \vec{r})/(\Delta t)$. It kind of makes sense intuitively, because I imagine following travelling from the first event to the second, so that they happen where you're at... but I can't connect the mathematics behind this intuition.
Can someone help me? Thanks!

A: The reason we define the proper time this way is to eliminate any effect of the travel time of light on the measurement of coordinates of events. If you assume that light travels at a finite speed, then the best way to eliminate any ambiguity is to simply travel in such a way that you happen to be at exactly the site of each event when it happens.


text:
Q: Sorting XML file based on XML nodes & XML comment tags using XSLT
Possible Duplicate:
Sorting XML file based on XML nodes & XML comments using XSLT

Hi All,
I need help in sorting an XML file based on xml nodes and ONE more thing is i have to place their comment tags corresponding to that node.
For Example: Input XML File is
<?xml version="1.0" encoding="UTF-8"?>
<!-- catalog main -->
<catalog>
 <!-- first book id -->
 <book id="bk101">
  <!-- author name 1 -->
  <author>Gambardella, Matthew</author>
  <!-- title name 1 -->
  <title>XML Developer's Guide</title>
  <genre>Computer</genre>
  <!-- price 1 -->
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
  <description>An in-depth look at creating applications
      with XML.</description>
 </book>
 <Book id="bk102">
  <author>Ralls, Kim</author>
  <title>Midnight Rain</title>
  <genre>Fantasy</genre>
  <price>5.95</price>
  <publish_date>2000-12-16</publish_date>
  <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
 </Book>

 <!-- languages -->
 <Languages>
  <!-- java comment -->
  <java>Galos, Mike</java>
  <c>Visual Studio 7: A Comprehensive Guide</c>
  <!-- dotnet comment -->
  <dotnet>Computer</dotnet>
  <!-- description -->
  <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
 </Languages>

 <!-- ABC book -->
 <ABC>
  <!-- ABC author -->
  <author1>Galos, Mike</author1>
  <title1>Visual Studio 7: A Comprehensive Guide</title1>
  <!-- ABC genre -->
  <genre1>Computer</genre1>
  <price1>49.95</price1>
  <publish_date>2001-04-16</publish_date>
  <!-- ABC description -->
  <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
 </ABC>
 <!-- ABC1 book -->
 <abc1>
  <!-- ABC1 author -->
  <author1>Galos, Mike</author1>
  <title1>Visual Studio 7: A Comprehensive Guide</title1>
  <!-- ABC1 genre -->
  <genre1>Computer</genre1>
  <price1>49.95</price1>
  <publish_date>2001-04-16</publish_date>
  <!-- ABC1 description -->
  <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
 </abc1>
</catalog>

EXPECTED OUTPUT XML FILE SHOULD BE:
<?xml version="1.0" encoding="UTF-8"?>
<!-- catalog main -->
<catalog>
 <!-- ABC book -->
 <ABC>
  <!-- ABC author -->
  <author1>Galos, Mike</author1>
  <!-- ABC description -->
  <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
  <!-- ABC genre -->
  <genre1>Computer</genre1>
  <price1>49.95</price1>
  <publish_date>2001-04-16</publish_date>
  <title1>Visual Studio 7: A Comprehensive Guide</title1>
 </ABC>
 <!-- ABC1 book -->
 <abc1>
  <!-- ABC1 author -->
  <author1>Galos, Mike</author1>
  <!-- ABC1 description -->
  <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
  <!-- ABC1 genre -->
  <genre1>Computer</genre1>
  <price1>49.95</price1>
  <publish_date>2001-04-16</publish_date>
  <title1>Visual Studio 7: A Comprehensive Guide</title1>
 </abc1>
 <!-- first book id -->
 <book id="bk101">
  <!-- author name 1 -->
  <author>Gambardella, Matthew</author>
  <description>An in-depth look at creating applications
      with XML.</description>
  <genre>Computer</genre>
  <!-- price 1 -->
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
  <!-- title name 1 -->
  <title>XML Developer's Guide</title>
 </book>
 <Book id="bk102">
  <author>Ralls, Kim</author>
  <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
  <genre>Fantasy</genre>
  <price>5.95</price>
  <publish_date>2000-12-16</publish_date>
  <title>Midnight Rain</title>
 </Book>
 <!-- languages -->
 <Languages>
  <c>Visual Studio 7: A Comprehensive Guide</c>
  <!-- description -->
  <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
  <!-- dotnet comment -->
  <dotnet>Computer</dotnet>
  <!-- java comment -->
  <java>Galos, Mike</java>
 </Languages>
</catalog>

A: This Question is similar to what i posted in another Question..
below is the url:
Sorting XML file based on XML nodes & XML comments using XSLT


text:
Q: Can someone explain the chi squared distribution in layman's terms I understand that the chi squared distribution is the square of a normal distribution. If X is a normal variable, what are we squaring, the values of X or the corresponding probabilities?
I am unable to see the intuitive explanation as to how by squaring a normal variable, I can use the resultant distribution for hypothesis testing and confidence interval?

A: Let's say you have random numbers $x_i$. When you estimate the variance of the series, you have to calculate sums like $\sum_i x_i^2$. If your numbers are from normal distribution, then the sum is from $\chi^2$ distribution. If you need to know the confidence intervals of your variance estimate, then you can use $\chi^2$ distribution to get them.
Often your numbers are not from normal distribution. However, due to central limit theorem (CLT) the sums of non-normal random variables are still normal in some cases. So, if you look at the mean of the sample, it's from normal distribution $\bar x=\frac{1}{n}\sum_i x_i$. Hence, if you want to know the variance of the sample mean, you'll get to calculate the sums like $\sum_k \mu_k^2$, where $k$ is a sample. Again, you can use $\chi^2$ to get confidence intervals of the variance of the sample mean.

A: Your understanding is slightly flawed. A $\chi^2$ distribution with $k$ degrees of freedom arises as the sum of squares of $k$ independent standard normal deviates.
This is useful for hypothesis tests when the data (are assumed to) follow a normal distribution. For example, in the case of Pearson's test $\chi^2$ test of independence, the test statistic is constructed as the sum-of-squared deviations from expected values.

A: As others have mentioned, a $\chi_{n}^2$ distribution is the distribution of the sum of $n$ (independent identically distributed) variables with Normal distributions (each of mean 0 and variance 1). But when students first encounter this concept, they're given tables to look up probabilities. How are those derived?
Let's start with $n=1$ so, for any $x \geq 0$, our variable $\leq x$ iff the underlying normal variable is $\in \left[-\sqrt{x},\,\sqrt{x}\right]$, which has probability $2\Phi\left(\sqrt{x}\right)-1$ where $\Phi\left( x \right)=\int_{-\infty}^x \frac{1}{\sqrt{2\pi}}\text{e}^{-t^2/2}dt$. Differentiating, the pdf is $x^{-1/2}\Phi'\left( \sqrt{x}\right)=\frac{1}{\sqrt{2\pi x}}\text{e}^{-x/2}$ for $x\geq 0$. Integrating that to check it's normalised is equivalent to computing $\Gamma\left( \frac{1}{2} \right)$, so the characteristic function turns out to be $\left( 1-2it \right)^{-1/2}$.
Now we can generalise to arbitrary $n$ . The characteristic function becomes $\left( 1-2it \right)^{-n/2}$ . By the inversion formula, the pdf on $\left[0, \,\infty\right]$ is proportional to $x^{n/2-1}\text{e}^{-x/2}$ (for the simple reason that such a pdf would obtain the right characteristic function). Now we just need the proportionality constant, viz. $\frac{x^{n/2-1}\text{e}^{-x/2}}{2^{n/2}\Gamma\left(\frac{n}{2} \right)}$. For even $n$ , an elementary expression for the cdf can be obtained by integration; for odd $n$ , we get a result in terms of $\Phi$, such as the one obtained above for the $n=1$ case. The $n=2$ case is especially simple; the pdf is $\frac{1}{2}\text{e}^{-x/2}$, which is an exponential distribution with $\lambda=\frac{1}{2}$.


text:
Q: Firebase function returning null value when called from iOS app I am making a call to a callable firebase function from my iOS app and am getting a return value of null. The correct value was returned just a few days ago, but now it's always returning null. The data is logging correctly in the console just before the return line, and there is no error appearing within the iOS call.
exports.startPlaylist = functions.https.onCall((data, context) => {
    const uid = context.auth.uid;
    const signature = data.signature;

    return axios.post('---url----', {
        data: signature
    }).then(function(response) {
        const val = response.data;

        const ref = database.ref().push();
        ref.set({
            host: {
                uid: uid
            },
            users: {
               uid: uid
            },
            books: val
         }, function(error) {
            if(error) {
                console.log('Not set');
            } else {
                const info = { id: ref.key };
                console.log(info) //Correct log value appears in console
                return info;      //Return null, however
            }
        });
    }).catch(function(err) {
        console.log(err);
    });
 });

Firebase call
Functions.functions().httpsCallable("startPlaylist").call(["signature": signature]) { (result, error) in
        guard let result = result, error == nil else { return }
        print(result.data) //<-- prints "null"
 }

A: As stated you should work with the promise returned by set:
            ref.set({
                host: {
                    uid: uid
                },
                users: {
                   uid: uid
                },
                books: val
             }).then(function() {
                const info = { id: ref.key };
                console.log(info)
                return info;
             })
             .catch(function(error) {
                  console.log('Not set');
             });


text:
Q: Multicast Message queue I am sending out large streams of video to many machines on an internal network.
I would like to use a message queue, but I cannot afford to uni-cast copies of the video to each of the machines.
Is there any message queue that implements fan-out [send multiple copies of message to several machines] via multicast?
Since this is video, creating several unicast streams is out of the question.

A: Video streaming via high level messaging technologies is probably a really bad idea in the first place. Why would you need messaging in the first place? What features do you need?
An IP multicast would disable most features of a messaging system since every message would be delivered at the same time.
Publish/subscribe is probably the closest you get to multicast on high level MOMs (RabbitMQ,ActiveMQ or other amqp/jms compliant suites). But I doubt it would be usable for video in most cases.
ZeroMQ is a low level messaging mechanism, closer to the wire - but without much of the high level features of MOM software. It supports multicast etc. Messaging systems using MQTT might be light weight enough to transport large amounts of video as well.

A: Not sure about JMS for this, but you might want to look at Netty's RTSP protocol implementation.
Rtsp:http://www.ietf.org/rfc/rfc2326.txt
Netty:http://netty.io/4.0/api/io/netty/handler/codec/rtsp/package-summary.html


text:
Q: Bluetooth discoverable on button click without navigating to bluetooth settings page How can we make bluetooth discoverable  on button click without going to bluetooth settings page.
 bt_strength.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (mBtAdapter.getScanMode()!= BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
           {

          make discoverable

            }

How can I do this?
Any help is always appreciated, Thanks

A: You would have Bluetooth Adapter object obtained from :
 BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

On Button Click you can call :
  mBluetoothAdapter.startDiscovery();

this will put your bluetooth in Discovery mode


text:
Q: Why does CakePHP use this method name in a MySQL query rather than return the result? In applying the answer from a previous question, I tried overriding one of CakePHP's built-in pagination methods:
function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
    if (isset($extra['group'])) {
        for ($i=0; $i<count($extra['group']);$i++) {
            if (strpos(strtolower($extra['group'][$i]),'having')!==false) unset($extra['group'][$i]);
        }
        exit();
    }
    $count = parent::paginateCount($conditions, $recursive, $extra);
    return $count;
}

The problem is that this seems to cause Cake to do a MySQL query consisting simply of the name of the method. Obviously this doesn't work and throws an error:

SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'paginateCount' at line 1

Since I have debugging enabled, I can see that where there would normally be the paginateCount() query:
1: SELECT COUNT(*) AS `count` FROM `tournaments` AS `Tournament` WHERE 1 = 1

I just get:
1: paginateCount

I've obviously misunderstood PHP's inheritance operators. My function seems to be returning the name of the function it is overriding rather than it's value.
How can I fix this?

A: This usually happens when CakePHP can't find the method in the model or attached behaviors.
It then passes the call to the datasource (hoping it has the method and knows what to do) and that's why you get this error.
I would check things are what they seem (is the method in the right model, is Cake making an automodel because of incorrect filenaming, etc.)

A: I've fixed this without really addressing the question I asked.
Instead of passing the adjusted parameters up the chain as I wanted to do in my above example, I've used them to do the same job directly:
return $this->find('count', compact($conditions, $recursive, $extra));

This works OK, but doesn't explain the odd behaviour that caused me to ask the question in the first place. My guess is that Cake is doing something funky with virtual/"automagic" methods.


text:
Q: Oidc client js: silent access token renew breaks because identity server authentication cookie sliding expiration doesn't work I'm working with an angular SPA which implements authentication by using identity server 4 and oidc client js.
Something is not working at the silent access token renew level. The expected behavior is an automatic renew of the access token, which happens under the hood thanks to an iframe which calls the /connect/authorize endpoint. This call sends the identity server authentication cookie along with the HTTP request, doing so identity server knowns that the user session is still valid and is able to issue a fresh new access token without requiring the user to sign in again interactively. Up to this point I'm quite sure that my understanding is fine.
Here is the tricky part: my expectation is that the identity server authentication cookie should have a sliding expiration, so that its expiration date is moved forward in time each time a call to the /connect/authorize endpoint is made. Put another way, I expected that after the user signs in the first time no other interactive login is required to the user, because the user session expiration date is automatically moved forward in time each time a new access token is required by the silent renew iframe.
In order to obtain this behavior I've set up the following configuration at the identity server level.
This is the client configuration (notice that the access token lifetime is 2 minutes = 120 seconds):
                    new Client
                    {
                        ClientId = "web-client",
                        ClientName = "SPA web client",
                        AllowedGrantTypes = GrantTypes.Code,
                        RequireClientSecret = false,
                        RequirePkce = true,
                        RequireConsent = false,
                        AccessTokenLifetime = 120,

                        RedirectUris =           { "https://localhost:4200/assets/signin-callback.html", "https://localhost:4200/assets/silent-callback.html" },
                        PostLogoutRedirectUris = { "https://localhost:4200/signout-callback" },
                        AllowedCorsOrigins =     { "https://localhost:4200" },

                        AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            IdentityServerConstants.StandardScopes.Email,
                            "dataset",
                            "exercise",
                            "user-permissions"
                        }
                    }

This is the ConfigureServices, where I've added all of the identity server configuration. Notice that the cookie lifetime is set to 15 minutes and that the cookie sliding expiration is required:
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<RequestLoggingOptions>(o =>
            {
                o.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
                {
                    diagnosticContext.Set("RemoteIpAddress", httpContext.Connection.RemoteIpAddress.MapToIPv4());
                };
            });

            services.AddControllersWithViews();

            var migrationsAssembly = GetRunningAssemblyName();
            var connectionString = this.Configuration.GetConnectionString(IdentityServerDatabaseConnectionString);

            var identityServerBuilder = services.AddIdentityServer(options =>
            {
                options.Authentication.CookieLifetime = TimeSpan.FromMinutes(15);
                options.Authentication.CookieSlidingExpiration = true;
            })
            .AddTestUsers(TestData.Users)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = dbContextBuilder =>
                    dbContextBuilder.UseSqlServer(
                        connectionString,
                        sqlServerOptionsBuilder => sqlServerOptionsBuilder.MigrationsAssembly(migrationsAssembly)
                    );
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = dbContextBuilder =>
                    dbContextBuilder.UseSqlServer(
                        connectionString,
                        sqlServerOptionsBuilder => sqlServerOptionsBuilder.MigrationsAssembly(migrationsAssembly)
                    );
            });

            services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServer4.IdentityServerConstants.DefaultCookieAuthenticationScheme);

            identityServerBuilder.AddDeveloperSigningCredential();
        }

I've added the call to services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServer4.IdentityServerConstants.DefaultCookieAuthenticationScheme); after reading this github issue. Based on my understanding this call is redundant, because the call to services.AddIdentityServer should already set the cookie authentication as the default authentication scheme, by using the constant IdentityServer4.IdentityServerConstants.DefaultCookieAuthenticationScheme as the authentication scheme name.
By using this identity server configuration the silen access token renew does not work the way I expect.
The access token is silently renewed 14 times, then the fifteenth attempt to renew the access token fails with the message SilentRenewService._tokenExpiring: Error from signinSilent: login_required.
This basically means that the authentication cookie sliding expiration is not working, because my authentication cookie has a 15 minutes lifetime, the access token for my SPA client has a 2 minutes lifetime and the oidc client js library is doing the silent refresh cycle once per minute (the access token is renewed 60 seconds before its expiration time, so with my settings the silent renew in done every minute). At the fifteenth attempt to renew the access token the authentication cookie is finally expired and the identity server authorize endpoint returns an error response to the https://localhost:4200/assets/silent-callback.html static page.
These are my console logs (notice that for 14 times the silen renew has worked as expected):

These are the server side logs written by identity server, which confirms that the user session is expired at the fifteenth attempt:

These are the response headers returned by identity server when the /connect/authorize endpoint is called during a successful attempt to renew the access token (one of the first 14 attempts to renew the access token). Notice that there is a response header which sets a new value for the idsrv cookie:

These are the response headers returned by identity server when the /connect/authorize endpoint is called during a failed attempt to renew the access token (the fifteenth attempt to renew the access token). Notice that the idsrv.session cookie is invalidated, because its expiration date is set to a past date in 2019:

Am I missing anything about the relationship between the silent access token renew and the authentication cookie sliding expiration ?
Is this the expected behavior ?
Is there a way to make the silent access token renew work without requiring a new user login interaction ?
Update 16th September 2020
I finally managed to solve this issue.
The fix is the updating of the IdentityServer4.EntityFramework nuget package to the latest available version (4.1.0 as of today).
All the details are reported in my own github issue on the
oidc-client-js github repository.
To summarize, the underlying cause of the strange behavior with the cookie sliding expiration is this identity server bug, fixed by the 4.1.0 release of IdentityServer4.EntityFramework nuget package, as pointed in the release notes.

A: Here is my configuration on your request:
public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks();

        services.AddControllersWithViews();

        services.AddCustomOptions(Configuration);

        services.AddCustomDbContext(Configuration)
            .ResolveDependencies();

        services.AddIdentityServer(options =>
                {
                    options.Authentication.CookieLifetime = AccountOptions.RememberMeLoginDuration;
                    options.Events.RaiseSuccessEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseErrorEvents = true;
                })
            .AddProfileService<ProfileService>()
            .AddSigningCertificate(Configuration)
            .AddInMemoryClients(Configuration.GetSection("IdentityServer:Clients"))
            .AddInMemoryIdentityResources(Resources.GetIdentityResources())
            .AddInMemoryApiResources(Resources.GetApis());

        var externalProviders = Configuration.GetSection(nameof(ApplicationOptions.ExternalProviders))
            .Get<ExternalProvidersOptions>();

        services.AddWindowsIdentityProvider(externalProviders.UseWindows);

        services.AddLocalization(options => options.ResourcesPath = Constants.Resources);

        services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();

        services.AddMvcCore()
            .AddCustomCors();
    }

Also, follwing is the client configuration in the appsettings:
{
    "Enabled": true,
    "ClientId": "dashboard",
    "ClientName": "Web Client",
    "ClientSecrets": [ { "Value": "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=" } ],
    "AllowedGrantTypes": [ "implicit", "authorization_code" ],
    "AllowedScopes": [ "openid", "email", "profile", "role" ],
    "AllowOfflineAccess": true,
    "AllowAccessTokensViaBrowser": true,
    "AllowedCorsOrigins": [
      "http://localhost:7004"
    ],
    "RedirectUris": [
      "http://localhost:7004/callback",
      "http://localhost:7004/refreshtoken"
    ],
    "PostLogoutRedirectUris": [
      "http://localhost:7004"
    ],
    "AccessTokenLifetime": 3600,
    "RequireConsent": false
  }


text:
Q: Create procedure to automate insert from another table by max(date) I am trying to create a procedure to insert missing rows from another table by max(date).  I would then schedule a job to run every 5 minutes to update a remote table.
I am unable to get my procedure to compile. I would like to add date format change as part of the session too.  Then how would I use job scheduler to call it to run every 5 minutes.
create or replace procedure update_cars
AS
v_date date;
begin
--execute immediate 'alter session set NLS_DATE_FORMAT='DD-MON-YY HH24:MI:SS'';
select max(inventory_date) from car_equipment into v_date;
return v_date;
insert /*+APPEND*/ into car_equipment    (count_cars,equipment_type,location,inventory_date,count_inventory)
select   count_cars,equipment_type,location,inventory_date,count_inventory from car_source where inventory_date > v_date;
end;
/

Error(6,47): PL/SQL: ORA-00933: SQL command not properly ended

A: *

*SELECT expression INTO variable FROM ... as APC mentioned.

*RETURN is probably misplaced, as APC mentioned

*Date format change? car_equipment.inventory_date is probably already a date, since you select it into a date variable. Is car_source.inventory_date a date column? If it is, than a date is a date is a date: nothing to do. If it is not a date (bad idea!) then use the appropriate to_char(inventory_date, 'DD/MM/YYYY') in the select.


text:
Q: Login to BigCommerce API through iOS Application as a customer I am developing an iOS application for a store on BigCommerce.com . I have successfully retrieved the products list from the BigCommerce API and I have also created a new user using the same.
Create User: https://developer.bigcommerce.com/api/stores/v2/customers#create-a-customer
Product List:
https://developer.bigcommerce.com/api/stores/v2/products
But i am unable to understand that how should i login into the BigCommerce Store as a customer to purchase products listed.
Please can anyone help.

A: You can login by sending a POST to:
/remote.php?w=expressCheckoutLogin

Send fields 'login_email' and 'login_pass' in your POST's body.

A: Its very hard to finding login api in bigCommerce. this solution is 100% working and tested.
Keep Enjoy
APi URL : https://api.bigcommerce.com/stores/[STORE_HASH]/v2/customers/[CUSTOMER_ID]/validate
Method : POST
Header
X-Auth-Client : Client_id
X-Auth-Token : Access Token
Accept :  application/json
Content-Type : application/json
Body
{
   "password": "123456"
}
Response
{
 "success": true
}


text:
Q: Code only returns if statement, ignores everything else I know this is simple but I can't get this code to work. No matter the order I put the variables or if/elif statements in, it only returns the if statement regardless of the month.
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program\n")

months_28 = "February"
months_30 = "April", "June", "September", "November"
months_31 = "January", "March", "May", "July", "August", "October", "December"

if months or months.casefold() in months_28:
    print("There are 28 days in", months.capitalize())
elif months or months.casefold() in months_30:
    print("There are 30 days in", months.capitalize())
elif months or months.casefold() in months_31:
    print("There are 31 days in", months.capitalize())
else:
    print("That's not a month")

I also am trying to work a while loop into this too (as reflected in the beginning) and any help there would be greatly appreciated.

A: You can Fabricate your code even more, with

*

*Python's one of the strongest data structures - Dictionaries

*Exception handling usage instead of if-else

*F-strings, to increase readability of code

These Changes not only optimises your code, but also reduces time and space complexity
I've recoded it for you --
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program")

Month_Days = {
  'February': 28,
  'April': 30, 'June': 30, 'September': 30, 'November': 30,
  'January': 31, 'March': 31, 'May': 31, 'July': 31, 'August': 31, 'October': 31, 'December': 31
  }

try: print(f"There are {Month_Days[months.title()]} days in", months.capitalize())
except Exception: print("That's not a month")

With this, you not even have to add additional condition for exit, that'll be handled by try/except

A: Your months_* need to be lists.
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program\n")

months_28 = ["february"]
months_30 = ["april", "june", "september", "november"]
months_31 = ["january", "march", "may", "july", "august", "october", "december"]

if months and months.casefold() in months_28:
    print("There are 28 days in", months.capitalize())
elif months and months.casefold() in months_30:
    print("There are 30 days in", months.capitalize())
elif months and months.casefold() in months_31:
    print("There are 31 days in", months.capitalize())
else:
    print("That's not a month")

Just using your code with the minor changes.  There are obviously different ways of printing what you want out.

A: Few mistakes in your code:

*

*months_28 is just a string. To convert that to a tuple add a , at the end

*Instead of using casefold(), I suggest using title() as the months names start with a Capital letter

*You must use and and not or in the if conditions because you want both the conditions to be True.

Below code will do what you require.
months = input("Enter a month to find out how many days are in that month, or enter 'exit' to quit the program\n")

months_28 = "February",
months_30 = "April", "June", "September", "November"
months_31 = "January", "March", "May", "July", "August", "October", "December"

if months and months.title() in months_28:
    print("There are 28 days in", months.capitalize())
elif months and months.title() in months_30:
    print("There are 30 days in", months.capitalize())
elif months and months.title() in months_31:
    print("There are 31 days in", months.capitalize())
else:
    print("That's not a month")

A: This fixes your problem and adds the loop you need.
months_28 = ["February"]
months_30 = ["April", "June", "September", "November"]
months_31 = ["January", "March", "May", "July", "August", "October", "December"]

another = True
while another:
    choice = input("[1] Enter a month to find out how many days are in that month\n[2] Enter 'exit' to quit\n")
    while True:
        if choice == '1':
            month = input("Enter month: ").capitalize().strip()
            if month in months_28:
                print("There are 28 days in", month)
            elif month in months_30:
                print("There are 30 days in", month)
            elif month in months_31:
                print("There are 31 days in", month)
            else:
                print("Invalid entry.")
        elif choice == '2':
            print('Buh bye!')
            break

        another = input("Try another month? Y/N: ").capitalize().strip()
        if another == 'Y':
            anpther = True
        elif another == 'N':
            print("Good bye!")
            break
    break


text:
Q: Send axios post request error message from node js server to client side How can I send a node JS Axios request error message? I don't want to print the error in the console, I want to send it to the application.
For instance, if I am testing on postman and i hit localhost:8080/list/2 and 2 is the wrong id, instead of endlessly showing sending request, I want the specific JSON error message returned.
**server.js** proxy server running on localhost:8000 makes request to another endpoint
app.get("/list/:id", function (req, res) {
  const { id } = req.params;
  axios
    .get(`${BASE_URL}/list/` + id)
    .then((response) => {
     res.send(response.data)
    })
    .catch((error) => {
       if(error.response) {
            res.send(error.response)
        }
    });
});

2. How can this error message be used in an Axios request on the client side?
const getList = () => {

    axios
      .get("http://localhost:8000/list", {
          params: {
            id: '4'
          }
        })
      .then((resp) => {
        const data = resp.data;
        console.log(resp.data)

      })
      .catch((err) => {
        console.error(err);
      });
  };

A: The error.response is an Axios Response object which doesn't serialise to JSON very well.
See Axios - Handling Errors.
You should respond with the upstream response status and data
app.get("/list/:id", async (req, res, next) => {
  const { id } = req.params;
  try {
    const { data } = await axios.get(`/list/${id}`, {
      baseURL: BASE_URL,
    });
    res.send(data);
  } catch (err) {
    if (err.response) {
      res
        .status(err.response.status) // proxy the status
        .send(err.response.data); // proxy the data
    }
    next(err); // some other error
  }
});

FYI, the Axios params option is for constructing URL query parameters. Your client-side request should use
axios.get("http://localhost:8000/list/4")

Another FYI, Express has a much simpler proxy library - express-http-proxy
const proxy = require('express-http-proxy');

app.use("/list", proxy(BASE_URL, {
  https: true,
  proxyReqPathResolver: (req) => req.originalUrl,
}));


text:
Q: ¿Cómo contar elementos de una columna sin tomar en cuanta los valores nulos en Laravel 6.0? Estoy intentando contar los elementos de una columna con Query Builder y no logro excluir los valores nulls del conteo, he intentado con este código pero no ha funcionado.
$ttg = DB::table('incidencias')
                 ->select(DB::raw('count(*) as ttg, inc_padre'))
                 ->where('inc_padre', '<>', null)
                 ->groupBy('inc_padre ')
                 ->get();

A: Puedes usar whereNotNull, como lo dice la documentación
$users = DB::table('users')
                    ->whereNotNull('updated_at')
                    ->get();

En el caso de tu consulta sería así:
$ttg = DB::table('incidencias')
                 ->select(DB::raw('count(*) as ttg, inc_padre'))
                 ->whereNotNull('inc_padre')
                 ->groupBy('inc_padre')
                 ->get();

A: Depende lo que necesites. Si necesitas tener si o sí los valores de inc_padre, entonces la respuesta de jolsalazar es totalmente válida.
$ttg = DB::table('incidencias')
        ->select('inc_padre', DB::raw('count(*) as ttg'))
        ->whereNotNull('inc_padre')
        ->groupBy('inc_padre')
        ->get();

Ahora, si quieres contar sin tener en cuenta el campo "inc_padre", puedes usar count() al final de la sentencia y quedarte con el valor.
$ttg = DB::table('incidencias')
        ->whereNotNull('inc_padre')
        ->count();

A: No veo necesidad de usar constructor de consultas de dicha forma si pudiera quedar así
$datos = Incidencia::whereNotNull('inc_padre')->count();

Ahí

*

*Empleas el modelo

*Filtras los no nulos con whereNotNull

*Obtienes el conteo final

De esa forma mantienes más simple la consulta, dado que tú count es un tanto genérico por eso considero este método concatenado al final debería bastar


text:
Q: How to initialize ajax request into php variable (for a another php function) I want to send a JavaScript variable Data into another php file for a php function.  I realized we are unable to use PHP Sessions for that. I tried to do it using AJAX (using jQuery), but I am unable to initialize the AJAX request in to a php variable. However AJAX give me a correct Response:(means ajax is working). but when i print the request [print_r($_POST)], it gave me zero result.
Here is the main html , javascript part.

"+ PostDataResponse + "
  // PostDataResponse is also ajax response, it is working correctly.
 click_Here_Link

When I click the click_Here_Link link I wont send the data to requestFile.php file as session variable. I developed the ajax post method in client side like this.(It give me a correct response.)
  function  saveData(){

     // $.post('/ server.php', { postingData: name});

     var name = document.getElementById("postData").innerHTML.trim();

   $.ajax ({
   type: 'POST',
   url: 'server.php',
   dataType: 'text',
   data: {postingData: name},

  success: function (Response) {
     alert(Response);
  },
   error: function () {
   alert('failure...!  ');
   }
 });
 }

Here is the server.php code.
<?Php
  $boat = $_POST['postingData'];
  echo $boat;
  print_r($_POST);
?>

when open the server.php file it give me a error.

Undefined index: postingData

A: replace your ajax with this :
 $.ajax ({
   method:'POST',
   url: 'server.php',
   data:"postingData="+$('#postData').getAttribute('name'),
  success: function (Response) {
     alert(Response);
  },
   error: function () {
   alert('failure...!  ');
   }
 });

A: Edit the following in ajax
.change name to name2
data: {postingData: name2},


text:
Q: Simscape, COMSOL compatibility in simulating electromagnetic range of inductive charging I am currently trying to use Simscape to design and simulate the electrical circuit and COMSOL Multiphysics to simulate the electromagnetic interaction between coils. What I'm not certain of is whether or not we can successfully link the two software packages nicely via MATLAB or not. They both have MATLAB support though.
I am also researching whether ANSYS suite. There may be some software we can use that would take the place of one or both of the previous software.

A: Several years ago I had to make a connection between COMSOL and Matlab as well. This is called a Matlab Comsol LiveLink.
However, I think (not sure), that the electrical circuit should be modeled in COMSOL. Using the LiveLink you can set parameters in COMSOL using Matlab and extract the updated calculation. To my knowledge you cannot input a model, do calculations, and then extract the results.
You can look in the users guide, maybe it says something about this
Some other links which may be useful:

*

*LiveLink™ for MATLAB®

*Integrate COMSOL Multiphysics® with
MATLAB® Scripting


text:
Q: CKFinder enable file browser I installed CKEditor and CKFinder in my site, and when I ran a sample of CKFinder to test the browse image functionality, it is saying:

The file browser is disabled for security reasons.

I could not find the way of enabling file browser, please can anyone provide the solution?

A: That is why ckfinder.config/php.config exists for.
You should enable ckFinder this way:
enabled = "false"

and configure your basedirectory according to your files (i.e.)
$baseUrl = '/ckfinder/userfiles/';

Another helpful thread.


text:
Q: Angular 6 form submitted property does not exist I am build an angular application in which I used angular forms. It works well on angular 5 and also on angular 6. But when I go to deploy it by ng build -prod it gives the errors

Here is my code for logincomponent
<form class="md-float-material form-material" [formGroup]="loginForm" (ngSubmit)="onSubmit()">

User Login

                Username
                <input type="text" formControlName="username" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />

Username is required

                Password
                <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />

Password is required

                <button class="btn btn-primary btn-md btn-block waves-effect waves-light text-center m-b-20">Login</button>

</form>

And here is TS Code
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AlertService, UserService } from '../_services';

@Component({ templateUrl: 'login.component.html' })
export class LoginComponent implements OnInit {
    loginForm: FormGroup;
    returnUrl: string;
    selectedValue: 'observer';

    constructor(
        public formBuilder: FormBuilder,
        public route: ActivatedRoute,
        public router: Router,
        public userService: UserService,
        public alertService: AlertService) { }

    public ngOnInit() {
        this.loginForm = this.formBuilder.group({
            username: ['', Validators.required],
            password: ['', Validators.required],
        });

        this.userService.logout();

        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
    }

    get f() { return this.loginForm.controls; }

    public onSubmit() {

        if (this.loginForm.invalid) {
            return;
        }

        this.userService.login(this.loginForm.value)
            .subscribe(
                response => {
                    this.alertService.success('User Authenticated', true);
                },
                error => this.alertService.error(error, false)
            );
    }
}

A: This error is a result of AoT(Ahead of Time) compilation.
The reason why these errors don't show up while running "ng serve" is because ng serve performs JiT(Just in Time) compilation.
In AoT compilation, you have to have each and every methods/variables declared along with many other things.
Once you define the missing variables (like submitted on the LoginComponent) on your ts, those errors will go away.

A: In this specific case, I would create an instance of FormControl in our class. For e.g.   loginForm = new FormControl();
Here is a good explanation of your problem:
https://www.concretepage.com/angular-2/angular-2-formcontrol-example


text:
Q: Vim pymode: meaning of  key combination I have come across the following key combinations(...i assume) in vim pymode documentation. <C-c>, <C-C>, <C-X><C-O>, <C-P>/<C-N>. How are they to be interpreted?

A: <C-c> and <C-C> both mean Ctrl+C.
I'm sure you can infer how to type the others.
See :help key-notation.


text:
Q: Can't connect to SFTP (with private key file) in Copy Data Tool I am trying to copy data from SFTP to blob but got stuck when creating SFTP source.
I have the connection details and can easily connect on Filezilla or WinSCP. However, I am unable to get it to work in Azure data factory.
I am not using code but the user interface.
The connection details on the page creating the SFTP source:
Connect via integration runtime: AutoResolveIntegrationRuntime (default)
Host: xyz

Port: 22 (can't remove it as it doesn't like it)

SSH Host Key Validation: Enable SSH Host Key Validation

SSH Host Key Finger-print: taken from WinSCP - Session - Server/protocol information

Authentication type: SSH Public Key Authentication   -can't use basic as the private key holds the security info

User name:XXX

Private Key Type: Use Key Content

Private key content: loaded the .ppk file, tried also tried loading the .pem file and got different errors

Pass Phrase: none

When setting up this sftp in WinSCP or FileZilla it automatically converted the provided .pem file into .ppk.
When I loaded the .ppk file into ADF I got an error: Invalid Sftp credential provided for 'SshPublicKey' authentication type.
When I loaded the .pem file I got: Meet network issue when connect to Sftp server 'spiderftp.firstgroup.com', SocketErrorCode: 'TimedOut'.
I have also tried 'Disable SSH Host Key Validation' in SSH Host Key Validation and made no difference.
I have also opened the .ppk file in PuttyGen and used that host key finger print and still no luck.
Only getting these 2 errors depending on which file I load.
Can't find anything about this online so would be grateful for some advice.

A: Have you read this note in this doc?
https://learn.microsoft.com/en-us/azure/data-factory/connector-sftp#using-ssh-public-key-authentication
SFTP connector supports RSA/DSA OpenSSH key. Make sure your key file content starts with "-----BEGIN [RSA/DSA] PRIVATE KEY-----". If the private key file is a ppk-format file, please use Putty tool to convert from .ppk to OpenSSH format.

A: Got this working today. Like you, could connect using WinSCP and failed when using ADF.
The link Fang Liu shared contains our answers, but my issue was not the private key. I suspect Fang's suggestion resolved your problem and I'm sharing my answer here to help others who may encounter similar.
My issue:
When using Private Key Authentication in ADF the password becomes a Pass Phrase and you no longer have the ability to supply a password. To overcome the problem we disabled password authentication for the user and the SFTP connection started working.
As stated in the documentation. The Pass Phrase is used to decrypt the private key if it is encrypted.
Also worth noting:

*

*If you store the contents of the private key in Key Vault you need
to base64 encode the entire contents of the exported key and use
that string. This includes "-----BEGIN RSA PRIVATE KEY-----" and the
end. The same applies if you want to paste the value into the
textbox of the SFTP linked service edit screen.

*I did not try to manually edit the JSON of the Linked Service to explicitly provide a password and this could be workaround for someone to test if they are unable to disable the password.

*I used PuTTYGen to export the PPK to a private key and had the same fingerprint issue too so I just disabled cert validation. Funnily you can use the fingerprint provided by the error and it passes validation so not sure where the bug lies. :-)


text:
Q: Flag your own questions as "for the experience" In the 19 questions I asked on Stack Overflow, I came across a lot of problems.
There are/were so many things I had to look at that I sometimes even forgot what I wanted to ask.
When I remembered my question, it seemed like I asked it totally wrong.
Of course I got some edits, some flag-downs. And whatever vote ups and downs.
Some badges here and there.
And then there's the language barrier, the typos.
Did the guy who asked the question ever go to school?
Does he have the money to buy all these books that should be read first?
Does everyone here have the time to study?
Prejudice: many people do here, yes it gives another +1 or sometimes +4, whatever.
Not everyone here is as skilled as you, and not all will follow what you expect of someone else.
Come on people, do something about that.
Give others the chance to contribute their way and don't give someone this feeling of being guilty of something.
Give the question asker some sort of preview before it goes live.
And when he thinks it is all right, and maybe with some help, post it as a live question.
This would give a more honest credit system.
I can make a much more clear "question", but I refuse; why not simply take some effort and read?
And if you don't understand, simply leave. You don't have to vote. Just let it be.

A: Your question is a bit of a rant IMHO, but I want to pick up one one point (emphasis mine):

Give the question asker some sort of preview before it goes live
And when he thinks it is all right, and maybe with some help, post it
  as a live question.
This would give a more honest credit system.
I can make a much more clear "question" but I refuse, why not simply
  take some effort and read. And if you don't understand, simply leave,
  you dont have to vote, just let it be.

The points you get/lose from votes on Stack Overflow aren't credits - they're reputation, and to me there's a fundamental semantic difference. Reputation is a measure of how much the community trusts you and your questions and answers. You can't buy it: it's won or lost through the quality of your contribution, both in terms of question/answer content, and the effort you're perceived to put in.
Bluntly put, if you can't put a clear question together, or refuse (refuse!?) to do so and would rather put the burden of making your question clear and useful on the rest of the community, then the voting system means that your reputation will correctly reflect your ability and your attitude relative to the reputation of someone who has the ability to do so or can at least be bothered to try.
In that sense, reputation is perfectly named, and works very well.

A:
Give the question asker some sort of preview before go live

We already have this feature, see the preview down below?

You can also edit when you don't notice straight away, such as I did with the quote block in this post - meaning you can possibly salvage your posts. And it's a two-way street: if people are going to take the time to even analyse your problem, not to mention aid in solving it, then they expect you to place some effort in composing it.

A: There is only one think in your question that I feel confident I understand correctly:

i can make a much more clearer "question" but i refuse,why not simply take some efford,and read. And if you dont understand,simply leave,you dont have to vote,just let it.

It doesn't work like that. When you are asking a question, you are asking for help, and the burden to clear up your question is solely up to you. Think about it, someone who reads your question is quite possibly someone who could answer it and help you solve whatever challenge you are facing. Do you want him/her to waste time trying to decipher your post? Wouldn't you much rather prefer it if (s)he invested that time in giving you a great answer?
Also, please don't take down votes personally. It's just how the system works, they say nothing about you personally. We use them to indicate that a post has quality problems, to the best of our ability. Down voted posts get more attention from higher rep users and moderators, and it's quite common for them to step up, clean up and salvage the question. Down votes, in that sense, are a force of good (imho). Please note how another user already cleaned up this question.
Every aspect of the system can be and is abused, from time to time, but generally speaking abuse is quickly identified and resolved, mostly by peer reviewing.


text:
Q: NGINX with NJS for token validation I am trying to use NGINX auth_request and NJS to validate the OAuth token. I also want to validate the token based on the parent request's $request_method, but I am not able to get the original request's method. Instead I am receiving the internal auth request's method and URI.
Requested method is GET /_oauth2_token_introspection

Is there any way to get the original request's $request_method and $request_uri. I referred to https://github.com/nginx/njs-examples/blob/master/README.rst#authorizing-requests-using-auth_request-httpauthorizationauth_request but the "r.method" is always GET even if the original parent request is PUT/POST.
I also tried to send it using headers and read it in NJS code, but it is always "undefined"
location = /_oauth2_token_introspection {
        internal;

        proxy_set_header Content-Length "";
        proxy_pass_request_headers on;
        proxy_set_header        X-Original-URI $request_uri;
        proxy_set_header        X-Original-METHOD $request_method;
        js_content oauth2.introspectAccessToken;
    }

Can someone help me in this regard

A: Using r.variables.request_uri and r.variables.request_method in my NJS script worked for me. For more details, refer https://github.com/nginx/njs/issues/100


text:
Q: How can I know client side which submit button causes submit when the submit button has been triggered? I'm using asp.net form. If a submit button is clicked I check his identity by doing
$('form').submit(function(e)
    {
        // VALIDAZIONE CAMPI LOGIN
        if(e.originalEvent.explicitOriginalTarget.id

But.. It doesn't work if the submit button isn't clicked, but triggered.
In a few words..
How can I know which submit button causes submit when the submit button has been triggered?
<form>
    <input type="submit" name="send1" value="Confirm" />
    <input type="submit" name="send2" value="Confirm2" />

    <input type="button" name="button2" />
</form>

$(function() {
    $('input[name="button2"]').click(function() {
        ('input[name="send2"]').trigger('click');
    });

    $('form').submit(function(e) {
        if (e...
"this is the point where I want to know which of the submit button has been triggered"
    });
});

A: Your solution does work you just havent defined the id attribute on your submit button. If you do that this line of code should work
e.originalEvent.explicitOriginalTarget.id

and if you do not want to use the id attribute and the name instead change it to
e.originalEvent.explicitOriginalTarget.name

see example below
http://jsfiddle.net/VVgYK/


text:
Q: SELECT "NOT IN", INNER JOIN and COUNT in SQL Query I am trying to select which co-ordinates from OA table are NOT found in the CUSTOMER address table.
SELECT DISTINCT
       OA.CO_ORDS
FROM
        CUSTOMER
INNER JOIN
        OA ON customer.address=oa.co_ords
ORDER BY ID ASC;

Returns the co-ordinates which ARE in the customer table. How do I return those that are not in the customer table?
Am I also able to COUNT how many of customers are is in each co-ordinate (The co-ords are not specific and not accurate, this is purely for query testing only)
SELECT DISTINCT
           OA.CO_ORDS
    FROM
            CUSTOMER
    INNER JOIN
            OA ON customer.address=oa.co_ords
    ORDER BY ID ASC;

A: We can use NOT EXISTS to find those co-ordinates which don't appear in the customer table:
SELECT co_ords
FROM oa
WHERE
  NOT EXISTS
    (SELECT 1 FROM customers
      WHERE address = oa.co_ords)
ORDER BY id;

In order to count how many customers belong to a certain co-ordinate, we can use COUNT with GROUP BY, something like this:
SELECT c.address, COUNT(*)
FROM customers c
JOIN oa
  ON c.address = oa.co_ords
GROUP BY c.address;

It could be better to count a specific column instead of *.
It could also be better to use an IN clause instead of JOIN the tables:
SELECT c.address, COUNT(*)
FROM customers c
WHERE address IN
  (SELECT co_ords FROM oa)
GROUP BY c.address;

Such details depend on your exact table structure, you should please try this out or provide more details.

A: You could also do:
SELECT co_ords
FROM   oa
MINUS
SELECT address
FROM   customers;

which can sometimes be faster than doing an anti-join. Note that MINUS does a distinct on the resultset.


text:
Q: Force SDK for make and xcrun version error I am trying to compile with make using c++ on a 10.15 system under Xcode and Command Line Tools 12.2. It keeps wanting to use the 10.15 SDK which does not support arm64. I am thus getting architecture not supported errors.
My make file contains:
SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.0.sdk

and the build command contains:
-isystem /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.0.sdk

Curiously:
xcrun --show-sdk-path
/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk

xcrun --show-sdk-version
xcodebuild: error: SDK "/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk" cannot be located.
xcrun: error: unable to lookup item 'SDKVersion' in SDK '/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk'

Any ideas? There was a clean install on Xcode 11.7 previously and then I copied 12.2 (replacing 11.7). I have verified that the SDK (v15) exists at /Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk and the OSX11 SDK is also in the SDK folder.
A build for x86_64 works fine.


text:
Q: ReferenceError: "getElementsByClassName" is not defined Hi I keep getting an error when I try to run this code, saying:

"getElementsByClassName" is not defined.

function doGet() {
  var html = UrlFetchApp.fetch('http://en.wikipedia.org/wiki/Document_Object_Model').getContentText();
  var doc = XmlService.parse(html);
  var html = doc.getRootElement();
  var menu = getElementsByClassName(html, 'vertical-navbox nowraplinks')[0];
  var output = XmlService.getRawFormat().format(menu);
  return HtmlService.createHtmlOutput(output);
}

Any idea why?

A: Replace
var menu = getElementsByClassName(html, 'vertical-navbox nowraplinks')[0];

With
var menu = doc.getElementsByClassName('vertical-navbox nowraplinks')[0];

A: Add getElementById, getElementsByClassName and getElementsByTagName function definitions from https://sites.google.com/site/scriptsexamples/learn-by-example/parsing-html to the script


text:
Q: NGRX changes subscribing. What's the best way for ngrx store-subscribe in multiple components? I have an angular project with the NGRX store. My NGRX store used by multiple components at the same time (over 7 components).
Should I subscribe for the store changes in all of that components (i think that can lead for loss of performance)? Or I should subscribe only on the TOP component and then pass ngrx changes to child components by @Inputs?

A: The answer really is "it depends", but the "container-presenter" or "smart-dumb" architectural model basically says you have a parent which deals with getting data from the store and passing it to its children via @Inputs. This allows you to separate display logic from business logic, and is what I recommend most of the time.
Commenters have said that there will be no performance issues. That isn't necessarily true, especially as your app becomes more complex.


text:
Q: Why my Bert pre-trained model's loss can't reduce? I tried to write a Bert pre-trained model to fine-tune it for a specific task. Here is my model:
model_path = config.model_path
class BertForCWS(transformers.BertPreTrainedModel):
    def __init__(self,config):
        super(BertForCWS,self).__init__(config)
        self.bert = transformers.BertModel.from_pretrained(model_path,config=config)
        self.softmax = nn.Softmax(dim=-1)
        self.lossCal = nn.CrossEntropyLoss()

    def forward(self,input,input_labels=None,tags=None,tag2vec=None,id2tag=None,attention_mask=None):
        output = self.bert(input,attention_mask=attention_mask)
        sequence = output[0]
        #get out the [cls] and [seq]
        sequence_out = [sen[1:-1] for sen in sequence]
        sequence_out= torch.tensor([item.detach().numpy() for item in sequence_out])
        score = []
        for sen in sequence_out:
            sen_score=[]
            for word in sen:
                word_score = []
                word_temp = word.unsqueeze(0)
                for tag,vec in tag2vec.items():
                    word_score.append(torch.mm(vec,word_temp.transpose(0,1)))
                sen_score.append(word_score)
            score.append(sen_score)
        score = torch.tensor(score)
        score = self.softmax(score)
        loss = 0
        for i in range(len(score)):
            for j in range(len(score[i])):
                loss_temp = 0
                for k in range(len(score[i][j])):
                    if(k == input_labels[i][j]):
                        loss_temp += (1-(score[i][j][k]))* (1-(score[i][j][k]))
                    else :
                        loss_temp += (score[i][j][k]) * (score[i][j][k])
            loss += loss_temp
        return sequence_out,score,loss

I just tried to use the vector which is the output of the Bert to dot product the target label which is also the output of the Bert to get four labels.
here is how I test it with just one input:
test = "我是高"
test_id = tokenizer.encode(test)
print("test_id:",test_id)
test_input = torch.tensor([test_id])
print("test_input:",test_input)
label = [2,2,0]
label = torch.tensor([label])
print(label.size())
for ep in range(200):
    model.train()
    model.zero_grad()
    test_output = model(test_input,input_labels=label,tag2vec=tag2vec)
    loss = test_output[2]
    loss = loss.requires_grad_()
    print(loss)
    optimizer.zero_grad()
    loss.backward()
    torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=1)
    optimizer.step()
    scheduler.step()

I got the loss:
tensor(2., requires_grad=True)
tensor(2., requires_grad=True)
tensor(1.9999, requires_grad=True)
tensor(2., requires_grad=True)
tensor(2., requires_grad=True)
tensor(2.0000, requires_grad=True)
tensor(2.0000, requires_grad=True)
tensor(2., requires_grad=True)
tensor(2.0000, requires_grad=True)
tensor(1.9981, requires_grad=True)
tensor(2.0000, requires_grad=True)
tensor(1.9860, requires_grad=True)
tensor(2.0000, requires_grad=True)
tensor(2., requires_grad=True)
tensor(2., requires_grad=True)
tensor(1.9971, requires_grad=True)
tensor(2., requires_grad=True)
tensor(1.9723, requires_grad=True)
tensor(2., requires_grad=True)
tensor(2.0000, requires_grad=True)

why the loss is always about 2 but never reduce?
Thx a lot!


text:
Q: Create Map with the first and the last character of a String I want to create output: First letter is K and n for second letter, but i dont know how to Map this code
fun main() {
    val text = "Kotlin".getFirstAndLast()

    val firstChar = text["first"]
    val lastChar = text["last"]

    // TODO 2
    println("First letter is $firstChar and $lastChar for second letter")

}

// TODO 1
fun String.getFirstAndLast(): Map<String, Char>{

    return mapOf()
}

A: Since String is an implementation of CharSequence you can use first and last functions from it. And you just want single pair of first to last then you can use Pair instead of Map (just a suggesstion).
fun main() {
    val (firstChar, lastChar) = "Kotlin".getFirstAndLast()

    println("First letter is $firstChar and $lastChar for last letter")
}

fun String.getFirstAndLast(): Pair<Char, Char> =
    first() to last()

And if you really want to use the map here:
fun main() {
   val text = "Kotlin".getFirstAndLast()

   val firstChar = text["first"]
   val lastChar = text["last"]

   println("First letter is $firstChar and $lastChar for last letter")
}

private fun String.getFirstAndLast(): Map<String, Char> =
   mapOf("first" to first(), "last" to last())

A: Simply use first() and last() function from CharSequence interface and build the map using mapOf, then use getValue() on the map to get the corresponding values:
fun main() {
   val text = "Kotlin".getFirstAndLast()

   val firstChar = text.getValue(FIRST_ID)
   val lastChar = text.getValue(LAST_ID)

   // TODO 2
   println("First letter is $firstChar and $lastChar for second letter")
}

// TODO 1
private fun String.getFirstAndLast(): Map<String, Char> {
   val first = this.first()
   val last = this.last()
   return mapOf(FIRST_ID to first, LAST_ID to last)
}

// these are useful to avoid code replication
companion object{
   const val FIRST_ID = "first"
   const val LAST_ID = "last"
}


text:
Q: $\lim\limits_{n\to\infty}\int_0^2 \frac{nx^{n-1}e^{-x^n}}{1+x}dx=1-\lim\limits_{n\to\infty}\int_0^2\frac{e^{-x^n}}{(1+x)^2}dx$ How can I show $\lim\limits_{n\to\infty}\int_0^2 \frac{nx^{n-1}e^{-x^n}}{1+x}dx=1-\lim\limits_{n\to\infty}\int_0^2\frac{e^{-x^n}}{(1+x)^2}dx$?
It is $\frac{d}{dx}x^n=nx^{n-1}$ so I tried to solve it with substitution but this idea did not lead to the goal.

A: Observe that:
$$
\frac{\mathrm{d}}{\mathrm{d}x} e^{-x^n} = -nx^{n-1}e^{-x^n}
$$
so you can integrate by parts to get:
\begin{align*}
\int_0^2 \frac{nx^{n-1}e^{-x^n}}{1 + x} \, \mathrm{d}x &= \left[-\frac{e^{-x^n}}{1 + x}\right]_0^2 - \int_0^2 -\frac{e^{-x^n}}{-(1 + x)^2} \, \mathrm{d}x \\
&= e^{-2^n} - \int_0^2 \frac{e^{-x^n}}{(1 + x)^2} \, \mathrm{d}x
\end{align*}
Letting $n \to \infty$, we have that $\lim_{n \to \infty} e^{-2^n} = 1$.


text:
Q: struts comes under which layer of three tier architecture in real time projects Where do struts come under in three tier architecture in real time projects? Please I need explanation?

A: what is three tire architechture?
In 3-tier, the application logic (or) process lives in the
middle-tier, it is separated from the data and the user
interface. 3-tier systems are more scalable, robust and
flexible. In addition, they can integrate data from
multiple sources. In the three tier architecture, a middle
tier was added between the user system interface client
environment and the database management server environment.
There are a variety of ways of implementing this middle
tier, such as transaction processing monitors, message
servers, or application servers. The middle tier can
perform queuing, application execution, and database
staging. For example, if the middle tier provides queuing,
the client can deliver its request to the middle layer and
disengage because the middle tier will access the data and
return the answer to the client
The most basic type of three tier architecture has a middle
layer consisting of Transaction Processing (TP) monitor
technology. The TP monitor technology is a type of message
queuing, transaction scheduling, and prioritization service
where the client connects to the TP monitor (middle tier)
instead of the database server. The transaction is accepted
by the monitor, which queues it and then takes
responsibility for managing it to completion, thus freeing
up the client.

A: Wrt the architecture of application projects struts is the framework which is generally used for the presentation layer with jsp and servlets being the technologies in the same. Coming to the service layer, EJB is the technology and Spring is the framework and in data access layer, JDBC and JPA are the technologies with Hibernate being the framework.

A: Struts is an entire framework and isn't really going to only be one layer of the typical "three tier" architecture (presentation, application, and data storage).
Struts is going to provide you an MVC framework in Java land. You'll be able to better divide your presentation layer, application layer, and data persistance rather than mingle and mash them all together.


text:
Q: Meteor duplicate insert conflict resolution Is there a design pattern in meteor application to handle multiple clients inserting the same logical record 'simultaneously'?
Specifically I have a scoring type application, and multiple clients could create the initial, basically blank, Score record for an Entrant when the entrant is ready to start.  The appearance of the record is then used to make it available on the page for editing by the officials, incrementing penalty counts and such.
Stages =  new Meteor.Collection("contests");
Entrants = new Meteor.Collection("entrants");
Scores = new Meteor.Collection("scores");

// official picks the next entrant
Scores.insert( stage_id:xxxx, entrant_id:yyyy)

I am happy with the implications of the conflict resolutions of edits to the Score record once it is in the Collection.  I am not sure how to deal with multiple clients trying to insert the Score for the stage_id/entrant_id pair.
In a synchronous app I would tend to use some form of interlocking, or a relational DB key constraint.

A: Well, according to this answer Meteor $upsert flag is still in enhancement list and seems to be added in stable branch after 1.0 release.
So the first way is how it was said to add an unique index:
All the implementation ways are listed here. I would recommend you to use native mongo indexes, not a code implementation.
The optimistic concurrency way is much more complicated according to no transactions in MongoDB.
Here comes my implementation of it(be careful, might be buggy))):
var result_callback = function(_id) {
  // callback to call on successfull insert made
}

var $set = {stage_id: xxxx, entrant_id: xxxx};
var created_at = Date.now().toFixed();
var $insert = _.extend({}, $set, {created_at: created_at});
Scores.insert($insert, function(error, _id) {
  if (error) {
    //handle it
    return;
  }
  var entries = Scores.find($set, {sort: {created_at: -1}}).fetch()
  if (entries.length > 1) {
    var duplicates = entries.splice(0, entries.length - 1);
    var duplicate_ids = _.map(duplicates, function(entry) {
      return entry._id;
    });
    Scores.remove({_id: {$in: duplicate_ids}})
    Scores.update(entries[0]._id, $set, function(error) {
      if (error) {
        // handle it
      } else {
        result_callback(entries[0]._id)
      }
    })
  } else {
    result_callback(_id);
  }
});

Hope this will give you some good ideas)
Sorry, previous version of my answer was completely incorrect.


text:
Q: Defining a type of group I have been tasked with proving the following:

Let $G= H \times K$ be the direct product of two groups $H$ and $K$. Let $\tilde{H}=\{(h, e_{k});h \in H\}$ and $\tilde{K}=\{(e_{H},k); k \in K\}$. Show that $\tilde{H}$ and $\tilde{K}$ are normal subgroups of $G$.

I know how to prove that something is a subgroup, and I believe I know how to show that it is a normal subgroup.
I am mostly confused on what exactly $\tilde{H}$ and $\tilde{K}$ are. Is that just another label for the groups? If the group name has a tilde on it is there some special property about it?
I know I am overthinking this, but it's the only thing I can't seem to figure out. Any help would be greatly appreciated. Thank you!

A: Generally if there is an existing object $X$, and there is a new object that is somehow dependent on $X$, it is convention to give the new object a name conveying this dependency.
Common notations include $f(X), Y_X$ (for some choice of letters not necessarily $f$ or $Y$), $\overline{X}, \widetilde{X},$ and most commonly, $X'$.
In this case, the subgroup being specified is uniquely determined by $H$, so we will write it down as $\tilde{H}$ so we don't forget this relationship.


text:
Q: extend/append a list for saving as geometry in a geodataframe how to use append and extend? and accumulating polygons and points, and then saving it as geometry
pointlist=[]
polylist=[]
for j,i in land:
     pointlist.append(Point(lon[i],lat[j]))
     pointlist.append(list(Point(lon[i],lat[j]).geometry))
     pointlist.extend(Point(lon[i],lat[j]))

     poly=[(lon[i],lat[j+1]),(lon[i+1],lat[j+1]),(lon[i+1],lat[j]),(lon[i],lat[j])]
poly = Polygon(poly)
     polylist.append(poly)
     polylist.append(list(poly.geometry))
     polylist.extend(poly)

shp_1 = gpd.GeoDataFrame(geometry=polylist)
shp_1.set_crs(epsg=4326, inplace=True)
shp_2 = gpd.GeoDataFrame(geometry=pointlist)
shp_2.set_crs(epsg=4326, inplace=True)

an error always appears when creating the geodataframe, it does not recognize the list as geometry
AttributeError: 'list' object has no attribute 'startswith'
or
TypeError("Input must be valid geometry objects: {0}".format(geom))
any ideas?


text:
Q: CompletableFuture.runAsync and thenRunAsync caused the program to block The goal I want to achieve is: serial processing of events with the same id, parallel processing of events with different ids.
After learning a lot of reference materials, I found that using CompletableFuture can accomplish the above goals very well.
However, in an accidental test I found that runAsync and thenRunAsync caused the program to block, and the program did not deadlock at this time. Does anyone know why this is? Below is my code:
public class Demo {
    private static LongAdder longAdder = new LongAdder();

    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            1 + 1 + 2,
            1 + 1 + 2,
            0,
            TimeUnit.SECONDS,
            new SynchronousQueue<>(),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );
    private static ArrayBlockingQueue<Event> arrayBlockingQueue = new ArrayBlockingQueue<>(20000);
    private static ConcurrentHashMap<Integer, CompletableFuture<Void>> dispatch = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        threadPoolExecutor.execute(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    Event event = new Event(0, "message" + i);
                    arrayBlockingQueue.put(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 1000; i++) {
                try {
                    Event event = new Event(1, "message" + i);
                    arrayBlockingQueue.put(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        threadPoolExecutor.execute(() -> {
            while (true) {
                try {
                    Event event = arrayBlockingQueue.poll();
                    if (event == null) {
                        continue;
                    }
                    dispatch.compute(event.getId() % 2, (eventId, completableFuture) ->
                            (completableFuture == null)
                                    ? CompletableFuture.runAsync(() -> {
                                System.out.println(Thread.currentThread().getName() + " <runAsync>: " + event);
                                longAdder.increment();
                                System.out.println("->" + longAdder.longValue());
                            }, threadPoolExecutor)
                                    : completableFuture.thenRunAsync(() -> {
                                        System.out.println(Thread.currentThread().getName() + " <thenRunAsync>: " + event);
                                        longAdder.increment();
                                        System.out.println("->" + longAdder.longValue());
                                    }, threadPoolExecutor));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

A typical result is:
.
.
.
pool-1-thread-3 <thenRunAsync>: Event(id=1, message=message996)
->1049
pool-1-thread-4 <thenRunAsync>: Event(id=1, message=message997)
->1050
pool-1-thread-3 <thenRunAsync>: Event(id=1, message=message998)
->1051
pool-1-thread-4 <thenRunAsync>: Event(id=1, message=message999)
->1052

Explain that only 1052 events were processed, why is this happening?