Get sql max datetime of multiple rows

Question: This statement returns 2 rows:
SELECT ts.UnitId,ts.TeststepId, MAX(ts.CreatedAt)as CreatedAt
FROM Teststep ts
INNER JOIN Unit u ON ts.UnitId = u.UnitId
Where u.TemplateId = 2
Group by TeststepId, ts.UnitId

How can I get the one row with the highest CreatedAt date ? Should I distinct the unitId?
UPDATE
Aaron and flem aksed for more info:
1 Template has N Units
1 Unit has N Teststeps

The clustered primary key of the Teststep table is TeststepId and CreatedAt.
[TeststepId] [int] NOT NULL,

[Name] [nvarchar](50) NOT NULL,

[PreCondition] [nvarchar](500) NOT NULL,

[TestInstruction] [nvarchar](500) NOT NULL,

[ExpectedResult] [nvarchar](500) NOT NULL,

[CreatedAt] [datetime] NOT NULL,

[CreatedBy] [nvarchar](50) NOT NULL,

[UnitId] [int] NOT NULL,

The Teststep table
sample data with the most important fields in the Teststep table could be:

The teststep shows historized teststeps. From the above image you see that the TeststepId = 4 exist 2 times. A historized version (58 sec.) and a current version (59 sec.).
I want to get only the teststepid 4 with 59 seconds to show in a "current" View.
UPDATE 2
I want to get only the teststepid 4 with 59 seconds AND
all other teststepIds with their current date. If there are only rows with different teststepids take those because they are the current rows.
I am just about to change my integration test and find about the solution.
Comment: Can you expand on what you are actually trying to achieve? e.g. What happens when there are more than units?
Comment: Agreed with @flem - do you want "the one row", or do you want one row ***PER UNITID***? Can you please specify so we know which question we're answering, and can you also specify the version of SQL Server?
Comment: @Aaron I updated my question. Your solutions both work, question is which one is faster. Usually there will not exist more than 20 teststeps with the same id but different dates. So i guess the orderby clause is faster than the CTE.
Comment: I can't tell you which one will be faster, but *you* can! Also I'm not sure I understand how they can return the same results, if there is more than one UnitId for any given TemplateId.
Comment: @Aaron sorry I should have posted from the beginning more info. The more I talk the more I see for myself where the problem lies ;-) see Update 2.
Comment: @Elisa you can't change requirements every 10 minutes and expect everyone to keep up with you. If your question has changed because you left important information out, please post a new question. [Please read this meta question](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions).
Comment: @Aaron. Yes you are right. Funny I added more different teststeps to my integration test and my former sql works as expected lol. But your solution is right on my former origion question. I wanted the one teststep and your query got me that with the top(1) etc... I just expressed myself wrong...
Answer: SELECT TOP (1) ts.UnitId, ts.TeststepId, ts.CreatedAt
  FROM dbo.Teststep AS ts
  INNER JOIN Unit AS u
  ON ts.UnitId = u.UnitId
  WHERE u.TemplateId = 2
  ORDER BY ts.CreatedAt DESC;

If you want a row per UnitId, and SQL Server 2005+, then:
;WITH x AS
(
  SELECT ts.UnitId, ts.TestStepId, ts.CreatedAt,
    rn = ROW_NUMBER() OVER (PARTITION BY ts.UnitId ORDER BY ts.CreatedAt DESC)
  FROM dbo.Teststep AS ts
  INNER JOIN Unit AS u
  ON ts.UnitId = u.UnitId
  WHERE u.TemplateId = 2
)
SELECT UnitId, TestStepId, CreatedAt
  FROM x
  WHERE rn = 1;

Comment: The info is in the question. The OP wants the highest CreatedAt value. In the event of a tie, there is no difference.
Comment: I think we have both made assumptions. I've assumed that the OP wants the highest "createAt" for each unit. You've assumed that the OP wants the highest "createAt" for any unit.
Comment: I downvoted before realising I'd also made an assumption. Edit your post and I'll remove it.
Comment: As I stated, I didn't know I'd made an assumption. I'll be more careful next time.
Answer: Another alternative
Try this:
WITH Data AS
(
    SELECT ts.UnitId, ts.TeststepId, ROW_NUMBER() OVER(PARTITION BY UnitId ORDER BY ts.CreatedAt DESC) Position
        FROM Teststep ts INNER JOIN Unit u ON ts.UnitId = u.UnitId
     WHERE u.TemplateId = 2
)
SELECT *
  FROM Data
 WHERE Position = 1

Answer: SELECT TOP 1 x.* FROM
    (SELECT ts.UnitId,ts.TeststepId, MAX(ts.CreatedAt)as CreatedAt FROM Teststep ts
      INNER JOIN Unit u ON ts.UnitId = u.UnitId
      Where u.TemplateId = 2
      Group by TeststepId, ts.UnitId
      ORDER BY ts.CreatedAt DESC) as [x]

Comment: See your discussion with AaronBertrand for my view on this!
Comment: @flem OP only wants the one row returned which contains the `max(ts.CreatedAt)`, which is the first row when orderd by `ts.CreatedAt` in descending order.
Comment: I think that's a little presumptuous. If that were the case, then the answer requires no grouping, just a simple `select top 1 ... where ... order by createdat desc`
Answer: another way:
with cte as (
SELECT ts.UnitId,ts.TeststepId, MAX(ts.CreatedAt)as CreatedAt
FROM Teststep ts
INNER JOIN Unit u ON ts.UnitId = u.UnitId
Where u.TemplateId = 2
Group by TeststepId, ts.UnitId)
select ts.UnitId,ts.TeststepId, CreatedAt from cte where CreatedAt
 =(select MAX(CreatedAt) from cte)

Comment: You should look at the execution plan for this statement oh my... ;-)

Get sql max datetime of multiple rows


How to set browser confirm box focus on cancel?

Question: I want to keep the default focus on cancel in confirm box. The browser based confirm box has default focus on OK. How can i alter it using java script.
Comment: You simply cannot override this.
Comment: You can achieve this by using a simple modal. Try [this](https://craftpip.github.io/jquery-confirm/)
Answer: You cannot change that. It's a behaviour which is dependant on the browser and/or OS at a level much lower than JS code has access to.
If you need to achieve this, I'd suggest using a library which overwrites the standard confirm() behaviour with a HTML-based modal which can be amended in whatever manner you require.
Comment: I've never done this personally, so can't recommend any. There does appear to be a *lot* of them if you Google.
Comment: @Ashutoshdwivedi the number of options are unlimited including simply writing your own, and it is based on your needs, I would suggest a google search
Comment: @AmrElgarhy Sure.
Comment: `Sweet Alert` maybe
Answer: You can't.  This is simply under the browsers control - the spec for confirm says the browser has to:

Show message to the user, and ask the user to respond with a positive or negative response.

It's entirely up to the browser how it does that, and you can't affect it from JavaScript.


Is it possible to add a user to an Analytics profile using the Management API?

Question: Instead of asking clients to log in their Analytics Admin panel, click "New User" and then entering my email address, I would like just to point them to a link where they can authorize an app which will do that automatically for them.
Here's a printscreen of the process: https://i.stack.imgur.com/37Nyn.png
Can this be done with one of the Analytics APIs? Or is there already an app which can do that?
Answer: No. The Google Analytics management API is currently read only.
And it doesn't have any methods that handle users. Not even user listing.


How to retain the dropdown value inside gridview after footer button click

Question: I have a Dropdown1 outside gridview contains three options Select,A,B.
Inside gridview two dropdowns Dropdown2,Dropdown3  in which Dropdown2 contains three options say Select,C,D.
Based on Dropdown1 & Dropdown2, I am populating Dropdown3 using onchange event in javascript in Dropdown2.
everything working fine for First row but when I add new row, Dropdown3 value vanishes to default "Select"

Javascript function
function DataformatFetch(Selection) {
                var status = Selection.options[Selection.selectedIndex].value;
                var row = Selection.parentNode.parentNode;
                var rowIndex = row.rowIndex - 1;

                if (document.getElementById("<%=DropDown1.ClientID%>").value == "A") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1","1");
                            Dataformatlist.options[2] = new Option("2","2");
                            Dataformatlist.options[3] = new Option("3","3");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("11","11");
                            Dataformatlist.options[2] = new Option("22","22");
                            Dataformatlist.options[3] = new Option("33","33");
                            break;
                    }
                }

                else if (document.getElementById("<%=DropDown1.ClientID%>").value == "B") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("111","111");
                            Dataformatlist.options[2] = new Option("222","222");
                            Dataformatlist.options[3] = new Option("333","333");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1111","1111");
                            Dataformatlist.options[2] = new Option("2222","2222");
                            Dataformatlist.options[3] = new Option("3333","3333");
                            break;
                    }
                }
            }

ASPX code
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Object Type">
                                <ItemTemplate>
                                   <asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);">
                                        <asp:ListItem Value="Select">Select</asp:ListItem>
                                        <asp:ListItem Value="C">C</asp:ListItem>
                                        <asp:ListItem Value="D">D</asp:ListItem>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>

