text:
Q: Filtering array of objects with multiple attribute on multiple condition I am trying to filter an array of objects with multiple attribute on multiple condition. so I'm creating an param array which consists of of multiple array holding the parameters. For example
var params = [
    ["id", "equals", "11060"],
    ["user_id", "exact", "84"]
];

first element is key , second one is condition  and third one is value.
so first filtering condition is
id == '11060' and second one is user_id = '84'
// data to filter
    var originalData = [{
        "id": 11141,
        "user_id": 84,
        "received": "26 Jan 2017",
        "approvalstatus": "Approved"
    }, {
        "id": 11080,
        "user_id": 84,
        "received": "25 Jan 2017",
        "approvalstatus": "Approved"
    }, {
        "id": 11079,
        "user_id": 84,
        "received": "25 Jan 2017",
        "approvalstatus": "Approved"
    }, {
        "id": 11078,
        "user_id": 84,
        "received": "25 Jan 2017",
        "approvalstatus": "Approved"
    }, {
        "id": 11060,
        "user_id": 84,
        "received": "24 Jan 2017",
        "approvalstatus": "Approved"
    }];

Following is my filtering function.
   filteredData = originalData.filter(function(item) {
        params.forEach(function(value, index) {
            var cond = value[1];
            var cKey = value[0];
            var cValue = value[2];
            var flag = false;
            if (cond == 'equals') {
                if (item[cKey] == Number(cValue)) {
                    flag = true;
                }
            } else if (cond == 'exact'){
                if (item[cKey].toString() == cValue) {
                    flag = true;
                }
            }
            return flag;
        });
        return false;
    });

but it's not working. What I am doing wrong? TIA.
jsfiddle

A: You do a forEach(), the return value will not be transmitted as the return value of the filtering function.
Also, you didn't decided if the value must pass all test successfully or only one. I assume it's all test must be passed successfully.
If it's only one of them, the code is slightly different.
filteredData = originalData.filter(function(item) {
    var i, ntest, cKey, cValue, flag;
    for(i=0, ntest=params.length; i<ntest; ++i) {
        cKey = params[i][0];
        cValue = params[i][2];
        switch(params[i][1]) {
            case "equals":
                if(item[cKey] != Number(cValue)) return false;
            break;
            case "exact":
                if(item[cKey].toString() != cValue) return false;
            break;
        }
    }
    return true;
});

A: Problem:
You cannot return from forEach. forEach will return an array to filter and an array is truthy. So, the resulting data will contain all the elements.
Solution:
for can be used instead of forEach. To check if all the conditions in the array are satisfied, check if flag is set to false and return from there to exclude that element from resulting array.

var originalData = [{
    "id": 11141,
    "user_id": 84,
    "received": "26 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11080,
    "user_id": 84,
    "received": "25 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11079,
    "user_id": 84,
    "received": "25 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11078,
    "user_id": 84,
    "received": "25 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11060,
    "user_id": 84,
    "received": "24 Jan 2017",
    "approvalstatus": "Approved"
}];

var params = [
    ["id", "equals", "11060"],
    ["user_id", "exact", "84"]
];

filteredData = originalData.filter(function(item) {
    var flag = false;

    for (var i = 0; i < params.length; i++) {
        var value = params[i];
        var condition = value[1];

        if (condition === 'equals') {
            flag = item[value[0]] === Number(value[2]);
        } else if (condition === 'exact') {
            flag = item[value[0]].toString() === value[2];
        }

        // If flag is false, return from here
        // No need to check other conditions
        if (flag === false) {
            break;
        }
    }
    return flag;
});

console.log(filteredData);

Better(?) Alternative
I'll recommend to use an object instead of array of arrays to store the filter criteria.

var originalData = [{
    "id": 11141,
    "user_id": 84,
    "received": "26 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11080,
    "user_id": 84,
    "received": "25 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11079,
    "user_id": 84,
    "received": "25 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11078,
    "user_id": 84,
    "received": "25 Jan 2017",
    "approvalstatus": "Approved"
}, {
    "id": 11060,
    "user_id": 84,
    "received": "24 Jan 2017",
    "approvalstatus": "Approved"
}];

// Filter criteria
var params = {
    id: 11060,
    user_id: 84
};

// Get keys from params
var keys = Object.keys(params);

filteredData = originalData.filter(function(item) {
    var flag = false;
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        // Check if value from filter criterial and
        // current element are equal
        flag = item[key] === params[key];
        if (flag === false) {
            break;
        }
    }
    return flag;
});

console.log(filteredData);

A: You could use Array#every and check every condition.

var params = [["id", "equals", "11060"], ["user_id", "exact", "84"]],
    originalData = [{ id: 11141, user_id: 84, received: "26 Jan 2017", approvalstatus: "Approved" }, { id: 11080, user_id: 84, received: "25 Jan 2017", approvalstatus: "Approved" }, { id: 11079, user_id: 84, received: "25 Jan 2017", approvalstatus: "Approved" }, { id: 11078, user_id: 84, received: "25 Jan 2017", approvalstatus: "Approved" }, { id: 11060, user_id: 84, received: "24 Jan 2017", approvalstatus: "Approved" }],
    filteredData = originalData.filter(function (item) {
        return params.every(function (value) {
            var cond = value[1],
                cKey = value[0],
                cValue = value[2];
            if (cond == 'equals') {
                return item[cKey] == Number(cValue);
            } else if (cond == 'exact') {
                return item[cKey].toString() == cValue;
            }
            return false;
        });
    });

