Erro ao enviar E-Mail pelo Indy 10

Question: Aparece o seguinte erro quando tenta executar a função de enviar e-mail:
Não há um programa padrão de e-mail associado para realizar a ação solicitada. instale um programa de e-mail ou, caso já exista um instalado, crie uma associação no painel de controle Programas Padrão.

Segue o código:
procedure TfrmEnviaEmail.btnEnviarClick(Sender: TObject);
var
    i: integer;
  IdAttachmentFile1 : TIdAttachmentFile;
  IdUserPassProvider: TIdUserPassProvider;
  idSASLLogin: TIdSASLLogin;
begin
  IdSMTP1.ConnectTimeout := 30000;
  IdSMTP1.ReadTimeout := 30000;
    try
//      cancelar:= false;
        Screen.Cursor:= crHourGlass;
        btnEnviar.Enabled:= false;

    if cbDominio.ItemIndex = 0 then    //anibaltec
    begin
      IdSMTP1.Host := 'anibaltec.com.br';
    end;
    if cbDominio.ItemIndex = 1 then    //gmail
    begin
      IdSMTP1.Host := 'smtp.gmail.com';
    end;
    if cbDominio.ItemIndex = 2 then    //hotmail
    begin
      IdSMTP1.Host := 'smtp.live.com';
    end;
    if cbDominio.ItemIndex = 3 then    //yahoo
    begin
      IdSMTP1.Host := 'smtp.mail.yahoo.com';
    end;
    if cbDominio.ItemIndex = 4 then    //tef.net
    begin
      IdSMTP1.Host := 'tef.net.br';
    end;

    IdMessage1.Clear;
    IdMessage1.MessageParts.Clear;
    IdMessage1.IsEncoded := True;
    IdMessage1.CharSet := 'iso-8859-1';
    IdMessage1.Encoding := MeMIME;
    IdMessage1.ConvertPreamble := True;
    IdMessage1.Priority := mpNormal;
    IdMessage1.Date := Now;
    IdMessage1.From.Address := edtEmailDest.Text;
        IdMessage1.Subject := EdtAssunto.Text;
    IdMessage1.Body.Text := 'Este e-mail e um e-mail automatico, por favor nao responde-lo. Segue em anexo o relatório.';
    IdMessage1.ContentType := 'multipart/mixed';
    IdMessage1.Recipients.EMailAddresses := EdtPara.Text;

    //recebimento de confirmação
    IdMessage1.Headers.Add('Disposition-Notification-To: '+edtEmailDest.Text);
    IdMessage1.ReceiptRecipient.Address := edtEmailDest.Text;
    IdMessage1.ReceiptRecipient.User := edtEmailDest.Text;
    IdMessage1.ReceiptRecipient.Text := IdMessage1.From.Text;

    if ListBox1.Items.Count > 0 then
        begin
            for i:= 0 to ListBox1.Items.Count - 1 do
      begin
        if FileExists(ListBox1.Items[i]) then
        begin
          IdAttachmentFile1 := TIdAttachmentFile.Create(IdMessage1.MessageParts, ListBox1.Items[i]);

          if ExtractFileExt(ListBox1.Items[i]) = 'ini' then
            IdAttachmentFile1.ContentType := 'application/txt;'
          else
            IdAttachmentFile1.ContentType := 'application/'+ExtractFileExt(ListBox1.Items[i])+';';

          IdAttachmentFile1.FileName := ExtractFileName(ListBox1.Items[i]);
        end;
            end;
    end;

    with idSMTP1 do
    begin
      try
        Port := 587;
        IOHandler := IdSSLIOHandlerSocketOpenSSL1;
        UseTLS := utNoTLSSupport;
//        UseTLS := utUseExplicitTLS;
//        IdSSLIOHandlerSocketOpenSSL1.SSLOptions.Method := sslvTLSv1;
        IdSSLIOHandlerSocketOpenSSL1.PassThrough := true;
      except
        on E: Exception do
        begin
          IOHandler := TIdIOHandler.MakeDefaultIOHandler( nil );
          UseTLS := utNoTLSSupport;
        end;
      end;
    end;
    if not IdSMTP1.Connected then
    begin
      try
        IdSMTP1.AuthType := satDefault;
        IdSMTP1.Username := edtEmailDest.Text;
        IdSMTP1.Password := edtSenhaDest.Text;
        IdSMTP1.ReadTimeout := 10000;

        IdSMTP1.Connect;
        IdSMTP1.Authenticate;
      except
        on e: Exception do frmprincipal.EscreveLog(caminholog, 'Aplicativo não conseguiu se comunicar com o servidor de e-mail! Erro: '+e.Message);
      end;
    end;

    IdSMTP1.Send(IdMessage1);

    if ListBox1.Items.Count > 0 then
        begin
            for i:= 0 to ListBox1.Items.Count - 1 do
      begin
        if FileExists(ListBox1.Items[i]) then
        begin
          try
            if IdSMTP1.Connected then
            begin
              frmPrincipal.EscreveLog(caminholog, 'Email enviado com sucesso. ' +
                'Relatório '+ListBox1.Items[i]+' em anexo');
            end;
          except
             on e: Exception do frmPrincipal.EscreveLog(caminholog,
                'Servidor de Email ('+IdSMTP1.Host+') não foi conectado');
          end;
        end;
      end;
    end;
  finally
    if IdSMTP1.Connected then
    begin
      frmPrincipal.StatusBar1.Panels[0].Text := 'Email enviado com sucesso.';
      frmprincipal.EscreveLog(caminholog, 'Email enviado com sucesso.');
    end
    else
    begin
      frmprincipal.EscreveLog(caminholog, 'Aplicativo não conseguiu se comunicar com o servidor de e-mail!');
    end;
    Screen.Cursor:= crDefault;
    IdSMTP1.Disconnect;
    btnEnviar.Enabled:= true;
    ListBox1.Clear;
    Close;
  end;
end;

Answer: De acordo com este artigo da Microsoft, siga os passos a seguir para resolver esse impasse.

Abra o Painel de Controle → Programas → Programas Padrão.
Clique sobre Definir acesso a programas e padrões do computador.
Na janela Definir acesso a Programas e Padrões do Computador, clique na seta da configuração Personalizada para abrir o menu de tal categoria.
Na categoria Escolha um programa de e-mail padrão, selecione o programa de e-mail que deseja utilizar, por exemplo, Microsoft Outlook e, a seguir clique em OK.

Essa configuração é guardada na seguinte chave no Registro:
HKEY_CLASSES_ROOT → mailto\shell\open\command

Para alterar esse valor programaticamente, você poderá usar a Winapi RegSetValueEx() ou utilizar as funções da classe Registry.
Exemplo 1 - RegSetValueEx()
function RegSetValue(Key: HKEY; SubKey, NomeDoValor, Valor: String): Boolean;
Var
  phk: HKEY;
begin
Result := False;
if RegOpenKeyEx(Key, pchar(SubKey), 0, KEY_SET_VALUE, phk) = 0 then begin
  Result := RegSetValueEx(phk, PChar(NomeDoValor), 0, REG_SZ, PChar(Valor), (Length(Valor) + 1) * SizeOf(Char)) = 0;
  RegCloseKey(phk);
end;
end;

Utilização:
procedure TForm1.Button2Click(Sender: TObject);
const
 EMAIL_PROGRAM_SYNTAX = 'C:\Path\Do\Programa\De\Email -c /e "%1"';
begin
if RegSetValue(HKEY_CLASSES_ROOT, 'mailto\shell\open\command', '', EMAIL_PROGRAM_SYNTAX) then
  ShowMessage('Operação Feita com sucesso!')
else
  ShowMessage('Erro na operação! Você tem privilégios para fazer isso?');
end;

Exemplo 2 - Registry
// Inclua em Uses: Registry;
function RegSetValue2(Key: HKEY; SubKey, NomeDoValor, Valor: string): Boolean;
Var
 Reg: TRegistry;
begin
Result := false;
Try
  Reg := TRegistry.Create;
  Reg.RootKey := Key;

  if (Reg.KeyExists(SubKey) and (Reg.OpenKey(SubKey, True))) then begin
    Reg.WriteString(NomeDoValor, Valor);
    result := True;
  end;
  Reg.CloseKey;

Finally
  Reg.Free;
End;
end;

Utilização:
procedure TForm1.Button1Click(Sender: TObject);
const
 EMAIL_PROGRAM_SYNTAX = 'C:\Path\Do\Programa\De\Email -c /e "%1"';
begin
if RegSetValue2(HKEY_CLASSES_ROOT, 'mailto\shell\open\command', '', EMAIL_PROGRAM_SYNTAX) then
  ShowMessage('Operação Feita com sucesso!')
else
  ShowMessage('Erro na operação! Você tem privilégios para fazer isso?');
end;

Para que funcione do modo esperado, você provavelmente terá que ter privilégios para fazer essa operação. Se atente também em passar a linha de argumentos de modo correto para o programa de e-mail de sua escolha.
Comment: Tem como fazer isso via delphi? fazer algo parecido no registro e tal?
Comment: amigo, tem como me enviar um exemplo?
Comment: Mechanic, cara, o indy utiliza algum programa padrão ou ele utiliza o envio de email via TelNet? as máquinas dos cliente estão dando este erro. é interessante mas, não tem Outlook na máquina deles. Resumindo, Indy deveria utilizar a ferramenta contida na DLL Winsock.dll e enviar os e-mails via telnet não? ou estou falando besteira? :P
Comment: @RamonRuan De uma olhada sobre [mAPI](http://en.wikipedia.org/wiki/Messaging_Application_Programming_Interface). [Aqui](http://www.swissdelphicenter.ch/en/showcode.php?id=1246) têm um exemplo para Delphi.

Erro ao enviar E-Mail pelo Indy 10


Activate Run the libLAS C++ library within R

Question: I would like to use the libLAS C/C++ library functions within R to import, analyse, export terrestrial lidar data. libLAS is a C/C++ library for reading and writing the very common LAS LiDAR format ( http://liblas.org/index.html ).
Would it be possible to use the Rcpp package to run this library (or other packages)? http://dirk.eddelbuettel.com/code/rcpp.html
Or should I compile and install it in order to use it following the compilation instructions http://liblas.org/compilation.html ? I am working on a MacOSx 10.6.5. As such I could also use it within Open Source GIS GRASS as described in the following wiki http://grass.osgeo.org/wiki/LIDAR#Micro-tutorial_for_LAS_data_import .
All advice is welcome related to reading and processing LIDAR data with R/GRASS.
Thanks,
Jan
Answer: For the question

Would it be possible to use the Rcpp
  package to run this library (or other
  packages)?

the answer is whopping Yup! as using it for glueing R to a given C/C++ library was pretty much the reason Rcpp was written for.  Come and see the documentation and/or the rcpp-devel list for examples.  There is some exciting new stuff happening with Rcpp modules but you can also get going the old-fashioned way of writing your wrapper.  Rcpp makes mapping and R and C++ types (in both directions) a lot easier.
Comment: What a lay-up.  No +1 from me.  You didn't even have to try. ;-)
Comment: Hm, I still have the feeling that the answer was a) appropriate and b) correct so that I not sure that a score of zero does it justice.
Comment: OK OK, that's 30K +10 for you then ;-)
Comment: Thanks :)  I wanted to applaud your for that SSD read/write performance question.  Nice focus, and of course empirics. Great job.


Can we deduce that the zeros of $g$ are also isolated?

Question: Let $f:Ω→ℂ$ be a non-zero holomorphic function and $g:Ω→ℂ$ be a non-zero non-holomorphic function. We know that all the zeros of $f$ are isolated. Assume that $$f(s)=0⇒g(s)=0$$
Can we deduce that the zeros of $g$ are also isolated?
Comment: No, because you don't know anything about the zeroes of $g$ that are not zeroes of $f$. For instance, $g$ could be $f \cdot \mathrm{Re}(z)$.
Comment: Not even the zeoroes of $g$ that are also zeroes of $f$ need be isolated zeroes of $g$. (And the zeroes of $f$ are also only isolated if $f\ne 0$)
Comment: But that's much too weak to tell you what you want. As a more extreme example, suppose $f$ is the constant function with value 1. Then your implication holds for _any_ $g$.
Comment: @AsalBeagDubh: But the property is true for all the zeros of $g$ that are zeros of $f$.
Answer: Consider $f(z)=z$ and $g(z)=Re(z)$.


Send me your email ID, I will fix it for you

