Coffeescript --- How to create a self-initiating anonymous function?

Question: How to write this in coffeescript?
f = (function(){
   // something
})();

Thanks for any tips :)
Answer: While you can just use parentheses (e.g. (-> foo)(), you can avoid them by using the do keyword:
do f = -> console.log 'this runs right away'

The most common use of do is capturing variables in a loop. For instance,
for x in [1..3]
  do (x) ->
    setTimeout (-> console.log x), 1

Without the do, you'd just be printing the value of x after the loop 3 times.
Comment: You can also write `f = do -> console.log x`
Comment: @scribu Well, those two statements are very different, and yours is actually the one that I should have given. Mine assigns the function `-> console.log 'this runs right away'` to `f`, then runs it; yours runs the function and then assigns its result to `f`, as in the original question. (Though in the case of `console.log`, the return value is always `undefined` anyway.)
Comment: As of CoffeeScript 1.3.1 (released April 2012), `do` also lets you pass arguments to the function. To pass `1` and `2` as the parameters `x` and `y`, write `do (x = 1, y = 2) ->`. (The documentation for this feature has [gotten lost](https://github.com/jashkenas/coffee-script/pull/2660#issuecomment-14369711), but [the issue where the feature was introduced](https://github.com/jashkenas/coffee-script/issues/960) has some examples.)
Comment: Exactly. Also, you can define object properties this way: `{f: do ->  // something}`
Answer: If you want to "alias" the arguments passed to self-invoking function in CoffeeScript, and let's say this is what you are trying to achieve:
(function ( global, doc ) {
  // your code in local scope goes here
})( window, document );

Then do (window, document) -> won't let you do that. The way to go is with parens then:
(( global, doc ) ->
  # your code here
)( window, document )

Comment: `do (global=window, doc=document) -> `
Answer: it's ridiculous easy in coffee:
do ->

will return
(function() {})();

Answer: try to use
do ($ = jQuery) ->

Answer: You can also combine the do keyword with default function parameters to seed recursive "self-initiating functions" with an initial value. Example:
do recursivelyPrint = (a=0) ->
  console.log a
  setTimeout (-> recursivelyPrint a + 1), 1000

Answer: do ->
    #your stuff here

This will create a self executing closure, which is useful for scoping.
Comment: This doesn't seem to add a whole lot of new information compared  to the other answers already posted. Rather than creating a competing answer, you might add more value by posting an informative comment under another answer that adds some clarity or useful information to the other answer.
Answer: Apologies, I solved it:
f = (
    () -> "something"
)()

Comment: @Squeegy I wouldn't necessarily say that. The `do` keyword has some limitations that make it necessary to use the JS-style approach sometimes (see [issue 960](https://github.com/jashkenas/coffee-script/issues/960)); `do` was really only added because of the loop-with-closures use case.
Comment: But we aren't using CoffeeScript to punch ourselves in the face like that either.
Answer: It should be
f = () ->
  # do something


How to display title of a webform in twig template Drupal 8

Question: I want to display webform title in a webform.html.twig but I did not find anything in variables array regarding the title of the webform
function THEMENAME_preprocess_webform($variables){
  $title = "?";
}

How do I get webform title in a preprocess function ? Any suggestions or other approach ?
Answer: Here is what I came up with
function THEMENAME_preprocess_webform(&$vars){
  $wfid = $vars["element"]["#webform_id"];
  $wf = \Drupal\webform\Entity\Webform::load($wfid);
  $vars["title"] = $wf->label();
}

Then in your theme's webform.html.twig you can use {{title}}
Comment: That is the best solution.
Comment: Thanks coming from you I take it its true ... wouldn't it make sense for webform to include it in the variables array for preprocessors to consume ?
Comment: The webform.twig.html template just renders the form does not really need to include the {{ title }}. https://cgit.drupalcode.org/webform/tree/templates/webform.html.twig
Comment: It doesn't *need* it, but if you `dump(_context|keys)` you'll see that it does have all the other makings necessary to have a working `{{title}}` field including `{{ title_attributes }}` as well as the less related misnomer `{{ title_prefix }}` and `{{ title_suffix }}`, so there is no reason *not* to pass the variable to the template, even if not used by default. I want to file this as a TX bug.


Java Enum with numeric values

Question: New to Java, but I've done some .Net programming. I'm wondering if Java has the equivalent of a .Net eum? Below is an example. I know Java has enum, but you can't assign values to it.
In .Net I could do an enum with values. When used in code I don't have to comment or, when writing new procedures, remember what 0, 1, 2, and 3 represent. I could also use the enum as parameter type in a constructor and then pass AccessType.Full, for instance, in as an argument.
How can I duplicate this is Android Studio?
Public Class Delete

    Private Enum AccessType
        Full = 0
        ReadOnly = 1
        Delete = 2
        Add = 3
    End Enum

    Private Sub DeleteIem(sItem As String)
        If User.Access = AccessType.Delete Or User.Access = AccessType.Full Then
            'delete something here
        Else
            MsgBox("You do not have access to delete these items.", vbInformation
        End If
    End Sub

End Class

In Android Studio I have the if{} block below.
if (AllLists.get(pos).Access == 0) {
    MsgText += getResources().getString(R.string.info_cat_shared_no) + "\n";
}
else if (AllLists.get(pos).Access == 1){
    MsgText += getResources().getString(R.string.info_cat_shared_edit) + "\n";
}
else if (AllLists.get(pos).Access == 2){
    MsgText += getResources().getString(R.string.info_cat_shared_no_edit) + "\n";
}

It would turn the code in to below and I wouldn't have to always be checking what 0, 1 ,2, & 3 represent. I looked up Java enums and they are just a list of string, which doesn't work for this, or at least not that I can think to implement it.
if (AllLists.get(pos).Access == AccessType.Full) {
    MsgText += getResources().getString(R.string.info_cat_shared_no) + "\n";
}
else if (AllLists.get(pos).Access == AccessType.ReadOnly){
    MsgText += getResources().getString(R.string.info_cat_shared_edit) + "\n";
}
else if (AllLists.get(pos).Access == AccessType.Delete){
    MsgText += getResources().getString(R.string.info_cat_shared_no_edit) + "\n";
}

Comment: possible duplicate of [Java Enum return Int](http://stackoverflow.com/questions/13792110/java-enum-return-int)
Answer: Actually, java enums are a pretty handy object.
You can add properties, even methods, if you want.  To assign properties, just add the value as an argument to the contructor as in:
public enum AccessType {
    Full(0),
    ReadOnly(1),
    Delete(2),
    Add(3);
    private final int code;

    AccessType(int code) {
        this.code = code
    }

    public int getCode() {
        return this.code;
    }
}

Comment: Thank you both. I read two or three examples of Java enums and neither showed how to add values like this. They were days of the week or colors, or something else with just strings. Frustrating.
Answer: Please have a look at this page from Oracle: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
You would have something like this for your ENUM (code untested):
public enum AccessType
{
    Full(0),
    ReadOnly(1),
    Delete(2),
    Add(3);

    AccessType(int type)
    {
        this.type = type;
    }
}

But the constructor by itself may not be necessary since you can use a switch case like this:
switch(AllLists.get(pos).Access)
{
    case Full:
        // ...
        break;

    case ReadOnly:
        // ...
        break;

    case Delete:
        // ...
        break;

    case Add:
        // ...
        break;
}

Java Enum with numeric values


Problema ao apresentar data no QTablewidget no python com PyQt5

Question: Tenho um programa que mostra informações sobre produtos e queria apresentar a data, só que quando aparece a data, é isto que mostra: PyQt5.QtCore.QDate(2018, 7, 7).
Para quem precisar esta aqui o código:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtWidgets import QTableWidgetItem, QTableWidget
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt
from adicionar_produtos import Ui_adicionar

class Ui_Produtos(object):

# Adicionar
 def add(self):
    self.window = QtWidgets.QMainWindow()
    self.ui = Ui_adicionar()
    self.ui.setupUi(self.window)
    self.window.show()
#MainWindow
def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.setMinimumSize(QtCore.QSize(0, 0))
    #MainWindow.setMaximumSize(QtCore.QSize(1920,510))
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
    self.gridLayout_2.setObjectName("gridLayout_2")
    self.gridLayout = QtWidgets.QGridLayout()
    self.gridLayout.setObjectName("gridLayout")
    self.horizontalLayout = QtWidgets.QHBoxLayout()
    self.horizontalLayout.setObjectName("horizontalLayout")
    self.btn_add = QtWidgets.QPushButton(self.centralwidget)
    self.btn_add.setObjectName("btn_add")
    self.horizontalLayout.addWidget(self.btn_add)
    #-----------------------------
    """
    self.btn_edit = QtWidgets.QPushButton(self.centralwidget)
    self.btn_edit.setObjectName("btn_edit")
    self.horizontalLayout.addWidget(self.btn_edit)
    """
    #---------------------------------------
    self.btn_del = QtWidgets.QPushButton(self.centralwidget)
    self.btn_del.setObjectName("btn_del")
    self.horizontalLayout.addWidget(self.btn_del)
    spacerItem = QtWidgets.QSpacerItem(998, 20, QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum)
    self.horizontalLayout.addItem(spacerItem)
    """
    self.btn_stock = QtWidgets.QPushButton(self.centralwidget)
    self.btn_stock.setObjectName("btn_stock")
    self.horizontalLayout.addWidget(self.btn_stock)
    spacerItem1 = QtWidgets.QSpacerItem(150, 20, QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Minimum)
    self.horizontalLayout.addItem(spacerItem1)
    """
    #---------------------------------------------------
    """
    self.btn_cat = QtWidgets.QPushButton(self.centralwidget)
    self.btn_cat.setObjectName("btn_cat")
    self.horizontalLayout.addWidget(self.btn_cat)
    """
    #-----------------------------------------------------------
    self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
    self.tablep = QTableWidget()
    self.gridLayout.addWidget(self.tablep)
    self.produtos()
    header = self.tablep.horizontalHeader()
    header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(6, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(7, QtWidgets.QHeaderView.ResizeToContents)
    header.setSectionResizeMode(8, QtWidgets.QHeaderView.ResizeToContents)
    #-------------------------------------------------------
    self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 783, 21))
    self.menubar.setObjectName("menubar")
    self.menuFicheirp = QtWidgets.QMenu(self.menubar)
    self.menuFicheirp.setObjectName("menuFicheirp")
    self.menuExibir = QtWidgets.QMenu(self.menubar)
    self.menuExibir.setObjectName("menuExibir")
    self.menuAjuda = QtWidgets.QMenu(self.menubar)
    self.menuAjuda.setObjectName("menuAjuda")
    self.menuSobre = QtWidgets.QMenu(self.menuAjuda)
    self.menuSobre.setObjectName("menuSobre")
    MainWindow.setMenuBar(self.menubar)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)
    self.actionExportar = QtWidgets.QAction(MainWindow)
    self.actionExportar.setObjectName("actionExportar")
    self.actionFechar_Janela = QtWidgets.QAction(MainWindow)
    self.actionFechar_Janela.setObjectName("actionFechar_Janela")
    self.actionSair = QtWidgets.QAction(MainWindow)
    self.actionSair.setObjectName("actionSair")
    self.actionComo_Utilizar = QtWidgets.QAction(MainWindow)
    self.actionComo_Utilizar.setObjectName("actionComo_Utilizar")
    self.actionCriador = QtWidgets.QAction(MainWindow)
    self.actionCriador.setObjectName("actionCriador")
    self.menuFicheirp.addAction(self.actionExportar)
    self.menuFicheirp.addSeparator()
    self.menuFicheirp.addAction(self.actionFechar_Janela)
    self.menuFicheirp.addAction(self.actionSair)
    self.menuSobre.addAction(self.actionCriador)
    self.menuAjuda.addAction(self.actionComo_Utilizar)
    self.menuAjuda.addSeparator()
    self.menuAjuda.addAction(self.menuSobre.menuAction())
    self.menubar.addAction(self.menuFicheirp.menuAction())
    self.menubar.addAction(self.menuExibir.menuAction())
    self.menubar.addAction(self.menuAjuda.menuAction())

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

    self.tablep.itemChanged.connect(self.editar)
    self.btn_add.clicked.connect(self.add)
    self.btn_del.clicked.connect(self.eliminar)

    #ler produtos
def produtos(self):
    db = QSqlDatabase.addDatabase('QMYSQL')
    db.setHostName("localhost")
    db.setDatabaseName("stock")
    db.setUserName("root")
    db.setPassword("")
    estado = db.open()
    print(estado)
    if estado == False:
       msgBox = QtWidgets.QMessageBox()
       msgBox.setIcon(QtWidgets.QMessageBox.Warning)
       msgBox.setWindowTitle("Erro")
       msgBox.setText(db.lastError().text())
       msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
       msgBox.exec_()
    else:
       self.tablep.setColumnCount(9)
       self.tablep.setHorizontalHeaderLabels(['ID', 'Nome', 'Descrição', 'Marca', 'Nível de Stock', 'Stock Fora?', 'Data de Reabastecimento', 'Preço', 'Validade'])
       row = 0
       sql = "SELECT ID, Nome, Descrição, marca, stock_nivel, stock_fora, dat_reabast, preco, validade FROM produtos"
       query = QSqlQuery(sql)
       while query.next():
             self.tablep.insertRow(row)
             ID = QTableWidgetItem(str(query.value(0)))
             nome = QTableWidgetItem(str(query.value(1)))
             Descricao = QTableWidgetItem(str(query.value(2)))
             Marca = QTableWidgetItem(str(query.value(3)))
             Stock_nivel = QTableWidgetItem(str(query.value(4)))
             Stock_fora = QTableWidgetItem(str(query.value(5)))
             dat_reabas = QTableWidgetItem(str(query.value(6)))
             preco = QTableWidgetItem(str(query.value(7)))
             Validade = QTableWidgetItem(str(query.value(8)))
             self.tablep.setItem(row, 0, ID)
             self.tablep.setItem(row, 1, nome)
             self.tablep.setItem(row, 2, Descricao)
             self.tablep.setItem(row, 3, Marca)
             self.tablep.setItem(row, 4, Stock_nivel)
             self.tablep.setItem(row, 5, Stock_fora)
             self.tablep.setItem(row, 6, dat_reabas)
             self.tablep.setItem(row, 7, preco)
             self.tablep.setItem(row, 8, Validade)
             row = row + 1
    db.close()
def eliminar(self):
    db = QSqlDatabase.addDatabase('QMYSQL')
    db.setHostName("localhost")
    db.setDatabaseName("stock")
    db.setUserName("root")
    db.setPassword("")
    estado = db.open()
    if estado == False:
       msgBox = QtWidgets.QMessageBox()
       msgBox.setIcon(QtWidgets.QMessageBox.Warning)
       msgBox.setWindowTitle("Erro")
       msgBox.setText(db.lastError().text())
       msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
       msgBox.exec_()
    else:
        rows = self.tablep.selectionModel().selectedRows()
        index = []
        for i in rows:
            index.append(i.row())
            index.sort(reverse=True)
            for i in index:
                ID = self.tablep.item(i, 0).text()
                self.tablep.removeRow(i)
                sql = "DELETE FROM produtos WHERE ID=:id"
                query = QSqlQuery()
                query.prepare(sql)
                query.bindValue(":id", ID)
                estado = query.exec_()
                if estado == False:
                     msgBox = QtWidgets.QMessageBox()
                     msgBox.setIcon(QtWidgets.QMessageBox.Warning)
                     msgBox.setWindowTitle("Erro")
                     msgBox.setText(db.lastError().text())
                     msgBox.setStandardButtons(QtWidgets.QMessageBox.Discard)
                     msgBox.exec_()
    db.close()

def editar(self):
    db = QSqlDatabase.addDatabase('QMYSQL')
    db.setHostName("localhost")
    db.setDatabaseName("stock")
    db.setUserName("root")
    db.setPassword("")
    estado = db.open()
    if estado == False:
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Warning)
        msgBox.setWindowTitle("Erro")
        msgBox.setText(db.lastError().text())
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msgBox.exec_()
    else:
        column = self.tablep.currentColumn()
        row = self.tablep.currentRow()
        ID = self.tablep.item(row, 0).text()
        value = self.tablep.currentItem().text()
        columns = ['ID', 'Nome', 'Descrição', 'Marca', 'Nível de Stock', 'Stock Fora?', 'Data de Reabastecimento', 'Preço', 'Validade']
        query = QSqlQuery()
        sql = "UPDATE produtos SET " + columns[column] + "=" + ":value WHERE ID=:id"
        query.prepare(sql)
        query.bindValue(":id", ID)
        query.bindValue(":value", value)
        estado = query.exec_()
        if estado == False:
            msgBox = QtWidgets.QMessageBox()
            msgBox.setIcon(QtWidgets.QMessageBox.Warning)
            msgBox.setWindowTitle("Erro")
            msgBox.setText(db.lastError().text())
            msgBox.setStandardButtons(QtWidgets.QMessageBox.Discard)
            msgBox.exec_()
    db.close()

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "Produtos"))
    self.btn_add.setText(_translate("MainWindow", "Adicionar"))
    #self.btn_edit.setText(_translate("MainWindow", "Editar"))
    self.btn_del.setText(_translate("MainWindow", "Eliminar"))
    #self.btn_stock.setText(_translate("MainWindow", "Stock"))
    #self.btn_cat.setText(_translate("MainWindow", "Categorias"))
    self.menuFicheirp.setTitle(_translate("MainWindow", "Ficheiro"))
    self.menuExibir.setTitle(_translate("MainWindow", "Exibir"))
    self.menuAjuda.setTitle(_translate("MainWindow", "Ajuda"))
    self.menuSobre.setTitle(_translate("MainWindow", "Sobre"))
    self.actionExportar.setText(_translate("MainWindow", "Exportar"))
    self.actionFechar_Janela.setText(_translate("MainWindow", "Fechar Janela"))
    self.actionSair.setText(_translate("MainWindow", "Sair"))
    self.actionComo_Utilizar.setText(_translate("MainWindow", "Como Utilizar"))
    self.actionCriador.setText(_translate("MainWindow", "Criador"))

