A simple SMTP server (in Python)

Question: Could you please suggest a simple SMTP server with the very basic APIs (by very basic I mean, to read, write, delete email), that could be run on a linux box?
I just need to convert the crux of the email into XML format and FTP it to another machine.
Comment: Some interesting reading about sending email with code: http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
Answer: Take a look at this SMTP sink server:
from __future__ import print_function
from datetime import datetime
import asyncore
from smtpd import SMTPServer

class EmlServer(SMTPServer):
    no = 0
    def process_message(self, peer, mailfrom, rcpttos, data):
        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),
                self.no)
        f = open(filename, 'w')
        f.write(data)
        f.close
        print('%s saved.' % filename)
        self.no += 1

def run():
    # start the smtp server on localhost:1025
    foo = EmlServer(('localhost', 1025), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    run()

It uses smtpd.SMTPServer to dump emails to files.
Comment: hmm, tweak it with: `sudo python -m smtpd -c DebuggingServer -n localhost:25`
Comment: Thanks, I'm author of SMTP sink server. I just learned from @zero that the command is more simple for test:`sudo /usr/lib/python2.4/smtpd.py -n -c DebuggingServer localhost:25`
Comment: it works well when the smtp server/sink and client/sender is on the same machine.. But i am trying a client from another computer of my network (setting the server as the IP of my smtp server) but it does not work.. any idea? I need to open the port somehow?
Comment: I get a depreciation warning about asyncore and this error: ImportError: cannot import name 'SMTPServer' from partially initialized module 'smtpd' (most likely due to a circular import) (/data/data/com.termux/files/usr/lib/python3.10/smtpd.py)
Comment: Apparently, the problem was that I named my file email.py, and that conflicted (but the depreciation warning still means the code is going to be broken soon).
Answer: There are really 2 things required to send an email:

An SMTP Server - This can either be the Python SMTP Server or you can use GMail or your ISP's server. Chances are you don't need to run your own.
An SMTP Library - Something that will send an email request to the SMTP server. Python ships with a library called smtplib that can do that for you. There is tons of information on how to use it here: http://docs.python.org/library/smtplib.html

For reading, there are two options depending on what server you are reading the email from.

For a POP Email Server - You can use the poplib python library: http://docs.python.org/library/poplib.html
For an IMAP Email Server - You can use the imaplib python library: http://docs.python.org/library/imaplib.html
Answer: To get Hasen's script working in Python 3 I had to tweak it slightly:
from datetime import datetime
import asyncore
from smtpd import SMTPServer

class EmlServer(SMTPServer):
    no = 0
    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'),
            self.no)
        print(filename)
        f = open(filename, 'wb')
        f.write(data)
        f.close
        print('%s saved.' % filename)
        self.no += 1

def run():
    EmlServer(('localhost', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    run()

Answer: A more modern approach is to use the aiosmtpd library (documentation available here).
You can find a good example here: https://aiosmtpd.readthedocs.io/en/latest/controller.html.
Answer: Two python smtp servers I've used with success are:

Twisted's Mail - A very flexible mail library for SMTP, IMAP, ...
python-slimta - A complete MTA (smtp relay/forwarding server)

Twisted's example is shown below
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

# You can run this module directly with:
#    twistd -ny emailserver.tac

"""
A toy email server.
"""
from __future__ import print_function

from zope.interface import implementer

from twisted.internet import defer
from twisted.mail import smtp
from twisted.mail.imap4 import LOGINCredentials, PLAINCredentials

from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.cred.portal import IRealm
from twisted.cred.portal import Portal

@implementer(smtp.IMessageDelivery)
class ConsoleMessageDelivery:
    def receivedHeader(self, helo, origin, recipients):
        return "Received: ConsoleMessageDelivery"

    def validateFrom(self, helo, origin):
        # All addresses are accepted
        return origin

    def validateTo(self, user):
        # Only messages directed to the "console" user are accepted.
        if user.dest.local == "console":
            return lambda: ConsoleMessage()
        raise smtp.SMTPBadRcpt(user)

@implementer(smtp.IMessage)
class ConsoleMessage:
    def __init__(self):
        self.lines = []

    def lineReceived(self, line):
        self.lines.append(line)

    def eomReceived(self):
        print("New message received:")
        print("\n".join(self.lines))
        self.lines = None
        return defer.succeed(None)

    def connectionLost(self):
        # There was an error, throw away the stored lines
        self.lines = None

class ConsoleSMTPFactory(smtp.SMTPFactory):
    protocol = smtp.ESMTP

    def __init__(self, *a, **kw):
        smtp.SMTPFactory.__init__(self, *a, **kw)
        self.delivery = ConsoleMessageDelivery()

    def buildProtocol(self, addr):
        p = smtp.SMTPFactory.buildProtocol(self, addr)
        p.delivery = self.delivery
        p.challengers = {"LOGIN": LOGINCredentials, "PLAIN": PLAINCredentials}
        return p

@implementer(IRealm)
class SimpleRealm:
    def requestAvatar(self, avatarId, mind, *interfaces):
        if smtp.IMessageDelivery in interfaces:
            return smtp.IMessageDelivery, ConsoleMessageDelivery(), lambda: None
        raise NotImplementedError()

def main():
    from twisted.application import internet
    from twisted.application import service

    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)

    a = service.Application("Console SMTP Server")
    internet.TCPServer(2500, ConsoleSMTPFactory(portal)).setServiceParent(a)

    return a

application = main()

Answer: These are nice examples for a start.
smtpd – Sample SMTP Servers
http://pymotw.com/2/smtpd/index.html
smtplib – Simple Mail Transfer Protocol client
http://pymotw.com/2/smtplib/index.html
Answer: I also wanted to start a smtp server in Python and send emails with Python. I wanted to run all this in a Flask web application in a single process, which means the smtp server must be non-blocking. Here's the solution I eventually came to [gist]:
app.py
from flask import Flask, render_template
from smtp_client import send_email
from smtp_server import SMTPServer

app = Flask(__name__)

@app.route('/send_email')
def email():
  server = SMTPServer()
  server.start()
  try:
    send_email()
  finally:
    server.stop()
  return 'OK'

@app.route('/')
def index():
  return 'Woohoo'

if __name__ == '__main__':
  app.run(debug=True, host='0.0.0.0')

smtp_server.py
# smtp_server.py
import smtpd
import asyncore
import threading

class CustomSMTPServer(smtpd.SMTPServer):
  def process_message(self, peer, mailfrom, rcpttos, data):
    print('Receiving message from:', peer)
    print('Message addressed from:', mailfrom)
    print('Message addressed to:', rcpttos)
    print('Message length:', len(data))
    return

class SMTPServer():
  def __init__(self):
    self.port = 1025

  def start(self):
    '''Start listening on self.port'''
    # create an instance of the SMTP server, derived from  asyncore.dispatcher
    self.smtp = CustomSMTPServer(('0.0.0.0', self.port), None)
    # start the asyncore loop, listening for SMTP connection, within a thread
    # timeout parameter is important, otherwise code will block 30 seconds
    # after the smtp channel has been closed
    kwargs = {'timeout':1, 'use_poll': True}
    self.thread = threading.Thread(target=asyncore.loop, kwargs=kwargs)
    self.thread.start()

  def stop(self):
    '''Stop listening to self.port'''
    # close the SMTPserver to ensure no channels connect to asyncore
    self.smtp.close()
    # now it is safe to wait for asyncore.loop() to exit
    self.thread.join()

  # check for emails in a non-blocking way
  def get(self):
    '''Return all emails received so far'''
    return self.smtp.emails

if __name__ == '__main__':
  server = CustomSMTPServer(('0.0.0.0', 1025), None)
  asyncore.loop()

smtp_client.py
import smtplib
import email.utils
from email.mime.text import MIMEText

def send_email():
  email@example.com'
  email@example.com'

  msg = MIMEText('This is the body of the message.')
  msg['To'] = email.utils.formataddr(('Recipient', recipient))
  msg['From'] = email.utils.formataddr(('Author', 'email@example.com'))
  msg['Subject'] = 'Simple test message'

  client = smtplib.SMTP('127.0.0.1', 1025)
  client.set_debuglevel(True) # show communication with the server
  try:
    client.sendmail('firstname.lastname@example.com', [recipient], msg.as_string())
  finally:
    client.quit()

Then start the server with python app.py and in another request simulate a request to /send_email with curl localhost:5000/send_email. Note that to actually send the email (or sms) you'll need to jump through other hoops detailed here: https://blog.codinghorror.com/so-youd-like-to-send-some-email-through-code/.
Comment: Is it possible to receive email from an email account, for example gmail ? If yes how?
Comment: @blob check out the codinghorror link above--there are a few steps involved, but this is possible...
Answer: There is Python SMTP server.

This module offers several classes to implement SMTP servers. One is a
  generic do-nothing implementation, which can be overridden, while the
  other two offer specific mail-sending strategies.
Comment: Yes,I know.But,I'm unable to figure out how to read email with that lib!
A way round this problem, perhaps?
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
Answer: If you want to quickly test Django's send_mail with hasen's answer above:
# Skip lines 3 and 4 if not using virtualenv.
# At command prompt

mkdir django1
cd django1
virtualenv venv
source venv/bin/activate
pip install django==1.11
django-admin startproject django1 .

# run the Django shell

python manage.py shell

# paste into shell following:

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'firstname.lastname@example.com',
    ['firstname.lastname@example.com'],
    fail_silently=False,
)
# This should write an email like the following:

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Subject here
From: firstname.lastname@example.com
To: email@example.com
Date: Wed, 02 May 2018 02:12:09 -0000
Message-ID: <20180502021209.32641.51865@i1022>

Here is the message.

Not necessary to have valid values in send_mail function. Above values will work just fine with hasen's example.

A simple SMTP server (in Python)


RNN vs Kalman filter : learning the underlying dynamics?

Question: Being recently interested in Kalman filters and Recurrent neural networks, it appears to me that the two are closely related, yet I can't find relevant enough litterature :
In a Kalman filter, the set of equations is :
$$x_{k} = Ax_{k-1} + Bu_{k} + w_{k-1}$$
$$ z_k  = Hx_k + v_k$$
with $x$ the state and $z$ the measurement.
In an Elman RNN (from here), the relation between the layers is:
$$h_{k} = \sigma_h (Uh_{k-1} + Wx_{k} + b)$$
$$ y_k  = \sigma_y (Vh_k + c)$$
with $x$ the input layer, $h$ the hidden layer and $y$ the output layer and $\sigma$ are the activation functions for the layers.
It's clear that the two set of equations are the same, modulo the activations. The analogy here seems to be the following. The output layer corresponds to the measured state, the hidden layer is the true state, driven by a process $x$ which is the input layer.

First question : is the analogy viable ? And how can we interpret the activations ?
Second question : in a Kalman filter the $A$ matrix is that of the underlying dynamics of the state $x$. Since training a RNN allows to learn the $W$ matrices, are RNN able to learn the dynamics of the underlying state ? Ie once my RNN is trained, can I look at the coefficients of my network to guess the dynamics behind my data ?