console.log(filteredData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A short version, would be, to convert all conditions to functions and call it with item.

var params = [["id", "equals", "11060"], ["user_id", "exact", "84"]],
    conditions = params.map(function (a) {
        switch (a[1]) {
            case 'equals': return function (o) { return o[a[0]] == Number(a[2]); };
            case 'exact': return function (o) { return o[a[0]].toString() == a[2]; };
        }
    }),
    originalData = [{ id: 11141, user_id: 84, received: "26 Jan 2017", approvalstatus: "Approved" }, { id: 11080, user_id: 84, received: "25 Jan 2017", approvalstatus: "Approved" }, { id: 11079, user_id: 84, received: "25 Jan 2017", approvalstatus: "Approved" }, { id: 11078, user_id: 84, received: "25 Jan 2017", approvalstatus: "Approved" }, { id: 11060, user_id: 84, received: "24 Jan 2017", approvalstatus: "Approved" }],
    filteredData = originalData.filter(function (item) {
        return conditions.every(function (condition) {
            return condition(item);
        });
    });

console.log(filteredData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: var filteredData = originalData.filter(function(data){
  var found = false;
  params.map(function(param){
    switch(param[1]){
        case "equals":
          if(data[param[0]] == param[2]){ found = true; }
        break;
        case "exact":
          if(data[param[0]] == param[2]){ found = true; }
        break;
    }
  })
  return found;
})

console.log(filteredData);


text:
Q: How to change the link of the wordpress logo in the admin bar? I have found solutions to change the logo itself and to remove that "about.php" link in the dropdown, but this does not affect the "about.php" link in the wordpress logo.
How can I change this?

A: You should add the following to your functions.php, you can add, edit or delete items to your desire.
remove_action( 'admin_bar_menu', 'wp_admin_bar_wp_menu', 10 );
add_action( 'admin_bar_menu', 'my_admin_bar_wp_menu', 10 );

    function my_admin_bar_wp_menu( $wp_admin_bar ) {
    $wp_admin_bar->add_menu( array(
        'id'    => 'wp-logo',
        'title' => '',
        'href'  => 'http://yourdomain.com',
        'meta'  => array(
            'title' => __('About my website'),
        ),
    ) );

    if ( is_user_logged_in() ) {
        // Add "About WordPress" link
        $wp_admin_bar->add_menu( array(
            'parent' => 'wp-logo',
            'id'     => 'about',
            'title'  => __('About WordPress'),
            'href'  => self_admin_url( 'about.php' ),
        ) );
    }

    // Add WordPress.org link
    $wp_admin_bar->add_menu( array(
        'parent'    => 'wp-logo-external',
        'id'        => 'wporg',
        'title'     => __('WordPress.org'),
        'href'      => __('http://wordpress.org/'),
    ) );

    // Add codex link
    $wp_admin_bar->add_menu( array(
        'parent'    => 'wp-logo-external',
        'id'        => 'documentation',
        'title'     => __('Documentation'),
        'href'      => __('http://codex.wordpress.org/'),
    ) );

    // Add forums link
    $wp_admin_bar->add_menu( array(
        'parent'    => 'wp-logo-external',
        'id'        => 'support-forums',
        'title'     => __('Support Forums'),
        'href'      => __('http://wordpress.org/support/'),
    ) );

    // Add feedback link
    $wp_admin_bar->add_menu( array(
        'parent'    => 'wp-logo-external',
        'id'        => 'feedback',
        'title'     => __('Feedback'),
        'href'      => __('http://wordpress.org/support/forum/requests-and-feedback'),
    ) );
}

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RadGrid get [GridClientSelectColumn] selected Items I would like to loop and get all the selected checkbox items from [GridClientSelectColumn], but there has no any row return even the column checked. Thanks for helping.
.aspx
<telerik:RadGrid ID="RadGrid_1" runat="server" AllowPaging="True"
    AutoGenerateColumns="False" CellSpacing="0" GridLines="None"
    Skin="Outlook" AllowMultiRowSelection="True" AllowSorting="True">

    <ClientSettings>
        <Selecting AllowRowSelect="True" />
    </ClientSettings>

<Columns>
    <telerik:GridClientSelectColumn FilterControlAltText="Filter template_selected column"
        UniqueName="template_selected">
    </telerik:GridClientSelectColumn>
    <telerik:GridBoundColumn FilterControlAltText="Filter ID column"
        HeaderText="PHID" UniqueName="ID" Visible="False"
        DataField="PHID">
    </telerik:GridBoundColumn>
    <telerik:GridBoundColumn FilterControlAltText="Filter Title column"
        HeaderText="Title" UniqueName="Title" DataField="Title">
    </telerik:GridBoundColumn>
</columns>

.aspx.cs
protected void btn_Click(object sender, EventArgs e)
{
    string id;
    bool chec;
    foreach (GridDataItem item in RadGrid_1.SelectedItems)
    {
        CheckBox chk = (CheckBox)item["template_selected"].Controls[0];
        title = item["Title"].Text;
        chec = chk.Checked;
    }
}

A: I'm not sure what version of Telerik you're using, but I do know that regardless of the version, the RadGrid can be quite picky.
The demo on the Telerik website for selecting items is as follows:
http://demos.telerik.com/aspnet-ajax/grid/examples/functionality/selecting/row-selection/defaultcs.aspx
Here's the markup that they use for the demo.
 <telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1" AllowMultiRowSelection="true"
    runat="server" AllowSorting="True" GridLines="None" OnPreRender="RadGrid1_PreRender">
    <MasterTableView>
        <Columns>
            <telerik:GridClientSelectColumn UniqueName="ClientSelectColumn">
            </telerik:GridClientSelectColumn>
        </Columns>
    </MasterTableView>
    <ClientSettings EnableRowHoverStyle="true">
        <Selecting AllowRowSelect="True"></Selecting>
        <ClientEvents OnRowMouseOver="RowMouseOver" />
    </ClientSettings>
</telerik:RadGrid>

Based on the above, I would check:

*

*Are you using a MasterTableView? If you're not, you might want to try that approach even if you don't have detail tables. If RadGrid_1.MasterTableView.SelectedItems doesn't work, you can try iterating through RadGrid_1.MasterTableView.Items and check for items where  item.Selected is true.

*I'm going to assume that </column> in your post above is just a typo, but it should be </Columns>
Hope that helps. (Incidentally, the demo code on their website is incorrect because they don't even define all of the columns in the grid within their "live" sample code, LOL.)

A: Here is what I do:
 For Each griditem1 As GridDataItem In RadGrid.MasterTableView.Items
            If griditem1.Selected Then
                Dim DocumentID As String = griditem1.OwnerTableView.DataKeyValues(griditem1.ItemIndex)("DocID").ToString

            End If


text:
Q: cURL: Hostname was NOT found in DNS cache We are having a strange error. It happens around once every minute and this is what we see in the logs:
* Connection #0 to host data01 left intact
* Hostname was NOT found in DNS cache
*   Trying x.x.x.x...
* connect to x.x.x.x port yyyy failed: Connection timed out
* Failed to connect to x.x.x.x port yyyy: Connection timed out
* Closing connection 0
We have data01 correctly defined in our /etc/hosts file but for some reason, the resolved x.x.x.x IP address is incorrect so the connection fails.
curl --version returns the following:
curl 7.35.0 (x86_64-pc-linux-gnu) libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3

Please help.

A: The maintainer of curl/libcurl (https://stackoverflow.com/users/93747/daniel-stenberg) stated in Libcurl Hostname was NOT found in DNS cache:

The texts about not found in the DNS cache is just junk and is removed in a future version

(Also I doubt that that message is only received by you sometimes rather than always , i.e. also if you don't experience a timeout- just guessing
here.)
Make sure nsswitch.conf prefers /etc/hosts:
$ grep host /etc/nsswitch.conf
hosts: files dns
Otherwise the wrong IP may be given by the DNS server. Check this by altering your /etc/hosts and $ ping -c1 data01.


text:
Q: Power Apps, SortByColumns, matching Dropdown choice to Column Name When I try my formula in browsegallery, I am only seeing data for the drop down CAATT ID and Requestor. I cant find out why my other dropdown choices arent working here.
Could it be column type? or could it be the column names are wrong? I am getting my column names from MS List.
If(
    Toggle2.Value = false,
    SortByColumns(
        Filter(
            [@'Documentation Tracker'],
            Or(Lower(Requestor_two) = Lower(User().Email), Lower(Approver.Value) = Lower(User().Email)) && TextSearchBox1.Text in Title
        ),
        If(Dropdown1.Selected.Value = "Documentation Type", "Doc_Type", Dropdown1.Selected.Value = "Requestor", "Requestor_two", Dropdown1.Selected.Value = "CAATT ID", "Title", Dropdown1.Selected.Value = "Status", "Approval Status", Dropdown1.Selected.Value = "Automation Type", "Automation Type", Dropdown1.Selected.Value = "Approver", "Approver", Dropdown1.Selected.Value = "Approval Date", "Approval Date",Dropdown1.Selected.Value = "CAATTS Name", "CAATTs Name", "ID"),
        Ascending
    ),
    SortByColumns(
        Filter(
            [@'Documentation Tracker'],
            TextSearchBox1.Text in Title
        ),
        If(Dropdown1.Selected.Value = "Documentation Type", "Doc_Type", Dropdown1.Selected.Value = "Requestor", "Requestor_two", Dropdown1.Selected.Value = "CAATT ID", "Title", Dropdown1.Selected.Value = "Status", "Approval Status", Dropdown1.Selected.Value = "Automation Type", "Automation Type", Dropdown1.Selected.Value = "Approver", "Approver", Dropdown1.Selected.Value = "Approval Date", "Approval Date",Dropdown1.Selected.Value = "CAATTS Name", "CAATTs Name", "ID"),
        Ascending
    )
)

Update new code:
If(
    Toggle2.Value = false,
    SortByColumns( AddColumns([@'Documentation Tracker'], "Doc_TypeValue", Doc_Type.Value),
        Filter(
            [@'ICFR Documentation Tracker'],
            Or(Lower(Requestor_two) = Lower(User().Email), Lower(Approver.Value) = Lower(User().Email)) && TextSearchBox1.Text in Title
        ),
        If(Dropdown1.Selected.Value = "Documentation Type", "Doc_TypeValue", Dropdown1.Selected.Value = "Requestor", "Requestor_two", Dropdown1.Selected.Value = "CAATT ID", "Title", Dropdown1.Selected.Value = "Status", "RequirementsApproval.Selected", Dropdown1.Selected.Value = "Automation Type", "DocumentationType", Dropdown1.Selected.Value = "Approver", "Approver", Dropdown1.Selected.Value = "Approval Date", "RequirementsApprovalDate",Dropdown1.Selected.Value = "CAATTS Name", "CAATTsName", "ID"),
        Ascending
    ),
    SortByColumns( AddColumns([@'Documentation Tracker'], "Doc_TypeValue", Doc_Type.Value),
        Filter(
            [@'ICFR Documentation Tracker'],
            TextSearchBox1.Text in Title
        ),
        If(Dropdown1.Selected.Value = "Documentation Type", "Doc_TypeValue", Dropdown1.Selected.Value = "Requestor", "Requestor_two", Dropdown1.Selected.Value = "CAATT ID", "Title", Dropdown1.Selected.Value = "Status", "RequirementsApproval.Selected", Dropdown1.Selected.Value = "Automation Type", "DocumentationType", Dropdown1.Selected.Value = "Approver", "Approver", Dropdown1.Selected.Value = "Approval Date", "RequirementsApprovalDate",Dropdown1.Selected.Value = "CAATTS Name", "CAATTsName", "ID"),
        Ascending
    )
)

Ive added the line AddColumns([@'Documentation Tracker'],, "Doc_TypeValue", Doc_Type.Value) after my SortByColumn, still getting an error.
Doc_Type is my field name in my sharepoint list
Does this make sense ?

A: You are facing this problem because of data type of your list columns. SortByColumns function will work fine with "Single line of text", "Number" or "Date and Time" columns simply by referring column names in formula.
But, sort on complex fields like "Choice" or "Person or Group" column will not work this way.
You have to get the value/property from these complex field based on which you will sort your gallery.
Example:
SharePoint list data:

To filter gallery based on Choice (Status) column, Person or Group (PersonCol) I have used formula like this:
SortByColumns(
    AddColumns(ReCreate, "StatusValue", Status.Value, "PersonColValue", PersonCol.DisplayName),
    If(
        Dropdown1.Selected.Value = "Title",
        "Title",
        Dropdown1.Selected.Value = "Modified",
        "Modified",
        Dropdown1.Selected.Value = "Status",
        "StatusValue",
        Dropdown1.Selected.Value = "Person Column",
        "PersonColValue",
        "ID"
    ),
    Ascending
)

Here I am filtering gallery items based on display name of Person or Group column.
Output:

Similarly, you have to adjust your formula based on data types you are using.
Documentations:

*

*AddColumns, DropColumns, RenameColumns, and ShowColumns functions in Power Apps

*Sort and SortByColumns functions in Power Apps

Update from comments:
Try using below formula for your requirements:
If(
    Toggle2.Value = false,
    SortByColumns(
        AddColumns(
            Filter(
                [@'ICFR Documentation Tracker'],
                Or(Lower(Requestor_two) = Lower(User().Email), Lower(Approver.Value) = Lower(User().Email)) && TextSearchBox1.Text in Title
            ),
            "Doc_TypeValue", Doc_Type.Value
        ),
        If(Dropdown1.Selected.Value = "Documentation Type", "Doc_TypeValue", Dropdown1.Selected.Value = "Requestor", "Requestor_two", Dropdown1.Selected.Value = "CAATT ID", "Title", Dropdown1.Selected.Value = "Status", "RequirementsApproval.Selected", Dropdown1.Selected.Value = "Automation Type", "DocumentationType", Dropdown1.Selected.Value = "Approver", "Approver", Dropdown1.Selected.Value = "Approval Date", "RequirementsApprovalDate",Dropdown1.Selected.Value = "CAATTS Name", "CAATTsName", "ID"),
        Ascending
    ),
    SortByColumns(
        AddColumns(
            Filter(
                [@'ICFR Documentation Tracker'],
                TextSearchBox1.Text in Title
            ),
            "Doc_TypeValue", Doc_Type.Value
        ),
        If(Dropdown1.Selected.Value = "Documentation Type", "Doc_TypeValue", Dropdown1.Selected.Value = "Requestor", "Requestor_two", Dropdown1.Selected.Value = "CAATT ID", "Title", Dropdown1.Selected.Value = "Status", "RequirementsApproval.Selected", Dropdown1.Selected.Value = "Automation Type", "DocumentationType", Dropdown1.Selected.Value = "Approver", "Approver", Dropdown1.Selected.Value = "Approval Date", "RequirementsApprovalDate",Dropdown1.Selected.Value = "CAATTS Name", "CAATTsName", "ID"),
        Ascending
    )
)


text:
Q: Weird InvokeRequired issue I have a UserControl with a TreeView control called mTreeView on it. I can get data updates from multiple different threads, and these cause the TreeView to be updated. To do this, I've devised the following pattern:
all data update event handlers must acquire a lock and then check for InvokeRequired; if so, do the work by calling Invoke. Here's the relevant code:
  public partial class TreeViewControl : UserControl
  {
    object mLock = new object();
    void LockAndInvoke(Control c, Action a)
    {
      lock (mLock)
      {
        if (c.InvokeRequired)
        {
          c.Invoke(a);
        }
        else
        {
          a();
        }
      }
    }

    public void DataChanged(object sender, NewDataEventArgs e)
    {
      LockAndInvoke(mTreeView, () =>
        {
          // get the data
          mTreeView.BeginUpdate();
          // perform update
          mTreeView.EndUpdate();
        });
    }
  }

My problem is, sometimes, upon startup, I will get an InvalidOperationException on mTreeView.BeginUpdate(), saying mTreeView is being updated from a thread different than the one it was created. I go back in the call stack to my LockAndInvoke, and lo and behold, c.InvokeRequired is true but the else branch was taken! It's as if InvokeRequired had been set to true on a different thread after the else branch was taken.
Is there anything wrong with my approach, and what can I do to prevent this?
EDIT: my colleague tells me that the problem is that InvokeRequired is false until the control is created, so this is why it happens on startup. He's not sure what to do about it though. Any ideas?

A: It is a standard threading race.  You are starting the thread too soon, before the TreeView is created.  So your code sees InvokeRequired as false and fails when a split second later the native control gets created.  Fix this by only starting the thread when the form's Load event fires, the first event that guarantees that all the control handles are valid.
Some mis-conceptions in the code btw.  Using lock is unnecessary, both InvokeRequired and Begin/Invoke are thread-safe.  And InvokeRequired is an anti-pattern.  You almost always know that the method is going to be called by a worker thread.  So use InvokeRequired only to throw an exception when it is false.  Which would have allowed diagnosing this problem early.

A: When you marshal back to the UI thread, it's one thread--it can do only one thing at at time.  You don't need any locks when you call Invoke.
The problem with Invoke is that it blocks the calling thread.  That calling thread usually doesn't care about what get's completed on the UI thread.  In that case I recommend using BeginInvoke to marshal the action back to the UI thread asynchronously.  There are circumstances where the background thread can be blocked on Invoke while the UI thread can be waiting for the background thread to complete something and you end up with a deadlock:  For example:
private bool b;
public void EventHandler(object sender, EventArgs e)
{
  while(b) Thread.Sleep(1); // give up time to any other waiting threads
  if(InvokeRequired)
  {
    b = true;
    Invoke((MethodInvoker)(()=>EventHandler(sender, e)), null);
    b = false;
  }
}

... the above will deadlock on the while loop while because Invoke won't return until the call to EventHandler returns and EventHandler won't return until b is false...
Note my use of a bool to stop certain sections of code from running.  This is very similar to lock.  So, yes, you can end up having a deadlock by using lock.
Simply do this:
public void DataChanged(object sender, NewDataEventArgs e)
{
      if(InvokeRequired)
      {
          BeginInvoke((MethodInvoker)(()=>DataChanged(sender, e)), null);
          return;
      }
      // get the data
      mTreeView.BeginUpdate();
      // perform update
      mTreeView.EndUpdate();
}

This simply re-invokes the DataChanged method asynchronously on the UI thread.

A: The pattern as you have shown it above looks 100% fine to me (albeit with some extra unnecessary locking, however I can't see how this would cause the problem you have described).
As David W points out, the only difference between what you are doing and this extension method is that you directly access mTreeView on the UI thread instead of passing it in as an argument to your action, however this will only make a difference if the value of mTreeView changes, and in any case you would have to try fairly hard to get this to cause the problem you have described.
Which means that the problem must be something else.
The only thing that I can think of is that you may have created mTreeView on a thread other than the UI thread - if this is the case then accessing the tree view will be 100% safe, however if you try and add that tree view to a form which was created on a different thread then it will go bang with an exception similar to the one that you describe.


text:
Q: How to get information from meta box in WordPress and show it in a page template I am having issues to echo metadata of the meta-box on the template page. The data seems to be saved, where am I doing wrong in echoing the data on the page?
The 'hello' that I have put inside the check if the varibale is set is acctualy showing on the page but not the variables themself. I have tried different places for the saving in the information in the functions.php but the place I put it know seems to be the only place that info is saved into them. Is there something wrong there? or how I'm trying to echo them on the page?
This is from my template side, HTML code. (page-facility.php)

  <?php
      if ( isset( $mf ) && '' !== $mf ) {
        echo 'hello';
        echo esc_attr( $mf );
     }
     if ( isset( $ls ) && '' !== $ls ) {
        echo 'hello';
        echo esc_attr( $ls );
     }
  ?>

This is my whole code for this in functions.php
/* Opening Hours meta box on template */
add_action('add_meta_boxes', 'add_openinghours_meta');
function add_openinghours_meta() {
    global $post;

    if(!empty($post))
    {
        $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);

        if($pageTemplate == 'page-facility.php' )
        {
            add_meta_box(
                'openinghours_meta', // $id
                'Öppettider', // $title
                'display_opening_information', // $callback
                'page', // $page
                'normal', // $context
                'high'); // $priority
        }
    }
}

if ( ! function_exists( 'display_opening_information' ) ) {

    /**
     * Meta box render function
     *
     * @param  object $post Post object.
     * @since  1.0.0
     */

    function display_opening_information($post) {
        // Add the HTML for the post meta
        $meta = get_post_meta( $post->ID );
        $openinghours_mf_input_field = ( isset( $meta['openinghours_mf_input_field'][0] ) && '' !== $meta['openinghours_mf_input_field'][0] ) ? $meta['openinghours_mf_input_field'][0] : '';
        $openinghours_ls_input_field = ( isset( $meta['openinghours_ls_input_field'][0] ) && '' !== $meta['openinghours_ls_input_field'][0] ) ? $meta['openinghours_ls_input_field'][0] : '';
        wp_nonce_field( 'openinghours_control_meta_box', 'openinghours_control_meta_box_nonce' ); // Always add nonce to your meta boxes!
        ?>

                <?php esc_attr_e( 'Måndag-Fredag:', 'openinghours_mf_input_field' ); ?>
                <input type="text" name="openinghours_mf_input_field" value="<?php echo esc_attr( $openinghours_mf_input_field ); ?>">

                <?php esc_attr_e( 'Lördag-Söndag:', 'openinghours_ls_input_field' ); ?>
                <input type="text" name="openinghours_ls_input_field" value="<?php echo esc_attr( $openinghours_ls_input_field ); ?>">

        <?php
    }
}

add_action( 'save_post', 'openinghours_save_metabox' );

if ( ! function_exists( 'openinghours_save_metabox' ) ) {
    /**
     * Save controls from the meta boxes
     *
     * @param  int $post_id Current post id.
     * @since 1.0.0
     */
    function openinghours_save_metabox( $post_id ) {
        /*
         * We need to verify this came from the our screen and with proper authorization,
         * because save_post can be triggered at other times. Add as many nonces, as you
         * have metaboxes.
         */
        if ( ! isset( $_POST['openinghours_control_meta_box_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['openinghours_control_meta_box_nonce'] ), 'openinghours_control_meta_box' ) ) { // Input var okay.
            return $post_id;
        }

        // Check the user's permissions.
        if ( isset( $_POST['post_type'] ) && 'page' === $_POST['post_type'] ) { // Input var okay.
            if ( ! current_user_can( 'edit_page', $post_id ) ) {
                return $post_id;
            }
        } else {
            if ( ! current_user_can( 'edit_post', $post_id ) ) {
                return $post_id;
            }
        }

        /*
         * If this is an autosave, our form has not been submitted,
         * so we don't want to do anything.
         */
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return $post_id;
        }

        /* Ok to save */

        if ( isset( $_POST['openinghours_mf_input_field'] ) ) { // Input var okay.
            update_post_meta( $post_id, 'openinghours_mf_input_field', sanitize_text_field( wp_unslash( $_POST['openinghours_mf_input_field'] ) ) ); // Input var okay.
        }
        if ( isset( $_POST['openinghours_ls_input_field'] ) ) { // Input var okay.
            update_post_meta( $post_id, 'openinghours_ls_input_field', sanitize_text_field( wp_unslash( $_POST['openinghours_ls_input_field'] ) ) ); // Input var okay.
        }

    }

    $mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
    $ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );
}

I want the variables to be printed with the info that is put into the meta-box. To show opening hours of the facility.

A: Please make sure that the $mf and $ls variables are initialized in the page-facility.php template file.
For example:

  <?php
     //initilize variables
     $mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
     $ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );

     //then check if empty
     if ( isset( $mf ) && '' !== $mf ) {
        echo 'hello';
        echo esc_attr( $mf );
     }
     if ( isset( $ls ) && '' !== $ls ) {
        echo 'hello';
        echo esc_attr( $ls );
     }
  ?>

A: I had put the code;
$mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
$ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );

inside the function, it was supposed to be within the WordPress loop, I finally figured it out last night, just forgot to post it here. Thank you all for looking at my problem!
So like this instead;

  <?php
      $mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
      $ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );

      if ( isset( $mf ) && '' !== $mf ) {
        echo 'hello';
        echo esc_attr( $mf );
     }
     if ( isset( $ls ) && '' !== $ls ) {
        echo 'hello';
        echo esc_attr( $ls );
     }
  ?>


text:
Q: no sound when using pjsip I've got a problem with pjsip. I'm trying to make an outgoing call with pjsua_call_make_call. It's working, but when I answer this call on a device, I can't hear any sound. However, I can see an icon on iPhone, indicating that a microphone is in use. Did anybody come across such issue?

A: I am having a similar issue. I place an outbound call and I can hear the audio on the device when I pick up the call, but can't hear any audio on the device using pjsip to make the call.
If your audio capture doesn't seem to be working make sure you have microphone permission, and you have to manually call pjsua_set_snd_dev(), when you connect. There's some other additional troubleshooting here https://trac.pjsip.org/repos/wiki/Getting-Started/iPhone#Commonproblems

A: I've no experience with iOS, but I suppose you should connect audio stream to some device in on_call_media_state callback (link). Look at minimal example from desktop app:
pjsua_call_info ci;
pjsua_call_get_info(call_id, &ci);

for (unsigned i = 0; i < ci.media_cnt; i++) {
    if (ci.media[i].type == PJMEDIA_TYPE_AUDIO) {
        if (ci.media[i].status == PJSUA_CALL_MEDIA_ACTIVE) {
            pjsua_conf_connect(ci.conf_slot, 0);
            pjsua_conf_connect(0, ci.conf_slot);
        }
    }
}

Edit:
iOS code for default audio stream in call:
var callinfo: pjsua_call_info = pjsua_call_info()
pjsua_call_get_info(call_id, &callinfo)
if(callinfo.media_status == PJSUA_CALL_MEDIA_ACTIVE) {
    pjsua_conf_connect(callinfo.conf_slot, 0)
    pjsua_conf_connect(0, callinfo.conf_slot)
}


text:
Q: Python relative imports. "Attempted relative import beyond top-level package" I would like to have a file with constants in my project's root directory. I'm trying to solve this my using relative imports. What I've tried so far is:
I have the following structure
└── project
    ├── packageA
    │   ├── fileA.py # contains class A
    │
    └── definitions.py
    └── main.py

Contents of fileA.py
from ..definitions import hello_world

class A:
    def __init__(self):
        print(hello_world)

Contents of definitions.py
hello_world = "Hello world"

Contents of main.py
from packageA.fileA import A

A()

I'm standing in the project dir and running the command
python3 main.py

I get the following error
 line 1, in <module>
    from ..definitions import hello_world
ValueError: attempted relative import beyond top-level package

So what am I doing wrong here?

A: Instead of
from ..definations import hello_world

You can just use
from definations import hello_world


text:
Q: How do I move tags in Subversion I wish Subversion had a better way of moving tags. The only way that I know to move a tag is to remove the file from the tag and then copy it again. Revision tree browsers don't seem to handle that very well. This also requires keeping the directory structure under the trunk and tag in sync.
Use case: We have thousands of "maps" and we want to tag which version of each map is the "production" version. We need to be able to easily get the production version of all maps.
Can anyone suggest a better way to address our use case?
I have considered properties also but then we can't get the prod version of all files easily. Merging to the tag doesn't appear to be very easy either.
(Originally posted to http://jamesjava.blogspot.com/2007/12/subversion-moving-tags.html)

A: I don't see the need to "remove" the file from the production tag. You should copy the new file over the existing one and check it in. That way you will preserve the history.
Of course you would need the production tag checked out to do this.

A: I don't think you can ever do this with the way that subversion operates.  I believe the best solution would be to look at a tool like git which seems like it fits into your use case.  You're production system could 'pull' in the "maps" that are accepted.  While I realize this isn't subversion, using git might be closer match to your use pattern than svn.
A really good write up on why git's pull based development model is a better match to your scenario is here.
There are also tutorials on how to start migrating like this.

A: This is not a good use for subversion.
Subversion tags are for giving a name to an instance of a tree as at a specific snapshot in its history, and should be kept static.
Perhaps you could use the current date, or an incrementing number as part of the tag? you could have a directory under tags containing the production versions as at any particular date. Take the latest date as the current production version.
Today's version could be found at
/svn/tags/production/2008/09/15/mapproject

A: I think you are trying to solve the wrong problem.
It sounds like you have a trunk which contains versions of maps which are not yet released, and when you do a release, you want to cherry pick which maps to update from all the possible updates on trunk.
Assuming this is the case, create a branch called "Release". (Consider creating a new empty directory, and copying each map version needed (with separate svn cp commands) if that will be faster).
Now you have the current release in the branch. Tag it (svn cp the whole directory) with "Release XXX" where XXX is the meaningful ID for your latest release.
Then as maps are approved for the next release, svn cp them to your release branch. I assume you don't want to use merge, because maps a discrete elements not source code.
At the time of the next release, you can tag again.
Now you know, what the latest approved maps are and what was in every release. If you really can't remember the latest release number, and you can come up with a time you'd need to know without just looking in the tags directory, you can create a tag which svn cp the latest release, then blow it away and re-copy when you do the next release.

A: Why don't you make a new tag for the current production version? Remember, Subversion is not CVS. So making a copy of the complete directory tree doesn't cost you anything.

A: One way would be to move to a "stable trunk" model.

*

*Make a branch from trunk to use as your working area.

*Stop making commits directly to trunk - have everyone switch to the development branch.

*Have trunk checked out by the people who are managing stable releases, ensure they have commit rights.

*When you wish to "release" a map, use "reintegrate merge" to pull in the changes to that file/directory and commit the changes.

This might appear a bit upside down but is fairly workable. You can either have production machines pull straight from trunk, or make a new tag from trunk for each release. For the latter, you will need some way to communicate the new tag to the production machines. Some sort of messaging, shared config or naming convention could work.
But be aware that you must get into the mindset of trunk being somewhat 'sacred' in this model.

A: If i understand well your needs, i think that the best way of doing it, is to have all maps as externals of the main trunk and then make a script that recursively tags each map (external) to it's current revision in the working copy (or the server if you want it that way).


text:
Q: Dojo store query with wildcard I'm using a Dojo memory store (dojo/store/Memory).  I would like to retrieve items based on a wildcard query but the query method doesn't seem to support wildcards.  i.e. given the following items:
{ id: "apple", details: "fruit" }
{ id: "applemac", details: "computer" }

store.query({ id: "apple" }) returns the first row as expected, but store.query({ id: "apple*" }) returns nothing.
Does anyone know if it's possible to use wildcards and if so, how?
Thanks

A: You can use a RegExp object to do wildcard queries
store.query({id:new RegExp("apple*")})

Here's a JSFiddle


text:
Q: Clang/LLVM enabling OpenMP-Support I am using Visual Studio 2017 Community Edition on Windows. My goal is to build a cross-plattform shared c++ library for mobile devices. So far i used the corresponding c++ development template.
After setting everything up i can't see how to enable openmp in the compiler. Coming from Android Studio it was sufficient to add "-fopenmp" to the compiler flags. VS seems to support equal compilers in this template gcc 4.9 and clang 3.8. I read that under "Configuration Properties -> C/C++ -> Language" there should be an option to enable OpenMP support, but in case of this template the option is not there. (I tested other c++ template which offers this possibility)
Even the compiler flag "-fopenmp", results in an "undefined reference error" of openmp. As i researched more i looked up the different toolchains which are delivered by VS, the LLVM toolchain seems not including omp header oder prebuilts.
Maybe some one can help, the code was working in android studio via cmake. I added all necessary dependencies through visual studio and installed the necessary vs packages.
Edit:
Maybe i should add that the platforms i want to build for are ARM and ARM64.

A: I solved this issues and maybe it helps someone. I switched the compiler to gcc in the already installed version. The issues was that i didn't set the compiler flag -fopenmp at the linker.
Now it is building, but i still don't know why clang/llvm is not working.


text:
Q: Not able to get Text for selected webelement I am trying to get text from class web element.
Here is my script :
public void test() throws InterruptedException{
    driver.manage().window().maximize();
    driver.get(adminUrl);
    txtUserName.sendKeys("gagnt2");
    txtPassword.sendKeys("okay123");
    btnLogin.click();
    driver.navigate().to(propertyDetails);
    System.out.println("Main Pop Up Window"+driver.getWindowHandle());

    WebElement element = driver.findElement(By.xpath("//*[@id='lnkSaveAllDetails']"));
    ((JavascriptExecutor) driver).executeScript(
            "arguments[0].scrollIntoView();", element);
    element.click();
    WebElement confirmbtn=driver.findElement(By.className("BlueBtn"));
    confirmbtn.click();

}

But I am getting excpetion
org.openqa.selenium.ElementNotVisibleException: element not visible
Here is html format of webpage:

A: Use this:
WebElement pop= driver.findElement(By.cssSelector("div#dvStillForSalePopup>p.para"));

A: try below code...
    driver.navigate().to(propertyDetails);
    System.out.println("Current Window"+driver.getWindowHandle());
    Actions action= new Actions(driver);
    action.moveToElement(btnUpdate).click().perform();
    driver.switchTo().activeElement();
    WebElement pop= driver.findElement(By.className("para"));


text:
Q: Creating a clone of an object, but of a class that inherits the original one In the given scenario, i have a class:
class shopCart {}

I use destructors and constructors in there, to perform certain actions.
Later on, i want to store a serialized version of the cart. However, the object i serialize should not incorporate the destructor and constructor methods.
In order to achieve this, i created a class:
class storageCart extends shopCart {
    function __construct(){}
    function __destruct(){}
}

Now, before i store the cart, i must create a new object of type storageCart and make sure it contains all the properties of shopCart.
To fulfill this need, shopCart has a method getInstanceForStorage():
public function getInstanceForStorage() {
    $storageCart = new storageCart();
    foreach(get_object_vars($this) as $k => $v){
        $storageCart->{$k}=$v;
    }
    return $storageCart;
}

The problem is that changes i make to the new instance (storageCart) seem to affect the original instance (shopCart).
It is important to mention here, that one of the variables of shopCart is an array containing objects (cart items).
I assume i ran into some object / instancing / copying / cloning (or lack thereof) mess. But i don't know what the problem could be, because i do not use pointers in my assignment in the above foreach loop.
Can anyone shed some light on what is happening here?
Note: This is PHP > 5.3
EDIT
I tried copying the contents of the array which contains the objects, by assigning them to the same array in the new object and using clone, but - to my surprise - i still end up with a reference. I don't understand.
Is it perhaps possible, that objects within the cloned objects are still references to the original objects?

A: The technique you want is called making a "deep clone", and can be implemented easily using the __clone()  magic method in your objects:
/**
 * Implement PHP __clone to create a deep clone, not just a shallow copy.
 */
public function __clone()
{
    foreach ($this as $key => $val) {
        if (is_object($val) || (is_array($val))) {
            $this->{$key} = clone $val;
        }
    }
}

Just define this in your main class, and in the classes of all the objects that you store as properties in that class, all the way down
Of course, if you hold an array of objects as a property, you'll need to adapt this code to walk that array as well


text:
Q: Curator Leader election give connection refused error I implemented curator leader election example which is given in this site
Instead of having number of curator clients I added only one curator client as follows
public void selectLeader() {
    CuratorFramework    client = null;
    try {
        client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(1000, 3));
        LeaderSelectorService    service = new LeaderSelectorService(client, "/leaderSelections", "LeaderElector");

        client.start();
        Thread.sleep(10000);
        service.start();
    } catch (Exception e) {
        System.out.println("error"+e);
    }finally
    {
        System.out.println("Shutting down...");
       // CloseableUtils.closeQuietly(client);
    }

}

public class LeaderSelectorService extends LeaderSelectorListenerAdapter implements Closeable {
private final String name;
private final LeaderSelector leaderSelector;

public LeaderSelectorService(CuratorFramework client, String path, String name) {
    this.name = name;

    // create a leader selector using the given path for management
    // all participants in a given leader selection must use the same path
    // ExampleClient here is also a LeaderSelectorListener but this isn't required
    leaderSelector = new LeaderSelector(client, path, this);

    // for most cases you will want your instance to requeue when it relinquishes leadership
    leaderSelector.autoRequeue();
}

public void start() throws IOException
    {
        // the selection for this instance doesn't start until the leader selector is started
        // leader selection is done in the background so this call to leaderSelector.start() returns immediately
        leaderSelector.start();
    }
@Override
public void takeLeadership(CuratorFramework arg0) throws Exception {
    // we are now the leader. This method should not return until we want to relinquish leadership

    final int         waitSeconds = (int)(5 * Math.random()) + 1;

    System.out.println(name + " is now the leader. Waiting " + waitSeconds + " seconds...");
    //System.out.println(name + " has been leader " + leaderCount.getAndIncrement() + " time(s) before.");
    try
    {
        Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));
    }
    catch ( InterruptedException e )
    {
        System.err.println(name + " was interrupted.");
        Thread.currentThread().interrupt();
    }
    finally
    {
        System.out.println(name + " relinquishing leadership.\n");
    }

}

