Likelihood function for switchpoint analysis--in this case example from PyMC3

Question: I was watching a video on PyMC3 for fitting Bayesian models, and an example they gave was of "switchpoint" analysis for coal mining disasters. A picture of the data is below, and the goal is to identify the year in which the distribution changes from a high number of disasters to low number of disasters regime.

My question is, what is the likelihood function for a switchpoint model? That was not mentioned in the talk or documentation. I understand the priors, but the likelihood almost seems like a mixture of poissons or something. I was just wondering what the precise mathematical specification of the likelihood function was--or at least the probability distribution used to setup the likelihood.
Now, the model is specified as:
$$
\begin{aligned}
D_{t} & \sim \operatorname{Pois}\left(r_{t}\right), r_{t}=\left\{\begin{array}{ll}
e, & \text { if } t \leq s \\
l, & \text { if } t>s
\end{array}\right.\\
s & \sim \operatorname{Unif}\left(t_{l}, t_{h}\right) \\
e & \sim \exp (1) \\
l & \sim \exp (1)
\end{aligned}
$$
And the PyMC3 code is
with pm.Model() as disaster_model:

switchpoint = pm.DiscreteUniform('switchpoint', lower=years.min(), upper=years.max(), testval=1900)

# Priors for pre- and post-switch rates number of disasters
early_rate = pm.Exponential('early_rate', 1)
late_rate = pm.Exponential('late_rate', 1)

# Allocate appropriate Poisson rates to years before and after current
rate = pm.math.switch(switchpoint >= years, early_rate, late_rate)

disasters = pm.Poisson('disasters', rate, observed=disaster_data)

Thanks for taking the time to look at my question.
Note, a similar question was asked before about this type of switchpoint analysis, but that question did not ask for the mathematical form of the likelihood function.
Switchpoint detection with probabilistic programming (pymc)
Comment: The book Bayesian Probability (https://www.amazon.com/Bayesian-Probability-Theory-Applications-Physical-ebook/dp/B00J8LQPVA/ref=sr_1_1?crid=3HR8SA1RLG5D8&keywords=von+der+linden%2C+dose%2C+von+Toussaint&qid=1695023531&s=books&sprefix=von+der+linden%2C+dose%2C+von+toussaint%2Cstripbooks-intl-ship%2C173&sr=1-1) has a full chapter on Change Point analysis (Ch. 24), which may be of interest.
Answer: Since
disasters = pm.Poisson('disasters', rate, observed=disaster_data)

for this model the likelihood is the Poisson:
$P(n_i|\lambda) = \frac{\lambda^{n_i} e^{-\lambda}}{n_i!}$
where $n_i$ represents the observed number of disasters of the year $i$ and each year is considered independent of the other i.e. the log-likelihood is just the sum over all the years of the log-likelihoods, while $\lambda$ represents the average rate of disasters per year.
In general, in a switch-point model, you may choose whatever likelihood you consider more appropriate, and in this case the Poisson seems quite logical, as the events we are counting are independent (it seems reasonable to assume that each disaster is independent on the previous ones).
As you pointed out, in this switch-point model, the average rates is
$$\lambda =
\begin{cases}
\lambda_e \text{ if } t < \tau_s \\
\lambda_l \text{ if } t >= \tau_s \\
\end{cases} $$
or, if you prefer,
$$\lambda = \lambda_l \theta(t-\tau_s) +  \lambda_e \theta(\tau_s-t) $$
I would not include $\lambda$ as a part of the likelihood, as it does not involve the data at all, but I'd rather consider it an intermediate random variable, since it's a function of the remaining priors only:
$$
\lambda_e, \lambda_e \sim \exp(1)
\\
\tau_s \sim \mathcal{U}(t_l, t_h)
$$
Comment: Hi @Stefano, the OP is asking about the `likelihood function for a switchpoint model` could adapt the answer by providing some thought on that?
Comment: Hi @utobi. Thanks, sure I'll try.


Postfix: can't send mail from remote client

Question: I'm having issues sending mail from postfix. I believe my conf. is very standard, at the end it was put together from various guides. I'm trying to send mail from remote client (iOS Mail, and Mac OS X Mail.app, Thunderbird on Linux). From iOS Mail it works ok, it does not for Mail.app and Thunderbird. I'm using SASL authentication (dovecot), and TLS, configuration below along with log message.
Error:
Jan 05 12:27:41 svali postfix/smtpd[26448]: NOQUEUE: reject: RCPT from aaa.chello.sk[220.127.116.11]: 553 5.7.1 <xxx>: Sender address rejected: not owned by user xxx; from=<xxx> to=<yyy> proto=ESMTP helo=<[10.0.2.4]>
Jan 05 12:27:41 svali postfix/smtpd[26448]: disconnect from aaa.chello.sk[184.108.40.206]
Jan 05 12:31:01 svali postfix/anvil[26450]: statistics: max connection rate 2/60s for (submission:184.108.40.206) at Jan  5 12:24:33

When it works (iOS Mail app)
Jan 05 12:45:23 svali postfix/smtpd[26807]: connect from aaa.chello.sk[188.8.131.52]
Jan 05 12:45:24 svali postfix/smtpd[26807]: 1328056578: client=aaa.chello.sk[22.214.171.124], sasl_method=PLAIN, sasl_username=xxx
Jan 05 12:45:24 svali postfix/cleanup[26821]: 1328056578: message-id=<42EC179A-DE92-4526-9F0E-DA3B5EF76B80@aaa>
Jan 05 12:45:24 svali postfix/qmgr[2599]: 1328056578: from=<xxx>, size=650, nrcpt=1 (queue active)
Jan 05 12:45:24 svali postfix/smtp[26824]: 1328056578: to=<yyy>, relay=gmail-smtp-in.l.google.com[2a00:1450:400c:c05::1a]:25, delay=0.71, delays=0.17/0.01/0.04/0.49, dsn=2.0.0, status=sent (250 2.0.0 OK 1388925924 f3si3608555wik.58 - gsmtp)
Jan 05 12:45:24 svali postfix/qmgr[2599]: 1328056578: removed
Jan 05 12:45:26 svali postfix/smtpd[26827]: connect from mail-qe0-f42.google.com[188.8.131.52]
Jan 05 12:45:27 svali postfix/smtpd[26827]: 28DA856578: client=mail-qe0-f42.google.com[18.104.22.168]
Jan 05 12:45:27 svali postfix/cleanup[26821]: 28DA856578: message-id=<42EC179A-DE92-4526-9F0E-DA3B5EF76B80@aaa>
Jan 05 12:45:27 svali postfix/qmgr[2599]: 28DA856578: from=<yyy+caf_=dusan=xxx>, size=2535, nrcpt=1 (queue active)
Jan 05 12:45:27 svali postfix/smtpd[26827]: disconnect from mail-qe0-f42.google.com[126.96.36.199]
Jan 05 12:45:28 svali dovecot[26832]: lda(xxx): sieve: msgid=<42EC179A-DE92-4526-9F0E-DA3B5EF76B80@aaa>: stored mail into mailbox 'INBOX'
Jan 05 12:45:28 svali postfix/pipe[26831]: 28DA856578: to=<xxx>, relay=spamass, delay=1.1, delays=0.69/0.01/0/0.36, dsn=2.0.0, status=sent (delivered via spamass service)
Jan 05 12:45:28 svali postfix/qmgr[2599]: 28DA856578: removed

main.cf
smtpd_banner = $myhostname ESMTP
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/svali.pem
smtpd_tls_key_file=/etc/ssl/private/svali.pem
smtpd_use_tls = yes
smtpd_tls_auth_only = yes

# Enabling SMTP for authenticated users, and handing off authentication to Dovecot
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes

smtpd_recipient_restrictions =
        permit_sasl_authenticated,
        permit_mynetworks,
        reject_unauth_destination

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = $myhostname
mydestination = localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all

# Handing off local delivery to Dovecot's LMTP, and telling it where to store mail
# virtual_transport = lmtp:unix:private/dovecot-lmtp
virtual_transport = spamass

# Virtual domains, users, and aliases
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf

# Disable TLS for SMTP connections
smtpd_discard_ehlo_keyword_address_maps = hash:/etc/postfix/discard_ehlo

# OpenDKIM
non_smtpd_milters=inet:127.0.0.1:8891
smtpd_milters=inet:127.0.0.1:8891

master.cf
#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       n       -       -       smtpd
#smtp      inet  n       -       n       -       1       postscreen
#smtpd     pass  -       -       n       -       -       smtpd
#dnsblog   unix  -       -       n       -       0       dnsblog
#tlsproxy  unix  -       -       n       -       0       tlsproxy
submission inet n       -       n       -       -       smtpd
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
  -o smtpd_sasl_security_options=noanonymous
  -o smtpd_sasl_local_domain=$myhostname
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_sender_login_maps=hash:/etc/postfix/virtual
  -o smtpd_sender_restrictions=reject_sender_login_mismatch
  -o smtpd_recipient_restrictions=reject_unknown_recipient_domain,reject_non_fqdn_recipient,permit_sasl_authenticated,reject
  -o smtpd_milters=inet:127.0.0.1:8891
#  -o syslog_name=postfix/submission
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps     inet  n       -       n       -       -       smtpd
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       n       -       -       qmqpd
pickup    unix  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp
        -o fallback_relay=
        -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache
spamass   unix  -       n       n       -       -       pipe
    flags=DRhu user=vmail:vmail argv=/usr/bin/vendor_perl/spamc -u ${recipient} -e /usr/lib/dovecot/deliver -d ${recipient}
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
#maildrop  unix  -       n       n       -       -       pipe
#  flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
#
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
#uucp      unix  -       n       n       -       -       pipe
#  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# ====================================================================
#
# Other external delivery methods.
#
#ifmail    unix  -       n       n       -       -       pipe
#  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
#
#bsmtp     unix  -       n       n       -       -       pipe
#  flags=Fq. user=bsmtp argv=/usr/local/sbin/bsmtp -f $sender $nexthop $recipient
#
#scalemail-backend unix -       n       n       -       2       pipe
#  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store
#  ${nexthop} ${user} ${extension}
#
#mailman   unix  -       n       n       -       -       pipe
#  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
#  ${nexthop} ${user}

Answer: This error
Sender address rejected: not owned by user xxx;

came from this restriction on submission port (master.cf file)
submission inet n       -       n       -       -       smtpd
  ...
  -o smtpd_sender_restrictions=reject_sender_login_mismatch
  ...

As explained in man 5 postconf,

reject_sender_login_mismatch

Reject the request when $smtpd_sender_login_maps specifies an owner for the MAIL FROM address, but the client is not (SASL) logged in as that MAIL FROM address owner; or when the client is (SASL) logged in, but the client login name doesn't own the MAIL FROM address according to $smtpd_sender_login_maps.

The reason of iOS Mail works but Mail.app and Thunderbird doesn't is likely you didn't specified the right sender address when configured mail client.


Are there objective, unambiguous ways that the level of similarity of two bits of music can be measured?

Question: I am not sure if this kind of question is on-topic or not.
I just heard the soundtrack used in Scott Manley's recent video SpaceX Radarsat Launch Highlights (fairly quiet sound level) with the notes

Twitter sized ( less than 140 seconds) with music by Test Shot Starfish.

It reminds me very much of Jamie xx's Gosh (loud sound level).
I've set the two time cues for the videos to roughly analogous points.
Are these in fact two versions of the same music, or is the resemblance just a coincidence? Are there objective, unambiguous ways that the level of similarity can be measured? If so, how might they be applied in this case?
This one has a fairly quiet sound level:

This one has a loud sound level:
Comment: This video about whether similarity equals plagiarism, and whether you can own chord progressions, may be of interest: https://www.youtube.com/watch?v=Tpi4d3YM79Q
Comment: This video by Adam Neely about a recent Katy Perry/Flame lawsuit might help you understand - https://www.youtube.com/watch?v=0ytoUuO-qvg
Answer: The answer is mostly "it depends."  Some examples:
"Cottontail"  is a jazz number which uses the exact chord sequence of "I Got Rhythm."
Many classical composers wrote "Variations on a Theme by {other composer}."
Several pieces by Mahler, Bartok, Dvorak, to name a few, incorporate folk-music themes.
What I'm suggesting is that any given person can generate his own "figure of merit score" based on things like chord sequence, rhythms, lead tune and decide how much alike two pieces are.
Comment: "Cherokee" does not use rhythm changes.
Comment: Double checking; the answer to "Are there objective, unambiguous ways..." is *it depends*?  Suggesting that *any given person can generate his own "figure of merit score"* doesn't seem to count as an "objective, unambiguous way..." which is what I have asked about. To my question as written, perhaps then your answer is no?
Comment: In fact, [rhythm changes](https://en.wikipedia.org/wiki/Rhythm_changes) are dirt common in jazz. I've read anecdotes that jazz music students are sometimes assigned to write music using the rhythm changes.
Comment: @PiedPiper you are correct;  I was ambiguous in my statements
Comment: A distinctive feature of Rhythm changes is the middle 8's 4 chained V-I progressions. Cherokee has a chain of 8.
Answer: No, there's no objective mathematical distance metric for music excerpts.  Although there's immense marketing funding to make one, it would depend on:

listeners' cultural background: if you grew up listening to ragas, Beethoven and the Beatles are indistinguishable.
human psychoacoustic messiness: listening conditions enormously affect which aspects of the music you can attend to, nevermind recall in an A-B-A test.
personal musical history: within the Western tradition, there's only so many chord progressions.  Air on the G String, Pachelbel's Canon, Wachet Auf, Warm and Tender Love all are sisters harmonically to Whiter Shade of Pale.  When one considers its lyrics, its sisters are even more numerous.

My recent peer-reviewed paper about this shows how far we still fall short of what you desire.
Comment: Gosh! (title of one of the videos) thanks for the links! I will have a look in depth soon. fyi speaking of ragas, I've just posted a question that I'd drafted a long time ago but apparently never asked: [Have traditional tunings for sitar been lost? Did the even-tempered scale have something to do with it?](https://music.stackexchange.com/q/91289/37941)
Answer: If you could reduce the two examples of music to some kind of code then you have an objective measure; two codebases can always be compared with tools.
So maybe some kind of frequency or signal curve analysis? It's not my field.
Comment: This is essentially what tools like Shazam do to identify not only the piece but the  specific performance.   I don't know what the Shazam's algorithms'  error rate is for two performances or songs that are almost identical.
Comment: @CarlWitthoft I use SoundHound rather than Shazam but there the error rate for different recordings of the same piece of classical music is extremely high. It mostly recognizes the piece, but which version it claims to identify is pure chance.


Create columned text reStructuredText

Question: I'm trying to format a reStructuredText section to look like so:
type1 : this     type4 : this     type7 : this
type2 : this     type5 : this     type8 : this
type3 : this     type6 : this     type9 : this

such that I can fill the page horizontally with text, does anyone know how I can accomplish this? I would guess it would have something to do with css and container?
Comment: Can you post your tried HTML and CSS?
Comment: If using a CSS framework is an option, you could accomplish something like this with Bootstrap.
Comment: Would a table be an option?
Answer: This is best alternative I have, in place of playing with css and container...
I don't think there is a way to natively do what you're trying in restructured text. But, if you use Sphinx, there is a directive called hlist (horizontal list): http://sphinx-doc.org/markup/para.html
You write something like this:
.. hlist::
  :columns: 3

* A list of
* short items
* that should be
* displayed
* horizontally

And it gets converted to:

Hope this helps!

Create columned text reStructuredText


Extjs: Setting an object's data to be shown in a form

Question: I currently have an object with various fields (mostly date fields) as shown from the console log below. There are more fields than this but all are similar. Also I am aware that they are all 1970 this is how we set them on the .net side.

Object {
  gasSafeLicenseNo: "3132571",
  ngDomesticPipework: "1970-01-01T00:00:00",
  lpgDomesticPipework: "1970-01-01T00:00:00"
  lpgCentralHeating: "1970-01-01T00:00:00"
  lpgDomesticBoats: "1970-01-01T00:00:00"
  lpgDomesticCaravans: "1970-01-01T00:00:00"

I have a  view with a form in holding all the date fields etc etc..

                   {
                        xtype: 'datefield',
                        labelWidth: 50,
                        name: 'ngDomesticPipework',
                        fieldLabel: 'NG'
                    },

All fields have identical names in the model, view and data object but will not load into my form ready for editing. I am simply getting the form element with a component query setting the data to be the object I want to load and calling load record.

           var data = record.get('engineer').gasSafeCard;
           gasSafeFormCmp.loadRecord(data);

Thanks folks massive help as always.
Answer: You data object is not a model instance, use setValues instead or loadRecord.
gasSafeFormCmp.getForm().loadRecord(data);

Comment: Hi Rixo thanks but there still not loading into the view ive tried both methods, could it be anything else?
Comment: Yes, since your dates are strings you should configure the date format in your fields, probably using [`altFormats`](http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.field.Date-cfg-altFormats) to save `dateFormat` for desired display format. FYI, your date format is `'Y-m-d\\TH:i:s'`.
Comment: Genius, I hope your getting paid enough to help people like me! Thanks again.


Unity 3D movement when no movement is desired

Question: Very new to mono develop and Unity 3d and seem to be having issues with this code. First off, the code IS working. It does what it's supposed to, however, it also does some funky stuff that it's not supposed to. You are able to look up, down, left and right as well as walk those directions, the bad part is though for some reason my character likes to nudge the direction of the mouse when standing still. What am I missing? More efficient/less buggy way of doing this?
<code>public class PlayerControl : MonoBehaviour {

    public float WALK_SPEED = 1.3f;
    public float RUN_SPEED = 4.0f;
    public float STRAFE_SPEED = 5.0f;
    public float ROTATION_SPEED = 300.0f;
    public float JUMP_FORCE = 250.0f;
    void Start()
    {
    }
    // Update is called once per frame

    void Update ()
    {
        float movementSpeed = WALK_SPEED;
        float strafeSpeed = STRAFE_SPEED;
        float rotationSpeedx = ROTATION_SPEED;
        float rotationSpeedy = ROTATION_SPEED;

        if (Input.GetKey(KeyCode.LeftShift))
        {
            movementSpeed = RUN_SPEED;
        }

        movementSpeed = Input.GetAxis("Vertical")  * movementSpeed * Time.deltaTime;
        strafeSpeed = Input.GetAxis("Horizontal")  * strafeSpeed * Time.deltaTime;
        rotationSpeedx = Input.GetAxis("Mouse X") * rotationSpeedx * Time.deltaTime;
        rotationSpeedy = Input.GetAxis("Mouse Y") * rotationSpeedy * Time.deltaTime;

        Vector3 rotate = new Vector3 (-rotationSpeedy, rotationSpeedx, 0);

        transform.Translate(Vector3.forward * movementSpeed);
        transform.Translate(Vector3.right * strafeSpeed);
        transform.Rotate(rotate);

        if (Input.GetKeyDown(KeyCode.Space) &&
            transform.position.y < 30)
        {
            rigidbody.AddForce(Vector3.up * JUMP_FORCE);
        }
    }
}
</code>
Comment: Alright this makes more sense now :) I would take ZoomVirus' advice and look into your input configuration. Try messing around with the values for your Mouse input axes to see if you can resolve it that way.
Comment: Can you clarify what that means? "nudge the direction of the mouse"
Comment: @SirBraneDamuj It's like the character slowly moves in the direction of the mouse without pressing any keys or making any movements. When they should be perfectly still, they are moving slightly. I know it has to do with the `Mouse Y` portion because if you remove it and replace the `rotate` code with `transform.Rotate(Vector3.up * rotationSpeedx)` it works perfectly, you just can't look up or down.
Comment: The deadzone needs to be taken into account as you are using floats and I can't see anywhere you taking it into account
Comment: @ZoomVirus Any chance you can elaborate on that? I'm very new to game development in general.
Comment: Basically all input devices have an area around of uncertainty and you need to take that into account them being alittle off for calculations so eg if(input is <100 &input is >-100) make input 0 this isn't the correct values as it varies from device to device if(input > 100)input-=100 to get positive amount does that make sence?
Comment: Deadzone is built in to the Unity input manager. You still have to configure it, but I"m pretty sure it has non-zero default values.
Comment: Also, there is nowhere in your code that actually rotates your object. You're creating a `Vector3` but not using it anywhere.
Comment: @SirBraneDamuj This line `Vector3 rotate = new Vector3 (-rotationSpeedy, rotationSpeedx, 0);` rotates it...
Comment: All that does is create a new `Vector3` object. You're not sending that to your `Transform` to do the rotation. That line of code is the equivalent of saying `int x = 3;` It creates a variable of value 3, but that's all it does. You have to actually use that variable somewhere to rotate the object.
Comment: @SirBraneDamuj You are correct! My fault. I missed the lines. They have been added.
Answer: Try freezing rotation constraints on rigidbody component. This may stop the nudging.


Remover dados do banco com GRAILS E GORM

Question: Estou aprendendo um pouco de GRAILS e estou com o seguinte problema consigo exibir as informações de alguns usuarios cadastrados normalmente mais quando tento exclui-los não consigo e não recebo erro algum, segue o codigo
def delete() {
    Usuario user = Usuario.get(params.id)
    user.delete()
    redirect action:"index"
}

se eu imprimo na tela essa variavel user eu tenho acesso a todas as informações do usuario porem ao tentar remove-lo nada acontece
estou enviando o id assim delete/id
//EDIT estou com o mesmo problema ao fazer update nos dados..
Answer: descobri uq era tava precisando mandar um flush:true junto pq o hibernate não atualiza os dados instantaneamente


Foreach Entry in DB: Table row with Onclick Modal with a row

Question: Sorry if the title may be confusing,
I'm using Laraverl blade, and I have a foreach inside my table in order to show as many rows as database records.
@foreach ($terminals as $terminal)

                                {{ $terminal->id }}
                                {{ $terminal->serial }}
                                @if ($terminal->state != 0)
                                    id }}">{!! GetTerminalState($terminal->state) !!}
                                @else
                                    {!! GetTerminalState($terminal->state) !!}
                                @endif

                                    id) }}" class="btn btn-primary btn-sm">
                                         Terminal Details

                            @if ($terminal->state != 0)