C# code
 private void AddNewRowToGrid()
        {
            try
            {
                if (ViewState["CurrentTable"] != null)
                {
                    System.Data.DataTable dtCurrentTable = (System.Data.DataTable)ViewState["CurrentTable"];
                    DataRow drCurrentRow = null;

                    if (dtCurrentTable.Rows.Count > 0)
                    {
                        drCurrentRow = dtCurrentTable.NewRow();
                        //drCurrentRow["REQUESTNO"] = dtCurrentTable.Rows.Count + 1;

                        dtCurrentTable.Rows.Add(drCurrentRow);
                        ViewState["CurrentTable"] = dtCurrentTable;

                        for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                        {
                            TextBox box2 = (TextBox)DataExchangeGridView.Rows[i].Cells[0].FindControl("PTNTextBox");
                            TextBox box3 = (TextBox)DataExchangeGridView.Rows[i].Cells[1].FindControl("PTDTextBox");
                            TextBox box4 = (TextBox)DataExchangeGridView.Rows[i].Cells[2].FindControl("PTRTextBox");
                            DropDownList box5 = (DropDownList)DataExchangeGridView.Rows[i].Cells[3].FindControl("PIPRDropdownlist");
                            DropDownList box6 = (DropDownList)DataExchangeGridView.Rows[i].Cells[4].FindControl("SupplierNameDroplist");
                            DropDownList box7 = (DropDownList)DataExchangeGridView.Rows[i].Cells[5].FindControl("ObjectTypeDropdownlist");
                            DropDownList box8 = (DropDownList)DataExchangeGridView.Rows[i].Cells[6].FindControl("DataformatDropdownlist");

                            dtCurrentTable.Rows[i]["PARTNUMBER"] = box2.Text;
                            dtCurrentTable.Rows[i]["PARTDESCRIPTION"] = box3.Text;
                            dtCurrentTable.Rows[i]["PARTREVISION"] = box4.Text;
                            dtCurrentTable.Rows[i]["PARTIPR"] = box5.Text;
                            dtCurrentTable.Rows[i]["SUPPLIERNAME"] = box6.Text;
                            dtCurrentTable.Rows[i]["OBJECTTYPE"] = box7.Text;
                            dtCurrentTable.Rows[i]["DATAFORMAT"] = box8.Text;
                        }

                        DataExchangeGridView.DataSource = dtCurrentTable;
                        DataExchangeGridView.DataBind();
                    }
                }
                else
                {
                    Response.Write("ViewState is null");
                }
                SetPreviousData();
            }
            catch (Exception rt)
            {
                rt.ToString();
            }
        }

        private void SetPreviousData()
        {
            try
            {
                int rowIndex = 0;
                if (this.DataExTypeDropDownList.SelectedItem.Value == "Import")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                box2.Enabled = box3.Enabled = box4.Enabled = false;
                                box2.Text = string.Empty;
                                box3.Text = string.Empty;
                                box4.Text = string.Empty;
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                //FillDropDownList(box8);

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    //box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                    string XE = box8.Items.FindByText(dt.Rows[i]["DATAFORMAT"].ToString()).Value;
                                    box8.Text = XE;
                                }
                                rowIndex++;
                            }
                        }
                    }
                }
                else if (this.DataExTypeDropDownList.SelectedItem.Value == "Export")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                }

                                rowIndex++;
                            }
                        }
                    }
                }
            }
            catch (Exception er)
            {
                er.ToString();
            }
        }

Comment: Maybe, post back occurs on add row. If so, then you may need to preserve the value using view state or some other suitable method and set it back to ddl
Comment: @Chidambaram Can you explain a bit more with sample code please.
Answer: To start with, the data format is not getting passed back due it being generated client side, so we can add a hidden field to save that value.
<asp:HiddenField ID="selectedValue" runat="server" Value='<%# Eval("Dataformat") %>' />

How we populate that field is adding OnChange to the data format dropdown.
<asp:DropDownList ID="Dropdownlist7" runat="server" OnChange="DataformatSelect(this);">

function DataformatSelect(Selection) {
    var selectedValue = Selection.options[Selection.selectedIndex].value;
    Selection.parentNode.getElementsByTagName('INPUT')[0].value = selectedValue;
}

On the server side, we must return all the data on postback (and on initial load).
private DataTable GetEmptyTable()
{
    var table = new DataTable();
    table.Columns.Add("ObjectType", typeof(string));
    table.Columns.Add("Dataformat", typeof(string));
    return table;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var table = GetEmptyTable();
        table.Rows.Add("Select", "Select");
        GridView1.DataSource = table;
        GridView1.DataBind();
    }
}

protected void btnAddRow_Click(object sender, EventArgs e)
{
    var table = GetEmptyTable();
    DataRow dr;

    foreach (GridViewRow gvr in GridView1.Rows)
    {
        dr = table.NewRow();
        DropDownList ddlObjectType = gvr.FindControl("Dropdownlist2") as DropDownList;
        HiddenField hdnDataFormat = gvr.FindControl("selectedValue") as HiddenField;

        dr[0] = ddlObjectType.SelectedValue;
        dr[1] = hdnDataFormat.Value;

        table.Rows.Add(dr);
    }

    table.Rows.Add("Select", "Select");

    GridView1.DataSource = table;
    GridView1.DataBind();
}

Ensure the Object Type is getting populated with the Bind.
<asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);" SelectedValue='<%# Bind("ObjectType") %>'>

Finally, on page load, we need to sync up the client side generated drop down lists.

function pageLoad() {
    [].forEach.call(document.getElementsByTagName('tr'), function (row, index) {
        if (index == 0) {
            return;
        }

        DataformatFetch(row.cells[0].getElementsByTagName('select')[0]);

        var selectedValue = row.getElementsByTagName('input')[0].value;
        row.cells[1].getElementsByTagName('select')[0].value = selectedValue;
    });
}

Hopefully that fills in any missing gaps to what you already have.
Thanks a lot to add new row in gridview after binding C#, ASP.net
Comment: I modifed your coding according to my requirement but not getting the desired result. Can you check my C# code and tell me where i going wrong. I have uploaded my whole form for your reference.
Comment: Getting JavaScript runtime error: Unable to get property 'options' of undefined or null reference for this line " var status = Selection.options[Selection.selectedIndex].value;"
Comment: I think I have a different number of columns than you, could you please update this line "DataformatFetch(row.cells[0]..." to "DataformatFetch(row.cells[6]..."?
Comment: I am getting the above error after giving cell value to 6 only.
Comment: and getting JavaScript runtime error: 'pageload' is undefined also


tsc not creating the dist folder

Question: All is in the title, trying to compile my TypeScript project to ./bin folder, the tsc commend execute without error resulting in nothing created, can't figure out why.
my tsconfig.json
{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": false,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "lib": ["es6", "es7", "dom", "esnext"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmit": true,
    "noImplicitAny": false,
    "outDir": "bin",
    "removeComments": true,
    "sourceMap": true,
    "target": "es2017",
    "rootDirs": ["src/", "config/"],
    "typeRoots": ["./node_modules/@types", "./typings"]
  },
  "include": ["src/**/*", "./typings"],
  "exclude": ["node_modules", "bin", "**/__mocks__*", "**/*.spec.**", "test", "assets"]
}

In my package.json this is my scripts to compile:
"scripts": {
    "build-ts": "tsc",
    "watch-ts": "tsc -w",
  },

the structure of my project:
rootdir
    |
    |-----src
    |      |----server.ts
    |      |----app.ts
    |-----test
    |-----node_modules
    |-----typings
    |-----config
    |-----tsconfig.json
    |-----package.json

Any idea what I'm doing wrong?
Comment: You need to either remove `"noEmit": true` or pass `--noEmit false` in your `build-ts` script
Comment: Starting with the most obvious: do you have permissions to create folders in that directory? Any errors in the shell? What happens when you run `tsc` directly at a prompt? Glancing over your config, it appears ok.
Comment: when i run the commend it execute without errors
Comment: @RemcoHaszing yes this is it :) thank you, if you write an answer i'll up vote
Answer: The noEmit option causes TypeScript to not emit any files. You need to either remove "noEmit": true or pass --noEmit false in your build-ts script.
Bonus tip: Rename the script to prepack to have npm compile the TypeScript for you when you run npm pack or npm publish.
Comment: Thanks! that worked for me too. I wonder how did it get there? I guess some package/script added it... regard to renaming, you mean literal replace "script" by "prepack" in the package.json? I'm also new to npm and react
Answer: Another situation where TypeScript might not create a dist folder is when "incremental": true or "composite": true is set in compilerOptions in tsconfig.json, and you delete the dist folder without deleting the tsconfig.tsbuildinfo that keeps track of the incremental builds.
If you keep tsconfig.tsbuildinfo around and delete or modify dist, the compiler won't see a need to output anything, since tsconfig.tsbuildinfo is telling it that there's no work to do. The problem is the tsconfig.tsbuildinfo references an old state of dist.
Say your npm run clean command runs rimraf dist. You'll have to update it to also rimraf tsconfig.tsbuildinfo.
Comment: OMG, I was the original poster of this question, 2 year letter, I get the same issue but with composite this time LOOL ...
Comment: In my case it was `"composite": true` setting, which implicitly sets `"incremental": true`.
Comment: I got it with tsconfig.tsbuildinfo when using rimraf dist && tsc. This saved me!
Comment: Finally solved it by deleting tsconfig.tsbuildinfo and then running tsc again. Thanks!!
Answer: Make sure that "outDir": "dist" inside tsconfig.json isn't commented out or isn't referring to another path :)

tsc not creating the dist folder


Problema no meu código Jquery

Question: Pessoal esse é o meu código em PHP
$sql = mysql_query("SELECT * FROM noty");
while($linha = mysql_fetch_array($sql)){
    $notificacao = $linha["notificacao"];

echo"
".$notificacao."
   <input type='text' class='input_edit' value='".$notificacao."'/>

";
}

Como vocês podem ver estou pegando as informações do banco e mostrando. Até ai tudo certo, mas o problema vem no JQuery.
$(document).ready(function(){

$(".adm_edit").on("click", function() {
    $(this).children(".input_edit").show();
    $("#exit_edit").show();
});

$("#exit_edit").click(function() {
    $(".adm_edit").text($(".input_edit").val());
    $(".input_edit").hide();
    $("#exit_edit").hide();
});
});

