What is the name of having two identical servers?

Question: I have a Windows Small Business Server 2011. I want to have another identical server (or mostly identical in hardware, thus identical in software). So, my email server, my users or anything else shall be identical on both server. I will have my main server (already existing) that copies on the fallback server. My webhoster (another company) will be set to transmit connections to the main server if available, otherwise, on the fallback one. So, a real-time sync is needed + an onload sync.
What is the name for this setup? And if you are able to answer, how may I do that? Is it only a matter of synchronizing files over internet?
Comment: SBS licensing doesn't allow for a hot-standby server. Thus the failover won't work as you'd probably expect since its a DC (Domain Controller). What resources (Websites, File Shares, DNS, etc) do you need in an HA (High Availability) configuration?
Comment: @user2320464 Exchange, Websites, Git server, other files. All the data of the services offered by the server so if it crash (like as a power failure), the other plays it role in the state the main was.
Comment: Best to research how to configure each of those services in HA since an SBS environment can have just a single Domain Controller (DC). AD can be extended to Azure though it has limitations.
Answer: its called failover
here are few links that might help
http://www.howto-expert.com/how-to-create-a-server-failover-solution/
https://technet.microsoft.com/en-us/library/cc731844(v=ws.10).aspx
Answer: Dealing with the organizational impacts of keeping a service running is business continuity. A service made more reliable by running on multiple hosts is highly available. The verb to move a service around a cluster is failing over. A request able to be served by any of multiple hosts is load balancing.
Comment: Thank you for giving me more terms. Unfortunately I will keep the answer accepted to the first guy because he was already correct.


Erro ao criar uma tabela MySQL

Question: eu criei uma tabela no Power Designer como mostra a abaixo
create table BANCO
(
   COD_BANCO            integer not null auto_increment,
   NOME_BANCO           varchar(50),
   AGENCIA_BANCO        integer,
   CONTA_BANCO          integer,
   GERENTE_BANCO        varchar(20),
   FONE_BANCO           varchar(10),
   primary key (COD_BANCO)
)
type = InnoDB;

porém gerou esse erro
error 1064 (42000)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type = InnoDB' at line 11

é porque o Power Designer estar trabalhando com MySQL 5 e o que estar instalado no meu pc é MySQL 5.5
como faço para resolver esse problema? vou ter que instalar a versão MySQL 5?
Answer: Troque type por engine. O type era usando em versões antigas do MySQL.

"The older term TYPE is supported as a synonym for ENGINE for backward
  compatibility, but ENGINE is the preferred term and TYPE is
  deprecated."
O TYPE, termo mais antigo, é suportado como um sinônimo de ENGINE para
  compatibilidade com versões anteriores, mas ENGINE é o termo
  preferido e TYPE está obsoleto.

Fonte
Answer: Para corrigir isto no power designer basta editar o DBMS e vá em MYSQL50::Script\Objects\Table\Options.
Role o texto para cima e você vai achar algo como isto no campo Value:
type = %s : list = BDB | HEAP | ISAM | InnoDB | MERGE | MRG_MYISAM | MYISAM, default = MYISAM

Edite esta linha deixando assim:
engine = %s : list = BDB | HEAP | ISAM | InnoDB | MERGE | MRG_MYISAM | MYISAM, default = InnoDB

Veja que alterei também o default para InnoDB, assim quando você criar a tabela ele já insere como engine = InnoDB.
Feito isto basta salvar como MySQL5.1 para que não sobreponha o DBMS do MySQL5.0.

Erro ao criar uma tabela MySQL


Cherry pick training data (question is NOT about train/validation/test split or ml algorithms )

Question: This is more of a general question and not ml-algorithm specific, are there any algorithms/tools/papers on the topic of 'selecting' training-data-entries?
Often you will have lack of training data and so it is advisable to use all of it or even try to find more data.
It seems that many people focus and developed many methods on feature selection/importance and algorithm tuning, but regarding training data the main approach is to gather more.
PS: google/literature has many information on which ml-algo to use for which data or how to split train/test data, but this is not what I need. Imbalanced classes comes closer to my question but is still not exactly what I try to find.
Comment: You say more is not always better, but what would be the basis of this claim? More data means your sample is closer to the population it represents. In what scenario would this be undesirable?
Comment: How are you measuring performance? Can you show that the apparent gains are not just an artifact of selection bias?
Comment: You don't say what purpose you want to achieve... There's the field of active learning: https://en.m.wikipedia.org/wiki/Active_learning_(machine_learning)
Comment: Also stratified sampling...
Answer: There are some papers related to selecting data from other domains to improve model performance:
Learning to select data for transfer learning with Bayesian Optimization
https://arxiv.org/abs/1707.05246
Instance Weighting for Domain Adaptation in NLP
http://sifaka.cs.uiuc.edu/czhai/pub/acl07.pdf


Gravar um Json string no banco de dados c#

Question: Estou conseguindo receber os dados corretamente, e os conseguindo separar corretamente também, único problema é que não sei como usar os valores e poder gravar no banco de dados, poderiam me ajudar ?
A imagem abaixo mostra como estou recebendo os dados e os tratando até então:

[HttpPost]
    public async Task<IActionResult> SellAdd(string products)
    {
        var objects = JsonConvert.DeserializeObject<List<object>>(products);
        string[] model = objects.Select(x => x.ToString()).ToArray();

        foreach (var product in model)
        {

        //    var produtoCodigo = await _productManager.GetProductCodigoAsync();

          /*  var venda = new ApplicationSell
            {
                Quantidade = product.quantidadeProduto,
                Total = product.valorTotalProduto,
                ProductId = produtoCodigo.Codigo
            };

            await _productManager.GravaVendaAsync(venda);  */
        }

        return RedirectToAction("Index");
    }

Comment: Olá @Matheus. Evite colocar o seu código em imagens, ao invés edite a sua questão e coloque-o lá.
Comment: tem algum código onde esteja a gravar alguma coisa na base de dados? Ou ainda não tem nada relativo a isso?
Answer: Olá, na minha humilde opinião, você poderia utilizar o entity framework para acesso ao banco de dados.
Criaria uma classe:
public class Products {
    int    codigoProduto {get;set;}
    int    quantidadeProduto {get;set;}
    double valorTotalProduto {get;set;}
}

Products  prod = JsonConvert.DeserializeObject<Products>(products);

Logo abaixo você poderia acessar as propriedades prod.valorTotalProduto por exemplo.
Em seguida usaria o entity framework para gravar ,atualizar ou deletar no banco de dados.
Espero ter ajudado me algo.
Comment: Mas no caso a class Products tem que ter exatamente o mesmo nome do json no caso ?
Comment: Sim, pois você está fazendo uma associação.


How to show that $\sum_{n=1}^\infty r^n\cos n\theta=\frac{r\cos\theta-r^2}{1-2r\cos\theta+r^2}$?

Question: I'm supposed to prove the following series expansion:
$$s_n=\sum_{n=1}^\infty r^n\cos n\theta=\frac{r\cos\theta-r^2}{1-2r\cos\theta+r^2}$$
I first note the following:
$$s_n=\sum_{n=1}^\infty \Re\left[re^{i\theta}\right]^n=\Re\left[\sum_{n=1}^\infty z^n\right]$$
Using geometric series definition:
$$s_n=\Re\left[\frac{1}{1-z}\right]$$
$$s_n=\Re\left[\frac{1-z}{1-2z+z^2}\right]$$
Substituting polar coordinates of $z$:
$$s_n=\Re\left[\frac{1-r\exp(i\theta)}{1-2r\exp(i\theta)+r^2\exp(2i\theta)}\right]$$
Taking real component:
$$s_n=\frac{1-r\cos\theta}{1-2r\cos\theta+r^2\cos2\theta}$$
I can't really seems to do anything beyond here, could someone point out where I've gone wrong?
Comment: In the last step:
$$
\Re\left[\frac{1-r\exp(i\theta)}{1-2r\exp(i\theta)+r^2\exp(2i\theta)}\right]\neq\frac{1-r\cos\theta}{1-2r\cos\theta+r^2\cos2\theta}$$

One should not simply take the real part in each single term.
Comment: In general, $$\Re[\frac{f(z)}{g(z)}]\neq\frac{\Re(f(z))}{\Re(g(z))}.$$ For instance $$\Re[\frac{1-i}{1+i}]\neq 1.$$
Comment: Consider the example $i/i$. Try to take real part of each term.
Comment: The first equality does not make sense: the LHS depends on $n$ while the RHS does not.
Comment: Moreover, how exactly did you "Taking real component" in the last step? One should **not** simply take the real part in each single term.
Comment: Using $\exp(i\theta)=\cos\theta+i\sin\theta$
Comment: @Jack Why can I not do that with the denominator?
Answer: Notice that $$\sum_{n=1}^\infty z^n=\frac{z}{1-z}\qquad |z|<1$$since the sum starts at $n=1$. Hence, $$\begin{align}\sum_{n=1}^\infty r^n\cos(n\theta)&=\Re\left( \frac{z}{1-z}\right)\\&=\Re\left(\frac{z-|z|^2}{|1-z|^2}\right)\\&=\frac{\Re(z)-|z|^2}{|1-z|^2}\\&=\frac{r\cos(\theta)-r^2}{(1-r\cos(\theta))^2+(-r\sin(\theta))^2}\\&=\frac{r\cos(\theta)-r^2}{1-2r\cos(\theta)+r^2}\end{align}$$
Note, $$\frac{z}{1-z}=\frac{z(1-\bar{z})}{|1-z|^2}$$
Comment: The geometric series starting at $n=1$ is $$\sum_{n=1}^\infty z^n=\frac{z}{1-z}$$which is not the same as when starting at $n=0$, $$\sum_{n=0}^\infty z^n=\frac{1}{1-z}$$Indeed, it can be shown in the same derivation as the geometric series formula, however we can also show it from the $n=0$ starting case: $$\sum_{n=1}^\infty z^n=\frac{1}{1-z}-1=\frac{1-(1-z)}{1-z}$$
Comment: Where does the $z$ in the numerator come from? From subtracting the $n=0$ case?
Comment: In general, $$\sum_{n=k}^\infty z^n=\frac{z^k}{1-z}$$provided the series converges of course.
Answer: Note that the sum starts at $1$ so the geometric sum will give
\begin{eqnarray*}
s_n=\Re\left[\frac{z}{1-z}\right]
\end{eqnarray*}
We now multiply top and bottom by the conjugate of the denominator
\begin{eqnarray*}
\Re\left[\frac{z}{1-z}\right] &=& \Re\left[\frac{r \cos(\theta)+ir \sin(\theta) }{1-r \cos(\theta)-ir \sin(\theta)}\right] \\
&=& \Re\left[\frac{r \cos(\theta)+ir \sin(\theta) }{1-r \cos(\theta)-ir \sin(\theta)}\frac{1-r \cos(\theta)+ir \sin(\theta) }{1-r \cos(\theta)+ir \sin(\theta)}\right] \\
&=& \Re\left[\frac{r \cos(\theta)(1-r \cos(\theta))-(r \sin(\theta))^2 +i(.)}{(1-r \cos(\theta))^2+(r \sin(\theta))^2}\right] \\
&=& \frac{r \cos(\theta)-r^2 }{1-2r \cos(\theta)+r^2}. \\
\end{eqnarray*}