@Override
public void close() throws IOException {
    leaderSelector.close();

}

}
I have only one zookeeper instance and I am using Zookeeper 3.4.6, curator-framework 4.0.0 and curator-recipes 4.0.0.
when I start the client, it connects to zookeeper and in the log I can see "State change : connected" message.
Then I wait 10s and start leader election which gives me below error repeatedly.
2017-09-06 09:34:22.727  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Unable to read additional data from server sessionid 0x15e555a719d0000, likely server has closed socket, closing socket connection and attempting reconnect
2017-09-06 09:34:22.830  INFO 1228 --- [c-1-EventThread] o.a.c.f.state.ConnectionStateManager     : State change: SUSPENDED
2017-09-06 09:34:23.302  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-09-06 09:34:23.303  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Socket connection established, initiating session, client: /127.0.0.1:49594, server: localhost/127.0.0.1:2181
2017-09-06 09:34:23.305  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x15e555a719d0000, negotiated timeout = 120000
2017-09-06 09:34:23.305  INFO 1228 --- [c-1-EventThread] o.a.c.f.state.ConnectionStateManager     : State change: RECONNECTED
2017-09-06 09:34:23.310  WARN 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Session 0x15e555a719d0000 for server localhost/127.0.0.1:2181, unexpected error, closing socket connection and attempting reconnect