Question:
I don't want to see from my third eye, but I am forced to sometime.

I have seen these few times that users asking for personal email ID in order to fix the issue. For ex: How to display Shop by options before the product details/ items in mobile view only?

I see above scenario as violation of SE's policy (wait I haven't checked SE's policy). At least it is not ethical for me to ask for email address. I can sense of some fishy going on there. I wouldn't recommend providing email ID or any other personal info publicly though.
I might be wrong totally. Pardon me if I am offending some of you. This is just my opinion.
Question
Can I flag these comments? OR simply should I ignore them.
Comment: Wow, this user is coming from the future, he has experience with Magento 5
Answer: This is certainly not good for our forum Q&A. Such comments should be flagged immediately so that moderators can take necessary actions against this.
Please flag all such users immediately without any mercy.
Comment: It defeats the point of the forum. Is everyone who has the same issues supposed to email this guy for years down the line hoping he will answer?

Reporting it immediately without a thought is the correct action, the action that happens afterwards can be where the though process kicks in.
Comment: "without any mercy" is kind of harsh, don't you think? Just flag the Q and let the mods deal with it.
Comment: @philwinkle i don't think it's harsh. i said do flagging without mercy or without a double thought. Oh may be in your country/region, it may sounds harsh. #LanguageBarrier. English is not my mother tongue lang. :)
Comment: Well, you don't flag users. You flag comments or posts that they make. After a while if a user continues to exhibits a certain behaviour pattern they may be [warned and/or suspended](http://meta.stackexchange.com/a/1336/243324)


Google Script For "Marking" Non Blank Rows

Question: I'm trying to create a google script that will look at my sheet, get the length of data and then mark "processed" in Column P. I can't do this with an array/if formula because I need to know when a new line comes in and has not been processed. My current script just writes never ending data to column P. I want it to only write to the last non blank row based on Column A.
Here is my example sheet and script that isn't working.
https://docs.google.com/spreadsheets/d/13Q4I91O4vMDSCHwAMG0DOLLkbzLCxWiQzbugJ-6nPjs/edit?usp=sharing
 function MarkrowsProcessed() {
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spr.getSheetByName("Sheet1");
  var column = spr.getRange('A:A').getValues();

  for (var i = 0; i < column.length; ++i)
  {
    var rowData = column[i];
    var emailSent = rowData[16];
    if (emailSent != 'Processed')
    {
   sheet.getRange(i+1, 16, column.length, 1).setValue('Processed');// Make sure the cell is
updated right away in case the script is interrupted
 }

}
}

Thanks in advance for the help.
Comment: 1) Your link says Access Denied. 2) How exactly you intend to call the function? Manually from the Script editor or via custom menu? Or by some events? 'I need to know when a new line comes in' -- you can run a script whenever some changes in the table do occur.
Answer: Your line sheet.getRange(i+1, 16, column.length, 1).setValue('Processed') assigns the value to a static line.

To change it an elegant way would be to start at a line of which you know for sure that it is not empty and find from there the last non-blank row with getNextDataCell().

Sample:
var notBlank = sheet.getRange("A1");
var lastRow = notBlank.getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow():
sheet.getRange(lastRow, 16, column.length, 1).setValue('Processed');

This would find the last row before the first blank row (could be an  interdispersed blank row between non-empty rows).

If you want to find the very last row of a sheet, then use getLastRow().

Sample:

var lastRow = sheet.getLastRow();
sheet.getRange(lastRow, 16, column.length, 1).setValue('Processed');

Careful:
Make sure that you really want to set the data into the last non-blank row (this means overwriting already existant data).
Answer: I'm not sure if I understand the task right. Either you need write 'Processed' in every cell in column 'P' or only at the end of it?
Here is corrected function that gets the length of column 'A', iterates trough column 'P' and writes 'Processed':
function MarkrowsProcessed() {
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spr.getSheetByName("Sheet1");

  // get data of column 'A'
  var column_A = spr.getRange('A:A').getValues();

  // get a len of column 'A'
  var len = column_A.filter(String).length; // it works if the column has no empty cells inside

  // get data of column 'P'
  var column_P = spr.getRange('P:P').getValues();

  // loop trough data of column 'P' (until last row in column 'A') and write 'Processed'
  for (var i=0; i<len; ++i)
  {
    if (column_P[i] != 'Processed') sheet.getRange('P' + (i+1)).setValue('Processed');
  }
}

If you need the very last row on the sheet (not the last row in column 'A') it will be even easier. You need to change one line in the function:
  var len = sheet.getLastRow();


Objects with common property

Question: I have three different classes A, B and C with some commons properties. For instance all of them have property called index. Also all of them inheritance from other class X which doesn't have property index and I can't modify these classes (it's from framework). Now I want to create instantiation one of these classes and set index property. How I'm doing it now:
func returnPreparedObjet() -> X? {
    if some_condition1 {
        let a = A()
        a.index = 1
        return a
    }
    else if some_condition2 {
        let b = B()
        b.index = 1
        return b
    }
    else if some_condition3 {
        let c = C()
        c.index = 1
        return c
    }
    return nil
}

What is the best option to achieve it without repeat .index = 1 and return lines? Can I achieve this also in situation when A,B,C don't inheritance from X?
Comment: maybe you can just conform A, B and C to a protocol with index variable.
Comment: Can I do it without modify A, B and C classes?
Answer: You could group the three classes under a common protocol:
protocol Indexed {
    var index: Int { get set }
}

, and add conformance for the three classes
extension A: Indexed {}
extension B: Indexed {}
extension C: Indexed {}

no code will be needed in the extensions as the classes already declare a writable index property.
You can then simplify the returnPreparedObject to something like this:
func returnPreparedObject() -> X? {
    let result: (X & Indexed)?
    if some_condition1 {
        result = A()
    } else if some_condition2 {
        result = B()
    } else if some_condition3 {
        result = C()
    }
    result?.index = 1
    return result
}

Objects with common property


Writing an object's property to a DataTable through Expression tree

Question: I have a list of this simple model:
// model:
public class Test {
    public int ID { get; set; }
    public string Name { get; set; }
}

as var list = new List<Test>() { /* some items here */ };. And I'm generating a DataTable from the list by this snippet:
var dataTable = new DataTable();
dataTable.Columns.Add("ID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
foreach (var item in list) {
    var dr = dataTable.NewRow();
    dr["ID"] = item.ID;
    dr["Name"] = item.Name;
    dataTable.Rows.Add(dr);
}

Now I'm trying to generating some expression-tree to do the above snippet at run-time (in a generic way). However, my attempt got me here:
    private static Action<DataTable, IEnumerable<T>> GetAction() {
        if (_filler != null)
            return;
        var type = typeof(T);
        var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        var tableParam = Expression.Parameter(typeof(DataTable), "targetTable");
        var rowsParam = Expression.Parameter(typeof(IEnumerable<T>), "rows");

        var loopVariable = Expression.Parameter(typeof(T), "item");

        var columnsVariable = Expression.Parameter(typeof(DataColumnCollection), "columns");
        var columnsAssign = Expression.Assign(columnsVariable,
            Expression.Property(tableParam, typeof(DataTable).GetProperty("Columns")));

        var headerExpressions = new List<Expression>();
        var bodyExpressions = new List<Expression>();

        var newRowParam = Expression.Parameter(typeof(DataRow), "currentRow");
        var newRowAssign = Expression.Assign(newRowParam, Expression.Call(tableParam, typeof(DataTable).GetMethod("NewRow")));

        foreach (var prop in props) {
            var getMethod = prop.GetGetMethod(false);
            if (getMethod == null)
                continue;
            var attr = prop.GetCustomAttribute<UdtColumnAttribute>();
            var name = attr == null ? prop.Name : attr.ColumnName;

            var headerNameParam = Expression.Parameter(typeof(string), "columnName");
            var headerNameAssign = Expression.Assign(headerNameParam, Expression.Constant(name, typeof(string)));

            var headerTypeParam = Expression.Parameter(typeof(Type), "columnType");
            var headerTypeAssign = Expression.Assign(headerTypeParam, Expression.Constant(prop.PropertyType, typeof(Type)));

            var columnsAddMethod = Expression.Call(columnsVariable,
                typeof(DataColumnCollection).GetMethod("Add", new[] { typeof(string), typeof(Type) }),
                headerNameParam, headerTypeParam);

            headerExpressions.AddRange(new Expression[] {
                                           headerNameParam,
                                           headerNameAssign,
                                           headerTypeParam,
                                           headerTypeAssign,
                                           columnsAddMethod,
                                       });

            var indexerProp = typeof(DataRow).GetProperty("Item", new[] { typeof(string) });
            var indexerParam = Expression.Property(newRowParam, indexerProp, Expression.Constant(name, typeof(string)));
            var propertyReaderMethod = Expression.Call(loopVariable, getMethod);
            var assign = Expression.Assign(indexerParam, Expression.TypeAs(propertyReaderMethod, typeof(object)));

            bodyExpressions.AddRange(new Expression[] { indexerParam, propertyReaderMethod, assign });
        }

        var finalExpressions = new List<Expression>() {
            tableParam,
            rowsParam,
            loopVariable,
            columnsVariable,
            columnsAssign,
            newRowParam,
            newRowAssign,
        };
        finalExpressions.AddRange(headerExpressions);

        var loop = ExpressionHelper.ForEach(rowsParam, loopVariable, Expression.Block(bodyExpressions));
        finalExpressions.Add(loop);
        var compilable = Expression.Block(finalExpressions);
        var code = compilable.ToString();
        Trace.WriteLine(code);
        var compiled = Expression.Lambda<Action<DataTable, IEnumerable<T>>>(compilable, tableParam, rowsParam).Compile();
        return compiled;
    }

But, when I call .Compile() method (at the end of block, just before return) I get this error:

An exception of type 'System.InvalidOperationException' occurred in
  System.Core.dll but was not handled in user code
Additional information: variable 'item' of type
  'TestEntity' referenced from
  scope '', but it is not defined

Do you have any idea what I missed here? Thanks in advance. Cheers.
UPDATE:
Here is the loop generator:
public static class ExpressionHelper {

    public static Expression ForEach(Expression collection, ParameterExpression loopVar, Expression loopContent) {

        var elementType = loopVar.Type;
        var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType);
        var enumeratorType = typeof(IEnumerator<>).MakeGenericType(elementType);

        var enumeratorVar = Expression.Variable(enumeratorType, "enumerator");
        var getEnumeratorCall = Expression.Call(collection, enumerableType.GetMethod("GetEnumerator"));
        var enumeratorAssign = Expression.Assign(enumeratorVar, getEnumeratorCall);

        // The MoveNext method's actually on IEnumerator, not IEnumerator<T>
        var moveNextCall = Expression.Call(enumeratorVar, typeof(IEnumerator).GetMethod("MoveNext"));

        var breakLabel = Expression.Label("LoopBreak");

        var loop = Expression.Block(new[] { enumeratorVar },
            enumeratorAssign,
            Expression.Loop(
                Expression.IfThenElse(
                    Expression.Equal(moveNextCall, Expression.Constant(true)),
                    Expression.Block(new[] { loopVar },
                        Expression.Assign(loopVar, Expression.Property(enumeratorVar, "Current")),
                        loopContent
                    ),
                    Expression.Break(breakLabel)
                ),
            breakLabel)
        );

        return loop;
    }

}

Comment: `loopVariable` is defined as a parameter, but you never provide it to your lambda. Did you mean to use `Expression.Variable` for it?
Comment: @Rob
I changed the `loopVariable` to `Expression.Variable` but the problem exists.
Answer: Updated working code is below and working example in DotNetFiddle is - https://dotnetfiddle.net/fyMOxe
Originally your code has two following issues:

Body expression should have separated variables and actual expressions. In your sample you are adding ExpressionParameter within other parameters and pass them to Body call. But they should be passed standalone. So you have to pass first parameter with list of variables, and second one with actual expressions.
Your loop code missed actual expression var dr = dataTable.NewRow(); that you generated, but didn't add to loop. And also it missed last call with dataTable.Rows.Add(dr); as filled row needs to be added back to Rows.

In in my example i fixed these two issues and now code fills DataTable based on list of Test entities.
public class Program
{
    static void Main(string[] args)
    {

        var data = new List<Test>()
        {
            new Test() {ID = 1, Name = "1Text"},
            new Test() {ID = 2, Name = "2Text"},
        };

        var action = ExpressionHelper.GetAction<Test>();

        var dataTable = new DataTable();
        action(dataTable, data);

        foreach (DataRow row in dataTable.Rows)
        {
            Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}");
        }

    }

}