(I'm going to try to do the experiment on artificially generated data, to see if this works, and will update as soon as it's done)
EDIT : I wish I had access to this paper
Comment: Did you get to a conclusion?
Comment: I've checked the paper, but unfortunately the authors have simply compared the performance of a RNN and a Kalman filter on a few basic systems.
Answer: Yes indeed they are related because both are used to predict $y_{n}$ and $s_{n}$ at time step n based on some current observation $x_{n}$ and state $s_{n-1}$ i.e. they both represent a function $F$ such that $$F(x_{n}, s_{n-1}) = (y_{n}, s_{n})$$
The advantage of the RNN over Kalman filter is that the RNN architecture can be arbitrarily complex (number of layers and neurons) and its parameters are learnt, whereas the algorithm (including its parameters) of Kalman filter is fixed.
Recurrent Neural Networks are more general than Kalman filter. One could actually train a RNN to simulate a Kalman filter.
Neural nets are kind of black box models and weights and activations are very often not interpretable (above all in the deeper layers).
In the end neural nets are only optimized to make the best predictions and not to have "interpretable" parameters.
Nowadays if you work on time series, have enough data and want the best accuracy, RNN is the preferred approach.
Comment: Both models have parameters that are learnt, and state space models can be arbitrarily complex as well. The rest of the answer is misleading as well.
Answer: As you say, the difference is the activation functions.
The usual purpose of a Kalman filter is used to model an intrinsically linear process, where the observations are subject to additive noise. You can get away with using a Kalman filter if there are slow deviation from linearity, but not if the process is strongly non-linear.
By contrast, neural nets get extra power by using a non-linear activation function. (Without it, stacking extra layers would never give a non-linear model.) So they are suitable for modelling non-linear processes, at least within the convex cover of the training set.
The asymptotic behaviour of a neural net is decided by the activation function, not by the training data. That is why the Universal Approximation Theorem has the condition "... on compact support". This isn't very surpising - no finite training set contains evidence about asymptotic behaviour.
Comment: What about filtering for nonlinear state space models?
Answer: They replace the kalman gain calculations by a RNN on this paper if you're still interested.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/327901)
Answer: I'll substitute linear Gaussian state space model for Kalman filter here.
Similarities

they both model time series
they both have a hidden/latent "state" or "layer" process for which there is no data
the observed dependent sequence depends/conditions on the above process
the hidden/latent state/layer can depend on independent predictors/inputs/covariates/exogenous variables, etc.
they both have parameters that (usually) must be learned/estimated

Differences

RNN have nonlinear activation functions while linear Gaussian state space models have linear state equations and observation equations
Linear Gaussian state space models have additive noise terms while RNN's do not

Misconceptions

RNNs are a class of models and Kalman filters are an algorithm. This makes comparison between the two misleading.
Kalman filters assume the parameters of the time series model are known, but that does not mean the models they are used on--linear Gaussian state space models--cannot have their parameters estimated/learned--they usually are, and the Kalman filter's likelihood evaluations can be used in an optimization or sampling-based strategy.

I have little experience with RNNs, but I tend to think that the last item in the "Differences" category is the most important. For example, RNNs such as long short term memory (LSTM) models and gated recurrent units (GRUs) have "forget gates" that describe how the hidden layer "forgets" its past values deterministically. On the other hand, a state space model's "forgetting" is random.
In my very humble opinion, I think this probably explains why RNNs are used a lot for non-noisy data such as text data, while lgSSMs are used on data that is "more random" such as financial returns. To be completely truthful, though, again, I don't have much experience with RNNs, so I don't claim this with any certainty.
The linear/nonlinear distinction is not so important. State space models can have nonlinear state and observation/emission equations and indeed frequently do. When this happens, though, you can't use the Kalman filter anymore, but there are many other approximate filtering techniques.
Regarding the other answer supposing that RNNs are "arbitrarily complex"--that reminds me of a Tweet I read a while back: https://twitter.com/sirbayes/status/1537177495866327040?s=20&t=eJ8U-Az5Tn_P0vH1afKLAw I have a hard time engaging in this debate, myself, though.


$A \times \left(B \times C\right) \cong \left(A \times B\right) \times C$

Question: I am proving the associativity of set products:

Suppose $A$, $B$ and $C$ are linearly ordered sets. Then
\begin{equation*}
A \times \left(B \times C\right) \cong \left(A \times B\right) \times C,
\end{equation*}
where the order of products is anti-lexicographic.

Proof. Define a function $f: A \times \left(B \times C\right) \to \left(A \times B\right) \times C$ such that
\begin{equation*}
\forall a \in A, \forall b \in B, \forall c \in C, f\left(a,\left(b,c\right)\right) = \left(\left(a,b\right),c\right).
\end{equation*}
It is obvious that $f$ is bijective. Next we shall prove the following statement:
\begin{equation*}
\left(a_{1},\left(b_{1},c_{1}\right)\right) <_{A \times \left(B \times C\right)} \left(a_{2},\left(b_{2},c_{2}\right)\right) \Longleftrightarrow \left(\left(a_{1},b_{1}\right),c_{1}\right) <_{\left(A \times B\right)\times C} \left(\left(a_{2},b_{2}\right),c_{2}\right).
\end{equation*}
Naturally, assume $\left(a_{1},\left(b_{1},c_{1}\right)\right) <_{A \times \left(B \times C\right)} \left(a_{2},\left(b_{2},c_{2}\right)\right)$. This condition can be decomposed into the following categories:

$c_{1} <_{C} c_{2}$
$c_{1} = c_{2}$ and $b_{1} <_{B} b_{2}$
$c_{1} = c_{2}$ and $b_{1} = b_{2}$ and $a_{1} <_{A} a_{2}$

If $c_{1} <_{C} c_{2}$, then it is clear that $\left(\left(a_{1},b_{1}\right),c_{1}\right) <_{\left(A \times B\right)\times C} \left(\left(a_{2},b_{2}\right),c_{2}\right)$. Next, if $c_{1} = c_{2}$ and $b_{1} <_{B} b_{2}$, then it is also clear that $\left(\left(a_{1},b_{1}\right),c_{1}\right) <_{\left(A \times B\right)\times C} \left(\left(a_{2},b_{2}\right),c_{2}\right)$. Finally, if $c_{1} = c_{2}$ and $b_{1} = b_{2}$ and $a_{1} <_{A} a_{2}$, we also have $\left(\left(a_{1},b_{1}\right),c_{1}\right) <_{\left(A \times B\right)\times C} \left(\left(a_{2},b_{2}\right),c_{2}\right)$.
Next, assume that $f\left(a_{1},\left(b_{1},c_{1}\right)\right) <_{\left(A\times B\right)\times C} f\left(a_{2},\left(b_{2},c_{2}\right)\right)$, that is,
\begin{equation*}
\left(\left(a_{1},b_{1}\right),c_{1}\right) <_{\left(A \times B\right)\times C} \left(\left(a_{2},b_{2}\right),c_{2}\right).
\end{equation*}
Then, we have the following categories:

$c_{1} <_{C} c_{2}$
$c_{1} = c_{2}$ and $b_{1} <_{B} b_{2}$
$c_{1} = c_{2}$ and $b_{1} = b_{2}$ and $a_{1} <_{A} a_{2}$

The argument is similar to our previous one. Thus, we may conclude that
\begin{equation*}
\left(a_{1},\left(b_{1},c_{1}\right)\right) <_{A \times \left(B \times C\right)} \left(a_{2},\left(b_{2},c_{2}\right)\right) \Longleftrightarrow \left(\left(a_{1},b_{1}\right),c_{1}\right) <_{\left(A \times B\right)\times C} \left(\left(a_{2},b_{2}\right),c_{2}\right).
\end{equation*}
As a result, we have
\begin{equation*}
A \times \left(B \times C\right) \cong \left(A \times B\right) \times C.
\end{equation*}
I am learning elementary set theory on my own. Is it a solid proof?
Comment: What order are you using on the product?
Comment: @egreg Anti-lexicographic. I have added the information in the post.
Answer: You're really done once you show that
$$\langle\langle a_1,b_1\rangle,c_1\rangle<_{(A\times B)\times C}\langle\langle a_2,b_2\rangle,c_2\rangle\tag{1}$$
and
$$\langle a_1,\langle b_1,c_1\rangle\rangle<_{A\times(B\times C)}\langle a_2,\langle b_2,c_2\rangle\rangle\tag{2}$$
are both equivalent to the assertion that either

$c_1<_C c_2$, or
$c_1=c_2$ and $b_1<_Bb_2$, or
$c_1=c_2$, $b_1=b_2$, and $a_1<_Aa_2$.

You could, however, stand to say a bit more to justify these equivalences. For $(1)$ it's pretty clear, but for $(2)$ I'd say more than you did:

$(2)$ means that either $\langle b_1,c_1\rangle<_{B\times C}\langle b_2,c_2\rangle$, or $\langle b_1,c_1\rangle=\langle b_2,c_2\rangle$ and $a_1<_Aa_2$. This in turn means that either $c_1<_Cc_2$, or $c_1=c_2$ and $b_1<_Bb_2$, or $c_1=c_2$, $b_1=b_2$, and $a_1<_Aa_2$.


swift SpriteNode and SceneKit multiple touch gestures

Question: I am making a word game. For this I am using SceneKit and adding a SpriteNodes to represent letter tiles.
The idea is that when a user clicks on a letter tile, some extra tiles appear around it with different letter options. My issue is regarding the touch gestures for various interactions.
When a user taps on a letter tile, additional tiles are shown.  I have achieved this using the following method in my tile SpriteNode class:
override func touchesBegan(_ touches:Set<UITouch> , with event: UIEvent?) {
    guard let touch = touches.first else {
        return
    }
    delegate?.updateLetter(row: row, column: column, x:xcoord, y:ycoord, useCase: 1)
}