java.io.IOException: Connection reset by peer
    at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[na:1.8.0_131]
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[na:1.8.0_131]
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[na:1.8.0_131]
    at sun.nio.ch.IOUtil.read(IOUtil.java:192) ~[na:1.8.0_131]
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380) ~[na:1.8.0_131]
    at org.apache.zookeeper.ClientCnxnSocketNIO.doIO(ClientCnxnSocketNIO.java:75) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:363) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1214) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]

after some time it started to give me below error message.
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:99) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.curator.framework.imps.CuratorFrameworkImpl.checkBackgroundRetry(CuratorFrameworkImpl.java:831) [curator-framework-4.0.0.jar:4.0.0]
    at org.apache.curator.framework.imps.CuratorFrameworkImpl.processBackgroundOperation(CuratorFrameworkImpl.java:623) [curator-framework-4.0.0.jar:4.0.0]
    at org.apache.curator.framework.imps.WatcherRemovalFacade.processBackgroundOperation(WatcherRemovalFacade.java:152) [curator-framework-4.0.0.jar:4.0.0]
    at org.apache.curator.framework.imps.GetConfigBuilderImpl$2.processResult(GetConfigBuilderImpl.java:222) [curator-framework-4.0.0.jar:4.0.0]
    at org.apache.zookeeper.ClientCnxn$EventThread.processEvent(ClientCnxn.java:590) [zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.zookeeper.ClientCnxn$EventThread.run(ClientCnxn.java:499) [zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]

2017-09-06 09:34:31.897  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
2017-09-06 09:34:31.898  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Socket connection established, initiating session, client: /127.0.0.1:49611, server: localhost/127.0.0.1:2181
2017-09-06 09:34:31.899  INFO 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x15e555a719d0000, negotiated timeout = 120000
2017-09-06 09:34:31.899  INFO 1228 --- [c-1-EventThread] o.a.c.f.state.ConnectionStateManager     : State change: RECONNECTED
2017-09-06 09:34:31.907  WARN 1228 --- [localhost:2181)] org.apache.zookeeper.ClientCnxn          : Session 0x15e555a719d0000 for server localhost/127.0.0.1:2181, unexpected error, closing socket connection and attempting reconnect