if __name__ == "__main__":
   import sys
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow()
   ui = Ui_Produtos()
   ui.setupUi(MainWindow)
   MainWindow.show()
   sys.exit(app.exec_())

Answer: Utilize o toString() para exibir.
Ex:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PyQt5.QtCore import QDate

# Exibindo a data que foi passada para o QDate().
print(QDate(2018, 7, 7).toString())

O toString() também permite a formatação da data, para isso:

d:       Os dias sem zero (1 até 31).
dd:      Os dias com zero (01 até 31).
ddd:     Nome do dia abreviado (Ex: 'Seg', 'Dom').
dddd:    Nome do dia completo (Ex: 'Segunda' to 'Domingo').
M:       O mês sem zero (1 até 12).
MM:      O mês com zero (01 até 12).
MMM:     Nome do mês abreviado (Ex: 'Jan', 'Dez').
MMMM:    Nome do mês completo (Ex: 'Janeiro', 'Dezembro').
yy:      Ano com 2 dígitos (00 até 99).
yyyy:    Ano com 4 dígitos.

Ex:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PyQt5.QtCore import QDate

# Formatando a exibição.
print(QDate(2018, 7, 7).toString('dd/MM/yyyy'))
print(QDate(2018, 7, 7).toString('ddd d MMMM yy'))
print('Hoje é:', QDate(2018, 7, 7).toString('dddd'))

Dependendo da situação você pode utilizar:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PyQt5.QtCore import QDate

# Formatadores prontos.
print('Dia:', QDate(2018, 7, 7).day())
print('Mês:', QDate(2018, 7, 7).month())
print('Ano:', QDate(2018, 7, 7).year())


Create new list from a old list using a lambda function