I18n translation of site_name not working

Question: I have installed i18n, changed settings.php according to this guide, set language detection to url and cleared cache.
Then on site config page, I set the url prefix to English and all UI changed to English. Then I updated the Site Name to something English.
Then I repeated the above steps for a local language.
But it looks like changing the url path prefix each time gives me identical results regarding Site Name, i.e. the Site Name is changing each time I update it, no matter which language path is chosen.
What am I doing wrong?
P.S. In table "variable" the site_name is just one. I never used i18n before, no idea how it should look here.
Answer: To translate a Drupal 7 Site name you have to activate Variable translation module (which is in the same package as i18n) and the required ones (like Variable store).
After you install these modules, go to Configuration -> Multilingual settings -> Variables tab and choose Site name (?q=admin/config/regional/i18n/variable),Then go to Configuration -> System -> Site information (q=admin/config/system/site-information) and select the language you want. Change the Site name field and save.
You'll find the translated site name in variable_store table.
Comment: I have done exactly like you explained but on site information variable does not appear please suggest ?


How to convert Multiple Json object to DataTable or DataSet in C#

Question: I have an below json object.I would to know 2 points

How to convert below json object to DataTable or Dataset in C# Code
After converting,reverse back to (How to convert DataTable to Json object)  in C# Code.
Please provide me example code

[
  {
    "transaction": {
      "Version": "1.01",
      "TranDtls": {
        "TaxSch": "GST",
        "SupTyp": "B2B",
        "RegRev": "Y",
        "EcmGstin": null,
        "IgstOnIntra": "N"
      },
      "DocDtls": {
        "Typ": "INV",
        "No": "DAOC/007",
        "Dt": "10/08/2020"
      },
      "SellerDtls": {
        "Gstin": "29AAFCD5862R000",
        "LglNm": "NIC company pvt ltd",
        "TrdNm": "NIC Industries",
        "Addr1": "5th block, kuvempu layout",
        "Addr2": "kuvempu layout",
        "Loc": "GANDHINAGAR",
        "Pin": 560037,
        "Stcd": "29",
        "Ph": "9000000000",
        "Em": "email@example.com"
      },
      "BuyerDtls": {
        "Gstin": "29AWGPV7107B1Z1",
        "LglNm": "XYZ company pvt ltd",
        "TrdNm": "XYZ Industries",
        "Pos": "12",
        "Addr1": "7th block, kuvempu layout",
        "Addr2": "kuvempu layout",
        "Loc": "GANDHINAGAR",
        "Pin": 562160,
        "Stcd": "29",
        "Ph": "91111111111",
        "Em": "firstname.lastname@example.com"
      },
      "DispDtls": {
        "Nm": "ABC company pvt ltd",
        "Addr1": "7th block, kuvempu layout",
        "Addr2": "kuvempu layout",
        "Loc": "Banagalore",
        "Pin": 562160,
        "Stcd": "29"
      },
      "ShipDtls": {
        "Gstin": "29AWGPV7107B1Z1",
        "LglNm": "CBE company pvt ltd",
        "TrdNm": "kuvempu layout",
        "Addr1": "7th block, kuvempu layout",
        "Addr2": "kuvempu layout",
        "Loc": "Banagalore",
        "Pin": 562160,
        "Stcd": "29"
      },
      "ItemList": [
        {
          "SlNo": "1",
          "PrdDesc": "Rice",
          "IsServc": "N",
          "HsnCd": "1001",
          "Barcde": "123456",
          "Qty": 100.345,
          "FreeQty": 10,
          "Unit": "BAG",
          "UnitPrice": 99.545,
          "TotAmt": 9988.84,
          "Discount": 10,
          "PreTaxVal": 1,
          "AssAmt": 9978.84,
          "GstRt": 12.0,
          "IgstAmt": 1197.46,
          "CgstAmt": 0,
          "SgstAmt": 0,
          "CesRt": 5,
          "CesAmt": 498.94,
          "CesNonAdvlAmt": 10,
          "StateCesRt": 12,
          "StateCesAmt": 1197.46,
          "StateCesNonAdvlAmt": 5,
          "OthChrg": 10,
          "TotItemVal": 12897.7,
          "OrdLineRef": "3256",
          "OrgCntry": "AG",
          "PrdSlNo": "12345",
          "BchDtls": {
            "Nm": "123456",
            "ExpDt": "01/08/2020",
            "WrDt": "01/09/2020"
          },
          "AttribDtls": [
            {
              "Nm": "Rice",
              "Val": "10000"
            }
          ]
        }
      ],
      "ValDtls": {
        "AssVal": 9978.84,
        "CgstVal": 0,
        "SgstVal": 0,
        "IgstVal": 1197.46,
        "CesVal": 508.94,
        "StCesVal": 1202.46,
        "Discount": 10,
        "OthChrg": 20,
        "RndOffAmt": 0.3,
        "TotInvVal": 12908,
        "TotInvValFc": 12897.7
      },
      "PayDtls": {
        "Nm": "ABCDE",
        "AccDet": "5697389713210",
        "Mode": "Cash",
        "FininsBr": "SBIN11000",
        "PayTerm": "100",
        "PayInstr": "Gift",
        "CrTrn": "test",
        "DirDr": "test",
        "CrDay": 100,
        "PaidAmt": 10000,
        "PaymtDue": 5000
         },
      "RefDtls": {
        "InvRm": "TEST",
        "DocPerdDtls": {
          "InvStDt": "01/08/2020",
          "InvEndDt": "01/09/2020"
        },
        "PrecDocDtls": [
          {
            "InvNo": "DOC/002",
            "InvDt": "01/08/2020",
            "OthRefNo": "123456"
          }
        ],
        "ContrDtls": [
          {
            "RecAdvRefr": "Doc/003",
            "RecAdvDt": "01/08/2020",
            "Tendrefr": "Abc001",
            "Contrrefr": "Co123",
            "Extrefr": "Yo456",
            "Projrefr": "Doc-456",
            "Porefr": "Doc-789",
            "PoRefDt": "01/08/2020"
          }
        ]
      },
      "AddlDocDtls": [
        {
          "Url": "https://einv-apisandbox.nic.in",
          "Docs": "Test Doc",
          "Info": "Document Test"
        }
      ],
      "ExpDtls": {
        "ShipBNo": "A-248",
        "ShipBDt": "01/08/2020",
        "Port": "INABG1",
        "RefClm": "N",
        "ForCur": "AED",
        "CntCode": "AE"
      },
      "EwbDtls": {
        "TransId": "12AWGPV7107B1Z1",
        "TransName": "XYZ EXPORTS",
        "Distance": 100,
        "TransDocNo": "DOC01",
        "TransDocDt": "10/08/2020",
        "VehNo": "ka123456",
        "VehType": "R",
        "TransMode": "1"
      }
    }
  }
]

Comment: Welcome to Stack Overflow. This site is not a code request site. If you need help with code, you will need to show what you have done so far, describe what you don't understand, describe the output of the code, and tell us what you would like it to do instead.
Comment: You don't include your attempt but you do include reams of unformatted JSON. -1
Comment: read this  newtonsoft json https://www.newtonsoft.com/json
Answer: You can check it here How to create dataset from Object?
There are a lot of ways you can use to instantiate an object from json string.
If you can't use any kind of third party libraries such as Newtonsoft.Json you can do it with JsonReaderWriterFactory
public static TEntity Create<TEntity>(string json)
{
    using (var memoryStream = new MemoryStream())
    {
        byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
        memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
        memoryStream.Seek(0, SeekOrigin.Begin);
        using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(
            memoryStream,
            Encoding.UTF8,
            XmlDictionaryReaderQuotas.Max,
            null))
        {
            var     serializer = new DataContractJsonSerializer(typeof(TEntity));
            TEntity entity     = (TEntity)serializer.ReadObject(jsonReader);
            return entity;
        }
    }
}

And vice-versa
public static string Create(object entity)
{
    var serializer = new DataContractJsonSerializer(entity.GetType());

    using (var stream = new MemoryStream())
    {
        using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8))
        {
            serializer.WriteObject(writer, entity);
        }

        return Encoding.UTF8.GetString(stream.ToArray());
    }
}

Then you will only need to work a little bit with C# to populate the required DataSet with your object instance.
Here is my code
Comment: Thanks for above code, can you have code for dataset instead of entity


AccessViolationException thrown by OleDbConnection.Open()

Question: I am getting a System.AccessViolationException error when trying to use the .Open() method on my OleDbConnection variable. But, confoundingly, it doesn't seem to happen when I run my code on a different computer.
My code is for a service that I want running on a server. It appears to work correctly when I run it on my personal computer, but it throws the AccessViolationException error when I try running it on the server.
Code Versions:

I am writing in C# using Visual Studios 2019 on Windows 10

OleDbConnection is from "Assembly System.Data, Version=188.8.131.52"

ADOX is from "Assembly Interop.ADOX, Version=126.96.36.199", System.Runtime.InteropServices

ADODB is from "Assembly Interop.ADODB, Version=22.214.171.124", System.Runtime.InteropServices

My code:
    internal static bool CreateMDB(MySchemaClass schema, string filePath)
    {
        OleDbConnection conn = null;
        bool status = true;
        string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", filePath);

        try
        {
            // Setup new file
            catalog.Create(connectionString);
            ((ADODB.Connection)catalog.ActiveConnection).Close();
            conn = new OleDbConnection(connectionString);
            conn.Open(); // <-- Error occurs here

            // Write to new file
            WriteDataToFile(schema, conn);
        }
        catch (Exception ex)
        {
            status = false;
        }
        finally
        {
            if (conn != null)
                conn.Close();
        }
        return status;
    }

StackTrace:

The best lead I have found so far is this post, but I'm a bit hazy about how to proceed from that starting point.
Comment: The only case I've seen an AccessViolationException thrown by `OleDbConnection.Open` was a totally corrupted mdb file. My hint here is, your `catalog` object is not freed and maybe the newly created mdb file isn't completely written to disk. Try to create the catalog object in your CreateMDB method, close the ActiveConnection and release `catalog` with Marshal.ReleaseComObject before you open the database with OleDbConnection.
Comment: What kind of Service project did you create?
Answer: To programmatically create an Access database do the following:
Add reference to Microsoft ADO Ext. 6.0 for DDL and Security

In VS menu, click Project
Select Add Reference
Click COM
Check Microsoft ADO Ext. 6.0 for DDL and Security