java.io.IOException: Xid out of order. Got Xid 41 with err -6 expected Xid 40 for a packet with details: clientPath:/leaderSelections serverPath:/leaderSelections finished:false header:: 40,12  replyHeader:: 0,0,-4  request:: '/leaderSelections,F  response:: v{}
    at org.apache.zookeeper.ClientCnxn$SendThread.readResponse(ClientCnxn.java:892) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.zookeeper.ClientCnxnSocketNIO.doIO(ClientCnxnSocketNIO.java:101) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:363) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1214) ~[zookeeper-3.5.3-beta.jar:3.5.3-beta-8ce24f9e675cbefffb8f21a47e06b42864475a60]

I tried several solution in the internet but non got succeeded. Does anybody know the root cause of this issue.

A: I have fixed this issue. There was version number mismatch between zookeeper version and curator version. I used curator version 4.0.0 with zookeeper 3.4.6. According to apache curator site
Curator 4.0.0 - compatible with ZooKeeper 3.5.x. I changed my curator version to 2.8.0


text:
Q: mysql query inner join on same table with different conditions I have a table transactions and I trying to figure out our new customers in a given month. That means that if a customer didn't have a transaction in the time before the month he/she counts as a new customer.
I have figured out a way, but it is seriously inefficient and takes ages. I then came across this artikel which compares different methods. I have tried to adjust that approach to mine without success.
To visualise my problem:
|--------------------------- time period with all transactions -----------------------|
|----- period before month transactions = 0) ---|---- curr month transactions > 0 ----|

The table looks like this:
transactions
id, email, state, date_paid

My query:
SELECT
    l.email
FROM
    transactions as l
LEFT JOIN transactions as r ON r.email = l.email
WHERE
    r.email IS NULL
AND l.state = 'paid'
AND r.state = 'paid'
AND l.date_paid <= '2013-12-31 23:59:59'
AND r.date_paid < '2013-12-01 00:00:00'

What am I doing wrong?

A: Try this:
SELECT l.email
FROM transactions AS l
LEFT JOIN transactions AS r ON r.email = l.email AND r.state = 'paid' AND r.date_paid < '2013-12-01 00:00:00'
WHERE r.email IS NULL AND l.state = 'paid' AND l.date_paid <= '2013-12-31 23:59:59'

