text:
Q: Does "You little liar" mean "You tell small and not so serious lies" or just "You tell lies in general"? When do we say "You little liar" and "You big liar"?
Do the words "little" and "big" mean what they mean?
"You little liar" mean "You tell small and not so serious lies"
and
"You big liar" mean "You tell big and serious lies"
Or "little liar" and "big liar" just mean "tell lies in general and we don't know if the lies are small or big"
Or the words "little" and "big" are there for emphasis only and not actually tell us if the lie is small or big and "You big liar" is stronger "You little liar"?

A: "You little liar" is in common usage.  It is a compound insult, both calling the person little (e.g. petty) and also calling them a liar.
"You big liar" is not in common usage.  It wouldn't be paired like that, because "big" is not such an insult.
"Big liar" is common; such as "Jim is a big liar".  But it would not be paired with "you".

A: The word "little" here is native colloquial English, in the UK at least, but this specific example is likely to be of, to, and between children, or in a child-like manner.
The little here, is to emphasise the offense perceived, and diminish the person it is addressed to. Similar phrases you might hear in arguments between adults - "You little bastard". "You little thieving shit". "She's a little cow". "You're the little snitch who told the police, aren't you?"
In all of these, "little" is used to belittle the person referenced, and emphasise the feelings of, and word used, by the speaker. It adds a feeling of distain and perhaps disgust or contempt, of the other person being weak, small or otherwise worth mocking and disregarding.
But perhaps because adults less often shout things like "you liar", that's more likely to be something said by, or related to, children, and therefore "You little liar" has a slightly childish petulant feeling that "You little bastard" (for.example) does not.
Update:
See also the Wikipedia article on intensifiers in swearing (AKA expletive attributives), which is almost exactly how 'little" is being used here - note the comment that "Words that are never thought of as offensive can be used in similar ways".

A: "Little" or "big" in that sentence applies to the "You" word in the sentence (the person you're addressing), not the "Lie" word in the sentence.

A: If these phrases are used between adults, it would be pretty likely that the adults are being playful or teasing. Adding "little" or "big" changes the tone from something more harsh as in saying "you liar," which I mostly hear only rarely and as more of a serious accusation.

A: As with much in the English language, it's entirely dependent on context and tone. I would say they are different but not actually in the difference between the definitions of 'little' and 'big'. Best illustrated with a few examples.
If my daughter said "Daddy, the mice ate all the chocolate biscuits again" with a naughty grin on her face, I might say either of those in reply with a grin and it'd be completely benign. Clearly she didn't intend me to believe what she said (that was a running joke between us when one of us had eaten something the other might have liked to have had some of).
In the benign case, the 'little' would be implying that it was a small lie and/or that she was in the habit of telling little lies, perhaps better known as 'fibs', 'little fibber' would be a better phrase as 'fib' implies a non-serious lie and makes it clear to the listener that you don't see this as a serious matter. The implication that she is in the habit of telling little lies itself is a benign one, and not meant to be taken seriously either.
In the benign case, the 'little' doesn't really refer to her being a child or physically small as one wouldn't change it in any way if saying it to one's spouse, for example.
If I said the same "You little liar" without the grin, and a more aggressive or even a fairly neutral tone she would immediately counter with "No Daddy, I didn't really mean it, I ate them, sorry" or similar (or just start crying I guess !), the point being that she would instantly know that I had mistaken her intent to make a joke which she didn't intend I take seriously, even though the words I said were exactly the same.
I would say that 'big' in a friendly context meant exactly the same, that it was a small lie, but British people commonly use 'small' to imply 'large' and vice-versa, it's all in the context and how it's said.
There is some element of familiarity (whether good or bad) implied by the use of either, "big liar" it's not generally a phrase an adult would use to another adult.
If said in reply to a work colleague saying "I didn't touch your wallet", when you just saw them putting it back in your jacket one might use either, but 'little' would be far more usual. In that case the 'little' would be a diminutive slight aimed at them. Not at their physical size or age, but purely as a demeaning slight.
Adding the 'little' in a negative sense is always about adding a barb to the statement, never about the lie being a small one.
One would be unlikely to say "You big liar" to a stranger, as it lacks impact and just sounds childish, it's not something you'd really say to seriously confront somebody whether you knew them or not. You'd simply say "You liar" if you were going to be terse about it or the rather more reserved British "I think you are lying", which might be said in an entirely level, calm manner but have more aplomb as a result.
The 'little' said to a woman doesn't make it specifically sexist as claimed above, it's demeaning to anybody regardless of their genetics when used in a negative context unless the definition of sexist means "Anything negative said to somebody of the opposite sex for any reason", which clearly it isn't.
In all cases, the implication of the big/little is found in the context of the exchange and the vocal inflection and any physical expressions when it is spoken.
I'm a mature well-read native English speaker with a classical education.

A: These would need to be understood in context.
"You little liar" sounds like something you might say to a child who lies, or someone who is childish. "You big liar" sounds like something you might say to someone who tells "big" lies.
Both sound colloquial and childish.  It is extremely rare for adults to tell adults that they are liars in such a casual way. Calling someone a liar is an insult. So use only with caution.

A:
When do we say "You little liar" and "You big liar"?

Neither of these sounds to me like idiomatic English, although it could depend on the context.
"Little" and "big" in these sentences modify "liar." They don't describe the lies. They describe the person telling the lies.
"You big liar" sounds to me like something that an adult native speaker would never say. A child might say it, and if so, it would imply that the person lies a lot or their lies are particularly bad and shameful.
In "You little liar," "little" does not soften or reduce the accusation. It does the opposite.
If an adult man says to an adult woman, "you little liar," then it's an extremely sexist insult. "Little" means she's low in status compared to the man. It infantilizes the woman. The connotation would be very much the same if a woman said it to another woman.
If a man says "you little liar" to another man, then it's an extremely insulting and demeaning thing to say. The implication is that the man being addressed is not a real man. He's like a child, or a cockroach. But I don't think native speakers would actually say this. They would be more likely to say things like "you pathetic little cockroach," or "you disgusting little liar." Without the additional words, "you little liar" comes off more like a childish playground taunt, and it loses its impact.

A: Said in anger at someone who has seriously deceived you, "You little liar!" is not at all childish. It calls them a liar, but also shows contempt for them by the use of "little", which here can mean "petty" or "insignificant".
I would say "You big liar" is more likely to be used playfully towards children, or casually with friends, but it too could be used in anger or frustration, roughly meaning "That's nonsense!", or "You're full of shit!", or other similar phrases with stronger words.
My context is that of a native English speaker in Alberta, Canada.

A: It certainly depends on the context.
To my ears both "little liar" and "big liar" sound colloquial and familiar, things you'd say lovingly to your kids.
Not seriously to someone who's betrayed your trust. For that you'd use other adjectives like "dirty", "ugly" or even the f word. Maybe even without an adjective is stronger "You LIAR!"
I'd leave this as a comment but I don't have yet enough rep!

A: "Little liar " applies the "little" to the person telling the lie. Usually a child or person of much reduced social status to the recipient.
"Big liar" applies the "big" to the nature of the lie. The lie is an exaggeration, or an outrageous claim.
Neither of these are hard rules, just the most common usage.
For example, "big liar" could also be directed at a physically large person bullying a small person, with the "big" applying to the liar's physique, not the nature of the lie.
If you want to refer to the lie itself as being greater, then you would say "you tell big lies". In this context "big" can only refer to the lies, not the person.

A: "You little liar" and "you big liar" are diminutives and/or familiars. They are also an example of the simplified usage that is typically reserved for children, akin to "baby-talk". While the meaning intended can somewhat echo the definitions for "little" and "big", the real point is to diminish, insult, or offend the person who is the point of the remark.
They could be used for rough humor amongst close associates, or associates who have a known (and sufficient) sense of humor to realize the remark was intended as rough (cutting) humor. This would require knowing your audience, or having sufficient confidence in your presentational abilities that you could be confident the audience would realize the remark was intended humorously. This sort of humor is a form of sarcasm.
One could use these, or witness them used, when there is a situation with extreme social differentiation. E.g. An adult addressing a child, or one of a high social class addressing someone they thought to be a lower social class. Using them then would be akin to saying: "I am your superior" and the assumption would be that the accusation of lying should be taken as true. In that case, it is a diminutive, intended to belittle and apply guilt to the accused.
Children, unaware of more sophisticated usage, might use either form. In one aspect - they might use it untruthfully, to insult and diminish the object person. Or, in the case where a lie was observed, it would be used accusatorily, to assign guilt to the object person. In both cases, the usage is diminutive, i.e. meant to diminish the status of the person who is the object of the comment.
As for using "little" or "big" in the phrase, the difference is essentially meaningless, even though the inferences are derived from essentially different definitions. In the case of "a little liar", "little" refers to the personage being addressed. As such, it is an insult or a diminutive - diminishing the status of the addressed. In the case of "a big liar", the reference is to the size, or frequency, of the lies, indicating that the lie is "a whopper", or that the addressed personage lies frequently. These usages are not logically, or grammatically, consistent. Without doing further research into the usage, I will say I think they are idiomatic, non-literal usage. Both usages are intended to accuse and apply guilt to the object person.
In closing, I would not recommend this usage for an ELL. By the time you are familiar enough with your associates, or your audience, to accurately and effectively use these phrases in a social setting, you will be well past "native-speaker" level. As humor, they are of the "cutting" variety, as banter, or sarcasm. Such usage requires a good level of recognition of verbal nuance, body language, and social skills, unless one does not mind socially awkward situations, or if one truly intends to give insult. If one intended to give insult, be aware that such usage risks extreme reactions.

A: Both "big liar" and "little liar" are describing the person and not what they said. Some good examples are the book titles My Brother is a Big Fat Liar and God is a Big Fat Liar, which are humorous books about a child getting angry at someone.  Pretty Little Liars is a book that is literally about attractive teenage girls who've told serious lies, whom we're meant to sympathize with because of their immaturity and powerlessness—the two senses in which they're "little."
Another adjective that's often used with phrases like this is "big old" or "little old."  These emphasize how insignificant and harmless someone is.  In context, it can be affectionate, or insulting.
In contrast, a "little white lie" is small and benign, or a "petty lie" is one about something inconsequential, with the implication that only a compulsive liar would say something like that.  The phrase "minor lie" is more neutral.  If you talk about your political opponents' "Big Lie," you're comparing them to the Nazi propaganda minister, Joseph Goebbels.

A: It's a friendly riposte to someone who speaks a probable untruth. It's not meant to be an insult.

A: I'm surprised that none of the answers so far give the source of this phrase: the poem Matilda, which is a precautionary tale for children, warning against lying, dating from the early part of the twentieth century when such tales were in vogue
. Since it is still under copyright I shan't reproduce it in full here, but it can be found online. Matilda is essentially a retelling of Aesop's The Boy Who Cried Wolf in which a young girl claims her house is burning down before eventually dying in a real blaze. When the real fire occurs, the poem includes this pair of lines:

For every time She shouted 'Fire!'
They only answered 'Little Liar'!

From which the phrase "Little Liar" entered common English usage. Although originally it referred to a child with a poor regard to truth, it is today most often used dismissively to refer to an adult who lies like a child and should know better.


text:
Q: About using Python PyQt5 in pycharm I tried running PyQt5 in pycharm which works initially as i can see an window popping up with a title fixed to it
import sys

from PyQt5 import QtCore
from PyQt5.QtGui import QCursor
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QWidget, QGridLayout

app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("Who wants to be a programmer?")
window.setFixedWidth(1000)

window.show()
sys.exit(app.exec())

if I run this code then a window appears with a title!
But if I try to work on it more and run the code, a window appears on the taskbar but I cannot see or open it!

A: Try sub-classing QWidget or QMainWindow. It will give better controllability.
import sys

from PyQt5 import QtCore
from PyQt5.QtGui import QCursor
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QWidget, QGridLayout

app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("Who wants to be a programmer?")
window.setFixedWidth(1000)

b11=QPushButton(window)

class w2(QWidget):
    def __init__(self):
        super(QWidget,self).__init__()
        self.b1=QPushButton(self)

w_2=w2()
w_2.show()
sys.exit(app.exec())

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I draw a picture like this? How can I draw a picture like the following using Mathematica's graphics primitives?

A: I'm bored:
s = .3 {{1, 0}, {.6, -.6}, {.3, -.2}};
k = {Arrowheads[.13], Thickness[.03], Circle[{0, 0}, .3], Arrow[BezierCurve[{s}]]};
Graphics[{Polygon[Table[.11 {Cos[t + Pi/17], Sin[t + Pi/17]}, {t, 0, 10 Pi, 10 Pi/8}]],
                  Table[Rotate[k, 2 Pi i/8, {0, 0}], {i, 8}]},
                  PlotRange -> .32 {{-1, 1}, {-1, 1}}]

A: Here's a start...
Manipulate[
 Show[poly[n], circ[n]],{{n, 5}, {5, 6, 7, 8, 9, 10}},
 Initialization :> (
  circ[n_] :=
  Graphics[{Arrowheads[.13], Thickness[.025], Circle[{0, 0}, 3],
  Table[Arrow[
    BezierCurve[{3 {Cos@(t + 1.6 \[Pi]/n), Sin@(t + 1.6 \[Pi]/n)},
       2 {Cos@(t + .4 \[Pi]/n), Sin@(t + .4 \[Pi]/n)},
      1 {Cos@t, Sin@t}}]], {t, 0, 2 \[Pi], 2 \[Pi]/n}]}];
 poly[n_] :=
  Graphics[
  Polygon[(4/5) Partition[
    Flatten@Table[{{Cos@t,
        Sin@t}, (2/3) {Cos@(t + \[Pi]/n), Sin@(t + \[Pi]/n)}}, {t,
        0, 2 \[Pi], 2 \[Pi]/n}], 2]]];)]


text:
Q: why is this css transistion menu not working in Chrome - horizontal menu? I have spent a few hours wondering what is wrong and fiddling with answers i found online but could not fix it. I am able to display the horizontal menu, but color of li element wont change on hover.
Please Help . I have just started working on a new website project and am a noob.
Here a snippet:

ul{
       line-style-type:none;
       overflow:hidden;
       background-color:#333;
       margin:0;
       padding:0px
       }

    li{
      float:right;
      }
    li a{
     display:inline-block;
     color:white;
     padding:10px 10px;
     text-decoration:none;
     text-align:center;

        display:block;
    }
    li a: hover{
     background-color:#223;
     display:block;
     position:relative;
     }

About Me

Blog

Contact Me

A: If you wanted a transition, and I'm assuming this is only for background-color, then you need to define the transition on the li a selector.
However, your :hover isn't working b/c you have a :hover, but needs to be a:hover
Here's a fiddle

Test 1

Test 2

Test 3

ul {
  list-style:none;  /* changed this as well, was incorrect */
  overflow: hidden;
  background-color: #333;
  margin: 0;
  padding: 0px;
}

li {
  float: right;
}

li a {
  /* you can also use "all", rather than specifying a specific transition,
     however, when it's not needed, it's best to specify the actual
     CSS to hit. If you have more than 1 transtion, you can break it up by
     using a comma, such as this:
     transition: background-color .2s ease-in, color .2s ease-in;
     Also do not forget to use prefixes for browsers (older), such as
     -webkit-transition
     -moz-transition
     -ms-transition
     -o-transition
  */
  transition: background-color .2s ease-in;
  display: inline-block;
  color: white;
  padding: 10px 10px;
  text-decoration: none;
  text-align: center;
  display: block;
}

li a:hover {
  background-color: #223;
  display: block;
  position: relative;
}

A: Please provide us the Html code too. But from my point of view the problem might be here
li { float: right; }

should be
li { float: left; }

and then
li a: hover{
    background-color:#223;
    display:block;
    position:relative;
}

should be li a:hover without a blank space between a and :hover.
Hope this helps.

A: Replace your hover class with this:
li a:hover{
            background-color:#223;
            display:block;
            position:relative;
         }

I just remove the space between a and hover


text:
Q: connecting with JBOSS EAP to H2 Console (Red Hat - Ticketmonster tutorial ) I'm doing the Red Hat TicketMonster tutorial but got stuck pretty fast.
You can find the tutorial (pdf) here
The problem:
At first everything worked just fine. I managed to deploy the app on localhost, could see the tables using h2console etc.
But when I decided to continue later, I couldn't enter the console like I did before. So I installed the H2 database engine and am able to at least log in but now my tables are gone.
I didn't change anything in the -ds.xml file (just added some Entities in the model package) and use the same url in the database engine.
Maybe the database is locked?
<connection-url>jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1</connection-url>

I don't know what went wrong and what to do next.

A: Never mind, found the reason why the connection to h2 console didn't work.
Apparently I didn't deploy the h2console.war in the right folder after changing the runtime server (to Wildfly).


text:
Q: Proof that a is an eigen value of p(T) if and only if a=p(lambda) for some eigenvalue lambda of T $\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\F}{\mathbb{F}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\LM}{\mathcal{L}}$
Question: Suppose $\F = \C, T \in \LM(V), p \in \mathcal{P}(\C))$ and $a \in \C$. Prove that $a$ is an eigenvalue of $p(T)$ if and only if $a = p(\lambda)$ for some eigenvalue $\lambda$
of $T$.
My proof so far:
Suppose $a=p(\lambda)$ for some eigenvalue $\lambda$ of $T$ and $v \in V$. Then, $p(T)v=a_0Iv+a_1Tv+\cdots+a_nT^nv$. Since $a=p(\lambda)$,
$a=a_0+a_1\lambda+\cdots+a_n\lambda^n$ for $a_0,\ldots,a_n \in \C$. Then
\begin{align*}
& (p(T) - aI)v=p(T)v-av\\
= {}& a_0Iv+a_1Tv+\cdots+a_nT^nv-(a_0+\cdots+a_n\lambda^n)v\\
= {} & (a_0Iv-a_0v)+(a_1Tv-a_1\lambda v)+\cdots+(a_nT^nv-a_n\lambda^nv)\\
= {}& 0
\end{align*}
Therefore, $a$ is an eigenvalue of $p(T)$.
Suppose $a$ is an eigenvalue of $p(T)$ and $v \in V$. Then
\begin{align}
0 & = (p(T) - aI)v \\
& =(a_0I+a_1T+\cdots+a_nT^n-aI)v \\
& =(a_0I+a_1T+\cdots+a_nT^n-aI)v
\end{align}
By subtracting from the right side,
\begin{align*}
a_0v+a_1Tv+\cdots+a_nT^nv & =av\\
(a_0-a)v+a_1Tv+\cdots+a_nT^nv & =0
\end{align*}
I see that $av$ is a multiple of $v$, which is the operand of $(p(T)-aI)$, so $(p(T)-aI)$ is invariant. Is this sufficient to show that an eigenvalue exists?