CreateAccessDatabase
public static string CreateAccessDatabase(string fullyQualifiedAccessFilename, string dbPassword = "")
{
    string connectionString = String.Format(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}", fullyQualifiedAccessFilename);

    if (String.IsNullOrEmpty(fullyQualifiedAccessFilename))
    {
        throw new Exception("Error (CreateAccessDatabase) - Database filename is null or empty.");
    }

    if (!String.IsNullOrEmpty(dbPassword))
    {
        connectionString = String.Format(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", fullyQualifiedAccessFilename, dbPassword);
    }

    //create new instance
    ADOX.Catalog cat = new ADOX.Catalog();

    //create Access database
    cat.Create(connectionString);

    //close connection
    cat.ActiveConnection.Close();

    //release COM object
    System.Runtime.InteropServices.Marshal.ReleaseComObject(cat);
    GC.Collect();

    cat = null;

    return String.Format("Database created '{0}'", fullyQualifiedAccessFilename);
}

Usage:
string result = string.Empty;

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Access Database 2000-2003 (*.mdb)|*.mdb|Access Database 2007 (*.accdb)|*.accdb";

if (sfd.ShowDialog() == DialogResult.OK)
{
    //create Access database
    result = CreateAccessDatabase(sfd.FileName);
}

To programmatically create a table in an Access database:
Add using statement:
using System.Data.OleDb;

CreateTableProduct:
public static int CreateTableProduct(string fullyQualifiedAccessFilename, string dbPassword = "")
{
    int result = 0;

    string connectionString = String.Format(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}", fullyQualifiedAccessFilename);

    if (!String.IsNullOrEmpty(dbPassword))
    {
        connectionString = String.Format(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", fullyQualifiedAccessFilename, dbPassword);
    }

    string sqlText = string.Empty;
    sqlText = "CREATE TABLE Product ";
    sqlText += "(ID AUTOINCREMENT not null primary key,";
    sqlText += " Name varchar(50) not null,";
    sqlText += " Price currency, Quantity integer);";

    using (OleDbConnection con = new OleDbConnection(connectionString))
    {
        //open connection
        con.Open();

        using (OleDbCommand sqlCmd = new OleDbCommand(sqlText, con))
        {
            //execute command
            result = sqlCmd.ExecuteNonQuery();
        }
    }

    return result;
}

Resources:

ADO Features for each Release
Which Access file format should I use?
CREATE TABLE statement (Microsoft Access SQL)
System.Data.OleDb Namespace
Answer: The underwhelming answer to the problem is that my server was lacking some of the files my personal computer had, and only needed the correct files installed.
The missing piece in this case was the Microsoft Access Database Engine 2016 Redistributable, which I ended up finding here. Running that executable on my server got the needed files and everything worked after that.


Google Analytics report on the website

Question: Is there a way of making the google analytics available for previewing on the drupal 7 site?
Answer: Try Google Analytics Reports module.

Graphical reports include a dashboard widget for admins, a small
  path-based report in blocks, and a full path-based report.
Prerequisites are the Google Charts API module and the OAth
  module. Do not forget to set the module's permissions about who has
  access to the reports.
Comment: Thanks so much for that @monymirza
I've installed all three of those modules but am getting this error message:
DrupalOAuthClient requires the PHP cURL library. (Currently using OAuth cURL library not found)
Is this where I am supposed to get the php curl library from and if so, how? :S http://php.net/manual/en/curl.setup.php
Comment: are you working locally? using wamp??
Comment: Locally @monymirza
Not wamp though.
Comment: which server using u r?
Comment: Sorry, linux server @monymirza
Comment: hmmm. i think u r using Ubuntu OS...
Comment: How do I check to see if I'm using ubunty? I am not aware that I am using it ... (Someone else setup the environment for me) @monymirza
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7471/discussion-between-monymirza-and-kine456)
Comment: I can't log into the chat :( @monymirza
Comment: @schnippy
would you happen to know what my issue is?

Google Analytics report on the website


Is it possible to create a scroll view with an animated page control in Swift?

Question: The designer wants the following animation from a swipe gesture.

As it can be seen the user can swipe cards and see what each card has. At the same time, the user can see in the right side of the screen the following card and the last one in the left. Also, cards are changing their size while the user is moving the scroll.
I have already worked with page control views but I have no idea if this is possible with a page Control (which actually is the question of this post).
Also, I have already tried with a collectionView but when I swipe (actually is an horizontal scroll) the scroll has an uncomfortable inertia and also, I have no idea how to make the animation.
In this question a scrolled page control is implemented but now I just wondering if and animation like the gif provided is possible.
If the answer is yes, I would really appreciate if you can give tips of how I can make this possible.
Thanks in advance.
Comment: You can try UICollectionViewLayout and UICollectionViewLayoutAttributes to make pages https://www.raywenderlich.com/107687/uicollectionview-custom-layout-tutorial-spinning-wheel. For transactions I'll advise UIViewControllerTransitioningDelegate https://www.raywenderlich.com/110536/custom-uiviewcontroller-transitions
Comment: Look for a Carousel library :)
https://www.cocoacontrols.com/search?q=carousel
Answer: Based on the Denislava Shentova comment I found a good library that solves this issue.
For all people in the future and their work hours, I just took code from UPCarouselFlowLayout library and deleted some I didn't need.
Here is the code of a simple viewController that shows the following result:

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    // CollectionView variable:
    var collectionView : UICollectionView?

    // Variables asociated to collection view:
    fileprivate var currentPage: Int = 0
    fileprivate var pageSize: CGSize {
        let layout = self.collectionView?.collectionViewLayout as! UPCarouselFlowLayout
        var pageSize = layout.itemSize
        pageSize.width += layout.minimumLineSpacing
        return pageSize
    }

    fileprivate var colors: [UIColor] = [UIColor.black, UIColor.red, UIColor.green, UIColor.yellow]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.addCollectionView()
        self.setupLayout()

    }

    func setupLayout(){
        // This is just an utility custom class to calculate screen points
        // to the screen based in a reference view. You can ignore this and write the points manually where is required.
        let pointEstimator = RelativeLayoutUtilityClass(referenceFrameSize: self.view.frame.size)

        self.collectionView?.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        self.collectionView?.topAnchor.constraint(equalTo: self.view.topAnchor, constant: pointEstimator.relativeHeight(multiplier: 0.1754)).isActive = true
        self.collectionView?.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        self.collectionView?.heightAnchor.constraint(equalToConstant: pointEstimator.relativeHeight(multiplier: 0.6887)).isActive = true

        self.currentPage = 0
    }

    func addCollectionView(){

        // This is just an utility custom class to calculate screen points
        // to the screen based in a reference view. You can ignore this and write the points manually where is required.
        let pointEstimator = RelativeLayoutUtilityClass(referenceFrameSize: self.view.frame.size)

        // This is where the magic is done. With the flow layout the views are set to make costum movements. See https://github.com/ink-spot/UPCarouselFlowLayout for more info
        let layout = UPCarouselFlowLayout()
        // This is used for setting the cell size (size of each view in this case)
        // Here I'm writting 400 points of height and the 73.33% of the height view frame in points.
        layout.itemSize = CGSize(width: pointEstimator.relativeWidth(multiplier: 0.73333), height: 400)
        // Setting the scroll direction
        layout.scrollDirection = .horizontal

        // Collection view initialization, the collectionView must be
        // initialized with a layout object.
        self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        // This line if for able programmatic constrains.
        self.collectionView?.translatesAutoresizingMaskIntoConstraints = false
        // CollectionView delegates and dataSource:
        self.collectionView?.delegate = self
        self.collectionView?.dataSource = self
        // Registering the class for the collection view cells
        self.collectionView?.register(CardCell.self, forCellWithReuseIdentifier: "cellId")

        // Spacing between cells:
        let spacingLayout = self.collectionView?.collectionViewLayout as! UPCarouselFlowLayout
        spacingLayout.spacingMode = UPCarouselFlowLayoutSpacingMode.overlap(visibleOffset: 20)

        self.collectionView?.backgroundColor = UIColor.gray
        self.view.addSubview(self.collectionView!)

    }

    // MARK: - Card Collection Delegate & DataSource

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CardCell

        cell.customView.backgroundColor = colors[indexPath.row]
        return cell
    }

    // MARK: - UIScrollViewDelegate

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let layout = self.collectionView?.collectionViewLayout as! UPCarouselFlowLayout
        let pageSide = (layout.scrollDirection == .horizontal) ? self.pageSize.width : self.pageSize.height
        let offset = (layout.scrollDirection == .horizontal) ? scrollView.contentOffset.x : scrollView.contentOffset.y
        currentPage = Int(floor((offset - pageSide / 2) / pageSide) + 1)
    }

}

class CardCell: UICollectionViewCell {
    let customView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.layer.cornerRadius = 12
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.addSubview(self.customView)

        self.customView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        self.customView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        self.customView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true
        self.customView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1).isActive = true

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

} // End of CardCell

class RelativeLayoutUtilityClass {

    var heightFrame: CGFloat?
    var widthFrame: CGFloat?

    init(referenceFrameSize: CGSize){
        heightFrame = referenceFrameSize.height
        widthFrame = referenceFrameSize.width
    }

    func relativeHeight(multiplier: CGFloat) -> CGFloat{

        return multiplier * self.heightFrame!
    }

    func relativeWidth(multiplier: CGFloat) -> CGFloat{
        return multiplier * self.widthFrame!

    }

}

Note that there are some other clases in this code but temporarily you can run the whole code in the ViewController.swift file. After you test, please split them into different files.
In order tu run this code, you need the following module. Make a file called UPCarouselFlowLayout.swift and paste all this code:
import UIKit

public enum UPCarouselFlowLayoutSpacingMode {
    case fixed(spacing: CGFloat)
    case overlap(visibleOffset: CGFloat)
}

open class UPCarouselFlowLayout: UICollectionViewFlowLayout {

    fileprivate struct LayoutState {
        var size: CGSize
        var direction: UICollectionViewScrollDirection
        func isEqual(_ otherState: LayoutState) -> Bool {
            return self.size.equalTo(otherState.size) && self.direction == otherState.direction
        }
    }

    @IBInspectable open var sideItemScale: CGFloat = 0.6
    @IBInspectable open var sideItemAlpha: CGFloat = 0.6
    open var spacingMode = UPCarouselFlowLayoutSpacingMode.fixed(spacing: 40)

    fileprivate var state = LayoutState(size: CGSize.zero, direction: .horizontal)

    override open func prepare() {
        super.prepare()

        let currentState = LayoutState(size: self.collectionView!.bounds.size, direction: self.scrollDirection)

        if !self.state.isEqual(currentState) {
            self.setupCollectionView()
            self.updateLayout()
            self.state = currentState
        }
    }

    fileprivate func setupCollectionView() {
        guard let collectionView = self.collectionView else { return }
        if collectionView.decelerationRate != UIScrollViewDecelerationRateFast {
            collectionView.decelerationRate = UIScrollViewDecelerationRateFast
        }
    }

    fileprivate func updateLayout() {
        guard let collectionView = self.collectionView else { return }

        let collectionSize = collectionView.bounds.size
        let isHorizontal = (self.scrollDirection == .horizontal)

        let yInset = (collectionSize.height - self.itemSize.height) / 2
        let xInset = (collectionSize.width - self.itemSize.width) / 2
        self.sectionInset = UIEdgeInsetsMake(yInset, xInset, yInset, xInset)

        let side = isHorizontal ? self.itemSize.width : self.itemSize.height
        let scaledItemOffset =  (side - side*self.sideItemScale) / 2
        switch self.spacingMode {
        case .fixed(let spacing):
            self.minimumLineSpacing = spacing - scaledItemOffset
        case .overlap(let visibleOffset):
            let fullSizeSideItemOverlap = visibleOffset + scaledItemOffset
            let inset = isHorizontal ? xInset : yInset
            self.minimumLineSpacing = inset - fullSizeSideItemOverlap
        }
    }

    override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