This triggers the delegate correctly which shows another sprite node.
What I would like to achieve is for a long press to remove the sprite node from parent.  I have found the .removeFromParent() method, however I cannot get this to detect a long press gesture.
My understanding is that this type of gesture must be added using UIGestureRecognizer. I can add the following method to my Scene class:
override func didMove(to view: SKView) {
    let longPress = UILongPressGestureRecognizer(target: self,
        action: #selector(GameScene.longPress(sender:)))
    view.addGestureRecognizer(longPress)
}
@objc func longPress(sender: UILongPressGestureRecognizer) {
    print("Long Press")

This will detect a long press anywhere on the scene. However I need to be able to handle the pressed nodes properties before removing it.  I have tried adding the below to the longPress function:
let location = sender.location(in: self)
let touchedNodes = nodes(at: location)
let firstTouchedNode = atPoint(location).name
touchedNodes[0].removeFromParent()

but I get the following error:  Cannot convert value of type 'GameScene' to expected argument type 'UIView?'
This seems a little bit of a messy way of doing things, as I have touch methods in different places.
So my question is, how can I keep the current touchesBegan method that is in the tile class, and add a long press gesture to be able to reference and delete the spriteNode?
Answer: Long press gestures are continuous gestures that may be called multiple times as you are seeing.  Have you tried Recognizer.State.began, .changed, .ended?  I solved a similar problem doing things this way.
EDIT - I think one way to get there is to get your object on handleTap and hang on to the object.  Then when LongPress happens, you already have your node.  If something changes before longPress, obviously you need to reset.  Sorry, this is some extra code on here, but look at hitTest.
@objc func handleTap(recognizer: UITapGestureRecognizer)
    {
        let location: CGPoint = recognizer.location(in: gameScene)

        if(data.isAirStrikeModeOn == true)
        {
            let projectedPoint = gameScene.projectPoint(SCNVector3(0, 0, 0))
            let scenePoint = gameScene.unprojectPoint(SCNVector3(location.x, location.y, CGFloat(projectedPoint.z)))
            gameControl.airStrike(position: scenePoint)
        }
        else
        {
            let hitResults = gameScene.hitTest(location, options: hitTestOptions)
            for vHit in hitResults
            {
                if(vHit.node.name?.prefix(5) == "Panel")
                {
                    // May have selected an invalid panel or auto upgrade was on
                    if(gameControl.selectPanel(vPanel: vHit.node.name!) == false) { return }
                    return
                }
            }
        }
    }

Comment: I try and put a print function when testing to confirm whether any methods are called. When I do the long press function my scene using the code given, I can see this is called. My issue is I do not know how to access the touched node or refer to its properties from within this function
Answer: So I am not completely satisfied with this answer, however it is a work around for what I need.
What I have done is added two variables 'touchesStart' and 'touchesEnd' to my tiles class.
Then in touchesBegan() I add a call to update touchesStart with CACurrentMediaTime() and update touchesEnd via the touchesEnded() function.
Then in the touchesEnded() I subtract touchesStart from touchesEnd. If the difference is more than 1.0 I call the function for long press. If less than 1.0 I call the function for tap.


O que significa o "MZ" listado no início de código executável?

Question: Nos bons tempos do MS-DOS eu executava o comando type <nome-do-arquivo> em arquivos .EXE e aparecia um monte de caracteres ASCII (indicativo de código binário) iniciados pela sigla MZ.
Sempre quis saber o que é esse MZ, mas nunca tive a curiosidade de ir atrás. Quem sabe o SOpt mata essa minha curiosidade.
Para deixar a resposta completa, gostaria que fossem explicados o que fazem as instruções iniciais do arquivo .EXE. O MZ tem algum uso? Os caracteres seguintes são responsáveis por que tipo de inicialização (leia-se: existe um cabeçalho)? Ou não ocorre nenhuma inicialização, apenas o programa é movido para a memória e posto para executar a partir da sua primeira instrução?
Comment: Meio extenso responder isso tudo, você teria que estudar o formato PE da Microsoft. Sobre o MZ, são as iniciais do Mark Zbikowski, um desenvolvedor do MS-DOS, e ele só está nos EXE como indicador de compatibilidade de subsistemas 16 bits (se tentar rodar um executável moderno no MS-DOS vai receber a mensagem de que a aplicação não pode ser executada em DOS, e esse aviso é a unica "funcionalidade" da "parte DOS" do executável) - O MZ diferencia o .exe do .com em sistemas 16 bits.
Answer: É uma assinatura de executável. É uma forma simples e ingênua de verificar se o executável está em determinado formato. Se tudo estiver certo funciona, mas pode ser algo forjado ou coincidente, é improvável, mas pode acontecer, e claro que tem outras validações, mas esta é a primeira que é feita, se não encontrar isso já sabe que esse formato não é.
Segundo a Wikipedia é abreviação do Mark Zbikowski, o cara que criou participou da criação.
Os bytes que veem a seguir são mais significativos e começam informar a composição deste executável específico. Neste tipo de formato há um tratamento bem complexo para inicializar e preparar a memória, apenas um formato bem antigo que consegue ir direto para a memória sem tratamento específico.
O caso de ser um MZ, ou seja, um executável DOS das antigas tem pouca informação específica seguinte, outros formatos (PE) são bem mais ricos.
Os executáveis mais novos ainda contém o "MZ" por questões de compatibilidade então não dá um erro qualquer se chamar um executável moderno em um sistema antigo, dará um erro mais específico que o próprio executável fornece. Isto é interessante porque sistemas mais antigos não entendem formatos novos e dariam um erro genérico.

Uma listagem de como ele pode ser composto.
O OSDev tem uma forma bem simplificada.
E tem um Wikibook com um resumo um pouco maior de como é o formato do PE moderno que acho mais interessante.
Documentação da Microsoft.
E um código se quiser escrever um executável na mão.

De qualquer forma parece bastante amplo tentar descrever tudo aqui.
Veja o diagrama da Wikipedia:

Coloquei no GitHub para referência futura.


R - How does t-test for significance of terms in GLM work?

Question: Let's have some generalized linear model and its summary:
Call:
glm(formula = time ~ poly(I(1/nprocs), 2, raw = T) + poly(nDOF,
    3, raw = T) + poly(ndoms, 3, raw = T) + I(1/nprocs):poly(ndoms,
    2, raw = T), family = gaussian(link = "log"), data = dataFact)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-0.34009  -0.07888  -0.02411   0.05733   0.23354

Coefficients:
                                       Estimate Std. Error t value Pr(>|t|)
(Intercept)                          -3.570e+00  1.339e-01 -26.662  < 2e-16 ***
poly(I(1/nprocs), 2, raw = T)1        7.868e-01  6.659e-02  11.815  < 2e-16 ***
poly(I(1/nprocs), 2, raw = T)2        1.199e-01  2.355e-02   5.093 7.75e-07 ***
poly(nDOF, 3, raw = T)1               6.790e-04  1.340e-05  50.681  < 2e-16 ***
poly(nDOF, 3, raw = T)2              -5.341e-08  1.609e-09 -33.197  < 2e-16 ***
poly(nDOF, 3, raw = T)3               1.570e-12  5.819e-14  26.979  < 2e-16 ***
poly(ndoms, 3, raw = T)1              5.545e-03  7.238e-04   7.661 6.40e-13 ***
poly(ndoms, 3, raw = T)2             -4.723e-06  1.213e-06  -3.893 0.000132 ***
poly(ndoms, 3, raw = T)3              1.648e-09  5.936e-10   2.776 0.005985 **
I(1/nprocs):poly(ndoms, 2, raw = T)1 -1.402e-03  1.887e-04  -7.429 2.60e-12 ***
I(1/nprocs):poly(ndoms, 2, raw = T)2  6.675e-07  1.198e-07   5.570 7.65e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for gaussian family taken to be 0.01261502)

    Null deviance: 1916.0464  on 223  degrees of freedom
Residual deviance:    2.6869  on 213  degrees of freedom
AIC: -331.13

Number of Fisher Scoring iterations: 6

I'm interested in the part Coefficients, where the results of t-tests for significance are listed. And my question is - how does the t-test work here?
Is it a One-sample t-test? In that case I think, that the predicted values by a model are the observations $x_1, \ldots, x_n$ and their mean is $\mu_0$. And then I think, that for every term is testing done by removing the term, computing the mean of new predicted values and compared to the "reference mean" $\mu_0$.
Does it work it this way? I'm a beginner with statistics, so, I'd be glad if you could provide more detailed answers.
Comment: This question seems clear enough to me, & it has an upvoted & accepted answer. I'm voting to leave open.
Comment: These are tests on the statistical significance of the regression coefficients.
Comment: @MichaelChernick They are, but I'm interested especially in this one which is native for [summary](https://stat.ethz.ch/R-manual/R-devel/library/stats/html/summary.glm.html) function in R.
Answer: The t-statistic in the R summary for glms is calculated by dividing the coefficient by the standard error:
t=coefficient_x / standard error_x

If I'm not mistaken this is the Wald test. The resulting p-value is then obtained from a t-distribution with degrees of freedom dependent on the amount of degrees of freedom used in the entire model and by the variable, and is given for a two-sided test.
Of note: you can also see this in R by looking at the code for summary.glm (run summary.glm without the brackets ()). Here you can see that the summary.glm function uses 2*pt(-abs(tstatistic),df) where df is the residual degrees of freedom stated elsewhere in the summary output.
Comment: Thank you very much for your answer! I'm just a little confused about the resulting p-value. When I to compute t-value, let's say $1.199e-01 / 2.355e-02 \approx 5.091295$, it is ok. But then, when I try to get p-value like this `pt(5.091295, 1)` I get the value 0.9382654 instead of  7.75e-07 which is in the table. Do you have any idea why?
Comment: Try 1- the value you find. R gives you the left hand side of the distribution
Comment: When I try that, I get $1 - 0.9382654 = 0.0617346$ which is still vastly different from  $7.75e-07$.
Comment: You are absolutely right, the degrees of freedom I stated were wrong. As nprocs is entered in your model as factor and uses 2df (or so it seems), the df used for the t-test is 213 (amount of df for your model) +2 = 215. Then the p-value is two-sided, so the value you get from 1-pt(t,df) should be doubled. (I've edited this into the answer)
Comment: Ok... Could you, please, add this short example into your answer too, together with the information about DoF for single terms? (I mean, why exactly 2 here?)


$page parameter doesn't appear to contain all the information used to render a page

Question: I'm using hook_menu to build a series (100+) of pages where the code uses a basic page "master template" and replaces strings in the "master template" node with elements of the URL that reaches the Drupal menu page callback routine.
Once the appropriate strings are replaced, the page callback routine uses node_view() to create the render array, and returns it for further processing and transmission to the client.
The "master template" page is at URL mysite/whatever-string. The problem is that Drupal sticks whatever-string into the page the client receives, and it looks like this:

        ....

I'm using dd($var, 'description') to look at data structures and elements as a debugging tool.  From the callback routine, dumping the unprocessed and processed "master template" node and the render array returned by node_view() and searching for whatever-string returns no results. The string isn't there.  Thinking that perhaps the render array produced by node_view() didn't have all of the elements that the page contained, I implemented hook_page_alter($page) to see if the render array that it gets as a parameter might contain the string.  It doesn't.  Is there some other hook that's available to a module which will have everything that goes into rendering the page ?
As a last resort, I'm sure I can work around this by writing theme/template code to wander through the html (or DOM) and make the changes needed.  I've done this a lot before, but I think it's cleaner (and marginally more efficient) to do it all when the page is generated, rather than looking at all the nodes that get rendered to see if it's a generated one, and make the changes to the HTML directly.
Answer: I would suggest using hook_preprocess_HOOK. In this instance I think hook_preprocess_node is what you want but _page may work as well.
Answer: Unfortunately when we try to subvert the Drupal workflow in favor of 'marginally more efficient' cpu/resource utilization, we will constantly run into this kind of problem.  ;)
Drupal wants you to override the 'node' template in this case.  It sounds like you may already be aware of this.
You may be able to limit the effect of this template override if all your 'interesting' nodes share a content type/s.  In which case, you may add a template suggestion to your theme's 'template.php';
function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type) && $vars['node']->type === 'my_interesting_type') {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

More info on this template suggestion workflow; https://www.drupal.org/node/1089656
Comment: In this case, I couldn't split the content out to a different site (modifying existing, not implementing for the first time).


How to use .so library in android

Question: I'm trying to use a python interpreter in my Android app to run SymPy. I already compiled Python for arm using this guide. http://mdqinc.com/blog/2011/09/cross-compiling-python-for-android/
This got me a libpython2.7.so file which I put into jniLibs/armeabi/.
In my app I load it as follows:
public class PythonTest {
    static {
        System.loadLibrary("python2.7");
    }

    public static native void Py_Initialize();
    public static native void Py_Finalize();
    public static native int PyRun_SimpleString(String s);
}

I am trying to use the methods from the headers located in the include directory which can also be found here: https://docs.python.org/2/c-api/
When I run the app on my device I get the following error:
No implementation found for void com.example.dorian.testapplication.PythonTest.Py_Initialize() (tried Java_com_example_dorian_testapplication_PythonTest_Py_1Initialize and Java_com_example_dorian_testapplication_PythonTest_Py_1Initialize__)

So to me this seems like the library loaded but it seems to look for the JNIEXPORT functions. But shouldn't I be able to use this library without writing specific C++ files? And if not, how would I accomplish this. Might there be a tool to generate wrapper files or something similar?
Comment: http://stackoverflow.com/questions/5659068/jni-tutorial-for-android should help.
Answer: You need a JNI wrapper lib that will serve as a bridge between your Java code and libpython2.7.so. It may be enough for straters to have the three functions wrapped according to the JNI convention, e.g.
JNIEXPORT jint JNICALL com_example_dorian_testapplication_PythonTest_PyRun_1SimpleString
  (JNIEnv *env, jclass jc, jstring js)
{
    char* cs = env->GetStringUTFChars(js, 0);
    std::string s = new std::string(cs);
    env->ReleaseStringUTFChars(env, js, cs);
    return PyRun_SimpleString(s.c_str());
}

If something is not clear, please read the tutorial at http://joaoventura.net/blog/2014/python-android-2.
Note that you can use any package name for the PythonTest class, not necessarily related to your Android app package name, e.g.
package com.python27;
class Python {
static {
    System.loadLibrary("python2.7");
}

public static native void Initialize();
public static native void Finalize();
public static native int Run(String s);
}

will expect the JNI wrappers
JNIEXPORT void JNICALL com_python27_Python_Initialize(JNIEnv *env, jclass jc);
JNIEXPORT void JNICALL com_python27_Python_Finalize(JNIEnv *env, jclass jc);
JNIEXPORT jint JNICALL com_python27_Python_Run(JNIEnv *env, jclass jc, jstring js);

How to use .so library in android


Get source string from NumberFormatException

Question: is it possible to obtain somehow source string from NumberFormatException in catch clause eg.:
try {
    Integer.parseInt("test");
} catch (NumberFormatException e) {
    e.sourceString(); \\ to return "test"
}

Thanks.
Stefan
Answer: Save it in a variable before the try block.
Comment: Unless you want to extend `NumberFormatException` (which will contain the parse string), and build a version of parseInt that throws that extended class; all of which is heavyweight, @chrylis solution is probably the best one.
Comment: That is one option, but it does not solves the problem, where I want to generate proper error message with source string inside.
Comment: So it is not possible to obtain it in some ellegant easy way from exception self.
Answer: TL;DR
There is no good way to do what you ask; better to save the variable before the try block.

Long answer:
Here's the source code that creates the exception:
static NumberFormatException forInputString(String s) {
    return new NumberFormatException("For input string: \"" + s + "\"");
}

As you can see, the parse string is not stored in the exception, as it creates the error message as part of the constructor. However, because we always know the format, we could write something like this:
try {
  int foo = Integer.parseInt("foo");
} catch (NumberFormatException e) {
  String message = e.getMessage();
  System.out.println(message.substring(19, message.length() - 1));
}

Therefore, as @chrylis said, storing the value in a variable before the try block and using it if there's an exception is the best solution.
Two reasons not to do it this way (which is really the only way to do what you've asked in the OP):

If they ever change the message, your code will break (this is still true of @EvgeniyDorofeev's answer)
This way is much slower as it has to parse the String
Answer: try this
String ss = e.getMessage();
ss = ss.substring(ss.indexOf('"') + 1, ss.length() - 1);


Returning the file name extension in java

Question: I have a parameter which contains the following value
 String filesTypesallowed =".xsl,.xslx ";

Now i have pass this parameter in another method named filterfile as shown below now as you can see that in the method i am getting the fileName as one of the parameter in which i must be getting any file name lets say it mite be abc.csv file , so what i have to do is that check whether the file that i am getting inside the parameter fileName ends with extension .xlsx or .xls then in that case i have to return the file name but other than that extension lets say i have got a file with an extension like ert.csv then in that case i have to return simply null
please advise how to achieve this what i have tried is
private String filterfile(String fileName , String filesTypesallowed) {
String s ;
s =fileName.substring(fileName.lastIndexOf("."));

}

Comment: Are you wanting to return a string, or a boolean?  If a string, what is that string supposed to contain?
Comment: @NathanMerrillbwell i was trying to return a string that contains the entire file name which was paassed to me in the fileName parameter only if it is .xsl or .xslx only other wise null
Comment: If you use Java 7 or higher you could use the method String.endsWith(String). Also if you just want to select which file is acceptable maybe a [FileFilter](http://docs.oracle.com/javase/7/docs/api/javax/swing/filechooser/FileFilter.html) would be something for you.
Answer: You could split the filesTypesallowed and then check if the extension is any of them:
private String filterfile(String fileName , String filesTypesallowed) {
    String extension = fileName.substring(fileName.lastIndexOf("."));
    String[] allowedExtensions = filesTypesallowed.split(",");
    if (Arrays.asList(allowedExtensions).contains(extension)) {
        return fileName;
    }
    return null;
}

Comment: `filesTypesAllowed` ends with a space in the example.
Comment: Isn't creating a list of the extensions vs iterating over the extensions a bit inefficient?
Answer: You could split the array, then build a Stream off it and simply use anyMatch.
Example :
private String filterFile(final String fileName, final String fileTypesAllowed) {
    return Stream.of(fileTypesAllowed.trim().split(","))
                 .anyMatch(ext -> ext.equals(fileName.substring(fileName.lastIndexOf("."))))
                     ? fileName
                     : null;
}

Note that I made a call to String.trim as the example you gave us contains one whitespace at the end, I'm not sure if it was a typo or not... Remove it if you want.
Answer: There are two key parts to this problem, getting the file extensions, and checking if the string ends with any of those extensions.
To get the file extensions, you need to use String.split().  If we pass it a comma, it'll return an array of the parts separated by a comma:
String[] extensions = fileTypesAllowed.split(",");

To check to see if the string ends with the extensions, we need to loop through the extensions, and use String.endsWith() to check to see if it ends with the extension:
for (String extension: extensions){
    if (fileName.endsWith(extension){
        return fileName;
    }
}
//If we get here, then it doesn't end with any of the extensions
return null;

As a side note, your fileTypesAllowed variable contains a space at the end.  You can remove it using String.trim(), but the ideal way to do it is to pass an array of strings into the function in the first place.  Passing lists as a string really isn't the way to do things.


How to use admin table theme with multistep form?

Question: I have 1000 records of users with name and checkbox. I want to show the list of users in table theme. I have use
theme('table', array('header' => $header, 'rows' => $rows));

But how to use it with multistep form. Please find the below code.
function getForm() {
$form = array();
$step1 = array();

drupal_add_js("
function checkUncheckAll(theElement){
  var theForm = theElement.form, z = 0;
  for(z=0; z<theForm.length;z++){
    if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
      theForm[z].checked = theElement.checked;
    }
  }
}", 'inline');

$step1['user'] = array(
   '#type' => 'container',
   '#tree' => TRUE,
   '#prefix' => '
',
   '#suffix' => '
',
);
$results = db_query("SELECT* FROM {user_token} ut LEFT JOIN {users} u ON u.uid= ut.uid where u.status=1 and u.uid!=0 group by ut.uid ")->fetchAll();

foreach($results as $k=>$result)
{
  $user[$result->uid] = $result->name;
    $defaults = array_keys($user);
}

 $step1['checkall'] = array(
 '#type' => 'checkbox',
 '#title' => t('Select / Unselect all'),
 '#attributes' => array('onclick' => 'checkUncheckAll(this);'),
 '#weight' => -1,
 );

 $step1['user'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Send message to listed users'),
 '#options' => $user,
 //'#default_value' => $defaults,
 '#attributes' => array('class' => array('check_notify_user'))
 );

 $step1['submit']=array(
     '#type'=>'submit',
     '#value'=>t('Next')
 );

$form[] = $step1;

$step2['message'] = array(
  '#type' => 'textarea',
  '#title' => 'Message',
  '#description' => t('No more than 250 words please!'),
  '#wysiwyg' => false,
  '#attributes' => array('maxlength' => 250),
);

$step2['prev'] = array(
  '#type' => 'submit',
  '#value' => t('Previous'),
  '#name' => 'prev',
  '#submit' => array('custom_previous_submit'),
);

$step2['submit']=array(
    '#type'=>'submit',
    '#value'=>t('Submit')
  );

$form[] = $step2;

return $form;

}
Answer: I assume you know how to do the multi-step form. For the table, you can use Drupal's table theme function. If the table contains only markup, you can do something like this:
$form['table'] = array(
  '#theme' => 'table',
  '#rows' => $rows,
  '#empty' => 'Empty List - No Entries',
  '#header' => $header,
);

or
$form['table'] = array ('#value' => theme('table', $headers, $rows));

You can use this in multistep form also.
If the table contains actual form elements (such as selects, textfields, etc.), you can wrap them in a form element that calls a theme function, like so:
$form['table'] = array ('#theme' => 'output_table');

$form['table']['element_1'] = array (...);
$form['table']['element_2'] = array (...);

Within 'theme_output_table', generate your $headers and $rows to feed to 'theme_table' by calling 'drupal_render' on the relevant form elements that are children of $form['table'].


formula in differential-geometry

Question: $(M,\omega)$ is a symplectic manifold, $\omega=d \lambda$, then I want to prove that:
$$
i_v\lambda\cdot\omega^n=n\lambda\wedge i_v\omega\wedge\omega^{n-1}.
$$
Answer: Let $N$ be a smooth manifold and $\alpha$ and $\beta$ differential forms and $X$ a vector field on it. Claim: $\imath_X(\alpha\wedge\beta)=\imath_X(\alpha)\wedge\beta+(-1)^{\mathrm{degree}(\alpha)}\alpha\wedge\imath_X(\beta)$.
Now you just need to use this formula in your particular case.
Here is an example, suppose that $\mathrm{degree}(\alpha)=k$ and $\mathrm{degree}(\beta)=k-1$:
\begin{equation}
\imath_X(\alpha\wedge\beta\wedge\beta)=\beta(X)\alpha\wedge\alpha+(-1)^{k-1}\beta\wedge\imath_X(\alpha\wedge\alpha) \\ =\beta(X)\alpha\wedge\alpha+(-1)^{k-1}\beta\wedge\imath_X(\alpha)\wedge\alpha+(-1)^{k-1}(-1)^k\beta\wedge\alpha\wedge(\imath_X\alpha) \ .
\end{equation}

formula in differential-geometry


What's the difference between java.lang.String.getBytes() and java.nio.charset.CharsetEncoder.encode()?

Question: I was reading through the source code of java.lang.String, specifically getBytes():
 public byte[] getBytes(Charset charset) {
         if (charset == null) throw new NullPointerException();
            return StringCoding.encode(charset, value, offset, count);
 }

However, I couldn't find the StringCoding.encode() method in the Java API.  I'd like to be able to compare it with java.nio.charset.CharsetEncoder.encode(), since that class/method is referenced as an alternative in the String.getBytes() javadoc.  How do I find the StringCoding class, and it's source code? And what is the difference between the respective .encode() methods?
Comment: See http://www.docjar.com/html/api/java/lang/StringCoding.java.html (It's not a public class...)
Comment: The source for StringCoding comes with String in the JDK.  In your IDE you can use `+` to navigate to it.
Answer: The difference is that with a CharsetEncoder you can choose how to fail; this is the CodingErrorAction class.
By default, String's .getBytes() uses REPLACE. Most uses of CharsetEncoder however will REPORT insead.
You can see an example of CodingErrorAction usage at the end of this page.
One such example of REPORT usage is in java.nio.file. At least on Unix systems, a pathname which you created from a String will be encoded before it is written to disks; if the encoding fails (for instance, you use ö and system charset US-ASCII), the JDK will refuse to create the file and you will be greeted with an (unchecked!) InvalidPathException.
This is unlike File which will create who knows what as a file name, and one more reason to ditch it...


How are melodic sequences used?

Question: I keep hearing about sequences. I know that there's both harmonic and melodic sequences. I am familiar with harmonic sequences I believe they're also called "basso ostinato" where you play a repeating loop in the bass, for example in Canon in D.
But what about melodic sequences. What are they usually used for? I'm not sure if they're supposed to loop also I'm not sure how they differ from a motif or just a basic melody.
Comment: https://en.wikipedia.org/wiki/Sequence_(music)
Answer: Ostinato is different than melodic or harmonic sequence.
Both involve repetition of material but in different ways. Ostinato would repeat a bass as the entirety of the formal theme. - not just a melodic segment, but all the harmonic material. Also the repeats do not shift the music around harmonically. It's the same harmony over and over. It's a form of theme and variation.
Sequence take a short segment of music and repeats it with some kind of harmonic transposing.

How are melodic sequences used?

As the linked wiki article explains there are many kinds of sequence. But it may be helpful to know that the commonest appearance of sequence in the common practice era will display both harmonic and melodic sequence...

Notice in that example from Bach (taken from the wiki article) the material is sequence both harmonically and melodically. I would say this is the typical way it is handled.
The fact is, when you sequence a passage by shifting it up or down by step, it simultaneously is a harmonic sequence. Harmonic and melodic sequence devices can be used independently, but it is very common to see then used simultaneous as just two sides of the same coin.
Comment: I see so it's just a pattern/motif that has a slight variation at each measure.
Comment: This is a diatonic sequence so the exact steps sizes (half or whole steps) change with each of the three sequences, but otherwise the melodic pattern is not changed. Look at only the top line, the melodic steps are: up 2, down 4, up a third. That patterns is sequenced _without variation_ three times. In this tonal style you wouldn't really consider the half/whole step changes which make it stay diatonic to be _variations_. Instead of calling it 3 small variations, call it 3 sequences.
Comment: That wording is just to make yourself clear to others. I think you understand the concept. Variation suggests some essential change or decoration to the melody, or a _relative_ change in harmony.
Answer: I'll just state my own experience with melodic patterns and sequences. A few years ago I found a copy of " Modern Improvising" by Leon White in an old used bookstore. I took it home and started working through the book and got to the section on Melodic Patterns, this book has 119 of them. I practiced religiously, 3 or 4 patterns a week, and within 2 or 3 weeks the melodic patterns began coming to mind whenever I would improvise on stage. Because I became very familiar with the sound of each pattern, I would start to hear them as useful parts in my head as I'm playing. It is kind of like learning new words I can use to communicate what I would like to say. The patterns can be used to build sequences if you choose but they are also useful as stand alone patterns. Additionally, practice of the patterns helps a lot with manual dexterity and alternate picking if you are playing guitar, and the rhythm of each pattern can help improve problems one might have with timing. For me it has been a win/win/win situation
Comment: @foreyez- A pattern would be a series of notes put together to make a short melody which can be used by itself or inserted in side a larger melodic line. Sometimes they are used in a sequence where the same interval step  pattern is applied followed by moving a step higher (ascending) or lower (descending) a selected distance up or down the scale. The" pattern" is repeating itself in a chosen "sequence" either ascending or descending the scale. Kind of like using words to build a sentence.
Comment: @foreyez- Motifs are usually altered slightly, whereas patterns maintain the same interval step pattern, but when used in sequences, move up or down using the next chosen scale degree as the first note of the pattern played in it's next repetition. It was a little bit confusing for me when I first got started with patterns but after working with them a few weeks, I was able to see the differences between patterns and Motifs
Comment: what would make a pattern into a sequence?
Comment: ok if I understand that right a sequence contains multiple patterns. and each pattern is slightly altered.

How are melodic sequences used?


How to Debug Tridion Templates and Workflows?

Question: I am new to SDL Tridion world and I have been assigned a couple of activities:
Create Page Template (PT), Component Template (CT), and a Sample Workflow. Basically I am experienced in .NET.
I have some startup code to start with, and I would like to know is there any way to debug the PT, CT, Workflow from Visual Studio 2010?
Your suggestion would be highly appreciated.
Comment: Are you able to debug directly on the CMS server, or will you be debugging remotely?
Answer: For compound templates either CT or PT, here is Tridion documentation (login required) with clear instructions on how to debug.
http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/idheading-259229208
For Workflow, it depends on what type of implementation you are following (VBScript or Event System (TOM .net) or Core Service ), but in general it is not different as above. You attach to the process and debug.
http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/task_BC70576958F3420CA4FC87B27CB0FC38
Comment: Workflow service will be running on your CMS Server. You login to your CMS Server and open VS attach to the workflow service. If you have to debug from Remote you can check here http://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx. I haven't tried remote debugging, I always do it from CMS server as it is easy and quick.


extrema in multivariate functions under consrtraints

Question: Given that
$f:\mathbb{R}^{2}\to \mathbb{R}$
$f(x,y) = e^{-xy}$
with constraint $x^{2} + y^{2} = 1$,
get the extrema of the function $f$
What I have tried so far:
I have set the latter equation as $y =\pm \sqrt{1-x^2}$
and substituted it into the function $f$, in order to get the first and the second derivates  with just one variable x. But this turned out to be awfully hectic, as I had to find in total of 4 derivatives and was wondering if there is a more elegant and concise way to go about this.
Answer: First of all, you can make the calculations a bit simpler if you realize that the minima/maxima of an exponential will occur in the same points as the minima/maxima of the exponent.
So, in this case, it is possible to show the the global extrema are attained in critical points of the Lagrangian
$$
L(x,y,\lambda)= -xy -\lambda(x^2+y^2-1)
$$
These critical points turn out to be $(\frac{\sqrt{2}}{2}, \pm \frac{\sqrt{2}}{2})$ and $(-\frac{\sqrt{2}}{2},\pm \frac{\sqrt{2}}{2})$, and the global minimum/maximum are $e^{-1/2}$ and $e^{1/2}$, respectively.
Comment: We haven't gotten to the topic of Larange multiplier, so I had to look it up. As far as I understand the first term in the right hand side should be $e^{-xy}$ but since the minima/maxima of the term will occure in the same points as the minima/maxima of the exponent, it can be replaced with just $-xy$?
Comment: Yes, you can right from the start replace $f(x,y)=e^{-xy}$ by $\tilde f(x,y)=-xy$ and the minima/maxima occur at the same points.
Answer: Maybe you can use polar coordinates $x=\cos\theta, y=\sin \theta$ to simplify the optimization problem.
You are left with extremizing
$f(\theta)=\exp \left[ -\frac12 \sin(2\theta) \right]$
It is simple to find that
minima is reached when $\theta=\{-3\pi/4,\pi/4\}$ and
maxima at $\theta=\{-\pi/4,3\pi/4\}$.


Hide path on frontpage redirect

Question: In a custom module i'm using an EventSubscriber to redirect different people to different frontpages. Below is the simplified code I'm using.
//GET PATH
$nid = 1;
$domain_url = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid);

//FRONTPAGE REDIRECT
$response = new RedirectResponse($domain_url);
$event->setResponse($response);

The module is working but there is one detail I can't seem to solve.
For example on my website domain.com I have node/1 that has an alias path /home.
When going to domain.com it is, because of my module as expected, redirected to domain.com/home. But what I want is the url not to show the home part. Is it possible to show the content of /home but keeping the url domain.com?
Comment: If you don't want to change the URL in the browser then don't redirect. From the event subscriber you could start a sub request. Or change the incoming path in path processing. For the latter @Jaypan has developed a solution by making path processing domain aware. See https://drupal.stackexchange.com/questions/288321/is-there-a-way-to-partially-rebuild-the-router-or-invalidate-a-route-cache
Comment: What @Jaypan has done...is exactly what I need but I can't figure out (by the post) what he did. It doesn't look like the full code. I'll try and figure out how path processing is working..
Comment: For *I've overriden Drupal\Core\Routing\RouteProvider::getRouteCollectionCacheId()* see https://www.bounteous.com/insights/2017/04/19/drupal-how-override-core-drupal-8-service/
Comment: Thanks! I ended up using large parts of the PathProcessorFront.php from core to get my module to work. Only thing is that I have a caching problem I'll create a new post for this.
Answer: You can add the path to your homepage from admin/config/system/site-information
And replace /node/1 to /home.
You don't need an even subscriber to do that.
Comment: I know the default way of setting the frontpage. I'm working with a custom module to be able to set multiple frontpages.
Comment: I would rather have one frontpage which would serve the content dynamically even if it needs multiple rules to load it and keep the default way of setting the frontpage.

Hide path on frontpage redirect


OWA 2003, can't save *.fr3 attachments

Question: I have a client who uses an application that uses *.fr3 files, which as far as I am aware are nothing more than binary files in a proprietary format. Those files are periodically emailed from the software company to my client. Using Outlook (2003 or 2010) the client can save the attachment and then copy the file to the application that uses them. No problems and nothing unusual so far.
When the client uses OWA (Exchange 2003), even on the same machine, and tries to save the attachments they result in zero byte files. The solution they have employed for those staff members who only have access via OWA has been to ask the software vendor to zip them up and resend them. This works fine as far as the file goes but involves extra steps and bother that shouldn't be required.
I can find nothing to explain why this only happens with *.fr3 files. All other attachments they receive, such as *.zip, *.pdf, *.doc(x), *.xls(x), etc. save perfectly. The anti-virus software (Avast) is not treating *.fr3 as anything special either.
Are *.fr3 files something special as far as OWA is concerned that I'm unaware of? How can I convince OWA to treat them the same as other file types, which all save without issue? This isn't a show-stopping problem but is just one of the annoyances I'm trying to clean up for the client.
Comment: It might be worth testing whether it's caused by the contents of the file or the extension by creating a junk binary file with a `.fr3` extension and sending that to the client or changing the extension on one of the legitimate files.
Comment: I'll give that a try on Monday.
Answer: I had the same problem with OWA 2003 a while back, using a custom extension.  Apparently the cause was a combination of no valid MIME type returned by the server, and IE detecting the MIME type incorrectly from the header of the file.
I'm still not sure why downloads were zero bytes (this can happen with XML files specifically, but I haven't read anything about it happening with binaries), but this solved it:

Add the .fr3 extension with the application/octet-stream MIME type on the IIS instance that serves OWA.  (If you can find a more appropriate MIME type for the files, use it instead -- application/octet-stream is for generic binaries).
Follow the steps posted by Brad_Saide to disable MIME handling and MIME sniffing on the client.  This is the short of it:

Navigate to the following registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_MIME_HANDLING
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_MIME_SNIFFING

Modify the DWORD value beside iexplore.exe from 1 to 0 in both areas.

The linked posting does not address zero byte downloads, and says that one or the other solutions  (either on the server or on the client) should fix DOCX download issues.  I made both changes and it solved my problem;  Unfortunately I didn't try making the changes incrementally, so I'm not sure if one or the other would fix it.
Try adding the extension/MIME pair to the server first, and then test and move onto the clients.

OWA 2003, can't save *.fr3 attachments


Can a Scala type parameter reference itself when used as a parameter to a base-class?

Question: If I have the following Scala type hierarchy:
// Base traits
trait TA[X <: TA[X,Y], Y <: TB[X,Y]]
trait TB[X <: TA[X,Y], Y <: TB[X,Y]]
trait TC[X <: TA[X,_]]

// More specific traits
trait TI[X <: TI[X,Y], Y <: TJ[X,Y]] extends TA[X,Y]
trait TJ[X <: TI[X,Y], Y <: TJ[X,Y]] extends TB[X,Y]
trait TK[X <: TI[X,_]] extends TC[X]

// Concrete class that should implement TK, but does not compile
class Z extends TK[TI[_,_]]

// What is needed to be able to get class Z to compile
// The reference of X to itself has been removed.
trait TC2[X <: TA[_,_]]
trait TK2[X <: TI[_,_]] extends TC2[X]
class Z2 extends TK2[TI[_,_]]

TC would be a generic manager of some sort of TA.
TK would be a more specific manager of a more specific TA (TI).
Z would be the concrete implementation that manages any object implementing TI.
Z is not legal, but Z2 is. Unfortunately, TC and TK are more specific than TC2 and TK2. So is there a way of declaring Z using TC and TK, instead of TC2 and TK2?
[EDIT] I failed to say in my original question, that I kind of understand why Z is unsound. What I really want to know is, if there is a way of saying something like:
class Z3 extends TK[TI[TI,_]]

Answer: When you have complex mutually recursive type bounds it can often be helpful see if you can translate your problem into an equivalent one using abstract type members instead. If we do that mechanically, your base and more specific traits end up looking like,
// Base traits
trait TA {
  type X <: TA
  type Y <: TB
}
trait TB {
  type X <: TA
  type Y <: TB
}

trait TC {
  self =>
  type X <: TA { type X <: self.X }
}

// More specific traits
trait TI extends TA {
  type X <: TI
  type Y <: TJ
}

trait TJ extends TB {
  type X <: TI
  type Y <: TJ
}

trait TK {
  self =>
  type X <: TI { type X <: self.X }
}

and now we have a straightforward definition of Z as,
class Z extends TK {
  type X = TI
}

Note that the definitions of the members of TA, TB and TI, TJ are essentially the same. Because these types are now type members we can factor them out into common base types like so,
// Base traits
trait T0 {
  type X <: TA
  type Y <: TB
}
trait TA extends T0
trait TB extends T0

trait TC {
  self =>
  type X <: TA { type X <: self.X }
}

// More specific traits
trait T1 extends T0 {
  type X <: TI
  type Y <: TJ
}

trait TI extends TA with T1
trait TJ extends TB with T1

trait TK extends TC {
  self =>
  type X <: TI { type X <: self.X }
}

class Z extends TK {
  type X = TI
}

Comment: While I can follow your argument, I think you have fixed the problem by changing the meaning of Z. Z was a TK, and therefore a TC in my example, but it wasn't, and shouldn't be, a TI. If TC is a "manager", TA is, for example, an office, and TB something office-related that a manager not cares about, and TK is an accounting manager and TI an accounting office, then Z would be a concrete instance of something that was at the same time an accounting manager and an accounting office. Also, I want to note that in my real code, TA and TB would differs because they would define their own behaviors.
Comment: Fair comment: I've tweaked the definition of Z above to address it. Note that you can add whatever other definitions you want to TA, TB, TI, TJ ... you just don't need to repeat the type members.
Answer: It would be unsound. Here is why, with a simplified example. We do not need two generic parameters, we do not need the subtypes TI,TJ and TK either
trait TA[X <: TA[X]]
trait TC[X <: TA[X]]
class Z extends TC[TA[_]]

type arguments [TA[_]] do not conform to trait TC's type parameter
  bounds [X <: TA[X]]

Let's see why this declaration is unsound, and it is proper that it fails.
Let's add some code. I change TC to a class, so that the code can be translated to java. A trait would do as well in scala.
trait TA[X <: TA[X]] {def f(x: X) }
class TC[X <: TA[X]] {def g(x: X) = x.f(x)}

It works fine, x: X is also TA[X], so there it has a routine f, which will accept an X.
If we try instead
class TC2[X <: TA[_]] {def g(x: X) = x.f(x)}

then it fails. We know there is an f method on x, but we do not know what type is needed as an argument, we cannot know that x will be ok. Indeed, suppose we define
class T1 extends TA[T1]] {def f(t1: T1) = {}; def t1Only = println("only in T1")}
class T2 extends TA[T1]] {def f(t1: T1) = t1.t1Only }

Now, if TC2 was allowed, I could create a TC2[T2], call g with a T2, which would call f in T2 with a T2. This is not allowed, and rightly so as T2 has no method t1Only.
This shows why TC cannot be accepts TA[_]] as its parameter, as that would allow T2, which is not compatible with method g. And so why we cannot define Z with parameter TA[_]. It would be the exact same in java, and with your original code as well.