A: Your first direction is correct, but has a confusing typo: You started by saying "Suppose $p(a)=\lambda$" when you meant to say "Suppose $a=p(\lambda)$."
In your second direction, you can do this:  Suppose $a$ is an eigenvalue of $p(T)$ with eigenvector $v$.  Then indeed (as you started):
$(p(T) - aI)v = 0$.
However, you need to do more than this. Note that you can always factor polynomials over their complex roots.  So for the polynomial $p(x)-a$, there is a number $c \neq 0$ and roots $r_1, r_2, \ldots, r_n$ such that:
$p(x)-a = c(x-r_1)(x-r_2)...(x-r_n)$.
In particular, $p(r_i)-a=0$ for all roots $r_i$. Applying this polynomial form to the equation $(p(T)-aI)v=0$ gives:
$(p(T)-aI)v = c(T-r_1I)(T-r_2I)…(T-r_nI)v = 0$.
Now you just need to show that one of the roots $r_i$ is an eigenvalue for $T$ (with eigenvector possibly different from $v$). This is similar to the standard proof that $T$ has an eigenvalue over the complex numbers, such as that given in the Sheldon Axler textbook Linear Algebra Done Right.


text:
Q: Use one entity with multiple databases in spring-data-jpa Suppose, i have two database "DB1" and "DB2", both databases have same table called "A".
I have created two entityManagerFactories and two datasources for these databases.

*

*How can i create only one entity "A", and specify it in both entityManagerfactories?

*Is it possible to create two jparepositories using this entity and mention the package name in @EnableJpaRepositories along with entityMangerRef?

I tried this, but i am getting data only from a database. I am using spring-data-jpa.