id }}">

                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Terminal (S/N: {{ $terminal->serial }})

In use by

                                                ID: {{ $terminal->user->id }}

                                                Username: {{ $terminal->user->name }}

                                                Real Name: {{ $terminal->user->realname }}

                                                E-Mail: {{ $terminal->user->email }}

                                                OID: {{ $terminal->user->oid }}

                                                user->id) }}" class="btn btn-block btn-primary btn-sm">
                                                     Profile

                                                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

                            @endif
                        @endforeach

As you can see, inside the ForEach I use my custom function GetTerminalState which echoes a bootstrap label ("Not in use" for when $terminal->state is 0, and "In use" for when it is not 0).
When it is 0 Zero it should generate a modal, which opens on click on the label. Inside this modal I want to use a table, but that doesnt work (Table inside of a table).
So I need to move the modal out of the table, but don't want to use another ForEach later on. Also, does anyone knows of a better method of dynamically generating modals per database record?
Answer: Use javascript to generate your modals.
Listen to click event on your labels, pass the DB record id to your javascript code and make an ajax call for the data that goes into the modal and render it.


Sending a variable back to Express on click?

Question: Let's say I have a list of 10 elements each with a unique id as their name and the user can add to the list whenever.
When I click an element, I want Express to get the id of the element I clicked. If it was just one element with a fixed id I could just use req.body.idname, but there can potentially be 100.
Is there a way to do this?
So far I have:
$( "li" ).click(function() {

  var x = $(this).attr('name');
  console.log(x);
});