public class ExpressionHelper
{
    public static Action<DataTable, IEnumerable<T>> GetAction<T>()
    {
        //if (_filler != null)
        //  return null;
        var type = typeof(T);
        var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        var tableParam = Expression.Parameter(typeof(DataTable), "targetTable");
        var rowsParam = Expression.Parameter(typeof(IEnumerable<T>), "rows");

        var loopVariable = Expression.Parameter(typeof(T), "item");

        var columnsVariable = Expression.Parameter(typeof(DataColumnCollection), "columns");
        var columnsAssign = Expression.Assign(columnsVariable,
            Expression.Property(tableParam, typeof(DataTable).GetProperty("Columns")));

        var headerExpressions = new List<Expression>();
        var bodyExpressions = new List<Expression>();

        var headerNameParam = Expression.Parameter(typeof(string), "columnName");
        var headerTypeParam = Expression.Parameter(typeof(Type), "columnType");

        var newRowParam = Expression.Parameter(typeof(DataRow), "currentRow");
        var newRowAssign = Expression.Assign(newRowParam, Expression.Call(tableParam, typeof(DataTable).GetMethod("NewRow")));

        bodyExpressions.Add(newRowAssign);
        foreach (var prop in props)
        {
            var getMethod = prop.GetGetMethod(false);
            if (getMethod == null)
                continue;
            var attr = prop.GetCustomAttribute<UdtColumnAttribute>();
            var name = attr == null ? prop.Name : attr.ColumnName;

            var headerNameAssign = Expression.Assign(headerNameParam, Expression.Constant(name, typeof(string)));

            var headerTypeAssign = Expression.Assign(headerTypeParam, Expression.Constant(prop.PropertyType, typeof(Type)));

            var columnsAddMethod = Expression.Call(columnsVariable,
                typeof(DataColumnCollection).GetMethod("Add", new[] { typeof(string), typeof(Type) }),
                headerNameParam, headerTypeParam);

            headerExpressions.AddRange(new Expression[] {
                                       headerNameAssign,
                                       headerTypeAssign,
                                       columnsAddMethod,
                                   });

            var indexerProp = typeof(DataRow).GetProperty("Item", new[] { typeof(string) });
            var indexerParam = Expression.Property(newRowParam, indexerProp, Expression.Constant(name, typeof(string)));
            var propertyReaderMethod = Expression.Call(loopVariable, getMethod);
            var assign = Expression.Assign(indexerParam, Expression.TypeAs(propertyReaderMethod, typeof(object)));

            bodyExpressions.AddRange(new Expression[] { assign });
        }

        // we should add that row back to collection
        var addRow = Expression.Call(
            Expression.Property(tableParam, "Rows"),
            typeof(DataRowCollection).GetMethod("Add", new Type[] {typeof(DataRow)}),
            newRowParam);
        bodyExpressions.Add(addRow);

        var finalExpressions = new List<Expression>()
        {
            columnsAssign,
            newRowAssign,
        };

        var variables = new List<ParameterExpression>()
        {
            loopVariable,
            columnsVariable,
            newRowParam,
            headerNameParam,
            headerTypeParam
        };

        finalExpressions.AddRange(headerExpressions);

        var loop = ExpressionHelper.ForEach(rowsParam, loopVariable, Expression.Block(bodyExpressions));
        finalExpressions.Add(loop);
        var compilable = Expression.Block(variables, finalExpressions);
        var code = compilable.ToString();
        Trace.WriteLine(code);
        var compiled = Expression.Lambda<Action<DataTable, IEnumerable<T>>>(compilable, tableParam, rowsParam).Compile();
        return compiled;
    }

    public static Expression ForEach(Expression collection, ParameterExpression loopVar, Expression loopContent)
    {

        var elementType = loopVar.Type;
        var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType);
        var enumeratorType = typeof(IEnumerator<>).MakeGenericType(elementType);

        var enumeratorVar = Expression.Variable(enumeratorType, "enumerator");
        var getEnumeratorCall = Expression.Call(collection, enumerableType.GetMethod("GetEnumerator"));
        var enumeratorAssign = Expression.Assign(enumeratorVar, getEnumeratorCall);

        // The MoveNext method's actually on IEnumerator, not IEnumerator<T>
        var moveNextCall = Expression.Call(enumeratorVar, typeof(IEnumerator).GetMethod("MoveNext"));

        var breakLabel = Expression.Label("LoopBreak");

        var loop = Expression.Block(new[] { enumeratorVar },
            enumeratorAssign,
            Expression.Loop(
                Expression.IfThenElse(
                    Expression.Equal(moveNextCall, Expression.Constant(true)),
                    Expression.Block(new[] { loopVar },
                        Expression.Assign(loopVar, Expression.Property(enumeratorVar, "Current")),
                        loopContent
                    ),
                    Expression.Break(breakLabel)
                ),
            breakLabel)
        );

        return loop;
    }
}

public class Test
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class UdtColumnAttribute : Attribute
{
    public string ColumnName { get; set; }
}

Comment: Glad that i helped :)
Comment: Thanks bro. I figured out the first issue and was able to compile the expression; but invoking the compiled expression, was throwing `null reference exception` - bcuz of the second issue - which I was trying to fix. You saved my day dude. Thank you again.
Answer: I am unsure what is the reason for using expression trees here, I guess you are worried about performance if using reflection (since you will not send this expression to EF, or any other queryProvider, right)? That also means that you forgot to add the _filler = compiled; just before returning....
The main problem with expression trees when compiled to delegates is, that they are not refactor-friendly at all, and hard to read/understand.
Now if you would use directly reflection, than the only penalty is the getter calls on the objects, all the rest of the work you have to do anyways. So you can cache that part, and then do all the rest without all the complexity, have a much cleaner code and more readable.
public class PropHelper
{
    public PropertyInfo PropInfo {get;set;}
    public Func<object, object> Getter {get;set;}
}

private static readonly ConcurrentDictionary<Type, IEnumerable<PropHelper>> s_cachedPropHelpers = new ConcurrentDictionary<Type, IEnumerable<PropHelper>>();

public static IEnumerable<PropHelper> GetPropHelpers(Type type)
{
    return s_cachedPropHelpers.GetOrAdd(type, t =>
        {
            var props = t.GetProperties();
            var result = new List<PropHelper>();
            var parameter = Expression.Parameter(typeof(object));
            foreach(var prop in props)
            {
                result.Add(new PropHelper
                    {
                        PropInfo = prop,
                        Getter = Expression.Lambda<Func<object, object>>(
                            Expression.Convert(
                                Expression.MakeMemberAccess(
                                    Expression.Convert(parameter, t),
                                    prop),
                                typeof(object)),
                            parameter).Compile(),
                    });
            }
            return result;
        });
}

private static Action<DataTable, IEnumerable<T>> GetAction<T>()
{
    return (dataTable, list) => {
        var props = GetPropHelpers(typeof(T));

        foreach(var prop in props)
            dataTable.Columns.Add(prop.PropInfo.Name, prop.PropInfo.PropertyType);

        foreach (var item in list)
        {
            var dr = dataTable.NewRow();
            foreach(var prop in props)
                dr[prop.PropInfo.Name] = prop.Getter(item);
            dataTable.Rows.Add(dr);
        }
    };
}

Is that not easier to read?


How to put select option value into particular category in webform module?

Question: I am using webform module and added a select field.
My option values are

One|Sample 1
  Two|Sample 2
  Three|Sample 3
  Four|Sample 4
  Five|Sample 5
  Six|Sample 6

But I want these three fields in a particular category named Sample list 1

One|Sample 1
  Two|Sample 2
  Three|Sample 3

Sample List 2:

Four|Sample 4
  Five|Sample 5
  Six|Sample 6

Note: I don't want to show it in groups <>.
I want a select list which consists of Sample List 1 and Sample List 2
In a single select field I want to store both of option values into their respective select lists.
Comment: So you want 2 fields in the database that display as one field to the user?
Comment: So you want a select list that allows you to choose one value from the first 3 items and one value form the next three items?!? Would it not be easier to just have 2 selects?
Comment: It is a dropdown which I need. You mean to say two select fields?
Comment: Dropdown or select - they are both different names for the same thing.
Comment: Yes right. But I am talking about the options. I need to put the option values in two different categories as I mentioned.
Comment: But you don't want to use optgroups? I'm confused...
Comment: No. I do not want to use optgroups. That will come as a separate groups in the drop down.
Comment: I need two categories(Sample list 1 and 2) which are select fields and just like a module connected to select option. On using option values for the other select field I need to use sample list 1 for entering values and sample list 2 for entered another set of values.
Comment: @rooby yes some what right
Comment: If that is somewhat right what is the part I'm missing?
Comment: First, I need select field with option values (2 or more) Secondly, I need another select field with option values belongs to the first option values. Hope you understood.
Answer: I think you want to store this a 2 separate fields however present it to the user as 1 field.
One solution would be to use hook_form_alter() to combine the 2 selects into 1, and then put the values back where it should be after the form is submitted.
For this example lets call the first select field A, and the second field B, and the new field that combines both A and B, C.
So - first combine the fields and add an additional submit handler:
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'webform_client_form_<ADD WEBFORM ID HERE>') {

    // Make a new field which will have both options. Base in on the existing
    // field A.
    $form['submitted']['field_c'] = $form['submitted']['field_a'];

    // Combine the options of field A and B for the new field.
    $form['submitted']['field_c']['#options'] = array_merge($form['submitted']['field_a']['#options'], $form['submitted']['field_b']['#options']);

    // Hide field A and field B.
    $form['submitted']['field_a']['#access'] = $form['submitted']['field_b']['#access'] = FALSE;

    // Add an additional submit handler to put the values back where they
    // should be. Add this before the existing submit handler so we can make
    // our changes before anything is saved.
    array_unshift($form['#submit'], 'split_combined_select_values_out');

    // Add a validate function to make sure only 1 option is selected from each category
    $form['#validate'][] = 'combined_select_validate';

  }

}

In the new validation function make sure that only 1 option is selected from each category:
function combined_select_validate($form, &$form_state) {

  $count_a = $count_b = 0;

  foreach($form_state['values']['submitted']['field_c'] as $val) {
    if(array_key_exists($val, $form['submitted']['field_a']['#options'])) {
      $count_a++;
    } elseif(array_key_exists($val, $form['submitted']['field_b']['#options'])) {
      $count_b++;
    }
  }

  if($count_a > 1 || $count_b > 1) {
    form_set_error('submitted][field_c', 'Can only select 1 option from each category');
  }

}

And then in the new submit handler put the values back where they should be:
function split_combined_select_values_out($form, &$form_state) {

  foreach($form_state['values']['submitted']['field_c'] as $val) {
    // Check if the value  selected is from field A or field B
    if(array_key_exists($val, $form['submitted']['field_a']['#options'])) {
      $form_state['values']['submitted']['field_a'][$val] = $val;
    } elseif(array_key_exists($val, $form['submitted']['field_b']['#options'])) {
      $form_state['values']['submitted']['field_b'][$val] = $val;
    }
  }

  // Unset the value from field C.
  unset($form_state['values']['submitted']['field_c']);

}

Comment: First, I need select fields with option values (2 or more) Secondly, I need another select field with option values belongs to the previous option values(First). Does this do this way?
Comment: I'm not quite sure what you mean I'm afraid. Have a go with the code and see if it helps.
Comment: More Detailed info: In general, dropdown with two values (Sample 1 and Sample 2) which is only shown to admin. Another dropdown with n number of values belongs to sample 1 and n number of values belongs to Sample 2 which is done by admin. The user will be shown only one dropdown of n number of values belongs to both Sample 1 and 2 in the webform. Hope you understood.
Comment: https://drupal.stackexchange.com/questions/17975/dynamic-options-list-based-on-the-previous-select-box-value. Exact match for my question. I guess you can help me out now. The answer is to use **[hierarchical_select][1]

  [1]: http://drupal.org/project/hierarchical_select** module. But I could not able to do what I intended to.
Answer: Create a taxonomy of these options & create hierarchy of them & enable hierarchy select webform module & add Hierarchy term select element in your webform.


Remove text between delimiters in linux