text:
Q: In FosUserBundle, get old and new password of a User to duplicate password reset on a third-party database I'm using the FosUserBundle to manage my web users, and also through an API to log in a mobile app.
I have a resetPasswordAction API method to enable password reset within the app.
But I'm also using a third-party database for some of the users which allows me to manage their roles, so these users have to register/log in with their third-party credentials. Then I copy the data in the FosUser database.
Now, if they want to reset their password, obviously it'll be done on my FosUser database with my API method, but not on the third-party one. What I want to achieve is catch the email of the User, its old password, and its new password, so that I can use the third-party API method to also update its password on the third-party database.
I've tried creating an Event Listener, but RESETTING_RESET_COMPLETED receives the FilterUserResponseEvent, so I can only catch only the email and the new password.
I a bit stuck here, so if anyone has a clue on how I can manage this, that would be a great help!
Thanks.

A: You might want to persist the old password on your User entity (that extends the FOS User entity) as a field.
/**
 * @var string
 *
 * @ORM\Column(name="old_password", type="string")
 */
private $oldPassword;

You'll have to create a command to migrate all users current password to the new "old_password" column in your database.
This also gets tricky because you'll have to populate that entity field every time the User changes passwords and also populate it when the user is created. This adds a lot of complexity to any controllers that handle the user interaction.
Then in your event listener, you'll have to get that old password from the User entity, do your API posts, and if all that goes without exception, then update the database and set "old_password" to current password.


text:
Q: In select mortality tables (assuming a 3-year select period), why is $\ell_{x+3}$ written without braces around the x?
I am currently referring to Life Contingencies by C. W. Jordan, which gives the following reason:
"The select symbol $[x]$ is not used in the $\ell_{x+3}$ column, since the effects of selection do not carry over into the fourth year, and $\ell_{x+3}$ is therefore equally representative of the number of survivors of the $\ell_{[x]}$ lives insured 3 years previously, the $\ell_{[x-1]}$ lives insured 4 years previously, and so on, and this column constitutes an ultimate mortality table."
However, I do not understand the author's reasoning (it's not just a specific part, I am really quite confused about the whole thing). Could someone give me a detailed walk-through of the reasoning used by the author?

A: It is assumed for this particular table that the effects of selection "wear out" after two years. That is, the mortality of a person who joined 3 or more years ago is determined only by their age and not by how long ago they started (provided it is greater than 2 years).
So x+3 is not select and therefore doesn't get the square brackets.
It could be for a particular population that selection effects last three years then you would see [x]+3 but x+4

A: To understand the select and ultimate life table, it is helpful to think of it in the context of an example in which lives follow one survival model for some specified amount of time, and then after that time elapses, they follow a different survival model.
To this end, one such example is when a life insurance policy is newly underwritten.  In such a case, the insured might be at higher risk of death for some number of years--this is not because the act of insuring them puts them at increased risk, but because the application for insurance suggests that the insured might have reason to believe they are at risk and need coverage.  After a few years, though, this selection effect "wears off."
If the select period did not apply, we would have the traditional life table that models the survivorship of the cohort.  However, to account for selection, we must expand the life table at each age at enrollment for each year (or period) in which the selection effect occurs.  In the table you provided, the selection effect has a duration of $3$ years, so there are three additional columns to describe the survivorship in the select period.  The notation $l_{[x]}$ indicates the number of lives surviving if selected at age $x$.  Then, by age $x+3$, the select period has ended, and the number of survivors is given by $l_{x+3}$.  Subsequently, you read the table down the final column.
Here's how you'd calculate survival probabilities for your table.  Suppose $[61]$ is underwritten for a life insurance policy.  What is the probability that $[61]$ survives $5$ years?  You would simply calculate $$_{5}p_{[61]} = \frac{l_{66}}{l_{[61]}} = \frac{65000}{78000} = 0.833333.$$  What is the probability that $[61]$ survives to $63$?  This is $$_{2}p_{[61]} = \frac{l_{[61]+2}}{l_{[61]}} = \frac{73000}{78000} = 0.935897.$$  Notice in both cases we have $l_{[61]}$ in the denominator, but in the first case, we can just write $l_{66}$ whereas in the second, we can neither write $l_{63} = 74000$ nor $l_{[63]} = 71000$, because those don't mean the same thing as $l_{[61]+2}$; the first represents the ultimate number living at age $63$, either because they were $60$ at selection and survived three years, or they were younger than $60$, survived the select period, and however many additional years to reach $60$.  The second represents the number of survivors aged $63$ in the cohort when selected--that is to say, when unwritten for insurance.  But $l_{[61]+2}$ represents the number alive who were selected at age $61$ and survived $2$ years of the select period.
For a slightly more sophisticated example, suppose as before $[61]$ is underwritten.  Given that they have survived the first year, what is the probability that they will survive another $3$ years?  Well, this is simply $$_{3}p_{[61]+1} = \frac{l_{65}}{l_{[61]+1}} = \frac{67000}{76000} = 0.881579.$$
But back to your specific question:  why, if the select period is only $3$ years, shouldn't there be a column for $l_{[x]+3}$?  As you can see from our earlier computations, we were basically reading the table along rows until the final column, and then read down that column, to follow a life that was selected at age $[x]$.  If you had a column for $[x]+3$, you couldn't read down that column because, like $l_{[x]}$, $l_{[x]+1}$, and $l_{[x]+2}$, we don't read down those columns to model the survivorship of $[x]$.  We have to read across until we reach an ultimate column.  Now, that is not to say you couldn't insert a column with $l_{[x]+3}$ there, but then what is $l_{x+4}$?  If your select period was only $3$ years, you'd have to make $l_{x+4} = l_{[x+1]+3}$, in which case that $l_{x+4}$ column is redundant.
To make it absolutely clear why that's the case, suppose we had a select period of only one year.  Then why would you need three columns to describe a model where survivorship is modified only in the first year of selection?


text:
Q: Gradient from svg to png not applied I had one SVG file, I changed it so it has a gradient.
Then I convert the SVG to png, but the gradient change is not in the new png.
I tried to convert SVG to png with an internet converter, but it still doesn't pass the gradient.
When I open svg file with Illustrator I cannot see the gradient. When the preview of the SVG file is shown I can see the gradient.
I get this error: org.apache.batik.bridge.BridgeException The attribute d of the element <path> is invalid.
My question is:
If anyone has faced a similar error or has an idea about how to fix this, could you give me some advice?
Here's my converter:
public void svgToPng() throws MalformedURLException {

    String svg= "/Users/userName/svg/";
    File folder = new File(svg);

    for (File fileEntry : folder.listFiles()) {

        String[] codigoAux = fileEntry.getName().split("\\.");

        if (codigoAux[0].isEmpty()) {

            LOGGER.debug("Name of file is empty");

        } else {
            try {

                PNGTranscoder transcoder = new PNGTranscoder();

                String svgURI = fileEntry.toURI().toURL().toString();
                TranscoderInput input = new TranscoderInput(svgURI);

                String outputPath = "/Users/userName/png/";

                OutputStream ostream = new FileOutputStream(outputPath + codigoAux[0] + ".png");
                TranscoderOutput output = new TranscoderOutput(ostream);

                transcoder.transcode(input, output);

                ostream.flush();
                ostream.close();

            }catch (TranscoderException ex) {

                LOGGER.error(ex);

            } catch (IOException ex) {

                LOGGER.error(ex);

            }

        }

    }

}

Here's my element path in my svg:
<path fill="#D1E9FD" d="M7095.36-13.684c800.463,818.206,1299.013,1969.505,1299.013,3244.739             c0,633.732-123.293,1236.744-345.429,1783.602H305.852C83.733,4467.799-39.558,3864.79-39.558,3231.055             c0-1275.234,498.537-2426.534,1299.021-3244.739H7095.36z"></path>

Here's my gradient in my SVG:
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
    <stop offset="0%" style="stop-color:#FFFFFF;stop-opacity:1"></stop>
    <stop offset="100%" style="stop-color:#FFE69C;stop-opacity:1"></stop>
</linearGradient>