Edit: I feel a little guilty about my answer. With the reason I gave why it should not be allowed, I thought there would be a simple workaround. It failed, I had no time to investigate further, and posted without mentioning it. The workaround was a self type. If we do
trait TA[X <: TA[X]] {self: X => }

then we cannot define T2 extends TA[T1]. So it is more limited that the original code. But we have to accept limitations to the original code anyway, because it was unsound. So it cannot be just a syntax trick, it has to make things impossible that were not. I thought T2 extends TA[T1] was likely not something that was intended, and that it was the one thing to prevent.
Apparently, it was not, same error. Now I do not have an example why it should not work. Which of course does not means there is none.
I then had a look at Miles' solution, wondering why the possibility of T2 extends TA[T1] does not hurt it. So again, discarding TB, Y, TI, TJ, and TK:
trait TA{type X}
trait TC{self => type X <: TA{type X <: self.X}
class Z extends TC{type X = TA}

This compiles. And we can do
trait T1 extends TA{type X = T1}
trait T2 extends TA{type X = T1}

But there is one thing we cannot do:
trait TA {type X <: TA; def f(x: X)}
trait TC {self =>
  type X <: TA{type X <: self.X}
  def g(x: X) = x.f(x)
}

We get the following error on g, for the x argument to f

type mismatch;  found   : x.type (with underlying type TC.this.X)
  required: x.X

TC is not exactly the original one (as originally, g was allowed). It is so because there is a type X <: self.X on TA while TC[X <: TA[X]] was the stronger type X = self.X. If we write that instead, we are back to the original error, Z does not compile.  So this TC is somewhat between the original TC (type X = self.X) and TC2 (no knowledge of the X of TA). Again, a limitation on the original code, we cannot define g.
If the limitation is acceptable, you're ok. I do not know how to write it as a generic (nor how to write the self type {self : X => with an abstract type member) . Miles is definitely the expert, I'm sure he would be able to tell either how it is done or that it is not possible.
Comment: Miles showed how it could work with abstract types, while you showed why it didn't work with generics. While both answers are useful, neither tells me if "class Z3 extends TK[TI[TI,_]]" is actually possible as generics, and how. Since generics and abstract types are said to be equivalent in Scala, would you know how to do it correctly with generics?
Comment: Sadly, short answer is I don't know. I'm not sure they are 100% equivalent. I would not have been able to convert to type members as @Miles did either. Long answer as an edit.
Comment: I don't know of any practical way of encoding the recursion you're after other than by using type members. Generics and type members aren't actually completely equivalent, and this is one of the situations which differentiates them.


How to automatically discover Web Service by scanning LAN C#

Question: I am consuming a web service (which was written in Java) in C#. The web service is available in LAN but at compile time I don't know the address of the server. I need to scan the network to find the IP address of the computer where the web service is hosted. I do know the port though.
At the moment, I have the following code, which is supposed to give me a list of all active IP address and then I am planning trying to find out if the write port is open, and as soon as I find a computer where the right port is open, I will know the IP address of the server, am I thinking along the correct lines?
<code>List<IPAddress> ipList = new List<IPAddress>();
IPGlobalProperties network = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = network.GetActiveTcpConnections();

foreach (TcpConnectionInformation ipEnds in connections)
{
    ipList.Add(ipEnds.LocalEndPoint.Address);
    Console.WriteLine(ipEnds.LocalEndPoint.Address.ToString());
}
</code>
Comment: Are you sure you want to scan every computer on the network to find the service? Can you modify the service at all?
Comment: @Steve What sort of changes would I have to make in the web service to make it easier?
Comment: If you have a range of IP addresses, you can use the netcat utility on linux (usually at /bin/nc) to check if a port on a specific IP is "UP". For e.g this simple bash script will identify the host for you: `$listOfIps="10.11.176.1 10.11.176.2 10.11.176.7"; for host in $listOfIps ; do if nc -z -w 5 $host 22; then echo "Service is up on port 22 on $host"; break; fi; done`
Comment: No, I have to do this programmatically in C#. And I know nothing about the LAN at compile time. @linuxfan
Comment: In that case you can attempt to connect to every (IP, port)  pair in your LAN with the connect() system call and check the return value for success. Netcat does the same but has some optimization in adding timeouts etc.
Comment: but how do I get the list of ALL IP addresses in the LAN?
Comment: No, using `IPGlobalProperties` will only provide actual active connections to the local computer. If I'm reading your question correctly, you don't know the IP to begin with, so NO connection. I'd start by listing the known hosts on your active `NIC` using `ARP` (e.g. type `arp -a` at a windows CMD prompt.) Collect the IP addresses listed, then one by one, try your connection string (I'm assuming HTTP) with each for the specific port.
Comment: yes, but how do I get the list in C#, I am not supposed to do it in a CMD prompt...