Question: Server got hacked and a fair amount of files were edited. We noticed that the code that was inserted were typically done between delimiters (e.g. /*e21234*/ blah blah /*/e21234*/). What is the most efficient way to remove this from a large number of files on a linux box? (I tried using sed but couldn't quite get it. I'm open to using perl or whatever would work)
Comment: [The easiest, and best way (by far) is to format the server and restore from backups.](http://serverfault.com/q/218005/118258)  Only way to be sure.
Answer: Did you try this:
sed 's,/\*e21234\*/.*e21234\*/,,g'

But I agree that restoring a backup is probably best!
Comment: This won't handle stuff spanning lines (in sed, '.' doesn't match newline). Perhaps `sed -r -e 's,/\*e2134\*/(.|\n)*/.*e21234\*/,,g'` helps. In any case, you won't ever be sure you got rid of all of it.

Remove text between delimiters in linux


.NET System.Diagnostics.Process output is incomplete

Question: I am unable to retrieve a complete output of a command executed in a shell. The program first writes a line stating it's connecting to a server to fetch data, then  it shows fetched data. In my tiny VB app I always get only that first line, which is indicating that the command is supplied with proper and verified arguments, but the rest of ouptut doesn't get through.
First, I just tried to read it with WaitForExit() and ReadToEnd(). Then reading it line by line with oProcess.StandardOutput.ReadLine().
As suggested in some thread, I tried to disable WaitForExit() and include loop that waits for a process to exit:
    Dim oProcess As New System.Diagnostics.Process()
    Dim oStartInfo As New System.Diagnostics.ProcessStartInfo("net", " user %USERNAME% /DOMAIN")
    oStartInfo.UseShellExecute = False
    oStartInfo.RedirectStandardOutput = True
    oStartInfo.CreateNoWindow = True
    oProcess.StartInfo = oStartInfo
    oProcess.Start()
    'oProcess.WaitForExit()

    Dim lns As String
    Dim q As System.Text.StringBuilder = New System.Text.StringBuilder()
    While Not (oProcess.HasExited)
        q.Append(oProcess.StandardOutput.ReadToEnd())
        lns &= q.ToString()
    End While
    Me.TextBox1.Text &= lns & vbCrLf

I tried to include a Thread.Sleep(500) as suggested in another thread.
Still just one line. Obviously, it works like a charm from the CMD. Any ideas, please?
Comment: If it's the `net` command, i guess the remaining output is on stderr, not stdout. Try capture stderr too.
Comment: @Zilog80 OK, that makes sense from the point of not seeing it. Thank you for suggestion, will try.
Comment: You might want to consider using the types built into .NET for interacting with Active Directory directly rather than shelling out to a command line tool and then having to parse it's output.
Comment: @Damien_The_Unbeliever Yes, that's a possibility, though it's quite an overkill to burden a tiny little feature with an AD query. The main problem there is, that for the moment I don't have all the information I need (like what OU is called) to set LDAP part.
Answer: Turns out the problem was rather silly, due to my little experience I didn't realized that in case of an error the error message goes into a different (error) output. That lead me to incorrectly describe the problem.
When reading the error output, I could see the query returns error that user is not found. The %USERNAME%wasn't processed and replacing it with Environment.GetEnvironmentVariable("USERNAME") fixed everything.


Feature Importance with categorical independent variables and non-normal continuous dependent variable

Question: I want to study the feature importance of a model with a continuous not normally distributed variable as response and a set of categorical and ordinal independent variables, with unequal variances in most of the groups:

gender (M/F): categorical, unequal variances (levene test p-val<0.001)
country (Ctr1/Ctr2):  : categorical, unequal variances (levene test p-val<0.05)
employment status (employed/unemployed): categorical, unequal variances (levene test p-val<0.001)
urbanisation level of the area (1/2/3): ordinal, equal variances (levene test p-val>0.05)
age group (1/2/3/4): : ordinal, equal variances (levene test p-val>0.05)

Given the nature of the features, I thought of applying an N-Way Welch Anova. But I am not sure how to do it in Python. Plus I am unsure if the results would be relevant given the non-normality of the response.
Would the results from a N-way Anova or even a linear regression implementation be relevant for this case? My objective is to assess the relative importance of the features on the response.
Answer: Since you know that your response is not normal, don't use ANOVA, it presumes normality.
But the good news is that there are other cool methods to determine feature importance. One of my favorites is random forest, but you could also use mutual information or lots of other techniques. An introduction with implementations in python can be found e.g. here.
Comment: If you are satisfied with the answer, please accept it. If not, you could consider leaving a comment detailing what you are missing.


Swift - Problema com NavigationBar junto com SearchController

Question: Estou tendo um problema com o NavigationBar quando usado junto com o SearchController.
Se o NavigationBar translucent property estiver configurado como false o NavigationBar sai da tela quando o SearchController está ativo. Se a translucent property estiver configurada como true funciona normalmente.
Como eu posso corrigir isso?
Código e images abaixo:
Arquivo Swift
import UIKit

class SelecionaPaisTableViewController: UITableViewController, UISearchResultsUpdating {

    //MARK: - Propriedades
    var paises = [PaisCodigo]()
    var paisesFiltrado = [PaisCodigo]()

    var controladorDeBusca: UISearchController!

    //MARK: - Métodos reescritos da View
    override func viewDidLoad() {
        super.viewDidLoad()

        //Dados dos países
        carregaDadosPaises()

        //Carrega configuração do SearchController
        configurarControladorDeBusca()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Métodos reescritos da Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if controladorDeBusca.active {
            return paisesFiltrado.count
        } else {
            return paises.count
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("PaisCell", forIndexPath: indexPath)
        //let cell = tableView.dequeueReusableCellWithIdentifier("PaisCell", forIndexPath: indexPath) as UITableViewCell
        let pais: PaisCodigo

        if controladorDeBusca.active {
            pais = paisesFiltrado[indexPath.row]
        } else {
            pais = paises[indexPath.row]
        }

        cell.textLabel?.text = pais.nome + " (+" + String(pais.codigo) + ")"

        if pais.nome != pais.nomeIngles {
            cell.detailTextLabel?.text = pais.nomeIngles
        } else {
            cell.detailTextLabel?.text = ""
        }

        return cell
    }

    //MARK: - Métodos do UISearchResultsUpdating
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        //paisesFiltrado.removeAll(keepCapacity: false)
    }

    //MARK: - Métodos
    func carregaDadosPaises() {
        let pais1 = PaisCodigo(nome: "Brasil", nomeIngles: "Brazil", codigo: 55)
        let pais2 = PaisCodigo(nome: "United States", nomeIngles: "United States", codigo: 1)

        paises += [pais1, pais2]

        //paisesTableView.reloadData()
    }

    func configurarControladorDeBusca() {
        //Configura Controlador de Busca
        controladorDeBusca = UISearchController(searchResultsController: nil)
        controladorDeBusca.searchResultsUpdater = self
        controladorDeBusca.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

        //Configura a barra do Controlador de busca
        controladorDeBusca.searchBar.placeholder = "Search country"
        controladorDeBusca.searchBar.sizeToFit()
        controladorDeBusca.searchBar.barTintColor = navigationController?.navigationBar.barTintColor
        controladorDeBusca.searchBar.translucent = true

        //UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = UIColor.whiteColor()

        //let atts = [NSForegroundColorAttributeName: UIColor.whiteColor()]

        let atts = [
            NSFontAttributeName: UIFont(name:"GillSans-Bold", size:16)!,
            NSForegroundColorAttributeName: UIColor.whiteColor(),
            NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue
        ]

        controladorDeBusca.searchBar.setScopeBarButtonTitleTextAttributes(atts, forState: .Normal)

        //Adiciona a barra do Controlador de Busca a Table View
        tableView.tableHeaderView = controladorDeBusca.searchBar
    }
}

Comment: Vê se isso aqui te ajuda... http://stackoverflow.com/questions/27710926/setting-navigationcontrollers-navigationbar-translucent-property-to-false-cause
Comment: Ajudou sim Jadson, resolveu o problema. Muito obrigado.
Answer: Se não estiver usando translucent no NavigationBar duas configurações devem ser feitas: adjusts scroll view insets e extend edges under opaque bars devem ser marcados como true no ViewController.
Resposta neste link:
https://stackoverflow.com/questions/27710926/setting-navigationcontrollers-navigationbar-translucent-property-to-false-cause


uploaded documents (cases_ShowDocument) authentication in processmaker

Question: It seems there is no authentication to download uploded documents from processmaker workflows.
test it!
when you upload a file in processmaker workflow, copy uploaded file link to another browser: ...../vezarat/cases/cases_ShowDocument?a=947019182595c2a0cab0f09097461912&v=1
you see this downloadable for everyone!
it is dangerous , is it?
Comment: I would suggest opening a bug in the processmaker bugzilla: bugs.processmaker.com
Comment: bugs.processmaker.com sign up does not send activation mail. do you have any solve to ignore download files by others? or do you know where is the section that I can enter my authentication. in my opinion migrate owncloud with processmaker is a way. just introduce loged in information to owncloud... should read more documentaion...
Answer: It depens on UID of document that is <code>"947019182595c2a0cab0f09097461912"</code> in your case.
When a user upload the file and open URL in browser without UID of document, the user is not able to get file.
You get file because you have UID.
So, its not un-secure.


OLS vs WLS in a Heteroskedastic Trending Regression

Question: Suppose we have the following heteroskedastic trending regression model: $$y_i=bi+a_i u_i$$ for some sequence of non-zero constants $a_i$ and $u_i$ an i.i.d. sequence of mean 0 and variance 1 random variables. I want to find the asymptotic distributions of the OLS and unfeasible WLS estimators and compare their efficiency.
To do this, I calculate the normalisation constants for both asymptotic distributions. I use the Lindeberg-Feller CLT and assume the relevant Grenander conditions hold. I calculate that for $\hat{b}_{OLS}$ and $\hat{b}_{WLS}$, $$\left(\sum_{i=1}^n i^2\right)\left(\sum_{i=1}^n a_i^2 i^2\right)^{-1/2}(\hat{b}_{OLS}-b)\xrightarrow{d} N(0,1)$$
$$\left(\sum_{i=1}^n i^2\right)\left(\sum_{i=1}^n \frac{i^2}{a_i^2} \right)^{-1/2}(\hat{b}_{WLS}-b)\xrightarrow{d} N(0,1)$$
However, I think this must be incorrect as I cannot see why the WLS is necessarily more efficient than the OLS estimator. I think there are cases when either normalisation is bigger, implying that either estimator could be efficient in different cases. For example, I think these imply that if $a_i>1$ for all $i$ then the WLS is more efficient, but if $a_i<1$ for all $i$ then the OLS is more efficient.
Am I doing something wrong in my calculations? I expect the WLS to be more efficient but can't see where the error is coming into my work.
Comment: Don't know where your mistake is, but there is no need for normalization or asymptotics here. The finite sample variance of WLS is smaller than that of OLS, simply by the G-M theorem. That should be apparent as well by inspection of the function forms of the finite sample variances, and an application of some inequality like C-S.
Comment: @BigBendRegion Unfortunately, I was constrained in my approach as this is from a past paper with a few subparts which guide the answer. I did manage to adapt what you said to find the problem and get a solution. Thanks!
Answer: I realised I made a mistake in my derivation of the normalisation for the WLS estimator. The right asymptotic should be $$\left(\sum_{i=1}^n \frac{i^2}{a_i^2}\right)^{1/2}(\hat{b}_{WLS}-b)\xrightarrow{d} N(0,1)$$
Then, since our OLS asymptotic is $$\left(\sum_{i=1}^n i^2\right)\left(\sum_{i=1}^n i^2a_i^2\right)^{-1/2}(\hat{b}_{OLS}-b)\xrightarrow{d} N(0,1)$$
WLS is more efficient when $$\left(\sum_{i=1}^n \frac{i^2}{a_i^2}\right)^{1/2}\geq \left(\sum_{i=1}^n i^2\right)\left(\sum_{i=1}^n i^2a_i^2\right)^{-1/2}$$
And this always holds by the Cauchy-Schwarz inequality since it states that $$\left(\sum_{i=1}^n i^2 \right) \leq \left(\sum_{i=1}^n i^2a_i^2\right)^{1/2}\left(\sum_{i=1}^n \frac{i^2}{a_i^2}\right)^{1/2}$$ So this shows that the WLS estimator is more efficient whenever its Grenander condition is satisfied.


Logic App : Finding element in Json Object array (like XPath fr XML)