And here's where I make a reference to the gradient:
<style>        #Countries path, #Countries polygon {
fill: url(#grad1);        filter: url(#dropshadow);        }
</style>

I expect the output to be a PNG image with the gradient that I have in the preview of my SVG file.


text:
Q: How to make input box a certain length? So I have this HTML/CSS,

input {
  box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
  height: 35px;
  width: 400px;
  overflow: hidden;
  border: none;
  padding-left: 10px;
  background-color: rgba(240, 240, 240);
  margin-right: 30px;
  overflow: hidden;
}
label {
  margin: 30px;
}

Mob Tag = <input type="text" id="mobTag" placeholder="My Mob" name="mobTag">

Chest Name = <input type="text" id="chestName" placeholder="empty" name="chestName">

and as you can see, the labels are nicely aligned, but I'm trying to get the end of the inputs to align as well. I tried increasing the width, hoping the margin-right would hide the overflow, but it just pushes the labels up a line.
Can anyone help?

A: Use flex:

p {width:50%; margin:1rem auto}

input {
  box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
  height: 35px;
  border: none;
  margin-left:.5rem;
  padding-left: 10px;
  background-color: rgba(240, 240, 240);
  flex:1 0;
}

label {
  display: flex;
  align-items:center;
  margin: 30px;
}

strong {
  flex: 0 0 auto;
  margin-right:.5rem;
}

Mob Tag = <input type="text" id="mobTag" placeholder="My Mob" name="mobTag">

Chest Name = <input type="text" id="chestName" placeholder="empty" name="chestName">


text:
Q: Is there a simple way to split ONE list into X sublists? I have a list of random size greater than 20k. How can I split them into sublists where each sublist will have equal lengths or equal length + 1(for the odd lists?)?
Since it is random size, implementation should not have any defined size right?
I am currently looking at this template:
public static <T> List<List<T>> split(List<T> list, int size) throws NullPointerException, IllegalArgumentException {
        if (list == null) {
            throw new NullPointerException("The list parameter is null.");
        }
        if (size <= 0) {
            throw new IllegalArgumentException("The size parameter must be more than 0.");
        }

        int num = list.size() / size;
        int mod = list.size() % size;
        List<List<T>> ret = new ArrayList<List<T>>(mod > 0 ? num + 1 : num);
        for (int i = 0; i < num; i++) {
            ret.add(list.subList(i * size, (i + 1) * size));
        }
        if (mod > 0) {
            ret.add(list.subList(num * size, list.size()));
        }
        return ret;
    }

This one is creating sublists based on known sublist size then creating the X sublists.
The result I need is to pass a LIST and a target sublistSize. So I pass a list with size 26346 records and sublistSize 5. I would end up with 5 sublists. the first four sublist would have 5269 records, and the last(5th) sublist would have 5270 records.

A: How about this? This will do what you said (if the order of the items is not important), create 'size' sublists, and it will distribute all items to the new lists.
public static <T> List<List<T>> split(List<T> list, int size)
        throws NullPointerException, IllegalArgumentException {
    if (list == null) {
        throw new NullPointerException("The list parameter is null.");
    }

    if (size <= 0) {
        throw new IllegalArgumentException(
                "The size parameter must be more than 0.");
    }

    List<List<T>> result = new ArrayList<List<T>>(size);

    for (int i = 0; i < size; i++) {
        result.add(new ArrayList<T>());
    }

    int index = 0;

    for (T t : list) {
        result.get(index).add(t);
        index = (index + 1) % size;
    }

    return result;
}

A: This is an improvement for Hamsar's aproch using the sublist method for optimization.
   public static <T> List<List<T>> splitListToSubLists(List<T> parentList, int subListSize) {
  List<List<T>> subLists = new ArrayList<List<T>>();
  if (subListSize > parentList.size()) {
     subLists.add(parentList);
  } else {
     int remainingElements = parentList.size();
     int startIndex = 0;
     int endIndex = subListSize;
     do {
        List<T> subList = parentList.subList(startIndex, endIndex);
        subLists.add(subList);
        startIndex = endIndex;
        if (remainingElements - subListSize >= subListSize) {
           endIndex = startIndex + subListSize;
        } else {
           endIndex = startIndex + remainingElements - subList.size();
        }
        remainingElements -= subList.size();
     } while (remainingElements > 0);

  }
  return subLists;

}

A: If you want to maintain the order of the large list in each of the sub-lists, try the following:
public static <T> List<List<T>> split(List<T> list, int numberOfLists) {
    if (list == null) {
        throw new NullPointerException("The list parameter is null.");
    }
    if (numberOfLists <= 0) {
        throw new IllegalArgumentException(
                "The number of lists parameter must be more than 0.");
    }

    int sizeOfSubList = list.size() / numberOfLists + 1;
    int remainder = list.size() % numberOfLists;

    List<List<T>> subLists = new ArrayList<List<T>>(numberOfLists);

    // if there is a remainder, let the first sub-lists have one length...
    for (int i = 0; i < numberOfLists - remainder; i++) {
        subLists.add(list.subList(i*sizeOfSubList, (i+1)*sizeOfSubList));
    }

    // ... the remaining sub-lists will have -1 size than the first.
    sizeOfSubList--;
    for (int i = numberOfLists - remainder; i < numberOfLists; i++) {
        subLists.add(list.subList(i*sizeOfSubList, (i+1)*sizeOfSubList));
    }

    return subLists;
}

A: This will split the main list into sublist based on the required size of the sublist .
public List splitListToSubList(List<Object> parentList, int childListSize) {
    List<List<Object>> childList = new ArrayList<List<Object>>();
    List<Object> tempList = new ArrayList<Object>();
    int count = 0;
    if (parentList != null) {
        for (Object obj : parentList) {
            if (count < childListSize) {
                count = count + 1;
                tempList.add(obj);
            } else {
                childList.add(tempList);
                tempList = new ArrayList<Object>();
                tempList.add(obj);
                count = 1;
            }

        }
        if (tempList.size() < childListSize) {
            childList.add(tempList);
        }
    }
    return childList;
}

}

A: try this for mantaining the order of the main list in the sublists.
public <T> List<List<T>> orderedSplit(List<T> list, int lists) throws NullPointerException, IllegalArgumentException {
    if (list == null) {
        throw new NullPointerException("La lista es nula.");
    }

    if (lists <= 0) {
        throw new IllegalArgumentException("La lista debe divirse en una cantidad mayor a 0.");
    }

    if(list.size() < lists){
        throw new IllegalArgumentException("El tamaño de la lista no es suficiente para esa distribución.");
    }

    List<List<T>> result = new ArrayList<List<T>>(lists);

    int listsSize = list.size() / lists;
    int remainder = list.size() % lists;

    int index = 0;
    int remainderAccess = 0;
    int from = index*listsSize + remainderAccess;
    int to = (index+1)*listsSize + remainderAccess;

    while(lists > index){

        if(remainder != 0){
            result.add(list.subList(from, to+1));
            remainder--;
            remainderAccess++;
        }else {
            result.add(list.subList(from, to));
        }

        index++;
        from = index*listsSize + remainderAccess;
        to = (index+1)*listsSize + remainderAccess;
    }

    return result;
}


text:
Q: Polar Form of the 2d DFT I know that there is a complex and a polar formulation of the Fourier series. The polar form can be transformed to the real valued Fourier series for the 1D case:
$$f(x)=a_{0}+\sum_{k}^{\infty} a_{k}\cos(k\omega_{0}x)+b_{k} \sin(k\omega_{0}x)= d_{0}+\sum_{k=1}^{\infty}d_{k}cos(k\omega_{0}x-\phi_{k})$$
with $\omega_{0} := 2\pi /T$ and
$$d_{0}=a_{0}, d_k:=\sqrt{a^2_k +b^2_k}\quad\text{as magnitude and the phase}\quad\phi_{k}:=\arctan{\frac{b_{k}}{a_{k}}}$$
, which can be calculated as follows for a dft:
$$d_k \cos\phi_k = \sqrt{2/N}\sum^{N}_{j=1}z_j \cos(2\pi k(j-1)/N)$$
$$d_k \sin\phi_k = \sqrt{2/N}\sum^{N}_{j=1}z_j \sin(2\pi k(j-1)/N)$$
It's essentially taking the real and the imaginary parts separately and using trigonometric relationships to calculate the coefficients.
Now for the 2D case, I have seen this approach(in a paper):
$$d_k \cos\phi_k = 1/N\sum^{N}_{j=1}\left(x_j\cos\left(\frac{2\pi (k+1)(j-1)}{N}\right)-y_j\sin\left(\frac{2\pi (k+1)(j-1)}{N}\right)\right)$$
$$d_k \sin\phi_k = 1/N\sum^{N}_{j=1}\left(x_j\sin\left(\frac{2\pi (k+1)(j-1)}{N}\right)+y_j\cos\left(\frac{2\pi (k+1)(j-1)}{N}\right)\right)$$
I just do not understand, where it is coming from. I also didn't encounter any book on DFT, which explains this. There were rare ones which mentioned at least the polar formulation.
I know how the complex case works. Does someone know how the above formulas for the 2d and 1d case are derived or any literature about the polar form?
And maybe how the treatment with just sin and cos work? I am not afraid of complex numbers, but I feel like I want to understand this way of doing it too.
I would really appreciate any information.


text:
Q: Cannot stream mp3 in Android. Error: 'Unable to play this type of audio file' I am using a WebViewClient to display a list of .mp3 files. After clicking on an mp3 file url, I want Android to pop up the 'Complete Action Using' menu that allows the user to select which Media Player to stream the mp3 from.
With the following code I am able to launch the 'Complete Action Using' menu and am able to select a media player. Unfortunately, every single media player spits out their own version of the "unable to play file" error message.
Do you see any errors in the following code? Thank you!
private class MapWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".mp3")) {

            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            File file = null;
            try {
                file = new File(url);
                intent.setDataAndType(Uri.fromFile(file), "audio/*");
                startActivity(intent);
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

            return true;
        } else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }


text:
Q: JWT access token based on user in Salesforce Have a scenario where I need to get the access token based on the user details.
There are few users configured in the connected app and there is already logic to retrieve the access tokens for the default users.
How can I pass the user name dynamically to the jwtUsername attribute and get the access token based on the user name?


text:
Q: serde_json::from_str error where string from file extern crate serde_json;

use serde_json::Value;

use std::fs::File;
use std::io::prelude::*;

fn main() {
    let filepath = "./map/test/anhui.txt";
    match File::open(filepath) {
        Err(why) => println!("Open file failed : {:?}", why.kind()),
        Ok(mut file) => {
            let mut content: String = String::new();
            file.read_to_string(&mut content);
            println!("{}", &mut content);
            serde_json::from_str(&mut content);
        }
    }
}

Error info:
error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [--explain E0282]
  --> src/main.rs:16:17
   |>
16 |>                 serde_json::from_str(&mut content);
   |>                 ^^^^^^^^^^^^^^^^^^^^

A: To fix it, you need to tell the compiler what type you are expecting as the result of serde_json::from_str. So you can change the line
serde_json::from_str(&mut content);

to
serde_json::from_str::<Value>(&mut content);

The reason you need to specify the type is becasue serde_json::from_str is a generic function which needs a type to be instantiated to a concrete function. Usually rustc takes care of it, and infer the type you want to use, but in this case, there is not enough information to let compiler infer it for you because the type is only referred in the result of the function while the result is never used in the given code.
You may also want to use the result of the from_str expression, otherwise the function call does nothing. If you specify the type when using a let binding, the compiler will be able to infer the type, like this:
let result: Value = serde_json::from_str(&mut content);