Cada conteúdo que é gerado pelo banco como vocês podem ver tem uma Input invisível que é mostrada quando o usuário clica no conteúdo. O problema vem depois disso que é quando eu gostaria que quando a Inputquando fosse fechada o conteúdo digitado ali passasse a ser da Div que foi clicada.
Comment: aonde está esse "#exit_edit" no arquivo php? está oculto mesmo?
Comment: **"como vocês podem ver tem uma Input invisível"**, desculpa. Mas não entendi essa frase, entrei num paradoxo.
Comment: Ia tentar ajudar, mas também achei confuso. Talvez alguém possa entender e ajudar, mas de repente é melhor tentar esclarecer melhor. Como não tenho uma noção visual dos elementos ficou meio difícil pra mim entender o que você chama de fechar input e também que div seria essa que teria um conteúdo a ser colocado no input.
Comment: @DiegodeSouzaSilva eu acabei não colocando o código do "exit.php" mas é uma div com "display:none" que serve para esconder a input quando clicada. Caso queira ver o código aqui está ""
Comment: @Zoom desculpe é minha primeira vez postando aqui e eu devia ter detalhado mais, mas sobre sua dúvida a input está com "display:none" e fica visível quando é clicado a div ".adm_edit"
Comment: @joaoPaulo desculpe minha primeira vez postando, mas obrigado por tentar ajudar hehe :). Na próxima vez vou tentar esclarecer melhor.
Answer: Igor, tente armazenar o .adm_edit e o .input_edit atuais em alguma variavel com escopo mais amplo.
$(document).ready(function(){
  (function () {
    var atual = {};
    var inputs = {};

    inputs.exitEdit = $("#exit_edit");
    inputs.admEdit = $(".adm_edit");
    inputs.admEdit.on("click", function() {
      atual.admEdit = $(this);
      atual.inputEdit = atual.admEdit.children(".input_edit");

      atual.inputEdit.show();
      inputs.exitEdit.show();
    });

    inputs.exitEdit.click(function() {
      atual.admEdit.text(atual.inputEdit.val());
      atual.inputEdit.hide();
      inputs.exitEdit.hide();
    });
  })():
});

Note que estou armazenando a div.adm_edit cliacado e o seu respesctivo input.adm_edit em uma variavel... fiz isto dentro de um closure para evitar problemas de escopo futuros.
Comment: Muito obrigado funcionou do jeito que eu queria :) e vou começar tentar utilizar sobre o que você falou sobre armazenar variáveis

Problema no meu código Jquery


Get an array back from an itertools.chain object

Question: Suppose I have list_of_numbers = [[1, 2], [3], []] and I want the much simpler object list object x = [1, 2, 3].
Following the logic of this related solution, I do
list_of_numbers = [[1, 2], [3], []]
import itertools
chain = itertools.chain(*list_of_numbers)

Unfortunately, chain is not exactly what I want because (for instance) running chain at the console returns <itertools.chain object at 0x7fb535e17790>.
What is the function f such that if I do x = f(chain) and then type x at the console I get [1, 2, 3]?
Update:  Actually the result I ultimately need is array([1, 2, 3]).  I'm adding a line in a comment on the selected answer to address this.
Answer: list. If you do list(chain) it should work. But use this just for debugging purposes, it could be inefficient in general.
Comment: How is this inefficient?
Comment: Having imported numpy as np, the one-line version that I'm using now is this:  `x = np.array(list(itertools.chain(*list_of_numbers))`.
Answer: If your ultimate goal is to get a Numpy array then you should use numpy.fromiter here:
>>> import numpy as np
>>> from itertools import chain
>>> list_of_numbers = [[1, 2], [3], []]
>>> np.fromiter(chain(*list_of_numbers), dtype=int)
array([1, 2, 3])
>>> list_of_numbers = [[1, 2]*1000, [3]*1000, []]*1000
>>> %timeit np.fromiter(chain(*list_of_numbers), dtype=int)
10 loops, best of 3: 103 ms per loop
>>> %timeit np.array(list(chain(*list_of_numbers)))
1 loops, best of 3: 199 ms per loop