Question: In my logic app, I have a JSON object (parsed from an API response) and it contains an object array.
How can I find a specific element based on attribute values... Example below where I want to find the (first) active one
{
    "MyList" : [
        {
            "Descrip" : "This is the first item",
            "IsActive" : "N"
        },
        {
            "Descrip" : "This is the second item",
            "IsActive" : "N"
        },
        {
            "Descrip" : "This is the third item",
            "IsActive" : "Y"
        }
   ]
}

Answer: Well... The answer is in plain sight ... There's a FILTER ARRAY action, which works on a JSON Object (from PARSE JSON action).. couple this with an @first() expression will give the desired outcome.
Answer: You can use the Parse JSON Task to parse your JSON and a Condition  to filter for the IsActive attribute:
Use the following Schema to parse the JSON:
{
  "type": "object",
  "properties": {
    "MyList": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "Descrip": {
            "type": "string"
          },
          "IsActive": {
            "type": "string"
          }
        },
        "required": [
          "Descrip",
          "IsActive"
        ]
      }
    }
  }
}

Here how it looks like (I included the sample data you provided to test it):

Then you can add the Condition:

And perform whatever action you want within the If true  section.
Comment: I guess that'll work ... I'll give it a try ... thanks


Segmentation fault: branch and bound em c

Question: Estou com um erro persistente em meu código. Meu objetivo é achar o caminho em um labirinto montado em uma matriz com um algoritmo do tipo branch and bound. Segue o código:
FILE *ent;
FILE *saida;
int NL;
int temp;
char c;
struct labirintos{
    int **lab;
};
struct labirintos *vetor;
int resolveLab(int **lab, int altura, int largura, int alturaInicial, int larguraInicial, int possibilidades);

int main() {
//declarações e abertura de arquivos
ent = fopen("ent.txt", "r"); //ent= fopen (argv[1], "r");
saida = fopen("sai.txt", "w"); //saida= fopen (argv[2], "w");

//ler arquivo de entrada e declarações
int i, j, k, largura = 0, altura = 0, larguraInicial = 0, alturaInicial = 0, possibilidades = 0;
fpos_t position;
char isCharacter;

fscanf(ent, "%d", &NL);
vetor = malloc(NL*sizeof(struct labirintos));
fprintf (saida, "%d\n", NL);
for(i = 0; i < NL; i++){
    fscanf(ent, "%d %d", &largura, &altura);
    fprintf (saida, "%d %d\n", largura, altura);
    //alocando o labirinto
    vetor[i].lab = malloc(altura*sizeof(int*));
    for(j = 0; j < altura; j++)
        vetor[i].lab[j] = malloc(largura*sizeof(int));
    //salvando arquivo no lab
    for(k = 0; k < altura; k++){
        for(j = 0; j < largura; j++){
            fgetpos (ent, &position);
            fscanf(ent, "%c", &isCharacter);
            if(isalpha(isCharacter)){
                    vetor[i].lab[k][j] = 5;
                    fgetpos (ent, &position);
                    alturaInicial = k;
                    larguraInicial = j;
            }
            else{
                fsetpos(ent, &position);
                fscanf(ent, "%d ", &temp);
                vetor[i].lab[k][j] = temp;
                if (temp == 0)
                    possibilidades++;
            }
            fprintf(saida, "%d ", vetor[i].lab[k][j]);
            printf("%d ", vetor[i].lab[k][j]);
        }
        fprintf(saida, "\n");
        printf("\n");
    }
    printf("resultado: %d \n", resolveLab(vetor[i].lab, altura, largura, alturaInicial, larguraInicial, possibilidades));
    printf("\n");
}
fclose(ent);
fclose(saida);
return 0;
}

//funcao resolve lab
int resolveLab(int **lab, int altura, int largura, int alturaInicial, int larguraInicial, int possibilidades){
struct passo{
     int altura, largura, tentativas;
};

int j = larguraInicial, k = alturaInicial, i = 0, resolvido = 0, tentativaAtual = 0;
struct passo vetor[possibilidades*3];
if(k == 0 || k == altura || j == 0 || j == largura)
    resolvido = 1;
while(!resolvido){
    if(tentativaAtual < 4){
       if(lab[k][j+1] == 0){
            lab[k][j] = 1;
            lab[k][j+1] = 5;
            vetor[i].altura = k;
            vetor[i].largura = j++;
            vetor[i].tentativas = 1;
        }
        else if(lab[k+1][j] == 0){
            lab[k][j] = 1;
            lab[k+1][j] = 5;
            vetor[i].altura = k++;
            vetor[i].largura = j;
            vetor[i].tentativas = 2;
          }
        else if(lab[k][j-1] == 0){
            lab[k][j] = 1;
            lab[k][j-1] = 5;
            vetor[i].altura = k;
            vetor[i].largura = j--;
            vetor[i].tentativas = 3;
        }
        else if(lab[k-1][j] == 0){
            lab[k][j] = 1;
            lab[k-1][j] = 5;
            vetor[i].altura = k--;
            vetor[i].largura = j;
            vetor[i].tentativas = 4;
        }
        else
            tentativaAtual = 4;
    }
    else{
        while (i > 0 && vetor[i].tentativas > 4){
            i--;
            lab[k][j] = 1;
            k = vetor[i].altura;
            j = vetor[i].largura;
            lab[k][j] = 5;   /****** O erro ocorre aqui *******/
        }
        if (vetor[i].tentativas == 4 && i == 0)
            break;
    }
    i++;
    if(k == 0 || k == altura || j == 0 || j == largura)
        resolvido = 1;
}
return resolvido;
}

Nas linhas assinaladas acima é apontado:

segmentation fault

É como se o vetor não estivesse armazenando os dados como deveria.
A matriz lab passada é desse tipo:
1  1  1  1  1
1  0  0  0  1
1  0  X  0  1
1  1  0  1  1

Onde X corresponde a posição inicial, 0 corresponde aos caminhos livres, 1 corresponde as paredes e possibilidades é a quantia de caminhos livres disponíveis.
Há também uma hierarquia nos movimentos onde: (Direita) (Frente) (Esquerda) (Trás), estão ordenados da maior a menor prioridade.

ent.txt
2
5 4
1 1 1 1 1
1 0 0 0 1
1 0 X 0 1
1 1 0 1 1
3 4
1 1 1
1 X 1
1 0 1
1 1 1

Sou grato a qualquer tipo de ajuda.
Comment: Bem vinda ao SOpt, você poderia postar como ficou sua main chamando essa função ?
Comment: De um exemplo do ficheiro `ent.txt` se puder.
Comment: Para leitura correcta do ficheiro deves ignorar espaços em branco ao ler o caracter: `fscanf(ent, " %c", &isCharacter);` senão `isCharacter` fica com espaços ou newlines.
Answer:         k = vetor[i].altura;
        j = vetor[i].largura;
        lab[k][j] = 5;   /****** O erro ocorre aqui *******/

Se interpretei bem o teu código (não li com atenção) o erro ocorre por tentares aceder a um elemento do array lab que nao existe.
Se vetor[i].altura (k) é o número de elementos de lab, o último elemento pode-se aceder com lab[k - 1]. O elemento lab[k] não existe!
Da mesma forma para a largura.
Comment: Mas os índices do vetor[i] foram gravados com as posições previamente acessadas na matriz lab.
Comment: @Ariel faz um `printf` antes e outro depois de `lab[k]` e já consegues ver se é mesmo ai o erro.
Comment: por exemplo: `fprintf(stderr, "Alterando lab[%d][%d] para 5\n", k, j);`
Comment: Vocês tinham razão, eu estava acessando um elemento inválido no vetor ^^
agora que arrumei isso, colocando um --i; antes do acesso, tá tudo perfeito hahahah.

Muito obrigado!


Pass an array of nids to a view

Question: How do I pass a view an array of node ids?  I can create the view using the ui, but the query I want to run is outside the scope of views.  I want to run the db query independently, gather the node ids into an array, and then pass it to the view for display.  Howvian I make this happen, if at all?
Comment: Can you please explain this a little more? You can to create a view that shows a in each row a different node?
Comment: thanks guys... These are great answers. I get quicker and better answers here than on drupal.org!
Answer: You can add a "Content: Nid" contextual filter to your view, so your view will narrow down the content to the NIDs you provided. Make sure you check the "Allow multiple values" box when configuring the contextual filter. This will allow a url like example.com/myview/12+45+78 which would limit the results to node IDs 12, 45 and 78.
Answer: If you want to display these nodes formatted with a view_mode, and not for example in a table, you could also use the API for that: node_view_multiple().
Simply pass the array of nid's with the desired $view_mode to that function and it will return an render array that you can return in a block or page callback or directly render with drupal_render().

Pass an array of nids to a view


Proving $\pi=(27S-36)/(8\sqrt{3})$, where $S=\sum_{n=0}^\infty\frac{\left(\left\lfloor\frac{n}{2}\right\rfloor!\right)^2}{n!}$

Question: I have to prove that:
$$\pi=\frac{27S-36}{8\sqrt{3}}$$
where I know that $$S=\sum_{n=0}^\infty\frac{\left(\left\lfloor\frac{n}{2}\right\rfloor!\right)^2}{n!}$$
Where do I get started?
Comment: Sometimes I wonder how someone comes up with a question like that, forget about the answer :)
Comment: I think flagging this as missing detail is a misuse of that flag. The question is indubitably clear. I don't think the OP should be penalised for not even knowing where to start—after all, the question just asks for help on where to start, not for a whole solution to copy verbatim and turn in.
Comment: @YuiToCheng That's the fault of the answerer, not the OP.
Comment: @YuiToCheng Why are the only two choices "A tailor-made hint that takes into account all of the OP's mathematical background" and "A full solution"? A third option: a general guide on how to get started. It's done all the time.
Comment: That's a nice question! What did you try?
Comment: @Jan I do not have a clue where to start.
Comment: I have recently read somewhere a proof of this beautiful equation. Maybe this can be useful: $$ \frac{n!}{(\lfloor \frac{n}{2} \rfloor !)^2} $$ is called the 'swinging factorial' of $n$
Comment: @gen-zreadytoperish But the accepted answer has given the whole solution. They have obviously ignored your comment.
Comment: @gen-zreadytoperish If the OP doesn't present his background/ effort/ what he knows, how can the answer tailor-make a hint?
Answer:
Assignment:
Prove:
$$\pi=\frac{27\mathcal{S}-36}{8\sqrt{3}}$$
Where:
$$\mathcal{S}:=\sum_{\text{n}\space\ge\space0}\frac{\left(\left\lfloor\frac{\text{n}}{2}\right\rfloor!\right)^2}{\text{n}!}$$
Where $\left\lfloor x\right\rfloor$ is the Floor function.