    override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let superAttributes = super.layoutAttributesForElements(in: rect),
            let attributes = NSArray(array: superAttributes, copyItems: true) as? [UICollectionViewLayoutAttributes]
            else { return nil }
        return attributes.map({ self.transformLayoutAttributes($0) })
    }

    fileprivate func transformLayoutAttributes(_ attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        guard let collectionView = self.collectionView else { return attributes }
        let isHorizontal = (self.scrollDirection == .horizontal)

        let collectionCenter = isHorizontal ? collectionView.frame.size.width/2 : collectionView.frame.size.height/2
        let offset = isHorizontal ? collectionView.contentOffset.x : collectionView.contentOffset.y
        let normalizedCenter = (isHorizontal ? attributes.center.x : attributes.center.y) - offset

        let maxDistance = (isHorizontal ? self.itemSize.width : self.itemSize.height) + self.minimumLineSpacing
        let distance = min(abs(collectionCenter - normalizedCenter), maxDistance)
        let ratio = (maxDistance - distance)/maxDistance

        let alpha = ratio * (1 - self.sideItemAlpha) + self.sideItemAlpha
        let scale = ratio * (1 - self.sideItemScale) + self.sideItemScale
        attributes.alpha = alpha
        attributes.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1)
        attributes.zIndex = Int(alpha * 10)

        return attributes
    }

    override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        guard let collectionView = collectionView , !collectionView.isPagingEnabled,
            let layoutAttributes = self.layoutAttributesForElements(in: collectionView.bounds)
            else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset) }

        let isHorizontal = (self.scrollDirection == .horizontal)

        let midSide = (isHorizontal ? collectionView.bounds.size.width : collectionView.bounds.size.height) / 2
        let proposedContentOffsetCenterOrigin = (isHorizontal ? proposedContentOffset.x : proposedContentOffset.y) + midSide

        var targetContentOffset: CGPoint
        if isHorizontal {
            let closest = layoutAttributes.sorted { abs($0.center.x - proposedContentOffsetCenterOrigin) < abs($1.center.x - proposedContentOffsetCenterOrigin) }.first ?? UICollectionViewLayoutAttributes()
            targetContentOffset = CGPoint(x: floor(closest.center.x - midSide), y: proposedContentOffset.y)
        }
        else {
            let closest = layoutAttributes.sorted { abs($0.center.y - proposedContentOffsetCenterOrigin) < abs($1.center.y - proposedContentOffsetCenterOrigin) }.first ?? UICollectionViewLayoutAttributes()
            targetContentOffset = CGPoint(x: proposedContentOffset.x, y: floor(closest.center.y - midSide))
        }

        return targetContentOffset
    }
}

Again, this module was made by Paul Ulric, you can installed with cocoa.
Comment: great job creating this basic example Hugo!


Recortar foto ao gerar thumbnail php

Question: Tenho uma classe que gera thumbnail corretamente, porém ao enviar fotos na vertical, ela fica esticada. Como eu faria para dentro dessa classe eu recortar ou redimensionar a foto para que ela se encaixe nas dimensões do thumbnail?
<code>/**
* Cria thumbnail das imagens
* @return $diretorioThumb.$codificarFoto
* @param $foto
*/
public function gerarThumb($foto){

  $diretorioNormal = "produtos/";
  $diretorioThumb = "produtos/thumb/";

  $fotoDir = $diretorioNormal.$foto;
  list($largura,$altura) = getimagesize($fotoDir);

  $novaLargura = 240;
  $novaAltura = 165;
  $codificarFoto = $foto;

   list($arquivo,$extensao) = explode(".",$foto);

    if($extensao == "jpg" || $extensao == "jpeg" || $extensao == "JPG"){
      $miniatura = imagecreatetruecolor($novaLargura, $novaAltura);
      $imagem = imagecreatefromjpeg($fotoDir);
      imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $novaLargura, $novaAltura, $largura, $altura);
      imagejpeg($miniatura,$diretorioThumb.$codificarFoto,90);
    }
    if($extensao == "png"){
      $miniaturaPNG = imagecreatetruecolor($novaLargura, $novaAltura);
      $imagemPNG = imagecreatefrompng($fotoDir);
      imagecopyresampled($miniaturaPNG, $imagemPNG, 0, 0, 0, 0, $novaLargura, $novaAltura, $largura, $altura);
      imagepng($miniaturaPNG,$diretorioThumb.$codificarFoto,null,90);
    }
    return $diretorioThumb.$codificarFoto;
} // fim do método gerarThumb
</code>
Comment: Eu uso sempre essa biblioteca http://wideimage.sourceforge.net/
Aqui tem uns exemplos que ajuda http://blog.thiagobelem.net/redimensionando-imagens-automaticamente-com-o-php
Comment: Olá Fábio. Tentei usar essa biblioteca, porém dá o seguinte erro: **Fatal error: Cannot declare class WideImage_InvalidImageHandleException, because the name is already in use in**
Comment: Não tem como fazer isso diretamente no PHP sem necessidade de bibliotecas? VI que tem o imagecrop(), mas como se usa essa função?
Comment: Tem, mas pra que ter trabalho se já existe algo pronto.
Esse é o propósito de bibliotecas, legal você já adquirir esse hábito pois são boas práticas.
Mas se mesmo assim queres ter o trabalho, da uma olhadinha como funciona o código da biblioteca.
Answer: Consegui resolver baseado em cima dessa função, porém tem essa também para recortar:
<code>/**
* Cria thumbnail das imagens
* @return $diretorioThumb.$codificarFoto
* @param $foto
*/
public function gerarThumb($foto){

$diretorioNormal = "produtos/";
$diretorioThumb = "produtos/thumb/";

$fotoDir = $diretorioNormal.$foto;

list($largura,$altura) = getimagesize($fotoDir);
list($arquivo,$extensao) = explode(".",$foto);

if($extensao == "jpg" || $extensao == "jpeg"){
  if($largura > $altura){
      $novaLargura = 240;
      $novaAltura = 165;
      $miniatura = imagecreatetruecolor($novaLargura, $novaAltura);
      $imagem = imagecreatefromjpeg($fotoDir);
      imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $novaLargura, $novaAltura, $largura, $altura);
      imagejpeg($miniatura,$diretorioThumb.$foto,90);
  }
  if($altura > $largura){
    $wmax = 240;
    $hmax = 170;
    $quebrar = explode(".", $foto);
    $fileExt = end($quebrar);
    $this->recortar($fotoDir, $diretorioThumb.$foto, $wmax, $hmax, $fileExt);
  }
}if($extensao == "png"){
  $miniaturaPNG = imagecreatetruecolor($novaLargura, $novaAltura);
  $imagemPNG = imagecreatefrompng($fotoDir);
  imagecopyresampled($miniaturaPNG, $imagemPNG, 0, 0, 0, 0, $novaLargura, $novaAltura, $largura, $altura);
  imagepng($miniaturaPNG,$diretorioThumb.$foto,null,90);
}
return $diretorioThumb.$foto;
} // fim do método gerarThumb

/**
* Recorta a imagem
* Função retirada do site http://www.developphp.com/video/PHP/Crop-Thumbnail-Image-Function-Tutorial-jpg-gif-png
* @param $target, $newcopy, $w, $h, $ext
*/
public function recortar($target, $newcopy, $w, $h, $ext) {

    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;
    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){
    $img = imagecreatefromgif($target);
    } else if($ext =="png"){
    $img = imagecreatefrompng($target);
    } else {
    $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    if ($ext == "gif"){
        imagegif($tci, $newcopy);
    } else if($ext =="png"){
        imagepng($tci, $newcopy);
    } else {
        imagejpeg($tci, $newcopy, 90);
    }
} // fim do método recortar()
</code>

Recortar foto ao gerar thumbnail php


Does getting disconnected from an SSH session kill your programs?