Comment: looks promising, although I can't seem to get the `%timeit` parts to work.  Some kind of syntax error.  I tried importing `timeit` first, and that did not help.  In general I don't follow your speed comparison. Are you saying that `numpy.fromiter` is the faster option?  If so, is that the main reason for preferring it?
Comment: `%timeit` is part of [IPython shell](http://ipython.org/). Of course speed is one reason to prefer `.fromiter`, plus we don't have to create an intermediate list here.
Answer: You can do it with list(chain).
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
Comment: it doesn't answer the question 'What is the function f such that if I do x = f(chain) and then type x at the console I get [1, 2, 3]?' or the title statement 'Get a "plain old" array back from an itertools.chain object'


AngularJS factory inside ng-class on body tag not working

Question: Was told to create service/factory and use it on global controller. It's my first time hearing global controller. Anyways, I created a factory called Scroll and injected it on our main.controller.js. The function in the factory is isScrollingEnabled which returns true or false. The other function is setScrolling which will set the variable to true or false. The default value is set to true.
Inside the main controller, I have this code
$scope.scrollEnabled = Scroll.isScrollingEnabled();
console.log('value of $scope.scrollEnabled', $scope.scrollEnabled);

That code spits out true in the console which is good.
on my template, I'm using it this way. I have button that sets scrolling to false. The value in the console spits out false which is good.

However, it's not working. If I change it to the code written below, it works

So I guess, it's not in scope especially ui-view is in index.html and main.controller.js and main.html will be loaded in the ui-view. The  is before this which tells me, any scope inside main.controller.js will not work outside of ui-view.
So what's the solution for this?
Sorry for not posting the factory. Here it is
  .factory('Scroll', function() {

    var scrollEnabled = true; // i then changed it to false hoping it will work, it didn't

    var ScrollEvent = {
      isScrollingEnabled: function () {
        return scrollEnabled;
      },
      disablePageScrolling: function() {
        scrollEnabled = false;
      }
    };

    return ScrollEvent;
});

Comment: Are you sure it is out of the scope? Have you tried doing scrollEnabled(). Also can you post some pseudo code for the structure of your html, the description is a little confusing
Answer: The $scope of the controller you're attaching the value to doesn't extend to the  element.  Instead, you can whip together a directive:
.directive('shouldScroll', function (Scroll) {
  return {
    restrict: 'A',
    link: function ($scope, elem) {
      $scope.$watch(Scroll.isScrollingEnabled, function (n) {
        if (n) {
          elem.addClass('scrolling');
        } else if (n === false) {
          elem.removeClass('scrolling');
        }
      });
    }
  };
});

You'd attach it to body like so:

Answer: Another solution that works in some cases is just to use class rather than ng-class:


Factorizing Given Problem

Question: I have searched through various site's and forums but couldn't find the answer to my problem,
$$z^2-\frac{1}{2}z-\frac{1}{4}=0$$
How will you factorize this
As I can't find $2$ numbers that give me $ac = -\frac{1}{4}$ and $b = -\frac{1}{2}$ when added
Is there a different approach for such sums.``
Comment: Do you know, how to find roots of $ax^2+bx+c$?
Answer: The quadratic formula can be used to find the roots of a quadratic equation.
$$x=\dfrac{-b\pm\sqrt{b^2-4ac}}{2a}$$ for a quadratic of the form $ax^2+bx+c=0$.
So for $a=1,b=-\frac{1}{2},c=-\frac{1}{4}$, we have that
$x=\dfrac{-\left(\frac{1}{2}\right)\pm\sqrt{(-\frac{1}{2})^2-4(1)(-\frac{1}{4})}}{2(1)}=\dfrac{-\frac{1}{2}\pm\sqrt{\frac{1}{4}+1}}{2}$

Factorizing Given Problem


Credential management / storage for client applications, company systems and third party applications?

Question: How does your company make sure all required employees have access to their (shared) credentials for client applications, company systems and third party applications?
For example:

Administrative credentials for a already deployed web application
Credentials for a third party website / application, such as a SSL provider
Credentials for inhouse applications
Answer: At small companies I've worked for we've usual created an encrypted file containing shared accounts with the program Password Safe. Password Safe will give you some added benefits like automatically clearing the password from the user's clipboard and relocking itself after a period of time.
However, at larger organizations that have to comply with various security standards (PCI, GLBA, HIPAA, etc.) shared credentials are one of the things the auditors will get fairly uppity about.  You're better off setting your applications up to authenticate against LDAP or RADIUS.  Having 1 shared login for administrative access can lead to an internal threat doing something stupid before quiting or other nefarious uses.
Ivan's comment mentions KeePass which I've known some organizations to use and like.  I personally havn't used it more than a few minutes, but people who like Password Safe's function but dislike its interface tend to like KeePass.  He also suggested LastPass which adds functionality like automating webforms, I haven't tried it personally but it looks like something I may try out and home and possibly work.
Comment: I agree, and it can be a nightmare if a user decides to change a password... LDAP is a great choice if available, and acting as an OpenID provider, you're all set. Another program like Password Safe is KeePass, which I've been running for several years (until I found LastPass).
Answer: For all size companies I have been a part of a team.  We work very hard to have individual login to everything.  We then used some single sign on technology to mange all of the logins for us.  These systems can be expensive and require hours to maintain.
Recently I have found a program that uses strong encryption, we have forced all our passwords into this program to the point where if I don't have PINs then I am not able to get anything done.  Some would say this is dangerous, but if a separation needs to take place then the heartburn of discovery is lessened.
http://www.mirekw.com/winfreeware/pins.html..this tool is awesome and would fit your needs easily.
Answer: We don't allow our people to have shared accounts. However administratively sometimes it isn't possible to have multiple account to vendors - like you said for ssl certs, etc it's more of a nightmare to track who's account that is associated with. For those cases we simple have a set of "Systems" passwords, that aren't written down anywhere and have codewords or triggers we use when communicating them to the other Systems personal. The codewords are generic and cannot be used to guess the password but we all know the password associated with it.
For example the password would be created using the Condense a phrase and add numbers and non alfanumeric charicatars such as:
"Windows Blinds are a Good thing to have" would become
WbRg!th@
and the code word would be "The Window Password"


Delphi Upload file to FTP

Question: I just created this little app that dumps 2 strings into txt file. Now i want that txt file to be uploaded to ftp. I've looked some tutorials but can't find any good one on how to do it. Please help me. I'll post my code for file.
   var

  fText:textfile;
  sText:string;
  s1Text:string;
begin
assignfile(fText,'d:\test.txt') ;

if fileExists('d:\test.txt') <>true then
begin

  rewrite(fText);
  end

  else
  begin
  Append(fText)
  end;

  sText:=Edit1.Text;
  s1Text:=Edit2.Text;
  writeln(fText,sText) ;
  writeln(fText,s1Text);
  closefile(fText);
end;

Answer: One way to do it, is via a Windows FTP command called from within your Delphi code using CreateProcess. To make it easy to expand the functionality to upload more files, I am using an uploadscript that tells the Windows FTP command what to do. (A similar function will work to download files: Start by changing the put to a get)
function TForm1.Upload: Boolean;
var
  Script: TStringList;
  Command: String;
begin

    Script := TStringList.Create;
    try
      Script.Text := 'User Username' + #13#10 +
      'Password' + #13#10 +
      'cd /temp' + #13#10 + // ftp folder (destination)
      'put d:\test.txt' + #13#10 + // local folder (source)
      'bye';
      Script.SaveToFile('d:\test\myuploadscript.txt');

      Command := 'FTP -v -i -n -s:"d:\test\myuploadscript.txt" ftp://mytestftpsite'

      Result := ExecNewProcess(Command, True);

   finally
     Script.Free;
   end;

end;

function TForm1.ExecNewProcess(ProgramName: String; AShowMsg: Boolean): Longword;
var
  StartInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
  CreateOK: Boolean;
begin

  FillChar(StartInfo,SizeOf(TStartupInfo),#0);
  FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
  StartInfo.cb := SizeOf(TStartupInfo);
  if AShowMsg then
  begin
    StartInfo.dwFlags := STARTF_USESHOWWINDOW;
    StartInfo.wShowWindow := SW_SHOW;
  end;

  CreateOK := CreateProcess(nil, @ProgramName[1], nil, nil, False,
              NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);

  if CreateOK then
  begin
    WaitForSingleObject(ProcInfo.hProcess, INFINITE);
    GetExitCodeProcess(ProcInfo.hProcess, Result);
  end;

  if ProcInfo.hProcess <> 0 then
    CloseHandle(ProcInfo.hProcess);
  if ProcInfo.hThread <> 0 then
    CloseHandle(ProcInfo.hThread);
end;

Comment: This is a terrible answer. Delphi comes with a perfectly good set of internet components (Indy) that supports FTP, and there are other native solutions available as well. Spawning a command-line utility to do something you can do natively (in fewer lines of code) is simply wrong.
Comment: It's still works though.
Comment: @Ken White Note, in my answer I said "One way to do it". I made no claim to it being the shortest, simplest, easiest or best answer. It is however, a complete answer to the question. As such, it can't be "wrong" - it's just one you don't happen to like!
Comment: Didn't say it was wrong. I said it's a terrible answer. It's like being asked how best to move 1000 chimney bricks and answering *Rent a Porsche and move 100 loads of 10 bricks each* rather than *Rent a truck*.
Comment: I see the words "is simply wrong" in your first comment above. Nevertheless, if I choose to move bricks 10 at a time using a Porsche, then why can't I? Will the brick-moving police slap me with a fine!?
Comment: I'm not debating this with you. See the approximately 5 lines of code in the duplicate question I linked, compared with the ridiculous number of lines (and increased complexity) of  code you posted. If you have the option of using a truck or a Porsche to move bricks, and you choose the Porsche, it doesn't demonstrate a lot of common sense. No one here is impressed that you can write dozens of lines of unnecessary code to reinvent the wheel (and do so in an extremely inefficient manner in the process).
Comment: The only reason the Indy version _appears_ simpler is because the complexity is in the underlying library, instead of in the calling code. My code illustrates several possibilities, and doesn't _just_ answer the question. That's useful,  even though if **you** think it's wrong, inefficient or terrible.
Comment: That's just nonsense. Using `CreateProcess` hides the underlying complexity of setting up registers and launching an application, too. By your logic, that should be eliminated as well and you should write it in pure assembly (which you can then further reduce to pure opcodes). Knock yourself out. Reinventing the wheel needlessly is seldom the right answer, and it's definitely not the right answer for someone who is clearly new to programming and Delphi (which is apparent from the question and code posted).

Delphi Upload file to FTP


Ajax authentication without letting browser pop up login dialog

Question: I am desiging a RESTful Web Service (JBoss + RESTeasy).  The UI programmer is writing an Ajax web app that will use it.  The web app will be one HTML page with everything done in JavaScript.  For security, all traffic goes through SSL.
Currently I'm using Basic authentication.  The UI programmer can show a dialog to get a username and password and put "Authorization: Basic xxxxx" in the header.  Unfortunately if the password is wrong, the ugly browser login dialog box comes up.  Also there is no way for the user to log off.  This is unacceptable.
There appears to be no way to intercept a 401 response to an XMLHttpRequest in any of the browsers we will use.
Form-based authentication won't work for us.  We need an automatic logoff after some period of inactivity (the equivalent of a session timeout).  We can't have the server suddenly return a login page when the client expects a JSON object.
JBoss offers four authentication strategies:  BASIC, FORM, CLIENT-CERT and DIGEST.  I think DIGEST has the same problem as BASIC.  None of the four is what we want.
This web application will be the only client (for now) so there is no requirement to use BASIC.  Is there any other authentication strategy I can install?  For instance is there an implementation of WSSE UsernameToken I can use?  (As described in Chapter 8 of the O'Reilly RESTful Web Services book.)  The server would send "WSSE" instead of "Basic" in the WWW-Authenticate header and presumably the browser would ignore it and pass it right through.
I want to configure security where it belongs -- in the JBoss configuration files, not in my RESTful Web Service -- so I'm looking for an implementation I can just plug into JBoss.
Answer: The browser won't present the password dialog if it doesn't recognize the authentication scheme in the WWW-Authenticate header. Your best bet may be to continue using basic auth on the server while setting the header manually to something like "Basic/MyApp" for 401 responses.
Comment: Authentication is done before the request reaches the web service.  Can I handle this by writing a filter that sits in front of the security framework?  Then I could tell the web programmer to add an "Authorization: Basic/MyApp" header to the first request.  The filter could then rewrite it as "Authorization: Basic" and rewrite the "WWW-Authenticate: Basic" header in the response as "WWW-Authenticate: Basic/MyApp".  Any other clients could use normal Basic authentication.  Will this work?  I think it might.
Comment: Hmm... I was assuming you had control over authentication at the script level on the server, and the header would be set after the authentication was handled but before you returned a response. I'm not too familiar with JBoss, but if you can filter and rewrite requests before the auth happens it sounds like it would be your best bet. And by setting the Authorization header in the web app, normal clients won't be affected. Nice.
Comment: As it turns out, you cannot have a pre-login filter.  The WebLogic server allows it, but the standard does not allow it and JBoss and Tomcat do not allow it.  It looks like I'll have to fiddle with JAAS to do this.
Comment: You can also set it to `WWW-Authenticate: None`.
Comment: Did you find a solution with JAAS?


Has anyone hit the wrong color ball in an important snooker match?

Question: I have been watching snooker for a few months now and I have never seen a player hit the wrong type of ball. Personally, I often get confused and forget which type the player is on (color or red) and then am surprised when the player lines up on the opposite type of ball.
Has any top player ever hit the wrong type of ball deliberately in an important match? By "hit the wrong type", I mean that the player deliberately pocketed a red instead of a color, or vice versa.
Comment: I added "deliberately" into your last paragraph because players have often accidently done this. If you meant to include those cases, please revert - although I'd then be very tempted to close it as "too broad".
Answer: Yes, because colour-blind players can easily mistake the brown for a red. Usually when the brown goes down table amongst the reds. Peter Ebdon and Mark Williams have hit the brown by mistake on TV.
You're not allowed to ask the ref where the brown is, or what colour a ball is. You can only ask "Is that the brown?". If anyone knows the rationale for such pedantry in the rules, I'd love to understand it.


How to hash based on host + path in Varnish?

Question: I want to use the hash director in Varnish to redirect all requests for a same URL without query parameters to the same server:
For example,
http://example.com/foo/bar?a=1
http://example.com/foo/bar?a=2&b=3

Should hash to the same server. I want to hash on host and path only.
Here is my configuration:
sub vcl_init {
    new workers = directors.hash();

    workers.add_backend(worker_1, 1);
    workers.add_backend(worker_2, 1);
    workers.add_backend(worker_3, 1);
}

I understand I need to set the hash function here:
sub vcl_recv {
    set req.backend_hint = workers.backend(...);
}

What should I put in there to hash on host + path, without query string?
Answer: It doesn't look like the default VCL-provided req object provides a way to get the request path, without query parameters, just the full URL.  Thus using some VMODs might help.
You might try using the QueryString VMOD, e.g. (from their docs):
import querystring;

sub vcl_hash {
    if (req.method == "GET" || req.method == "HEAD") {
        hash_data(querystring.remove(req.url));
    }
    else {
        hash_data(req.url);
    }
    hash_data(req.http.host);
    return (lookup);
}

And another nice VMOD, VSLP might also be of interest, given the increased control it provides over backend selection.
Using Varnish 4.1, you might be able to use:
sub vcl_recv {
    if (req.http.host) {
        set req.backend_hint = workers.backend(req.http.host + regsub(req.url, "\?.*$", ""));
    }
    else {
        set req.backend_hint = workers.backend(server.ip + regsub(req.url, "\?.*$", ""));
    }
}

Hope this helps!
Comment: For posterity: the correct syntax is `set req.backend_hint = workers.backend(req.http.host + regsub(req.url, "\?.*$", ""));`. Note the `+` instead of the `,` and `\?` instead of `?`. @Castaglia, maybe you want to update your answer? BTW, it works perfectly like that, thanks again!
Comment: I'm afraid the QueryString vmod doesn't support Varnish 4 at the moment. Also, I would be grateful if you could provide a turnkey configuration to match my requirements, i.e. what to put in `req.backend_hint`!
Comment: @Benjamin: I'll certainly try.  Just to make sure: what's the exact Varnish version you're running?
Comment: At the moment I'm running 4.1!
Comment: Thanks for your updated answer, I'll need to test your suggestions before accepting it, in the meantime, enjoy the bounty!


Estimating weight of hidden coin

Question: Consider the following problem:
You have two coins each with it's own weight (probability of giving heads). Somebody will flip the coins for you in another room (you trust them). You can either ask them to flip both coins and they will tell you if they are both heads or not both heads. Or you can ask them to flip only the first coin (you can't only flip the second) and they will tell you if it was heads or not.
How should you proceed to find an estimator of the weight of the second coin. You are allowed to ask the person multiple times. The main goal is to make the estimator not depend on the weight of the first coin. Is this possible?
An aside for motivation of this problem: This is analogous to how measurements in quantum mechanics with linear loss are done. The loss is the first coin, the measurement is the second coin. We can never get rid of the loss but we can do a trivial second measurement (gives always heads) and then the real measurement. Particularly, this is the problem of measuring the polarization degree of freedom of photons from a heralded single photon SPDC source.
Comment: By definition, an estimator cannot depend on the weight of *either* coin: it can only depend on the results of the flips. It is intuitive that with a very large number of trials you can precisely estimate the "weight" of the first coin. After that your problem is substantially the same as a technique used to ask sensitive survey questions, called "randomized response sampling."  This indicates a solution is possible, thereby making the question one of finding an optimal way to estimate the "weight" of the second coin, perhaps by minimizing expected flips using a sequential rule.
Comment: So to be clear, both coins have unknown weight?
Comment: Yes, both coins have an unknown weight.
Answer: Method 1: Comparing double and single coin flips as two binomial distributed variables (biased)
Say you flip $n$ times both with $k_n$ times double heads, and you flip $m$ times the first with $k_m$ times the heads. The unknown weights $\theta_1$ and $\theta_2$ can be estimated by the maximum likelihood estimate:

The conditional probability is $$P(k_n,k_m|\theta_1,\theta_2) = {{n}\choose{k_n}} {{m}\choose{k_m}} \theta_1^{k_n}(1-\theta_1)^{n-k_n} (\theta_1\theta_2)^{k_m}(1-\theta_1\theta_2)^{n-k_m}$$
Log-likelihood (and eliminating the binomial coefficients):
$$\log \mathcal{L}(\theta_1,\theta_2) =  k_n \log(\theta_1) + (n-k_n) \log(1-\theta_1)+ k_m \log(\theta_1\theta_2) + (m-k_m) \log (1-\theta_1\theta_2)$$
Derivatives
$$\frac{\partial\log \mathcal{L}(\theta_1,\theta_2)}{\partial\theta_1} = \frac{k_n}{\theta_1} - \frac{n-k_n}{1-\theta_1} + \frac{k_m}{\theta_1} - \theta_2 \frac{m-k_m}{1-\theta_1\theta_2}  $$
$$\frac{\partial\log \mathcal{L}(\theta_1,\theta_2)}{\partial\theta_2} =  \frac{k_m}{\theta_2} - \theta_1 \frac{m-k_m}{1-\theta_1\theta_2}  $$
Which is zero for
$$\theta_1 = \frac{k_n}{n} $$ and $$\theta_2 = \frac{k_m}{m} \frac{n}{k_n} $$

This estimate does have some bias. Using simulation I found the expectation value $E(\theta_2)>\theta_2$
(and technically the expectation value is infinite due to the small possibility of $k_n=0$ but you could add some stopping rule that prevents $k_n$ from being zero. Since $k_m < k_n$ anyway I don't believe that this introduces too much bias, if at all)

Method 2: Performing double coin flips with number of trials depending on the amount of flips necessary to get k heads in single coin flips (unbiased ?)

You flip the first coin until you got $k$ success and count the number $X$ that you need to flip.
Then you flip both coins a multiple $n$ times $X$ and count the number $Y$ that both coins land heads.

Intuitively I'd say $\theta_2 = \frac{Y}{nk}$ is an unbiased estimator (with a negative aspect that $\theta_2$ can be above 1). The simulation below seems to show that there is only a small bias (also the variance/error is smaller in comparison to the first method with similar amount of coin flips). You would have to compute the conjugate distribution for the variable $Y$ to see if there is no bias.
<code>k=50
p1=0.5
p2=0.5
n=10
X <- rnbinom(10000,k,p1)+k
Y <- rbinom(10000,X*n,p1*p2)
mean(Y/k/n-p2)
var(Y/k/n)
plot(hist(Y/k/n))
</code>

Estimating weight of hidden coin


Adding a new initial state to WorkItem type Bug - Web Acess task board shows error TF400917

Question: I am using TFS 2012 (Update 4).
After adding a new initial state New to my Bug work item workflow
the backlog and the task board show the error:

TF400917: The current configuration is not valid for this feature.
  This feature cannot be used until you correct the configuration.

I tried to fix this by adding a new line in the common process configuration :

< BugWorkItems category="Microsoft.BugCategory"><States>
  <State type="New" value="Proposed" />
  <State type="InProgress" value="Active" />
  <State type="Complete" value="Closed" />
  <State type="Resolved" value="Resolved" />
</States>

But importing this via witadmin - I get the error:

witadmin.exe importcommonprocessconfig /collection:< my collection> /p:Kanban  /f:d:\tmp\CommonProcessConfig_Kanban_new.xml
Line: 5 Position: 14 - The 'type' attribute is invalid - The value 'New' is invalid according to its datatype 'StateFieldEnum' - The Enumeration const
  raint failed.

Which types (and meta types) are valid for my Bug work item and where is this StateFieldEnum defined?
In the field explorer the field System.State has a allowed value New.
Answer: I have found the error myself. It was the correct approach to edit the BugCategory.
I have swapped the type and value - the correct xml to import is:
<BugWorkItems category="Microsoft.BugCategory">
    <States>
      <State type="Proposed" value="New" />


Possible DNS hijacking at ISP

Question: I was about to login to control panel of our hosting provider and it went to some other webpage which was not my hoster's server (I confirmed with them that the IP is not theirs)
<code>mixdev@ThinkpadT430:~$ ping manage.softlayer.com
PING manage.softlayer.com (188.8.131.52) 56(84) bytes of data.
64 bytes from vps-1131725-16286.manage.myhosting.com (18.104.22.168): icmp_req=1 ttl=47 time=286 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (220.127.116.11): icmp_req=2 ttl=47 time=285 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (22.214.171.124): icmp_req=3 ttl=47 time=287 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (126.96.36.199): icmp_req=4 ttl=47 time=294 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (220.127.116.11): icmp_req=5 ttl=47 time=284 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (18.104.22.168): icmp_req=6 ttl=47 time=285 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (184.108.40.206): icmp_req=7 ttl=47 time=310 ms
64 bytes from vps-1131725-16286.manage.myhosting.com (18.104.22.168): icmp_req=8 ttl=47 time=285 ms
^C64 bytes from vps-1131725-16286.manage.myhosting.com (126.96.36.199): icmp_req=9 ttl=47 time=285 ms

--- manage.softlayer.com ping statistics ---
9 packets transmitted, 9 received, 0% packet loss, time 8005ms
rtt min/avg/max/mdev = 284.838/289.510/310.756/8.034 ms
</code>
This happens only with one ISP (Airtel) in all my machines (different OSes). All other ISP's show the correct page. No problem if I reconfigure to use Google DNS either. Running Ubuntu 12 LTS and my hosts file is clean.
My worry is that this is some attack on the domain manage.softlayer.com at ISP DNS level and someone did manage to successfully change it to another server of theirs. So, they can simply put a login page exactly like softlayer's and capture all my passwords (and all other users who happen to use the affected DNS server). Is this possible at all? How risky should one consider this situation?
[So I contacted the hosting provider about the problem and they claim that since the issue is not with their servers, they shouldn't act.]
Comment: Such an attack wouldn't work unless they successfully obtained an SSL certificate for `manage.softlayer.com` or against someone who didn't check that the page was secure before entering sensitive password information. The hosting provider is incorrect -- it is an issue with their servers -- it's their nameserver that's providing incorrect information. (And if they take that attitude, I wouldn't suggest using their nameservers.)
Comment: What is the content of `/etc/resolv.conf`?
Answer: For optimal security, you should only use (a) DNS servers you can trust, and (b) an ISP you can trust.
You've informed the the ISP that they may be victims of a DNS cache poisoning attack or other attack on their resolving nameserver. If they don't think it's their problem, then you've got no other recourse but to find someone else who isn't so naive.
[Note, this is not a problem with softlayer; they have no control over your ISP's DNS servers]

Possible DNS hijacking at ISP


Which Google API to use for Domain users

Question: Here is the context :
I am the admin of a Google Domain for my enterprise. I need to load every user and manage their access rights for Google Drives directories.
I already use the Google Drive API to upload file. Can it manage access rights also ? Which API can I use to list users ?
Thanks for your help and sorry if this is a dumb question !
Answer: I think that the Google Domain API is this one Google+ Platform - APIs for Google Apps. No its not the same as the Google Drive API that you are using.


Fadeout Cursor in JavaFX After Few Seconds Delay

Question: On my application(Media Player), when application is in fullscreen mode, I am fading out the top bar and bottom bar. I also wants to fade out the cursor after few seconds delay. I tried FadeTransition, but it take only Node as parameter.
I also tried using thread.
    Platform.runLater(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                Thread.sleep(2000);
                scene.setCursor(Cursor.NONE);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

        }
    });

Here I just wanted to hide the cursor after two seconds delay. It works, but also hang my application for two seconds which I don't expect.
In which way I can fade out the cursor after two seconds delay?
Comment: About the opacity it maybe be possible creating 10 different icons of the same cursor with different opacity.Then very fast change them from one to other through for example 1 second,using `ImageCursor`.Cause i am curious about that ,maybe i do it and post the code.:)
Comment: Here you are: https://github.com/goxr3plus/JFXCustomCursor
Comment: Thanks, I have seen your project, it is really nice :)
Comment: Glad to hear!      .
Answer: Your code is making the UI hang because you are making a blocking call (Thread.sleep(...)) on the FX Application Thread. If you want to do it that way, you should block on a background thread and schedule the change of the cursor on the FX Application Thread when the pause is complete.
An easier way, though, is just to use a PauseTransition:
PauseTransition pause = new PauseTransition(Duration.seconds(2));
pause.setOnFinished(e -> scene.setCursor(Cursor.NONE));
pause.play();

You can use this as well to make the cursor reappear on when the user does something, and disappear again after 2 seconds:
scene.addEventHandler(MouseEvent.ANY, e -> {
    scene.setCursor(Cursor.DEFAULT);
    pause.playFromStart();
});

Comment: Thanks, the 2nd part added extra advantage for me.
In addition, can you help me about fading out the cursor. I would like if it will disappear gradually.
Comment: I don't see any way to do that. `Cursor` doesn't have an `opacity` property, and I don't think there's a way to create a `Cursor` out of a `Node`.
Comment: @James_D I am using a `WritableImage` along with a `PixelWriter` to make the image transparent but instead of that i get a black rectangle..Why that happens?`WritableImage` doesn't support transparent?Help appreciated..


Problem with GWT behind a reverse proxy - either nginx or apache

Question: I originally asked this question on SO, but perhaps SF is a better place for traction on this question.
I'm having this problem with GWT when it's behind a reverse proxy.  The backend app is deployed within a context - let's call it /context.
The GWT app works fine when I hit it directly:
http://host:8080/context/
I can configure a reverse proxy in front it it.  Here's my nginx example:

upstream backend {
    server 127.0.0.1:8080;
}

...

location / {
   proxy_pass        http://backend/context/;
}

But, when I run through the reverse proxy, GWT gets confused, saying:

2009-10-04 14:05:41.140:/:WARN:  Login: ERROR: The serialization policy file '/C7F5ECA5E3C10B453290DE47D3BE0F0E.gwt.rpc' was not found; did you forget to include it in this deployment?
2009-10-04 14:05:41.140:/:WARN:  Login: WARNING: Failed to get the SerializationPolicy 'C7F5ECA5E3C10B453290DE47D3BE0F0E' for module 'https://hostname:444/'; a legacy, 1.3.3 compatible, serialization policy will be used.  You may experience SerializationExceptions as a result.
2009-10-04 14:05:41.292:/:WARN:  StoryService: ERROR: The serialization policy file '/0445C2D48AEF2FB8CB70C4D4A7849D88.gwt.rpc' was not found; did you forget to include it in this deployment?
2009-10-04 14:05:41.292:/:WARN:  StoryService: WARNING: Failed to get the SerializationPolicy '0445C2D48AEF2FB8CB70C4D4A7849D88' for module 'https://hostname:444/'; a legacy, 1.3.3 compatible, serialization policy will be used.  You may experience SerializationExceptions as a result.

In other words, GWT isn't getting the word that it needs to prepend /context/ then look for C7F5ECA5E3C10B453290DE47D3BE0F0E.gwt.rpc, but only when the request comes throught proxy.  A workaround is to add the context to the url for the web site:

location /context/ {
    proxy_pass        http://backend/context/;
}

but that means the context is now part of the url that the user sees, and that's ugly.
Anybody know how to make GWT happy in this case?
Software versions:
GWT - 1.7.0 (same problem with 1.7.1)
Jetty - 6.1.21 (but the same problem existed under tomcat)
nginx - 0.7.62 (same problem under apache 2.x)
My suspicion is that perhaps GWT is picking up on the Referer header, and getting confused (is there a way for nginx to turn off that header?) or that there's a difference since the traffic between the proxy and GWT/Jetty is HTTP/1.0 instead of HTTP/1.1.
Answer: I think you should
<code>location /context/ {
    proxy_pass        http://backend/context/;
}
</code>
and then use rewrite to strip /context part from URL
Comment: It took me a while to figure this out, but it finally dawned on me that my problem was that I was doing the rewrite in the location context, and it needed to be in the server context:

        rewrite ^/(.*)$ /stuff/$1;

        location /stuff/ {
            proxy_pass        http://backend/stuff/;
        }
Comment: Scratch that - it didn't fix the problem.  Maybe it really is a GWT bug.
Comment: i think nginx has some different behavior depending on closing slashes in proxy_pass directive, so you can play with it


Extracting power of a power law from data

Question: My question is more about the methodology. Assuming in some experiment we have measured quantity $y$ per each unit of time $x.$ So $y$ and $x$ form our data set here. Moreover, we know that they are related by a
power law type of relation, e.g., $y = D x^{\alpha},$ where $D$ is just a constant.
Now to extract $\alpha$ from the data-set, I know two ways:

a) Calculating the logs of our data, we can then compute the derivative of the $\ln(y)$ w.r.t $\ln(x),$ so $\frac{d\ln y}{d\ln x}=\alpha$ and extract the power. One problem with this is that the sampling may not have been done logarithmically, so the spacings between the log'ed values are different. That means numerically it is going to be hard to accurately compute such derivative.
b) Another way would be: taking the logs again as in above, but then we just fit the log'ed data with a line, the slope of which should give us an average $\alpha,$ right? Assuming this is correct, one problem is that if $\alpha$ is changing during different time scales of the experiment, the above fit wouldn't capture it. Maybe one could perform the fits piece-wise.