A: try this:
SELECT l.email
FROM transactions l
WHERE NOT l.email IN (SELECT r.email
                      FROM transactions r
                      WHERE r.state = 'paid' AND r.date_paid < '2013-12-01 00:00:00')
      AND l.state = 'paid' AND l.date_paid <= '2013-12-31 23:59:59'


text:
Q: In Chrome, SVG elements constructed too far off-screen do not render when brought into view I am creating a web-site that drives content for a large 2D area off a CMS, so I have a system that runs on a timer, examines the part of the area that is currently on-screen, and loads content that is close enough to the view area that it might soon come into view.
This all seems to work quite nicely, apart from one small glitch.
Some of my content is SVG elements created procedurally via JS (the load mechanism feeds data from the CMS into JS functions, which create the using document.createElementNS and insert it into a div in the correct absolute position).
This content appears fine if is on-screen at the time it is loaded (this happens when the page is initially loaded).
And it also appears if it loaded while an animation is moving the visible area (animation is used to follow paths across the 2D space).
HOWEVER, if I am manually moving the visible area (which I have implemented via click+drag) then the SVG elements are added to the document tree, but when they come into view they do not render.
If I do something to "nudge" the renderer, such as hiding an unrelated element via DevTools, or resizing the window slightly, then they appear.
I am thinking this may be a bug in Chrome?  e.g. where it has initially decided the elements need not be drawn and does not reprocess correctly when that needs reconsideration?  Or maybe I am missing something, I am only semi-experienced in manipulating HTML documents via JS (but after a quick look I do not see the same behaviour in firefox...)
I am moving the visible area by changing the (left, top) of a parent element (I do not want to use scrolling for that as the size of the 2D space is not defined in advance...)
Otherwise, is there some way I could trick the browser into recalculating what should be drawn?  I was wondering about having a small transparent element on screen that I show and hide on a timer, although a workaround that prevents the problem in the first place would be preferable...
Thanks for any advice!
Ian
p.s. I cannot instantly produce demo code for this as the code-base is moderately large, but I will spend time to make a simpler example if that proves necessary...


text:
Q: How to convert an integer array into string in javascript without losing the square bracket I want to access object property. i m not able to access key value without single quotes around the array. when i put single quotes manually it returns value. but how to get single quotes placed automatically. is there any function in java script. if i convert to string using String() function i lose the square bracket. Here is my code:
var seen = {'[7, 6]': '[0, 0]'}
function getParent(childState){
        //"""return parent of state, if it exists"""
        if(childState in seen){ return seen[childState]; }
        else{ return undefined; }
};
getParent([7, 6]);

A: In order to use a property accessor, you need to provide a string. That means that the keys in your seen object need to be in a string format. If you want to interact with getParent() using arrays, then you should translate the parameter into a string first. But the values in your seen object can still be arrays.
var seen = {'7,6': [0, 0]}
function getParent(childState){
    var key = childState.toString();
    return seen[key];
};
getParent([7, 6]);

A: You can detect if you are beign passed an array and manually build the string key
if(typeof childState =="object"){
   childstate = "[" + childState.toString() + "]";
}


text:
Q: Webflow 1 to Webflow 2 Migration - WARNING: the bean attribute is no longer supported I've inherited an application that is currently using Webflow 1.0.6 and am attempting to upgrade this to Webflow 2.3.4 as an interim step before upgrading to a later version.
I've run one of the flows through the WebFlowUpgrader and it has produced the below output:
list-asset-flow.xml
<?xml version="1.0" encoding="UTF-8"?>
<webflow:flow xmlns:webflow="http://www.springframework.org/schema/webflow" xmlns:ns0="http://www.w3.org/2001/XMLSchema-instance" ns0:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd" start-state="uc1000_SearchAndListStructure">
<webflow:var name="ControllerHelper">
<!-- WARNING: the bean attribute is no longer supported --></webflow:var>
<webflow:var name="ListStructureDataController">
<!-- WARNING: the bean attribute is no longer supported --></webflow:var>
<webflow:var name="ViewElementDetailController">
<!-- WARNING: the bean attribute is no longer supported --></webflow:var>
<webflow:on-start>
        <webflow:evaluate expression="flowScope.ListStructureDataController.init()"/>
<!-- <set attribute="ControllerHelper" value="flowScope.ListStructureDataController.controllerHelper" scope="flow" /> --><webflow:set name="flowScope.ListStructureDataController.controllerHelper" value="flowScope.ControllerHelper"/>
        <webflow:set name="flowScope.ViewElementDetailController.controllerHelper" value="flowScope.ControllerHelper"/>
    </webflow:on-start>
<webflow:view-state id="uc1000_SearchAndListStructure" view="/uc1000_SearchAndListStructure.jsp">
        <webflow:on-entry>
            <webflow:evaluate expression="flowScope.ListStructureDataController.display()"/>
        </webflow:on-entry>
        <webflow:transition on="failure" to="uc1000_SearchAndListStructure"/>
        <webflow:transition on="success" to="uc1000_SearchAndListStructure"/>
        <webflow:transition on="reset" to="uc1000_SearchAndListStructure"/>
        <webflow:transition on="close" to="uc1000_SearchAndListStructure"/>
        <webflow:transition on="uc1025" to="maintain-asset-flow"/>
        <webflow:transition on="uc3003" to="maintain-asset-flow"/>
        <webflow:transition on="uc3003a" to="maintain-asset-flow"/>
        <webflow:transition on="back" to="uc1000_SearchAndListStructure"/>
    </webflow:view-state>
<webflow:subflow-state id="maintain-asset-flow" subflow="maintain-asset-flow">
        <webflow:input name="ControllerHelper" value="flowScope.ControllerHelper"/>
        <webflow:input name="ViewElementDetailController" value="flowScope.ViewElementDetailController"/>
        <webflow:transition to="uc1000_SearchAndListStructure">
            <webflow:evaluate expression="flowScope.ListStructureDataController.searchSubmitt()"/>
        </webflow:transition>
    </webflow:subflow-state>
<webflow:bean-import resource="helper-beans.xml"/>
<webflow:bean-import resource="list-asset-beans.xml"/>
</webflow:flow>

list-asset-beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
        "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <!-- For UC1000 Search and list Structures Screen -->
    <bean id="ListStructureDataController" class="uk.co.organisation.application.presentation.controllers.ListStructureDataController" singleton="false">
        <!-- <property name="controllerHelper" ref="ControllerHelper" /> -->
        <property name="civilsReferenceDataProcessProxy" ref="CivilsReferenceDataProcessProxy" />
        <property name="monitorConditionProcessProxy" ref="MonitorConditionProcessProxy" />
    </bean>

    <!-- For UC1025 View structure group Screen -->
    <bean id="ViewElementDetailController" class="uk.co.organisation.application.presentation.controllers.ViewElementDetailController" singleton="false">
        <!-- <property name="controllerHelper" ref="ControllerHelper" /> -->
        <property name="civilsAssetProcessProxy" ref="CivilsAssetProcessProxy" />
        <property name="civilsReferenceDataProcessProxy" ref="CivilsReferenceDataProcessProxy" />
    </bean>

   <!-- For UC3003 Maintain structure group Screen -->
    <bean id="MaintainElementDetailController" class="uk.co.organisation.application.presentation.controllers.MaintainElementDetailController" singleton="false">
        <!-- <property name="controllerHelper" ref="ControllerHelper" /> -->
    </bean>

</beans>

I'm unsure how to resolve the warning WARNING: the bean attribute is no longer supported
Prior to the running through the WebFlowUpgrade upgrade the variables were declared as:
    <var name="ControllerHelper" bean="ControllerHelper" scope="flow" />
    <var name="ListStructureDataController" bean="ListStructureDataController" scope="flow" />
    <var name="ViewElementDetailController" bean="ViewElementDetailController" scope="flow" />

A: Try using class:
<webflow:var name="ControllerHelper" class="com.example.ControllerHelper">


text:
Q: extract the date from the file name I have this code :
import sys
import os
import re
import fnmatch
import csv
import pandas as pd
import numpy as np
from dateutil.parser import parse as parseDate
from datetime import datetime, time, timedelta

file = open("0556_16-09-20114725356354 --- 16-12-2016 07-00-00.csv", 'r')
filename = os.path.splitext(os.path.basename(file))[0]
timestamp = filename[-19:]
print timestamp
date = timestamp[:10] + " " + timestamp[-8:].replace("-",":")
print date
newdatefile = parseDate(date, yearfirst=True)
print newdatefile

My objective is to extract the date from the file name and parse it and save it in a variable. What I want to get is something like this : 16-12-2016 07-00-00
This is the error I get :
Traceback (most recent call last):
  File "t.py", line 13, in <module>
    filename = os.path.splitext(os.path.basename(file))[0]
  File "/usr/lib/python2.7/posixpath.py", line 114, in basename
    i = p.rfind('/') + 1
AttributeError: 'file' object has no attribute 'rfind'

Any ideas about what could that be ?

A: os.path.basename(file) you're passing a file object here, while it expects a string

A: You don't need to have os.path do it for you. Why not simply take the filename directly from the parameter you're passing to open:
filename = "0556_16-09-20114725356354 --- 16-12-2016 07-00-00.csv"
file = open(filename, 'r')