Question: So, say I get disconnected from an SSH-session after I've started rsync or cp or any other command that can be long running. Does that command keep running until it's finished after I get disconnected or does it just get killed?
Always wondered this.
Comment: I just want to add to what has been said above that, if you find yourself in a situation when you need to put an already running process into `screen`, try [reptyr](https://github.com/nelhage/reptyr).
Comment: It will kill your programs. Very annoying if you're updating OS version from say Ubuntu 16.04 to 17.10 via SSH
Answer: Edit for 2016:
This Q&A predates the systemd v230 debacle. As of systemd v230, the new default is to kill all children of a terminating login session, regardless of what historically valid precautions were taken to prevent this. The behavior can be changed by setting KillUserProcesses=no in /etc/systemd/logind.conf, or circumvented using the systemd-specific mechanisms for starting a daemon in userspace. Those mechanisms are outside the scope of this question.
The text below describes how things have traditionally worked in UNIX designspace for longer than Linux has existed.

They will get killed, but not necessarily immediately. It depends on how long it takes for the SSH daemon to decide that your connection is dead. What follows is a longer explanation that will help you understand how it actually works.
When you logged in, the SSH daemon allocated a pseudo-terminal for you and attached it to your user's configured login shell. This is called the controlling terminal. Every program you start normally at that point, no matter how many layers of shells deep, will ultimately trace its ancestry back to that shell. You can observe this with the pstree command.
When the SSH daemon process associated with your connection decides that your connection is dead, it sends a hangup signal (SIGHUP) to the login shell. This notifies the shell that you've vanished and that it should begin cleaning up after itself. What happens at this point is shell specific (search its documentation page for "HUP"), but for the most part it will start sending SIGHUP to running jobs associated with it before terminating. Each of those processes, in turn, will do whatever they're configured to do on receipt of that signal. Usually that means terminating. If those jobs have jobs of their own, the signal will often get passed along as well.
The processes that survive a hangup of the controlling terminal are ones that either disassociated themselves from having a terminal (daemon processes that you started inside of it), or ones that were invoked with a prefixed nohup command. (i.e. "don't hang up on this") Daemons interpret the HUP signal differently; since they do not have a controlling terminal and do not automatically receive a HUP signal, it is instead repurposed as a manual request from the administrator to reload the configuration. Ironically this means that most admins don't learn the "hangup" usage of this signal for non-daemons until much, much later. That's why you're reading this!
Terminal multiplexers are a common way of keeping your shell environment intact between disconnections. They allow you to detach from your shell processes in a way that you can reattach to them later, regardless of whether that disconnection was accidental or deliberate. tmux and screen are the more popular ones; syntax for using them is beyond the scope of your question, but they're worth looking into.

It was requested that I elaborate on how long it takes for the SSH daemon to decide that your connection is dead. This is a behavior which is specific to every implementation of a SSH daemon, but you can count on all of them to terminate when either side resets the TCP connection. This will happen quickly if the server attempts to write to the socket and the TCP packets are not acknowledged, or slowly if nothing is attempting to write to the PTY.
In this particular context, the factors most likely to trigger a write are:

A process (typically the one in the foreground) attempting to write to the PTY on the server side. (server->client)
The user attempting to write to the PTY on the client side. (client->server)
Keepalives of any sort. These are usually not enabled by default, either by the client or the server, and there are typically two flavors: application level and TCP based (i.e. SO_KEEPALIVE). Keepalives amount to either the server or the client infrequently sending packets to the other side, even when nothing would otherwise have a reason to write to the socket. While this is typically intended to skirt firewalls that time out connections too quickly, it has the added side effect of causing the sender to notice when the other side isn't responding that much more quickly.

The usual rules for TCP sessions apply here: if there is an interruption in connectivity between the client and server, but neither side attempts to send a packet during the problem, the connection will survive provided that both sides are responsive afterwards and receiving the expected TCP sequence numbers.
If one side has decided that the socket is dead, the effects are typically immediate: the sshd process will send HUP and self-terminate (as described earlier), or the client will notify the user of the detected problem. It's worth noting that just because one side thinks the other is dead does not mean that the other is has been notified of this. The orphaned side of the connection will typically remain open until either it attempts to write to it and times out, or receives a TCP reset from the other side. (if connectivity was available at the time) The cleanup described in this answer only happens once the server has noticed.
Comment: Also, while it's not technically part of your answer, here's an interesting bit of trivia: you can use `kill -HUP` as root to force someone's terminal to hang up. You shouldn't do this without good reason. I get most of my mileage out of it when users leave shells running during maintenance and I need to unmount a filesystem that their shell is keeping open. If the user is connected but terminally idle, send the signal to their sshd process. Otherwise, if it's running inside of a terminal multiplexer, send it to the shell you want stopped. Only hang up the shell keeping you from working!
Comment: I'd also add the 'dtach' command to that list - it's sort of the opposite of screen/tmux in that it lets you attach multiple terminals to a single session, and is also great for prolonging a session, although it doesn't provide any means of replaying the recent history.
Comment: excellent explanation.  I feel more linuxey already!
Comment: `dtach` url is here: http://dtach.sourceforge.net/
Comment: @AndrewB, could you please elaborate on how "the SSH daemon process ... decides that your connection is dead"? And how can I know if the SSH daemon thinks/knows that the (which) connection is dead or not?
Comment: @Xiao Edited the answer to clarify, see the bottom. Beyond these generalizations, you will need to either consult the documentation or examine the source code for the product in question.
Comment: This is an impressive and well written answer.
Comment: Please clarify, tmux is work as expected (not killed by systemd)?
Comment: @mmv-ru Beyond the scope of my ability to answer. I have no idea what version of systemd you are running, how it has been built, or how it has been configured. [tmux refused to change themselves for systemd](https://github.com/tmux/tmux/issues/428), so my assumption is that it still gets killed unless your distro changed the default settings. (edit: As an example, [Fedora is currently overriding the default](https://bugzilla.redhat.com/show_bug.cgi?id=1357426).)
Answer: As other's have mentioned, once you disconnect from ssh anything running within it is gone.
As @Michael Hampton and others have mentioned you can use tools like tmux or screen to disconnect/reconnect to terminals without loosing their content (i.e. child processes).
Additionally you can put a process into the background using an ampersand & and then use the command disown to disassociate them with the current shell.
# start a command
% sleep 5000 &
[1] 3820

# check it
% jobs
[1]+  Running                 sleep 5000 &

# disown everything
% disown -a

# check it again (gone from shell)
% jobs
%

# but it's still running on the system
% ps -eaf|grep "[s]leep"
saml      3820 23791  0 00:16 pts/1    00:00:00 sleep 5000
%

Comment: Yes. See this U&L question for details: http://unix.stackexchange.com/questions/4034/how-can-i-disown-a-running-process-and-associate-it-to-a-new-screen-shell
Comment: Is it possible to reattach a terminal session to a `disown`ed process?
Answer: No, any programs still attached to the terminal, and not placed into the background with something like nohup, would be killed.
This is why there are virtual terminal solutions like tmux and the older screen which create sessions which continue running even if you are disconnected, and to which you can reattach later.


Spring Security without spring core?

Question: I have a really simple question, that I just can't find the answer.
If I want to use only Spring Security, do I need Spring core or any other dependency?
In this link, in the bottom I see only spring security jars as dependencies, but still I couldn't get it to work. I only got it to work when I used a lot more of spring jars (core, context, and more).
So, what are the minimal dependencies I need for using Spring Security? All I need is an authorization and authentication framework, and I want as little dependencies as possible.
Thank you!
Comment: You answered both of your questions.  No, you can't use Spring Security without Spring core.  You know you need core and context.  As for "more", keep adding until you don't get ClassNotFoundException.  That's the minimal set. Does Spring Security have a Maven project that pulls in your dependencies for you?
Comment: Check the [FAQ](http://static.springsource.org/spring-security/site/faq/faq.html#faq-what-dependencies) and the [reference manual](http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#appendix-dependencies).
Answer: For every spring extension you need to use Srping core, because every extension is build on top of spring core

Spring Security without spring core?


Could someone show me a simple example of something being proved unprovable?

Question: Could someone show me a simple example of something being proved unprovable?
Pretty much what the title says, I want to understand a proof of some statement being proved unprovable.
E: Please read properly the question before marking as duplicates, I'm asking for a proof of a statement being proved unprovable, not examples of unprovable/indecidable statements.
Comment: The sentence $\forall x\forall y(xy=yx)$ is neither provable nor refutable from the axioms of Group Theory. Proof:  There are groups that are Abelian, and groups that are not.
Comment: I don't understand how that's irrefutable, isn't it enough to provide a counter-example?
Comment: @YoTengoUnLCD: A refutation would be a proof that it is false from the axioms of group theory. In a very broad sense, the Continuum Hypothesis has the same nature with respect to ZFC. For ZFC has models in which it is true and models in which it is false. But Group Theory *by design* is incomplete, while the axioms of ZFC, or first order Peano Arithmetic are designed to be strong.
Comment: In Douglas Hofstader's "Gödel, Escher, Bach"  Godel numbering is used to create self referential propositions - he demonstrates incompleteness by forming the mathematical equivalent of "This statement is false"
Comment: http://math.stackexchange.com/questions/1052299/what-is-a-simple-example-of-an-unprovable-statement
Comment: @WW1 Technically, that is really Godel's creation. Hofstadter reiterates it in his book. Sorry, I know I'm being extremely pedantic.
Comment: @ColmBhandal: Almost certainly so, though there are some examples of (uninteresting) theories that prove their own consistency. But certainly the sketch of a proof I wrote would use something other than the axioms of group theory to prove the existence of the relevant models.
Comment: @Colm: The statement is $\forall x\forall y(x\cdot y=y\cdot x)$. Not "There are abelian groups".
Comment: @AsafKaragila I am a slow idiot. Of course! The *statement* resides in group theory. The *proof* (of unprovability) outside. Got it.
Comment: http://people.cs.uchicago.edu/~simon/RES/collatz.pdf
Comment: Here is a statement which is proved unprovable: $\exists n\in \mathbb N\colon n<0$.
Comment: @Victor The .pdf you linked appears to be corrupted.
Comment: I take it that you refer to a statement which can't be proved to be true OR false.
Comment: Quite strange. You may want to read about the Collatz conjecture, it's a tedious tease.
Comment: @AndréNicolas- the statement "There are groups that are Abelian, and groups that are not" must be only provable then *outside* the axioms of group theory? Is this true?
Comment: @Colm Bhandal: The axioms of group theory talk about the elements of a group; not about groups themselves. This statement is not expressible in the language of group theory to begin with.
Comment: @AsafKaragila in that case its sort of a cheat. I mean *any* statement that's not expressible in group theory is not provable in group theory, trivially. For example, $1 + 1 = 2$ can't be proved in group theory. Hmmm, a better example is needed I think.
Comment: @AsafKaragila Please review my edit.
Answer: If you are willing to take the completeness theorem for granted, then it can be quite easy.

If $T$ is a first-order theory, then $T\vdash\varphi$ if and only if $T\models\varphi$.

This means that in order to prove that $\varphi$ is unprovable from $T$, then we only need to exhibit a model of $T$ in which $\varphi$ is false.
For example, we can prove that as a field $\Bbb R\models\exists x(x\cdot x=1+1)$, but the Greek also proved that $\sqrt2$ is not a ratio of two integers, therefore $\Bbb Q\models\lnot(\exists x(x\cdot x=1+1))$. And so we proved that the theory of fields does not prove the existence of $\sqrt2$.
Andre suggested in the comments a similar example with group theory and the statement "multiplication is commutative".

Other even easier examples may include things like a language $\cal L$ with a single constant symbol $c$, and the empty theory. Then $\forall x(x=c)$ is not provable, since in any structure for $\cal L$ with more than one element $\exists x(x\neq c)$ is a true statement.
Or even without constants, just look at $\forall x\forall y(x=y)$.
Comment: Rob's right. You only need soundness, which is that provability over $T$ implies truth in all models of $T$. So your sentence cannot be provable over $T$ because it is not true in some model of $T$. And also your sentence is not disprovable since it is true in some model of $T$ and hence its negation cannot be proven, again by soundness. I am sure you know all this very well so you must have misinterpreted Rob's comment. =)
Comment: All you need here is soundness, not completeness: no sound theory of fields can prove $\exists x\cdot x^2 = 2$. That aside, I think this is very much the right answer to the OP's question.
Comment: My point was that your answer shouldn't mention completeness. It's just about soundness: (i) the first-order theory of fields is sound for fields; (ii) there are fields in which $\exists x\cdot x^2 = 2$ is false; hence (iii) $\exists x\cdot x^2 = 2$ is provably unprovable in the theory of fields. Maybe we can mop this up another day. Cheers.
Comment: You mean, once that you know that $\sqrt2$ is irrational?
Comment: No, I mean that there are fields in which $\exists x\cdot x^2 = 2$ is false, so no sound theory of fields can include that sentence.
Comment: So you do mean that once you know $\sqrt2$ is irrational.
Comment: No, I don't mean that. $\exists x \cdot x^2 = 2$ is false in $\mathbb{Z}/3\mathbb{Z}$. It's a sentence that is meaningful in every field but doesn't hold in every field. The statement that $\sqrt{2}$ is irrational can't be expressed in the first-order language of a field.
Comment: Right. But before you are taught that $\Bbb{Z/3Z}$ is a field, and that in fact $2$ is not a square there, you are taught that $\sqrt2\notin\Bbb Q$. I know that being irrational cannot be expressed in the first-order language of fields, I'm not sure why you brought that up. But I feel that this discussion has circled enough through the same point, so I bid you adieu and good night.
Comment: Maybe the explanation for this odd cross-talk is just that some people (like Asaf Karagila in the original answer) think of "completeness" as a biconditional ("provable iff valid"); whereas other people think of it as only one direction ("provable if valid") to be complemented by soundness.  Both usages have their merits...
Answer: Consider statement, $P$:
"It is impossible to prove statement $P$."
Suppose it's true. Then, as per $P$, it's impossible to prove statement $P$, even though it's true.
Suppose it's false. Then, as per $P$, it's possible to prove statement $P$, even though it's false.
Asserting either the truth or the falsehood of the statement leads to a contradiction.
The statement appears to be impossible to prove. (Although, perhaps we shouldn't come right out and say it.)
Comment: You can have a statement which talks "about itself", but it's not at all simple to do so. In general $P$ is not part of the language, but rather a sentence in the language. And in order to talk about statements you need things like Godel numbering and so on. So some nontrivial amount of information needs to be established first.
Comment: My point is that your example is either wrong, or misleading when you dress it as "simple".
Comment: Indeed. The OP is looking for a simple example. I don't know if this is too simple for their needs. Your response is at least mathematical, which may meet the OP requirement.
Comment: Hmm... I'll have to consider that


How to smart authenticate login in laravel 5.3

Question: How to smart login in laravel???
How to login so that any user login system do not allow the same user at the same time, another place after logon how to do.
Comment: Welcome to StackOverflow. Please provide a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example showing the actual code you are trying to use and explain what is not working in it for you.
Answer: Please go to
vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php app/MyAuthAndRegistersUsers.php
than flow it's
<code> public function postLogin(Request $request)
    {
        $this->validate($request, [
            'username' => 'required', 'password' => 'required',
        ]);

        $credentials = $request->only('username', 'password');

        if ($this->auth->attempt($credentials, $request->has('remember')))
        {
            return redirect()->intended($this->redirectPath());
        }

        return redirect($this->loginPath())
            ->withInput($request->only('username', 'remember'))
            ->withErrors([
                'username' => $this->getFailedLoginMessage(),
            ]);
    }
</code>
Your can read more here
    https://laracasts.com/discuss/channels/requests/laravel-5-middleware-login-with-username-or-email


Refreshing a block using AJAX

Question: I am trying to apply the example from [the Flag API page][1] to refresh a block dynamically via AJAX. I am looking into customised jQuery code because my block is created via a module, not a view.
I have implemented the callback in the .module file and it works. It is when I try to copy blockExistsOnPage() where I fail. It talks about a component module which is necessary for the execution of the code, but this module is obsolete for drupal 7. I think that I stumble on the definition of var domId. This is my JavaScript code.
(function ($) {
 $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
   alert('Object #' + data.contentId + ' (of type ' +
   data.contentType + ') has been ' + data.flagStatus +
   ' using flag "' + data.flagName + '"');

    if (data.flagName == 'myflag') {

        if (blockExistsOnPage('mymodule', 'mymodule_blockid')) {
            refreshBlock('mymodule', 'mymodule_blockid');
        }
    }
  });

// Attempt at refreshing the block
function blockExistsOnPage(module_name, block_id) {
  var domId = module_name + '/' + block_id;
  return $('#'+domId).length != 0;
}

function refreshBlock(module_name, block_id) {
  var domId = module_name + '/' + block_id;
  $.get(base_url + 'node/' + $nodeid + '/' + block_id, null, function(newHtml)  {
    // Replace the old block with the new one.
    var domElement = $(newHtml).insertAfter('#'+domId);
    $('#'+domId).remove();
    if (Drupal.attachBehaviors) {
       Drupal.attachBehaviors(domElement);
    }
 });
}

edit: I am trying to use a $.ajax request instead. It seems cleaner, but I am struggling to get my relative address of the type node/[nid]/module_name/block_id. Should I modify the block_id in the menu hook? Or should I find a way to create a url in the jquery:
module hook menu:
    function get_involved_menu() {
// Ajax Callback. Returns updated content of block
$items['block_id'] = array (
 'title' => 'Content of module_name block',
 'page callback' => 'module_name_createcontent',
 'access arguments' => array ('access content'),
 'type' => MENU_CALLBACK,
 );

return $items;
}

jquery:
    $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  $.ajax({
     type: "POST",
     url: 'module_name/block_id',
     success: function (data){
        $('div.get-involved-divblock').html(data);
     }
   });
 });

the code below returns an empty block. If I am on node '57', and I put instead
 url: '57/module_name/block_id',

Then it returns the content. How can I make it a relative path? How do I obtain the node id in the jquery?
Comment: The domID here refers to the *unique* ID of the block. This block ID is generated from the module_name + block ID. if your module defines the block, check the html source to find the `id` attribute of the block.
Comment: Hello Ayesh,in my case, the module is 'get_involved' and the block id is 'get_involved_block', which I had defined. I do not seem to get anything out of the 'return $('#'+domId).length != 0;' line. Is my command ok? I am no expert in jQuery...
Comment: The problem is that node/[nid]/[block_id] is not a valid path, in plain Drupal; that is probably something the missing module provided.
Comment: Thanks Kiamlaluno. I am looking into getting the right path...
Comment: I have used GUE's answer from this page: http://drupal.stackexchange.com/questions/78662/how-to-get-the-drupal-node-id-from-within-jquery-javascript, and it loads something in my block. But currently, it is loading the whole page! Not just my block...
Answer: depending on how your module is setting up the block, you could look into Block Refresh:

Block Refresh allows an administrator to configure a block to refresh
  it's content via 3 different methods: automatically via a timer (eg
  every 30 seconds) , manually via a 'refresh' link, and once on page
  load.