Questions:

Have I laid out the above methods correctly? (e.g., is b) correct?)
Does one method come more recommended or it really depends on the context? (i.e., in view of the aforementioned difficulties) Finally, please feel free to suggest other ways of extracting $\alpha$ if you know of different methods, I'm very curious to find out.

(If you prefer explaining your method with an example, I have created dummy data for purposes of illustration, here's the link, first column is $x$ and second column $y.$)

Clarifications upon reading discussions in the comment section:
The aim here is only to tackle the problem of how to reasonably estimate (for instance by fitting) power laws that describe a given bivariate data set, and more precisely, finding power laws that correspond to each region of interest [*] (i.e., subsets of the data). With this in mind, what the user Nick Cox has proposed as answer, is precisely on point.
[*]: thus e.g., fitting subsets of the data, and more contextually, looking for different power laws at different time-scales, because for instance from a physical point of view we expect the data to exhibit different power laws.
Comment: @NickCox Dear Nick, very well captured, this is indeed what I am trying to learn to do (in terms of applications, e.g., in context of physics, this type of analysis is relevant when extracting different regime in the dynamics of a system, by measuring mean-squared-displacement of particles as function of time, and seeing what power-law governs the MSD during which time scales). Sure, I will generate dummy data that can be utilized to illustrate here.
Comment: @DJohnson Sorry, but I think you misread the question in your enthusiasm to link to one of your top interests. The OP has confirmed that. You might as well say that all questions in which logarithms are mentioned or implied are the same question.  Gumbel was there just copying from Russell, but failing to cite him, incidentally
Comment: @DJohnson There is no sense whatsoever in which e.g. the analysis in my answer is an extension of the theory for univariate distributions you point to. I think you're just confusing an otherwise well-focused thread: the first paragraph of the original question is crystal clear on what the problem is, and that is reinforced by the OP's comment on the other answer to underline the distinction. I  am happy to let readers decide on whatever  they find here that is focused, interesting and helpful.
Comment: @DJohnson  We don't expect to convince each other, but I do care that other people can be misled by error, confusion and irrelevance. These comments aren't pertinent or even factual: power functions aren't nonlinear exponential  models; they go back at least to the 18th century; nor are they univariate processes, whatever that means. Marginal and even conditional distributions don't need to be considered to apply the analysis in my answer.
Comment: Power functions $y = ax^b$ as are discussed in this thread (except in your comments) are not S-shaped. They are convex or concave curves in $(x, y)$ space and straight lines in $(\log x, \log y)$ space.
Comment: User929304 Comments mean much less on this site than do actual answers.  When two (or more) people seem to be disputing matters of fact or art in comments, and one of them does not post an actual answer and resorts to *ad hominem* arguments (which are never appropriate here), then it is always a good idea to treat their position sceptically. As @Nick has suggested, such disputes can arise from different readings of the original question, so edits to clarify it are always welcome.
Comment: Not for the first time, there seems to be danger of confusing quite different problems: (1) fitting a power function or power law to bivariate data and (2) fitting a power law (Pareto or Pareto-like) distribution to univariate data. What the problems have in common is the wording "power law" and the appearance of powers in two sets of equations. Your question seems to be about #1, in which case suggestions about #2 appear irrelevant, whatever their inherent interest. You seem to want to fit different power laws to different subsets of your data, but it's hard to be precise without examples.
Comment: @NickCox the power-law changes at different time scales, e.g., during the first decades (of sampling) it shows diffusion, meaning ($y\propto x^{\alpha}$ where $\alpha = 1$) and later may become sub-diffusive, so $\alpha$ coverging to smaller than $1$ values. By the way, I've edited and added example data.
Comment: @user929304 No; you're entirely innocent.  Thanks for accepting my answer.  I won't try to summarize the disagreement between DJohnson and myself, for reasons obvious and not so obvious.  You can comment, or not, entirely as you please.
Comment: Another term for *a* is the tail index or exponent of the distribution. There are several approaches to its estimation. A good heuristic can be found in Gabaix's paper *Rank-1/2: A Simple Way to Improve the OLS Estimation of Tail Exponents* (http://www.nber.org/papers/t0342.pdf). More rigorous approaches include Hill's method and Pickand's method. Googling both will turn up many related papers. In addition googling 'filetype:pdf tail index estimation' will turn up many other alternatives.
Comment: Thinking in relative proportionate terms works for both uni- and bivariate models. Psychologists speak of two 'types' of cognitive function: lumpers and splitters. The risks of the former are that gross differences are blurred while the risks of the latter are that hairs are split or purely pedantic distinctions are made. Reconciling this binary opposition is, for practical purposes, impossible. Another way of stating this is, after Gumbel, "A (statement) can have either intelligibility or correctness. To combine the two is impossible." Splitters will find this remark a nonsequitur (again)
Comment: @nickcox  You've misread the intent of my original comment. The OP *liked* the suggestion of the tail exponent as an intuitive heuristic, *period*. Any effort at gainsaying that is, quite simply, inappropriate, misguided and wrong. Given such a basic, foundational understanding at the univariate level it is a trivial extension to go to the bivariate case, as you suggest.
Comment: @NickCox what is going on in these discussions? :( I hope I didn't cause this fight...
Comment: @whuber Couldn't agree more. I've edited the post to provide more definite clarifications.
Answer: As in my first comment on the question I see this as being entirely about power laws for bivariate data. (The inclination to read it otherwise is puzzling.)
Based on the posted data, I did local polynomial smoothing; the choices here are no more than not very smart defaults in the program used, but equally there doesn't seem much need to play with other choices. (The $R^2$ here is just the square of the correlation between observed and smoothed; 1 isn't even a target as interpolating the data could achieve that.)

It seems clear that the slope stabilises fairly quickly and systematically in logarithmic space, so that numerical differentiation could give you estimates of slope as it changes.
Comment: Thank you for performing the test, I don't know what fit function you have used (or what program), but I have tried taking the derivative of this sample data (in log space) in python and it's fluctuating all over the place so to speak... it may be my method in python is not appropriate (I've simply used `np.gradient(np.log(y))/np.gradient(np.log(x))` `np` standing for `numpy` here. It would be interesting to see how the derivative turns out with your program if you could kindly check.
Comment: As said, this is local polynomial smoothing; there is no global function, just linear regression within moving windows and with weights within the window. I imagine that, as I should have emphasised, you have to smooth first because numeric differentiation is sensitive to local noise. I'm calling up `lpoly` in Stata documented at https://www.stata.com/manuals/rlpoly.pdf except that I am calling it through my own program which just chooses different defaults. Conversely, sorry, but I don't use python and can't advise on how to do it. Presumably, there will be implementations to choose from.
Comment: Alright, fair enough. If you find the time to perform the derivative in your program, let me know please how it turns out, it would be a sanity check for me that I'm doing things correctly in python.
Comment: I get final slopes about 0.3.
Answer: Edit: The question is actually about data in which $x$ and $y$ are allowed to vary. This answer is not relevant to that case, but only to the case when $x$ is a quantity and you want to fit a distribution of the form $f(x) \propto x^{\alpha}$ to it. However, I am leaving it up because it links to a paper which is state-of-the-art for this case, which may be useful for some readers who are confused (like I was) by the question title.
I suggest reading the following paper by Clauset, Shalizi and Newman. It recommends using maximum likelihood to fit a power law (so, not taking logs and fitting a straight line at all).
Even if you know that the data follow a power law and you are just trying to find an exponent, it might still not be appropriate to fit a straight line to the log-log plot with least squares. This is because, if you fit such a line, any statistical calculations are implicitly assuming that the errors in measuring $\log(y)$ are normally distributed, which may not be true, depending on circumstances. See Appendix A of the above paper.
Comment: This is a very good paper, & always worth a read. However, note that it pertains to a *univariate* power law distribution, not a *bivariate* power law relationship. This is the point @NickCox was trying to bring out.
Comment: I'd say: keep your answer. First, the _title_ of the thread may make it entirely relevant to some readers. Second, it should now be clear to careful readers of the thread what is what.
Comment: Very interesting! thanks a lot for bringing this paper to my attention. I wonder, for Appendix A, isn't the case being discussed only of relevant for when the lhs is a probability distribution?
Comment: Yes, I understand the point but was not sure whether to delete my answer, since the OP seemed to find it useful.


what are secure rules for firebase in production mode and how to define it

Question: I am creating a website where users can register and add their personal info in their profile section and chat with others etc.... so this website is a startup idea meaning that we will publish it and then do some marketing to get customers, I want a suggestion from a senior firebase developer that which security rules should i define then? because test mode is not secure and if i choose production mode then users can't register because it does not allow read write access, so what are the secure and strong rules for firebase production mode for a real world application which will be served to millions of users.
What could be the security rules of companies who are using firebase?
P.S: I would also like to hear some tips/tricks about security, optimization etc...
Test Mode? or Production Mode?
if(Production Mode){ then('what rules') }
Answer: There is no singular answer for "good rules for my production app" just like there is no singular answer for "good code for my production app".
You will have to develop security rules that match with the code of your app. I recommend:

Start in production mode, so with the database locked down for all client-side access.
Implement the first use-case in your application code.
Watch the code fail, because the permission is denied by your rules.
Make the minimal change to your rules that allow the current code to work, but all other possible code to still fail.
Repeat from step 2.

There is no shortcut for this, just like there is no shortcut for writing the code for your application.

Also see:

The Firebase documentation on getting started with Firebase Security Rules
Change Realtime DB security rules from test to locked mode
How to manage Firebase RealtimeDate base Security Rule for Production App


captured screen video from ADB screenrecord results in a black screen

Question: I'm using a Droid Maxx with v4.4.4 Android.  I'm trying to do:
adb shell screenrecord /sdcard/myvideo.mp4

and I am able to capture a video, which shows the desktop fine, but my app, results in a black screen showing.  I tested with facebook, which records just fine.
with verbose on, I get this as part of the shell:
Main display is 720x1280 @60.00fps (orientation=0)
Configuring recorder for 720x1280 video at 4.00Mbps
Content area is 720x1280 at offset x=0 y=0

Example recorded video shown here: http://youtu.be/ZeKhTzRpRns
Answer: Make sure that you aren't setting FLAG_SECURE:

the user may see a blank region on the screen instead of the contents of secure surfaces or protected buffers.

https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SECURE
https://developer.android.com/reference/android/view/Display.html#FLAG_SECURE


Is there a way to sigaction() to a signal handler with multiple parameters?

Question: I am using sigaction() to perform an action every time SIGINT is received. All tutorials I have seen use this prototype as a signal handler
void sig_handler(int sig);

Is there a way somehow to make this to take more parameters so it suits my needs? So for example
void sig_handler(char* surname, int age);

This is my code:
void sig_handler(int sig) {
    printf("SIGINT(%d) received\n", sig);
}

int main( ){
    struct sigaction act;
    act.sa_handler=sig_handler;

    sigaction(SIGINT, &act, NULL);

    while(1){};
    return 0 ;
}

Answer: Not directly, but you could set a global variable that tells your sig_handler() what to do.
int ACTION = 0;

void sig_handler(int sig) {
    if (sig == SIGINT) {
        switch (ACTION) {
          case 0: other_function(char* surname, int age);
          break;
        // more cases
        default:
          ;
        }
    } else if ( ....  // more signals
    }
}

int main( ){
    struct sigaction act;
    act.sa_handler=sig_handler;

    sigaction(SIGINT, &act, NULL);

    while(1){};
    return 0 ;
}

Comment: Thought of it just before you answered but you get my vote still :D
Answer: You can't do this with signals. How would these parameters be supplied and delivered? A signal is just a predefined numeric code that causes the process to execute the handler asynchronously, by interrupting the main flow.
You can, however, use a Unix socket, a pipe, or a fifo file for this.


How to retrieve tweets of user and his/her followers under a certain hashtag using Twitter4j?

Question: I am trying to build a twitter4j application that creates a small twitter network, actually. Here is my sample code snippet:

//Monitoring hashtags
Query query = new Query("#anger");
query.setCount(100); //get 100 tweets
query.setSince("2010-01-01");
QueryResult result;
try {
     result = twitter.search(query);
     for (Status status : result.getTweets())
     {
      if (status.getText() != null)
      {
             // Getting followers list of a given user
             ArrayList<User> followers = getFollowers(status.getUser().getScreenName());
           for (User user : followers)
    {
                    if (status.getUser().getScreenName().contains(user.getScreenName()))
      {
                      System.out.println(status.getUser().getScreenName());
      }
           }
       }
      }
    } catch (TwitterException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
           }

I think that this code should print existence(names) of the followers of users under "#anger" hashtag. However, when I run this code, it violates the api 1.1 rate limits with an exception (message - Rate limit exceeded, code - 88). How can I overcome this issue?
Here is also my getFollowers() method:

// Getting followers list of a given user
public static ArrayList<User> getFollowers (String usname)
{
  Twitter twitter = initTwitter();
  String username = usname;
  ArrayList<User> followers = new ArrayList<User>();
  long nextCursor = -1;
  do  {
    PagableResponseList<User> usersResponse;
    try
    {
      usersResponse = twitter.getFollowersList(username, nextCursor);
   nextCursor = usersResponse.getNextCursor();
   followers.addAll(usersResponse);
    }
 catch (TwitterException e)
 {
   e.printStackTrace();
 }
   } while (nextCursor > 0);

return followers;
}
Comment: Probably it is from `getFollowers` method. Can you post that?
Comment: I have added getFollowers() method into my post @RamananR. Thanks for trying to help.
Answer: Rate limit for calling getFollowers() is:
Requests / 15-min window (user auth): 15
Requests / 15-min window (app auth): 30

https://dev.twitter.com/rest/reference/get/followers/list
Since you are calling getFollowers() more than this from for (Status status : result.getTweets()) you are getting rate limit error.
Check rate limits here:
    for (Status status : result.getTweets())
     {
         if (status.getText() != null)
         {
             // Getting followers list of a given user
             ArrayList<User> followers = getFollowers(status.getUser().getScreenName());
             // Here, Check if you rate limit has been exceeded.
             // If so, wait till limit is over and then continue
              .....
         }
     }


CSV file contains trailing pipe delimiters

Question: I have an excel file and I exported the file into a pipe delimited csv file. However, in each row of the csv file, there are trailing pipes.
Here's a typical row:
<code>dsad|asd|safd|sadaf|      |||||||||
ddss|sd|saadfdaf|dadf     |||||||||
</code>
Does anyone know how not to include those trailing pipes while exporting to csv from excel?
Thanks.
Answer: The sheet you are exporting probably contains cell that excel believes has values in them (I call them ghost cells). To prevent this behaviour, I have two suggestions:

Copy the spreadsheet to a fresh new spreasheet and export again. It should be fine.
Delete all the columns after the last column containing data (Do not use the Delete/Del key, select the columns till the end and use Ctrl+- instead). After this, save the workbook then export again.

If those don't work, there's probably some rows with actual data somewhere, and there, the data will be correctly delimited by the pipes. Might be best to count the number of columns of data that you have and make sure your resulting csv file has the same number of columns.
If this still doesn't work... just shout I guess? ^^;


Chi-square test of equality for 25th and 75th percentile

Question: I would like to examine the equality of the 25th and 75th percentile between two groups.
One way would be to apply Mood's test adapted to the 25th percentile (and then to the 75th):

Construct the 2x2 contingency table counting the number of instances above versus below the 25th percentile for each of the two groups (similarly a contingency table for the 75th percentile)
Then compute the chi-square test-statistic as the sum of square differences between observed versus expected frequencies.
Then accept or reject the null hypothesis of homogeneity if the chi-square test-statistic falls beyond the critical (e.g. 95%) chi-square value.

Another way would be to:

Split the data in the middle (by the median value).
For each of the two resulting datasets apply Mood's test as explained above but testing for equality of the median value (the median of the median would become the 25th and 75th percentile).

My questions are:

Do you think these two approaches are equivalent?
Is any of these approaches violating any of the chi-square-test assumptions ?

Thank you.
Answer: Your first approach uses more of the data and so seems preferable. Why not split the table into a 2 by 3 table and test both at once?
Comment: I am concerned that neither test may be valid, because they involve dependent values that are assumed independent.  In the first one the two $\chi^2$ statistics are dependent.  In the second one, the two subsets are dependent because they are determined by the same median value.  I am also suspicious that [the $\chi^2$ distribution might be incorrect in the first place.](http://stats.stackexchange.com/a/17148/919)  Could you comment on those issues?
Comment: @whuber Good points, my suggestion of the 3 by 2 table is also guilty of using data dependent cut-offs which may mean the calculated $\chi^2$ may  follow the theoretical distribution even more approximately than usual.


Determining parameters of Poisson distributions from their difference

Question: Let $X, Y$ be two independent random variables with Poisson distributions $Po(\lambda), Po(\mu)$ respectively. We don't know the values of $\mu$ and $\lambda$, but we know that $P(X>Y) = a, P(X=Y) = b$, where $a, b$ are known constants. Is there some good way how to determine $\mu$ and $\lambda$ from this?
Answer: So long as $a+b\lt 1$ and $b$ is not too small, it looks fairly simple to set up an optimistion problem with $\displaystyle a = \sum_{i=1}^k \sum_{j=0}^{i-1} e^{-\lambda}\frac{\lambda^i}{i!} e^{-\mu}\frac{\mu^j}{j!} $  $\displaystyle , b = \sum_{i=0}^k e^{-\lambda}\frac{\lambda^i}{i!} e^{-\mu}\frac{\mu^i}{i!} $ for some suitably large $k$, and then use your favorite optimiation software.
Doing so with Excel's solver gave the following illustrative approximate results, which in particular show that a smaller $b$ tends to lead to larger $\lambda$ and $\mu$ (and the need for a larger $k$).
<code>a       b        lambda  mu
0.3     0.6999   0.3567  0.0001
0.3     0.6      0.4171  0.1590
0.3     0.5      0.5058  0.3632
0.3     0.4      0.6512  0.6512
0.3     0.3      0.9392  1.1333
0.3     0.2      1.7549  2.2801
0.3     0.1      6.2794  7.7330
0.3     0.05    24.4076 27.6896
0.5999  0.4      0.9163  0.0002
0.5     0.4      0.8753  0.2445
0.4     0.4      0.7884  0.4666
0.3     0.4      0.6512  0.6512
0.2     0.4      0.4666  0.7884
0.1     0.4      0.2445  0.8753
0.0001  0.4      0.0002  0.9163
</code>
Comment: Btw. how can you see that $\lambda, \mu$ are uniquely determined by those conditions?
Comment: I think it is fairly obvious that if $a=\frac{1-b}{2}$ then $\lambda = \mu$ and that they reduce together as $b$ increases.  But for fixed $b$, $\lambda$ increases with $a$ and $\mu$ falls as $a$ increases.


Simple way to pick first variable that exists

Question: Is there a simple way to input a couple variables and return the first one that exists?
For example, either $_POST['a'][$field] or $_POST['b'][$field] will exist – only one or the other, never both.
I want to assign whichever variable exists to a variable.
I was hoping for a syntax like this:
$field = $_POST['a'][$field] or $_POST['b'][$field];

but this will only return $_POST['a'][$field] (if it exists) or NULL
And I do know that I can do:
if(isset($_POST['a'][$field])){
    $field = $_POST['a'][$field];
} else {
    $field = $_POST['b'][$field];
}

but I was wondering if there is something more simple that I am not thinking of.
Answer: You can use the null coalesce operator. It can be chained it as many times as you need, so you can also have a default value if neither is selected.
$field = $_POST['a'][$field] ?? $_POST['b'][$field] ?? "default";

Comment: Was about to ask if this is better than ternary operator of `?:` but I see the page you linked shows the equivalent. Thank you!
Comment: No point in using the ternary any longer. (For this use case!)


Swap the word in the String

Question: input:-
1
Ans kot

Output:-
kot Ans

INPUT :
the first line of the input contains the number of test cases. Each test case consists of a single line containing the string.
OUTPUT :
output the string with the words swapped as stated above.**
Code:-
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
StringBuffer result = new StringBuffer();
for (int i = 0; i  0; j--) {
        r.append(my[j] + " ");
    }
    r.append(my[0] + "\n");
    result.append(r.toString());
}
System.out.println(result.toString());
}

What is wrong in my code ? above is code which i am trying.
Comment: No, that's what you want. I mean what your program does.
Comment: And what's the output of your code?
Comment: i mention above in question @eyp... just reverse the word
Comment: You can design a function which reverse *a single word*; lets call it ```reverser(String):String``` then call it for every word.
Comment: It seams the code of a question in HackerRank... isn't it?
Comment: You're not trying to reverse a word, but a sequence of words.
Answer: String my[] = b.split(" ");
StringBuffer r = new StringBuffer();
for (int j = my.length - 1; j > 0; j--) {
    r.append(my[j] + " ");
}

this snippet of your code is only gonna reverse the sentence "word by word" not "character by character". therefore, you need reverse the string (my[j]) before you append it into the StringBuffer
Comment: @kucing-terbang any specific reason you have used `StringBuffer` instead of `StringBuilder` ?
Comment: @Ramswaroop No reason, I just copy pasted from the OP's code.
Answer: Use this
 Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            sc.nextLine();
            StringBuffer result = new StringBuffer();
            for (int i = 0; i  0; j--) {
                    r.append(my[j] + " ");

                }
                r.append(my[0] + "\n");
                result.append(r.toString());
            }
            System.out.println(result.toString());
        }