text:
Q: Undefined reference to several functions in libcsfml-window on Solus OS After building CSFML from the latest sources, and setting it up in Code::Blocks, I am getting an undefined reference error when I attempt to build my project. I've linked all of the CSFML libraries in Code::Blocks. I am running the latest version of Solus Budgie and Code::Blocks.
This is the relevant error:
../../../../usr/local/lib/libcsfml-window.so: undefined reference to `sf::String::operator std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >() const'

Here is where the error appears to originate, as this is a c-based project and it is attempting to build using g++:
g++ -L/home/riley/Downloads/CSFML-2.2-linux-gcc-64-bit/CSFML-2.2/lib -o bin/Release/Asterisk obj/Release/display.o obj/Release/entity.o obj/Release/levels.o obj/Release/main.o obj/Release/map.o obj/Release/quest.o obj/Release/terrain.o  -s  /usr/local/lib/libcsfml-audio.so /usr/local/lib/libcsfml-graphics.so /usr/local/lib/libcsfml-network.so /usr/local/lib/libcsfml-system.so /usr/local/lib/libcsfml-window.so -lsfml-graphics

Based on what I know, it appears that there are several functions and other things that are referenced in libcsfml-window that I don't have installed. How can I go about fixing this error? I'm not sure what I don't have installed, as I have all of the standard libraries installed, as well as SFML.


text:
Q: increase number in Class CSS automatically I want to make the following happen in:
There is a for loop generating images of a list. I still want to be capable of styling indiviual images with CSS, so I need to generate a unique Class for each element of the list.
Is there a way to generate a string like ("a") plus the generated number so that the result is a1, a2, a3, a4...(a.id)?
Lets say the list is 4 elements long.

    class="a + {{ chair.id }}"

A: You could ignore the plus + sign and append the value directly.

  ...

If for instance the chair.id values are 1, 2, 3,... then the rendered list would look like

...

...

...

...

A: You can use ngClass
Although, in general, I don't recommend doing it like that.
You can use CSS nth-child for use case like that.
If you prefer doing it with ngClass the syntax is that

  ...


text:
Q: Multiple colors drawn for NSBezierPath in cycle I have following code in func draw(_ dirtyRect: NSRect) method but all the lines are drawn with the same color even if it should be randomized. I read that it may has something to do with fps but is there any way how to draw it multicolored?
Thanks for any hint.
for y in 1...3 {
    for x in 1...20 {
        switch arc4random_uniform(5) {
            case 0:
                color = NSColor.red
            case 1:
                color = NSColor.purple
            case 2:
                color = NSColor.green
            case 3:
                color = NSColor.blue
            case 4:
                color = NSColor.yellow
            default:
                color = NSColor.yellow
            }
            point.move(to: NSPoint(x: x*10, y: y))
            point.line(to: NSPoint(x: x*10, y: y+100))
            color.setStroke()
            point.stroke()
     }
}

A: Finally I found the solution or at least workaround - I put declaration of
   let point = NSBezierPath()

into  inner "x" loop and it works as expected. Not sure if it`s the mos efficient  and proper solution so any further suggestions are welcome.


text:
Q: how to update an element of a specific div? I am creating a web page where the user can select an item and the information is displayed. I have two buttons (btnBuy0 and btnBuy1). When BtnBuy0 is clicked, the details of the items showing quantity of 1 is displayed. Again, if btnBuy1 is clicked, the details of that item should be appended below details of item0 but I can't get that to work. Instead the details of item0 is replaced by details of item1.
$("#btnBuy0").click(function() {
    if (!sessionStorage['quantity0']) {
        sessionStorage['quantity0'] = 1;
        $("#dropbox").append('
'+ teddy[0].desc + ", Price £"
        + teddy[0].price + ", Quantity: " + sessionStorage.getItem('quantity0') + "<button id = 'btnRemove0'>Remove</button>

");
        updateBasket();
        sessionStorage["total0"] = parseInt(sessionStorage.getItem('quantity0')) * teddy[0].price;
        updateSubtotal();
    } else {
        sessionStorage['quantity0']++;
        $("#dropbox").html('
' + teddy[0].desc + ", Price £"
        + teddy[0].price + ", Quantity: " + sessionStorage.getItem('quantity0') + "<button id = 'btnRemove0'>Remove</button>

");
        updateBasket();
        sessionStorage["total0"] = parseInt(sessionStorage.getItem('quantity0')) * teddy[0].price;
        updateSubtotal();

    }

    if (Modernizr.sessionstorage) {  // check if the browser supports sessionStorage
        myids.push(teddy[0].partnum); // add the current username to the myids array
        sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
    } else {
     // use cookies instead of sessionStorage
    }
});

$("#btnBuy1").click(function() {
    if (!sessionStorage['quantity1']) {
        sessionStorage['quantity1']=1;
        $("#dropbox").append('
' + teddy[1].desc + ", Price £"
         + teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button>

");
         updateBasket();
        sessionStorage["total1"] = parseInt(sessionStorage.getItem('quantity1')) * teddy[1].price;
        updateSubtotal();
    } else {
        sessionStorage['quantity1']++;
        $("#dropbox").html('
' + teddy[1].desc + ", Price £"
         + teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button>

");
         updateBasket();
        sessionStorage["total1"] = parseInt(sessionStorage.getItem('quantity1')) * teddy[1].price;
        updateSubtotal();
    }

    if (Modernizr.sessionstorage) {  // check if the browser supports sessionStorage
        myids.push(teddy[1].partnum); // add the current username to the myids array
        sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
    } else {
     // use cookies instead of sessionStorage
    }
});

A: Your code repeats itself almost exactly in the both cases. You should write it once, put it a named function, passing in 1 or 0 depending on the clicked button, and use a variable inside to work out all the code. Something like this:
function clicked(whichOne) {
    yolo = 'quantity' + whichOne; //Here I just declare your most used variable to make the code easier to read.

    if(!sessionStorage[yolo]) {
        sessionStorage[yolo] = 1;
    } else {
        sessionStorage[yolo]++;
    }

    //Notice that using .html() will always replace what's inside the #dropbox.
    //If you want to add to what is already inside, use .append() instead.
    $("#dropbox").html('
'+ teddy[whichOne].desc + ", Price £" + teddy[whichOne].price + ", Quantity: " + sessionStorage.getItem(yolo) + "<button id = 'btnRemove"+ whichOne +"'>Remove</button>

");

    updateBasket();

    sessionStorage["total" + whichOne] = parseInt(sessionStorage.getItem(yolo)) * teddy[whichOne].price;

    updateSubtotal();
}

$("#btnBuy0").click(function() {
    clicked(0);
});

$("#btnBuy1").click(function() {
    clicked(1);
});

You could probably reduce this even more. This is just an example and you'll need to adapt it to fit your situation.
Btw here's a fiddle you can play around with to get a better idea: http://jsfiddle.net/ArzSs/2/


text:
Q: Error, int given when trying to map a Doctrine query result to a DTO I have this configuration:
Agent entity class:
/**
 * Agent
 *
 * @ORM\Table(name="agent")
 * @ORM\Entity(repositoryClass="App\Repository\AgentRepository")
 */
class Agent
{
  ...

Agent DTO:
class AgentDTO
{

    public function __construct(Agent $agent)
    {
      ...

Agent repository:
public function findAgentByField(string $field)
{
    return $this->getEntityManager()
        ->createQueryBuilder()
        ->select('NEW App\DTO\AgentDTO(a)')
        ->from('App:Agent', 'a')
        ->where('a.field= :field')
        ->setParameter('field', $field)
        ->getQuery()->getResult();
}

This throws the following error.

Argument 1 passed to App\DTO\AgentDTO::__construct() must be an
  instance of App\Entity\Agent, int given

I have put this $arg_list = func_get_args(); into the constructor of AgentDTO and I noticed there is a single parameter which is the identifier of the entity. Why isn't it an instance of Agent?

A: The documentation clearly states:

Note that you can only pass scalar expressions to the constructor.

But still, there is another possible way to map your result to DTO - by providing custom hydration mode:
In the end of the query specify a hydrator name:
...
->getQuery()
->getResult('AgentHydrator');

Then, in your config file under orm property specify hydrator mappings (Symfony docs link):
doctrine:
  orm:
    ...
    hydrators:
      AgentHydrator: My\Bundle\Hydrators\Agent\AgentHydrator

And finally specify the custom hydrator:
class AgentHydrator extends AbstractHydrator
{
    /**
     * {@inheritdoc}
     */
    protected function hydrateAllData()
    {
        $result = [];

        while ($data = $this->_stmt->fetch(\PDO::FETCH_OBJ)) {
            $result[] = new AgentDTO($data);
        }

        return $result;
    }
}


text:
Q: How to fix Excel.Application error that occurs randomly when instantiating the Excel.Application object I have a c# program that opens an excel worksheet, populates it with some data, and retrieves some information from the worksheet before closing the sheet.  This happens several times inside of a loop.  The program executes for some time completing the loop and then fails at random times during the loop with the following error:

System.Runtime.InteropServicdes.COMException (0x80080005): Retrieving
  the COM class factor for component with CLSID {xxx} failed due to the
  following error: 80080005 Server execution failed [Exception from
  HRESULT:0x80080005 (CO_E_SERVER_EXCEC_FAILURE)).

I have checked my reference for Microsoft.Office.Interop.Excel and it is the Microsoft Excel 16.0 Object Library version 1.9.0.0 and I have Excel 2016 installed.  The code that is causing the problem is similar to the following:
for (int i = 0; i < 100; i++)
{
     Excel.Application xlApp;
     Excel.Workbooks xlWorkBooks;
     Excel.Workbook xlWorkBook;
     Excel.Sheets xlWorksheets;
     Excel.Worksheet xlWorkSheet;
     object misValue = System.Reflection.Missing.Value;

     xlApp = new Excel.Application(); //line that causes error

     xlApp.Visible = false;
     xlApp.ScreenUpdating = false;
     xlWorkBooks = xlApp.Workbooks;
     xlWorkBook = xlWorkBooks.Open(IIHSTemplate.Text, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
     xlWorksheets = xlWorkBook.Worksheets;
     xlWorkSheet = xlWorksheets["Automatic-Data-Analysis"];
     IIHSDemerit = Convert.ToDouble((xlWorkSheet.Cells[30, 14] as Excel.Range).Value2);

      xlWorkBook.Close(false, misValue, misValue);
      xlApp.Quit();

      releaseObject(xlWorksheets);
      releaseObject(xlWorkSheet);
      releaseObject(xlWorkBooks);
      releaseObject(xlWorkBook);
      releaseObject(xlApp);
}

private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

My program writes the results of the excel data to a text file and executes several times with no errors.  After a random number of iterations (number is different each time I run the program) the program will fail with the error listed above.  Any ideas on what is causing the error and how to correct it?

A: Solution was to move the instantiation and releasing of the Excel app object out of the loop since I only needed to be opening and closing workbooks inside the loop.  Thanks to @SmrtGrunt for pointing that out in comments.


text:
Q: How to create a scrollable heatmap with plotly? I wonder whether it is possible to create a heatmap with scrollbars in plotly/dash? Sometimes I have data with thousands of rows or columns and I would like to visualize it in a heatmap, but not all at once. So, it would be nice to select maybe 10/20 rows/columns at a time and have a scrollbar. Has anyone done that before?

A: You need to put the heatmap into a scrollable html.Div using the overflow CSS property:
style=dict(height='500px',overflow='scroll')
This will give you a div limited to a given height and that has the ability to scroll down. Use the overflowY CSS property if you only want to scroll down.


text:
Q: Angular- How to add different style to a reusable component? I have made a table where user can add data. The input field is a resuable component.

I want to increase the width and height of the highlighted input field while decreasing the width of the ones inside the table. How do I do it?
This is the stackblitz link

A: There are two suggestions.

*

*You can set the width of this component to 100% and then control the width of the component from where it is being used. (Only works for width)

width: 100%;

*You can make the height and width as @Input fields of the component and also set up some default values so that you don't need to give the height and width every time you use the component.

resusable-component.ts
   @Input()
   height = 100;

   @Input()
   width= 100;

resusable-component.html
<div
  [style.width.px]={width}
  [style.height.px]={height}>
</div>

parent.component.html
<!-- When you want to have a custom height and width-->
<resusable [height]=200 [width]=300></reusable>

<!-- When you want to have a default height and width-->
<resusable></reusable>


text:
Q: Can't specify alternate login for remote share This is hopefully a simple question. I'm trying to connect to a remote share from Windows 7. The first time I went to connect, I accidentally specified the wrong username. Now, whenever I try to connect to that share, it won't let me specify another username. There is only one tile in the authentication dialog and it's pre-filled with the username I entered incorrectly. A reboot has not fixed the problem.
Note that this only seems to affect Windows Explorer. I can connect properly using NET USE on the command line, where I can specify the username explicitly as a command line parameter.

A: You need to go into the "Credentials Manager" for Windows credentials.
This is found in Control Panel under User Accounts and "Manage Your Credentials".
In there you should find a reference to the resource. Simply delete the credential and Windows will re-prompt.


text:
Q: How to SkippCall while Hooking in Deviare? Does anyone how to SkipCall() in Deviare (Python)?
They say something like:
HRESULT     SkipCall ()
    Skip calling the original function.
When I try to do this, it doesn't work. It goes in a loop at the same call. I guess that I should also do some stuff on registers (like to restore EBP). But the thing is that NktCallInfo.Register set doesn't work in Python. I try something like:
NktHookCallInfo.Register(ESP, EBP)

But it doesn't work. Help please ?

A: I recently see this question. Expect not to be late. (I'm a Deviare developer)
When you call SkipCall, you must setup a return value and, optionally the Win32 lasterror using the provided 'INktHookCallInfo' methods. If the function being hooked is in the database, it will remove the parameters from stack depending on the calling convention.
If you are hooking an arbitrary address without assigning a function, you must do the unwind manually by setting the ESP/RSP registers as appropiate.


text:
Q: How does Jira Issue Security limit a user's access to a specific issue? I want to make it so certain users can view and/or comment on specific issues, but not all issues. I was reading that I can use Issue Security for this but I'm not understanding one thing.
My understanding:

*

*Enable Issue Security to a project

*Issue security scheme defined with who can view/comment on issues by specifying Jira groups in the Issue Security settings:

*

*group ABC can view

*group DEF can view + comment

*People get added to those groups

But, what controls the issue they can access?
If Joe is added to group ABC, what says they can view issue 123 BUT NOT issue 456?

A: Every issue has a security level, which can be chosen among those that are available in the Issue Security Scheme associated to that project. I suppose you haven't created them yet: then you need to edit the Issue Security Scheme and add all the security levels that you need. More info on security levels here.
In your case, if you want a simple model you could call the security levels something like "Public" and "Restricted". Issue 123 is set to Public, issue 456 to Restricted, and to view restricted issues you must belong to group DEF, so those that are only in group ABC cannot see them.
If you want to manage multiple customers/suppliers and keep things separated, you can create a group for each company, and a security level for each: visible_by_company_A, visible_by_company_B, and so on. Then each security level is configured so that they are visible only be the right groups/roles, and then users must be assigned to the right groups or roles. A user could belong to both groups, or to just one (or to none).
The catch is that each issue can have only one security level, so if you need an issue to be visible by both company A and company B you must create a specific security level for that, like "visible_by_A_and_B", and this doesn't scale well. But in general this rarely happens (at least in my experience), and I've never needed to create too many levels.
One last thing: users who want to set the security level must have the "Set issue security" permission, make sure they have it.


text:
Q: Electron - Uncaught TypeError: Cannot read properties of undefined (reading 'showOpenDialog') I'm trying to open the dialog on electron, but I'm getting this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'showOpenDialog')

I've already visited several forums and communities to see if I have a solution to my problem. But none resolved perhaps because of the version.
The version of electron I currently use is 16.0.5
This answer didn't help me much
https://stackoverflow.com/a/63756725/14271847
I won't leave all of my main.js, but the part I changed is this one, enableRemoteModule:
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      enableRemoteModule:true,
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })

file test.js
And here's what I'm trying to do on electron, following what's in this link
const { dialog } = require('electron')
console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))

I've tried it with the remote, but it doesn't work:
const { dialog } = require('electron')
console.log(dialog.remote.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))

Could someone help please?

A: Enabling Context Isolation and disabling nodeIntegration is best practice nowadays to truly secure your Electron application. Additionally, the use of remote is discouraged as we now have Inter-Process Communication.
Not knowing what your preload.js script looks like, I have included a simple preload.js script below that uses a list of whitelisted channel names and implementation of ipcRenderer methods only. That said, having a different looking preload.js script should not change too much the core approach that should be used in
your main.js and index.html files to get your dialog working.

Using of the invoke method will allow us to send a message to the main process to open the dialog and receive a reply, all in one.
preload.js (main process)
// Import the necessary Electron components.
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;

// White-listed channels.
const ipc = {
    'render': {
        // From render to main.
        'send': [],
        // From main to render.
        'receive': [],
        // From render to main and back again.
        'sendReceive': [
            'dialog:openMultiFileSelect' // Channel name
        ]
    }
};

// Exposed protected methods in the render process.
contextBridge.exposeInMainWorld(
    // Allowed 'ipcRenderer' methods.
    'ipcRender', {
        // From render to main.
        send: (channel, args) => {
            let validChannels = ipc.render.send;
            if (validChannels.includes(channel)) {
                ipcRenderer.send(channel, args);
            }
        },
        // From main to render.
        receive: (channel, listener) => {
            let validChannels = ipc.render.receive;
            if (validChannels.includes(channel)) {
                // Deliberately strip event as it includes `sender`.
                ipcRenderer.on(channel, (event, ...args) => listener(...args));
            }
        },
        // From render to main and back again.
        invoke: (channel, args) => {
            let validChannels = ipc.render.sendReceive;
            if (validChannels.includes(channel)) {
                return ipcRenderer.invoke(channel, args);
            }
        }
    }
);

A summary on the use of the above preload.js script is shown below.
/**
 * Render --> Main
 * ---------------
 * Render:  window.ipcRender.send('channel', data); // Data is optional.
 * Main:    electronIpcMain.on('channel', (event, data) => { methodName(data); })
 *
 * Main --> Render
 * ---------------
 * Main:    windowName.webContents.send('channel', data); // Data is optional.
 * Render:  window.ipcRender.receive('channel', (data) => { methodName(data); });
 *
 * Render --> Main (Value) --> Render
 * ----------------------------------
 * Render:  window.ipcRender.invoke('channel', data).then((result) => { methodName(result); });
 * Main:    electronIpcMain.handle('channel', (event, data) => { return someMethod(data); });
 *
 * Render --> Main (Promise) --> Render
 * ------------------------------------
 * Render:  window.ipcRender.invoke('channel', data).then((result) => { methodName(result); });
 * Main:    electronIpcMain.handle('channel', async (event, data) => {
 *              return await promiseName(data)
 *                  .then(() => { return result; })
 *          });
 */

In the main.js script, using the handle method, let's listen for a message on the dialog:openMultiFileSelect channel. Once received, open the dialog.showOpenDialog() method and .then wait for a result. Once a result has been received (IE: Files selected and dialog accepted), return the result (via the handle method)  back to the render process.
main.js (main process)
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const electronDialog = require('electron').dialog;
const electronIpcMain = require('electron').ipcMain;

const nodePath = require("path");

// Prevent garbage collection
let window;

function createWindow() {
    const window = new electronBrowserWindow({
        x: 0,
        y: 0,
        width: 800,
        height: 600,
        show: false,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: nodePath.join(__dirname, 'preload.js')
        }
    });

    window.loadFile('index.html')
        .then(() => { window.show(); });

    return window;
}

electronApp.on('ready', () => {
    window = createWindow();
});

electronApp.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        electronApp.quit();
    }
});