Block Refresh uses jQuery/AJAX so the refresh happens
  "behind-the-scenes".
Block refresh can be handy to serve fresh content in certain blocks on
  otherwise cached pages. You can opt to bypass drupal's cache for the
  refresh callbacks for each block.

Edit
I just ran into this exact problem and developed a simple little approach that works nicely:

using Block Refresh

set up each of the blocks you want to refresh as manual - this would normally cause a link to appear in each block allowing a click refresh

create some css to hide the ugly links:
.block-refresh-button
{
    display:none;
}

then add a simple jQuery click to force block refresh to do all the work for you - this can be modified appropriately as necessary:
jQuery(".flag-wrapper").click(function()
{
    jQuery(".block-refresh-button").each(function()
    {
        jQuery(this).click();
    });
});

I found this will refresh ALL blocks on the page set up with block refresh, including Views.
Comment: Thanks Geoff,I tried that module, but it does not allow to trigger a refresh based on a flag event.
Comment: I added an edit

Refreshing a block using AJAX


Spartacus Multisite support

Question: I am trying to add Multisite in my Spartacus application. I have two domain names (let's say abc.in and xyz.in). Whenever I hit abc.in it should redirect to abc.in/electronic-spa/en and while hitting xyz.in it should redirect to xyz.in/apparal/en.
How to achieve this using MultiSite configurations in Spartacus?
Comment: Have you seen https://sap.github.io/spartacus-docs/automatic-context-configuration/?
Comment: Yes. I refer to that link. But I didn't get a clear idea of how to do it with the different domain names and multiple sites. Kindly help me to resolve this.
Comment: Kindly help me to do it for multiple sites with different domains.
Answer: Multisite works with the following mechanism:

Multiple sites (BaseSite) are setup in the commerce backend. Each site might have a custom product and content catalog, but it's quite flexible to mix and match it all together. Customer are using a variety of combinations to end up with the actual site/content that they need for a specific market.
Almost all API endpoints have the site.uid as part of the url. The API therefor can easily understand which content to return.
If the same storefront application (Spartacus in this case) should use a single API, the storefront actually must know the site.uid, so it can construct the right API endpoint. The storefront would normally not know this unless you hard-code it.
The commerce platform comes with a capability to link the storefront URL to the basesite, by using so-called regular expressions. A basesite can have multiple regex to configure to which storefront url the base site belongs. This is a very old mechanism in the commerce backend, that has been used in the (java) CmsSiteFilter. In spartacus we cannot use this filter, but we're using a similar filter mechanism. The same regex patterns are used, to filter the site, but it's done client side.

What you'd need to do to get it working:

use minimal 1905 version on the backend (otherwise the /basesites endpoint is not available)
setup your local hosts file, to mimic domain based URLs locally
setup the basesite regex (urlPatterns) so that it will match the actual domain URLs
run your Spartacus app with the --disable-host-check flag, so that it will listen to any local domain.

Spartacus Multisite support


How can two domains link to different sites of one website?

Question: I have a website and two domains. Domain one should as usually link to the webpage. The second domain should link to a subpage of the website:
 www.domain1.com --> index.html (and all other pages)
 www.domain2.com --> otherPage.html

I found out that I should enable mod_rewrite and could add some rewrite rules in the .htaccess-file. How can I do this?
Any suggestions are really much appreciated.
Answer: Add these rules to the htaccess file in your document root:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.domain2\.com$ [NC]
RewriteRule ^$ /otherPage.html [L]

Comment: hi Jon Lin. Thanks for your post. Unfortunately, I get an error 500 if I call www.domain2.com. I adapted the domain and filename. Unfortunately, I don't know why as I also don't really understand what those three lines do. Do you have an idea what my mistake is? What does the second/third line exactly do? Thank you!
Comment: @casaout sorry, left out a `$`
Answer: Jon Lin's post helped me to find the working answer:
RewriteEngine On
RewriteCond %{HTTP_HOST} www.domain2.ch$ [NC]
RewriteRule ^index\.htm$ /otherPage.html [PT]


Error in Herstein's "Topics in Algebra", zero ring has characteristic $1$ which is not prime

Question: I was trying to prove the following statement:
"If an integral domain has a finite characteristic then the characteristic of the integral domain is a prime number"
This made me look at the definition of an integral domain, as given in the book, "Topics in Algebra " by I.N Herstein (2nd Edition) in Chapter -3 (Ring Theory) page number-126. The definition is as follows:

If $R$  is a commutative ring, then $a\neq 0\in R$ is said to be a
zero-divisor if there exists a $b\neq 0\in R,$ such that $ab=0.$
A commutative ring is an integral domain if it has no zero-divisors.

Later in the book, on page number-129, the definitions of the characteristic of an integral domain are given as:

Definition: An integral domain $D$ is said to be of characteristic $0$ if the  relation $ma = 0,$ where $a\neq 0$ is in $D,$ and where $m$ is an integer, can hold only if $m = 0.$
The ring of integers is thus of characteristic $0,$ as are other familiar rings such as the even integers or the rationals.
Definition: An integral domain $D$ is said to be of finite characteristic if there exists a positive integer $m$ such that $ma = 0$ for all $a\in D.$
If $D$ is of finite characteristic, then we define the characteristic of $D$ to be the smallest positive integer $p$ such that $pa = 0$ for all $a\in D.$

The problem is with a remark that followed these definitions above. The remark was:

It is not too
hard to prove that if $D$ is of finite characteristic, then its characteristic is a prime
number.

Acccording to the definition of an integral domain as given in the book, the ring $R=\{0\}$ i.e containing only the zero element is also an integral domain.
Now, we note that, $m.0=0$ for any integer $m.$ So, $R=\{ 0 \}$ is not of characteristic zero. But, $R$ has a finite characteristic. The smallest positive integer that $m$ can be, in this case is $1.$ But $1$ is not a prime number. So, the thing given in the remark is false, because, even $R$ is an integral domain with a finite characteristic, the characteristic of $R$ is not a prime, and neither is it a composite number.
But nearly every where, I have found the statement:
"If an integral domain has a finite characteristic then the characteristic of the integral domain is a prime number"
true in general. This is why, I think that some definition in the book might be misleading or better say incorrect such that it contradicts such well- established statement.
Any help regarding this issue will be highly appreciated.
Comment: Some books require that rings have a distinct 1, so that there is no $0$ ring. This is just a matter of convention. Check where your text defines rings.
Comment: It's also common to say that integral domains must have a distinct $1$. Check your book's definition of integral domains. In any case, if this is an error, it's not a serious one. This is the one and only exception to the oft-cited fact that finite characteristics are prime.
Comment: @CharlesHudgins Even in the context of unital rings, there is still a zero ring: you would need an additional axiom $0\not=1$ to rule this out. (More generally, any purely equational theory - such as the theories of groups, unital rings, and non-unital rings, but not the theory of fields - has a one-element model.) Bringing things back to the OP, in my experience this axiom (+ the existence of 1 in general, if we're working non-unitally) is part of the definition of integral domains.
Comment: @CharlesHudgins Ok, but in this book, the author does not require that the ring must have a unit element. They even mention it explicitly. So, they are allowing zero rings.
Comment: @NoahSchweber that's why I edited my comment to say *distinct* 1. I probably could have been clearer.
Comment: @CharlesHudgins Do some texts actually require that rings have a distinct 1? I've never seen that before.
Comment: @CharlesHudgins I wrote the whole definition of what an integral domain is, word-by-word in the OP. So, I checked it throughly before posting :) So, do you suggest to treat this error as an exception?
Comment: Meanwhile, Lehmer is said to be the last major mathematician who referred to $1$  as a prime. Still, the statement " $1$  is not a prime"  is not absolute
Comment: @ThomasFinley Sorry I missed it because it was briefer than I was expecting. I still might not insist on calling it an error. The $0$ ring is so problematic that "except the $0$ ring" sometimes goes without saying. But yes, it is just an exception.
Comment: @NoahSchweber maybe not. I think I was thinking of how some books say that integral domains must have a distinct $1$.
Comment: @CharlesHudgins Ok, I will then take the whole issue just arose because the phrase "except the zero ring" was not written. I think this is the best approach to handle these sort of things, isn't it?
Comment: I read the first bit of the title in the "unexpected item in the bagging area" voice.
Comment: @NoahSchweber: In Abstract Algebra by Herstein, he does not require rings to have an identity element; however, he defines a ring with unit to be a ring with a multiplicative identity $1$ such that $0\neq 1$. (I think this is a very poor convention, but it does go to show how little the terminology in ring theory has been standardised...)
Answer: Typically, an integral domain is defined to additionally require that $0 \neq 1$.
Another way to express this requirement is as follows. For all $n \in \mathbb{N}$, for all sequences $a_1, \ldots, a_n$, if the product $a_1 \cdots a_n = 0$ then there is some $i$ such that $a_i = 0$. The case $n = 0$ is precisely saying that $0 \neq 1$. For if we have $1 = 0$, that's the same as saying the empty product is $0$. But there is no $a_i$ at all that could equal $0$.
If you drop the requirement $0 \neq 1$, the above Lemma about finite products only applies when $n \geq 1$.
Comment: @QiaochuYuan This is actually the same sort of logic for why local rings require that $0 \neq 1$. It turns out that the local ring condition is equivalent to the following: for all finite sequences $a_1, \ldots, a_n$, if $a_1 + \cdots + a_n$ is a unit, then some $a_i$ is a unit. There are a lot of similar things across mathematics - for instance, why the whole space is open in topology.
Comment: Oh, this is nice!
Answer: As has been discussed in the comments, there is this minor annoyance that one way or the other you need to exclude the zero ring from the definition of an integral domain. One way to say this is that you want to define integral domains in such a way that the integral domains should be exactly the subrings of fields (so that integral domains always have fields of fractions), which the zero ring isn't. (One way or the other you also need to exclude the zero ring from the definition of a field.)
Comment: @Thomas: yes, that's what I just said.
Comment: Should I define that the zero ring is not an integral domain? This is because as we see if we consider zero ring as an integral domain it creates some problems like the one in the OP.


Passing an object from view to controller

Question: I want to add new message to database from my .jsp inputs via controller. I tried to just create new object of message in controller and put it in database and it works fine. But when I try to do it using inputs i receive error like this:
SEVERE [http-nio-8080-exec-2]org.springframework.web.servlet.tags.form.InputTag.doStartTag Neither   BindingResult nor plain target object for bean name 'message' available as  request attribute
 java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'message' available as request attribute

My code:
@Controller
public class DemoController {

@Autowired
UserService userService;

@Autowired
MessageService messageService;

@PostMapping("/messages/sendNewMessage")
public String sendNewMessage(@ModelAttribute("message") MessagesEntity tempMessage) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    tempMessage.setFromUsername(userService.getUser(auth.getName()));

    messageService.sendNewMessage(tempMessage);
    return "redirect:/messages";
}
}