Comment: But why with next it is not working... and nextLine it is working... can u explain it
Comment: Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.
Comment: http://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class
Answer: Takes String input and return String in reverse order of each characters.
String reverse(String x) {
        int i = x.length() - 1;
        StringBuilder y = new StringBuilder();
        while (i >= 0) {
            y.append(x.charAt(i));
            i--;
        }

        return y.toString();
    }

Answer: public static String reverseWords(String input) {
    Deque<String> words = new ArrayDeque<>();
    for (String word: input.split(" ")) {
        if (!word.isEmpty()) {
            words.addFirst(word);
        }
    }
    StringBuilder result = new StringBuilder();
    while (!words.isEmpty()) {
        result.append(words.removeFirst());
        if (!words.isEmpty()) {
            result.append(" ");
        }
    }
    return result.toString();
}

Answer: You can run this code:
String[] splitted = yourString.split(" ");

for (int i = splitted.length-1; i>=0; i--){
    System.out.println(splitted[i]);
}

Answer: Multiple things:

You are using next api which will just read your string that you type word by word and you loop until a i.e. in your example just once. So instead use nextLine api which will read whole line instead of just a word and then split by space:
String b = sc.nextLine();

You are reading input with nextInt api followed by enter, you you might sometime end up having return character when reading next token using next api. Instead use:
int a = Integer.parseInt(sc.nextLine());

You are using StringBuffer which has an overhead of obtaining mutex and hence should use StringBuilder.
Answer:

Code:-

    Scanner sc =new Scanner(System.in);
        int a =Integer.parseInt(sc.nextLine());
        StringBuffer result= new StringBuffer();
        for (int i = 0; i 0; j--) {
      r.append(my[j]+" ");

     }
     r.append(my[0] + "\n");
          result.append(r.toString());
    }
     System.out.println(result.toString());

enter code here

Swap the word in the String