the thing is, the software is going to be deployed at a customers site, and it is just supposed to work out of the box, I don't know what the IP address for the server is going to be.
Comment: @Marci-man If you can change the web service (or actually, if you have access to the computer running the web service), you could add an additional function to the service (or a new service). It would listen for broadcast messages (maybe a UDP packet) that meets certain criteria. Call it a "discovery" packet. The server sees this, and immediately responds with a message saying "I'm right here, and my IP address is ...". Two packets. And you don't have to know the IP at all. Note that UDP isn't guaranteed to be received, so you might have to try more than once.
Answer: The web-services must have define the way you can discovered, for example you throw a broadcast with a specific soap message, in that way al services that matched with that soap message must response to you.
Also you can use DiscoveryClient class (C#) to discovered services, it allow you define scopes and other specifications.
Answer: Is your C# application that consumes the data at a static location?
At build time, you could modify your Java application to reach out to the consuming service to provide an accurate location. This should reduce extra noise on your network. This should also reduce time that your application will hang attempting to connect to each IP address on the specified port.


Minimizing a strictly convex function with inequality constraint

Question: So we've been learning about the Kuhn Tucker conditions in my non-linear optimization course and I've been having trouble with this problem: QUestion: description here
Question: a strictly convex function, $f$, achieves a global minimum over $R^2$ at $(-5,2)$. If you restrict the domain to $x,y \geq 0$, then prove that the minimum must occur at $x = 0$.
So far I've split it up into 4 cases: 1 the minimum occurs when both constraints are inactive ($x>0, y>0$), but this can't be a min since $grad(f) = 0$ only at $(-5,2)$, so the second case ($x=0, y>0$) I have to prove works which is essentially that $\frac{df}{dx} = \mu_1 >0$, and that the third case $\frac{df}{dx} = \mu_2$. I must prove is less than zero, so that makes it not possible, which also deals with the fourth case.
Any tips would be greatly appreciated,
Thanks a lot
Comment: What is the meaning of mew ?
Comment: It should be mu, sorry! Its from the Kuhn Tuckers conditions, if its an equality constraint we use lambda, and if it's an inequality constraint we use mu (for active constraints)
Comment: I´ve made an edit. Proof if it is in your sense.
Comment: Why are you already taking derivatives ? Nobody said the function was smooth. Avoid taking derivatives whenever you see a function...
Answer: Let $(x^*, y^*) = \arg\min_{x\geq 0, y\geq 0}f(x,y)$ such that $x^*>0$. Define $\alpha$ as the solution of the following equation $$-5\alpha + (1-\alpha)x^*=0.$$
Then $f$ attains a smaller value at $(0, 2\alpha+(1-\alpha)y^*)$ than $f(x^*, y^*)$. In fact, we obtain
$$f(x^*, y^*) > \alpha f(-5,2)+(1-\alpha)f(x^*, y^*)\geq f(0, 2\alpha+(1-\alpha)y^*),$$
where in the first inequality we used strict convexity, and in the second just the definition of convexity. This contradiction almost finishes the proof. Almost because in the very beginning you need to show that there exists at least one minimizer $(x^*, y^*)$. It remains as a simple exercise.


CSS treats height differently than width?

Question: On this podcast it is stated that CSS widths are passed down to the children but the heights are passed up to the parents. The relevant portion starts at 11:43 and goes on for a few minutes.
While I unfortunately find it all too easy to believe that CSS does a weird thing like that, I would like to see an example page that demonstrates this.
Can someone make a page that clearly shows that the height is passed up rather than down?
Answer: Up to down (Outside to inside). The outside height doesn't affect the inside.

div {
  border: 1px solid;
}

.outside {
  height: 200px;
}

Inside

Down to up (Inside to outside). The inside height does affect the outside.

div {
  border: 1px solid;
}

.inside {
  height: 200px;
}

    Inside


show a form in a popup when a button is pressed

Question: I am creating  a registration form it has multiple stages. I am able to redirect to another page with the help of a link.
How can i get the form as a popup with a button.
 $form['adding_disease']=array(
   '#markup'=> ''.t('disease_list').'',
 );

Here this snippet is written in a form with many other fields.
this link is in the middle of the form.
Answer: Another solution is to use Ctools Automodal module. This approach is less complicated to @Web-Beest answer.
Here is the example on how to use it.
function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE,
  );
}

