问:
how to get the input value of dynamically generated textboxes?
I have a button to add textarea, but how to retrieve values from the text areas.
I have tried using

```<code>document.getElementById('newutterances').value;
</code>```

but its not working.

Please help, as I am new to JavaScript.

    <input type="button" value="Add Text Area" onClick="addTextArea();">
    <button type="button" onClick="getValue()">Get Value</button>

    ```

答:
Add some class for fields and use document.getElementsByClass();

```<code><script type="text/javascript">
    var count = 0;
    function addTextArea() {
        count++;
        var objNewDiv = document.createElement('div');
        objNewDiv.innerHTML = 'Textbox ' + count + ': <input type="text" class="field" name="tb_"/>';
        document.getElementById('newutterance').appendChild(objNewDiv);
    }
    function getValue() {
        var fields = document.getElementsByClassName('field');
        var values = [];
        for (var i = 0; i < fields.length; i++) {
            values.push(fields[i].value);
        }
        return values;
    }
</script>
</code>```

Body:
I have a button to add textarea, but how to retrieve values from the text areas.
I have tried using

document.getElementById('newutterances').value;

but its not working.

Please help, as I am new to JavaScript.

    <input type="button" value="Add Text Area" onClick="addTextArea();">
    <button type="button" onClick="getValue()">Get Value</button>

Body:
Add some class for fields and use document.getElementsByClass();

<script type="text/javascript">
    var count = 0;
    function addTextArea() {
        count++;
        var objNewDiv = document.createElement('div');
        objNewDiv.innerHTML = 'Textbox ' + count + ': <input type="text" class="field" name="tb_"/>';
        document.getElementById('newutterance').appendChild(objNewDiv);
    }
    function getValue() {
        var fields = document.getElementsByClassName('field');
        var values = [];
        for (var i = 0; i < fields.length; i++) {
            values.push(fields[i].value);
        }
        return values;
    }
</script>


来源: stackexchange

问:
Angular2 tree checkbox with EventEmitter
I have problems with tree view which has checkboxes on children. So, the problem is that I get nested stuff from event emitter. Please see screenshot and code.

This is my custom component where I have recursion and I just want to pass selected child or parent.

Component

```<code>import { Component, Input, EventEmitter, Output } from '@angular/core';

@Component ({
    selector: 'category-tree-view',
    template: `
    <ul class="tree">
        <li *ngFor="let category of treeData">
            <label class="control control--checkbox" *ngIf="hasCheckbox">
                <input type="checkbox" [checked]="category.checked" (change)="selectedCategory(category, $event)" />
                <div class="control__indicator"></div>
            </label>
            <span *ngIf="category.subcategories?.length" (click)="toggleChildren(category)" class="toggle">+</span>
            {{category.name}}
            <div class="tree-actions" *ngIf="hasActions">
                <button class="btn btn-link edit" (click)="editCategory(category)">
                  <i class="icon-admin-edit"></i>
                </button>
                <button class="btn btn-link delete" (click)="deleteCategory(category)">
                  <i class="icon-admin-close"></i>
                </button>
            </div>
            <category-tree-view [treeData]="category.subcategories" *ngIf="category.visible" (edit)="editCategory($event)" (delete)="deleteCategory($event)" [hasCheckbox]="hasCheckbox" (selected)="selectedCategory($event)" [hasActions]="hasActions"></category-tree-view>
        </li>
    </ul>
    `
})
export class ProductCategoryTreeView {
    @Input() treeData: any[];
    @Input() hasCheckbox: boolean = false;
    @Input() hasActions: boolean = false;
    @Output() edit = new EventEmitter();
    @Output() delete = new EventEmitter();
    @Output() selected = new EventEmitter();

    constructor() {}

    toggleChildren(node: any) {
        node.visible = !node.visible;
    }

    editCategory(category){
        this.edit.emit(category);
    }

    deleteCategory(category) {
        this.delete.emit(category);
    }