JSP here
<form:form action="sendNewMessage" modelAttribute="message" method="POST">

            Username:
            <form:input path="toUsername" />

            Subject:
            <form:input path="subject" />

            Content:
            <form:input path="content" />

            <input type="submit" value="Send" class="save" />

</form:form>

Answer: you are using action url as sendNewMessage in jsp view but in the controller, it is /messages/sendNewMessage.
Comment: Yes, you're right, my bad. I've tried many things before and forgot to change it. After the change, the problem is the same.
Comment: @PaulSmith
I tried your code, just  with simple text element removing table attribute with input fields i.e  ``  and other two. Everything just works fine with modelAttribute[** by correcting url**]. What I can suggest more is you can parse the table data  if you want to submit a table data or submit by ajax call. That would be much easier.
Comment: I think I know where the problem may be. "toUsername" actually is not a plain text, but it's User entity. Anyway I don't know how to get User entity by username in jsp file.
Answer: You need to put MessagesEntity object in ModelAttribute.
Either define the ModelAttribute while loading the form page like below.
@RequestMapping(value = "/", method = RequestMethod.GET)
public String messageForm(Model model) {
    model.addAttribute("message", new MessagesEntity());
    return "messageFormPageName";
}

or Put below method in the controller which will be common for complete controller so ModelAttribute will be available always.
@ModelAttribute("message")
public MessagesEntity createModel() {
    return new MessagesEntity();
}


Stacking menu items under eachother with scss and a slider under it

Question: I got a menu, but I want submenus to be stacked under it.
I tried, but all the menu items were in the same spot.
Anyone know what to do?
My jsfiddle:
http://jsfiddle.net/aLhPr/
I got a slider under the menu, so it needs to be on top of the slider.
My scss:
#menu {
  height:48px;
  font-size: 15px;
  font-family: $myriad;
  color: $white;
  background-color: $lightpurple;
  border: 1px solid $lightpurple;
  ul {
    margin-left: -40px;
    display:block;
  }
  li {
    display: inline;
    padding: 15px;
    &:hover {
      background-color: $darkpurple;
      padding: 15px;
    }
  }
 a {
    color: $white;
    text-decoration:none;
    &:hover{
    color: $lightgray;
    }
        i {
            font-size:9px;
            &.icon{
                font-size:17px;
            }
        }
    }
}

Thanks
Answer: I'm unsure if this is exactly what you wanted. But I created a fiddle where you have submenu items on your first menu item(Leden) by using position: absolute on the submenu items.
JSFIDDLE
Note that I also moved your A tags so they're inside of the LI tags. This is because having them surrounding the LI tags is invalid HTML.


Is there a function $f \gt 0$ such that $\int f dx=0$?

Question: If $$f \ge 0$$, then $$\int f dx \ge 0$$.
There is a function such that
$$f \gt 0$$ but $$\int f dx=0$$?
Comment: What's your domain of integration?
Comment: Oh sorry.A domain is closed interval [a,b]
Comment: Then such function doesn't exist. You can find a proof below. You can also argue it by using the fact $f$ is Riemann integrable $\iff$ it's bounded and continuous almost everywhere.
Comment: Thank you for commet. Can I do this without measure theory??
Answer: If you choose your domain of integration be a measure zero set, then any Lebesgue integrable (in particular Riemann integrable) function has zero integral.
If you consider Riemann integrable function on $[a,b]$ with  $a<b$, then it's not possible, see a proof here.


Initialization of an object of class/struct

Question: When trying initialize an object for MyClass, I saw these two methods are used:
MyClass a;
MyClass a{};

Both cases seem to work fine, but I am wondering is there a better practice that one should use which in certain scenarios?
Comment: Without having constructor arguments, there's absolutely no difference.
Comment: What is `MyClass`? The effect is actually different for built-in types or classes without explicit constructors.
Comment: I believe `MyClass a{};` will zero initialize `a` in some cases where as `MyClass a;` won't. It depends on what `MyClass` is.
Comment: @πάνταῥεῖ this is not true for all types.
Comment: @FrançoisAndrieux not zero-initialize, but value-initialize it members.
Comment: @SergeyA Ah, yes, I see. The question needs more context though.
Comment: @SergeyA I was thinking specifically of non-class types where value initialization delegates to zero initialization.
Answer: There is a subtle different between MyClass a; and MyClass a{};.  If Myclass is a fundamental type or an aggregate then
MyClass a;

will leave  a's sate/members uninitialized while
MyClass a{};

will value initialize a's state/members.
If Myclass is neither of the above then they will have the same behavior.
Comment: Just add a possibility of `using MyClass = int` and we will have a complete answer.
Comment: @SergeyA Updated.


Efficiently find $x(k)$ where $x$ is given by $Ax=b$ and $A$ is tridiagonal

Question: Say $A$ is a $n\times n$ ($n$ odd) real matrix that is tridiagonal (but need not be symmetric). What is the most efficient way to compute the value of $x(\frac{n+1}{2})$ (informally, the 'middle value') where $Ax=b$?  No assumptions are made on $b$.  I am already familiar with tridiagonal solvers, so the part of the problem to focus on is obtaining the necessary values of $x$.
So far my code uses $x=A\backslash b$ and then just grabs the needed value, which is pretty fast in MATLAB.  However, I feel like there might be a really nice trick here.
BONUS:
The thing I REALLY want is the answer for when $A$ is 'block tridiagonal' with block sizes $m$ and I want the middle $m$ values of $x$.  ie. in MATLAB speak if $A$ was $3m\times 3m$  I want $x((m+1):2m)$
Answer: What you looking for is a Thomas algorithm which is a simplified form of a Gaussian Elimination or if you want LU decomposition.
Matlab looks fast because Matlab identifying such special cases and call in such case to a very effective solver for banded-matrices. This solver is little bit more general then Thomas algorithm.
The very rough idea is that you know that you don't need to run over all matrix entries but only from the rightest to the leftest diagonal entry in each row.
Edit: to asnwer the added "BONUS" question
In order to retrieve specific entry of the x=A\b, given that only $\Theta(1)$ such values are required one could think about a Cramer's rule. However, using this method would be inefficient, since one need to compute at least $2$ determinants, which is briefly $O(n^3)$ operations. For a tridiagonal matrix one could find a determinant very fast, at only $O(n)$, see here.
However, you talking about retrieving $m=O(n=3m)$ values, which by Cramer's rule would mean $m+1$ determinants, so $O(mn)$. Thus, using Thomas algorithm is much more efficient, since it require $O(n)$ computational steps only.
Note that your problem cannot be solved faster then $O(n)$ since you have $m=O(n)$ unknowns. In the best situation you could improve a constant hidden under the sign of $O$ which isn't too big ($\approx 9m$?).
http://www.sciencedirect.com/science/article/pii/S0377042703007726
Comment: This is nice, but doesn't help us obtain particular values of $x$.


Customizing SimpleCaptcha

Question: We're using SimpleCaptcha http://simplecaptcha.sourceforge.net/ to creating a captcha in our registration form (running on Tomcat)
We create the captcha using:
Captcha captcha = new Captcha.Builder(300, 57).build();

and the captcha is displayed as follows:

But when I add more options to the captcha such as Captcha captcha = new Captcha.Builder(300, 57).addNoise().build();, it's still displayed in the same way without the noise. I tried more options but still get the same results.
Does anyone know why this is happening please?
Thanks,
Kurt
Answer: I tried the code above (with java 1.6 version) and it produces nothing. The reason is that you don't have .addText(). (I would have written this as a comment but I don't have enough reputation for it). This suggests to me that your code above isn't your actual code, maybe you forgot something when posting.
Here's what I use that works:
public class MyCaptchaServlet extends SimpleCaptchaServlet
{
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        Captcha captcha = new Captcha.Builder(120,40).addText().addBorder().gimp().addBackground(new GradiatedBackgroundProducer()).build();