The most important line in the above code is 'modal' => TRUE,.
Answer: You can use a CTools Modal window for this.
First you need to add a path to your hook_menu() which will call the modal function.
$items['your_path'] = array(
  'title' => 'Do modal popup',
  'page callback' => 'module_form_modal',
  'type' => MENU_NORMAL_ITEM,
);

Then you can create the function which will do the magic. The 'ctools_modal_form_wrapper' will wrap the form so it can be loaded in the modal.
function module_form_modal() {
  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'ajax' => TRUE,
    'title' => '',
    'build_info' => array('args' => array()),
  );
  $commands = ctools_modal_form_wrapper('YOUR_FORM_NAME', $form_state);
  if (!empty($form_state['ajax_commands'])) {
    $commands = $form_state['ajax_commands'];
  }
  print ajax_render($commands);
}

Then you need to add a ctools button in your form so it knows to use the modal.
$link = ctools_modal_text_button($text, 'your_path', $alt, $class);

Answer: this worked for me.
$form['adding_disease']=array(
'#markup'=>''.t('click here').''
);

and don't forget to include the below three lines in the callback, before calling the form.
ctools_include('modal');
ctools_modal_add_js();
ctools_include('ajax');


Parse database receiving corrupted audio files with Android Cordova App

Question: This code is working perfectly as expected on iOS, and appears to work perfectly on the Android device, but on inspecting the database, all the recordings made on an android phone wind up on the database with a size of 0kb and won't play. So they are corrupted or something...

        var options = { limit: 1, duration: 10 };
        console.log(options);
        $cordovaCapture.captureAudio(options).then(function(audioData)
        {
          //  alert("Record was success");

            console.log("in $cordovaCapture.captureAudio function")
            var path = audioData[0].fullPath;
            console.log(path + "   var path")
            window.localStorage['tmpRecord'] = path;
            console.log(window.localStorage['tmpRecord'] + " window.localStorage")
            window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, fail);

            function gotFS(fileSystem) {
                console.log(fileSystem + " gotFS function");
                fileSystem.root.getFile(audioData[0].name, {create : true}, gotFileEntry, fail);
            }

            function gotFileEntry(fileEntry) {
                console.log("gotFileEntry:" + fileEntry);
                fileEntry.file(gotFile, fail);
            }

            function gotFile(file){
                console.log("gotFile");
                //readBinaryString(file);
                readArrayBuffer(file);
            }

            /* GET TIMESTAMP */
            function checkTime(i) {
                if (i < 10) {
                    i = "0" + i;
                }
                return i;
            }

            function getHHMMSS(){
                var today = new Date();
                var h = today.getHours();
                var m = today.getMinutes();
                var s = today.getSeconds();
                // add a zero in front of numbers<10
                m = checkTime(m);
                s = checkTime(s);
                return h + ":" + m + ":" + s;
            }

            /************* SAVE THE FILE *************/
            function readArrayBuffer(file){
                var reader = new FileReader();
                console.log(reader + "   var reader is here");
                reader.onloadend = function(evt) {
                    console.log("readArrayBuffer : " + evt.target.result);

                    var ParseFile = new Parse.File("recording.wav", file);
                    console.log(ParseFile + "    var Parsefile is here")
                    ParseFile.save().then(function()
                    {
                       // alert('Inside ParseFile.save()');
                        var myPoint = new Parse.GeoPoint({latitude: $scope.currentLiveLatitude, longitude: $scope.currentLiveLongitude});
                        console.log(myPoint)
                        var recording = new Parse.Object("Recordings");
                        console.log(recording)
                        /*Set variables */
                        recording.set("username", "Sasstic Plurgery");
                        recording.set("latitude", $scope.currentLiveLatitude.toString());
                        recording.set("longitude", $scope.currentLiveLongitude.toString());
                        recording.set("geoLocation", myPoint);
                        recording.set("dateTime", getHHMMSS());
                        recording.set("recording", ParseFile);

                        /*Save to server */
                        recording.save({
                            success: function(recording) {
                                alert("Recordings saved successfully");
                            },
                            error: function(recording, error){
                                alert("Recordings save failure, error = " + error + " error msg: " + error.message);
                            }
                        });
                    },function(error) {
                        alert("File save failure");
                    });
                }
              reader.readAsArrayBuffer(file);
            }

What's going on here? I googled and googled, and didn't find any answers. Googled at least 3 pages, and a couple different queries too.
UPDATE - so I figured out how to check if the file is there in the first place using this code:

            function checkIfFileExists(path){
                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
                    fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
                }, getFSFail); //of requestFileSystem
            }
            function fileExists(fileEntry){
                alert("File " + fileEntry.fullPath + " exists!");
            }
            function fileDoesNotExist(){
                alert("file does not exist");
            }
            function getFSFail(evt) {
                console.log(evt.target.error.code);
            }
            checkIfFileExists(audioData[0].name);