    selectedCategory(category, event) {
        this.selected.emit({category, event});
    }
}
</code>```

This is what I have in my other html page, which is the different component, in this case, product-form.component.html

```<code><category-tree-view [treeData]="categories" (edit)="editCategory($event)" (delete)="deleteCategory($event)" (selected)="selectCategory($event)" [hasCheckbox]="true"></category-tree-view>
</code>```

And also I just have method in component product-form.component.ts

```<code>selectCategory(cat, event) {
    console.log(cat, event);
}
</code>```

Here's the screenshot what I got when I console log that data.

答:
Can you please try with below code and check if it works or not?</p>

```<code>selectedCategory(category, event) {
    this.selected.emit(event);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have problems with tree view which has checkboxes on children. So, the problem is that I get nested stuff from event emitter. Please see screenshot and code.

This is my custom component where I have recursion and I just want to pass selected child or parent.

Component

import { Component, Input, EventEmitter, Output } from '@angular/core';

@Component ({
    selector: 'category-tree-view',
    template: `

                <input type="checkbox" [checked]="category.checked" (change)="selectedCategory(category, $event)" />

            +
            {{category.name}}

                <button class="btn btn-link edit" (click)="editCategory(category)">

                </button>
                <button class="btn btn-link delete" (click)="deleteCategory(category)">

                </button>

            <category-tree-view [treeData]="category.subcategories" *ngIf="category.visible" (edit)="editCategory($event)" (delete)="deleteCategory($event)" [hasCheckbox]="hasCheckbox" (selected)="selectedCategory($event)" [hasActions]="hasActions"></category-tree-view>

    `
})
export class ProductCategoryTreeView {
    @Input() treeData: any[];
    @Input() hasCheckbox: boolean = false;
    @Input() hasActions: boolean = false;
    @Output() edit = new EventEmitter();
    @Output() delete = new EventEmitter();
    @Output() selected = new EventEmitter();

    constructor() {}

    toggleChildren(node: any) {
        node.visible = !node.visible;
    }

    editCategory(category){
        this.edit.emit(category);
    }

    deleteCategory(category) {
        this.delete.emit(category);
    }

    selectedCategory(category, event) {
        this.selected.emit({category, event});
    }
}

This is what I have in my other html page, which is the different component, in this case, product-form.component.html

<category-tree-view [treeData]="categories" (edit)="editCategory($event)" (delete)="deleteCategory($event)" (selected)="selectCategory($event)" [hasCheckbox]="true"></category-tree-view>

And also I just have method in component product-form.component.ts

selectCategory(cat, event) {
    console.log(cat, event);
}

Here's the screenshot what I got when I console log that data.

Body:
Can you please try with below code and check if it works or not?

selectedCategory(category, event) {
    this.selected.emit(event);
}


问:
How to use dropdown and textbox field for one parameter in same report on SSRS
I want to use two options.

1- If users want to use dropdown list for order they should use dropdown list parameter and textbox must be invalid or textbox must be set in dropdown value.

2 - Or if users want to type with keyboard manuelly for order, dropdown list must be invalid or dropdown must be show just type in textbox value. I added screenshot.

Do you have some suggestions? How can I do like this? My customers want to use dropdown list and type in manuelly in textbox for same parameter(@order parameter) on one report.

Thanks.

答:
As far as I am aware it is not possible to disable one parameter input control or another. Parameters are 1 directional. You can have one based on the results of another but only in one direction. However, you should be able to produce something close enough to be satisfactory.

Here's a step by step report, based on the NorthWind database. You should be able to modify this to suit your database. If you want to copy this example exactly you'll first need to download and restore the NorthWind sample database if you don't already have it. You can find the database here.
NorthWind database download on Codeplex

You can see the report design here, I'll explain each step.

Create a new, blank report

Create a datasource in your report and point it to the NorthWind database

Create a dataset called Order. This will be the final query containing the data that you want in the main body of the report. The query for this data set is.

SELECT * FROM [Order Details Extended]
WHERE OrderID = @ReportOrderID

Create another dataset called OrdersInDateRange. This will be the list of orders that you will see in your drop down list. It filters the available orders to only those that appear with a date range. Note It also contains a null entry so our final parameter can be edited without choosing anything from the list. The query looks like this.

SELECT NULL AS OrderID
UNION ALL
SELECT DISTINCT OrderID
  FROM Orders
  WHERE OrderDate BETWEEN @StartDate AND @EndDate
  ORDER BY OrderID

This gets a list of all order IDs within a date range plus a NULL order id.

Create two new Parameters StartDate and EndDate and set them to be date time parameters.

You should now have 4 parameters, StartDate, EndDate, OrderID and ReportOrderID.

Edit the OrderID parameter, check the "Allow Null Value" option. Then set "Available Values" to a query and choose OrdersInDateRange as the dataset, choose OrderID as the Value and Label. Add a Default value of (Null). You need to set the default value as the final parameter (ReportOrderID) will not be enabled unless a value is selected in this parameter.

Edit the ReportOrderID parameter. Leave available values as none. For Default Values, choose "Specify Values" add a value, click the [fx] button and set the value to

=Parameters!OrderID.Value

This will set this parameter to the value choosen in the drop down so the user can pick from a list but allows the user to type in an order ID manually too.

The report uses the ReportOrderID parameter to fetch data, the drop down list only exists as a helper.

Add a table and design your report layout

That's it.

Here's the finished report choosing from the list.

Here it again with nothing chosen in the list (the default value NULL is shown)

ContentLicense: CC BY-SA 4.0


问:
How to handle click events in html(Html which is appended/replaced from another ajax call's data)
```<code>    $('.a').on('click', function() {
        $.ajax({
            url: "url",
            type:'POST',
            dataType: 'json',
            data: {'user':user},
            showLoader: true,
            success: function(response){
             ******Appending content from response*****
            }
        });
    });
</code>```

After this, If I click on a button which is from that appended content it is not triggering the click event.
I tried adding .trigger("click"), didn't help though.

Thanks in advance

答:
Your appended button does not exist at the time of your on click binding, so no event is bound to these elements.

Try using the on function with a selector instead

```<code>$(document).on('click', '.a', function() {
    // DO STUFF
});
</code>```

This binds the click event to all elements with the .a class, regardless if they exists at the time of binding or not.

http://api.jquery.com/on/

Body:
    $('.a').on('click', function() {
        $.ajax({
            url: "url",
            type:'POST',
            dataType: 'json',
            data: {'user':user},
            showLoader: true,
            success: function(response){
             ******Appending content from response*****
            }
        });
    });

After this, If I click on a button which is from that appended content it is not triggering the click event.
I tried adding .trigger("click"), didn't help though.

Thanks in advance

Body:
Your appended button does not exist at the time of your on click binding, so no event is bound to these elements.

Try using the on function with a selector instead

$(document).on('click', '.a', function() {
    // DO STUFF
});

This binds the click event to all elements with the .a class, regardless if they exists at the time of binding or not.

http://api.jquery.com/on/


问:
How to check if dotnet restore was ok in ps1?
I have dockertask.ps1 file with dotnet restore command, the question is how to make sure if it runs without errors???

答:
After executing a programm you can catch the exit code with $?, but only right after execution.

```<code>dotnet restore
ErrNo="$?"
if [ "$ErrNo" -ne 0 ]
then
echo "error code ${ErrNo} received."
fi
</code>```

$? includes the error code of the last execution.

The if command with -ne means Not Equal.

Body:
After executing a programm you can catch the exit code with $?, but only right after execution.

dotnet restore
ErrNo="$?"
if [ "$ErrNo" -ne 0 ]
then
echo "error code ${ErrNo} received."
fi

$? includes the error code of the last execution.

The if command with -ne means Not Equal.


问:
Differentiate between a user changing the Checkbox.Checked value, or it programmatically changing
I see that Checkboxes have a CheckedChanged event. is it possible to tell whether it was changed programmatically, or by the user actually checking the checkbox?

I've got a large grid where the user can type in a filter, or use checkboxes for a sort of "Quick filter" that offers common filtering parameters. Then say they go and modify the filter through the textbox, I was checking whether or not I should programmatically (un)check the CheckBox controls so that it reflects the filter in the textbox.

```<code>    private void genericCheckbox_CheckedChanged(object sender, EventArgs e)
    {
        UpdateFilter();
    }

    private void UpdateFilter()
    {
        if (gdcSVNDefaultView.RowCount == 0)
            return;

        gdcSVNDefaultView.ActiveFilterString = BuildTableFilter();
        gdcSVNDefaultView.BestFitColumns();
    }

    private void gdcSVNDefaultView_ColumnFilterChanged(object sender, EventArgs e)
    {
        lblTotalFileCount.Text = gdcSVNDefaultView.RowCount.ToString();

        if (gdcSVNDefaultView.ActiveFilterString.Contains("Normal"))
            cheNormalFiles.Checked = true;
        else
            cheNormalFiles.Checked = false;

        if (gdcSVNDefaultView.ActiveFilterString.Contains("bin") ||
            gdcSVNDefaultView.ActiveFilterString.Contains("obj"))
            cheBinObjFolders.Checked = true;
        else
            cheBinObjFolders.Checked = false;
    }
</code>```

With some very light testing, this seems to work just as I want it to. But I'm afraid that there's some sort of 'infinite loop' case where the ColumnFilterChanged event will fire because of the UpdateFilter method being called when the CheckedChanged event happens, which could in turn cause CheckedChange to happen again since the ColumnFilterChanged manipulates the Checkboxes.

答: In general you may use the Click event CheckBoxName_Click which is called only when the user click the checkbox (and not when you set the checkbox checked property from code), as the event name suggests.

Body:
I see that Checkboxes have a CheckedChanged event. is it possible to tell whether it was changed programmatically, or by the user actually checking the checkbox?

I've got a large grid where the user can type in a filter, or use checkboxes for a sort of "Quick filter" that offers common filtering parameters. Then say they go and modify the filter through the textbox, I was checking whether or not I should programmatically (un)check the CheckBox controls so that it reflects the filter in the textbox.

    private void genericCheckbox_CheckedChanged(object sender, EventArgs e)
    {
        UpdateFilter();
    }

    private void UpdateFilter()
    {
        if (gdcSVNDefaultView.RowCount == 0)
            return;

        gdcSVNDefaultView.ActiveFilterString = BuildTableFilter();
        gdcSVNDefaultView.BestFitColumns();
    }

    private void gdcSVNDefaultView_ColumnFilterChanged(object sender, EventArgs e)
    {
        lblTotalFileCount.Text = gdcSVNDefaultView.RowCount.ToString();

        if (gdcSVNDefaultView.ActiveFilterString.Contains("Normal"))
            cheNormalFiles.Checked = true;
        else
            cheNormalFiles.Checked = false;

        if (gdcSVNDefaultView.ActiveFilterString.Contains("bin") ||
            gdcSVNDefaultView.ActiveFilterString.Contains("obj"))
            cheBinObjFolders.Checked = true;
        else
            cheBinObjFolders.Checked = false;
    }

With some very light testing, this seems to work just as I want it to. But I'm afraid that there's some sort of 'infinite loop' case where the ColumnFilterChanged event will fire because of the UpdateFilter method being called when the CheckedChanged event happens, which could in turn cause CheckedChange to happen again since the ColumnFilterChanged manipulates the Checkboxes.


问:
HiveQL string function questions
I'm using HiveQL to run the below query.

The intention is that the case statement removes the last XX characters from the end of the domain, dependent on the suffix (.com, .co.uk).

This doesn't seem to work as there is no change to the strings in the 'domainnew' column in the output.

Can anyone advise how I would make this work?

I also then need to take the output of  'domainnew' and take only the characters to the right of the first '.' when reading from the right handside.

domain  = mobile.domain.facebook.com

domainnew = mobile.domain.facebook

newcalc = facebook

Any advice on this would be brilliant!!

Thank you

```<code>select domain, catid, apnid, sum(optimisedsize) as bytes,

          CASE domain
            WHEN  instr(domain, '.co.uk')  THEN substr(domain,LENGTH(domain)-6)
            WHEN  instr(domain, '.com')  THEN substr(domain,LENGTH(domain)-6)
            ELSE domain
          END as domainnew

from udsapp.web

where dt = 20170330 and hour = 04 and loc = 'FAR1' and catid <> "0:0" group by domain, catid, apnid sort by bytes desc;
</code>```

Title: HiveQL string function questions

Body:
I'm using HiveQL to run the below query.

The intention is that the case statement removes the last XX characters from the end of the domain, dependent on the suffix (.com, .co.uk).

This doesn't seem to work as there is no change to the strings in the 'domainnew' column in the output.

Can anyone advise how I would make this work?

I also then need to take the output of  'domainnew' and take only the characters to the right of the first '.' when reading from the right handside.

domain  = mobile.domain.facebook.com

domainnew = mobile.domain.facebook

newcalc = facebook

Any advice on this would be brilliant!!

Thank you

select domain, catid, apnid, sum(optimisedsize) as bytes,

          CASE domain
            WHEN  instr(domain, '.co.uk')  THEN substr(domain,LENGTH(domain)-6)
            WHEN  instr(domain, '.com')  THEN substr(domain,LENGTH(domain)-6)
            ELSE domain
          END as domainnew

from udsapp.web

where dt = 20170330 and hour = 04 and loc = 'FAR1' and catid <> "0:0" group by domain, catid, apnid sort by bytes desc;

Body:
with t as (select 'mobile.domain.facebook.com' as domain)

select  regexp_extract(domain,'(.*?)(\\.com|\\.co\\.uk|)$',1)      as domainnew
       ,regexp_extract(domain,'.*?([^.]+)(\\.com|\\.co\\.uk|)$',1) as new_calc

from    t
;

+------------------------+----------+
|       domainnew        | new_calc |
+------------------------+----------+
| mobile.domain.facebook | facebook |
+------------------------+----------+


问:
Android How to set onClick event in list item of ListView
ListView click event not working using SimpleAdapter.

I  would like to set onclick event in list item of ListView.
Now, how can I add a click listener on the listview for opening every row into the activity?

I hope that I've explained correctly the problem and I'm sorry for my very bad english! Thanks to all.

```<code>    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.res.Configuration;
    import android.graphics.drawable.LayerDrawable;
    import android.os.AsyncTask;
    import android.support.design.widget.NavigationView;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    import org.json.JSONArray;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import android.graphics.drawable.Drawable;

    public class NotificationsActivity extends AppCompatActivity {
        DrawerLayout drawerLayout;
        ActionBarDrawerToggle drawerToggle;
        NavigationView navigation;

        ListView notificationListView;
        private int mNotificationsCount = 0;

        private static final String NOTIFICATIONS_URL = "notification_url";
        private static final String NOTIFICATION_COUNT_URL = "notification-count_url";

        UserToken userToken = UserToken.getInstance();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_notifications);
            initInstances();
            new FetchCountTask().execute();

            notificationListView = (ListView)findViewById(R.id.notificationListView);

            String usertoken = userToken.getValue();
            if(usertoken == null) {
                Intent intent = new Intent(NotificationsActivity.this, MainActivity.class);
                startActivity(intent);
            }

            getJSON(NOTIFICATIONS_URL + "?token=" + usertoken);

        }

        private void getJSON(String url) {
            class GetJSON extends AsyncTask<String, Void, String> {
                ProgressDialog loading;
                SimpleAdapter simpleAdapter;

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    loading = ProgressDialog.show(NotificationsActivity.this, "Please Wait...",null,true,true);
                }

                @Override
                protected String doInBackground(String... params) {

                    String uri = params[0];

                    BufferedReader bufferedReader = null;
                    try {
                        URL url = new URL(uri);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        StringBuilder sb = new StringBuilder();

                        bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                        String json;
                        while((json = bufferedReader.readLine())!= null){
                            sb.append(json+"\n");
                        }
                        return sb.toString().trim();

                    }catch(Exception e){
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    loading.dismiss();

                    try{
                        JSONObject emp = (new JSONObject(s)).getJSONObject("data");

                        if (emp != null) {
                            JSONArray notificationsArr = emp.getJSONArray("notifications");
                            if(notificationsArr.length() > 0) {

                                int lenArray = notificationsArr.length();
                                if (lenArray > 0) {
                                    ArrayList<HashMap<String,String>> arrayList=new ArrayList<>();
                                    for (int jIndex = 0; jIndex < lenArray; jIndex++) {

                                        JSONObject innerObject = notificationsArr.getJSONObject(jIndex);

                                        HashMap<String,String> hashMap=new HashMap<>();
                                        //hashMap.put("image",Integer.toString(R.drawable.bell));
                                        //hashMap.put("image",innerObject.getString("image"));
                                        hashMap.put("body",innerObject.getString("body"));
                                        hashMap.put("date",innerObject.getString("created_date"));
                                        arrayList.add(hashMap);
                                    }

                                    //String[] from={"image","body","date"};//string array
                                    String[] from={"body","date"};//string array
                                   // int[] to={R.id.userPhoto,R.id.notificationBody,R.id.notificationDate};//int array of views id's
                                    int[] to={R.id.notificationBody,R.id.notificationDate};//int array of views id's
                                    SimpleAdapter simpleAdapter=new SimpleAdapter(NotificationsActivity.this,arrayList,R.layout.notification_row,from,to);
                                    notificationListView.setAdapter(simpleAdapter);

                                    /*notificationListView.setOnItemClickListener(
                                    new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            String cities = String.valueOf(parent.getItemAtPosition(position));
                                            //Toast.makeText(Cities.this, cities, Toast.LENGTH_LONG).show();

                                        }

                                    });*/
                                }
                            }
                        }

                    }catch (Exception e) {
                        //e.printStackTrace();
                        Toast.makeText(NotificationsActivity.this, "Error: "+e.toString(), Toast.LENGTH_LONG).show();
                    }

                }
            }
            GetJSON gj = new GetJSON();
            gj.execute(url);
        }

        private void initInstances() {
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
            drawerToggle = new ActionBarDrawerToggle(NotificationsActivity.this, drawerLayout, R.string.hello_world, R.string.hello_world);
            drawerLayout.setDrawerListener(drawerToggle);

            navigation = (NavigationView) findViewById(R.id.navigation_view);
            navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    int id = menuItem.getItemId();
                    switch (id) {
                        case R.id.navigation_item_1:
                            startActivity(new Intent(NotificationsActivity.this,ProfileActivity.class));
                            break;
                        case R.id.navigation_item_2:
                            startActivity(new Intent(NotificationsActivity.this,BlogsActivity.class));
                            break;
                        case R.id.navigation_item_3:
                            startActivity(new Intent(NotificationsActivity.this,GroupsActivity.class));
                            break;
                        case R.id.navigation_item_4:
                            startActivity(new Intent(NotificationsActivity.this,EventsActivity.class));
                            break;
                        case R.id.navigation_item_5:
                            userToken.setValue(null);
                            startActivity(new Intent(NotificationsActivity.this,MainActivity.class));
                            break;
                        case R.id.navigation_item_6:
                            startActivity(new Intent(NotificationsActivity.this,SettingsActivity.class));
                            break;
                    }
                    return false;
                }
            });

        }

        @Override
        public void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);

            // Get the notifications MenuItem and
            // its LayerDrawable (layer-list)
            MenuItem item = menu.findItem(R.id.action_notifications);
            LayerDrawable icon = (LayerDrawable) item.getIcon();

            // Update LayerDrawable's BadgeDrawable
            Utils.setBadgeCount(this, icon, mNotificationsCount);

            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (drawerToggle.onOptionsItemSelected(item))
                return true;

            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_notifications) {
                //return true;
                startActivity(new Intent(NotificationsActivity.this,NotificationsActivity.class));
            }

            return super.onOptionsItemSelected(item);
        }

        /*
       Updates the count of notifications in the ActionBar.
        */
        private void updateNotificationsBadge(int count) {
            mNotificationsCount = count;

            // force the ActionBar to relayout its MenuItems.
            // onCreateOptionsMenu(Menu) will be called again.
            invalidateOptionsMenu();
        }

        /*
        Sample AsyncTask to fetch the notifications count
        */
        class FetchCountTask extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                String usertokenss = userToken.getValue();
                String uri = NOTIFICATION_COUNT_URL + "?token=" + usertokenss;

                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                    }

                    return sb.toString().trim();

                }catch(Exception e){
                    return null;
                }
            }

            @Override
            public void onPostExecute(String s) {
                try {
                    JSONObject emp = (new JSONObject(s)).getJSONObject("data");
                    int notification_count = emp.getInt("notification_count");

                    updateNotificationsBadge(notification_count);

                }catch (Exception e) {e.printStackTrace();}
            }
        }
    }
</code>```

答:
```<code>list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                Intent intent = new Intent(context, SendMessage.class);
                String message = "abcpqr";
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });
</code>```

try this way.

Body:
ListView click event not working using SimpleAdapter.

I  would like to set onclick event in list item of ListView.
Now, how can I add a click listener on the listview for opening every row into the activity?

I hope that I've explained correctly the problem and I'm sorry for my very bad english! Thanks to all.

    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.res.Configuration;
    import android.graphics.drawable.LayerDrawable;
    import android.os.AsyncTask;
    import android.support.design.widget.NavigationView;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    import org.json.JSONArray;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import android.graphics.drawable.Drawable;

    public class NotificationsActivity extends AppCompatActivity {
        DrawerLayout drawerLayout;
        ActionBarDrawerToggle drawerToggle;
        NavigationView navigation;

        ListView notificationListView;
        private int mNotificationsCount = 0;

        private static final String NOTIFICATIONS_URL = "notification_url";
        private static final String NOTIFICATION_COUNT_URL = "notification-count_url";

        UserToken userToken = UserToken.getInstance();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_notifications);
            initInstances();
            new FetchCountTask().execute();

            notificationListView = (ListView)findViewById(R.id.notificationListView);

            String usertoken = userToken.getValue();
            if(usertoken == null) {
                Intent intent = new Intent(NotificationsActivity.this, MainActivity.class);
                startActivity(intent);
            }

            getJSON(NOTIFICATIONS_URL + "?token=" + usertoken);

        }

        private void getJSON(String url) {
            class GetJSON extends AsyncTask<String, Void, String> {
                ProgressDialog loading;
                SimpleAdapter simpleAdapter;

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    loading = ProgressDialog.show(NotificationsActivity.this, "Please Wait...",null,true,true);
                }

                @Override
                protected String doInBackground(String... params) {

                    String uri = params[0];

                    BufferedReader bufferedReader = null;
                    try {
                        URL url = new URL(uri);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        StringBuilder sb = new StringBuilder();

                        bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                        String json;
                        while((json = bufferedReader.readLine())!= null){
                            sb.append(json+"\n");
                        }
                        return sb.toString().trim();

                    }catch(Exception e){
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    loading.dismiss();

                    try{
                        JSONObject emp = (new JSONObject(s)).getJSONObject("data");

                        if (emp != null) {
                            JSONArray notificationsArr = emp.getJSONArray("notifications");
                            if(notificationsArr.length() > 0) {

                                int lenArray = notificationsArr.length();
                                if (lenArray > 0) {
                                    ArrayList<HashMap<String,String>> arrayList=new ArrayList<>();
                                    for (int jIndex = 0; jIndex < lenArray; jIndex++) {

                                        JSONObject innerObject = notificationsArr.getJSONObject(jIndex);

                                        HashMap<String,String> hashMap=new HashMap<>();
                                        //hashMap.put("image",Integer.toString(R.drawable.bell));
                                        //hashMap.put("image",innerObject.getString("image"));
                                        hashMap.put("body",innerObject.getString("body"));
                                        hashMap.put("date",innerObject.getString("created_date"));
                                        arrayList.add(hashMap);
                                    }

                                    //String[] from={"image","body","date"};//string array
                                    String[] from={"body","date"};//string array
                                   // int[] to={R.id.userPhoto,R.id.notificationBody,R.id.notificationDate};//int array of views id's
                                    int[] to={R.id.notificationBody,R.id.notificationDate};//int array of views id's
                                    SimpleAdapter simpleAdapter=new SimpleAdapter(NotificationsActivity.this,arrayList,R.layout.notification_row,from,to);
                                    notificationListView.setAdapter(simpleAdapter);

                                    /*notificationListView.setOnItemClickListener(
                                    new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            String cities = String.valueOf(parent.getItemAtPosition(position));
                                            //Toast.makeText(Cities.this, cities, Toast.LENGTH_LONG).show();

                                        }

                                    });*/
                                }
                            }
                        }

                    }catch (Exception e) {
                        //e.printStackTrace();
                        Toast.makeText(NotificationsActivity.this, "Error: "+e.toString(), Toast.LENGTH_LONG).show();
                    }

                }
            }
            GetJSON gj = new GetJSON();
            gj.execute(url);
        }

        private void initInstances() {
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
            drawerToggle = new ActionBarDrawerToggle(NotificationsActivity.this, drawerLayout, R.string.hello_world, R.string.hello_world);
            drawerLayout.setDrawerListener(drawerToggle);

            navigation = (NavigationView) findViewById(R.id.navigation_view);
            navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    int id = menuItem.getItemId();
                    switch (id) {
                        case R.id.navigation_item_1:
                            startActivity(new Intent(NotificationsActivity.this,ProfileActivity.class));
                            break;
                        case R.id.navigation_item_2:
                            startActivity(new Intent(NotificationsActivity.this,BlogsActivity.class));
                            break;
                        case R.id.navigation_item_3:
                            startActivity(new Intent(NotificationsActivity.this,GroupsActivity.class));
                            break;
                        case R.id.navigation_item_4:
                            startActivity(new Intent(NotificationsActivity.this,EventsActivity.class));
                            break;
                        case R.id.navigation_item_5:
                            userToken.setValue(null);
                            startActivity(new Intent(NotificationsActivity.this,MainActivity.class));
                            break;
                        case R.id.navigation_item_6:
                            startActivity(new Intent(NotificationsActivity.this,SettingsActivity.class));
                            break;
                    }
                    return false;
                }
            });

        }

        @Override
        public void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);

            // Get the notifications MenuItem and
            // its LayerDrawable (layer-list)
            MenuItem item = menu.findItem(R.id.action_notifications);
            LayerDrawable icon = (LayerDrawable) item.getIcon();

            // Update LayerDrawable's BadgeDrawable
            Utils.setBadgeCount(this, icon, mNotificationsCount);

            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            if (drawerToggle.onOptionsItemSelected(item))
                return true;

            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_notifications) {
                //return true;
                startActivity(new Intent(NotificationsActivity.this,NotificationsActivity.class));
            }

            return super.onOptionsItemSelected(item);
        }

        /*
       Updates the count of notifications in the ActionBar.
        */
        private void updateNotificationsBadge(int count) {
            mNotificationsCount = count;

            // force the ActionBar to relayout its MenuItems.
            // onCreateOptionsMenu(Menu) will be called again.
            invalidateOptionsMenu();
        }

        /*
        Sample AsyncTask to fetch the notifications count
        */
        class FetchCountTask extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                String usertokenss = userToken.getValue();
                String uri = NOTIFICATION_COUNT_URL + "?token=" + usertokenss;

                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json+"\n");
                    }

                    return sb.toString().trim();

                }catch(Exception e){
                    return null;
                }
            }

            @Override
            public void onPostExecute(String s) {
                try {
                    JSONObject emp = (new JSONObject(s)).getJSONObject("data");
                    int notification_count = emp.getInt("notification_count");

                    updateNotificationsBadge(notification_count);

                }catch (Exception e) {e.printStackTrace();}
            }
        }
    }