        CaptchaServletUtil.writeImage(response, captcha.getImage());

        request.getSession().setAttribute(Captcha.NAME, captcha);
    }
}

Adding .addNoise() just before .build() does show the noise.

Customizing SimpleCaptcha


Verificar e alterar atributos de uma coluna a partir de uma lista com R

Question: Preciso substituir os dados de uma coluna em uma tabela se eles não estiverem contidos numa lista especificada pela string "Não Informado"
Tentei esse comando:
jan_mar$Bairro[which(!(bairros_cidade)] = "Não Informado"

Também tentei:
jan_mar$Bairro[jan_mar$Bairro != bairros_cidade] = "Não Identificado"

Com este ultimo comando a resposta foi:
"Warning message:
In jan_mar$Bairro != bairros_cidade :
comprimento do objeto maior não é múltiplo do comprimento do objeto menor"
E o valor retornado de "Não Informado" foi de 15112, muito acima dos 795 obtidos a partir do calculo manual das inconsistências
Com nenhuma deles obtive o resultado desejado
library(xlsx)
library(tidyverse)
library(data.table)

cursor1 = read.xlsx("Estácio - Vacinação COVID Jaraguá do Sul - Jan a Mar.2021.xlsx", sheetIndex = 1)
cursor2 = read.xlsx("Estácio - Vacinação COVID Jaraguá do Sul - Jan a Mar.2021.xlsx", sheetIndex = 2)

jan_mar = merge.data.frame(cursor1, cursor2, all = TRUE)

bairros_cidade = c("Agua Verde", "Aguas Claras", "Amizade", "Barra do Rio Cerro", "Barra do Rio Molha", "Boa Vista",
                   "Braço do Ribeirão Cavalo", "Centenario", "Centro", "Chico de Paulo", "Czerniewicz", "Estrada Nova",
                   "Ilha da Figueira", "Jaragua 84", "Jaragua 99", "Jaragua Esquerdo", "João Pessoa", "Nereu Ramos",
                   "Nova Brasilia", "Parque Malwee", "Rau", "Ribeirão Cavalo", "Rio Cerro I", "Rio Cerro II",
                   "Rio da Luz", "Rio Molha", "Santa Luzia", "Santo Antonio", "São Luis", "Tifa Martins", "Tifa Monos",
                    "Tres Rios do Norte", "Tres Rios do Sul", "Vieira", "Vila Baependi", "Vila Lalau", "Vila Lenzi",
                   "Vila Nova")

jan_mar$Bairro[which(!(bairros_cidade)] = "Não Informado"

jan_mar$Bairro[jan_mar$Bairro != bairros_cidade] = "Não Identificado"

table(jan_mar$Bairro)

Answer: Como não incluiu uma amostra dos seus dados, vou usar exemplos genéricos.
R é voltado para operações vetoriais. O operador == atua elemento a elemento:
a <- 1:3
b <- 3:1

a == b
#> [1] FALSE  TRUE FALSE

No caso de vetores com comprimentos diferentes, o resultado será um vetor lógico com o maior comprimento. Se o comprimento menor for múltiplo do maior, será reciclado. Se não, retornará FALSE para as posições sem equivalente, juntamente com um aviso:
c <- c(1,2,1,3)
d <- 1:2

c == d
#> [1]  TRUE  TRUE  TRUE FALSE

c == a
#> [1]  TRUE  TRUE FALSE FALSE
#> Warning message:
#> In c == a : longer object length is not a multiple of shorter object length

Para comparar se os elementos de um vetor estão inclusos entre os elementos de outro, independente de posição, use o operador %in%:
x <- LETTERS[1:5]
y <- LETTERS[2:3]

x %in% y
#> [1] FALSE  TRUE  TRUE FALSE FALSE

x[!x %in% y] <- "X"

x
#> [1] "X" "B" "C" "X" "X"

No seu caso:
jan_mar$Bairro[!jan_mar$Bairro %in% bairros_cidade] <- "Não Informado"


If $f$ is differentiable at $a$, exists $M,\varepsilon>0$ such that $|v|<\varepsilon\Rightarrow (a+v\in U\text{ and }|f(a+v)-f(a)|\leq M|v|)$

Question: Let $U\subset\mathbb{R}^m$ be a open set and $f:U\to\mathbb{R}$ differentiable at $a\in U$. How to prove that there exists $M>0$ and $\varepsilon>0$ such that, if $|v|<\varepsilon$, than $a+v\in U$ and $|f(a+v)-f(a)|\leq M|v|$?
Thanks.
Comment: Right. After 60+ questions, I think we can ask you to **add your thoughts** about the questions you ask.
Comment: Then we've got a problem ([Houston](http://en.wikipedia.org/wiki/Houston,_We%27ve_Got_a_Problem)): anybody moderately familiar with the definition of a differential should have an idea (even false) of something to try (and perhaps this something will fail, but this is no big deal). If you have no idea whatsoever about what is happening, how to write an answer that will help you? To begin with, what is the meaning of "$f$ is differentiable at $a$"? (Unrelated: why did you delete your previous comment?)
Comment: @Did Sorry. I have no idea how to solve it.
Comment: @Did "how to write an answer that will help you?" answer: in the following link there are more then 50 examples http://math.stackexchange.com/users/70305/perguntador. (I deleted the previous comment because I think the last looks better).
Comment: Surely you realize that your last comment sounds awfully like "I do not care about the rules of the site and I will not follow them as long as I get answers to my homework questions simply by copying them here".
Comment: @Did You are wrong (because do my homework is not my aim here), but seems right (because the most of my questions has no comment about what I tried). In the next questions, I will follow the rules of the site. Ok? Sorry for my comments and thanks for your help.
Answer: I'll give it a try to help you out. If someone finds some mistake I didn't see, please correct me.
Since $f : U \to \Bbb R$ is differentiable at $a$, there is a linear transformation, namely the derivative $Df(a) : \mathbb{R}^n \to \mathbb{R}$, such that for every $v$ with $a+v \in U$:
$$\lim_{v\to 0}\frac{|f(a+v)-f(a)-Df(a)(v)|}{|v|}=0$$
By the triangle inequality we have:
$$\frac{|f(a+v)-f(a)-Df(a)(v)|}{|v|}\leq \frac{|f(a+v)-f(a)|+|Df(a)(v)|}{|v|}$$
Now, by the definition of limit, we can select $r > 0$ greater than the right hand side of the above inequality, and there will be $\varepsilon_1 >0$ such that if $|v|<\varepsilon_1$, then:
$$\frac{|f(a+v)-f(a)-Df(a)(v)|}{|v|}<r$$
We must assure yet that $a+v \in U$. So, since $U$ is open there is some ball of radius $\varepsilon_2$ centered at $a$ contained in $U$. Thus, if $a + v = b$, if $|v| = |b-a| < \varepsilon_2$ we are assured that $a+v \in U$, so we take $\varepsilon = \min\{\varepsilon_1, \varepsilon_2\}$ and $a+v \in U$ and in the same time, we will have the desired inequality. So supposing $|v| < \varepsilon$ we will have:
$$\frac{|f(a+v)-f(a)-Df(a)(v)|}{|v|}\leq \frac{|f(a+v)-f(a)|+|Df(a)(v)|}{|v|} < r$$
And thus $|f(a+v)-f(a)|<r|v|-|Df(a)(v)|$. Now, since $Df(a)$ is linear, there is $k$ such that $|Df(a)(v)|\leq k|v|$ and hence if $|v|<\varepsilon$, we have $|f(a+v)-f(a)|<M|v|$ where $M=r-k$, showing that there is $\varepsilon$ and $M$ with $|f(a+v)-f(a)|<M|v|$ as desired.
Answer: Recall if $f:U\to\mathbb{R}$ is differentiable then for $\|h\|<\delta$ (choose $h$ small neough that a ball fits inside $U$ which can be done since its open)
$\frac{|f(x+h)-f(x)-Df_{x}(h)|}{\|h\|}<\epsilon$.
So by reverse triangle inequality and multiplying by $\|h\|$
(i.e $|f(x+h)-f(x)|-|Df_{x}(h)|\le|f(x+h)-f(x)-Df_{x}(h)|$ and $|f(x+h)-f(x)|-|Df_{x}(h)|<\epsilon\|h\|$)
we get
$|f(x+h)-f(x)|<|Df_{x}(h)|+\epsilon\|h\|\le(\|Df_{x}\|+\epsilon)\|h\|=M\|h\|$. Now take $x=a$, choose a direction, $v$, for $h$ (that is take $h=v$ for $v$ in the $\delta$ ball about $0$ from before). $M>0$ being the sum of two non-negative numbers.


Como resetar a propriedade DataSource de um DataGridView e não apagar as colunas do Cabeçalho?

Question: Estou preenchendo meu DataGridView com uma lista de objetos, porém, quando preencho o grid pela primeira vez da tudo certo. Quando seto a propriedade DataSource como nulo, são apagadas as colunas da grid.
Existe a possibilidade de resetar a propriedade DataSource sem apagar as colunas do cabeçalho ?
Trecho de código que utilizo:
if (listVetObj.Count > 0)
{
    dgvControle.DataSource = listVetObj;
    dgvControle.Update();
    dgvControle.Refresh();

    txtQtdeLinhas.Text = dgvControle.RowCount.ToString();
    txtQtdeLinhas.Refresh();
}

Quando reseto a propriedade dentro de um método são apagadas as colunas do cabeçalho:
Código:
private void LimparCampos()
{
    dgvControle.DataSource = null;
    dgvControle.Update();
    dgvControle.Refresh();
}

Comment: Isso elas são fixas no grid. Quando insiro linha a linha da certo, por questões de perfomance, comecei a usar list e setando direto no DataSource, ai começou esse problema.
Comment: As colunas do cabeçalho você cria antes correto ?
Answer: Bom se pode fazer uma lista vazia pra que ele não desmonte o seu controle e permanece com o mesmo layout
private void LimparCampos()
{
    dgvControle.DataSource = new List<Class>();
    dgvControle.Update();
    dgvControle.Refresh();
}

Onde a Class é o nome da sua classe que carrega esse controle.
Referencias:

Como associar dados ao controle DataGridView dos Windows Forms
Propriedade DataGridView.DataSource
Comment: Um detalhe, `new List()` já cria uma lista, não precisa do `ToList()` depois.
Comment: @VirgilioNovic, fiz da forma que falou e resolveu o problema, porém, como o jbueno comentou fiz sem o ToList(). Obrigado
Comment: Isso @DiegoFarias pode testar das duas maneiras se no seu caso for uma implentação de `IList` `IListSource` `BindList` se não for precisa usar o `ToList` se não nem precisa! eu Coloquei propositalmente.
Comment: @VirgilioNovic obrigado. Abraço
Comment: O `ToList` foi proposital, eu não sei o modo que ele envia essa Lista @jbueno fique tranquilo eu sei disso observando a pergunta não sei o modo real que ele utiliza.
Comment: Vou testar desse modo que você passou. E vou fazer o teste com e sem o ToList();
Comment: @DiegoFarias pronto formatei como você resolveu.