And it returns false. So the file is being created by the Android Voice Recorder, but it supposedly does not exist within the file system, which is confusing since the file path in audioData[0].fullPath seems to be right, since I can see a file in Android File Transfer with that name under the Sounds directory.
Another explanation I came up with is that the livereload debugging mode of ionic run android -l supposedly uses the computer for all the file hosting, while just using the device as an interface. So maybe that has something to do with it - but when I do a plain ionic build and ionic or cordova run, I'm getting the same error with the uploaded file.
Right now the solution seems to be finding out where the default voice recorder saves its files and directing the path to refer to that.
Answer: Figured out the problem - the {create: true} parameter was causing a file to be made no matter what, thereby making a file with 0 kb. But still have the pathing problem. Have to figure out how to go from the fileSystem root of the app up a couple directories then back down one to the /Sounds folder, where the default voice recorder stores its stuff. Unless there is another plugin that can do the recording for us.


Quick reminder about asymptotes of piecewise functions

Question: it has been a while since doing calculus. I just need a reminder about vertical asymptotes. If I have
$$
 f(x) =
  \begin{cases}
      \hfill \frac{\cos(x)}{x}    \hfill & \text{ if $x\ne0$} \\
      \hfill 1 \hfill & \text{ if $x=0$} \\
  \end{cases}