Body:
list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                Intent intent = new Intent(context, SendMessage.class);
                String message = "abcpqr";
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });

try this way.


问:
Extract lines corresponding to the minimum value in the last column
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

```<code>VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10
</code>```

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

```<code>102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111
</code>```

I could use awk to get the least value as "7" from the last column using the code as below:

```<code>awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt
</code>```

and to print only the values in square brackets [] buy using the awk code as below:

```<code>awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt
</code>```

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

Body:
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111

I could use awk to get the least value as "7" from the last column using the code as below:

awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt

and to print only the values in square brackets [] buy using the awk code as below:

awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

Body:
Using sort as a helper to get a neat code:

$ sort -t\] -nk 2 your_file |awk '$NF!=L && L{exit}{L=$NF;print $2}' FS='[][]'
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111
102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111


问:
Alt key wipes up labels in list view in xamarin forms uwp app?
We observed that in xamarin forms UWP app when alt key is pressed all the labels inside listview control are wiped out. Is this a known issue in xamarin forms? </p>

答:
There is a bug on the Xamarin Bugzilla which has similar behaviour. I don't see anything mentioned about the ALT key however. But it seems that in various scenarios the labels are wiped blank.

So yes, this is a known issue, it's probably best to keep track of the progress in the bug report.