Solution:
First, let's add the sum over all odd and even numbers:
\begin{equation}
\begin{split}
\mathcal{S}&=\frac{\left(0!\right)^2}{0!}+\frac{\left(0!\right)^2}{1!}+\frac{\left(1!\right)^2}{2!}+\frac{\left(1!\right)^2}{3!}+\frac{\left(2!\right)^2}{4!}+\frac{\left(2!\right)^2}{5!}+\dots\\
\\
&=\underbrace{\sum_{\text{n}\space=\space0}^\infty\frac{\text{n}!\cdot\text{n}!}{\left(2\text{n}+1\right)!}}_\text{odd part}+\underbrace{\sum_{\text{n}\space=\space0}^\infty\frac{\text{n}!\cdot\text{n}!}{\left(2\text{n}\right)!}}_\text{even part}\\
\\
&=\sum_{\text{n}\space=\space0}^\infty\frac{\text{n}!\cdot\text{n}!}{\left(2\text{n}+1\right)!}+\sum_{\text{n}\space=\space0}^\infty\frac{\text{n}!\cdot\text{n}!}{\left(2\text{n}+1\right)!}\cdot\left(2\text{n}+1\right)
\end{split}\tag1
\end{equation}
Now, let's recall that the Gamma function is defined as:
$$\Gamma\left(\text{n}+1\right)=\text{n}!\tag2$$
$\forall\text{n}\in\mathbb{N}_0$.
We can now re-write the factorials using the Gamma function and combine the sums:
\begin{equation}
\begin{split}
\mathcal{S}&=\sum_{\text{n}\space=\space0}^\infty\frac{\Gamma\left(\text{n}+1\right)\cdot\Gamma\left(\text{n}+1\right)}{\Gamma\left(2\text{n}+2\right)}+\sum_{\text{n}\space=\space0}^\infty\frac{\Gamma\left(\text{n}+1\right)\cdot\Gamma\left(\text{n}+1\right)}{\Gamma\left(2\text{n}+2\right)}\cdot\left(2\text{n}+1\right)\\
\\
&=\sum_{\text{n}\space=\space0}^\infty\left\{\frac{\Gamma\left(\text{n}+1\right)\cdot\Gamma\left(\text{n}+1\right)}{\Gamma\left(2\text{n}+2\right)}+\frac{\Gamma\left(\text{n}+1\right)\cdot\Gamma\left(\text{n}+1\right)}{\Gamma\left(2\text{n}+2\right)}\cdot\left(2\text{n}+1\right)\right\}\\
\\
&=\sum_{\text{n}\space=\space0}^\infty\frac{\Gamma\left(\text{n}+1\right)\cdot\Gamma\left(\text{n}+1\right)}{\Gamma\left(2\text{n}+2\right)}\cdot\left(2\text{n}+2\right)
\end{split}\tag3
\end{equation}
Now, recall that the Beta function is given by:
$$\beta\left(x,\text{y}\right)=\frac{\Gamma\left(x\right)\Gamma\left(\text{y}\right)}{\Gamma\left(x+\text{y}\right)}\tag4$$
Applying this to our sum gives:
$$\mathcal{S}=\sum_{\text{n}\space=\space0}^\infty\left(2\text{n}+2\right)\beta\left(\text{n}+1,\text{n}+1\right)\tag5$$
The integral representation of the Beta function is:
$$\beta\left(x+1,\text{y}+1\right)=\int\limits_0^1 t^x\left(1-t\right)^\text{y}\space\text{d}t\tag6$$
Applying this to the sum gives:
$$\mathcal{S}=\sum_{\text{n}\space=\space0}^\infty\left(2\text{n}+2\right)\int\limits_0^1 t^\text{n}\left(1-t\right)^\text{n}\space\text{d}t=2\int\limits_0^1\sum_{\text{n}\space=\space0}^\infty\left(\text{n}+1\right)\left(t\left(1-t\right)\right)^\text{n}\space\text{d}t\tag7$$
Let's recall that:
$$\sum_{\text{k}\space=\space0}^\infty\left(\text{k}+1\right)x^\text{k}=\frac{1}{\left(1-x\right)^2}\tag8$$
This can easily be proven using the Geometric series and differentiating both sides.
Using that we can re-write $(7)$:
$$\mathcal{S}=2\int\limits_0^1\frac{1}{\left(1-t\left(1-t\right)\right)^2}\space\text{d}t\tag9$$

Using a substitution $t-\frac{1}{2}=\frac{\sqrt{3}}{2}\cdot\tan\left(\theta\right)$, it is not hard to prove that:
$$\mathcal{S}=\frac{4}{3}+\frac{8\pi\sqrt{3}}{27}\tag{10}$$
Which I let you do, and that proves your result, because:
$$\mathcal{S}=\frac{4}{3}+\frac{8\pi\sqrt{3}}{27}\space\Longleftrightarrow\space\pi=\frac{27\mathcal{S}-36}{8\sqrt{3}}\tag{11}$$


How to fit map to all markers in React Native maps?

Question: I'm trying to position my map screen so that I can see all markers when the map renders. I've tried fitToCoordinates but I get an error that says "fitToCoordinates is not a function". I' attached a picture of my code.
Comment: How did you pass the ref of `_map`? Is it with `useRef`?
Comment: yes, const _map = React.useRef(null);
Answer: I would do it the following way.

The onLayout method is afaik not documented (I am not using it in the app I'm working on, and it relies pretty heavily on the mapView), but there's a better method to use with the map - onMapReady.
Refs have a property called current, which you have to access, you can't just access them as you did, because in that way it would be undefined.

So try smth like this
const setMapReady = () => {
  if (_map.current) {
    _map.current.fitToCoordinates([{..}, {...}]); // you can pass `animated` here and more props
  }
}

<MapView>
  ref={_map}
  ...
  onMapReady={setMapReady}
</MapView>

Comment: Glad to hear that! :)


Unknown map column when migrating users from CSV file

Question: I'm trying to import the users from CSV file, but the import fails with the following error:

Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'map.sourceid4' in 'where clause', in includes/database/database.inc:2171

Migrate class is:
<?php

/**
 * @file
 * Class for migrating users from a CSV file.
 */

/**
 * Class FooMigrateUsers.
 */
class FooMigrateUsers extends Migration {

  /**
   * Constructor.
   *
   * @inheritdoc
   */
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = t('Foo users from CSV file');

    // Create the migrate source.
    $import_path = drupal_get_path('module', 'foo_migrate') . '/import/users.csv';
    $options = array(
      'header_rows' => 1,
    );

    $this->source = new MigrateSourceCSV($import_path, array(), $options);
    $this->destination = new MigrateDestinationUser();

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'Title' => array(
            'type' => 'varchar',
            'length' => 15,
            'not null' => TRUE,
            'description' => 'Title',
          ),
          'Firstname' => array(
            'type' => 'varchar',
            'length' => 35,
            'not null' => TRUE,
            'description' => 'First name',
          ),
          'Lastname' => array(
            'type' => 'varchar',
            'length' => 35,
            'not null' => TRUE,
            'description' => 'Last name',
          ),
          'Primary email address' => array(
            'type' => 'varchar',
            'length' => 80,
            'not null' => TRUE,
            'description' => 'Primary email address',
          ),
        ),
        MigrateDestinationUser::getKeySchema()
        );

    // Mapped fields

    // We must have a unique username in the Drupal 'users' table.
    // dedupe() takes the Drupal table and column for determining uniqueness.
    $this->addFieldMapping('name', 'Primary email address')
         ->dedupe('users', 'name');
    $this->addFieldMapping('mail', 'Primary email address')
         ->dedupe('users', 'mail');

    //$this->addFieldMapping('pass', 'password');

    // Apply default role.
    $this->addFieldMapping('roles')
         ->defaultValue(DRUPAL_AUTHENTICATED_RID);

    $this->addFieldMapping('field_user_first_name',      'Firstname');
    $this->addFieldMapping('field_user_last_name',       'Lastname');

    $this->addUnmigratedSources(array('Title'));

    $this->addUnmigratedDestinations(array(
      'access',
      'created',
      'data',
      'is_new',
      'language',
      'login',
      'pass',
      'picture',
      'role_names',
      'signature',
      'signature_format',
      'theme',
      'timezone',
    ));

  }

  /**
   * Modifies the row to be imported.
   *
   * @inheritdoc
   */
  public function prepareRow($row) {
    return parent::prepareRow($row);
  }

}

The CSV data is like:
"Title","Firstname","Lastname","Primary email address"
"Mr","Foo","Bar","email@example.com"
"Mrs","Bar","Foo","email@example.com"

Answer: The 'Column not found' (map.sourceid4) error sounds like migration table related to source mapping is not complete.
You should identify the table (e.g. using drush command):
drush sqlq "SHOW TABLES LIKE 'migrate_map_%'"

Note: You can also execute above in SQL editor by using quoted part only.
and check the list of available columns for that table:
$ drush sqlq "DESC migrate_map_foomigrateusers"
sourceid1   varchar(128)    NO  PRI NULL
sourceid2   varchar(128)    NO  PRI NULL
sourceid3   varchar(128)    NO  PRI NULL
destid1 int(10) unsigned    YES     NULL
needs_update    tinyint(3) unsigned NO      0
rollback_action tinyint(3) unsigned NO      0
last_imported   int(10) unsigned    NO      0
hash    varchar(32) YES     NULL

The number of sourceidX column should match with number of columns in CSV file. If they won't, probably you've modified the CSV file and after each structure change you have to re-register your migration class (see: hook_migrate_api).
So please reregister any statically defined migration classes by (check list by drush ms):
drush migrate-deregister FooMigrateUsers
drush migrate-register FooMigrateUsers

In case of further problems, these drush commands can be handy as well:
drush migrate-mappings --all # To verify mapping.
drush migrate-fields-source --all # To list source field mapping.

When ready, try re-importing the data again:
drush mi FooMigrateUsers


The topology on $X / G$ where $G$ acts on $X$

Question: The elements are orbits, but how do we find the neighbourhoods?
In particular, let $G= ( \mathbb R^+ , \cdot )$ and $X=[0, \infty )$.
Let $G$ act on $X$ via the usual multiplication.
Then $X/G = {\bigg \{ } \{0 \} \ , \ (0, \infty )  {\bigg \} }$ has two elements.

I guess the topology on $X/G$ is not discrete. What is it?
Can I consider $G$ only as a group to define a topology on $X/G$? Or
does $G$ have to be a topological group?

Thanks in advance.
Answer: Might be helpful to consider the quotient topology.  Let $\pi: X \to X/G$ be the projection mapping.  Then $U \subseteq X/G$ is open if and only if $\pi^{-1}(U) \subseteq X$ is open.  Using this idea we then have only a few subsets to check.  Clearly $\pi^{-1}(\emptyset) = \emptyset$ and $\pi^{-1}(X/G) = X$.  We then have that $\pi^{-1}(\{\{0\}\}) = \{0\}$ which is not open in $[0,\infty)$.  We do however have that $\pi^{-1}(\{(0,\infty)\}) = (0,\infty)$ which is open in $[0,\infty)$ so this subset is open.  Therefore the topology on $X/G$ is given by
$$
\mathcal{T} \;\; =\;\; \Big\{\emptyset, X/G, \{(0,\infty)\}    \Big\}.
$$
Comment: @ThePortakal By "projection" I mean the map that takes each element of $X$ to its orbit in $X/G$.  So in your example if $x \neq 0$ then $\pi(x) = (0,\infty)$, and $\pi(0) = \{0\}$.  And no, $G$ doesn't need to be a topological group in order for it to act on a topological space.  However, some of the more important/exciting theorems do require a topology on $G$.  Even if $G$ is finite or discrete it is possible to define the discrete topology on $G$, but in this case it is not needed.
Comment: @ThePortakal This is the Sierpinski Space: https://en.wikipedia.org/wiki/Sierpi%C5%84ski_space
Comment: Thanks. Why did you call the map "projection" ? And as I understand from your answer, the group $G$ doesn't have to be a topological group in order to define the topology on $X/G$, is that right?


Is it possible to tune a ukulele in GDAE (Irish tenor)?

Question: I would like to change the tuning of my concert ukulele from GCEA to GDAE. Which kind of string do I need for that (diameter) ? Is it dangerous for the bridge ?
(Ref. my ukulele is a Lanikai LU-21 CE)
Comment: You may be able to tune a ukelele, but you can't tune a fish
Answer: It would not be dangerous for the bridge if the four strings you select to produce that tuning have about the same tension (measured in lbs or kg) as the strings used for standard tuning.
The D'Addario string company publishes an elaborate reference guide for all the strings they sell for guitars and a few other instruments. You can download the PDF of this guide here.
Here is their explanation of the calculations involved:

Understanding what determines string tension.
In order to determine
the tension at which a string will vibrate, you need three pieces of
information: the Unit Weight, the Scale Length, and the Frequency of
the string. You can use
the formulas below to calculate the exact tension for any string using
the scale length of your particular instrument. All of the charts
illustrate string tensions for each string at a variety of pitches, in
case you use alternative tunings.
UW- Unit Weight.
In all the charts and formulas in the brochure, unit
weight is expressed in pounds per linear inch (lb/in).
L- Scale Length. This is the vibrating length of the string. This is determined
by measuring the distance from the nut to the bridge of the instrument
in inches (in).
F- Frequency or pitch. This is the pitch at which you
will be tuning the string expressed in cycles per second (Hertz).
To
calculate the tension of a string in pounds use the formula below,
inserting the three variables described above:
T(Tension)= (UW
x (2 x L x F)^2)/386.4
To convert the result into Newtons, simply multiply
by 4.45.
If you know what tension you want the string to have, you can
calculate the string unit weight. You can then use the charts in this
guide to locate a string with approximately the same desired unit
weight.
UW(unit weight)= (T x 386.4)/(2 x L x F)^2

Read the actual PDF for more information.
Comment: Thanks a lot for your answer. I will check the length of my ukulele and try to find a set with existing UWs.
Answer: Aquila makes a GDAE set for soprano ukes, but I don't think they sell a set with that tuning for concert scale.
They do sell a CGDA concert length set, however.
Answer: I have a cheap Clifden  soprano bought in lidl for 18 e and put standard nylon guitar strings cut down to length and it works fine.Just use 4 high strings and ditch the bass E and A.Just make sure the high E string has a double knot on the end to take the tension without pulling out of the slot if that is the way yours is inserted.