electronApp.on('activate', () => {
    if (electronBrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// ---

electronIpcMain.handle('dialog:openMultiFileSelect', () => {
    let options = {
        properties: ['openFile', 'multiSelections']
    };

    return electronDialog.showOpenDialog(window, options)
        .then((result) => {
            // Bail early if user cancelled dialog
            if (result.canceled) { return }

            return result.filePaths;
        })
})

Finally, in the index.html file, we listen for a click event on the button and then send a message via the dialog:openMultiFileSelect channel to open the dialog (in the main process). Once a result is returned, .then display the selected file(s).

Note how we detect a result of undefined and manage it accordingly. This occurs when the user cancels the dialog.

index.html (render process)
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Electron Test</title>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>

        <input type="button" id="button" value="Open File Dialog">


text:
Q: How to detect changes of data grid in VB.NET I have a datagrid in VB.NET class. The cells are editable. Is there any way to trigger a function when each of the cells are edited?

A: Yes, the CellValueChanged Event:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx
    Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
       'do something
    End Sub

EDIt as per your comment:
Yes you could save the current value to a class level variable on BeginEdit and retreieve it in the CellValueChanged event:
Private cellValue As String = String.Empty

Private Sub DataGridView1_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
    cellValue = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString
End Sub

Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    MessageBox.Show("row index: " & e.RowIndex & Environment.NewLine & "old value: " & cellValue)
End Sub


text:
Q: Capitilize first letter of AlertIOS.prompt So i am querying the user for input to save a document that they are writing. I want the first letter of the input to be a capital letter - by automatically toggling on the capital "up" arrow when the keyboard is shown. I have the following code:
AlertIOS.prompt('Saving Document',
                        'Please name this document',
                            [{text: 'Cancel'},
                             {text: 'Save', onPress: input => this._saveFile(input)}
                            ]
                       )

Just wondering how i can do so. I realise that i can edit the input in the back end and capitilize the first letter there, but i am looking for a method in which the user can see that the first letter is a capital when entering input.
Most IOS apps have this feature and i was wondering how to do so in react native.
Thanks in advance.

A: As the comments say, at the moment there is no way to do this with the AlertIOS component, at least not without getting into native code. But take a look at https://www.npmjs.com/package/react-native-prompt, it appears this might have the functionality you are looking for. You should be able to set the autoCapitalize prop on the textInput using this property:
textInputProps (Object) -- Additional props on the input element


text:
Q: Matlab) how can I plot graphs of function with various input arguments? mfunction.m
function[P] = mfunction(v,M,R,T)
P=4*pi*(M/(2*pi*R*T)).^(3/2)*v.^2*exp((-M*(v.^2))/(2*R*T));
end

I want to make a graph. x would be v and the range is 1: 1200,
M = 0.032,R = 8.31, T= 300

and I want to plot y=mfunction(x)
and errors pop up. How can I draw a graph?

A: The problem lies at the middle multiplication
P=4*pi*(M/(2*pi*R*T)).^(3/2)*v.^2  *   exp((-M*(v.^2))/(2*R*T));
                                   ^

What you are doing is similar to doing
[1,2] * [1,2]

, which gives you the error "mtimes Inner matrix dimensions must agree", because it is multiplying a mx1 matrix to an mx1 matrix.
Depending on want you need, you can do one of the following:
>> [1,2] * [1,2]'  %inner product

ans =

     5

>> [1,2]' * [1,2]

ans =

     1     2
     2     4

>> [1,2] .* [1,2]  %element-wise product

ans =

     1     4


text:
Q: How to delete a session file in *public_html/writable/session* after destroying session and prevent getting wrong session data I have a CodeIgniter 4 project.
When a user logins in and navigating through the website, at times the session()->get() will get a wrong session data thereby showing wrong user data because I use session to query user details from database.
This is how I set the session
$this->setUserSession($user);

    private function setUserSession($user)
    {
        $data = [

            'id' => $user['id'],
            'username' => $user['username'],
            'isLoggedIn' => true,
        ];

        session()->set($data);

        return true;
    }

I call it using session()->get('id')
And I destroy it using
public function logout()
    {
        session()->destroy();
        return redirect()->to('login');
    }

Please How can I prevent the session from getting a wrong session data?


text:
Q: VBA excel Passing back parameter Okay I want to add something to this macro
Sub Search()
  Inputbox myInput
  found = false
  loop
     Call getInput (myInput)            '~> check multiple files
  end loop
  If found = false
    'DO something
  End if
End sub

Sub getInput(ByVal inputVar As String, ByVal Input as Boolean)
  If a = inputVar Then
      found = true                      '~> I want to pass this parameter back to search
  End If
End sub

The case is like, I want my sub to pass the found parameter from
  Search() to getInput() and then getInput() return the found parameter to
  Search()

Should I add something like search(ByVal found as boolean) ?

A: if you want to return a value, then you should change the getInput Sub to a function as they can return values.
Sub Search()
  Dim found As Boolean

  InputBox myInput

  found = checkInput(myInput)

  If found = False Then
    'DO something
  End If
End Sub

Function checkInput(inputVar As String) As Boolean

    Dim result As Boolean

    'do your checking here and set result

    'return the result
    checkInput = result

End Function


text:
Q: How to put Task into ObservableCollection and process it with EventLoopScheduler? Currently I have a task processed by TPL scheduler:
var result = await task;

Is it possible to postpone its awaiting/execution by putting it into ObservableCollection and processing by specific Rx scheduler:
var scheduler = new EventLoopScheduler();

Observable
    .FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
        e => _collection.CollectionChanged += e,
        e => collection.CollectionChanged -= e)
    .Where(e => e.EventArgs.Action == NotifyCollectionChangedAction.Add)
    .Select(e => e.EventArgs.NewItems.Cast<Task<T>>())
    .ObserveOn(scheduler)
    .Do(x => scheduler.Schedule(
        () => Thread.Sleep(TimeSpan.FromSeconds(1)))) // once a second
    .Subscribe(???);

So calling code wouldn't be changed:
var result = await Later(task);

A: var do= new Do();

var result = await do.Later(() => 1 + 2);

public class Do
{
    private Subject<Action> _backlog = new Subject<Action>();

    public Do()
    {
         Observable.CombineLatest(_backlog, Observable.Timer(...), (l, r) => l)
              .Subscribe(x => x());
    }

    public Task<T> Later(Func<T> getResult)
    {
        var tcs = new TaskCompletionSource<T>();
        _backlog.OnNext(() => {
             try
             {
                 var result = getResult();
                 tcs.SetResult(result);
             }
             catch(Exception ex)
             {
                 tcs.SetException(ex);
             }
        });
        return tcs.Task;
    }
}

A: Why use TPL at all if you plan to transition to RX? Just use something like below and use whatever scheduler you'd like.
Observable.Interval(TimeSpan.FromSeconds(1))
            .Select(_ => "SomeResult")
            .Subscribe(x => Console.WriteLine("{0} - {1}", DateTime.Now.Second, x));


text:
Q: How to display input buttons on one line in Bootstrap? I've made a small little Bootstrap panel, and I have 3 Bootstrap buttons in the panel at the bottom. What I'm trying to do is make all the buttons be on one line and have a small gap, not bunched together. Here's what I have right now, and here's what it's doing:

.recent
{
    margin-top: 50px;
    margin-right: 500px;
}

.recent input
{
    float: left;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

Recent

- Aurora, Colorado : Blah Blah Blah

                                <input type="button" value="View all" onClick="#" class="btn btn-primary">
                                <input type="button" value="Last 24 hours" onClick="#" class="btn btn-danger">
                                <input type="button" value="Last 48 hours" onClick="#" class="btn btn-warning">

What's happening is this:

https://gyazo.com/46b7c219adc26be516475c8f3b4d803d
Is there any way to make them stay on one line, or would I have to make the column larger?

A: You'll need to make the column width wider. Since you're using col-lg-3 class, the last button is wrapping to the next line.  Try changing it to a larger column (i.e. col-lg-6).  To answer the second part of your question, you can add a CSS rule like .btn {margin: 0 5px;} if you want some space between the buttons.

A: you can also achieve with out using float property. You use display:inline-block instead of float.
or you use 3 multiple division(.col-sm, .col-md, .col-lg) in .row or .container

A: You can try this code

Recent

- Aurora, Colorado : Blah Blah Blah

<input type="button" value="View all" onClick="#" class="btn btn-primary">

<input type="button" value="Last 24 hours" onClick="#" class="btn btn-danger">

<input type="button" value="Last 48 hours" onClick="#" class="btn btn-warning">

A: Here are few points.

*

*Why are you giving 500 margin right to recent class? it will create problem in responsiveness. Even if you are targeting only desktop screen it is not good practice. 500 margin forcing to reduce width of recent.

*you are using col-lg-3 It might be fine to use col-lg-3 for larger screens more than 1200px wide.. for small screens there are col-md-3, col-sm-3 and col-xs-3

*Give a little margin-right to buttons so that they have a little space.

.recent
{
    margin-top: 50px;
}

.recent input
{
    float: left;
}
.m-right{
    margin-right:5px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

Recent

- Aurora, Colorado : Blah Blah Blah

                                <input type="button" value="View all" onClick="#" class="btn btn-primary m-right">
                                <input type="button" value="Last 24 hours" onClick="#" class="btn btn-danger m-right">
                                <input type="button" value="Last 48 hours" onClick="#" class="btn btn-warning m-right">


text:
Q: Models per database table? I am using codeigniter, and have found myself in a similar situation where I have repeated Model methods.
I am creating a Model per Controller. But I would creating a Model per database table be considered good practice? That way methods aren't written twice.
Instead of Model per Controller or Several small Models that  are shared.
Example if I have a model method get_user($user_id) I could write it on users_models.php ...
One of the downsides I see of this is that I might have to call several models, rather than just controllername_models.php .
Could loading several models where several methods might not be used from a controller affect performance and speed? What could be the best way to tackle this down?
Note: There are similar question, but they do not cover the ground of Model per database table.

A: I's say that a model per table is just recreating your database in a class structure. It is known as a anemic model and considered an anti-pattern. That is because classes are intended to have both data and behaviour. If you restrict your models to a single table, where do you put the code (behaviour) that needs to deal with data and behaviour from multiple tables? Your controllers would then need models that use one or more of these "table" models... So, apart from in the most basic of apps, you gain little if anything from this approach.

A: I mostly agree with Dime's answer that you want to create your models per business object - the problems that the business is trying to solve should drive how you create the model classes. In practice, I've found that creating one model per table is a good place to start. A properly designed schema is likely to mimic the business processes that you need to model in application code - also called the Domain Model.
Using an Object/Relational Mapping layer is useful so your Domain Model contains the same relationships as the database schema without the need for repetitive calls to a data access layer. Check out Eloquent for PHP as an example. Both the schema and the Domain Model should be designed to support the business processes.
This leads into the first part of Marjan Venema's answer:

I's say that a model per table is just recreating your database in a class structure. It is known as a anemic model and considered an anti-pattern.

An Anemic Domain Model is an anti-pattern. A "model per table" as Venema suggests could be seen as "recreating your database," however it is absolutely incorrect to say this alone is an Anemic Domain Model.
From Martin Fowler:

The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters.

(emphasis, mine)
The key factor in an anemic domain model is a lack of behavior, or methods, on the Domain Model classes.

That is because classes are intended to have both data and behaviour. If you restrict your models to a single table, where do you put the code (behaviour) that needs to deal with data and behaviour from multiple tables?

Again, you can, and should, put behavior in your Domain Models, even if they only map to one table. Behavior that affects multiple tables really affects multiple objects that happen to map to multiple tables. Domain Driven Design is an approach to precisely the same problem Venema mentioned: "where do you put the code (behaviour) that needs to deal with data and behaviour from multiple tables?"
And the answer is an Aggregate Root. Martin Fowler states:

Aggregate is a pattern in Domain-Driven Design. A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An example may be an order and its line-items, these will be separate objects, but it's useful to treat the order (together with its line items) as a single aggregate.

(emphasis, mine)
A "cluster of domain objects" can also be viewed as "Domain Models that map to multiple tables." Behavior that affects multiple tables should be defined on the Aggregate Root - A class that encapsulates the "thing" that affects multiple tables or objects:
Again, from Martin Fowler:

An aggregate will often contain mutliple collections, together with simple fields.

To answer the OP's original question:

... would creating a Model per database table be considered good practice? That way methods aren't written twice.

I would say this is a good place to start, but be aware that your schema and object model do not have to match 100%. The object model should be more concerned with implementing and enforcing business rules. The schema should be more focused on storing business data in a modular and scalable way.
A model per controller would not be good practice, although there is a variation of model called a View Model that does fit into the Controller layer. A View Model is a reorganization of the Domain Model to fit a certain kind of display, be it a web page or form in a GUI application.

A: In general you should create your models not per table or per controller but per business object. Sometimes it maybe a 1:1 relationship with your tables structure or with your controllers, but not necessary.
In your example you may have one users_model class that is called from several controllers. This is fine and sometimes even desirable. However in most cases the users_model class will get its data from several tables.
For example, last_login_date property of the users_model class can (not must) be obtained from a separate user_audit table that has one-to-many relationship with the main users table.
And I would say if you have one SQL table per business object then it is most likely that your database structure is not normalized.


text:
Q: Hide addon per story in Storybook I am building a component library using Storybook with React.
Stories are included using the CSF method.
I have multiple addons, and use them when displaying individual stories.
I am also displaying all stories together in one view, as a reference - it is this story that I want to disable particular addons. In this case, I want to disable Knobs.
When I try to disable individual addons per story, nothing happens.
I have included a simplified version of my stories.js file below:
import React from 'react';
import Button from './button';
import { withKnobs, text } from '@storybook/addon-knobs/react';

// global settings to be exported
export default {
  title: 'components/Buttons',
  component: Button,
  decorators: [withKnobs],
  parameters: { options: {showPanel: true }}
}

// define individual stories
const Basic = () => <Button className={text("ClassName-Basic", "button basic")} id={text("ID", "Hello-id-basic")} content={text('Content', 'some text for Basic button here')}/>;
const Primary = () => <Button className={text("ClassName-Primary", "button primary")} id={text("ID", "Hello-id-primary")} content={text('Content', 'some text for Primary button here')}/>;
const Secondary = () => <Button className={text("ClassName-Secondary", "button secondary")} id={text("ID", "Hello-id-secondary")} content={text('Content', 'some text for Secondary button here')}/>;
const Disabled = () => <Button className={text("ClassName-Disabled", "button disabled")} id={text("ID", "Hello-id-disabled")} content={text('Content', 'some text for Disabled button here')}/>;
// define all stories together to be displayed in one view
const All = () =>
<Basic />
<Primary />
<Secondary />
<Disabled />
;

// export all components individually, and then export them all together
export  {Basic, Primary, Secondary, Disabled, All};

// settings for the 'All' story
All.story = {
  parameters: {
    options: {
      withKnobs: {
        disable: true, // do not show the knobs addon on this story
      }
    }
  }
};

Despite adding this setting to disable Knobs on the All story view, it still shows.
What am I doing wrong?
I am using storybook version 5.2.8


text:
Q: Struts2 validation expression sample What does this [D][C][M])[-]*[a-zA-z0-9]*$ mean? What do *,^,$ [-] all mean? Please explain.

A: That looks like part of a regular expression validator -

*

** - match the previous item 0 or more times

*^ - the beginning of a line

*$ - the end of a line

*[-] - the character class that contains "-"

*[1-5] - the character class that contains the range of "1" to "5" inclusive

*[a-z] - the character class that contains the range of "a" to "z" inclusive

[D][C][M])[-]*[a-zA-Z0-9]*$:

*

*[D][C][M]) - some capture group ending with the characters "DCM"