which does get the correct name of the element but that's it.
What I'm trying to do is pass in the id as a parameter for a function like
exports.somePage = function(req, res){
    var id = //id from clicked element goes here
    //getElement finds the foo with the id
    databaseTable.getFoo(id, function (err, foo){
        if(err)
            console.log("error");
        else {
            res.render('page', { title: 'Page',
                foo : foo
        });
    }
});

};
Comment: Use AJAX or create routes like that `/getfoo/:id` i think. Or use query parameter (`/foo/?id=ID`)
Answer: You could use AJAX to POST the data.
$("li").click(function()
{
    var ajaxData = {};
        ajaxData.name = $(this).attr('name');
    var request = $.ajax({
        type: 'POST',
        data: ajaxData,
        url: 'http://localhost:3000/handleName'
    });
    request.success(function(data)
    {
        console.log("Success.");
        for(var i = 0 ; i < data.length ; i++)
        {
            // Optional to pass some data back.
        }
    });
    request.error(function(request, status, error)
    {
        console.log(request.responseText);
    });
});

Wherea your handleName looks something like this:
app.post("/handleName", function(request, response)
{
    response.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1'); // Sometimes required.
    var name= request.body.name;
});

Maybe this isn't 100% copy/paste working for you but using AJAX and fetching the name in the request should work.
Answer: This is a two step process. First on express you need the proper routing set:
Server Side
//app = express();
    app.get('/api/:paramID1/:paramID2',function(req, res){
    //your code req.params.paramID1 or req.params.paramID2
    });

On the client side you need a link that invokes the url or ajax like: http://yourdomain/api/1/abc where 1 and abc are param1 and param2 respectively.
So something as simple as: Some Demo on click could send the information you need to the server. Or using a little bit more complex example with JQuery/Ajax:
$.get( "/api/1/abc", function( data ) {
  alert( "Load was performed. " + data );
});

Please note that when using rest there are different type of "methods" that can be invoke depending on your needs, such as POST, DELETE, UPDATE or the one just mentioned in the example GET.


PHP Apply filter on multidimensional array

Question: I have this array:
Array
(
[54190] => Array
    (
        [Dealer] => RETIRO ANDEN ANDEN
        [Products] => Array
            (
                [SWEETS] => Array
                    (
                        [2000 - 0] => Array
                            (
                                [DESC] => KIT KAT
                                [DIM] => 36X41.5G
                            )
                        [3993 - 0] => Array
                            (
                                [DESC] => COOKIE COCO
                                [DIM] => 30 X 120 GRM
                            )
                    )
                [REFRIGERATED] => Array
                    (
                        [1000 - 0] => Array
                            (
                                [DESC] => SEM C/CCHA
                                [DIM] => 9X4X135
                            )
                    )
            )
    )
[54183] => Array
    (
        [Dealer] => MIGUEL PEREZ (HIJO)
        [Products] => Array
            (
                [TRADITIONAL] => Array
                    (
                        [200 - 0] => Array
                            (
                                [DESC] => COFFEE STICK CL
                                [DIM] => 77X172.8G
                            )
                    )
            )
    )
[54451] => Array
    (
        [Dealer] => HUGO FRUGO.
        [Products] => Array
            (
                [SWEETS] => Array
                    (
                        [3993 - 0] => Array
                            (
                                [DESC] => COOKIE COCO
                                [DIM] => 30 X 120 GRM
                            )
                    )
            )
    )
[54107] => Array
    (
        [Dealer] => JAVIER M.
        [Products] => Array
            (
                [SWEETS] => Array
                    (
                        [2001 - 0] => Array
                            (
                                [DESC] => COOKIE VAINILLA
                                [DIM] => 30 X 120 GRM
                            )
                    )
            )
    )
)

And I need to apply a filter to show only those arrays that contain within the  [Products] array the following codes '2000 - 0' or '2001 - 0' and also excluding the rest of the products.
Output:
Array
(
[54190] => Array
    (
        [Dealer] => RETIRO ANDEN ANDEN
        [Products] => Array
            (
                [SWEETS] => Array
                    (
                        [2000 - 0] => Array
                            (
                                [DESC] => KIT KAT
                                [DIM] => 36X41.5G
                            )
                    )
            )
    )
[54107] => Array
    (
        [Dealer] => JAVIER M.
        [Products] => Array
            (
                [SWEETS] => Array
                    (
                        [2001 - 0] => Array
                            (
                                [DESC] => COOKIE VAINILLA
                                [DIM] => 30 X 120 GRM
                            )
                    )
            )
    )
)

And i solved the question, the answer is below. and works perfectly to the case.
Special thanks to incognito user that helped, but eliminated his response. :)
Comment: http://php.net/manual/en/function.array-filter.php
Comment: Hint: For each dealer filter the products down to what you are looking for, then filter out the dealers with no more products.
Comment: This will help, http://php.net/manual/en/function.array-key-exists.php if you have any problem we will help you.
Comment: Possible duplicate of [Check if specific array key exists in multidimensional array - PHP](https://stackoverflow.com/questions/19420715/check-if-specific-array-key-exists-in-multidimensional-array-php)
Answer: Solution:
$find = array('2000 - 0', '2001 - 0');
    foreach ($ArrayIn as $k1 => $v1) {
        foreach ($v1['Products'] as $v2 => $v3) {
            foreach ($v3 as $key => $value) {
                    if(in_array($key, $find)){

                        if($Last != $k1){
                        $Line = array();
                        $Last=$k1;
                        }

                        $Line[$v2][$key]= $ArrayIn[$k1]['Products'][$v2][$key];

                        $output[$k1] = $output[$k1] = array(
                                        'Dealer' => $ArrayIn[$k1]['Dealer'],
                                        'Products' => $Line
                                        );
                    }
                }
            }
        }


Editar com Radio button em jsf

Question: Bom estou comecando agora a desenvolver com o JSF e estou com uma duvida de como fazer para o meu metodo editar receba o objeto certo do radio button , do jeito que esta implementado ele sempre pega o primeiro da table e nao o que esta selecionado pelo radio, o que eu deixei de ver ?

JSF

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
    <link rel="stylesheet" href="#{resource['css:materialize.min.css']}" type="text/css"/>
    <link rel="stylesheet" href="#{resource['css:style.css']}" type="text/css"/>
    <title>Usuários</title>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

</h:head>

<h:body>

Editar com Radio button em jsf


Suppose that $v_1,...,v_m$ is a list in $V$.

Question: Suppose that $v_1,...,v_m$ is a list in $V$. What can be said of the list if $v_j \in span(v_1,....,v_{j-1})$, for some $1 \leq j \leq n$? What happens to the span if $v_j$ is removed from the list?
not sure what would be an answer for the first question but i think if $v_j$ is removed then the list would still be equal.
Comment: You are correct that $v_j$ can be removed from the list without changing the $\text{Span}$. That's because the list is one of linearly dependent vectors, as $v_j\in\text{Span}(v_1,\ldots,v_{j-1})$ means that $v_j$ can be obtained by a linear combination of the vectors $v_1,\ldots,v_{j-1}$. So, $v_j$ is redundant in the list.
Answer: If $v_j\in span\{v_1,...,v_{j-1}\}$, then we know that $v_1,...,v_m$ are not linearly independent and therefore are not a basis for $V$.
You are correct: if $v_j$ is removed from the list, then the span would still be equal (though the list itself would have one fewer element, so you may want to check your wording).
Answer: As for the first question, we can say that the vectors $v_1,\ldots,v_m$ are not linearly independent. As for the second, the span is not changed.


How do I measure the time series forecasting accuracy?

Question: I have my data for 10 years and I used ARIMA model to forecast data for 30 years.
Now, I want to measure the forecasting accuracy for the next 30 years.
How do I calculate each one of MAD, SMAPE, MAPE and etc....?
Each one of these formulas needs actual and forecast data. How could I do with 30 years forecast, where there is no actual data?
Comment: If there is no actual data to validate the forecasts against, then there is no way to assess forecast accuracy. You have to forecast data that you actually have (i.e. pseudo out-of-sample forecasting) to be able to assess forecast accuracy out of sample.
Comment: @Richard Hardy. Huge and Big THANKS. I will not use pseudo out-of-sample forecasting but from your comment I got the answer.
Comment: You are welcome! Good luck with forecasting!
Comment: Easy, just wait 30 years and you will see ;) Seriously though, the right approach has been mentioned in an answer, but I still wouldn't forecast 30 years into the future based on 10 years data.
Comment: @user7019377 :) heh. It is industrial problematic. There is no data enough and they need to forecast. I cannot say it will be precise but can be good enough.
Comment: What I mean by that is that I wouldn't forecast 30 years into the future by basing it just on data and the assumption that any observed trends can be extrapolated. You need domain knowledge to anticipate possible events that might affect the trend but cannot be seen in historic data. You should then construct a couple of scenarios (if this happens, the trend likely reacts like this, if that happens, the trend would however react like this...)
Answer: To answer this question.
You need to train your model on the data that you have first.
Like train your forecasting model on 5 over 10 years data.
Then select the best state that you can use to evaluate the rest of data and forecasting accuracy.
Later, forecast data for 30 years.
In this case, you validate your model and you have the worthy case to forecast by.
Comment: Just be aware that you cannot train and evaluate the model on the same data. You should train the model on the training subsample and then evaluate on another subsample. Otherwise you will get overly optimistic evaluations.
Comment: Yes totally agree
Comment: @RichardHardy that's a good advice


IIS 7. Websites routing to avoid CORS

Question: I'm trying to setup my local development environment for an angular application. I have the following projects:

.NET Web API project that is hosted on a separate website (let's say localhost:81)
MVC project with angular components hosted on default web site (localhost)

I want to use API from my angular app, however right now I need to deal with CORS requests as API is hosted on different web site. I want to avoid it.
I want to setup and endpoint for my MVC site (localhost/api) that is the proxy to API web site.
How can I do this using IIS?
URL rewrite module is not suited for such scenarios.
Answer: I hope this answers your question or points you in the right direction, I am also looking into this,
I used POSTMAN to test IIS web site to return something, for example
http://localhost/assets/json/config.json?=undefined
...I get the following header items:
Postman GET API result without CORS
as you can see the CORS is missing,

In the root directory which IIS web site points at (i.e. wwwroot) create if one does not exist yet web.config file and in it add the following

Adding web.config file to IIS web app root directory
web.config

now run same thing with postman again and you should see CORS appearing

Postman GET API result with CORS
source:
https://enable-cors.org/server_iis7.html

IIS 7. Websites routing to avoid CORS


Problema em respeitar grids, adicionando campos dinamicamente

Question: Bom dia,
Estou criando um formulário que o usuário irá adicionar mais campos dinamicamente (Código referência), Porém o campo é criado mas não respeita as grids (Bootstrap4) que deveria seguir.
Exemplo:

Área selecionada em vermelho foi criada manualmente no código, está correto!
Porém a área Azul que foi criada dinamicamente deveria ocupar o mesmo tamanho que a área vermelha (manual) o que não ocorre :(
OBS: Área vermelha e azul apenas são para exemplificar o local/tamanho.
Segue o código (jsfiddle), para visualizar o problema é necessário expandir ao máximo há área que renderiza o código.
Desculpe o código ruim, ainda estou estudando...
Agradeço desde já.
Atenciosamente,
Jeferson Silva.
Answer: Simples amigo, dando uma olhada no link que você disponibilizou eu observei que você fazia um:
let container = document.getElementById('people-container');
let div = document.createElement('div');
div.innerHTML = template;
container.appendChild(div);

A ideia está correta, oque está errado é o lugar onde a div people-container se encontra. você está adicionando form-row dentro de um form-row, a solução para seu problema é colocar a div com id people-container fora da div form-row. Vou compartilhar o código com sua estrutura editado.

      <form action="" method="post">

Nome_Projeto

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias, velit.

            Nome Data Exntesion:
            <input type="text" class="form-control" id="NomeDE" placeholder="Nome Data Extension..." name="NomeDE" required>

            External Key:
            <input type="text" class="form-control" id="ExternalKey" placeholder="External Key..." name="ExternalKey" required>

            Nome Campo:
            <input type="text" class="form-control" id="NomeCampo" placeholder="Nome Campo..." name="NomeCampo[1]">

            Tipo:
            <select class="form-control" id="TipoCampo" name="TipoCampo[1]">
                  <option>Text</option>
                  <option>Number</option>
                  <option>Date</option>
                  <option>Boolean</option>
                  <option>EmailAddress</option>
                  <option>Phone</option>
                  <option>Decimal</option>
                  <option>Locale</option>
            </select>

            Status:
            <select class="form-control" id="StatusCampo" name="StatusCampo[1]">
                  <option>Primary Key</option>
                  <option>Nullable</option>
            </select>

 // coloquei a div aqui, fora da div form-row

          + Campo

      </form>

Bons estudos Jeferson. Confira o código funcionando aqui.
Comment: Cara muito obrigado ontem eu fiquei tentando várias coisas e não tinha chegado nisso!
Comment: Que ótimo que consegui te ajudar Jeferson, poderia marcar minha resposta como a certa ? É só você clicar no ícone de certo do lado da minha resposta :) .
Comment: já marquei irmão! Obrigado mesmo!
Answer: 1 - remove a div id="people-container", id deve ser unico, se necessario cria uma class
2 - usa o append de html em vez de criar div, essa nova div não vai conter estilos, e por isso não respeita as grids
let i = 2;
document.getElementById('add-new-person').onclick = function () {
    let template = `

      Nome Campo:
      <input type="text" class="form-control" id="NomeCampo" placeholder="Nome Campo..." name="NomeCampo[1]">

      Tipo:
      <select class="form-control" id="TipoCampo" name="TipoCampo[1]">
            <option>Text</option>
            <option>Number</option>
            <option>Date</option>
            <option>Boolean</option>
            <option>EmailAddress</option>
            <option>Phone</option>
            <option>Decimal</option>
            <option>Locale</option>
      </select>

      Status:
      <select class="form-control" id="StatusCampo" name="StatusCampo[1]">
            <option>Primary Key</option>
            <option>Nullable</option>
      </select>

`;

let container = document.getElementById('people-container');
container.insertAdjacentHTML('beforeend', template);

i++;
}

Comment: Obrigado também por responder!! de coração!


Converting date to GMT

Question: I want to convert a date to GMT.
I get a date in BST, I want to convert it to GMT without time zone conversion.
Example:
**If the BST date is: Wed June 26 13:30:13 BST 2019
I want to convert it to Wed 26 Jun 2019 13:30:13 GMT**
I want to ignore the timezone info and return the same date as GMT.
For this I am trying
        private SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            private SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            private SimpleDateFormat dateFormatGmtText = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss 'GMT'");

              dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
          String textDate = dateFormatLocal.format(date);

//Date is Wed June 26 13:30:13 BST 2019
    private Date toGMTDate(final Date date) {
            String textDate = dateFormatLocal.format(date);
            try {
                String[] dateParts = textDate.split("\\+");
                textDate = dateParts[0] + "+0000";
                return dateFormatGmt.parse(textDate);
            } catch (ParseException e) {
                return null;
            }
        }

        private String toGMT(final Date date) {
            return dateFormatGmtText.format(toGMTDate(date));
        }

When I call toGMT it returns Wed 26 Jun 2019 14:30:13 GMT
I am not sure why it is so?
What is wrong here?
Comment: A `Date` is just a number of milliseconds since the unix epoch. It doesn't have a time zone. It's unclear where your data is coming from, or in what format, but this sounds like something which is better fixed earlier on. I'd also strongly recommend using java.time rather than `Date`, `SimpleDateFormat` etc.
Comment: I recommend you don't use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime`, `OffsetDateTime` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/).
Comment: You don't get a `Date` in BST and you cannot convert to a `Date` in GMT. An old-fashioned `Date` object can have neither time zone nor GMT offset.
Comment: I think this is a duplicate of [SimpleDateFormat returns wrong time zone during parse](https://stackoverflow.com/questions/16107898/simpledateformat-returns-wrong-time-zone-during-parse) and other questions.
Comment: Since you want it as a String anyway, why not just replace the String "BST" with "GMT" and be done with it?
Comment: @OleV.V. Thanks for the comment. I am aware of the new time library, but for some reasons I can't use them.
Answer: java.time
You said you can't use the modern date and time API, but for other readers I should like to present that option first. SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome, so I recommend avoiding them.
I am assuming that BST is for British Summer Time (other interpretations exist). And I am assuming that you cannot avoid getting an old-fashioned Date object.
private static DateTimeFormatter formatter
        = DateTimeFormatter.ofPattern("EEE dd MMM yyyy HH:mm:ss z", Locale.UK);
private static ZoneId britain = ZoneId.of("Europe/London");
private static ZoneId gmt = ZoneId.of("Etc/GMT");

private static String toGMT(final Date date) {
    ZonedDateTime britishTime = date.toInstant().atZone(britain);
    ZonedDateTime gmtTime = britishTime.withZoneSameLocal(gmt);
    return gmtTime.format(formatter);
}

Try it out with your Date of Wed Jun 26 13:30:13 BST 2019:
    String textDate = dateFormatLocal.format(date);
    System.out.println(textDate);

    System.out.println(toGMT(date));

Output is:

2019-06-26T13:30:13+0100
Wed 26 Jun 2019 13:30:13 GMT

Whenever you get an old-fashioned Date, the first thing to do is to convert it to Instant. Then do any further conversions from there. The key to changing time zone and keeping the date and time of day (hour-minute-second of day) is the withZoneSameLocal method of the ZonedDateTime class.
I recommend specifying locale for the formatter.

I am not sure why it is so? What is wrong here?

A Date hasn't got, as in cannot have a time zone. It's a point in time, nothing more. YourtoGMTDate method returns a point in time that is an hour later: The time you gave it was 13:30:13+0100, and it returned 13:30:13+0000, which is the same point in time as 14:30:13+0100. Next you formatted this point in time using a formatter that used your default time zone, Europe/London, and therefore produced 14:30:13, but at the same time printed GMT in the string — the result you reported.

…the new time library, but for some reasons I can't use them.

If you really have got an evil boss that either forces you to use Java 1.4 or 1.5 and/or forbids the use external dependencies, the pretty simple hack is:
private String toGMT(final Date date) {
    return dateFormatGmtText.format(date);
}

The cheating is: Your dateFormatGmtText uses your default time zone, Europe/London, but lies and prints GMT in the formatted string. This gives the same output as above — the output you asked for. Compared to your code I am just leaving out the date conversion.
Link: Oracle tutorial: Date Time explaining how to use java.time.

Converting date to GMT


C# Conflicts with the declaration

Question: I have written this Employee class using C# winforms where Employee is promoted if Employee.Experience >=5.
I am getting an error on the line:
Employee.PromoteEmployee(empList,employee=>employee.Experience>=5);

conflicts with the declaration Delegateusage01.Employee

I have read an article on MSDN and few others on Stackoverflow on this topic but I just can not find that error.
namespace DelegateUsage01
{
    public partial class Form1 : Form
    {
        static List<Employee> empList = new List<Employee>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CreateNewEmployee(new Employee() { Id = 101, Experience = 5, Name = "Peter", Salary = 4000 });
            CreateNewEmployee(new Employee() { Id = 100, Experience = 5, Name = "Peter", Salary = 4000 });
        }

        private static void CreateNewEmployee(Employee emp)
        {
            int index = empList.FindIndex(Employee => Employee.Id == emp.Id);
            if (index != -1)
            {
                Console.WriteLine("Two id can not be the same");
            }
            else
            {
                empList.Add(emp);
            }
            Employee.PromoteEmployee(empList,employee=>employee.Experience>=5);
            //getting error on this line
        }
    }

    delegate bool IsPromotable(Employee empl );

    class Employee
    {
        private int _id;
        private int _salary;
        private string _name;
        private int _experience;

        public int Id
        {
            get { return _id; }
            set
            {
                if (value <= 0)
                {
                    throw new Exception("ID can not be null");
                }
                _id = value;
            }
        }

        public string Name
        {
            get { return _name; }
            set
            {
                if (value == String.Empty)
                {
                    throw new Exception("Name can not be empty");
                }
                _name = value;
            }
        }

        public int Salary
        {
            get { return _salary; }
            set
            {
                if(value<=0)
                { throw  new Exception("Salary cannot be negative");}

                _salary = value;
            }
        }

        public int Experience
        {
            get { return _experience; }
            set
            {
                if (value < 0)
                {
                    throw new Exception("Experience can not be negative");
                }
                _experience = value;
            }
        }

        public static void PromoteEmployee(List<Employee> employeeList,IsPromotable IsEligibleToPromote)
        {
            foreach (var employee in employeeList)
            {
                if (IsEligibleToPromote(employee))
                {
                    Console.WriteLine("Employee: {0} with employee id: {1} is eligible for promotion", employee.Name, employee.Id);
                }
            }
        }
    }
}

Answer: The problem is in the line that you call FindIndex from List, you cannot use the name Employee there, use this instead :
  int index = empList.FindIndex(e => e.Id == emp.Id);

Answer: Change your method signature from
PromoteEmployee(empList,employee=>employee.Experience>=5)

to the following
PromoteEmployee(empList,Func<Employee,bool>);

then you call
Employee.PromoteEmployee(empList,employee=>employee.Experience>=5);

Comment: Dear friend its generic delegates you can pass any logic to it like if you  dont want to hard code your implementation then you can use it like in you scenario you pass your employee type then in calling code you can do any thing you want. like as you do comparing
Comment: and one thing more please mark as answer if its helpful for you :D
Comment: thanks for answer. Why do you suggest I should use Func  What is the difference?
Answer: Drop the delegate alltogether, that's obsolete .NET 1.0 stuff.
Your function should take a Func<Employee,bool> instead. That should compile.
Comment: Actually Func was only added in 3.5, but Predicate is a good alternative for 2.0 or 3.0.

C# Conflicts with the declaration


Calculating the amount we shorten the repayment time of a loan by readjusting installments

Question: Assuming we can afford to pay 1000 E/month and we subscribe to a 20-year mortgage plan at 5% annual rate. I first want to know what the maximal mortgage can be.
I have the following formula:
$C=\cfrac{P}{\cfrac{1-(1+r/12)^{-n}}{r/12}}$,
 where $n$ is the number of monthly instalments of $C$ euros we have to pay in order to pay off our loan of $P$ euros with $r$ the annual interest rate.
I know that $n=20*12=240$ months, $ r=0.05$ and $ C=1000 $ thus I calculate the maximal mortgage ($P$) using the formula this gives $P=151525$.
Know assume that after 5 years we readjust the installments to 1200 E/month. I want to know how much this shortens the repayment time. Again I have a formula that calculates the amount we have to pay after k payments:
$P\cfrac{(1+r/12)^{n}-(1+r/12)^{k}}{(1+r/12)^{12}-1}$
with this I calculate the amount we have to pay after 5 years i.e. $5*12=60$ payments thus if we use $k=60$, $r=0.05$ and $n=20*12=240$ we get that $P=126454.98$. Now that we have the amount we still have to pay I can use the initial formula $C=\cfrac{P}{\cfrac{1-(1+r/12)^{-n}}{r/12}}$ with $P=126454.98$, $ r=0.05$ and to calculate $n$ when I do this I get that $n=-138.473$ in other words I still have to pay $-138.473/12=-11.5$ years. This doesn't seem right can anyone tell me what I'm doing wrong?
Answer: Loan balance equals the NPV of future cash-flows.
Under level payments:
$P = C\sum_\limits{i=1}^{n} (\frac {1}{1+r})^i$
$P = C\frac {(1- (\frac {1}{1+r})^n)}{r}$
with stepped up payments after 5 years
$1000\sum_\limits{i=1}^{240} (\frac {1}{1.004167})^i = 1000\sum_\limits{i=1}^{60} (\frac {1}{1.004167})^i+1200\sum_\limits{i=61}^{x} (\frac {1}{1.004167})^i$
And we need to find x
$1000\sum_\limits{i=61}^{240} (\frac {1}{1+r})^i = 1200\sum_\limits{i=61}^{x} (\frac {1}{1+r})^i$
$1000\frac {(1+r)^{60} - (1+r)^{240}}{r} = 1200\frac {(1+r)^{60} - (1+r)^x}{r}\\
200(1+r)^{60} + 1000(1+r)^{240} = 1200(1+r)^x\\
\frac {2969}{1200} = (1.004167)^x$
take the log of both sides
$x = \frac {\log 2.4744}{\log 1.04167} = 218$
total payments  or 22 months shorter.


Multiple t tests or something else?

Question: I have shown my respondents eight short films and asked them to rate the emotions that each film caused. Under each short film, I asked the respondents to rate on a scale of 1-5 how much of each emotion they felt when watching the film. There were six emotions to rate under each film. Four of the films are uneventful and four are dramatic, and I would like to assess if the four dramatic films cause more emotions overall than the "boring" ones. What would be the best way to do the comparison?
Comment: If you are interested in dramatic versus uneventful in general rather than your specific 4 dramatic versus your 4 uneventful, you should include "film" as a random effect.
Answer: It appears that you have a block experiment with subjects as blocks and films as treatments. If you can fit that block model for each emotion you measured, then it appears the question you ask could be addressed by estimating and testing a single contrast with coefficients <code>[-1, -1, -1, -1, +1, +1, +1, +1] / 4</code>, (re-ordered as necessary -- I'm assuming the first 4 are boring and the last 4 are dramatic), which will compare the average rating for the dramatic films minus the average rating for the undramatic films.
I see the SPSS tag, and it has been so many decades since I've used that program that I can't help in the particulars of doing it with that software.
I hope you randomized the order of films differently for each subject. If not, the differences among the films could be due in part to the order in which they were presented, and there is no way of knowing with much certainty what those effects are.

Multiple t tests or something else?


Exchange the double infinite sum order

Question: I am trying to exchange the order of a double summation, but I think I've failed on doing it. The sum and my result is
$\sum_{r=0}^n\sum_{m=r}^\infty=\sum_{m=0}^\infty\sum_{r=0}^m$
I obtained this drawing a triangle and seeing the behavior of the indices,
but I'm almost sure that there is an error, since the main result of the whole equation is not satisfactory. So I would be really grateful if some could help me to find the way to solve this. Thanks in advance.
Comment: On the right hand side there isn't an $n$ so that you're allowing values of $r$ bigger than $n$. This doesn't happen on the left hand side. Instead, for fixed $m$ on the right hand side, you should get values of $r$ between $0$ and $\min\{m,n\}$.
Comment: So, if I understand correctly, I have to split the two sums in the left to four sums in the right?
Answer: As @rhys suggested. The way of change the order of the double sum is taking into account that we are performing a summation over an infinite triangle $0 \leq r \leq m $. So the double sum turns into
$\sum_{r=0}^n \sum_{m=r}^\infty = \sum_{m=0}^n \sum_{r=0}^m + \sum_{m=n+1}^\infty \sum_{r=0}^n $

Exchange the double infinite sum order


elastic search combining multiple term and range queries is providing zero results

Question: I am struggling on this for a week now. I need to write an elasticsearch query api in java with following combinations:

Price range (0 to n number of ranges)
Age range (0 to n number of ranges)
Search text
Term Filters (can match more than one field

I want to have OR relationship within each group (e.g. price 0-10 or 11-15) but AND relationship among different groups (e.g. price 0-10 AND productType="clothing")
I have written the below code in Java, I have verified that the data exists for the range and filter I am testing with but I am getting zero resultset.  I am not sure what is missing here.
<code>@Override
public List<Shoppingi> search(SearchCriteria criteria, Pageable pageable) {

    final NativeSearchQueryBuilder searchQuery = new NativeSearchQueryBuilder();
    BoolQueryBuilder boolQuery = boolQuery();
    // apply the text search
    if (StringUtils.isNotBlank(criteria.getSearchText()))
        boolQuery.must(multiMatchQuery(criteria.getSearchText(), FIELD_NAMES_FOR_TERM_SEARCH));
    // apply the term filters
    BoolQueryBuilder termsQuery = boolQuery();
    criteria.getFilters().entrySet().stream().forEach(entry -> termsQuery.should(termsQuery(entry.getKey(), entry.getValue())));
    // apply the range filters
    BoolQueryBuilder rangeQuery = boolQuery();
    criteria.getRangeFilters().forEach((key, value) -> rangeQuery.should(rangeQuery(key).gte(value.getLowerBound()).lt(value.getUpperBound())));
    boolQuery.must(termsQuery);
    boolQuery.must(rangeQuery);
    searchQuery.withQuery(boolQuery);
    searchQuery.withPageable(pageable);
    NativeSearchQuery query = searchQuery.build();
    log.info("query: {}", query.getQuery().toString());
    return elasticsearchTemplate.queryForList(query,Shopping.class);
}
</code>
Answer: I annotated the price object as index.no, which caused the query to not work. Once I re-indexed my data with price as non_analyzed, my code started working. So it was nothing wrong with the code above, it was the way I configured the variable I was querying against.


Factoring polynomials modulo 3

Question: Let $f(x) = x^5 + 2x^2 + 2x + 2 \in\mathbb Z_3[x]$. Then the irreducible factorization of $f(x)$ is $(x^2 +1)(x^3+2x+2)$ even though it does not have a root in $\mathbb Z_3$. How did we find that factorization? What am i missing here?
I want to build an extension field over $\mathbb Z_3$.
Comment: You could note that $\pm i$ are roots.
Answer: You find this by trying to divide $f(x)$ by all possible irreducible polynomials of degree $2$ over ${\mathbb Z}_3$.
Since $f(x)$ has no root and it is of degree $5$, it is either irreducible or factors as a polynomial of degree $2$ times a polynomial of degree $3$. There are only 9 monic polynomials of degree $2$ over ${\mathbb Z}_3$ and only three of them are irreducible: $x^2 + 1$, $x^2 + x + 2$, $x^2 + 2x + 2$. Even if you don't know these or don't want to figure them out first, you can always try all $9$, discarding the ones that you immediately identify as reducible.
Answer: It's easy to see that $f(x)$ has no root in $Z_3$, just by checking $x=0,1,2$, so if $f(x)$ did factor, it must factor as a degree 2 polynomial multiplied with a degree 3 polynomial. We can further deduce to:
$$f(x)=(x^2+ax+b)(x^3+cx^2+dx+e)$$ with each $a,b,c,d,e\in Z_3$. expanding this out gives:
$$x^5+2x^2+2x+2=x^5+(a+c)x^4+(a+b+d)x^3+(ad+bc+e)x^2+(ae+bd)x+be$$
So we now have the system:
$$a+c=0$$
$$a+b+d=0$$
$$ad+bc+e=2$$
$$ae+bd=2$$
$$be=2$$
So either $b=1$ and $e=2$ or the way around, and $c=-a$, guessing $b=2$ and $e=1$ gives:
$$a+d=1$$
$$ad-2a+1=2$$
$$a+2d=2$$
Subtracting the first from the third results in $d=1$, so that $a=0$, but this would make $1=2$ with the second equation, so really $b=1$ and $e=2$ and we actually now have:
$$a+d=2$$
$$ad+c=0$$
$$2a+d=2$$
and now subtracting the first from the third gives $a=0$, making $d=2$ and $c=0$, which completes the factorization.

Factoring polynomials modulo 3


case when for multiple conditions not working in R

Question: Here's my code:
    breakover <- function(correlation, growth_factor, wells_per_section, max_breakover = 16){
           case_when(correlation[wells_per_section == max_breakover] > 0.999 ~ max_breakover,
                all(growth_factor) > 0.8 ~ max_breakover,
                T ~ wells_per_section[min(which(growth_factor < 0.8))]-1)
    }

If the 16th correlation between section_eur and wells_per_section is greater than 0.999, record the breakover spacing as 16.
If the growth_factor column is always > 0.8 (from first row to the max row for the same reservoir_id), record the breakover spacing as 16,
The third condition is if none of the above is true, go find where growth_factor is <0.8 locate the cell above it since that's the last >0.8 value, and record the wells_per_section, so when I don't have "all(growth_factor) > 0.8 ~ max_breakover," it's working fine, when I add it, it's not working as desired, but I do need that condition.
And here's the partial dataset if it helps to understand my problem:
data <- tibble::tribble(
  ~reservoir_id, ~Wells_per_section,        ~well_eur,     ~section_eur,         ~incr_eur,      ~growth_factor,      ~correlation,
            187,                 1L, 23175.4846595876, 23175.4846595876,  23175.4846595876,                   1,                 1,

I'll then apply this function to get a new data frame:
breakover_spacing <- sim_breakover %>%
  dplyr::group_by(reservoir_id)%>%
  dplyr::summarise(breakover = breakover(correlation, growth_factor, Wells_per_section))

This would be the output:
  reservoir_id, breakover
       187         16
       188          2

I think my issue is in the case when "all(growth_factor) > 0.8 ~ max_breakover"
Answer: There are couple of issues in the breakover code i.e. all(growth_factor) > 0.8 would be all(growth_factor > 0.8) (as all(growth_factor) returns TRUE when all the values are not 0 instead it should be based on the logical condition with 0.8) and in the first condition should be wrapped in any.  Also, as this is a summarisation which involves returning a single value, we may use if/else here
library(dplyr)
sim_breakover %>%
  group_by(reservoir_id) %>%
  dplyr::summarise(breakover =  if(any(correlation > 0.999 &
      Wells_per_section == 16) |all(growth_factor > 0.8)) 16
     else first(Wells_per_section[growth_factor < 0.8])-1)

-output
# A tibble: 2 × 2
  reservoir_id breakover
         <dbl>     <dbl>
1          187        16
2          188         2

Comment: Hello sir, thank you for the explanation! When I run with my real data, there's an undefined value and it's causing this error "x missing value where TRUE/FALSE neededℹ The error occurred in group 3090: reservoir_id = 3090." Am I able to bypass the error and continue the run?
Comment: Change the `first(Wells_per_section[growth_factor < 0.8])` to `Wells_per_section[growth_factor < 0.8][1]`


Calculate supremum of $\left|1-e^{-\gamma_n t}\right|$

Question: Calculate Sup (Supremum) of:
$$\sup_n \left|1-e^{-\gamma_n t}\right|$$
and
$$\sup_n \left(e^{-\gamma_n t}\right)$$
where $|\gamma_n|\leq M$, $M \in \mathbb R^+$ and $\gamma_n\in \mathbb R$; t is a parameter such that $t\in [-\pi,\pi]$.
My solution.
$$\sup_n \left(e^{-\gamma_n t}\right)\leq e^{|L|}$$
because $e^{-x}$ is decreasing and L real constant (maybe $L=M\pi$?)
$$\sup_n \left|1-e^{-\gamma_n t}\right|\leq e^{|L|}-1$$
because, putting $y=|1-e^{-x}|$ and evaluating in $x=\pm h, h>0$ we have that $y_{h^-}>y_{h^+}$.
Is my procedure right? I made a mistake?
thank you very much
Comment: there is an issue with the supremum over $n$, since it does not depend on $t$ we cannot determine whether $\gamma_nt$ is positive or negative.
Answer: It seems right but I think for:
$\sup_n(e^{-\gamma_nt})$, you need to argue the fact for $t\in[-\pi,\pi]$ there exists a $t^*=-sign(\gamma_n)\pi$, since then you can argue:
$\sup_n(e^{-\gamma_nt})\leq\sup_n(e^{-\gamma_nt^*})=\sup_n(e^{-(-sign(\gamma_n))\gamma_n\pi})=\sup_n(e^{sign(\gamma_n)\gamma_n\pi})=\sup_n(e^{|\gamma_n|\pi})=e^{M\pi}$.
Comment: Ok. This also applies to $\sup_n \left|1-e^{-\gamma_n t}\right|
$?
Comment: Yes it would :)


How Android grid layout set component fill the specified row and column?

Question: code:
<code><GridLayout
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:rowCount="6"
  android:columnCount="4" >

<!-- define textbox,Across the four columns -->

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_columnSpan="4"
    android:textSize="50sp"
    android:layout_marginLeft="4px"
    android:layout_marginRight="4px"
    android:padding="5px"
    android:layout_gravity="right"
    android:background="#eee"
    android:textColor="#000"
    android:text="test"
    />
<!-- define two buttons,Delete and reset -->

<Button
    android:id="@+id/bn1"
    android:layout_columnSpan="2"
    android:layout_rowSpan="1"
    android:layout_gravity="fill"
    android:text="clear"
     />

<Button
    android:id="@+id/bn2"
    android:layout_columnSpan="2"
    android:layout_rowSpan="1"
    android:layout_gravity="fill"
    android:text="selete"
    />
</code>
The above is the mail.xml code. The results below:

How to set the two buttons half and half and fill a line?
Thanks in advance!
Answer: You just want the two bottom buttons to fill the width equally?  Put them in a LinearLayout with layout_width=fill_parent and horizontal orientation.  Set each one to have the same layout_weight, and each one to have a width of 0dp.  That will make them equal width.


Left eigenvector for eigenvalue < 1 for a square stochastic matrix: coordinates of eigenvector sum to zero.

Question: If $v$ is a left eigenvector of stochastic matrix $P$ with $vP = \lambda v$ for $\lambda <1$, can you show that $\sum_{i = 1}^{N} v_{i} = 0$. You can assume that $v$ is normalized.
Answer: Hint. Consider $vPe$ where $e=(1,1,\ldots,1)^T$.
Comment: Thanks, I see how this works relying on orthogonality of left and right eigenvectors for distinct eigenvalues.


After using inverse probability weight, two groups are still significant

Question: I used the inverse probability weight to eliminate the bias of demographics. After creating the propensity weight, I conducted series chi-square tests to compare demographic variables among treatment groups. However, two out of seven covariates were still significant. Later on I need to create K-M curve and conduct cox-regression analysis. I am not worried about cox-regression analysis because I can put both weight and the two significant covariates into the model. But I probably can't take the two significant covariates into account when I create K-M curve plot, right? I am wondering what can I do about this? Can I ignore the two significant covariates? Or there are some methods that I can account for the two covariates when I create K-M curve? Thank you!
Answer: The use of a propensity score may not fully "eliminate" differences between groups. If the propensity model is not accurate or if real differences exist between groups assigned to various treatments, the propensity score may not normalize the covariates between groups. When this happens, you should recognize this as a limitation of your approach. However, you can make some conclusions despite covariate imbalances.
Regarding the concern about K-M modeling, use the Cox model as you normally would, and create adjusted survival or cumulative hazard curves to depict the effect of the variable of interest. In a non-randomized study design, adjusted curves are more likely to represent the true effect of a covariate of interest than KM curves.


Find out which Keystore file I used

Question: I can´t remember which Keystore file I used for my Android app.
Is there any way to find out?
Or can I search my hard drive for all Keystore files? The problem is that the file has no extension.
Comment: This could help you -- https://stackoverflow.com/questions/11331469/how-do-i-find-out-which-keystore-was-used-to-sign-an-app
Answer: Keystore files can have any extension, so it is unlikely that searching will help you.
You can extract certain details from an already signed file, like the public key, but none of these will help you locate the corresponding file on the device.
If you did it through Eclipse, it may remember the location.
If you did it through the terminal, and it wasn't ages ago, you could keep pressing the up arrow key and hope that you reach the commands you used to sign it, which will contain the file path, or you may reach a cd which switches to the directory containing the file right before your run the signing commands.
If none of these work, you're out of luck and will have to search through your files manually, or create a new keystore (in which case you will have to republish your app under a new package name if it is published).
In future, please backup your keystore to multiple (secure) locations to prevent situations like this.
Comment: To add to what you've said. As per android documentation this command can extract certain details of your .apk: `jarsigner -verify -verbose -certs my_application.apk`
Comment: This was my first Android app and I was to eager to upload it to Google Play that I didn´t read all the instructions. Big misstake!
The file is there somewhere...
Answer: If you did it through Eclipse, try re-exporting your app using:
File>>Export>>Export Android Application
and hopefully it will still be pointing to the last location of your keystore.

Find out which Keystore file I used


Is there a way to get Views Bulk Operation to place field options in the main VBO exposed dropdown

Question: I am using VBO to set the author for a one of my content types.  Currently, when you want to use the change author page, you have to..

Navigate to the page.
Select the target content items
Select 'Change Author' from the VBO drop down list (this is the only option)
Wait for the new page to load
Select the new author form the (only) drop down lost on this page.
Submit

It seems that there are a lot of extra steps here.  Is there a way to set-up the primary VBO drop down list (refereed to in step 3) so that it displays the different authors (like the drop down refereed to in step 5?)
Answer: If you check the "Skip confirmation step" box below the "Change the author of content" action, you can remove the confirmation step.
As for making it a one-click change, that would probably require either extending VBO with another module, or somehow invoking ctools modal windows with VBO. I haven't found any success stories with the latter, but there's this: Ctools Modal + Views Bulk Operations? (drupal.org)
Comment: Just remembered the "Colorbox trigger" field (requires Colorbox module). I was curious and added it to a view display and chose "Content" (my VBO field) as my trigger. Unfortunately, when I check one or more rows and invoke a VBO action, the only result is a blank colorbox. But still, this could be promising. There's also a Lightbox trigger and I wouldn't be surprised if there were a Fancybox trigger.  I probably won't experiment much more on this any time soon, but thought I'd throw this out there.


Qual a diferença entre teste e depuração?

Question: No livro "Introdução ao Teste de Software" de Ammann & Offutt menciona na  p.32 os 5 níveis modelos de maturidade de teste de software:

Nível 0 - Não há diferença entre teste e depuração.
Nível 1 - A finalidade de um teste é mostrar que um software funciona.
Nível 2 - A finalidade de um teste é mostrar que o software não funciona.
Nível 3 - A finalidade de um teste não é provar nada em específico, mas reduzir os riscos de uso do software.
Nível 4 - Teste de software é uma disciplina mental que ajuda todos os profissionais de TI a desenvolverem softwares de qualidade.

Apesar de não entrar em detalhes sobre depuração. Qual a diferença entre teste e depuração?
PS: pergunta traduzida de uma pergunta na comunidade programmers (en)
Answer: Teste
Na pergunta já tem uma boa definição sobre testes. Tem uma definição mais em ampla em Testes, TDD, Unit Test, QA e assemelhados. Qual a diferença dos conceitos sobre testes?.
Então podemos concluir que ele é uma medida para "garantir" qualidade. Você verifica se o software está conforme.
É um processo do desenvolvimento como um todo. Testes duram em todo o ciclo de vida do projeto.
Novos testes são sempre desejáveis. Se um problema for detectado por outros meios (uma depuração, por exemplo), um teste para garantir que o problema não volte ocorrer é interessante.
Testes são feitos com ferramentas específicas que automatizam o processo e códigos que possui a função de dizer se algo bem específico gerando o resultado esperado ou não.
A preocupação é com o resultado, não como se chegou nele.
Teste é para identificar quando um código está correto, não quando ele tem problema. Um erro comum é as pessoas acreditarem que se passar no teste há ausência de problemas do código, mas ele só diz que certas situações aconteceram corretamente, não pode inverter a lógica de que se passou no teste não há bugs.
Depuração
Depuração é um processo de conserto de algo que sabe-se estar quebrado.
Em geral é pontual para um defeito.
Muitas vezes o processo é iniciado porque um teste detetou que há esse defeito.
É algo que simula-se a execução passo a passo manualmente para achar o motivo do problema e determinar o que precisaria ser mudado para resolvê-lo.
Em geral é feito com o auxílio de ferramentas adicionais ou código extra para determinar o que está acontecendo e no final quando o problema é resolvido aquilo é jogado fora.
O foco é o detalhe da execução, há uma preocupação com o algoritmo e as mudanças de estado.

Todo mundo sabe que a depuração é duas vezes mais difícil do que escrever um programa em primeiro lugar. Então, se você for tão inteligente quanto pode, quando escrevê-lo, porque você vai depurá-lo?
-- Brian Kernighan

O que eu gostaria mesmo é que as pessoas que resolvem programar aprendessem pelo menos o básico da depuração, o que já ajuda entender um pouco melhor o que ela está fazendo. Em tempos que "programar" virou copiar códigos prontos e preencher lacunas sem entender o que está fazendo, saber depurar parece ser algo desnecessário. Por sorte ainda temos profissionais interessados em fazer o melhor possível e entender o processo completo.
Coloquei no GitHub para referência futura.


Graph with exactly one perfect matching

Question: How do I prove that if $G$ is a graph with $2n$ vertices and has exactly one perfect matching, then $|E(G)| \le n^2$?
Comment: What have you tried so far?  It doesn't have to seem like much, but any thoughts will help.
Comment: I am not sur but will https://en.wikipedia.org/wiki/Tur%C3%A1n%27s_theorem#Mantel.27s_theorem help? Have you tried using it?
Answer: Let $G$ be a graph with exactly one perfect matching $M$, $2n$ vertices and $m$ edges.
Let $v$ and $w$ be two vertices that are endpoints of an edge of $M$ and let $d(v)=t$.
A neighbor $u$ of $v$ different from $w$ is endpoint of an edge $e_u$ of $M$ and $w$
may not have an edge to the other endpoint of $e_u$ or we find an alternating 4-cycle,
which would lead to a second perfect matching.
So the neighbors of $w$ must avoid $t-1$ vertices, which means that $d(v)+d(w)\leq t+((2n-1)-(t-1))=2n$.
This is true for each of the $n$ matched pairs of vertices, so we find
$2m=\Sigma_v d(v)\leq n\cdot 2n$, or $m\leq n^2$, as desired.
Note that, although we only cared about alternating 4-cycles, this bound is actually sharp:
it is easy to construct (for any $n$) a graph with $2n$ vertices and $n^2$ edges that
has exactly one perfect matching.
Answer: Suppose $\{x_1y_1,\dots,x_ny_n\}$ is the unique perfect matching in $G$. Any additional edge must join a vertex in $\{x_i,y_i\}$ to a vertex in $\{x_j,y_j\}$ for some $i\ne j$. But $x_ix_j$ and $y_iy_j$ can't both be edges, or else we could get a new matching with those edges replacing $x_iy_i$ and $x_jy_j$. Likewise $x_iy_j$ and $x_jy_i$ can't both be edges. Hence there are at most $2$ edges between $\{x_i,y_i\}$ and $\{x_j,y_j\}$, and the total number of edges is $|E(G)|\le n+2\binom n2=n^2$.
The graph $G$ of order $2n$ with $V(G)=\{x_1,\dots,x_n,y_1,\dots,y_n\}$ and $E(G)=\{x_ix_j:1\le i\lt j\le n\}\cup\{x_iy_j:1\le i\le j\le n\}$ has a unique perfect matching and exactly $n^2$ edges.

Graph with exactly one perfect matching


How prove this $ \sqrt{\frac{a}{a+3b+5bc}}+\sqrt{\frac{b}{b+3c+5ca}}+\sqrt{\frac{c}{c+3a+5ab}}\geq 1.$

Question: Let $a,b,c$ be nonnegative real numbers such that $a+b+c=3$, Prove that

$$ \sqrt{\frac{a}{a+3b+5bc}}+\sqrt{\frac{b}{b+3c+5ca}}+\sqrt{\frac{c}{c+3a+5ab}}\geq 1.$$

This problem is from  http://www.artofproblemsolving.com/Forum/viewtopic.php?f=52&t=555716
@Calvin Lin  Thank you
Comment: It might help to substitute $a=3x^2$, $b=3y^2$ and $c=3z^2$. Equality holds for $a=b=c=1$.
Answer: Let $\displaystyle A = \sqrt{\frac{a}{a+3b+5bc}}+\sqrt{\frac{b}{b+3c+5ca}}+\sqrt{\frac{c}{c+3a+5ab}}$ and $\displaystyle B = \sum_{cyc}a^2(a+3b+5bc)$.
Then by Hölder's inequality we have $A^2B \ge (a+b+c)^3 = 27$.
So it is sufficient to prove that $B \le 27$
$$B = \sum_{cyc}a^3 + 3 \sum_{cyc}a^2b+5\sum_{cyc}a^2bc$$
As $\displaystyle \sum_{cyc}ab^2 \ge 3abc$ by AM-GM, we have
$$B \le \left(\sum_{cyc}a^3 + 3 \sum_{cyc}a^2b + 3 \sum_{cyc}ab^2 + 6abc\right) - 15abc + 5\sum_{cyc}a^2bc \\
 = (a+b+c)^3 - 5abc (3-\sum_{cyc}a) = 27$$
Comment: +1; Nice answer; but for Holder inequality I got $(\sum a^{2/3})3$. Just want to be sure that everything is fine.
Comment: @Arash All that is accounted for in the last edit. Thanks anyway.
Comment: You are welcome! I hope we can turn this website into something with more hospitable comments rather than hostile comments from arrogant people. :-)
Comment: @Arash You are absolutely right, my bad. Have corrected it now.
Comment: By the way, $5\sum_{cyc}a^2bc=15abc$ so the last part you have equality. Also the last term is $5\sum_{cyc}abc(a - 1)$, isn't it?
Answer: Since $a+b+c=3$ you can reduce $f(a,b,c)$ to $f(3-b-c, b, c)$. With only 2 variables you can make a 3D plot and see if it gets below $1$ for $b+c\le3$. Not an elegant proof, but it works. If nothing else it will at least show you where the edge cases are.
Comment: Are you implying that looking at a graph is a real proof ?
Comment: Sorry, I worded that badly, I meant it is not a proof and not very elegant, but it can be helpfull to see how the function behaves.
Answer: We know the one result if sum of two numbers $a$ and $b$ is constant, the max. of $ab$ occurs when both $a$ and $b$ equal. Eg. if $a+b=6$, then $\max\{ab\}=9$. Use this result, we get proof.
Comment: You don't know inequality...
Comment: I know well. I give hint only. using this hint, you prove this result.


Can not find script file "Z:\Scripts\LiteTouch.wsf"

Question: I installed and configured MDT 2013 yesterday on server 2012. I have a WDS also. I am able to create a WIM file. I did PXE boot into a test virtual machine and I was able to install Windows 10. My MDT is also on vmware ESXI. MDT server is joined to my domain.
I created a task sequence with "sysprep and capture". On the vm that I want to capture I mapped the deployment share and I tried to run the "LiteTouch.vbs" I got the following error:
Can not find script file "Z:\Scripts\LiteTouch.wsf"

I am confused because "LiteTouch.wsf" is just below the vbs file.
This is the first time I am trying to capture an image on the newly built MDT.
Please let me know what I am doing wrong or what I can do to resolve this.
Comment: Are you running this under the local administrator account, or a domain account?
Comment: @RobbieCrash on virtual machine I want to capture I am logged in as local admin, but I mapped the deployment share using domain admin credentials.
Answer: The file share to the WDS server has been created wrong. Remove the file share. Then open an elevated command prompt and use:
net use z: \\servername\deploymentshare$

and it will work as expected.
Another issue is you cannot create an image of a computer joined to a domain.
It has to be in a workgroup.


How can I drag and drop a date not event to outside the calendar in fullcalendar V2?

Question: I want to choose some hours in Fullcalendar and drag it in another div for some things.
For instance, in the calendar I want to choose the hours and days where the teachers are free to tell studentabout it.
monday  at 8:00 am 2016-05-20
tuesday at 11:00 am 2016-05-21
friday at 04:00 pm 2016-05-24.
Comment: Please clarify your question. What do you mean with _choose some hours in fullcalendar and drag it in another div for some things_?! Give us an example if possible. Thanks!
Comment: example when an administrator want programming some hours to a teacher to study students .. he will click in every hours and day or drag and drop it to a div in the right of calendar to see what  he selected .. i  gave an example in my question
Answer: in FullCalendar plugin there is the select
<code>select: function (start, end) {

  // Your logic

 }
</code>


Trouble calculating Fourier series of a function

Question: Calculate the Fourier series
$$
f(x) = \left\{\begin{aligned}
& 7\sin(x), && 0 \le x \le \pi\\
& 0, && \pi \le x \le 2\pi
\end{aligned}
\right.$$

I know that when $f(x+L) = f(x)$, for all real $x$, the Fourier series expansion is
$$f(x) = \dfrac{a_0}{2} + \sum_{n = 1}^{\infty} a_n \cos\left(n \tfrac{2\pi}{L}x \right) + b_n\sin\left(n \dfrac{2\pi}{L}x \right)$$
where
$$a_n = \dfrac{2}{L}\int\limits_{x_0}^{x_0+L}f(x)\cos\left( n \tfrac{2\pi}{L} x \right) dx \qquad x_0 \in \mathbb{R}$$
and $$b_n = \dfrac{2}{L}\int\limits_{x_0}^{x_0+L}f(x)\sin\left( n \tfrac{2\pi}{L} x \right) dx \qquad x_0 \in \mathbb{R}$$
But if we attempt to calculate $a_n$, we get $a_n = \dfrac{7}{\pi}\int^{\pi}_0 \sin(x)\cos(nx) dx$. For $n \ge 1$, I do not understand how to calculate this integral. Even If I use integration by parts, I still get an integral that is not solvable.
EDIT: To be honest, I am not even sure I got this part correct. We are supposed to have $-L \le x \le L$, but for this problem, we do not have a $-L$? Instead, we have $0 \le x \le 2\pi$. What is going on here?  (This was corrected in the equations above.)

I would greatly appreciate it if people could please take the time to explain how to solve such a problem.
Comment: Shortcut: $f(x)-\frac{7}{2}\sin x=\frac{7}{2}\lvert\sin x\rvert$ is even, hence $b_1=\frac{7}{2}$ and $b_n=0$ for $n>1$. To compute the $a_n$, note that $\sin x\cos (nx)=\frac{1}{2}\Bigl(\sin\bigl((n+1)x\bigr)-\sin\bigl((n-1)x\bigr)\Bigr)$. Note that $\int_0^{\pi}\sin(kx)\,dx=0$ for even $k$, so $a_n=0$ for odd $n$. And for odd $k$, we have $$\int_0^{\pi}\sin(kx)\,dx=\frac{-\cos(kx)}{k}\biggr\rvert_0^{\pi}=\frac{1-(-1)^k}{k}=\frac{2}{k}$$ since $\cos(k\pi)=(-1)^k=-1$ then. So for even $n$, we have $$a_n=\frac{7}{\pi}\biggl(\frac{1}{n+1}-\frac{1}{n-1}\biggr)=-\frac{14}{\pi(n^2-1)}.$$
Comment: You can simplify that. $\cos (\pi + n\pi) = \cos \bigl((n+1)\pi\bigr) = (-1)^{n+1}$. Similarly, $\cos (\pi - n\pi) = (-1)^{n-1} = (-1)^{n+1}$. So your numerator becomes $$2 - (-1)^{n+1}\bigl((1-n) + (1+n)\bigr) = 2 - (-1)^{n+1}\cdot 2 = 2\bigl(1 + (-1)^n\bigr).$$ Altogether, for odd $n$ you get $0$ (because $1 + (-1)^n = 0$ then), and for even $n$, since $1 + (-1)^n = 2$ then, you get $-\dfrac{7\cdot 4}{2\pi(n^2-1)}$. Which, when you simplify becomes exactly what MyGlasses and I got.
Comment: No, the sign of $1-n$ doesn't play a role, you have $2 -(-1)^{n+1}\bigl(1-n) + (1+n)\bigr)$.
Comment: Yes, but you have $2 - a(-1)^{n+1} - b(-1)^{n+1}$. Grouping the last two terms together, it's $a+b$ that matters. And $(1-n) + (1+n) = 2$ for all $n$.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/58250/discussion-on-question-by-the-pointer-trouble-calculating-fourier-series-of-a-fu).
Comment: $a_n = \dfrac{-7}{ \pi } \left( \dfrac{2 - (1 - n)\cos(\pi + n \pi) - (1 + n)\cos(\pi - n \pi) }{ 2(n^2 - 1) }   \right)$ for $n > 1$. Therefore, $(1 - n) < 0$, $\cos(\pi + n \pi) = (-1)^{n+1}$, $(1 + n) > 0$, $\cos(\pi - n \pi) = (-1)^{n+1}$. This gives us $\dfrac{-7}{\pi} \cdot \dfrac{ \left( 2 + (-1)^{n+1} - (-1)^{n+1}  \right) }{ 2(n^2 - 1)}$ $= \dfrac{-7}{\pi} \cdot \dfrac{1}{n^2 - 1}$?
Comment: @DanielFischer why doesn't it play a roll? It's always negative for $n > 1$, isn't it?
Comment: @DanielFischer ok. Thank you very much for the assistance. I understand much more now.
Answer: Hint: The Fourier series of a function $f$ in $[a,a+2\ell]$ with period $T=2\ell$ is
$$f(x) = \dfrac{a_0}{2} + \sum_{i = 1}^{\infty} a_n \cos\left( \dfrac{n\pi x}{\ell} \right) + b_n\sin\left( \dfrac{n\pi x}{\ell} \right)$$
where
\begin{eqnarray}
a_0 &=& \dfrac{1}{\ell}\int_a^{a+2\ell}f(x)  dx \\
a_n &=& \dfrac{1}{\ell}\int_a^{a+2\ell}f(x)\cos\left( \dfrac{n\pi x}{\ell} \right) dx \\
b_n &=& \dfrac{1}{\ell}\int_a^{a+2\ell}f(x)\sin\left( \dfrac{n\pi x}{\ell} \right) dx
\end{eqnarray}
Edit: Here $a=0$ and $\ell=\pi$ then
\begin{eqnarray}
a_0 &=& \dfrac{1}{\pi}\int_0^\pi7\sin x\,dx\\
&=&\dfrac{7}{\pi}\int_0^\pi\sin x\,dx\\
&=&\color{blue}{\dfrac{14}{\pi}}\\
a_n&=&\dfrac{1}{\pi}\int_0^\pi7\sin x\cos nx\,dx\\
&=&\dfrac{7}{2\pi}\left(-\dfrac{\cos(1-n)x}{1-n}-\dfrac{\cos(1+n)x}{1+n}\right)_0^\pi\\
&=&\color{blue}{\dfrac{7}{\pi}\dfrac{(-1)^n+1}{1-n^2}}
\end{eqnarray}
for $n\neq1$ and when $n=1$
$$a_1=\dfrac{1}{\pi}\int_0^\pi7\sin x\cos x\,dx=\dfrac{7}{2\pi}\int_0^\pi\sin2x\,dx=\color{blue}{0}$$
also
\begin{eqnarray}
b_n
&=&\dfrac{1}{\pi}\int_0^\pi7\sin x\sin nx\,dx\\
&=&\dfrac{-7}{2\pi}\int_0^\pi\cos(1+n)x-\cos(1-n)x\,dx\\
&=&\dfrac{-7}{2\pi}\left(\dfrac{\sin(1+n)x}{1+n}-\dfrac{\sin(1-n)x}{1-n}\right)_0^\pi\\
&=&\color{blue}{0}~,~(n>1)\\
b_1&=&\dfrac{1}{\pi}\int_0^\pi7\sin x\sin x\,dx\\
&=&\dfrac{7}{2\pi}\int_0^\pi1-\cos2 x\,dx\\
&=&\color{blue}{\dfrac{7}{2}}
\end{eqnarray}
thus
$$\color{blue}{\boxed{f(x)=\dfrac{7}{\pi}+\dfrac{7}{2}\sin x+\dfrac{7}{\pi}\sum_{n=2}^\infty\dfrac{(-1)^n+1}{1-n^2}\cos nx}}$$
or
$$\color{blue}{\boxed{f(x)=\dfrac{7}{\pi}+\dfrac{7}{2}\sin x-\dfrac{14}{\pi}\left(\dfrac{\cos 2x}{3}+\dfrac{\cos 4x}{15}+\dfrac{\cos 6x}{35}+\cdots\right)}}$$
Comment: Thank you very much for all of your assistance. :)


drush devel-reinstall does not rebuild tables

Question: For some reason if a module is a dependency other another module, and I run 'drush devel-reinstall' on it, it does not delete and then rebuild the tables for that module.  Does anyone know why?
Answer: Apparently because the module can't be uninstalled because another one is dependent on it.


Is query filtering by a keyword going to perform better than filtering by an integer?

Question: Lets say I have a posts index which holds all the data for all the posts made by every user on a forum, and I wanted to search through the posts made by one particular user, containing the word videogame.

The query would look something like this.

'query' : {
  'body' : {
    'should': {
      'match': {
        'posts.text': {
          'query': 'videogame',
          'fuzziness': 2,
        }
      }
    },
    'filter':{
      'term' : {
        'user_id': 3
      }
    }
  }
}

Now my mapping has it set such that user_id is mapped as an integer. Would I be able to achieve a query performance gain by having the filter term be a keyword instead? Coming from a SQL background, I'm not totally certain what field types are 'indexed' in the same way that SQL is, and I haven't been able to find very good documentation regarding it.
Comment: Elastic/Lucene has some optimisations when indexing number data-types, to enhance query time range queries. If you don't need this, use a keyword :D
Answer: There are 2 main section when it come to search data.  1. How ES index document, and second how query works.
1.  https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis.html      2.  https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html
I hope it should help you.


Samba server that allows all Linux characters in file names

Question: I don't use any Windows client and would like to have a Samba server that allows all characters in file names that Linux supports. Is this possible?
Examples: Foo"Bar or Bar:Baz
Comment: If you don't have Windows clients, why do you want Samba?
Comment: For me setting up the shares and user management with samba far easier than with NFS.
Answer: Set mangled names = no in your smb.conf.
Bear in mind that some clients may hide files with names they don't support so you may need to use the catia VFS object to remap characters if you find that being a problem.


JavaScript struggling with date format

Question: I am trying to retrieve a date but I am struggling with the month because January = 0 instead of 1. I need to retrieve items which occured after today -60 days.
 var today = new Date();
 if (today.getMonth() < 1) {
     var numberOfDaysLastMonth = getDaysInMonth(12,today.getFullYear()-1);    //number of days in december last year
     var numberOfDaysThisMonth = getDaysInMonth(today.getMonth()+1,today.getFullYear());  //number of days this month
} else {
    var numberOfDaysLastMonth = getDaysInMonth(today.getMonth(), today.getFullYear());    //number of days last month
    var numberOfDaysThisMonth = getDaysInMonth(today.getMonth()+1, today.getFullYear());  //number of days this month
};

var startDate = new Date();
var myMonth;
var myYear;

if (today.getMonth() < 1) {
   myMonth = today.getMonth() + 1;
    myYear = today.getFullYear()-1;
} else {
    myMonth = startDate.getMonth()-1;
myYear = today.getFullYear();
};

startDate  = myYear+"-"+myMonth+"-"+startDate.getDate();  // returns last month

Is there a more simple (and working) way to do this?
Comment: `myMonth = today.getMonth() + 1` this solves your "January = 0 instead of 1" problem, right? To get time from today -60 days: `new Date(new Date().getTime() - 86400000 * 60).toISOString()` hope this helps in some way. :)
Comment: Indeed. And using that code I can skip a lot of other code as well. for instance I don't need to define the myMonth and MyYear.
All I could do is count the days in the month of last month and the month befor that together. So I could use that number instead of 60.
Comment: @Barskey—not all days have 24 hrs where daylight saving is observed, far better to subtract 60 days using `today.setDate(today.getDate() - 60)`.
Comment: @Marco—if you want the same date 2 months ago, use `date.setMonth(date.getMonth() - 2)`. May need a slight adjustment where 2 months ago was February or the current date is 31 but 2 months ago only had 30 days, for a fix see [*Adding months to a Date in JavaScript*](https://stackoverflow.com/questions/12793045/adding-months-to-a-date-in-javascript/12793246#12793246).
Answer: If it's difficult to use dates as they are in Javascript, then modify them to work as they want them to work. An example:
Date.prototype.getMyMonth = function() {return this.getMonth() + 1;};

Now, you can change your code to use .getMyMonth instead of .getMonth.

JavaScript struggling with date format


Does the binary operation $m ⋆ n = m^n$ on $\mathbb N$ have a neutral element?

Question: Does the binary operation $\,m ⋆ n = m^n\,$  on  $\,\mathbb N\,$ have a neutral element?
I said yes, and it is $\,e=1\,$ because  $\,m ⋆ e = m^e = m^1 = m,\;$ but apparently that is wrong.
Answer: Recall that for a neutral element $e$, we must also have that $e\star m = m$.
Now, if $e = 1$ as you propose, then, unless $m = e = 1$
$$m\neq 1 \implies (e\star m = 1^m = 1\neq m)$$
Answer: Suppose $k$ is a neutral element.
Then $m\star k = m$ for all $m\in\mathbb{N}$.
But this means that $m^k = m$ for all $m\in\mathbb{N}$.
So $k=1$. However then $k\star m = m$ for all $m\in\mathbb{N}$ fails!