Symmetric polynomial identities: $(x,y,z)^n$ in terms of $\sigma _1=x+y+z$, $\sigma _2 = xy+yz+xz$ and $\sigma _3 = xyz$

Question: In Arthur Engels "Problem Solving Strategies" book in the section on symmetric polynomials, he asks us to prove the identities below.  I read up on expanding trinomials and got the quickest method to be a variation on Pascal's triangle.  Is there a different method to prove these identities; perhaps recursively?
Thanks
Comment: In [wikipedia's article](https://en.wikipedia.org/wiki/Newton's_identities) there are a few proofs.
Comment: @floodbaharak Are you sure? I think it would be better if you'll see my solution. Thank you!
Answer: $$x^2+y^2+z^2=x^2+y^2+z^2+2(xy+xz+yz)-2(xy+xz+yz)=$$
$$=(x+y+z)^2-2(xy+xz+yz)=\sigma_1^2-2\sigma_2;$$
$$x^3+y^3+z^3=\sum_{cyc}x^3=\sum_{cyc}(x^3+x^2y+x^2z)-\sum_{cyc}(x^2y+x^2z+xyz)+3xyz=$$
$$=\sum_{cyc}x^2(x+y+z)-\sum_{cyc}xy(x+y+z)+3xyz=$$
$$=(x^2+y^2+z^2)(x+y+z)-(xy+xz+yz)(x+y+z)+3xyz=$$
$$=(\sigma_1^2-2\sigma_2)\sigma_1-\sigma_2\sigma_1+3\sigma_3=\sigma_1^3-3\sigma_1\sigma_2+3\sigma_3;$$
$$x^2y+x^2z+y^2x+y^2z+z^2x+z^2y=\sum_{cyc}(x^2y+x^2z)=$$
$$=\sum_{cyc}(x^2y+x^2z+xyz)-3xyz=\sum_{cyc}(x^2y+xy^2+xyz)-3xyz=$$
$$=\sum_{cyc}xy(x+y+z)-3xyz=(x+y+z)(xy+xz+yz)-3xyz=\sigma_1\sigma_2-3\sigma_3;$$
$$x^2y^2+x^2z^2+y^2z^2=\sum_{cyc}x^2y^2=\sum_{cyc}(x^2y^2+2x^2yz)-2\sum_{cyc}x^2yz=$$
$$=(xy+xz+yz)^2-2xyz(x+y+z)=\sigma_2^2-2\sigma_1\sigma_3$$ and
$$x^4+y^4+z^4=\sum_{cyc}x^4=\sum_{cyc}(x^4+2x^2y^2)-2\sum_{cyc}x^2y^2=$$
$$=\left(\sum_{cyc}x^2\right)^2-2\sum_{cyc}x^2y^2=(\sigma_1^2-2\sigma_2)^2-2(\sigma_2^2-2\sigma_1\sigma_3)=$$
$$=\sigma_1^4-4\sigma_1^2\sigma_2+2\sigma_2^2+4\sigma_1\sigma_3.$$
Comment: Why someone down voted?


Integral $\int{\frac{1}{(x^{3} \pm 1)^2}}$