问:
Change Foreground of ReadOnly TextBox
In my Windows Phone App I want to have a TextBox which must be readOnly, but this makes its Foreground color look grayish, I want the Foreground color to be black, Is that possible?

Or how else can I have a textblock with black font, but not editable by the user?

答: Also you can just set TextBox Style to null, and set Foreground as usual.</p>

Title: Change Foreground of ReadOnly TextBox


问:
SQL Order by from another table
I'm trying to display my posts by upvote on my page.

My table posts:

```<code>(id, post_name, post_description, post_category, post_subcategory)
</code>```

and table votes:

```<code>(id, post_id, vote_rank)
</code>```

I can display all my post with

```<code>$bdd->query('SELECT * FROM posts WHERE post_subcategory = "'.$_GET['s'].'" ORDER BY post_name');
</code>```

I tried with JOIN but nothing appears.

```<code>$bdd->query('SELECT *
            FROM posts AS p
               JOIN votes as v ON v.post_id = p.id
            WHERE p.post_subcategory =  "'.$_GET['s'].'"
            ORDER BY v.vote_rank');
</code>```

Any idea?

答:
```<code>$bdd->query('SELECT p.*
        FROM posts p LEFT JOIN votes v ON v.post_id = p.id
        WHERE p.post_subcategory =  "'.$_GET['c'].'"
        ORDER BY v.vote_rank');
</code>```