*[-]* - 0 or more "-"s

*[a-zA-Z0-9]*$ -  0 or more alphanumeric characters at the end of the line


text:
Q: Infinite loop Kafka Consumer I'm testing some basic Kafka feature, I have basics zookeeper/kafka servers running on a Ubuntu Server 18.04 LTS virtual machine. And I use the kafka-node module.
This script should be waiting for new message to arrive in order to consume it.
But it is stuck in an infinite loop as soon as I launch it.
I can't find where it comes from,
"use strict"
require('dotenv').config();
var kafka = require('kafka-node');

const client = new kafka.Client("localhost:2181");
var topics = [{
  topic: 'stuff',
  offset: 0
}];
var options = {
  autoCommit: false
}
const HLConsumer = new kafka.HighLevelConsumer(client, topics, options);

HLConsumer.on('message', function(message) {
  console.log(message);
});

HLConsumer.on('error', function(err) {
  console.log('error', err);
});

HLConsumer.on('offsetOutOfRange', function(err) {
  console.log('offsetOutOfRange:', err);
})

Have a nice day every one, and thanks
Edit 1 :
I updated as requested autoCommit to true and still have to problem.
Here is a cheap gif of the issues, in fact it loop through every offset and then read 10/15 message with an offset of 0 then restart looping on every offset of the topic