text:
Q: Factorization of $ax^2 +bx+c$ Assume {$a, b, c$} is coprime. I know $ax^2+bx+c$ can always be factorised as $a(x-\alpha)(x-\beta)$ with the quadratic formula where $\alpha$ and $\beta$ can be integers, rational, irrational, or imaginary.
Based on experience, I think I can claim that with a proper choice of integers $a_1$ and $a_2$ where $a_1a_2=a$, we have $ax^2+bx+c=(a_1x+h)(a_2x+k)$ with $h, k$ being both integers, irrational, or imaginary. But I cannot prove it rigorously that it is not possible for one of the $h$ and $k$ being integer while the other one being a fraction no matter how we choose $a_1$ and $a_2$.
Having been trying to play with the algebra and lots of numerical experience, I still could not figure out a rigorously proof for it. I feel like it is number theory stuff which I am not good at.


text:
Q: Validation for multi-step form I am trying to make a multi-step form using that checks if the first two input fields are valid before moving on the the next step. The code below validates the two fields, but continues to the next step regardless if the forms are valid or not. I suspect the problem lies in the fact the onClick hook is changing the state without any checks. I do not know how to check if the fields are valid or not, before changing the state. I am using yup for validation alongside mantine for a component library.
const schema = yup.object().shape({
  email: yup.string().email('Email is invalid.').required(),
  password: yup.string().required(),
});

function Example() {
  const [activeStep, setActiveStep] = useState(0);
  const form = useForm({
    schema: yupResolver(schema),
    initialValues: {
      email: "",
      password: "",
      firstName: "",
      lastName: ""
    }
  });

  return (
    <form
      onSubmit={form.onSubmit((values) => {
        console.log(values);
      })}
    >
      <Paper shadow="xs" p="md">
        {activeStep === 0 && (
          <>
            <Title>Info</Title>
            <Group>
              <TextInput
                label="Email"
                {...form.getInputProps("email")}
              />
              <TextInput
                label="Password"
                {...form.getInputProps("password")}
              />
            </Group>
          </>
        )}

        {activeStep === 1 && (
          <>
            {" "}
            <Title>Personal</Title>
            <Group>
              <TextInput
                label="First name"
                {...form.getInputProps("firstName")}
              />
              <TextInput
                label="Last names"
                {...form.getInputProps("lastName")}
              />
            </Group>
          </>
        )}

        <Group mt="xl">
          <Button
            onClick={() => setActiveStep((prev) => prev - 1)}
            disabled={activeStep === 0}
          >
            Previous
          </Button>
          <Button
            onClick={() => setActiveStep((prev) => prev + 1)}
            type="submit"
            disabled={activeStep === 1}
          >
            Next
          </Button>
        </Group>
      </Paper>
    </form>
  );
}


text:
Q: What are the most commonly used runtime exceptions in java? As a java programmer who wishes to perfect his programming skills, I often come across the situations that I have to create a runtime exception. I know it's a good practice if one use wisely.
Personally, NullPointerException and IllegalStateException are the most commonly used in the softwares that I have created. How about you?
What runtime exceptions do you often use? In what situations do you use them?

A: I never throw NullPointerException. For me, it is one that appears naturally in the code when something goes wrong and that requires a developer to look at what happens. Then (s)he fixes the cause and it doesn't happen again.
I use IllegalStateException to signal that an object is incorrectly configured or that calls are in an incorrect order. However, we all know that ideally, an object should ensure it can't be in a bad state and that you can't call it in incorrect order (make a builder and a resulting object ...).
I use a lot of IllegalArgumentException when a method detects that its parameters are incorrect. This is the responsibility of any public method, to stop processing (to avoid indirect errors that are more difficult to understand). Also, a few ifs in the beginning of a method serve a documentation purpose (documentation that never diverge from the code because it is the code :-) ).
     public void myMethod(String message, Long id) {
       if (message == null) {
          throw new IllegalArgumentException("myMethod's message can't be null");
          // The message doesn't log the argument because we know its value, it is null.
       }
       if (id == null) {
          throw new IllegalArgumentException("myMethod's id can't be null");
          // This case is separated from the previous one for two reasons :
          // 1. to output a precise message
          // 2. to document clearly in the code the requirements
       }
       if (message.length()<12) {
          throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'");
          // here, we need to output the message itself,
          // because it is a useful debug information.
       }
     }

I also use specific Runtime Exceptions to signal higher level exceptional conditions.

For example, if a module of my application couldn't start, I might have a ModuleNotOperationalException thrown (ideally by a generic code like an interceptor, otherwise by a specific code) when another module calls it. After that architectural decision, each module has to deal with this exception on operations that call other modules...

A: I use IllegalArgumentException relatively often. Most of the time, I will try to return the default value as soon as it is logical but some of the time it was not, and so I use this one.
Another one I use is ArrayIndexOutOfBoundsException.

A: UnknownException, very usefull :P
i also like org.apache.commons.lang.NotImplementedException

A: According to Joshua Bloch in Effective Java,
The most commonly reused exceptions:

*

*IllegalArgumentException

*IllegalStateException

*NullPointerException

*IndexOutOfBoundsException

*ConcurrentModificationException

*UnsupportedOperationException

A: Mostly I don't throw runtime exception. Rather than after checking specific conditions throw user defined exceptions. But the few I have used are -
IllegalAccessException ,  ArithmeticException, NumberFormatException and SecurityException.

A: I've always considered that runtime exceptions should represent programming errors (e.g. null reference passed in when not expected, array index out of bounds, etc.) while checked exceptions should represent exceptional conditions in the environment that cannot be "coded away" (e.g. IOException, SQLException).
One violation of this is that sometimes you'll need to wrap what ought to be a checked exception in a RuntimeException, in order to satisfy the definition of an interface.  As a brief example, you might have some snazzy implementation of java.util.List that manages a distributed list between multiple machines.  Clearly this would throw checked exceptions (probably some subclass of IOException) if defined on its own, but the benefits of making this class implement List is that clients can use it almost transparently, anywhere they use another list.
This can lead to what Joel terms a leaky abstraction, though, so it's important that your documentation is clear what exceptions can be thrown and what they mean!  In this case I find a custom subclass of RuntimeException to generally be clearer at communicating the root cause rather than trying to shoehorn it into an existing runtime exception class.


text:
Q: Sorting a list by a referenced field react-admin I started using react-admin and is basically works fine. However I have some trouble using the ReferenceField.
The REST API I'm calling returns e.g. the following JSON data:
/language
{
  "language": [
    {
      "id": 0,
      "name": "Language #0"
    },
    {
      "id": 1,
      "name": "Language #1"
    },
    {
      "id": 2,
      "name": "Language #2"
    },
    {
      "id": 3,
      "name": "Language #3"
    }
  ]
}

/myreferences
{
  "myreferences": [
    {
      "id": 0,
      "langauge": {
        "id": 0,
        "name": "Language #0"
      },
      "name": "My reference #0"
    },
    {
      "id": 1,
      "langauge": {
        "id": 1,
        "name": "Language #1"
      },
      "name": "My reference #1"
    },
    {
      "id": 2,
      "langauge": {
        "id": 2,
        "name": "Language #2"
      },
      "name": "My reference #2"
    }
  ]
}

And that's how map this in react-admin.
export const LanguageList = props => (
  <List
    title="Languages"
    sort={{ field: "name", order: "ASC" }}
    filters={<LanguageFilter/>}
    {...props}
  >
    <Datagrid>
      <NumberField source="id" label="ID" />
      <TextField source="name" label="Name" />
      <EditButton />
    </Datagrid>
  </List>
);

export const MyReferenceList = props => (
  <List
    title="My References"
    sort={{ field: "name", order: "ASC" }}
    filters={<MyReferenceFilter />}
    {...props}
  >
    <Datagrid>
      <NumberField source="id" label="ID" />
      <TextField source="name" label="Name" />
      <ReferenceField source="langauge.id" reference="language" label="Language">
        <TextField source="name" />
      </ReferenceField>
      <EditButton />
    </Datagrid>
  </List>
);

My problem is that the references are shown correctly but when I click on the column for the referenced language name react-admin sorts by the language's ID instead of its name.
What do I need to adapt so that sorting by name is working?

A: The <ReferenceField> component accepts a sortBy prop, which specifies the field to use for sorting instead of the source. So in your case, you can write:
      <ReferenceField source="language.id" sortBy="language.name" reference="language" label="Language">
        <TextField source="name" />
      </ReferenceField>

This is explained in the React-admin documentation:
https://marmelab.com/react-admin/Fields.html#referencefield


text:
Q: How to start a new console and run a command in it programmatically? I'm running tons of experiments and I'm tired of manually opening a terminal and typing:
!tensorboard --logdir="C:\Users\OneDrive \Pycharm\DANN MNISTM SVHN\tmp\1561358957553" --host localhost --port 9353

to start TensorBoard. I want to do this programmatically.
I want to do this in Pycharm, or even Jupyter. But, I want this to be done in a new notebook / terminal in case of Jupyter, not the one I'm currently running cause this will hog the terminal and prevents me from doing extra processing. Same thing in case of Pycharm, I want the command above to be run in a new IPython console / terminal. Is there a Python/IPython way to do that?
Here is what I tried:
import os
os.startafile('cmd')

But I don't know how to write commands to that newly created window without going to it manually.
I also tried subprocess Popen, but it didn't work, in particular, I created a baby process using Popen but when I call communicate method and send a command it waits for a response! I don't want to wait, there is no any response. I just want to move on to next command.

A: I solved it, but I'm not satisifed.
I used os.popen('the command'). It is working fine, but, it keeps sending back updates to my interactive consonle, this clutters it with useless wiritings, tons of them.


text:
Q: In TypeScript, what does it mean for an import or export to be "top-level"? The TypeScript docs say:

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

What does it mean for an import or export to be "top-level"?

A: Top level import is the static import which is located at the very top of the file. Accent on static, it's called "top-level" not because it is located at the top of the file, but because there are dynamic imports that are not top level:
import foo from 'foo' // top level import, static one