Try It

Title: SQL Order by from another table

Body:
I'm trying to display my posts by upvote on my page.

My table posts:

(id, post_name, post_description, post_category, post_subcategory)

and table votes:

(id, post_id, vote_rank)

I can display all my post with

$bdd->query('SELECT * FROM posts WHERE post_subcategory = "'.$_GET['s'].'" ORDER BY post_name');

I tried with JOIN but nothing appears.

$bdd->query('SELECT *
            FROM posts AS p
               JOIN votes as v ON v.post_id = p.id
            WHERE p.post_subcategory =  "'.$_GET['s'].'"
            ORDER BY v.vote_rank');

Any idea?

Body:
$bdd->query('SELECT p.*
        FROM posts p LEFT JOIN votes v ON v.post_id = p.id
        WHERE p.post_subcategory =  "'.$_GET['c'].'"
        ORDER BY v.vote_rank');

Try It


问:
Java android TimePickerDialog change tittle display time
I created a TimePickerDialog and on top on my dialog I see a time which I set. I see HH:mm AM but I don't want to see a "AM". I don't set title and I don't know how I can override this title. How I can do this?

```<code> public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{

        private TimePickerDialog timepic;
        private Calendar dateLimit;

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calendar = new GregorianCalendar();
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            if (flag == 0) {
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                startDate = calendar.getTime();
//                if (endDate.getTime() < startDate.getTime())
//                    tvEndDate.setText("");
//                tvStartDate.setText(simpleDateFormat.format(startDate));
            } else if (flag == 1) {
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 0);
                endDate = calendar.getTime();
//                if (endDate.getTime() >= startDate.getTime())
//                    tvEndDate.setText(simpleDateFormat.format(endDate));
//                else
//                    Toast.makeText(getActivity().getApplicationContext(), "Data końcowa musi być większa od daty początkowej", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Calendar c = Calendar.getInstance();
            if (flag == 0) {
                c = DateToCalendar(startDate);
            } else if (flag == 1) {
                c = DateToCalendar(endDate);
            }
            timepic = new TimePickerDialog(getActivity(), this, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
            return timepic;
        }
    }
</code>```

答: TimePickerDialog is subclass of AlertDialog. It means you can use setTitle(CharSequence text) method directly when onTimeSet is called.

Body:
I created a TimePickerDialog and on top on my dialog I see a time which I set. I see HH:mm AM but I don't want to see a "AM". I don't set title and I don't know how I can override this title. How I can do this?

 public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{

        private TimePickerDialog timepic;
        private Calendar dateLimit;

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calendar = new GregorianCalendar();
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            if (flag == 0) {
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                startDate = calendar.getTime();
//                if (endDate.getTime() < startDate.getTime())
//                    tvEndDate.setText("");
//                tvStartDate.setText(simpleDateFormat.format(startDate));
            } else if (flag == 1) {
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 0);
                endDate = calendar.getTime();
//                if (endDate.getTime() >= startDate.getTime())
//                    tvEndDate.setText(simpleDateFormat.format(endDate));
//                else
//                    Toast.makeText(getActivity().getApplicationContext(), "Data końcowa musi być większa od daty początkowej", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Calendar c = Calendar.getInstance();
            if (flag == 0) {
                c = DateToCalendar(startDate);
            } else if (flag == 1) {
                c = DateToCalendar(endDate);
            }
            timepic = new TimePickerDialog(getActivity(), this, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
            return timepic;
        }
    }


问:
Confusion about callback function design
I'm designing a library that will be used to intercept and process incoming messages from a message queue. Library users will write their own message handling functions for different kinds of messages received.

I have a MessageConsumer class that needs to handle messages of different kinds. I combined all handler functions into an abstract base class called MessageHandlerBase. Library users will inherit from this and write their own MessageHandler classes.

Relevant parts of the MessageConsumer definition:

```<code>class MessageConsumer {
protected:
    const MessageHandlerBase* m_mesgHandler;
public:
    MessageConsumer( const std::string& brokerURI,
                     const std::string& inputQueueName,
                     const MessageHandlerBase* messageHandler);
    virtual ~MessageConsumer() { this->cleanup(); }
    void runConsumer();

    virtual void onMessage( const Message& message )
    {
         // code to receive and parse messages ...

        if ( message is of type 1 ) {
            m_mesgHandler->handle_message_type_1(message);
        else if ( message is of type 2 ) {
            m_mesgHandler->handle_message_type_2(message);
         // ... and so on for different types of messages
    }
};
</code>```

And the MessageHandlerBase definition is

```<code>class MessageHandlerBase {
    public:
        virtual void handle_message_type_1( const Message& ) const =0;
        virtual void handle_message_type_2( const Message& ) const =0;
        virtual void handle_cms_exception() const {}
        virtual void handle_transfer_interrupted() const {}
        virtual void handle_transfer_resumed() const {}
};
</code>```

Users usually will just care about handling messages of type 1 & 2 so I just made those pure virtual.

My big problem is this: While implementing their own MessageHandler class's handle_message_type_1 and handle_message_type_2 methods, users need access to methods from one (or possibly more) of their helper classes. How can these classes be made available to MessageHandler, without making them global? I can pass the class as a void* argument to handle_message_type_1 but I don't want to because (i) what if I need to pass more than one functions and (ii) then I need to change the call in MessageConsumer; I want to totally  abstract these message handling details from MessageConsumer.

Is there a more elegant way of handling this whole thing?

答:
How can these classes be made available to MessageHandler, without making them global?

Users need to derive from your class. What stops them putting all kinds of data members into their derivate, referencing whatever they need?

That's the main advantage of using functors instead of function pointers: It makes void* userData obsolete.

ContentLicense: CC BY-SA 2.5

Body:
I'm designing a library that will be used to intercept and process incoming messages from a message queue. Library users will write their own message handling functions for different kinds of messages received.

I have a MessageConsumer class that needs to handle messages of different kinds. I combined all handler functions into an abstract base class called MessageHandlerBase. Library users will inherit from this and write their own MessageHandler classes.

Relevant parts of the MessageConsumer definition:

class MessageConsumer {
protected:
    const MessageHandlerBase* m_mesgHandler;
public:
    MessageConsumer( const std::string& brokerURI,
                     const std::string& inputQueueName,
                     const MessageHandlerBase* messageHandler);
    virtual ~MessageConsumer() { this->cleanup(); }
    void runConsumer();

    virtual void onMessage( const Message& message )
    {
         // code to receive and parse messages ...

        if ( message is of type 1 ) {
            m_mesgHandler->handle_message_type_1(message);
        else if ( message is of type 2 ) {
            m_mesgHandler->handle_message_type_2(message);
         // ... and so on for different types of messages
    }
};

And the MessageHandlerBase definition is

class MessageHandlerBase {
    public:
        virtual void handle_message_type_1( const Message& ) const =0;
        virtual void handle_message_type_2( const Message& ) const =0;
        virtual void handle_cms_exception() const {}
        virtual void handle_transfer_interrupted() const {}
        virtual void handle_transfer_resumed() const {}
};

Users usually will just care about handling messages of type 1 & 2 so I just made those pure virtual.

My big problem is this: While implementing their own MessageHandler class's handle_message_type_1 and handle_message_type_2 methods, users need access to methods from one (or possibly more) of their helper classes. How can these classes be made available to MessageHandler, without making them global? I can pass the class as a void* argument to handle_message_type_1 but I don't want to because (i) what if I need to pass more than one functions and (ii) then I need to change the call in MessageConsumer; I want to totally  abstract these message handling details from MessageConsumer.

Is there a more elegant way of handling this whole thing?


问:
Why is C array so much faster than std::array?
We are currently writing some performance critical code in C++ that operates on many large matrices and vectors. Regarding to our research, there should be no major performance difference between std::array and standard C arrays
(See This question or this).
However, while testing we experienced a huge performance improvement by using C arrays over std::array.
This is our demo code:

```<code>#include <iostream>
#include <array>
#include <sys/time.h>

#define ROWS 784
#define COLS 100
#define RUNS 50

using std::array;

void DotPComplex(array<double, ROWS> &result, array<double, ROWS> &vec1, array<double, ROWS> &vec2){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void DotPSimple(double result[ROWS], double vec1[ROWS], double vec2[ROWS]){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void MatMultComplex(array<double, ROWS> &result, array<array<double, COLS>, ROWS> &mat, array<double, ROWS> &vec){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

void MatMultSimple(double result[ROWS], double mat[ROWS][COLS], double vec[ROWS]){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

double getTime(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    double tmp = (double)currentTime.tv_sec * 1000.0 + (double)currentTime.tv_usec/1000.0;
    return tmp;
}

array<double, ROWS> inputVectorComplex = {{ 0 }};
array<double, ROWS> resultVectorComplex = {{ 0 }};
double inputVectorSimple[ROWS] = { 0 };
double resultVectorSimple[ROWS] = { 0 };

array<array<double, COLS>, ROWS> inputMatrixComplex = {{0}};
double inputMatrixSimple[ROWS][COLS] = { 0 };

int main(){
  double start;
  std::cout << "DotP test with C array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPSimple(resultVectorSimple, inputVectorSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "DotP test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPComplex(resultVectorComplex, inputVectorComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C array : " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultSimple(resultVectorSimple, inputMatrixSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultComplex(resultVectorComplex, inputMatrixComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;
}
</code>```

Compiled with: icpc demo.cpp -std=c++11 -O0
This is the result:

```<code>DotP test with C array:
Duration: 0.289795 ms
DotP test with C++ array:
Duration: 1.98413 ms
MatMult test with C array :
Duration: 28.3459 ms
MatMult test with C++ array:
Duration: 175.15 ms
</code>```

With -O3 flag:

```<code>DotP test with C array:
Duration: 0.0280762 ms
DotP test with C++ array:
Duration: 0.0288086 ms
MatMult test with C array :
Duration: 1.78296 ms
MatMult test with C++ array:
Duration: 4.90991 ms
</code>```

The C array implementation is much faster without compiler optimization. Why?
Using compiler optimizations the dot products are equally fast. But for the matrix multiplication there is still a significant speedup when using C arrays.
Is there a way to achieve equal performance when using std::array?

Update:

The compiler used: icpc 17.0.0

With gcc 4.8.5 our code runs much slower than with the intel compiler using any optimization level. Therefore we are mainly interested in the behaviour of the intel compiler.

As suggested by Jonas we adjusted RUNS 50.000 with the following results (intel compiler):

With -O0 flag:

```<code>DotP test with C array:
Duration: 201.764 ms
DotP test with C++ array:
Duration: 1020.67 ms
MatMult test with C array :
Duration: 15069.2 ms
MatMult test with C++ array:
Duration: 123826 ms
</code>```

With -O3 flag:

```<code>DotP test with C array:
Duration: 16.583 ms
DotP test with C++ array:
Duration: 15.635 ms
MatMult test with C array :
Duration: 980.582 ms
MatMult test with C++ array:
Duration: 2344.46 ms
</code>```

答:
First up, the amount of runs you are using is simply too few. Personally, I did not realize (before running the code) that your "Duration" measurements are in miliseconds

By increasing the RUNS to 5,000,000 for DotPSimple and DotPComplex the timing are something like:

DotP test with C array:

Duration: 1074.89

DotP test with C++ array:

Duration: 1085.34

That is, they are very close to being equally fast. In fact, which ever was the fastest differed from test to test, due to the stochastic nature of a benchmark. The same was true for MatMultSimple and MatMultComplex, though they only needed 50,000 runs.

If you really want to measure and know more, you should embrace the stochastic nature of this benchmark and approximate the distributions of the "Duration" measurements. Including a random order of the functions, to remove any ordering bias.

EDIT:
The assembly code (from user2079303's answer) prove outright that there are no differences with optimization enabled. Thus, the zero-cost abstractions are in fact zero-cost with optimization enabled, which is a reasonable requirement.

UPDATE:

The compiler I used:

```<code>g++ (Debian 6.3.0-6) 6.3.0 20170205
</code>```

With the following command:

```<code>g++ -Wall -Wextra -pedantic -O3 test.cpp
</code>```

Using this processor:

```<code>Intel(R) Core(TM) i5-4300U CPU @ 1.90GHz
</code>```

Body:
We are currently writing some performance critical code in C++ that operates on many large matrices and vectors. Regarding to our research, there should be no major performance difference between std::array and standard C arrays
(See This question or this).
However, while testing we experienced a huge performance improvement by using C arrays over std::array.
This is our demo code:

#include <iostream>
#include <array>
#include <sys/time.h>

#define ROWS 784
#define COLS 100
#define RUNS 50

using std::array;

void DotPComplex(array<double, ROWS> &result, array<double, ROWS> &vec1, array<double, ROWS> &vec2){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void DotPSimple(double result[ROWS], double vec1[ROWS], double vec2[ROWS]){
  for(int i = 0; i < ROWS; i++){
    result[i] = vec1[i] * vec2[i];
  }
}

void MatMultComplex(array<double, ROWS> &result, array<array<double, COLS>, ROWS> &mat, array<double, ROWS> &vec){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

void MatMultSimple(double result[ROWS], double mat[ROWS][COLS], double vec[ROWS]){
  for (int i = 0; i < COLS; ++i) {
      for (int j = 0; j < ROWS; ++j) {
        result[i] += mat[i][j] * vec[j];
      }
  }
}

double getTime(){
    struct timeval currentTime;
    gettimeofday(&currentTime, NULL);
    double tmp = (double)currentTime.tv_sec * 1000.0 + (double)currentTime.tv_usec/1000.0;
    return tmp;
}

array<double, ROWS> inputVectorComplex = {{ 0 }};
array<double, ROWS> resultVectorComplex = {{ 0 }};
double inputVectorSimple[ROWS] = { 0 };
double resultVectorSimple[ROWS] = { 0 };

array<array<double, COLS>, ROWS> inputMatrixComplex = {{0}};
double inputMatrixSimple[ROWS][COLS] = { 0 };

int main(){
  double start;
  std::cout << "DotP test with C array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPSimple(resultVectorSimple, inputVectorSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "DotP test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    DotPComplex(resultVectorComplex, inputVectorComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C array : " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultSimple(resultVectorSimple, inputMatrixSimple, inputVectorSimple);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;

  std::cout << "MatMult test with C++ array: " << std::endl;
  start = getTime();
  for(int i = 0; i < RUNS; i++){
    MatMultComplex(resultVectorComplex, inputMatrixComplex, inputVectorComplex);
  }
  std::cout << "Duration: " << getTime() - start << std::endl;
}

Compiled with: icpc demo.cpp -std=c++11 -O0
This is the result:

DotP test with C array:
Duration: 0.289795 ms
DotP test with C++ array:
Duration: 1.98413 ms
MatMult test with C array :
Duration: 28.3459 ms
MatMult test with C++ array:
Duration: 175.15 ms

With -O3 flag:

DotP test with C array:
Duration: 0.0280762 ms
DotP test with C++ array:
Duration: 0.0288086 ms
MatMult test with C array :
Duration: 1.78296 ms
MatMult test with C++ array:
Duration: 4.90991 ms

The C array implementation is much faster without compiler optimization. Why?
Using compiler optimizations the dot products are equally fast. But for the matrix multiplication there is still a significant speedup when using C arrays.
Is there a way to achieve equal performance when using std::array?

Update:

The compiler used: icpc 17.0.0

With gcc 4.8.5 our code runs much slower than with the intel compiler using any optimization level. Therefore we are mainly interested in the behaviour of the intel compiler.

As suggested by Jonas we adjusted RUNS 50.000 with the following results (intel compiler):

With -O0 flag:

DotP test with C array:
Duration: 201.764 ms
DotP test with C++ array:
Duration: 1020.67 ms
MatMult test with C array :
Duration: 15069.2 ms
MatMult test with C++ array:
Duration: 123826 ms

With -O3 flag:

DotP test with C array:
Duration: 16.583 ms
DotP test with C++ array:
Duration: 15.635 ms
MatMult test with C array :
Duration: 980.582 ms
MatMult test with C++ array:
Duration: 2344.46 ms

Body:
First up, the amount of runs you are using is simply too few. Personally, I did not realize (before running the code) that your "Duration" measurements are in miliseconds

By increasing the RUNS to 5,000,000 for DotPSimple and DotPComplex the timing are something like:

DotP test with C array:

Duration: 1074.89

DotP test with C++ array:

Duration: 1085.34

That is, they are very close to being equally fast. In fact, which ever was the fastest differed from test to test, due to the stochastic nature of a benchmark. The same was true for MatMultSimple and MatMultComplex, though they only needed 50,000 runs.

If you really want to measure and know more, you should embrace the stochastic nature of this benchmark and approximate the distributions of the "Duration" measurements. Including a random order of the functions, to remove any ordering bias.

EDIT:
The assembly code (from user2079303's answer) prove outright that there are no differences with optimization enabled. Thus, the zero-cost abstractions are in fact zero-cost with optimization enabled, which is a reasonable requirement.

UPDATE:

The compiler I used:

g++ (Debian 6.3.0-6) 6.3.0 20170205

With the following command:

g++ -Wall -Wextra -pedantic -O3 test.cpp

Using this processor:

Intel(R) Core(TM) i5-4300U CPU @ 1.90GHz


问:
Split and remove particular value in href attribute and add new value using jquery
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

```<code><a class="chapter_video" href="http://localhost/SVE128-portal2/public/video/9/25"></a>
</code>```

And my jquery is

```<code> var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);
</code>```

I have tried

```<code> var remove = href.replace('split[7]', '')
</code>```

instead of href.remove(split[7]);

答:
If the url is generated from server side then this way of solving problem is not future proof, what if url changes overtime?
More accurate way is to have static part of url in different attribute:</p>

```<code><a
  class="chapter_video"
  href="http://localhost/SVE128-portal2/public/video/9/25"
  data-href="http://localhost/SVE128-portal2/public/video"
  data-pid="9"
  data-id="25"
>
</a>

var new = 4;
var video_url = $('.chapter_video');
var href_part = video_url.attr("data-href");
var pid = video_url.attr("data-pid");

video_url.attr('href', href_part + '/'+ pid + '/' + new);
</code>```

Body:
I have splitted the value in href attribute of a tag.

i splitted the value but i cannot remove the values and append new into it.

My HTML code is

And my jquery is

 var new = 4;
 var video_url = $('.chapter_video');
 var href = video_url.attr("href");
 //splitting value of href
 var split = href.split("/");
 if(split[7] !== undefined){
     href.remove(split[7]);
 }

 video_url.attr('href', video_url.attr('href') + '/'+ new);

I have tried

 var remove = href.replace('split[7]', '')

instead of href.remove(split[7]);

Body:
If the url is generated from server side then this way of solving problem is not future proof, what if url changes overtime?
More accurate way is to have static part of url in different attribute:

<a
  class="chapter_video"
  href="http://localhost/SVE128-portal2/public/video/9/25"
  data-href="http://localhost/SVE128-portal2/public/video"
  data-pid="9"
  data-id="25"
>
</a>

var new = 4;
var video_url = $('.chapter_video');
var href_part = video_url.attr("data-href");
var pid = video_url.attr("data-pid");

video_url.attr('href', href_part + '/'+ pid + '/' + new);


问:
Send email through php using mailer class get spam emails
I am working to send email via the PHP Mailer class. I tried many times but I'm getting spam email every time. I want to use it for whatuser. I am using the PHP Mailer class and get spam emails. Please help, my code is the following:</p>

```<code>require_once("PHPMailer-final/class.phpmailer.php");
$admin_email="support@example.com";

$admin_email_caption="example.com";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host     = "mail.example.com"; // SMTP servers
$mail->Port = 26;
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Mailer   = "smtp";
$mail->Username = "support@example.com";  // SMTP username
$mail->Password = "123456789"; // SMTP password
$subject=$subject_mem;
$cs_email=$to_mem;
$body_admin = $body_mem;
$headers ="From:".$admin_email_caption."<".$admin_email.">\nReply-To:".$admin_email."\nContent-Type:text/html";
$mail->From = $admin_email;
$mail->FromName = $admin_email_caption;
$mail->AddReplyTo($admin_email);
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $body_admin;
$mail->AltBody = "This is alt body.";
$mail->AddAddress($cs_email);
if(!$mail->Send())
    @mail($cs_email,$subject,$body_admin,$headers) or die("not send");
//echo $cs_email."<br>";
$mail->ClearAddresses();
$mail->ClearAttachments();
$mail=NULL;
</code>```

答:
You should check your SMTP configurations.

Maybe SMTP configuration is not correct. For this reason your mail() function is working. And mail() function have some missing headers. Example charset. Missing or invalid header is another reason for getting mail in spam

Here is the details about PHPMailer Configurations

Uncomment the line //$mail->SMTPDebug = 3; for Debugging your SMTP configurations

Body:
I am working to send email via the PHP Mailer class. I tried many times but I'm getting spam email every time. I want to use it for whatuser. I am using the PHP Mailer class and get spam emails. Please help, my code is the following:

require_once("PHPMailer-final/class.phpmailer.php");
$admin_email="support@example.com";

$admin_email_caption="example.com";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host     = "mail.example.com"; // SMTP servers
$mail->Port = 26;
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Mailer   = "smtp";
$mail->Username = "support@example.com";  // SMTP username
$mail->Password = "123456789"; // SMTP password
$subject=$subject_mem;
$cs_email=$to_mem;
$body_admin = $body_mem;
$headers ="From:".$admin_email_caption."<".$admin_email.">\nReply-To:".$admin_email."\nContent-Type:text/html";
$mail->From = $admin_email;
$mail->FromName = $admin_email_caption;
$mail->AddReplyTo($admin_email);
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $body_admin;
$mail->AltBody = "This is alt body.";
$mail->AddAddress($cs_email);
if(!$mail->Send())
    @mail($cs_email,$subject,$body_admin,$headers) or die("not send");
//echo $cs_email."
";
$mail->ClearAddresses();
$mail->ClearAttachments();
$mail=NULL;


问:
Cannot edit EditText in AlertDialog
I am trying to get a value from the user the first time the app is opened. I am inflating an AlertDialog to get the value from the user. I am not able to input any text into the EditText, eventhough I can see the cursor blinking.

The code in MainActivity

```<code>SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
        boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
        if (!hasRun) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean("hasRun", true);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
            final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
            builder.setView(dialogView)
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            editText.requestFocus();
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                            regNum = editText.getText().toString();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            builder.show();
            edit.putString("registerNumber", regNum);
            edit.apply();
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        } else {
            //code if the app HAS run before
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        }
</code>```

The layout file is

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/alertDialog"
    >

    <TextView
        android:id="@+id/alert_dialog_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Register Number"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/alert_dialog_editText"
        android:hint="Type your register number here"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_below="@+id/alert_dialog_textview"
         />

</RelativeLayout>
</code>```

What am I doing wrong?

答:
Try using this method:

```<code>public void showEditTextDialog()
{

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflater = LayoutInflater.from(this);

    final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
    final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);

    // Keyboard
    final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

    // Auto show keyboard
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean isFocused) {

            if (isFocused)
            {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            }
        }
    });

    builder.setView(dialogView)
            .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    regNum = editText.getText().toString();
                    Log.d("STACKOVERFLOW", "Registration number: " + regNum);

                    // Hide keyboard
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    // Hide keyboard
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

                    dialog.cancel();
                }
            });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}
</code>```

OUTPUT:

Title: Cannot edit EditText in AlertDialog

Body:
I am trying to get a value from the user the first time the app is opened. I am inflating an AlertDialog to get the value from the user. I am not able to input any text into the EditText, eventhough I can see the cursor blinking.

The code in MainActivity

SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
        boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
        if (!hasRun) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean("hasRun", true);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
            final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
            builder.setView(dialogView)
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            editText.requestFocus();
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                            regNum = editText.getText().toString();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            builder.show();
            edit.putString("registerNumber", regNum);
            edit.apply();
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        } else {
            //code if the app HAS run before
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        }

The layout file is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/alertDialog"
    >

    <TextView
        android:id="@+id/alert_dialog_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Register Number"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/alert_dialog_editText"
        android:hint="Type your register number here"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_below="@+id/alert_dialog_textview"
         />

</RelativeLayout>

What am I doing wrong?

Body:
Try using this method:

public void showEditTextDialog()
{

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflater = LayoutInflater.from(this);

    final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
    final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);

    // Keyboard
    final InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

    // Auto show keyboard
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean isFocused) {

            if (isFocused)
            {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            }
        }
    });

    builder.setView(dialogView)
            .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    regNum = editText.getText().toString();
                    Log.d("STACKOVERFLOW", "Registration number: " + regNum);

                    // Hide keyboard
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    // Hide keyboard
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

                    dialog.cancel();
                }
            });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

OUTPUT:


问:
Using an MVC API with Windows Authentication from VBA
I have developed a MVC Application, which, for the purpose of this question only has one controller:

```<code>Public Function GetValue()
    Return User.Identity.Name
End Function
</code>```

The application is to be used on an Intranet network, therefore, I have set it to 'Windows Authentication'

The aim is to query this application, through VBA.

```<code>Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
With objHTTP
    .Open "GET", URL, False
    .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    .setRequestHeader "Content-type", "application/json"
    .setRequestHeader "data-type", "json"
    .send
    .WaitForResponse
    sResult = .ResponseText
End With
Debug.Print (sResult)
</code>```

If I run the application locally (ie. debug on the computer that is running Excel), it works through Chrome (accessing localhost:xxxxx/api/name returns an xml file with my ActiveDirectory username).

The VBA routine works fine as well, and the Output window displays the XML I get in Chrome.

Now, if I publish the project to the IIS server, it still works through Chrome (accessing myserver/api/name returns an xml file with my ActiveDirectory username).
However, when I run the VBA module, it returns an Error 401:

```<code>Error:401 - Unauthorized: Access is denied due to invalid credentials.
</code>```

The fact that it works in browsers leads me to believe that server-side configuration is OK, and that I need to tweak something in my VBA.

I have to admit that I am a bit clueless at this point...
Thank you for any leads you may give me :)

答:
Thanks to @SWa comment, I solved this with a minor tweak to the function: Switching to WinHttpRequest and using setAutoLogonPolicy 0

```<code>Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
With objHTTP
    .Open "GET", URL, False
    .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    .setRequestHeader "Content-type", "application/json"
    .setRequestHeader "data-type", "json"
    .setAutoLogonPolicy 0
    .send
    .WaitForResponse
    sResult = .ResponseText
End With
Debug.Print (sResult)
</code>```

Body:
I have developed a MVC Application, which, for the purpose of this question only has one controller:

Public Function GetValue()
    Return User.Identity.Name
End Function

The application is to be used on an Intranet network, therefore, I have set it to 'Windows Authentication'

The aim is to query this application, through VBA.

Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
With objHTTP
    .Open "GET", URL, False
    .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    .setRequestHeader "Content-type", "application/json"
    .setRequestHeader "data-type", "json"
    .send
    .WaitForResponse
    sResult = .ResponseText
End With
Debug.Print (sResult)

If I run the application locally (ie. debug on the computer that is running Excel), it works through Chrome (accessing localhost:xxxxx/api/name returns an xml file with my ActiveDirectory username).

The VBA routine works fine as well, and the Output window displays the XML I get in Chrome.

Now, if I publish the project to the IIS server, it still works through Chrome (accessing myserver/api/name returns an xml file with my ActiveDirectory username).
However, when I run the VBA module, it returns an Error 401:

Error:401 - Unauthorized: Access is denied due to invalid credentials.

The fact that it works in browsers leads me to believe that server-side configuration is OK, and that I need to tweak something in my VBA.

I have to admit that I am a bit clueless at this point...
Thank you for any leads you may give me :)

Body:
Thanks to @SWa comment, I solved this with a minor tweak to the function: Switching to WinHttpRequest and using setAutoLogonPolicy 0

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
With objHTTP
    .Open "GET", URL, False
    .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    .setRequestHeader "Content-type", "application/json"
    .setRequestHeader "data-type", "json"
    .setAutoLogonPolicy 0
    .send
    .WaitForResponse
    sResult = .ResponseText
End With
Debug.Print (sResult)


问:
Get real exception type that is contained in AggregateException
a database query is performed in a task which has a CancellationToken of 59sec. If the task is cancelled, a TaskCanceledException is thrown. But this exception is catched as part of a AggregateException.
I want to provide a specific error message. So is it possible to validate in the code if the real exception in the AggregateException is a TaskCancelationException?</p>

答:
You can get the list of exceptions, or use the first one if there is just one:</p>

```<code>var first = agg.InnerException; // just the first

foreach (Exception ex in agg.InnerExceptions) // iterate over all
{
    // do something with each and every one
}
</code>```

Body:
You can get the list of exceptions, or use the first one if there is just one:

var first = agg.InnerException; // just the first

foreach (Exception ex in agg.InnerExceptions) // iterate over all
{
    // do something with each and every one
}


问:
Cordova emulate android Exit Code 1
I have code that is building successfully through cordova. However, when I try to emulate it, I get this error "Error:cmd: Command failed with exit code 1". Any ideas on how to fix this?Here is my output from attempting to emulate the code</p>

答:
I had the same problem. It looks like you don't have any AVD running. I don't think ionic's tutorial specifies that you need to do that. I assume you're following this guide.

To fix the issue (if the error in your case is also caused by the lack of Android Virtual Device running) simply:

Start Android Studio.

Navigate to Tools -> Android -> AVD Manager.

Create virtual device (button on the bottom left corner).

Set up the device by configuring it to suit your needs.

Run the virtual device by pushing the green triangle in AVD Manager, under "Actions" column (a new window with the emulated phone should pop up).

Run the ionic emulate android command again.

Note that if you - for some reason - don't have "Android" submenu under "Tools" menu (that was my first issue), you have to simply start the Android Studio installer once more and reinstall it, making sure you check the box for Android Virtual Device during installation.

Title: Cordova emulate android Exit Code 1


问:
Changing color of material ui tab label
I tried to change the label color of tab to black but it doesn't change. Label color remains white only. Is it hard coded in material-ui only? If no, then how can I change it? This is what I tried</p>

```<code>const styles = {
    tab: {
        padding: '2px 34px',
        width: '140px',
        height: '72px',
        color: '#4b4b4b'
    },
    tabItemContainer: {
        background: 'none'
    }
}
<Tabs
                        tabItemContainerStyle={styles.tabItemContainer}
                        value={this.state.selectedTab}
                        onChange={this.handleTabChange}>
                        <Tab
                            value={0}
                            buttonStyle={styles.tab}
                            label='Members'/>
                        <Tab
                            value={1}
                            buttonStyle={styles.tab}
                            label='Permissions'/>
                    </Tabs>
</code>```

答:
Try to use the style property instead of buttonStyle

```<code><Tab
   value={0}
   style={styles.tab}
   label='Members'
/>
</code>```

Title: Changing color of material ui tab label

Body:
I tried to change the label color of tab to black but it doesn't change. Label color remains white only. Is it hard coded in material-ui only? If no, then how can I change it? This is what I tried

const styles = {
    tab: {
        padding: '2px 34px',
        width: '140px',
        height: '72px',
        color: '#4b4b4b'
    },
    tabItemContainer: {
        background: 'none'
    }
}
<Tabs
                        tabItemContainerStyle={styles.tabItemContainer}
                        value={this.state.selectedTab}
                        onChange={this.handleTabChange}>
                        <Tab
                            value={0}
                            buttonStyle={styles.tab}
                            label='Members'/>
                        <Tab
                            value={1}
                            buttonStyle={styles.tab}
                            label='Permissions'/>
                    </Tabs>

Body:
Try to use the style property instead of buttonStyle

<Tab
   value={0}
   style={styles.tab}
   label='Members'
/>