Question: I have the following: List<InputRow> which contains a number of InputRow objects.
I am wondering if there is a way for me to use a lambda function on my original list to give me a new List where InputRow.someProperty > 1 for all the objects.
This would leave me with a list of InputRow objects all having someProperty greater than 1.
Comment: possible duplicate of [using LINQ to remove objects within a List](http://stackoverflow.com/questions/853526/using-linq-to-remove-objects-within-a-listt)
Answer: You can of course also do this:
var list = new List<string>(){ "a", "b", "c" };

list.RemoveAll(s => s == "b");

which removes the items in place instead of creating a new list.
Answer: You could use LINQ (a conjunction of the .Where() and .ToList() extension methods):
List<InputRow> originalList = ...
List<InputRow> filteredList = originalList
    .Where(x => x.someProperty > 1)
    .ToList();

Comment: Using `RemoveAll` on the List avoids deleting and re-creating the list.
Comment: @Servy Baxter wants those results not remove them
Comment: @Servy Can you elaborate on the usage of RemoveAll?  I could flip the statement to say RemoveAll less than or equal to 1.  I am just not sure what the syntax for that would be.
Comment: list.RemoveAll(x => x.SomeProperty<=1);
Comment: @NikhilAgrawal You can either logically refactor the lambda to mean the opposite (simple enough in this case), or you can just add a NOT outside of the whole thing to cover the general case.
Comment: To turn true into false just add !        list.RemoveAll(x => !(x.SomeProperty<=1));
Comment: Excellent, thank you for all the great answers / comments on this.  I have a much better idea of how to use those now.
Answer: Sure. You can do this:
var newList = inputRowList.Where(inputRow => inputRow.someProperty > 1).ToList();

Answer: List<InputRow> newlist = oldlist.Where(x => x.someProperty > 1).ToList();

This will search your old list on the condition that someProperty > 1 and convert the result into List using .ToList()


Sendbird SDK requires fs package in react native

Question: When I install the sendbird SDK into a expo managed react native project I get the following error:
<code>The package at "node_modules/sendbird/SendBird.min.js" attempted to import the Node standard library module "fs". It failed because React Native does not include the Node standard library. Read more at https://docs.expo.io/versions/latest/introduction/faq/#can-i-use-nodejs-packages-with-expo
</code>
However fs is a node package which isn't the environment run by react native. I've looked through the Sendbird examples, and have used this very same SDK in other apps. What am I doing wrong with this one?
Answer: SendBird here! Our apologies, but there is a known issue in JavaScript version 3.0.119 that is causing it. This will be fixed in the next version, coming very soon! In the meantime, please build with version 3.0.118 as needed.
If you are using npm, you can run this command:
npm install --save firstname.lastname@example.com


java - jdbc performance

Question: I need one help from you guys regarding JDBC performance optimization. One of our pojo is using jdbc to connect to a oracle database and retrieve the records. Basically the records are email addresses basing upon which emails will be sent to the users. The problem here is the performance. This process happens every weekend and the records are very huge in number, around 100k.
The performance is very slow and it worries us a lot. Only 1000 records seem to be fetched from the database every 1 hour, which means that it will take 100 hours for this process to complete (which is very bad). Please help me on this.
The database server and the java process are in two different remote servers. We have used rs_email.setFetchSize(1000); hoping that it would make any difference but no change at all.
The same query executed on server takes 0.35 seconds to complete. Any quick suggestion would of great help to us.
Thanks,
Aamer.
Comment: When you say "remote server" do you actually mean "servers that are far apart" (in terms of network infrastructure) or do you simply mean that they are two separate servers (in the same data center)? That kind of performance should *not* happen anyway. Do you execute only a single query?
Comment: Please show us the queries that are being performed here and maybe some pseudocode of the process.  Right now we are guessing at the problems.
Comment: Are you sure that the fetch is the slow point?  The fact that you are fetching only 1000 rows per hour raises a red flag (for me) that the stuff processing the rows is the choke point.
Comment: Another idea; Are you connecting to the database to fetch each row?  In general, that is a bad idea.
Comment: Are you sure the problem is with retrieving the mailaddresses from the database, and not with - for example - sending the email? In the past I have seen SMTP services taking several seconds to send a single message because of various security checks (origin, destination, blacklists, reverse DNS checks that failed or were slow etc). In your example a single message takes 3.6 seconds to process. I would sooner try to blame the sending of mail, than the database.
Answer: First look at your queries. Analyze them. See if the SQL could be made more efficient (ie, ask the database for what you want, not for what you don't want -- makes a big difference). Also check to see if there are indexes on any fields in your where and join clauses. Indexes make a big difference. But it can't be just any indexes. They have to be good indexes (ie, that the fields that make up the index provide enough uniqueness for the database to retrieve things appropriately). Work with your DBA on this. Look for either high run time against the db or check for queries with high CPU usage (even if the queries run sub-second). These are the thing that can kill your database.
Also from a code perspective, check to see if you are opening and closing your connections or if you are re-using them. Can make a big difference too.
It would help to post your code, queries, table layouts, and any indexes you have.
Answer: Use log4jdbc to get the real sql for fetching single record. Then check speed and plan for that sql. You may need a proper index or even db defragmentation.
Answer: Not sure about the Oracle driver, but I do know that the MySQL driver supports two different results retrieval methods: "stream" and "wait until you've got it all".
The streaming method lets you start process the results the moment you've got the first row returned from the query, whereas the other method retrieves the entire resultset before you can start work on it. In cases where you deal with huge recordsets, this often leads to memory exceptions, or slow performance because java hit the "memory roof" and the garbage collector can't throw away "used" records like it can in the streaming mode.
The streaming mode doesn't let you navigate/scroll the resultset the way the "normal"/"wait until you've got it all" mode...
Anyway, not sure if this is of any help but it might be worth checking out.
Comment: By the way...make sure the connection uses compression. In cases where you're not retrieving results from the same physical server, compression can often give a fair performance boost.
Comment: there's tonnes of other things such as clustering indexes, using materialised query tables, partitioning data but I'd for the low hanging fruit first.
Answer: My answer to your question, in summary is:
1. Check network
2. Check SQL
3. Check Java code.
It sounds very slow. First thing to check would be to see if you have a slow network.  You can do this pretty quickly by just pinging the database server.  Or run the database server on the same machine as your  JVMM.  If it is not the network, get an explain plan for your SQL and ensure you are not doing table scans when you don't need to be.   If it is not the network or the SQL, then it's time to check your Java code. Are you doing anything like blocking when you shouldn't be?

java - jdbc performance


: Can the canonical theorem on Riemann integrability be taken as the definition of continuity?

Question: Can the canonical theorem on Riemann integrability (namely, that a bounded real-valued function defined on a closed interval is Riemann-integrable if, and only if, its discontinuities constitute a set of measure zero) be taken as the definition of continuity? If so, it would then be a theorem that a function f is continuous at a limit point a in its domain if, and only if, the limit of f(x) as x goes to a is f(a).
edit (2.Sep.2013, CST, MERCA)
I am not interested in defining continuity this way. I'm only interested in whether it is POSSIBLE to define continuity this way. That is, just as there is a (long) list of statements equivalent to the Axiom of Choice, so also was I wondering whether this is on the list of statements equivalent to the definition of continuity, that's all. I (weakly) conjecture that it is indeed on the list, and so I'm holding out for an answer that proves this. An answer that simply says that the answerer does not see how it can be done is not sufficient for me to give up my conjecture, but a counterexample certainly would.
Comment: I think you're going to have to clarify how you expect a definition of continuity to arise out of this.
Comment: To elaborate on Ben's point: this theorem lets us make the following definition: A bounded function $f\colon [a,b] \to \mathbb{R}$ is "continuous almost everywhere" iff it is Riemann integrable. However, it's not clear (at least to me) how to proceed to define the notion of continuity at a point. (And on top of that, there's the fact that the theorem is limited to bounded functions.) The underlying issue, I think, is that given a function $f\colon [a,b] \to \mathbb{R}$ altering its value at a single point will affect its continuity but not its Riemann integrability
Comment: ...For instance, suppose I said "I conjecture that continuity of a function $f: \mathbb{R} \rightarrow \mathbb{R}$ can be given in terms of cyclic groups".  That sounds ridiculous, but how do I disprove it?
Comment: @Mike: The Axiom of Choice is a statement -- it has a truth value --  as are the things that are equivalent to it.  What does it mean for two definitions (of different things) to be equivalent (definitions can't be true or false)?  Can you give an example of this?  Until you do this what you are asking does not seem clear enough to allow a proof or counterexample.
Comment: To say a little more: sometimes the definition of $X$ can be expressed in terms of the definition of $Y$ and conversely, in a useful way.  For instance, the definition of continuity is traditionally given in terms of limits.  But this can also be done the other way around: $\lim_{x \rightarrow c}f(x) = L$ if when you define $f(c) = L$ you get a function which is continuous at $c$.  This notion of equivalence is useful but very informal.  I'm not sure how meaningful it is to conjecture such an equivalence exists because I don't know what it means to disprove such a conjecture....
Answer: The (Riemann)-Lebesgue Criterion gives a criterion for a bounded function to be almost everywhere continuous.  So you could take that as the definition of almost everywhere continuity for bounded functions if you want, although I don't see any particular advantage in doing so.  (Why do you want to define continuity in terms of Riemann integrability anyway?)
If $f$ is continuous at $c$ and we modify the value of $f$ at $c$ (while keeping every other value unchanged) then the modified function cannot be continuous at $c$.  The same holds if we modify the value of $f$ at any finite set of points on its domain.
On the other hand, if $f: [a,b] \rightarrow \mathbb{R}$ is Riemann integrable, then if we change the values of $f$ at any finite set we do not disturb the Riemann integrability or the value of the integral.  This is a nice elementary exercise involving the definition of the Riemann integral: the idea is to take an arbitrarily small subinterval around each modified point.
These diametrically opposite properties make it hard to see how one could possibly define continuity in terms of Riemann integrability.
Comment: This answer is mostly pretty good, but I find your description of continuity as a pointwise property a rather strange one. After all, you can't tell if a function is continuous by looking at any single point (heck, in the real case you can't even look at merely countably many points!) – it's only when you look at relationships between points that you can see it. Contrast to a property like "pointwise bounded" where the property holds exactly if it holds at every point considered individually.
Comment: @Ben: OK, I agree that "pointwise property" didn't really mean much, so I took it out and left the contrasting properties of continuity and Riemann integrability that I actually meant.
Answer: You have given a definition of Riemann integrability for bounded functions, which states that the function f can be discontinuous on a set of measure 0.  So if it is discontinuous, it is discontinuous, even though it is perfectly integrable.  Your definition of continuity is correct, but there is no guarantee that f will meet that definition -- it might, or it might not.
However $\int f$ (i.e. any function F whose derivative is f where f is continuous) can be defined to be continuous although it will not be everywhere differentiable.
In general integration makes functions smoother, so that a slightly discontinuous function has a continuous integral F (in the sense of described above); a continuous function will yield an F that is differentiable and so on.


Integral of $e^{ix^2}$

Question: How does one evaluate
$$\int_{-\infty}^{\infty} e^{ix^2} dx$$
I know the trick how to evaluate $\int_{-\infty}^{\infty} e^{-x^2}dx$ but trying to apply it here I get a limit which does not converge:
$I = \int_{-\infty}^{\infty} e^{ix^2}dx = \int_{-\infty}^{\infty} e^{iy^2}dy \\\implies I^2 = \int_{-\infty}^{\infty} \int_{-\infty}^{\infty} e^{i(x^2+y^2)}dxdy = \int_{0}^{2\pi}\int_{0}^{\infty} re^{ir^2} = -\pi i (e^{i\infty}-e^0) $
and $e^{i\infty} $ is not defined.
Are there any other methods? I am not interested in the result (WolframAlpha can do this for me), but rather the method.
Comment: $|e^{i x^2}| = 1$ for all $x$, so it can't converge in the usual sense.
Comment: This is known as the Fresnel integral.
Comment: Consider the two paths (1) from $0$ to  ${1+i \over \sqrt{2}} R$ and from ${1+i \over \sqrt{2}} R$ to $R$, and (2) from $0$ to $R$. Since $f(z) = e^{i z^2}$ is entire, the integrals over either path are the same. Show that the integral over the arc goes to zero and the integral over the ${\pi \over 4} $ ray has the limit (as $R \to \infty$) ${1+i \over \sqrt{2}} {\sqrt{\pi} \over 2}$.
Comment: @copper.hat ah you mean absolute convergence, got it
Comment: Hint: integrate around a wedge  with angle $\pi/4$ in the first quadrant in the comlplex plane...
Comment: the answer should be $$(1+i) \sqrt{\frac{\pi }{2}}$$
Comment: Yes, I am trying to solve the fresnel-integrals that way
Comment: @tired I did that and what I have to show now is that $\int_0^R \exp(ix^2)dx = \exp(i\pi/4) \int_0^R \exp(-x^2) dx $ ... can you help me over there?
Comment: what exactly is the problem? this is a quiete straighforward excersise in parameterizing curves in the complex plane
Comment: the parameterization and showing that one integral goes to zero is no problem, but to show that the equation above holds is my problem
Comment: I might add to show that this equation holds without using fresnel-integrals
Comment: you can deform your contour of integration by using the analitccity of the integrand for example
Comment: Without contours, one uses the [imaginary error function](https://www.wolframalpha.com/input?i=int+exp%28i+x%5E2%29), takes a limits, and the answer appears
Comment: @copper.hat what do you mean by the norm is 1 for all x, so it can't converge in the usual sense? Why does it need to converge and in what usual sense?
Comment: @AnnaVakarova Meaning it is an improper integral.
Answer: All right, let's do some complex analysis!  Let's integrate $e^{iz^2}$ over the closed contour defined in three pieces (the arrows indicating the direction of contour integration)
$$
\begin{cases}
\Gamma_1: & |z|:0\rightarrow R, & \theta=0 \\
\Gamma_2: & |z| = R, & \theta: 0\rightarrow \pi/4\\
\Gamma_3: & |z|:R\rightarrow0, & \theta=\pi/4
\end{cases}
$$
which we will eventually want to take the limit $R\rightarrow\infty$.
It can be seen that
$$
\int_0^\infty e^{ix^2}dx=\lim\limits_{R\rightarrow\infty}\int_{\Gamma_1}e^{iz^2}dz
$$
and since $e^{ix^2}$ is an even function
$$
\int_{-\infty}^{\infty}e^{ix^2}dx=2\int_0^\infty e^{ix^2}dx
$$
so we're heading in the right direction.
Now Cauchy's Theorem states that
$$
\oint_D f(z)dz =0
$$
for $f(z)$ analytic in $D$.  Our function, $e^{iz^2}$, has no singularities and is defined on the entire complex plane, so it is considered an entire function, and Cauchy's Theorem holds for our closed contour:
$$
\int_0^R e^{ix^2}dx+\int_{\Gamma_2}e^{iz^2}dz+\int_{\Gamma_3}e^{iz^2}dz=0
$$
For our second integral above, we show that it vanishes as $R\rightarrow\infty$ using the ML test given by
$$
\left|\int_\Gamma f(z)dz\right|\leq ML
$$
where $M$ is a finite upper bound of $f(z)$ and $L$ is the length of the contour $\Gamma$.  Of course, we need to assume that $f(z)$ is bounded and analytic on $\Gamma$ for this.
In order to apply the ML test, we substitute into our integrand $z=re^{i\theta}$ so that
$$
z^2 = r^2e^{2i\theta} = r^2\cos(2\theta)+ir^2\sin(2\theta)
$$
$$
|e^{iz^2}|=|e^{ir^2\cos(2\theta)-r^2\sin(2\theta)}|\leq e^{-R^2}=M
$$
because $r=R$ on this contour and $\sin(2\theta)\leq1$.  While,
$$
L=\frac{\pi R}{4}
$$
since we are looking at $1/8$th of the perimeter of the circle with radius $R$.  By the ML test
$$
\left|\int_{\Gamma_2} e^{iz^2}dz\right| \leq e^{-R^2}\frac{\pi R}{4}
$$
which goes to $0$ as $R\rightarrow\infty$.
Now we want to deal with the 3rd contour integral $\Gamma_3$.  Fortunately, the contour we picked allows us to easily parameterize this integral, as $y=x$.  We will also need $z^2=(x+iy)^2=x^2-y^2+2ixy$.  Recalling that $dz=dx+idy$ the integral becomes
$$
\int_{\Gamma_3} e^{i(x^2-y^2)-2xy}(dx+idy)
=\int_{R}^{0} e^{-2x^2}dx+i\int_{R}^{0} e^{-2y^2}dy
\rightarrow-\sqrt{\frac{\pi}{8}}(1+i)\ \text{as}\ R\rightarrow0
$$
from our real Gaussian integral identities.
Taking $R\rightarrow\infty$, our results for the contour integrals in our Cauchy's Theorem equation imply that
$$
\int_0^\infty e^{ix^2}dx = \sqrt{\frac{\pi}{8}}(1+i)
$$
The integral from $-\infty$ to $\infty$ is just twice this.  So boom.
If you want, you can rewrite $e^{ix^2}=\cos(x^2)+i\sin(x^2)$ and equate the real and imaginary parts in the last equation and you will get the limiting values of the Fresnel Integrals.
Boom.
Also, since
$$
(1+i)=\sqrt{2}e^{i\pi/4}=\sqrt{2e^{i\pi/2}}=\sqrt{2i}
$$
we have
$$
\int_0^\infty e^{ix^2}dx = \sqrt{\frac{i\pi}{4}} = \frac{1}{2}\sqrt{-\frac{\pi}{i}}
$$
which exactly matches the well-known Gaussian integral identity
$$
\int_0^\infty e^{-\alpha x^2}dx = \frac{1}{2}\sqrt{\frac{\pi}{\alpha}}
$$
with $\alpha=-i$.  Boom.  Thus, this suggests that this identity can work for imaginary $\alpha$, and possibly certain complex $\alpha$ with the right combination of real and imaginary parts as well as choice of contours that do not make our integrals blow up.
Comment: The ML argument is wrong. You can only say $\sin(2\theta) \ge 0 \implies M \le e^0 = 1$. Funnily enough, the same mistake was in the textbook I am using which is why I came to look for correct solution on MSE. I think I came up with a workaround though. First make a substitution $x^2\ = t$. Then you will have $\sqrt{t}$ in the denominator and you can show that the integral on the arch tends to zero. Then you come back to original coordinates.
Comment: @RodionZaytsev is correct, the ML argument is wrong. We should use $sin(\theta)\geq \frac{2\theta}{\pi}$ for $\theta\in[0,\frac{\pi}{2}]$ and obtain $R\int_0^{\pi/2} e^{-R^2\theta}d\theta$ which goes to zero for $R\to\infty$.
Comment: Hi, to avoid the technicalities in those case, then say (using integration by parts) that $\int_0^\infty e^{-i x^2}dx = \lim_{\epsilon \to 0^+}\int_0^\infty e^{-(i+\epsilon) x^2}dx$, and $\int_{-\infty}^\infty e^{-a x^2}dx = a^{-1/2} \int_{-\infty}^\infty e^{- x^2}dx$ for $a > 0$ and for $\Re(a) > 0$ by analytic continuation.
Comment: Boom, Boom,  Boom. Strongly attacked that integral.
Comment: Nice results $\int_{-\infty}^\infty e^{ix^2}dx = \sqrt{\pi i}$.
Answer: This answer is dedicated to give an alternative proof of
$$
\lim_{R\to+\infty}\int_\Gamma e^{iz^2}\mathrm dz=0
$$
where $\Gamma$ denotes a circular arc connecting $R$ and $e^{i\pi/4}R$. Using the parametrization that $z=Re^{i\theta}$, we have
\begin{aligned}
\left|\int_\Gamma e^{iz^2}\mathrm dz\right|
&\le R\int_0^{\pi/4}e^{-R^2\sin(2\theta)}\mathrm d\theta \\
&=R\left(\int_0^\delta+\int_\delta^{\pi/4}\right)e^{-R^2\sin(2\theta)}\mathrm d\theta \\
&<R\delta+{R\pi\over4}e^{-R^2\sin(2\delta)}
\end{aligned}
Since $\sin u\sim u$ when $u\to0$, we see that for small $\delta>0$ there is $\sin(2\delta)>\delta$, which means when $\delta=R^{-3/2}$ and $R$ is large there is
$$
\left|\int_\Gamma e^{iz^2}\mathrm dz\right|<{1\over\sqrt R}+{\pi R\over2}e^{-\sqrt R}=O\left(1\over\sqrt R\right)
$$
Answer: Here is another solution with a different contour.
Let $$I=\int^{\infty}_{-\infty}e^{ix^2}\text{ d}x$$ and let $$f(z)=e^{iz^2}$$ Note that our function is even.
In user279043's answer, the contour they chose was (what I would presume) based on the fact that the complex integrand can be rewritten like this $$\exp\left(z^2e^{\frac{i\pi}2}\right)=\exp\left(\left(ze^{\frac{i\pi}4}\right)^2\right)$$ which implies that the integrand is well behaved along the ray $e^{\frac{i\pi}4}$.
However, we can also note that along the imaginary axis, our function is similarly well behaved. Consider the following contour shown below

consisting of the paths $$\mathcal{C}=B+\Gamma+L$$
Thus, our contour integral about said contour would be $$\oint_{\mathcal{C}}f(z)\text{ d}z=\int_B+\int_{\Gamma}+\int_Lf(z)\text{ d}z=0$$
Each path can be parameterized as follows
\begin{alignat*}{5}
    B&:\text{ }z=x,\qquad &\text{d}z&=\text{d}x,\qquad &x&\in[0, R\,]\\
    \Gamma &:\text{ }z=Re^{i\theta},\qquad &\text{d}z&=iRe^{i\theta}\text{ d}\theta,\qquad &\theta&\in\left[0, \frac{\pi}{2}\right]\\
    L&:\text{ }z=iy,\qquad &\text{d}z&=i\text{d}y,\qquad &y&\in[\,R, 0]
\end{alignat*}
Now let's evaluate each integral. The integral about $B$ is just half of $I$
$$\lim_{R\to+\infty}\int_Bf(z)\text{ d}z=\lim_{R\to+\infty}\int^{R}_0e^{ix^2}\text{ d}x=\frac{1}{2}I$$
The integral about $\Gamma$ vanishes along our integration interval using typical inequalities. Note that I put in red whatever goes to $1$.
\begin{align}
    \left|\int_{\Gamma}f(z)\text{ d}z\right|&\le\int^{\frac{\pi}2}_{0}\left|e^{iR^2e^{2i\theta}}\right|\cdot\color{red}{|i|}|R|\color{red}{\left|e^{i\theta}\right|}\text{ d}\theta\\
    &\le\int^{\frac{\pi}2}_{0}R\color{red}{\left|e^{iR^2\cos(2\theta)}\right|} \left|e^{-R^2\sin(2\theta)}\right| \text{ d}\theta\\
    &\le\int^{\frac{\pi}4}_{0}R e^{-R^2\cdot \frac{4\theta}{\pi}} \text{ d}\theta+\int^{\frac{\pi}2}_{\frac{\pi}4}R e^{R^2\cdot \frac{4\left(\theta-\frac{\pi}{2}\right)}{\pi}} \text{ d}\theta
\end{align}
Which goes to $0$ when we take the limit as $R$ goes to infinity. The third line comes from Jordan's inequality.
Lastly, the integral along $L$ gives
$$\lim_{R\to+\infty}\int_Lf(z)\text{ d}z=\lim_{R\to+\infty}\int^{0}_{R}e^{i(iy)^2}\cdot i\text{ d}y=-i\int^{\infty}_0e^{-iy^2}\text{ d}y$$
So we have
$$\oint_{\mathcal{C}}f(z)\text{ d}z=\int_B+\int_{\Gamma}+\int_Lf(z)\text{ d}z=\frac12 I-i\int^{\infty}_0e^{-iy^2}\text{ d}y=0$$
Lastly, we can rearrange our equation and solve as follows
\begin{align}
    \frac12 I&=i\int^{\infty}_0e^{-iy^2}\text{ d}y\\
    \implies\left(\frac{I}{2i}\right)^2&=\int^{\infty}_0e^{-iy^2}\text{ d}y\cdot\int^{\infty}_0e^{-it^2}\text{ d}t\\
    &=\int^{\infty}_0\int^{\infty}_0e^{-i(y^2+t^2)}\text{ d}y\text{ d}t\\
    &=\int^{\frac{\pi}2}_0\int_0^{\infty}e^{-ir^2}\cdot r\text{ d}r\text{ d}\theta=\frac{\pi}{2}\int_0^{\infty}re^{-ir^2}\text{ d}r\\
    &=\frac{\pi}{4i}\int^{\infty}_0e^{-u}\text{ d}u=\frac{\pi}{4i}\cdot 1\\
    \implies \frac{I}{2i}&=\sqrt{\frac{\pi}{4i}}\\
    \implies I&=2i\cdot\frac{\sqrt{\pi}}{2}\cdot e^{-\frac{i\pi}{4}}=\sqrt{\pi}e^{\frac{i\pi}4}=(1+i)\sqrt{\frac{\pi}{2}}
\end{align}
we can see that line 4 follows from the polar coordinate change of variables
$$y=r\cos(\theta),\,\,t=r\sin(\theta),\qquad J_f=\left[\begin{array}{cc}
     \cos(\theta)& -r\sin(\theta) \\
     \sin(\theta)& r\cos(\theta)
\end{array}\right],\qquad \left|\det\left(J_f\right)\right|=r$$
and line 5 follows from this simple u-sub
$$u= ir^2,\qquad\frac{\text{d}u}{\text{d}r}=2ir,\qquad\text{d}r=\frac{\text{d}u}{2ir}$$
Hence $$I=\boxed{(1+i)\sqrt{\frac{\pi}{2}}}$$
Comment: The 3rd $\le$ process in your estimation of $\int_\Gamma$ is incorrect.
Comment: @TravorLZH where is it incorrect
Comment: The part where you state $e^{-R^2\sin(2\theta)}\le e^{-R^2}$ is incorrect
Comment: Moreover, the u-sub you performed in line 5 actually converts the $\int_0^\infty$ to $\int_0^{+i\infty}$, so that part has issues too
Comment: I guess you could bound gamma by a constant. As for the last u sub I dont think that should be a problem, complex infinity can be reached by taking the real number line to infinity. What's with the downvote?
Comment: If you only bound $\int_\Gamma$ by a constant, then your Cauchy's theorem argument will not allow you to calculate the integral. For your second statement, the integral $\int_0^{+i\infty}e^{-u}\mathrm du$ does not converge.
Comment: Well then use the ML argument I suppose instead of the constant. How would the second integral diverge? Again you can reach complex infinity through the real number line, it would give the same answer.
Comment: The second integral diverges because for any $a>0$ you can always pick some $b>a$ such that $\left|\int_{ia}^{ib}e^{-u}\mathrm du\right|>0$, which violates Cauchy's criterion.
Comment: What ML argument do you have, the one stated in the other answer is erroneous too
Comment: Actually you don't even need ML. instead of bounding it with 1 use the Jordan's inequality to bound sin(2x) by 2x/pi, this will suffice to show it goes to 0.

As for the integral, again we are choosing a particular path we take to go from 0 to complex infinity. We can choose the real axis.
Comment: You cannot bound $\sin2\theta$ with 1 in that situation because $\sin2\theta\le1$, and the issue in your second integral is not gone even if you deform the path of integration.
Comment: What? Reread what I said lol. I boudned it with 2x/pi, not 1. And no, if we choose the real axis the integral converges.
Comment: but how would you justify that you can "choose the real axis"?
Comment: We are taking a path from 0 to complex infinity. Within our bounds, we can choose any ray from 0 in the positive quadrant to go to complex infinity, to which we can decide to go from the real axis. You could also justify this by using DCT to take the left handed limit of the regular gaussian formula of $\sqrt{\frac{\pi}{a}}$ and show that it exists and we can plug in $i$ for a.
Comment: It is common that wrong argument produces correct results (e.g. $\zeta(-1)=-1/12$ by re-arranging the terms in $1+2+3+4+\dots$). Looking closely to your second integral, I see that you missed a few steps to make it rigorous. Set $$I_1(T)=\int_0^{iT}e^{-u}\mathrm du,$$ $$I_2(T)\int_0^T e^{-u}\mathrm du,$$ and $I_3(T)$ denotes the integral of $e^{-u}$ over $u=Te^{i\phi},0\le\phi\le\pi/2$. Then Cauchy's theorem gives $I_2(T)=I_1(T)+I_3(T)$, and setting $T\to+\infty$ gives $I_3(+\infty)=0$ (via Jordan's inequality), hence $I_1(+\infty)=I_2(+\infty)=1$.
Comment: Ah I see. Thank you for the correction! :)
Comment: I will remove the downvote if you replace your estimation $\int_\Gamma$ using Jordan's inequality since $1\ge e^{-R^2\sin(2\theta)}\ge e^{-R^2}$.
Comment: @TravorLZH done. Honestly you're answer for the argument is quite a lot more rigorous so I guess we could just stick with that lol.
Answer: Another method.
$$\int_{-\infty}^\infty\exp(ix^2)\mathrm dx=2\int_0^{\infty} \exp(ix^2)\mathrm dx\tag{1}$$
Let $-z=ix^2\implies x=(iz)^{1/2}\implies \mathrm dx=\frac{i^{1/2}}{2}z^{-1/2}\mathrm dz$ hence
$$\int_0^{\infty} \exp(ix^2)\mathrm dx=\frac{i^{1/2}}{2}\int_0^{-i\infty}z^{-1/2}\exp(-z)\mathrm dz\tag{2}$$
This is almost the Gamma function, but the limits of integration are wrong. We need to somehow argue that we can switch the $\int_0^{-i\infty}$ to $\int_0^\infty$. We consider the following contour in the complex plane:

We call this closed contour $C(r,R)$, a union of the four curves $C_1,C_2,C_3,C_4~(r,R)$. Explicitly,
$$C_1(r,R)=\{t\mid t\in[R,r]\} \\ C_2(r)=\{re^{it}\mid t\in[0,-\pi/2]\} \\ C_3(r,R)=\{-it\mid t\in[r,R]\} \\ C_4(R)=\{Re^{it}\mid t\in[3\pi/2,2\pi]\} \\ C(r,R)=C_1(r,R)\cup C_2(r)\cup C_3(r,R)\cup C_4(R)$$
Because we have an integrand that is analytic everywhere in the interior and on the boundary of $C(r,R)$, we know that
$$\oint\limits_{C(r,R)}z^{-1/2}\exp(-z)\mathrm dz=0$$
Obviously, what we'd like to show is that the integrals on $C_2$ and $C_4$ go to $0$ as $r\to 0,R\to\infty$. Let's have a look at $C_2$ first. Being that the integration goes in the counter-clockwise direction, we actually traverse $C_2$ in the clockwise direction and so we can parameterize the integration along $C_2$ as
$$\int\limits_{C_2(r)}z^{-1/2}\exp(-z)\mathrm dz=\int_{0}^{-\pi/2}(re^{it})^{-1/2}\exp(-re^{it})ire^{it}\mathrm dt$$
Simplifying things a little,
$$\int\limits_{C_2(r)}z^{-1/2}\exp(-z)\mathrm dz=-ir^{1/2}\int_{0}^{\pi/2}e^{it/2}\exp(-re^{-it})\mathrm dt$$
As $r\to 0$ we use a Taylor expansion on the $\exp$:
$$\exp(-re^{-it})=1-re^{-it}+\mathrm O(r^2)$$
So
$$\int\limits_{C_2(r)}z^{-1/2}\exp(-z)\mathrm dz=-ir^{1/2}\int_{0}^{\pi/2}e^{it/2}\exp(-re^{-it})\mathrm dt \\ =-ir^{1/2}\int_0^{\pi/2}e^{it/2}\mathrm dt+ir^{1/2}\int_0^{\pi/2}e^{it/2}re^{it}\mathrm dt +\mathrm O(r^2)\\ =ir^{1/2}\cdot(\text{integral not depending on}~r)+ir^{3/2}\cdot(\text{integral not depending on}~r)+\mathrm O(r^2) \\ =\mathrm O(r^{1/2})\to 0~\text{as}~r\to 0.$$
Now we look at $C_4$. This path is indeed counter-clockwise so we parameterize as such:
$$\int\limits_{C_4(R)}z^{-1/2}\exp(-z)\mathrm dz=\int_{3\pi/2}^{2\pi}(Re^{it})^{-1/2}\exp(-Re^{it})iRe^{it}\mathrm dt \\ =iR^{1/2}\int_{3\pi/2}^{2\pi}e^{it/2}\exp(-Re^{it})\mathrm dt$$
Expanding with Euler's formula,
$$\int\limits_{C_4(R)}z^{-1/2}\exp(-z)\mathrm dz=iR^{1/2}\int_{3\pi/2}^{2\pi} e^{it/2}\exp(-R\cos t-iR\sin t)\mathrm dt \\ =iR^{1/2}\int_{3\pi/2}^{2\pi} e^{it/2}\exp(-R\cos t)\exp(-iR\sin t)\mathrm dt $$
We know that $|\exp(-iR\sin t)|=|e^{it/2}|=1$ and so via the estimation lemma we know that
$$\left|\int_{C_4(R)}z^{-1/2}\exp(-z)\mathrm dz\right|= R^{1/2}\left|\int_{3\pi/2}^{2\pi} e^{it/2}\exp(-R\cos t)\exp(-iR\sin t)\mathrm dt\right| \\ \leq R^{1/2}\left|\int_{3\pi/2}^{2\pi}\exp(-R\cos t)\mathrm dt\right|\tag{3}$$
Past this point, the simple bound from the estimation lemma is actually not enough here, as it would only give us
$$\left|\int_{C_4(R)}z^{-1/2}\exp(-z)\mathrm dz\right|\leq \frac{\pi}{2}R^{1/2}$$
Which still goes to $\infty$ as $R\to \infty$. So we need to find a better way to bound the integral $\int_{3\pi/2}^{2\pi}\exp(-R\cos t)\mathrm dt$.
Due to periodicity,
$$\int_{3\pi/2}^{2\pi}\exp(-R\cos t)\mathrm dt=\int_{-\pi/2}^{0}\exp(-R\cos t)\mathrm dt$$
And then the evenness of the integrand,
$$\int_{-\pi/2}^{0}\exp(-R\cos t)\mathrm dt=\int_0^{\pi/2}\exp(-R\cos t)\mathrm dt$$
Here we will need to consult some mathematical literature. It turns out that
$$\int_0^{\pi/2}\exp(-R\cos t)\mathrm dt=-\frac{\pi}{2}M_0(R)$$
Where $M_0$ is a zeroth-order Modified Struve function. It has the asymptotic expansion
$$M_0(z)\asymp\frac{-1}{2\pi z}+\mathrm O(|z|^{-2})  \\ \text{as}~|z|\to\infty\\ (\operatorname{Re}z>0)$$
Which means, going back to $(3)$,
$$\left|\int_{C_4(R)}z^{-1/2}\exp(-z)\mathrm dz\right|\leq R^{1/2}\frac{\pi}{2}M_0(R)\asymp \frac{1}{4R^{1/2}}$$
Which allows us to conclude
$$\left|\int_{C_4(R)}z^{-1/2}\exp(-z)\mathrm dz\right|\to 0 \\ \text{as}~R\to\infty$$
Therefore,
$$0=\oint_{C(r,R)}z^{-1/2}\exp(-z)\mathrm dz =\left(\int\limits_{C_1(r,R)}+\int\limits_{C_2(r)}+\int\limits_{C_3(r,R)}+\int\limits_{C_4(R)}\right)z^{-1/2}\exp(-z)\mathrm dz \\ \to \left(\int\limits_{C_1(r,R)}+\int\limits_{C_3(r,R)}\right)z^{-1/2}\exp(-z)\mathrm dz~~\text{as}~r\to 0~,~R\to\infty$$
This finally allows us to conclude
$$\int_0^{-i\infty}z^{-1/2}\exp(-z)\mathrm dz=-\int_\infty^0 z^{-1/2}\exp(-z)\mathrm dz \\ =\int_0^\infty z^{1/2-1}\exp(-z)\mathrm dz \\ =\Gamma(1/2)=\sqrt{\pi}$$
Going all the way back to the beginning, this means
$$\int_{-\infty}^\infty\exp(ix^2)\mathrm dx=i^{1/2}\sqrt{\pi}=\sqrt{\frac{\pi}{2}}+i\sqrt{\frac{\pi}{2}}$$
Which instantly gives us the famous Fresnel Integrals:
$$\boxed{\int_{-\infty}^\infty \cos(x^2)\mathrm dx=\int_{-\infty}^\infty \sin(x^2)\mathrm dx=\sqrt{\frac{\pi}{2}}}$$

While lengthier than the other responses, this answer is, in my opinion, far more direct than the others and I think is an accurate reflection of the calculations one would have to go through if one had not seen the problem beforehand. It's my first full attempt at solving this problem, anyhow.
Comment: I don't know, but I dont think this method is "far more direct". The answer here https://math.stackexchange.com/a/2482385/1097360 if we were to compare is "much more direct". There is no need to convert the function and contour to something unnecessarily complicated, especially when solving them involve special functions. The observation that https://math.stackexchange.com/a/4534130/1097360 made in regards to the function's behavior along the 45 degree ray is a perfectly reasonable reflection on first sight.

Integral of $e^{ix^2}$


What is "formal semantics"?

Question: I'm reading a very silly paper and it keeps on talking about how Giotto defines a "formal semantics".

Giotto has a formal semantics that specifies the meaning of mode switches, of intertask communication, and of communication with the program environment.

I'm on the edge of, but just cannot quite grasp what it means by "formal semantics."
Comment: It's when the semantics are diagrammed wearing tuxedos.
Comment: Wikipedia says: "The Giotto programming language for real-time embedded systems".  And does not say anything more.
Answer: To expand on Michael Madsen's answer a little, an example might be the behaviour of the ++ operator. Informally, we describe the operator using plain English. For instance:

If x is a variable of type int, ++x causes x to be incremented by one.

(I'm assuming no integer overflows, and that ++x doesn't return anything)
In a formal semantics (and I'm going to use operational semantics), we'd have a bit of work to do. Firstly, we need to define a notion of types. In this case, I'm going to assume that all variables are of type int. In this simple language, the current state of the program can be described by a store, which is a mapping from variables to values. For instance, at some point in the program, x might be equal to 42, while y is equal to -5351. The store can be used as a function -- so, for instance, if the store s has the variable x with the value 42, then s(x) = 42.
Also included in the current state of the program is the remaining statements of the program we have to execute. We can bundle this up as <C, s>, where C is the remaining program, and s is the store.
So, if we have the state <++x, {x -> 42, y -> -5351}>, this is informally a state where the only remaining command to execute is ++x, the variable x has value 42, and the variable y has value -5351.
We can then define transitions from one state of the program to another -- we describe what happens when we take the next step in the program. So, for ++, we could define the following semantics:
<++x, s> --> <skip, s{x -> (s(x) + 1)>

Somewhat informally, by executing ++x, the next command is skip, which has no effect, and the variables in the store are unchanged, except for x, which now has the value that it originally had plus one. There's still some work to be done, such as defining the notation I used for updating the store (which I've not done to stop this answer getting even longer!). So, a specific instance of the general rule might be:
<++x, {x -> 42, y -> -5351}> --> <skip, {x -> 43, y -> -5351}>

Hopefully that gives you the idea. Note that this is just one example of formal semantics -- along with operational semantics, there's axiomatic semantics (which often uses Hoare logic) and denotational semantics, and probably plenty more that I'm not familiar with.
As I mentioned in a comment to another answer, an advantage of formal semantics is that you can use them to prove certain properties of your program, for instance that it terminates. As well as showing your program doesn't exhibit bad behaviour (such as non-termination), you can also prove that your program behaves as required by proving your program matches a given specification. Having said that, I've never found the idea of specifying and verifying a program all that convincing, since I've found the specification usually just being the program rewritten in logic, and so the specification is just as likely to be buggy.
Comment: your last argument about verification and specification is spot on. With formal proof and specifications written in logic, we're just shifting the responsibility from writing bug-free code to writing bug free high level logic languages specs. Guess which one is easier? That being said, there is a need for formal verification, but I think the most we could ever hope to comprehend on an industrial level is using SAT solvers and generating specifications are propositional logic statements.
Comment: Initially I read _In a formal semantics (and I'm going to use operational semantics)_, which makes me think that _operational semantics_ are a subset of _formal semantics_; is this the case?
Answer: Formal semantics describe semantics in - well, a formal way - using notation which expresses the meaning of things in an unambiguous way.
It is the opposite of informal semantics, which is essentially just describing everything in plain English. This may be easier to read and understand, but it creates the potential for misinterpretation, which could lead to bugs because someone didn't read a paragraph the way you intended them to read it.
A programming language can have both formal and informal semantics - the informal semantics would then serve as a "plain-text" explanation of the formal semantics, and the formal semantics would be the place to look if you're not sure what the informal explanation really means.
Comment: @bobobobo: Actually, I believe both are informal. Formal semantics is associated with mathematical notation, and I don't think either of them use that. While ANSI C might use more formal language than K&R, that doesn't make the semantics formal. (However, since I haven't read either, I can't say for sure.)
Comment: The other advantage of formal semantics is that you can use them to prove certain properties of your program, for instance that it terminates. As well as showing your program doesn't exhibit bad behaviour (such as non-termination), you can also prove that your program behaves as required by proving your program matches a given specification. Having said that, I've never found the idea of specifying and verifying a program all that convincing, since I've found the specification usually just being the program rewritten in logic, and so the specification is just as likely to be buggy.
Comment: So, would a "formal semantics" for C be "The ANSI C specification", and an "informal semantics" for C be "K&R"?
Answer: Just like the syntax of a language can be described by a formal grammar (e.g. BNF), it's possible to use different kinds of formalisms to map that syntax to mathematical objects (i.e. the meaning of the syntax).
This page from A Practical Introduction to Denotational Semantics is a nice introduction to how [denotational] semantics relates to syntax.  The beginning of the book also gives a brief history of other, non-denotational approaches to formal semantics (although the wikipedia link Michael gave goes into even more detail, and is probably more up-to-date).
From the author's site:

Models for semantics have not
  caught-on to the same extent that BNF
  and its descendants have in syntax.
  This may be because semantics does
  seem to be just plain harder than
  syntax. The most successful system is
  denotational semantics which describes
  all the features found in imperative
  programming languages and has a sound
  mathematical basis. (There is still
  active research in type systems and
  parallel programming.) Many
  denotational definitions can be
  executed as interpreters or translated
  into "compilers" but this has not yet
  led to generators of efficient
  compilers which may be another reason
  that denotational semantics is less
  popular than BNF.
Answer: What is meant in the context of a programming language like Giotto is, that a language with formal semantics, has a mathematically rigorous interpretation of its individual language constructs.
Most programming languages today are not rigorously defined. They may adhere to standard documents that are fairly detailed, but it's ultimately the compiler's responsibility to emit code that somehow adheres to those standard documents.
A formally specified language on the other hand is normally used when it is necessary to do reasoning about program code using, e.g., model checking or theorem proving. Languages that lend themselves to these techniques tend to be functional ones, such as ML or Haskell, since these are defined using mathematical functions and transformations between them; that is, the foundations of mathematics.
C or C++ on the other hand are informally defined by technical descriptions, although there exist academic papers which formalise aspects of these languages (e.g., Michael Norrish: A formal semantics for C++, https://publications.csiro.au/rpr/pub?pid=nicta:1203), but that often do not find their way into the official standards (possibly due to a lack of practicality, esp. difficulty to maintain).

What is "formal semantics"?


Mail subject and body remain empty using mailManager

Question: I have been fiddling with sending a mail in my custom module in Drupal 8.
The mail gets sent but the subject and body are empty.
It has been an issue for days and I can't get it to work. The code and var_dump are below. I just can't find the issue. Maybe someone can!
Code in hook_mail:
<?php
/**
 * Implements hook_mail().
 */
function document_mail($key, $message, $params)
{
    $options = array(
        'langcode' => $message['langcode'],
    );
    switch ($key) {
       case 'send_file':
            $message['from'] = \Drupal::config('system.site')->get('mail');
            $message['subject'] = t('@title', array('@title' => $params['mail_title']), $options);
            $message['body'][] = $params['message'];
        break;
    }
}

Code to send mail:
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'document';
    $key = 'send_file';
    $to = 'email@example.com';
    $params['mail_title'] = 'a title';
    $params['message'] = 'a message';
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $send = true;
    $result = $mailManager->mail($module, $key, $to, $langcode, $params, null, $send);
    var_dump($result);
    if ($result['result'] !== true) {
        drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
    } else {
        drupal_set_message(t('Your message has been sent.'));
    }

var_dump of result from $result of mailManager
array(12) {
["id"]=> string(18) "document_send_file"
["module"]=> string(8) "document"
["key"]=> string(9) "send_file"
["to"]=> string(24) "email@example.com,"
["from"]=> string(22) "firstname.lastname@example.com"
["reply-to"]=> NULL
["langcode"]=> string(2) "en"
["params"]=> array(2)
{
    ["mail_title"]=> string(7) "a title"
    ["message"]=> string(9) "a message"
}
["send"]=> bool(true)
["subject"]=> object(Drupal\Core\StringTranslation\TranslatableMarkup)#410 (5)
{
    ["string":protected]=> string(6) "@title"
        ["translatedMarkup":protected]=> NULL
        ["options":protected]=> array(1)
        {
                ["langcode"]=> string(2) "en"
        }
        ["stringTranslation":protected]=> NULL
        ["arguments":protected]=> array(1)
        {
            ["@title"]=> string(7) "a title"
        }
    }
    ["body"]=> array(1)
    {
        [0]=> string(9) "a message"
    }
    ["headers"]=> array(7)
    {
        ["MIME-Version"]=> string(3) "1.0"
        ["Content-Type"]=> string(51) "text/plain; charset=UTF-8; format=flowed; delsp=yes"
        ["Content-Transfer-Encoding"]=> string(4) "8Bit"
        ["X-Mailer"]=> string(6) "Drupal"
        ["Return-Path"]=> string(22) "email@example.com"
        ["Sender"]=> string(22) "firstname.lastname@example.com"
        ["From"]=> string(44) "a string"
    }
    ["result"]=> bool(true)
}

Comment: @NoSssweat thank you for your comment! I have tried it and sadly the issue remains the same.
Comment: Code is working fine. Please check disabling modules one by one. Other module might be causing the issue.
Answer: I believe you forgot to pass $message by reference (&), so please double check the implementation of your hook_mail as per details below:

hook_mail($key, &$message, $params)

Otherwise, any changes to $message won't take any effect.
Comment: Wow! That worked! just 1 character difference... Thanks a lot!
Answer: Remove the empty array tag from body as below.
$message['body'] = $params['message'];

Comment: Hello! Thank you for your answer. I have tried it and sadly the issue remains. The empty array tag is actually necessary. At least according the hook_mail docs from Drupal. [link](https://api.drupal.org/api/drupal/core%21core.api.php/function/hook_mail/8.3.x)


Is there Page bulk manager?

Question: I tried to look for bulk page manager for Drupal 7, but I wasn't successful. More specifically, I'd like to change access settings for multiple pages in one step. Something similar to what VBO provides for entities.
Any suggestions?
Answer: Content Access VBO
Maybe you want to look at Content Access VBO ... It's (still) a sandbox project, so not sure if you really want to consider it. Here are some details about it (quote from that link):

... creates an action for Views Bulk Operations to update per node content access (view/edit/delete etc). It adds a menu item to the Content menu tree and adds a new view which lists content with the VBO action as a button.

But at least it may help to get more inspiration to build your custom module to get this done.
Combine Rules with Views Bulk Operations or Content Access
Another approach is to use the Rules module, combined with modules Views Bulk Operations and/or Content Access. Here are a few questions that may help to get more inspiration about its possibilities (the sky is the limit ...):

Is there a module that lets one person do a bulk publish/update?
https://drupal.stackexchange.com/questions/159988/how-to-implement-a-complex-workflow-in-a-website-with-subsites-and-using-opensch/161616?s=8|0.2610#161616
How can an author mark the update date of a node to be visible or hidden for visitors?
Is there a module that lets one person do a bulk publish/update?
How do I publish nodes 3 times a day?.
Comment: Thanks, but all these solutions seems to be related to entities, not Ctools Pages. I'll look into the CA VBO module, but it seems to be using very different concepts.

Is there Page bulk manager?


Gerar relatório IReport / Jasper Report contendo 2 páginas (com 3 colunas cada) em uma mesma folha em modo paisagem

Question: estou fazendo um relatório para um cliente e não estou conseguindo montá-lo de acordo com a sua necessidade. O que ele precisa é gerar um PDF de folha A4 no modo paisagem, contendo cada folha duas páginas (ímpar e par), e cada página com 3 colunas.
Já pesquisei em vários fóruns (tanto aqui no GUJ quanto em outros) mas em nenhum consegui encontrar algo para me ajudar com esta resolução, e já estou atrasado com a entrega deste software, onde só falta este relatório dos produtos.
Para exemplificar melhor, estou enviando neste post a imagem do resultado que preciso.
Por favor pessoal, alguém conhece e/ou já precisou gerar um relatório de duas páginas em 1 mesma folha? As 3 colunas eu consigo gerar, porém somente em 1 página.
Se tiverem alguma idéia, ou também até sugestão de outra maneira para gerar, serão muito bem vindas, pois minhas possibilidades estão muito próximas de esgotadas, por isso preciso e muito da ajuda de vocês.
Estou usando IReport versão 5.6.0
Obrigado!
Comment: *Para exemplificar melhor, estou enviando neste post a imagem do resultado que preciso.* - Cadê a imagem?
Comment: Eu tinha enviado mas a imagem nao subiu. Agora sim segue ela no post.
Comment: Qual a diferença entre o seu problema e um relatório com uma página de 6 colunas? Uma outra possibilidade (um tanto capenga =/ ) seria apenas orientar seu cliente a usar o software da impressora para imprimir duas páginas por folha...
Comment: Alguma resposta lhe foi útil? Poderia escolher alguma e marcá-la como aceita?
Comment: Eu acho que o conceito do jasper raport está sendo misturado. Você está querendo dizer que quer o detail repetindo 2x no corpo da folha por pagina ? Se for isso, creio que a solução proposta pelo @Nigini seja a mais adequada
Answer: Achei essa thread discutindo mais ou menos o mesmo problema que o seu. O curioso é que a resposta do Staff da Jasper foi na linha do meu comentário na sua pergunta. =]
Vou copiar o código que foi postado lá com alguns poucos comentários meus. Não testei aqui, mas parece fazer sentido no universo que conheço do JasperReports:
//Começa configurando o relatório normalmente!
JasperDesign jd = JRXmlLoader.load(ResourceUtils.getFile(getFileResourcesJRXML("myjasper_A5.jrxml")));
JasperReport jrRH02 = JasperCompileManager.compileReport(jd);
jp = JasperFillManager.fillReport(jrRH02, data, dataSource);

getResponse().setContentType("application/pdf");
ServletOutputStream outputStream = getResponse().getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jp);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();

//Não entendi porquê ele fez isso...
exporter.reset();
exporter = null;
System.gc();

//Aqui é onde a hackeada começa:
Document document = new Document();
//Define as dimensões da página no braço
document.setPageSize(new Rectangle(jp.getPageWidth(), jp.getPageHeight() * 2)); // This is because A4 Size == 2 * A5
//lê os dados do relatório originalmente produzido (páginas separadas)
PdfReader pdfReader = new PdfReader(baos.toByteArray());
//cria um novo escritor de PDF usando a configuração acima
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
//Faz um loop que lê as páginas do relatório inicial
// e coloca no relatório novo
//Estranhamente ele deixou a definição do loop incompleto,
// não deve ser difícil completar...
for(int i = 1; i ...){
    document.newPage();
    PdfImportedPage page = writer.getImportedPage(pdfReader, i);
    cb.addTemplate(page, 0, 0);
    cb.addTemplate(page, 0, jp.getPageHeight());
}
outputStream.flush();
document.close();

Answer: Neste caso eu faria o seguinte:
Na paisagem A4 colocaria 2 SubReports com 400 pixels cada devidamente configurado as sobras do tamanho, e no meio vi que tem uma linha vertical, pois bem, adicione uma linha vertical.
Configurar os SubReports tanto no Ireport/JasperStudio e em código, dividindo minha exibições em duas lista(Uma para cada SubReport) para não haver redundância.


Angularjs / HTML Show and Hide li elements onClick

Question: I am having a problem with the appearance of the "Categories" and their subordinate lists.
The lists should not be displayed when loading the page. So only be visible by a click of the user. Unfortunately, these list items disappear immediately as soon as a checkbox is selected. That should not happen. The content under "Categories" should only disappear or be made visible when the word Categories is clicked.
What changes do I have to make to make this work as I imagine?
Here's the HTML of the container it's about:

Kategorien

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Rind" data-ng-false-value="">
             Rind

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Geflügel" data-ng-false-value="">
            Geflügel

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Schwein" data-ng-false-value="">
            Schwein

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Schaf" data-ng-false-value="">
            Schaf

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Wild" data-ng-false-value="">
            Wild

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Ziege" data-ng-false-value="">
            Ziege

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Pferd" data-ng-false-value="">
            Pferd

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Alpaka" data-ng-false-value="">
            Alpaka

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Fisch" data-ng-false-value="">
            Fisch

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Kaninchen" data-ng-false-value="">
            Kaninchen

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Mineral" data-ng-false-value="">
            Mineralfutter

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Einzel" data-ng-false-value="">
            Einzelfutter

            <input class="filter" type="checkbox" ng-model="search.definition" ng-true-value="Spezial" data-ng-false-value="">
            Spezialfutter

 Filter zurücksetzen

And here are the excerpts from the script file:
app.controller('PageCtrl', ['$scope', 'filterFilter', '$http', function ($scope, filterFilter, $http) {
$scope.items =[];

$http.get("document.json").success(function(response){
    $scope.items = response;  //ajax request to fetch data into $scope.data
// pagination controls
    $scope.currentPage = 1;
    $scope.totalItems = $scope.items.length;
    $scope.entryLimit = 200; // items per page
    $scope.noOfPages = Math.ceil($scope.totalItems / $scope.entryLimit);
    $scope.orderByField = 'evaluation_result';
    $scope.reverseSort = true;
    $scope.IsVisibleCategory = false;
    &scope.IsVisibleSubCategory = false;
    &scope.IsVisibleComposition = false;
    &scope.IsVisibleAnteile = false;
    $scope.ShowHideCategory = function () {
    //If DIV is visible it will be hidden and vice versa.
        $scope.IsVisibleCategory = $scope.IsVisibleCategory ? false : true;
    };
    $scope.ShowHideSubcategory = function () {
    //If DIV is visible it will be hidden and vice versa.
        $scope.IsVisibleSubcategory = $scope.IsVisibleSubcategory ? false : true;
    };
    $scope.ShowHideComposition = function () {
    //If DIV is visible it will be hidden and vice versa.
        $scope.IsVisibleComposition = $scope.IsVisibleComposition ? false : true;
    };
    $scope.ShowHideAnteile = function () {
    //If DIV is visible it will be hidden and vice versa.
        $scope.IsVisibleAnteile = $scope.IsVisibleAnteile ? false : true;
    };
});

Comment: As your `li` items are inside the `div`, the `data-ng-click` method is called every time you click anywhere inside the div. Try to separate them.
Answer: The problem here is, that you set the ng-click on the containing div. So every click on a child, will trigger the ShowHideCategory() function.
Try moving the click handler to the actual word:

Kategorien

  [...]

Side note, not related to your question
In your ShowHide function, you could optimise your code a bit:
$scope.IsVisibleCategory = !$scope.IsVisibleCategory;


Is it still a force at 2nd?

Question: Man on first, grounder to 1st baseman, he steps on 1st to get the runner out and throws to 2nd for the double play.  Is it a force at 2nd or does it become a tag play?
Answer: The runner must be tagged out. To quote from the MLB rules, Rule 5.09(b)(6):

if a following runner is put out on a force play, the force is removed and the
  runner must be tagged to be put out.

The following runner in your scenario is the batter-runner, so the force is removed as soon as the first baseman steps onto the base.

Is it still a force at 2nd?


No Internet access while being connected to VPN using Cisco VPN Client 5

Question: I have an access to corporate VPN using Cisco VPN Client 5.0.00:0340, but when I'm connected to it, I don't have an Internet access. I'm using Windows XP SP3. As it was suggested here
http://forums.speedguide.net/showthread.php?t=209167
, I tried to enable "Allow local LAN Access" but it doesn't work. I also tried a second solution - deleting entry using "route" command, but it didn't help. I used "route delete 192.168.100.222". It's a third day of my attempts to solve this issue and I don't have an idea what else to do. I'm not very experienced in VPN stuff, but I know something about networking. Basing on my knowledge, I think that it's theoretically possible to achieve Internet access using my local network and only corporate stuff to be routed using VPN connection.
I think that theoretically this should look like this:

every IP being inside by corporation -> VPN interface IP
every other IP -> my ethernet interface

I've tried many possibilities of how to change those routes, but neither of them work. I'd really appreciate any help.
My route configuration before connecting to VPN:
===========================================================================
Interface List
0x1 ........................... MS TCP Loopback interface
0x2 ...00 c0 a8 de 79 01 ...... Atheros AR5006EG Wireless Network Adapter - Teefer2 Miniport
0x10005 ...02 00 4c 4f 4f 50 ...... Microsoft Loopback Card
0x160003 ...00 17 42 31 0e 16 ...... Marvell Yukon 88E8055 PCI-E Gigabit Ethernet Controller - Teefer2 Miniport
===========================================================================
===========================================================================
Active routes:
Network Destination        Netmask          Gateway        Interface Metrics
          0.0.0.0          0.0.0.0  192.168.101.254  192.168.100.222      10
         10.0.0.0    255.255.255.0        10.0.0.10       10.0.0.10       30
        10.0.0.10  255.255.255.255        127.0.0.1       127.0.0.1       30
   10.255.255.255  255.255.255.255        10.0.0.10       10.0.0.10       30
        127.0.0.0        255.0.0.0        127.0.0.1       127.0.0.1       1
    192.168.100.0    255.255.254.0  192.168.100.222  192.168.100.222      1
  192.168.100.222  255.255.255.255        127.0.0.1       127.0.0.1       1
  192.168.100.255  255.255.255.255  192.168.100.222  192.168.100.222      1
        18.104.22.168        240.0.0.0        10.0.0.10       10.0.0.10       3
        220.127.116.11        240.0.0.0  192.168.100.222  192.168.100.222      1
  255.255.255.255  255.255.255.255        10.0.0.10       10.0.0.10       1
  255.255.255.255  255.255.255.255  192.168.100.222  192.168.100.222      1
  255.255.255.255  255.255.255.255  192.168.100.222               2       1
Default gateway:  192.168.101.254.
===========================================================================

My route configuration after connection to VPN:
===========================================================================
Interface List
0x1 ........................... MS TCP Loopback interface
0x2 ...00 c0 a8 de 79 01 ...... Atheros AR5006EG Wireless Network Adapter - Teefer2 Miniport
0x10005 ...02 00 4c 4f 4f 50 ...... Microsoft Loopback Card
0x160003 ...00 17 42 31 0e 16 ...... Marvell Yukon 88E8055 PCI-E Gigabit Ethernet Controller - Teefer2 Miniport
0x170006 ...00 05 9a 3c 78 00 ...... Cisco Systems VPN Adapter - Teefer2 Miniport
===========================================================================
===========================================================================
Active routes:
Network Destination        Netmask          Gateway        Interface Metrics
          0.0.0.0          0.0.0.0       10.251.6.1     10.251.6.51       1
         10.0.0.0    255.255.255.0        10.0.0.10       10.0.0.10       30
         10.0.0.0    255.255.255.0       10.251.6.1     10.251.6.51       10
        10.0.0.10  255.255.255.255        127.0.0.1       127.0.0.1       30
      10.1.150.10  255.255.255.255  192.168.101.254  192.168.100.222      1
       10.251.6.0    255.255.255.0      10.251.6.51     10.251.6.51       20
      10.251.6.51  255.255.255.255        127.0.0.1       127.0.0.1       20
   10.255.255.255  255.255.255.255        10.0.0.10       10.0.0.10       30
   10.255.255.255  255.255.255.255      10.251.6.51     10.251.6.51       20
        127.0.0.0        255.0.0.0        127.0.0.1       127.0.0.1       1
    192.168.100.0    255.255.254.0  192.168.100.222  192.168.100.222      10
    192.168.100.0    255.255.254.0       10.251.6.1     10.251.6.51       10
  192.168.100.222  255.255.255.255        127.0.0.1       127.0.0.1       10
  192.168.100.255  255.255.255.255  192.168.100.222  192.168.100.222      10
  188.8.131.52  255.255.255.255  192.168.101.254  192.168.100.222      1
        126.96.36.199        240.0.0.0        10.0.0.10       10.0.0.10       30
        220.127.116.11        240.0.0.0      10.251.6.51     10.251.6.51       20
        18.104.22.168        240.0.0.0  192.168.100.222  192.168.100.222      10
  255.255.255.255  255.255.255.255        10.0.0.10       10.0.0.10       1
  255.255.255.255  255.255.255.255      10.251.6.51     10.251.6.51       1
  255.255.255.255  255.255.255.255  192.168.100.222  192.168.100.222      1
  255.255.255.255  255.255.255.255  192.168.100.222               2       1
Default gateway:   10.251.6.1.
===========================================================================

Update:
@ggonsalv:
I did nearly the same thing as you've said. First I deleted "0.0.0.0" rule that was there during VPN connection. And then I've used your command, but with "if ethernet_card_id" at the end.
route add 0.0.0.0 mask 0.0.0.0 192.168.101.254 metric 1 if 0x3

That didn't work. What gives me a headache is how the hell the traffic is routed to the internal corporate network now. Routing is now set to route everything to my local network, not the VPN. When I type "google.com" in my browser, sniffer shows me that the DNS query goes to VPN DNS=10.22.20.1 which is defined as DNS address of VPN connection. I even changed DNS address in there to my local, now queries are with that address but I don't get any response. How is that even possible?! I'm not an expert at all and I just don't get it. Now my routing table looks like this (IP inside VPN changes between connections):
===========================================================================
Interface List
0x1 ........................... MS TCP Loopback interface
0x2 ...00 c0 a8 de 79 01 ...... Atheros AR5006EG Wireless Network Adapter - Teefer2 Miniport
0x3 ...00 17 42 31 0e 16 ...... Marvell Yukon 88E8055 PCI-E Gigabit Ethernet Controller - Teefer2 Miniport
0x10005 ...02 00 4c 4f 4f 50 ...... Microsoft Loopback Card
0x20006 ...00 05 9a 3c 78 00 ...... Cisco Systems VPN Adapter - Teefer2 Miniport
===========================================================================
===========================================================================
Active routes:
Network Destination        Netmask          Gateway        Interface Metrics
          0.0.0.0          0.0.0.0  192.168.101.254  192.168.100.222      1
         10.0.0.0    255.255.255.0        10.0.0.10       10.0.0.10       30
         10.0.0.0    255.255.255.0       10.251.6.1    10.251.6.144       20
        10.0.0.10  255.255.255.255        127.0.0.1       127.0.0.1       30
      10.1.150.10  255.255.255.255  192.168.101.254  192.168.100.222      1
       10.251.6.0    255.255.255.0     10.251.6.144    10.251.6.144       20
     10.251.6.144  255.255.255.255        127.0.0.1       127.0.0.1       20
   10.255.255.255  255.255.255.255        10.0.0.10       10.0.0.10       30
   10.255.255.255  255.255.255.255     10.251.6.144    10.251.6.144       20
        127.0.0.0        255.0.0.0        127.0.0.1       127.0.0.1       1
    192.168.100.0    255.255.254.0  192.168.100.222  192.168.100.222      20
    192.168.100.0    255.255.254.0       10.251.6.1    10.251.6.144       20
  192.168.100.222  255.255.255.255        127.0.0.1       127.0.0.1       20
  192.168.100.255  255.255.255.255  192.168.100.222  192.168.100.222      20
  220.127.116.11  255.255.255.255  192.168.101.254  192.168.100.222      1
        184.108.40.206        240.0.0.0        10.0.0.10       10.0.0.10       30
        18.104.22.168        240.0.0.0     10.251.6.144    10.251.6.144       20
        220.127.116.11        240.0.0.0  192.168.100.222  192.168.100.222      20
  255.255.255.255  255.255.255.255        10.0.0.10       10.0.0.10       1
  255.255.255.255  255.255.255.255     10.251.6.144    10.251.6.144       1
  255.255.255.255  255.255.255.255  192.168.100.222  192.168.100.222      1
  255.255.255.255  255.255.255.255  192.168.100.222               2       1
Default gateway:  192.168.101.254.
===========================================================================

I even deleted this line and it didn't help:
192.168.100.0    255.255.254.0       10.251.6.1    10.251.6.144       20

Comment: Related: http://superuser.com/questions/284709/how-to-allow-local-lan-access-while-connected-to-cisco-vpn
Answer: Not sure on the Cisco setup, because we use Watchguard. However, when setting up a new VPN account I have a checkbox that says forward all traffic from user over VPN. If this is checked all network traffic from the user is forced through the VPN. This is set up on the gateway device, not on the users system. I don't know if it is the same with Cisco, but I would assume it is similar.
Comment: There is a similar option in Cisco.  I don't know exactly what it is called, but basically the network administrator can do this to prevent you from bridging a non-secure network into a secure network.
Comment: @Catherine: It's called split-tunneling
Comment: +1 Split-tunneling! As soon as I read that the light bulbs went on. That is exactly the word I was looking for.
Answer: The VPN server is pushing you a new default gateway instead of your usual one, so all of your outbound traffic is routed through the VPN tunnel; this is what is blocking you from Internet access while you're connected to the VPN.
Not sure where this can be changed in the Cisco VPN Client, or even if you actually can change it (it probably is managed centrally by the VPN server). If you were using the built-in Windows VPN client, you'd have to edit the advanced TCP/IP properties of the VPN connection and disable the "Use default gateway on the remote network" setting.
Comment: +1 for this solution. I was looking for that setting for quite a while.
Answer: Open up properties on the LAN connection you're using then do the following:
Click Internet Protocol (TCP/IP) then click Properties.
In the Internet Protocol (TCP/IP) window click on Advanced...
Click the DNS tab and select "Append primary and connection
specific DNS suffixes"

After you've set that you should be able to access the internet again.
Cisco seems to change this when you connect then reverts it back once you've disconnected from the VPN.
Answer: Unless your VPN connection allows internet you will not get the internet
The route rule
            0.0.0.0          0.0.0.0       10.251.6.1     10.251.6.51       1
says when you goto any web site (ip address) it will routed via 10.251.6.1
you also use the route /add to add a new persistent route.
Give this is a try
route  add 0.0.0.0 MASK 0.0.0.0 192.168.101.254 METRIC 1
It should add 192.168.101.254 as the top route.
Answer: I had the same issue but I resolved it.
Check if you have the access-list ext under crypto isakmp client configuration group cisco.
Answer: I used to have this problem then found a quick solution for resolving it.
Open up properties on the LAN connection you're using then do the following:

Click Internet Protocol (TCP/IP) then
click Properties.
In the Internet    Protocol (TCP/IP)
window click on Advanced...
Click the DNS tab and    select
"Append primary and connection
specific DNS suffixes"

After you've set that you should be able to access the internet again.
Cisco seems to change this when you connect then reverts it back once you've disconnected from the VPN.
Answer: I had the same issue. Using the following line solved my problem:
route add 0.0.0.0 MASK 0.0.0.0 192.168.0.1 METRIC 1

192.168.0.1 being the default gateway of my main server serving internet connections within our office.
However using the following did NOT work:
Open up properties on the LAN connection you're using then do the following:

Click Internet Protocol (TCP/IP) then click Properties.
In the Internet Protocol (TCP/IP) window click on Advanced...
Click the DNS tab and select "Append primary and connection specific DNS suffixes"
Answer: This has been a vexing issue sense I got this Cicso Anyconnect VPN Client installed on my Windows 7 64 bit PC.
The solutions I found on the internet were to restart the PC. That would restore the internet connectivity.
I found a better way to re-enable the internet after disconnecting from a remote server.
Steps to re-enable WAN access:
Disconnect the Cisco AnyConnect VPN client (disconnect the client from the server).
Open Control Panel
Open System in Control Panel
In System, find Device Manager
Open Device Manager
Find Network adapters in Device Manager
Expand Network adapters
Right click on the Ethernet Controller, select Disable and confirm disable
Right click on the Ethernet Controller, Select Enable and close the windows.
Your internet access should be restored without a PC restart.
I hope this works for many people...
Cheers!
Comment: This question is about older `Cisco VPN Client`. Here are other questions about `Cicso Anyconnect VPN Client`: http://superuser.com/questions/616192/split-tunnel-and-cisco-anyconnect,  http://serverfault.com/questions/663947/lan-access-with-cisco-anyconnect-secure-mobility-client-v-3-0-4235. This answer should be moved there.
Answer: The easier way to resolve this issue, since I read that someone didn't have this issue on win xp, try to :

Completely uninstall your vpn client
make a clean from registry (Advanced user please) optional for beginner
Change the COMPATIBILY of your setup.exe file (vpn client)
-->Check the "run as administrator"
-->change the compatibility to Win xp sp3
Run your compatible setup.exe file (vpn client)
Once completed, run your vpn client, and navigate on Internet without any issue.

I have tested it on :
- Win 7 32 and 64 bits
- Make sure that your have the lastest java installed
- IE, firefox, other browsers (VPN+Internet)
- Wireless
- Ethernet
- Several laptops, within different network architectures
Note: this option resolves a lot of issues on other OS, before making any other troubleshooting checklist
Answer: I am using WINDOWS 10 and had similar issue when connecting to my work Cisco AnyConnect Secure Mobile Client. Pretty much I would lose my wifi connectivity when I connected to AnyConnect VPN. To be more specific, the wifi connection would show up as "No Internet, Secured".
Doing the following fixed this issue:
1) Go to Control Panel > Network and Internet > Network and Sharing Center
2) On the left side panel, there should be an option called "Change Adapter Settings". Click on it
3) Single left click on "Wi-Fi" to select it and you should see option called "Change Settings of this connection" pop up on a tab located right above this "Wi-Fi" icon. Click it. If you don't see it. Click ">>" to expand and you should this option
4) This will bring up "Wi-Fi Properties" window. Click on "Sharing" tab
5) Check the box "Allow Connection Sharing" and under "Home networking connection", I chose "Ethernet". You can Choose "Wi-Fi" if you want.
The above setup should now allow you to connect to AnyConnect Cisco VPN while staying connected with your local wifi connection.
Answer: Network and internet settings - > VPN -> Change adapter options
It will list all the interfaces
Right click -> properties
Uncheck ipv6
Do this for the VPN and other network interface.
Worked for me.


Make a new column panda from a string. Do I need some kind of iterable?

Question: Ok, so this works:
import pandas as pd
import numpy as np

ind = [0,1,2]
d = {'col1' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']), 'col2' : pd.Series([5, 6, 7, 8],  index=['a', 'b', 'c', 'd']), 'col3' : pd.Series([9, 10, 11, 12], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print(df)

gives the following:
   col1  col2  col3
a     1     5     9
b     2     6    10
c     3     7    11
d     4     8    12

to add a column using math, this works:
df['new'] = df['col2'] + df['col3']

which gives:
   col1  col2  col3  new
a     1     5     9   14
b     2     6    10   16
c     3     7    11   18
d     4     8    12   20

BUT THIS DOESNT WORK:
df['new2'] = str(df['col3'])

if gives this, which is weird:
   col1  col2  col3  new                                             new2
a     1     5     9   14  a     9\nb    10\nc    11\nd    12\nName: col3...
b     2     6    10   16  a     9\nb    10\nc    11\nd    12\nName: col3...
c     3     7    11   18  a     9\nb    10\nc    11\nd    12\nName: col3...
d     4     8    12   20  a     9\nb    10\nc    11\nd    12\nName: col3...

Help would be awesome, thanks!
Answer: try this once
df['new2'] = df['col3'].astype(str)

Comment: so, that works, and it technically answers the question, but i actually needed something more general. I can ask it in a different way though. Thanks a lot.
Comment: i am sorry if i couldnt help you the way you wanted. :(
Comment: @mmvw - Faster is use `astype(str)` as `apply(str)`, so I think this is better solution.
Answer: df['new'] = df['col3'].apply(str)

You can find lots of such methods in pandas.
https://pandas.pydata.org/pandas-docs/stable/tutorials.html


How to re render MKMapView to update overlay according to new coordinates

Question: I've written this function to add overlay at Loading View and its working perfectly.
How can I use this function or any other method to update overlay according to new coordinates I pass on a button click.
I'm passing an array of type CLLocationCoordinate2D of coordinates.
 func drawpolyline(loclist: Array<CLLocationCoordinate2D>) {
   //  if let overlays = self.mainMapView?.overlays {
   //      self.mainMapView.removeOverlays(overlays)
   //  }

   if (loclist != nil && loclist.count > 1) {
        let startmark = loclist.first
        let cord1 = CLLocationCoordinate2D(latitude: (startmark?.latitude)!, longitude: (startmark?.longitude)!)

        let polyline = MKPolyline(coordinates: loclist, count: loclist.count)
        print(polyline.pointCount)
        let latDelta:CLLocationDegrees = 0.02
        let lonDelta:CLLocationDegrees = 0.02

        let mapSpan = MKCoordinateSpanMake(latDelta, lonDelta)
        let mapRegion = MKCoordinateRegion(center: cord1, span: mapSpan)
        // let adjustedRegion: MKCoordinateRegion = [self.mainMapView regionThatFits:viewRegion]

        if (mainMapView != nil) {
          self.mainMapView.delegate = self
          self.mainMapView.add(polyline)
          self.mainMapView.setRegion(mapRegion, animated: true);
          // self.mainMapView.addAnnotation(mapAnnotation);
        }
    } else {
        configureMap()
    }
}

//function of MKMapViewDelegate for making overlays
//Function to give polyline color and width etc.
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    //Return an `MKPolylineRenderer` for the `MKPolyline` in the `MKMapViewDelegate`s method
     if let polyline = overlay as? MKPolyline {
        let testlineRenderer = MKPolylineRenderer(polyline: polyline)
        testlineRenderer.strokeColor = .blue
        testlineRenderer.lineWidth = 3.0
        return testlineRenderer
    }

    fatalError("Something wrong...")
    return MKOverlayRenderer()
}

Answer: I assume you have a button set up, and linked with IBAction.
You need to call the drawpolyline function from the button action giving the new coordinates in the same format as you have previously when calling it on launch but for your new location.
If you don't understand, maybe provide some more information on how you call the drawpolyline function on launch, I assume in the viewDidLoad.
If you don't know how to call a button use
@IBAction func showListPressed(_ sender: UIButton) {

    // call drawpolyline function here with new coordinates
}

Comment: I am calling this function in ViewDeidLoad to draw polyline on launch.

But when I call this function on button click,  the mainMapView object is nil every time.