import('foo').then(/* ... */) // not top level import, dynamic one

// no static top-level import can live here (after any code that is not a top-level import declaration)

function bar() {
  import('foo').then(/* ... */) // not top level import, dynamic one
  // no static top-level import can live here
  // no export can live here too
}

// no static top-level import can live here

export const baz = 123 // exports are always top level, and static

// You still can add not top level imports here, in the very end
import('foo').then(/* ... */)

Now, why this matters in Typescript?
Well if you put two files without a top-level import/export, that has two identifiers that are the same, you will get an error:
// a.ts
let foo = 1 // Error: duplicate identifier

// b.ts
let foo = 1 // Error: duplicate identifier

This happens because there are no top-level export/import declarations and TS considers these files to be scripts (in contrast to modules). And what happens if you load in a browser two scripts with same identifiers? Right, a "duplicate identifier" error will rise. Because both variables live in the global namespace.
Therefore, to avoid that you can do this:
// a.ts
let foo = 1 // Ok

// b.ts
let foo = 1 // Ok
export {} // This is the magic. b.ts is now a module and hence, is not polluting the global namespace.

A:
The top-level in typescript is the outer most scope.

What is a "scope"?
You create a scope every time you open a set of { braces¹.
Scope limits the visibility of variables and functions to the scope they are defined in and child scopes.
For example:
import { something } from "<module>"; <-- Global / Top-level scope

function divide(x, y) { <-- Start function scope
  if(y == 0) { <-- Start of the if's scope
    /*
     * Here is a child scope of the function
     * This means x and y are available here.
     */

    var error = new Error("Cannot divide by 0); <-- "error" is only available here.
    throw error;
  } <-- End of the if's scope

  /*
   * The "error" variable is not available here
   * since the scope it was defined in, was already closed.
   */

  return x / y;
} <-- Ends the functions scope

var z = 0; <-- Global scope

This means:
import { x } from "<module>"
/* rest of code */

works but for example:
if (true) {
  import { x } from "<module>";
}

does not work, since the import is wrapped in the scope of the if statement and therefore is not at the top-level scope anymore.
But this does not mean the "top-level" is at the top of the file. It just means the outer most scope.
function add(a, b) {
  return a + b;
}

import { x } from "<module>";

This still works, since the scope of the function ends with the closing } brace¹. Meaning everything after it is at the top-level again.
Everything said about import's also applies to export's

1: Sometimes you can omit the {|} braces to create a new scope. You still create a new scope, but do so implicitly.
For example, consider the two snippets below - They are the same. Languages create scope lexically - scope is not defined by tokens

if(true)
  return true;
else
  return false;

is the same as
if(true) {
  return true;
} else {
  return false;
}


text:
Q: Linking Main menu to the onscreen option button in my android application Hello Guys i am facing a problem in my Android application.
I made an android application and then tested it on LG optimus 2x with ICS android version
but when i am testing it on SONY xperia C it is giving me some problems
The first and the most important problem is that i had made an menu in my application which used to open by pressing option hardware key on my Lg optimus 2x but in sony Xperia C with JB android OS that hardware key is all ready attributed to some other function and does not open my options menu
Now what i want to do is that i want to make an on screen options button which i will then use to call in the menu.
i have already made a button but i dont know how to link my button to call in the menu in my application
below is the code from my layout.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
     >
<TextView
    android:id="@+id/colortxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Result will be displayed here.."
    android:textColor="#000000"
    android:textSize="12sp"
    />
    </LinearLayout>

<Button
    android:id="@+id/Button"
    android:textColorLink="#3334"
    android:shadowColor="#4445"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="Buttonbtn1"
    android:text="Options"
    />

 <org.opencv.android.JavaCameraView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/color_blob_detection_activity_surface_view" />

this is the code from my .java file
    package imtech.aglab;

import java.util.List;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import com.InjQuant.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.style.SuperscriptSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;

public class MainActivity<Button> extends Activity implements OnTouchListener, CvCameraViewListener2 {
    private static final String  TAG = "OCVSample::Activity";

    private boolean              mIsColorSelected = false;
    private Mat                  mRgba;
    private Scalar               mBlobColorRgba;
    private Scalar               mBlobColorHsv;
    private BlobDetector          mDetector;
    private Mat                  mSpectrum;
    private Size                 SPECTRUM_SIZE;
    private Scalar               CONTOUR_COLOR;
    TextView tf;

    private CameraBridgeViewBase mOpenCvCameraView;

    private BaseLoaderCallback  mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                    mOpenCvCameraView.setOnTouchListener(MainActivity.this);
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
    private Object[] data;

    public MainActivity() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_main);

        mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.color_blob_detection_activity_surface_view);
        mOpenCvCameraView.setCvCameraViewListener(this);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
    }

    public void onDestroy() {
        super.onDestroy();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    public void onCameraViewStarted(int width, int height) {
        mRgba = new Mat(height, width, CvType.CV_8UC4);
        mDetector = new BlobDetector();
        mSpectrum = new Mat();
        mBlobColorRgba = new Scalar(255);
        mBlobColorHsv = new Scalar(255);
        SPECTRUM_SIZE = new Size(200, 64);
        CONTOUR_COLOR = new Scalar(255,0,0,255);
    }

    public void onCameraViewStopped() {
        mRgba.release();
    }

    public boolean onTouch(View v, MotionEvent event) {

        tf=(TextView)findViewById(R.id.colortxt);
        int cols = mRgba.cols();
        int rows = mRgba.rows();

        int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
        int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;

        int x = (int)event.getX() - xOffset;
        int y = (int)event.getY() - yOffset;

        Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");
        tf.setText("Touch image coordinates: (" + x + ", " + y + ")");

        if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;

        Rect touchedRect = new Rect();

        touchedRect.x = (x>4) ? x-4 : 0;
        touchedRect.y = (y>4) ? y-4 : 0;

        touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
        touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;

        Mat touchedRegionRgba = mRgba.submat(touchedRect);

        Mat touchedRegionHsv = new Mat();
        Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);

        // Calculate average color of touched region
        mBlobColorHsv = Core.sumElems(touchedRegionHsv);
        int pointCount = touchedRect.width*touchedRect.height;
        for (int i = 0; i < mBlobColorHsv.val.length; i++)
            mBlobColorHsv.val[i] /= pointCount;

        mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);

        Log.i("Color Check" + TAG , "Touched hsv color: (" + mBlobColorHsv.val[0] + ", " + mBlobColorHsv.val[1] +
                ", " + mBlobColorHsv.val[2] + ")");
     tf.setText(tf.getText()+ "\n" + "Touched hsv color: (" + mBlobColorHsv.val[0] + ", " + mBlobColorHsv.val[1] +
                ", " + mBlobColorHsv.val[2] + ")");

        Log.i("Color Check" + TAG , "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
                ", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");
      tf.setText(tf.getText() + "\n" +"Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
              ", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");
        mDetector.setHsvColor(mBlobColorHsv);

        Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);

        mIsColorSelected = true;

        touchedRegionRgba.release();
        touchedRegionHsv.release();

        return false; // don't need subsequent touch events
    }

    public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
        mRgba = inputFrame.rgba();

        if (mIsColorSelected) {
            mDetector.process(mRgba);
            List<MatOfPoint> contours = mDetector.getContours();
            Log.e(TAG, "Contours count: " + contours.size());
          ;
            Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);

            Mat colorLabel = mRgba.submat(4, 68, 4, 68);
            colorLabel.setTo(mBlobColorRgba);

            Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
            mSpectrum.copyTo(spectrumLabel);
        }

        return mRgba;
    }

    private Scalar converScalarHsv2Rgba(Scalar hsvColor) {
        Mat pointMatRgba = new Mat();
        Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
        Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);

        return new Scalar(pointMatRgba.get(0, 0));
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        //respond to menu item selection

        int itemId = item.getItemId();

        if (itemId == R.id.aboutapp) {
            // Toast.makeText(getBaseContext(), "Color Blob Detection Application.", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Aboutapp.class));
            return true;

        } else if (itemId == R.id.developers) {
            //          Toast.makeText(getBaseContext(), "IMTECH Lab.", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, developers.class));
            return true;

        } else if (itemId == R.id.credits) {
            //          Toast.makeText(getBaseContext(), "IMTECH Lab.", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, cridits.class));
            return true;

        } else if (itemId == R.id.save) {
            Toast.makeText(getBaseContext(), "Save Results in the Database.", Toast.LENGTH_SHORT).show();
            //          startActivity(new Intent(this, Save.class));
            return true;

        } else if (itemId == R.id.help) {
            // Toast.makeText(getBaseContext(), "How to use this application?", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, help.class));
            return true;

        } else if (itemId == R.id.action_settings) {
            Toast.makeText(getBaseContext(), "Settings", Toast.LENGTH_SHORT).show();
            //          startActivity(new Intent(this, Setting.class));
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }

}
     public class MyActivity extends Activity {
         private View Buttonbtn1;

        protected void onCreate (Bundle icicle) {
             super.onCreate(icicle);
             setContentView(R.layout.activity_main);
             final Button button = (Button) findViewById (R.id.Button);
             Buttonbtn1.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View view) {
                     // put the method hear about what the button should do
             }
         });
     }

    public void onBackPressed()
    {
        AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
        b.setTitle("Exit");
        b.setMessage("Do you want to exit?");
        b.setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                MainActivity.this.finish();
            }
        });

        b.setNeutralButton("No",null);
        b.show();

        //super.onBackPressed();

    }
     }
}

and the second problem is that my application call in the camera function but when it open the camera in SONY xperia C it does not use the full screen for the camera but uses only small portion of it as expected this application used the full screen camera when i run it on the old Lg optimus 2x

Guys please help me in knowing where and what code to put so that i
  achieve the desired results..