A: I had that problem before, the solution was update kafka-node.

A: I found what was causing this :
I used to declare my consumer like that
var kafka = require('kafka-node');
...
var consumer = new kafka.Consumer(client, topics, options);

but the good way to do it is :
var kafkaConsumer = require('kafka-node').Consumer;
...
var consumer = new kafkaConsumer(client, topics, options);


text:
Q: overflow not flowing over enough I've got a piece of code consisting of styled images that need to fit within a fixed sized div. If it does not, it should flow over. However, the floated element that does not fit, flows over as it should but touches the other elements and places itself over one of their shadows.
It's best to explain using an example: http://jsfiddle.net/wjw83/10/
The 7th image (barely visible) should vanish entirely or move further down where it moves out of the visible area. Can anyone help me accomplish this?
Thank you.
EDIT
Being out of ideas and on the verge of raging, I've started pasting random attributes and eventually was successful.
Solved: http://jsfiddle.net/wjw83/13/
All I had to was add "margin-bottom: 20px;" to the image class. Since it's the same value as the shadow, it leaves the shadow intact while completely removing the clipped element. Whoohoo!

A: .main{
    padding-top: 15px;
    width: 870px;
    height: 140px; /* Reduced height */
    overflow:hidden;
}

Live demo: Fiddle

A: Being out of ideas and on the verge of raging, I've started pasting random attributes and eventually was successful.
Solved: http://jsfiddle.net/wjw83/13/
All I had to was add "margin-bottom: 20px;" to the image class. Since it's the same value as the shadow, it leaves the shadow intact while completely removing the clipped element. Whoohoo!


text:
Q: Can you be in the "95% percentile"? I have a feeling there's only one way to say this: you can be in the "95th percentile". A colleague of mine says it's OK to say "the 95% percentile", which doesn't seem to make mathematical sense to me.
What's correct?

A: Percentiles, whether we mean rank or range, are discussed using ordinal numbers: first, 50th, 95th, etc. To say "ninety-five percent percentile" would be considered an error in any kind of formal or academic setting, as well as being redundant.

Percentile ranks are reported on an ordinal scale.

Applied Statistics in Education and Psychology I


text:
Q: Roll/Dice command? I'm trying to make roll command that generates a random number based on user input.
For example:

user: !roll 1d100
bot: Your output is 65 (or some other random number)

I have tried a couple of different things, but none of them have worked, the output was "NaN".
My nearest code was:
const argsminus8 = message.content.slice(prefix.length).trim().split(/ +/g);
const commandminus8 = argsminus8.shift().toLowerCase();

if(message.content.startsWith (prefix + `random-number`)) {
  function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  if (!argsminus8.length) {
    return message.channel.send(`What roll am I supposed to make?`);
  }
  const embed = new MessageEmbed()
    .setTitle('Number:')
    .setDescription( getRandomIntInclusive())
    .setColor(0x0099ff)
    .setTimestamp()
  message.channel.send({ embed });
}

A: If you create a function that takes in parameters you have to use those.
function getRandomIntInclusive(min, max) {
        min = Math.min(min, max);
        max = Math.max(max, min);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    let num1 = argsminus8[0];
    let num2 = argsminus8[1];
    if(!num1) return message.reply("Please enter a first number");
    if(!num2) return message.reply("Please enter a second number");

    const embed = new MessageEmbed()
        .setTitle('Number:')
        .setDescription(getRandomIntInclusive(num1, num2))
        .setColor(0x0099ff)
        .setTimestamp()
    message.channel.send({ embed });

Implement this inside if(message.content.startsWith (prefix + 'random-number')).
This will create random numbers between 1 and 100, because for the min parameter I said 1 and for the max parameter I said 100.
You can change the numbers to whatever you like.

A: The fastest answer is that in your getRandomIntInclusive, variables min and max have the value of undefined. In JavaScript every arithmetic operation with a non-numeric (NaN) value results in NaN.
Why undefined? Because your function is expecting those two parameters (min and max) when used:
// Wrong
getRandomIntInclusive();

// Correct
getRandomIntInclusive(1, 100)

Also, if you are calling your function Int (from Integer) there's no need to .ceil() or .floor() since both methods round the fractional part to the nearest integer and, as far as I know, you don't need a random number between 0.97 and 99.01.
If your only issue is that NaN result, you can simplify your code a lot by using the advice I gave you, and maybe using a more common dice (a random number between 1 and 6)

/**
* Simplified randomizer method
*/
const getRandomIntInclusive = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

console.log(getRandomIntInclusive(1,6));


text:
Q: 1st July 2022 "Seeing is believing" blog post has a few problems The blog post "Seeing is believing: The Stack Overflow Podcast now available as video" has a few problems for me.

*

*There's no clickable link to the Stack Overflow's YouTube channel. For example, quoting the blog:

Starting today, Stack Overflow will be joining the party, publishing a video version of our weekly podcast to our YouTube channel and sharing some highlights and clips on our social media accounts

I scrolled through the post several times without finding an obvious link I could click to the YouTube channel, or to the episode. (I was left wondering if the podcast has its own YouTube channel or if it's on the SO's main YouTube channel.)

*At least for me I don't see any video or screenshot of the video in the post, where it says:

Below is video to accompany the podcast that was published this morning.

All I see is a long blank space. (Using Firefox on Windows 10 with everything vanilla.)

*Apparently there should be another large item at the end of the post but I also can't see it.

A: This seems to be triggered by denying targeting cookies. I assume the YouTube embedding includes targeting cookies or by itself counts as targeting as it inevitably submits information to Google.
There should be a proper fallback to the embedding here; failing silently is quite bad UX.


text:
Q: Imagick (Imagemagick on PHP): serve a file without saving to disk first? I'm trying to use Imagemagick (actually PHP's Imagick) to create and output (serve) an image without saving it to disk first.
Currently I'm having to save the file and then use verot upload class to serve the image.
(Apache 2 server, PHP5)

A: Sure. This should work for you:
$image = new Imagick();
// Do your image creation stuff. Make sure to set $image->setImageFormat();

header('Content-Type: image/filetype'); // Change filetype
echo $image;

A: I admit to never having used Imagick, but just looking at the examples, echoing the image should work just fine:
header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

echo $image;