$$
Clearly, the first piece has a vertical asymptote at $x=0$ (the limit as $x$ tends to $0$ is $\pm \infty$ depending on the side). So even though $f$ is defined for $x=0$, it doesn't change the fact that $f(x)$ has a vertical asymptote there, right? That is, we can't simply define our way out of a vertical asymptote?
Answer: The function is, for all intents and purposes, the same. The area under the curve from 0 to 1 is still not convergent, and the function is not differentiable at $x=0$ (as the limit of the value is still $\pm\infty,$ but the value at the point is 1, implying discontinuity). Depending on what you consider a vertical asymptote, it may or may not have one. The limit is still $\pm\infty$ depending on the side you approach from, a common definition for a vertical asymptote, but the value of x is defined, so the function is defined on the y axis. Assuming you go with the conventional definition that an asymptote "is a line such that the distance between the curve and the line approaches zero as they tend to infinity" (Wikipedia), then I would say the answer is yes - the asymptote still exists
Comment: Thanks a lot. It seemed I even answered my question by mentioning that the limit went to $\infty$. It helped to see you write it down though.
Answer: Here's your function:

Your asymptotes are still there as suspected. I think this confirms your suspicion. The asymptotes haven't been defined away.


Measure the performance of this year

Question: I am going to measure the performance of this year. The average of the past year records (e.g. 5 years) and this year record will be used to judge how many standard deviation it is and if this year performance has improved or not. However, I have a doubt if the average should also include this year record for calculation?
Answer: From a practical standpoint, by including the current year in whatever calculation you want to do, you are probably reducing the chance that the current year's value deviates from whatever baseline expectation you have.

Measure the performance of this year


Prove that the number of pairs of edges that cross in a drawing of $K_n$ is at least $\frac{1}{5}\binom{n}{4}$ (for $n\geq 5$)

Question: Here, $K_n$ is the complete graph on $n$ vertices.
The only thing I can think of is induction on the number of vertices. The claim holds for $n=5$; this is easy to check. I was thinking of assuming that it holds for $n-1$ and then consider a drawing of $K_{n-1}$ with a minimal number of crossings. Then add a vertex at each crossing to form a planar graph $L$, and then somehow get a lower bound $k$ on the size of a face $L$. Then when you add a vertex to $K_{n-1}$ to form $K_n$ it is in one of the faces of $L$, and it adds at least $n-1-k$ crossings.
But I can't get this to work out at all and I suspect it's a completely dead end.
Comment: It may help others if you properly define $K_n$. Or does the use of "drawing" give it a precise meaning?
Comment: @JaycobColeman good point, done.
Comment: It probably is a dead end - the problem is that a 'best-case graph' for $K_{n-1}$ isn't necessarily obtained by restricting the best-case graph for $K_n$, so you can't simply assume that $K_{n-1}$ can be extended in this fashion.
Comment: Have you looked at http://en.wikipedia.org/wiki/Crossing_number_(graph_theory) ? It gives a proof for a bound that evaluates to $\theta(n^4)$ for the complete graph, so it's of the right order.
Answer: Pick any five vertices. Then, as $K_5$ is not planar, there is a pair of edges in the graph generated by these 5 vertices which cross.
Thus, we get at least one crossing for every combination of $5$ vertices. In total, our count is at least $\binom{n}{5}$.
But, we might had counted the same crossing multiple times. Look at a crossing: lets say $v_iv_j$ and $v_kv_l$.We counted this crossing at most $n-4$ times: we might have counted it in the quintle $v_i v_j v_k v_l v_s$ where $1 \leq s \leq n$ and $s \neq i, s \neq j , s\neq l s\neq m$.
If $k$ is the number of crossings, and we counted each crossing at most $n-4$ times, our count is at most $k(n-4)$. Thus
$$k(n-4) \geq \binom{n}{5}\,.$$
Thus the number of crossings is at least
$$\frac{\binom{n}{5}}{n-4}=\frac{1}{5}\binom{n}{4}$$
Answer: A crossing in a drawing of $K_n$ is an unordered pair $\{e,f\}$ of edges which cross each other but have no endpoint in common, i.e., they have $4$ distinct endpoints between them. If $x=\{e,f\}$ is a crossing, let $V(X)$ be the set consisting of the $4$ endpoints of $e$ and $f$.
Let $f(n)$ be the crossing number of $K_n$, i.e., the minimum possible number of crossings in a drawing of $K_n$ in the plane. We know that$f(5)=\frac15\binom54$. In order to prove that $f(n)\ge\frac15\binom n4$ for all $n\ge5$, it will suffice to show that $f(n)/\binom n4$ is a nondecreasing function of $n$.
Consider any $n\ge5$. I want to show that $f(n)/\binom n4\ge f(n-1)/\binom{n-1}4$, i.e., that $(n-4)f(n)\ge nf(n-1)$.
Consider a drawing of $K_n$ with exactly $f(n)$ crossings. Let $S$ be the set of all pairs $(X,v)$ such that $X$ is a crossing in $K_n$ and $v$ is a vertex in $V(K_n)\setminus V(X)$. Choosing $X$ first, we see that $|S|=(n-4)f(n)$. Choosing $v$ first, we see that $|S|\ge nf(n-1)$. Thus $(n-4)f(n)\ge nf(n-1)$, Q.E.D.
Since $f(5)=1$, it follows that $f(n)\ge\frac15\binom n4$ for all $n\ge5$. Likewise, if we know (e.g. from OEIS or Wikipedia) that $f(7)=9$, it follows that $f(n)\ge\frac9{35}\binom n4$ for all $n\ge7$. Moreover, it is easy to see that there is a constant $c\gt0$ such that $f(n)\sim c\binom n4\sim\frac n{24}n^4$ as $n\to\infty$. The same arguments apply, e.g., to the rectilinear crossing number of $K_n$, i.e., the minimum number of crossings in a drawing of $K_n$ in which edges are drawn as straight line segments.
Comment: I don't see how "the crossing in a given krossing contribute to many krossings"? If edge $ab$ crosses edge $cd$, that contributes to the krossing $\{a,b,c,d\}$, period. Are you thinking of drawings where $ab$ crosses $ac$, or $ab$ crosses $ab$? OK, by a "krossing" I mean a drawing of $K_4$ in which **two independent edges** (so they have $4$ distinct endpoints) cross.
Comment: Two things: (1) Why must there be as many crossings as 'krossings'?  The 'krossing sets' don't have to be independent, and the crossing in a given krossing can contribute to many krossings.  (2) Where does your final argument use anything about the specific properties of krossings?  I don't see how it doesn't prove the same thing about any arbitrary graph property.
Comment: (Actually, adding my own answer to (2) : it doesn't use anything about _krossings_, but it uses the *decomposability* of $K_n$ essentially; it's not actually related to krossings at all, but That's Okay.  I'm still not sure about (1), though...
Comment: Regarding (2), this simple argument is indeed very general. For instance, in Ramsey theory: It's easy to see that any coloring of the edges of $K_6$ with $2$ colors contains at least $2$ monochromatic triangles. It follows from that (by the same argument I used in my answer) that, for $n\ge6$, any coloring of the edges of $K_n$ with $2$ colors contains at least $\frac1{10}\binom n3$ monochromatic triangles.
Comment: Ahh, I've got it.  Somehow I had a mental image of a 'krossing' (boy, does my autocorrect hate that term) as a thing that was a property of just a couple of the elements $a,b,c,d$ - I think as though those were edges rather than vertices.  But obviously any 'krossing' can only belong to one $K_4$, since it involves four distinct vertices.  What you're saying makes perfect sense to me.  Thank you!


Facebook php SDK - simple datafetch

Question: I'm trying to integrate my facebook app with PHP. What I need to do is have users go to the app-page, authenticate the app and then somehow I want to end up with a variable that contains the info I need so I can store it in MySQL.
I downloaded the facebook SDK, but I cannot figure out how to make it work. All the examples I can find refer to a file called facebook.php - but there is no such file in the SDK (maybe the changed it?).
I managed to get it working with JavaScript, but I don't know how to get from JavaScript to php (the user object, that is).
I would prefer to just run it entirely through php. What I'm trying to do is very simple, but I don't understand what I'm doing wrong. The following, for instance, does not work:
<?php
FacebookSession::setDefaultApplication('appid', 'appsecret');
require facebook-php-sdk-v4-master\src\Facebook\FacebookCanvasLoginHelper.php;

$helper = new FacebookCanvasLoginHelper();
try {
  $session = $helper->getSession();
} catch(FacebookRequestException $ex) {
  echo "error";
} catch(\Exception $ex) {
  echo "error 2";
}
if ($session) {
    echo "logged in";
}

?>

Gives PHP Fatal error:  Class 'FacebookSession' not found in
Where do I go? I don't think the Facebook getting started guide is helpful at all. It just starts out with "you have to do this" (what I did above) - but that doesn't work?
Comment: What version of PHP are you using?
Comment: Newest version... and Apache too.
Comment: 5.5.11 to be specific!
Comment: You need to require the FacebookSession.php file or configure an autoloader
Answer: Looks like they changed the whole SDK for PHP 5.4.
Well there's a few options, you could go with the older SDK and all those tutorials you found will work for that. Or you could learn some new things!
I suggest that if you want to use the new Facebook SDK, you go ahead an learn about composer first, it makes including libraries a piece of cake and all you'd have to do is include the autoloader at the top of the file. Once done, you can just follow the example and it should work.
If you don't want to learn composer, you'll have to include all the required files manually. Here's a basic example.
Comment: This gets me somewhere. Thanks a lot.
Comment: But ... I can't figure out how to use php to fetch data AND javascript to login at the same time? I end up in a huge mess everytime.

I just need to login, get data, post to SQL. Why is this so hard? I coded an entire iOS app that does this by the push of a button and that seemed like a walk in the park compared to this.
Answer: In your example it looks like the error was because you were calling
FacebookSession::setDefaultApplication

Before you'd actually included the SDK

Facebook php SDK - simple datafetch


which permission should be for client svn folder?(Ubuntu)

Question: which permission should be for client svn folder?(Ubuntu)
the case:
I should download files from svn server to my computer and able to do all svn action as programmer that doing change in the code(update etc..).
Default folder permission enforce working with sudo, Soo i think to change folder permission to 755.
Thanks,
Yosef
Answer: The default folder permissions are 0755 on Linux.  If you're asking whether or not you should change folder permissions to something other than that, the answer is almost certainly "no."
Update: It sounds like you have an ownership issue based on your comments.  To change ownership to your user and your user's group, use the following:
chown -R youruser:youruser /path/to/svn/working/dir

So for your case, if your username is yosef and you had used svn co in /home/yosef/some_svn_repo_you_checked_out, your command would be:
chown -R yosef:yosef /home/yosef/some_svn_repo_you_checked_out

Comment: soo why when i $ mkdir newdir not working? only with sudo?
Comment: Its probably not *owned* by the right user.  Run `ls -l ` and see what user owns it.
Comment: root, I ask about which permission should be for svn client folder
Comment: In your question, you asked about default [folder permissions](http://en.wikipedia.org/wiki/Filesystem_permissions).  What you're talking about now is ownership, and the question is--if this is indeed the client side, why did you checkout your svn repository as the root user?  I've updated my original answer to get you out of the mess--but it goes without saying that you should NEVER be executing arbitrary commands as root.