Question: I need to solve the following integrals:
$$\int{\frac{1}{(x^3+1)^2}}dx$$
and
$$\int{\frac{1}{(x^3-1)^2}}dx$$
My first thought was to use a trigonometric substitution but the $x^3$ messed it up. Can you guys suggest another method?
Comment: As a hint, integrate by parts (by adding an$\frac{x^2}{x^2}$ and use the numerator ($x^2$) as the derivative of $1\pm x^3$), then let $x=\frac{1}{t}$. Try to add maybe some more context though (e.g. what is obtained after using the above hint).
Comment: Thanks Rob Pratt for the edit. I'm using an old computer and I'm having a ton of problems with it working, typing in it is hell.
Comment: You missed your basic differentials, $\mathrm dx.$
Answer: The standard method uses partial fractions decomposition.
Here is how it begins for the first integral: factorout  the denominator into irreducible factors with high-school identities:
$$x^3+1=(x+1)(x^2-x+1)$$
Newt proceed to decompose into partial fractions:
$$\frac{1}{(x^3+1)^2}=\frac{1}{(x+1)^2(x^2-x+1)^2}=\frac A{x+1}+\frac B{(x+1)^2}+\frac {Cx+D}{x^2-x+1}+\frac{Ex+F}{(x^2-x+1)^2}.$$
Answer: $$I=\int{\frac{1}{(x^3+1)^2}}dx$$
$$I=-\int  \frac {1}{3x^2}\color {red}{{\frac{-3x^2}{(x^3+1)^2}}}dx$$
The function in red is a derivative.
$$I=-\int  \frac {1}{3x^2}\color {red}{ \left ({\frac{1}{x^3+1}} \right )'}dx$$
The integral is now of the form:
$$ \color {blue}{I=\int f(x) g'(x)dx}$$
Integrate by part
$$ \color {blue}{\int f(x) g'(x)dx=f(x)g(x)-\int f'(x)g(x) dx}$$
$$I=- \frac {1}{3x^2}{\frac{1}{(x^3+1)}}-\frac {2}{3}\int  \frac {1}{x^3}{\frac{1}{(x^3+1)}}dx$$
$$I_2=\int  \frac {1}{x^3}{\frac{1}{(x^3+1)}}dx$$
$$I_2=\int  \frac {dx}{x^3}-\int {\frac{dx}{(x^3+1)}}$$
$$I_2=-  \frac {1}{2x^2}-\int {\frac{1}{(x^3+1)}}dx$$
So that we have :
$$I=\frac x{3(x^3+1)}+\frac23\int\frac1{x^3+1}dx$$
Then use fraction decomposition method for that integral.
Comment: Thanks a lot! Just one question, how did you go from the second to the third step? How is that method called?
Comment: Integration by part where one of the function is a derivative....You first tarnsform the original integral into a product of a function and another one thats a derivative....Do you know the integral of $f(x)=-\frac 1 {x^2}$  it's a derivatvie the integral of a dervative..I did the same here.
Answer: There's been a lot of this lately so what if we want to do
$$\begin{align}\int\frac{dx}{(x^n+a)^m}&=\frac1a\int\frac{(x^n+a-x^n)dx}{(x^n+a)^m}\\
&=\frac1a\int\frac{dx}{(x^n+a)^{m-1}}-\frac1a\int\frac{x\cdot x^{n-1}dx}{(x^n+a)^m}\\
&=\frac1a\int\frac{dx}{(x^n+a)^{m-1}}+\frac x{a(m-1)n(x^n+a)^{m-1}}\\
&\quad-\frac1{a(m-1)n}\int\frac{dx}{(x^n+a)^{m-1}}\\
&=\frac{mn-n-1}{a(m-1)n}\int\frac{dx}{(x^n+a)^{m-1}}+\frac x{a(m-1)n(x^n+a)^{m-1}}\\
&=\frac{a^{m-1}\Gamma\left(m-\frac1n\right)\Gamma(m-1)}{a^m\Gamma\left(m-1-\frac1n\right)\Gamma(m)}\int\frac{dx}{(x^n+a)^{m-1}}+\frac x{a(m-1)n(x^n+a)^{m-1}}\end{align}$$
So we can say
$$\begin{align}\frac{a^m\Gamma(m)}{\Gamma\left(m-\frac1n\right)}\int\frac{dx}{(x^n+a)^m}&=\frac{a^{m-1}\Gamma(m-1)}{\Gamma\left(m-1-\frac1n\right)}\int\frac{dx}{(x^n+a)^{m-1}}\\
&\quad+\frac{a^{m-1}\Gamma(m-1)x}{n\Gamma\left(m-\frac1n\right)(x^n+a)^{m-1}}\\
&=\frac a{\Gamma\left(1-\frac1n\right)}\int\frac{dx}{x^n+a}+\sum_{k=2}^m\frac{a^{k-1}\Gamma(k-1)x}{n\Gamma\left(k-\frac1n\right)(x^n+a)^{k-1}}\end{align}$$
For the purposes of this question, let $a=\pm1$, $\omega^3=-a$, then
$$\frac1{x^3+a}=\sum_{k=1}^3\frac{A_k}{x-\omega^{2k-1}}$$
Where we can compute
$$A_k=\lim_{x\rightarrow\omega^{2k-1}}\frac{x-\omega^{2k-1}}{x^3+a}=\frac1{3\omega^{4k-2}}=\frac{\omega^{2k-1}}{3(-a)^{2k-1}}=-\frac{\omega^{2k-1}}{3a}$$
Then
$$\int\frac{dx}{x^3+a}=-\frac1{3a}\sum_{k=1}^3\omega^{2k-1}\int\frac{dx}{x-\omega^{2k-1}}=-\frac1{3a}\sum_{k=1}^3\omega^{2k-1}\ln(x-\omega^{2k-1})+C$$
So the integral is done, but we have a little cleaning up to do. Since $\omega^3=-a$, the other $2$ roots are complex conjugates: $\omega^5=\omega^*$ and we can write
$$\begin{align}\omega\ln(x-\omega)+\omega^*\ln(x-\omega^*)&=\frac12(\omega+\omega^*)\ln(x-\omega)+\frac12(\omega-\omega^*)\ln(x-\omega)\\
&\quad+\frac12(\omega^*+\omega)\ln(x-\omega^*)+\frac12(\omega^*-\omega)\ln(x-\omega^*)\\
&=\Re\omega\ln(x^2-2\Re\omega x+1)+2i\Im\omega\cdot i\tan^{-1}\left(\frac{-\Im\omega}{x-\Re\omega}\right)\end{align}$$
For $a=1$, $\omega=e^{\pi i/3}=\cos(\pi/3)+i\sin(\pi/3)=\frac12+\frac i2\sqrt3$, while for $a=-1$, $\omega=e^{2\pi i/3}=-\frac12+\frac i2\sqrt3=\frac a2+\frac i2\sqrt3$ in both cases. Thus our formula becomes
$$\int\frac{dx}{x^3+a}=-\frac1{3a}\left\{\frac a2\ln(x^2-ax+1)+\sqrt3\tan^{-1}\left(\frac{\sqrt3}{2x-a}\right)-a\ln(x+a)\right\}$$
Thus for $n=3$, $m=2$, and $a=1$ we get
$$\begin{align}\int\frac{dx}{(x^3+1)^2}&=\frac{0!x}{(1)1!(3)(x^3+1)}+\frac{\left(1-\frac13\right)}{(1)1!}\left(-\frac1{3(1)}\right)\left\{\frac{(1)}2\ln(x^2-(1)x+1)\right.\\
&\quad\left.+\sqrt3\tan^{-1}\left(\frac{\sqrt3}{2x-(1)}\right)-(1)\ln(x+(1))\right\}+C\\
&=\frac{x}{3(x^3+1)}-\frac29\left\{\frac12\ln(x^2-x+1)\right.\\
&\quad\left.+\sqrt3\tan^{-1}\left(\frac{\sqrt3}{2x-1}\right)-\ln(x+1)\right\}+C\end{align}$$
Checked while for $n=3$, $m=2$, and $a=-1$ we have
$$\begin{align}\int\frac{dx}{(x^3-1)^2}&=\frac{0!x}{(-1)1!(3)(x^3-1)}+\frac{\left(1-\frac13\right)}{(-1)1!}\left(-\frac1{3(-1)}\right)\left\{\frac{(-1)}2\ln(x^2-(-1)x+1)\right.\\
&\quad\left.+\sqrt3\tan^{-1}\left(\frac{\sqrt3}{2x-(-1)}\right)-(-1)\ln(x+(-1))\right\}+C\\
&=-\frac{x}{3(x^3-1)}-\frac29\left\{-\frac12\ln(x^2+x+1)\right.\\
&\quad\left.+\sqrt3\tan^{-1}\left(\frac{\sqrt3}{2x+1}\right)+\ln(x-1)\right\}+C\end{align}$$
Also checked. Lets see... my formulas have problems with discontinuities and domains so I should probably change
$$\tan^{-1}\left(\frac{\sqrt3}{2x\pm1}\right)$$
to
$$\frac{\pi}2-\tan^{-1}\left(\frac{2x\pm1}{\sqrt3}\right)$$
And also $\ln(x\pm1)$ t0 $\ln\lvert x\pm1\rvert$ to fix these problems.
Perhaps a little long-winded but I wanted to sum the recurrence relation in case a higher power of the denominator was assigned next week.
Comment: In the first and second lines, the first integral should be, $\displaystyle\int \dfrac{dx}{(x^n + a)^{m-1}}$
Comment: @Aaratrick Thanks you your careful reading of my post! Corrected.
Answer: Hint:
Simplify
$$\int{\frac{1}{(x^3+1)^2}}dx=\frac x{3(x^3+1)}+\frac13\int\frac2{x^3+1}dx$$
Then, decompose
$$\frac2{x^3+1}=\frac1{x+1}+\frac{1}{x^2-x+1}- \frac{x^2}{x^3+1}$$
Answer: $$
\begin{aligned}
I &=\int \frac{1}{\left(x^{3}+1\right)^{2}} d x \\
&=-\frac{1}{3} \int \frac{1}{x^{2}} d\left(\frac{1}{x^{3}+1}\right) \\
&=-\frac{1}{3 x^{2}\left(x^{3}+1\right)}-\frac{2}{3} \int \frac{1}{x^{3}\left(x^{3}+1\right)} d x \\
&=-\frac{1}{3 x^{2}\left(x^{3}+1\right)}-\frac{2}{3} \int\left(\frac{1}{x^{3}}-\frac{1}{x^{3}+1}\right) d x \\
&=-\frac{1}{3 x^{2}\left(x^{3}+1\right)}+\frac{1}{3 x^{2}}+\frac{1}{3} \int \frac{d x}{x^{3}+1}
\end{aligned}
$$
By my post,
$$
\therefore I=\frac{1}{18}\left[\frac{6 x}{\left(x^{3}+1\right)}+\ln \left|\frac{(1+x)^{2}}{1-x+x^{2}}\right|+2 \sqrt{3} \tan ^{-1}\left(\frac{2 x-1}{\sqrt{3}}\right)\right]+C
$$


Displaying Lots of Images Using One PHP File

Question: I hope someone will help me with this. Namely, I need a PHP code which will display images in a HTML/PHP page based on their id. For example: the file ShowPicture.php, and the code in it something like this:
PictureID = "MyPicture1"
MyPicture1_Source = "/Pictures/Picture1.jpg";
PictureID = "MyPicture2"
MyPicture2_Source = "/Pictures/Picture2.png";
PictureID = "MyPicture3"
MyPicture3_Source = "/Pictures/Picture3.gif";
PictureID = "MyPicture4"
MyPicture4_Source = "/Pictures/Picture4.bmp";

Example of usage on the pages:
HTML/PHP PAGE 1:
HTML/PHP PAGE 4:
HTML/PHP PAGE 2:
HTML/PHP PAGE 3:

I don't currently use any code since I didn't find good enough which will suit this particular need of mine.
The file should be something like Facebook's rsrc.php file, which fetches all the graphics for the site whilst hiding the real source path.
EDIT: I do not need Sessions nor Cookies, I want the pictures to be displayed permanently on pages through PHP, even after the user refreshes/reloads the pages.
EDIT 2: No (My)SQL. The PHP file itself and alone must be sort of a database for storing and displaying images.
Comment: So basicly you want a secure way to display images, but you don't want to use the tools that are required for that? Well in that case, show us what you've tried yourself. Because as you know, SO is here to help with issues you have with your code. Not to do your job for you.
Comment: Have a look at my answer on this question: [Gettings private files or showing private images in a HTML page](http://stackoverflow.com/questions/32410732/gettings-private-files-or-showing-private-images-in-a-html-page/32412736#32412736). It's not 100% the same, but you should easily be able to adept the idea to what you want. The code keeps the actual path to images 100% secure. Even if you know the direct link to the image, you won't be able to access it.
Comment: @icecub I have tried nothing yet due to the lack of appropriate code. I am not expecting you to do the job for me if you are not skillful enough. That's why I explained close enough what I need, if it can be achieved so.
Comment: It has nothing to do with being skilled enough or not. Basicly what you are asking is the equivalent of **I want to secure my house, but I don't want to use any doors or locks**. It's not possible. You can put guards and dogs and weapons everywhere, your house is still wide open.
Comment: It doesn't have to be **secure** way, it only has to be a way for accomplishing it. Regardless of security. Gotcha? :-)
Comment: you need masking the call for example the url page will be img.php?image=1234, on the code behind read the image and return in the response as image...
Comment: @icecub You wanted code, so here it is, but it doesn't work:
``

And  won't display any picture.
Comment: I've written the code for you. Next time leave the attitude behind. Stack Overflow has pretty strict rules regarding what kind of questions you can ask and what is expected from you when asking. No one here is trying to be an ass to you. We're just keeping people out that are looking for a free programmer to do their work.
Answer: I wanted you to put efford in it yourself. Stack Overflow is ment to help you when you have issues with your code. It's not ment for people that just want some programmer to do all the work for them. Anyway, I've taken a few minutes to do it for you now, so here it is:
<?php

$id = $_GET["id"];

switch($id){
    case "MyPicture1":
        $file = "img/img1.jpg";
        break;
    case "MyPicture2":
        $file = "img/img2.jpg";
        break;
    case "MyPicture3":
        $file = "img/img3.jpg";
        break;
    case "MyPicture4":
        $file = "img/img4.jpg";
        break;
    default:
        echo "Invalid ID given!";
        exit;
}

if(file_exists($file)){
    $size = getimagesize($file);
    $fp = fopen($file, 'rb');

    if($size and $fp){
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
        header('Content-Type: '.$size['mime']);
        header('Content-Length: '.filesize($file));

        fpassthru($fp);
    }

    exit;
} else {
    echo "File not found!";
}

?>

You can modify it any further yourself.
Comment: Thank you. I am still a novice with PHP.
Comment: @DejanVasiljević No problem. Please click "Accept answer" next to the answer. It's a way to show your appreciation to the one that helped you out as well as making sure your question doesn't remain unanswered forever.
Comment: Of course I will, once I clarify/fix this:
I loaded my image with  and it rendered like this: http://s32.postimg.org/3pg24o5vp/2016_05_05_225424.jpg It is full path, but still won't load. If I enter the picture's full path in the URL bar, it loads normally. Now, I wonder is it a .htaccess problem or the problem in your file?
Comment: @DejanVasiljević It's probebly not a htaccess problem. Otherwise none of the images would work. It could be though that it's case sensative and you didn't notice that. Without seeing your code / server it's hard for me to guess what's going on.
Comment: Error log file:
`[06-May-2016 16:51:16 UTC] PHP Warning:  Cannot modify header information - headers already sent by (output started at Pictures.php:1) in Pictures.php on line 18

[06-May-2016 16:51:16 UTC] PHP Warning:  Cannot modify header information - headers already sent by (output started at Pictures.php:1) in Pictures.php on line 19

[06-May-2016 16:51:16 UTC] PHP Warning:  Cannot modify header information - headers already sent by (output started at Pictures.php:1) in Pictures.php on line 20`
Comment: @DejanVasiljević Make sure that you do not have _any_ whitespace before your opening `<?php` tag.


How can we make a JavaScript property global?

Question: Please refer the below example code
var report = {
    chartTypes : null,
    init: function () {
        this.getChartTypes(function(data){
            this.chartTypes = data;
        });
    },

    getChartTypes: function(callback) {
        $.ajax({
            data:'',
            url:'',
            success:function(response){
               chartTypes = JSON.parse(response);
               callback(chartTypes);
            }
        });
    },
    getToolbar:function() {
        this.chartTypes --------------- NULL
    }
}

getChartTypes function load different chart types via AJAX. Therefore i put it as a callback function. Data is received successfully. But when i use this.chartTypes in a different function like getToolbar it says this.chartTypes is null. Even i have initialized the same in the starting. May be scope issue. Please advise.
Comment: @NeilMunro this is *not* primarily a scope issue - it's an async issue
Comment: @Alnitak — Probably, we can't see how the two functions are called in relation to each other though.
Comment: It is neither scope nor async (although there might be an additional async problem). `this.chartTypes` simply doesn't refer to the global variable `chartTypes`.
Comment: This has been answered before here: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript
Comment: You seem to be assigning a value of the `chartTypes` variable inside the AJAX success callback. So before calling the `getToolbar` function which reads this variable you should make sure that the `getChartTypes` function has been called and the AJAX request has successfully finished executing.
Comment: @Alnitak This is a scope issue too
Comment: @Quentin yes, there's that too, but once that's fixed he still has the async problem
Comment: Seems weird to use callbacks when you are using an OOP approach.
Answer: You are assigning to a variable (probably global) called chartTypes, but that isn't the same as reoprt.chartTypes. You need to assign to this.chartTypes, but this in your anonymous function won't be the same as this outside it, so you need to remember that value using another variable:
getChartTypes: function(callback) {
    var self = this;
    $.ajax({
        data:'',
        url:'',
        success:function(response){
           callback( self.chartTypes = JSON.parse(response) );
        }
    });
}

Comment: It seems to be working. But getToolbar function is called from two places. For the first time chartTypes contains the expected value. But again it is null. How can we make it global so that it does not became empty.
Comment: @manashb Maybe you have the async issue as well. Are you calling `getToolbar` before the Ajax response comes back, like `report.getChartTypes(); report.getToolbar();`, that would return null, since the Ajax callback hasn't executed yet.
Comment: Paulpro there is no async issue. getToolbar is called only after AJAX response comes back. But the AJAX function is called only once and getToolbar function is called two times. First time chartType is not empty but 2nd time it is empty.
Comment: @manashb Something else must be setting it back to null then. Once it's set it won't be changed unless it is reassigned a new value. Is your `report` object still in scope? (`console.log( report );`)
Comment: Resolved. Thanx for your reply. it is really helpful
Answer: With an OOP approach, most developers would use a method and use .bind() to maintain the proper scope when the asynchronous success method is triggered. This way you do not have to worry about closures and using variables to hold the scope of this.
var report = {
    chartTypes : null,
    init: function () {
        this.getChartTypes();
    },

    getChartTypes : function(callback) {
        $.ajax({
            data:'',
            url:''
        }).done(this._setSuccessResponse.bind(this));
    },

    _setSuccessResponse : function(data){
        this.chartTypes = data;
    },

    getToolbar : function() {
        console.log(this.chartTypes);
    }
}

You also need to make sure that when you call getToolbar that the Ajax call has also been completed.


What are the difficulties of playing a musical saw?

Question: I'm interested in playing around with a musical saw, like the theme from One Flew Over The Cuckoo's Nest.
Looking around and watching a few tutorial videos, it looks like a very easy instrument to pick up and play; it seems like you don't need anywhere near the bow control that you need for a decent violin sound.
I'm concerned that a) it will be difficult to control the pitch you're playing at, and b) that it's harder than it looks to get the bowing right (I don't play a string instrument)
so, what are some of the technical issues I should consider, and how easy is the musical saw, as an instrument, to play?
Answer: I own a musical saw. I have found it very difficult to get started, and gave up before being able to play a simple tune with any kind of fluency.
The first challenge is to coax a clean note out of the saw. You must bend the saw into an 'S' shape, and bow at the resonant position. If you bow in the wrong place, you'll get an ugly scrape. If you bow in just the right place, you'll get the pure ringing saw sound you're used to. There is a right amount of pressure - too light and the sound will be thin. Too heavy and the sound will be dull.
Many people use a "cheat" to make forming the 'S' shape easier - this is a wooden handle with a slot into which the end of the saw fits. It just gives you some leverage instead of having to hold the end in a tiring, vice-like grip.
Then, when you change the depth of the 'S' to change the pitch, the resonant position changes, so you have to bow in a different place. To play fluently, you need to constantly move the bowing position to correspond to the pitch.
On top of that, as you've already noted, you have to intonate by ear - which may or may not be a challenge for you.
Perhaps with one-to-one instruction it would be easier. I think with a teacher telling me how much pressure to apply to the bow, how much rosin to put on, and so forth, I might have got further.
I still believe it would be an extremely satisfying skill to gain.
Answer: Easy to learn to make noise with, difficult to learn to play well. Perhaps this is why there aren't that many sawists... The NYC Musical Saw Festival has workshops included in the festival's price of $10. Probably the best deal www.MusicalSawFestival.org Private lessons available also.
The type of saw you get also can greatly help speed up the learning process. I suggest you e-mail your questions through the festival's 'Contact' page.