问:
How can I ensure my spinner (inside menu) updates my menu title and ensure the title is displayed in full?
Edit: Upon Re-setting the emulator the code is working fine and the title updates instantly when a spinner item is selected. However, the title is still not being displayed in full

Edit 2: Upon Re-setting the emulator once more I am having the same issues again...

I have tried to implement a spinner inside my menu for my recordExerciseActivity.

Every time an item inside the spinner is selected, this is set as the new menu title.

The problem I am having is that the first time I open the activity and click on a spinner item the title is not updated. (The onItemSelected code does not run)

However, the second time it works perfectly fine.

Moreover, in activities which the exercise names are really long, it only displays the first few letters.

Sometimes only the first letter...

How can I ensure the spinner updates my menu title correctly every time?
(displaying the full title as well).

Menu XML

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:background="#ffffff"
        app:actionViewClass="android.widget.Spinner"
        app:showAsAction="always"
        android:title="spinner Title" />
</menu>
</code>```

RecordExerciseActivity

```<code>
public class RecordExerciseActivity2 extends AppCompatActivity {

    List<String> allChildExerciseNames = new ArrayList<>();
    public static final String PARENT_EXERCISE_ID = "-999";
    public static final String EXTRA_DATE = "com.example.exerciseappv4.EXTRA_DATE";
    public static final String EXTRA_WEEK_DATES = "1";
    public static String EXTRA_JUNCTIONID = "EXERCISE_JUNCTION_ID";
    int parentExerciseID;
    private ChildExerciseViewModel childExerciseViewModel;
    String firstExerciseName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_exercise);

        Intent intent = getIntent();
        if (intent.hasExtra(PARENT_EXERCISE_ID)) {
            parentExerciseID = Integer.parseInt(intent.getStringExtra(PARENT_EXERCISE_ID));
        }

        BottomNavigationView bottomNav = findViewById(R.id.top_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, new RecordExerciseFragment()).commit();

        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
        childExerciseViewModel = ViewModelProviders.of(this).get(ChildExerciseViewModel.class);
        childExerciseViewModel.getChildExerciseNameFromParentID(parentExerciseID).observe(this, this::setChildExerciseName);
        childExerciseViewModel.getAllchildExercisesFromParentID(parentExerciseID).observe(this, this::getAllChildExercisesFromParentID);

    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.nav_track:
                            selectedFragment = new RecordExerciseFragment();
                            break;
                        case R.id.nav_history:
                            selectedFragment = new RecordExerciseHistoryFragment();
                            break;
                        case R.id.nav_exercise_list:
                            selectedFragment = new ExerciseGraphFragment();
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, selectedFragment).commit();

                    return true;
                }
            };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.record_exercise_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) item.getActionView();
        ArrayList<String> spinnerStringArray = new ArrayList<>();
        //Add your data to your array
        spinnerStringArray.addAll(allChildExerciseNames);

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, allChildExerciseNames);
        spinner.setAdapter(spinnerAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.i("Spinner Item Selected", "TRUE");
                String selectedExercise = parent.getItemAtPosition(position).toString();
                setTitle(selectedExercise);

            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        return true;
    }

    private void setChildExerciseName(String childExerciseName) {
        firstExerciseName = childExerciseName;
        setTitle(firstExerciseName);
    }

    private void getAllChildExercisesFromParentID(List<String> allChildExercisesReceived) {
        allChildExerciseNames.addAll(allChildExercisesReceived);
    }
}

</code>```

答:
Try with this custom layout file for your Spinner :simple_spinner_item_custom.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_text_1"
    style="?android:attr/spinnerItemStyle"
    android:singleLine="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="none"
    android:textAlignment="inherit" />
</code>```

This is the simple modification of original simple_spinner_item.xml file to make it work in your scenario with editing attributes such as android:singleLine="true" and android:ellipsize="marquee" which wouldn't let you show multiline text.
Now, pass this layout as the argument in the ArrayAdapter constructor as :

```<code>ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
                R.layout.simple_spinner_item_custom, spinnerStringArray);
</code>```

Note:
There is no point in setting title of the Activity using setTitle() method. Thanks to the new LiveLayoutInspector feature in Android Studio 4.0, I found out that this Spinner(so will its parent i.e ActionMenuView ) will be stretched to fit the content inside it and title of Activity will be sandwiched. I tried to reduce the width of Spinner or ActionMenuView with no success. Sadly, this way, I think your back navigation button will also be hidden.

But again, if you use app:showAsAction="ifRoom|collapseActionView" attributes to the Spinnermenu, you will get more or less similar kind of UI.
Play with such attributes until they fit into your need.

Another alternative that I can think of at this moment is to inflate a normal menu with down arrow as icon, then in onOptionsItemSelected, handle it to open a Popup menu which will show the list of items that currently your Spinner is showing. Then, handle the onClick of Popup again to change the title of Toolbar(because the title of Activity doesn't support multiline and it doesn't have any id, so that its object can't be created).

Body:
Edit: Upon Re-setting the emulator the code is working fine and the title updates instantly when a spinner item is selected. However, the title is still not being displayed in full

Edit 2: Upon Re-setting the emulator once more I am having the same issues again...

I have tried to implement a spinner inside my menu for my recordExerciseActivity.

Every time an item inside the spinner is selected, this is set as the new menu title.

The problem I am having is that the first time I open the activity and click on a spinner item the title is not updated. (The onItemSelected code does not run)

However, the second time it works perfectly fine.

Moreover, in activities which the exercise names are really long, it only displays the first few letters.

Sometimes only the first letter...

How can I ensure the spinner updates my menu title correctly every time?
(displaying the full title as well).

Menu XML

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:background="#ffffff"
        app:actionViewClass="android.widget.Spinner"
        app:showAsAction="always"
        android:title="spinner Title" />
</menu>

RecordExerciseActivity

public class RecordExerciseActivity2 extends AppCompatActivity {

    List<String> allChildExerciseNames = new ArrayList<>();
    public static final String PARENT_EXERCISE_ID = "-999";
    public static final String EXTRA_DATE = "com.example.exerciseappv4.EXTRA_DATE";
    public static final String EXTRA_WEEK_DATES = "1";
    public static String EXTRA_JUNCTIONID = "EXERCISE_JUNCTION_ID";
    int parentExerciseID;
    private ChildExerciseViewModel childExerciseViewModel;
    String firstExerciseName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_exercise);

        Intent intent = getIntent();
        if (intent.hasExtra(PARENT_EXERCISE_ID)) {
            parentExerciseID = Integer.parseInt(intent.getStringExtra(PARENT_EXERCISE_ID));
        }

        BottomNavigationView bottomNav = findViewById(R.id.top_navigation);
        bottomNav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, new RecordExerciseFragment()).commit();

        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
        childExerciseViewModel = ViewModelProviders.of(this).get(ChildExerciseViewModel.class);
        childExerciseViewModel.getChildExerciseNameFromParentID(parentExerciseID).observe(this, this::setChildExerciseName);
        childExerciseViewModel.getAllchildExercisesFromParentID(parentExerciseID).observe(this, this::getAllChildExercisesFromParentID);

    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.nav_track:
                            selectedFragment = new RecordExerciseFragment();
                            break;
                        case R.id.nav_history:
                            selectedFragment = new RecordExerciseHistoryFragment();
                            break;
                        case R.id.nav_exercise_list:
                            selectedFragment = new ExerciseGraphFragment();
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, selectedFragment).commit();

                    return true;
                }
            };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.record_exercise_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) item.getActionView();
        ArrayList<String> spinnerStringArray = new ArrayList<>();
        //Add your data to your array
        spinnerStringArray.addAll(allChildExerciseNames);

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, allChildExerciseNames);
        spinner.setAdapter(spinnerAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.i("Spinner Item Selected", "TRUE");
                String selectedExercise = parent.getItemAtPosition(position).toString();
                setTitle(selectedExercise);

            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        return true;
    }

    private void setChildExerciseName(String childExerciseName) {
        firstExerciseName = childExerciseName;
        setTitle(firstExerciseName);
    }

    private void getAllChildExercisesFromParentID(List<String> allChildExercisesReceived) {
        allChildExerciseNames.addAll(allChildExercisesReceived);
    }
}

Body:
Try with this custom layout file for your Spinner :simple_spinner_item_custom.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_text_1"
    style="?android:attr/spinnerItemStyle"
    android:singleLine="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="none"
    android:textAlignment="inherit" />

This is the simple modification of original simple_spinner_item.xml file to make it work in your scenario with editing attributes such as android:singleLine="true" and android:ellipsize="marquee" which wouldn't let you show multiline text.
Now, pass this layout as the argument in the ArrayAdapter constructor as :

ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
                R.layout.simple_spinner_item_custom, spinnerStringArray);

Note:
There is no point in setting title of the Activity using setTitle() method. Thanks to the new LiveLayoutInspector feature in Android Studio 4.0, I found out that this Spinner(so will its parent i.e ActionMenuView ) will be stretched to fit the content inside it and title of Activity will be sandwiched. I tried to reduce the width of Spinner or ActionMenuView with no success. Sadly, this way, I think your back navigation button will also be hidden.

But again, if you use app:showAsAction="ifRoom|collapseActionView" attributes to the Spinnermenu, you will get more or less similar kind of UI.
Play with such attributes until they fit into your need.

Another alternative that I can think of at this moment is to inflate a normal menu with down arrow as icon, then in onOptionsItemSelected, handle it to open a Popup menu which will show the list of items that currently your Spinner is showing. Then, handle the onClick of Popup again to change the title of Toolbar(because the title of Activity doesn't support multiline and it doesn't have any id, so that its object can't be created).


来源: stackexchange

问:
Regex expression to fetch correct value in python
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

```<code>SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y
</code>```

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

```<code>import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)
</code>```

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]

答:
I would suggest looking for [field_label]=[field_value] pairs, instead of trying to match a huge chunk of text.

First, have a non-capturing group, that defines allowed field labels:

```<code>labels_group = "(?:" + "|".join(field_labels) + ")"
</code>```

Then, define what a [field_label]=[field_value] pair looks like:

```<code>pat = f'{labels_group}=(.+?)\s+'
# if you dont like f-strings: pat = '{}==(.+?)\s+'.format(labels_group)
</code>```

An important thing to note is that for the field value, we want to match as few characters as possible (using +?) before the whitespace.

ContentLicense: CC BY-SA 4.0

Body:
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]

Body:
I would suggest looking for [field_label]=[field_value] pairs, instead of trying to match a huge chunk of text.

First, have a non-capturing group, that defines allowed field labels:

labels_group = "(?:" + "|".join(field_labels) + ")"

Then, define what a [field_label]=[field_value] pair looks like:

pat = f'{labels_group}=(.+?)\s+'
# if you dont like f-strings: pat = '{}==(.+?)\s+'.format(labels_group)

An important thing to note is that for the field value, we want to match as few characters as possible (using +?) before the whitespace.


问:
Bootstrap modal doesn't open on some devices
I'm tring to open Bootstrap modal by clicking a button. I't works from my browser and from some galaxy devices, but it's not working from Iphone and from my Galaxy A70. (my friend also tried it from A70 and it works fine!!!)

I realy dont know what is going on because it works before and now I just changed the modal content.

In addition, when I write an alert inside this function-$("#exampleModalCenter").on("show.bs.modal") on my JS code, the alert is shown in my device.

If someone can help me I would be realy thankful!

my HTML code for triggering the modal:

```<code><button type="button" style="font-size: medium ;" class="btn btn-outline-primary  btn-sm btn-block container-non-responsive" data-toggle="modal" data-target="#exampleModalCenter" data-title="T-shirt" data-tag="3">
    <b>choose</b>
    </button>
     </p>
</code>```

my modal:

```<code> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content" style="margin-right: 15px;">
                <div class="modal-header " dir="rtl">
                    <h5 class="modal-title " id="exampleModalCenterTitle" dir="rtl"></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true" style="margin-right: 65px;">×</span>
                      </button>
                </div>
                <div class="modal-body">
                    <div class="form-row">
                        <div class="col-md-4 mb-3 ">
                            <table class="table table-borderless table-sm">
                                <tr>
                                    <td>
                                        <div class="btn-group dropdown " dir="rtl">
                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownQuantity" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                      </button>
                                            <div class="dropdown-menu quantites" aria-labelledby="dropdownMenu2">

                                            </div>
                                        </div>

                                    </td>
                                    <td>
                                        <div class="dropdown ">
                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownSize" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dir="rtl">

                      </button>
                                            <div class="dropdown-menu sizes" aria-labelledby="dropdownMenu2">

                                            </div>
                                        </div>
                                    </td>
                                    <td>

                                        <div class="dropdown ">
                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownColor" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dir="rtl">

                    </button>
                                            <div class="dropdown-menu color" aria-labelledby="dropdownMenu2" id="colorDiv">

                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <tr id="americanTr">
                                    <td></td>
                                    <td></td>
                                    <td>

                                        <div class="dropdown " id="americanChoseSleeveDD">
                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownSleeveColor" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dir="rtl">

                    </button>
                                            <div class="dropdown-menu Sleevecolor" aria-labelledby="dropdownMenu2" id="sleeveColorDiv">

                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>

                            <table class="table table-borderless table-sm">
                                <tr>
                                    <td>
                                        <div class="btn-group dropdown " dir="rtl">
                                            <button class="btn btn-outline-primary  dropdown-toggle " type="button" id="dropDownSchool" style="margin-left: 40px;" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                            </button>
                                            <div class="dropdown-menu dropdown-menu-right dropdown-menu-lg-left school" id="schoolDiv" aria-labelledby="dropdownMenu2">

                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="btn-group dropdown " dir="rtl">
                                            <button class="btn btn-outline-primary  dropdown-toggle " type="button" id="dropDownLocation" style="margin-right: 10px;" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                </button>
                                            <div class="dropdown-menu dropdown-menu-right dropdown-menu-lg-left location" id="cityDiv" aria-labelledby="dropdownMenu2">

                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                            <div class="col-md-6 mb-3" dir="rtl" id="schoolNameElseDiv">
                                <label for="schoolName" style="float: right;">else</label>
                                <input type="text" class="form-control" name="schoolName" id="schoolNameElseInput" placeholder="add your school name" value="" required>
                                <div class="invalid-feedback d-block" style="text-align: right;">
                                    required
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <table class="table table-borderless table-sm" id="symbols" style="max-width: 100%;">
                    <tr id=symbolsPlace>

                    </tr>

                </table>
                <p class="mb-1 text-muted text-center text-small">
                    <a href=" #0" onclick="openSizeRuler()">open size ruler</a> </p>
                <div class="modal-footer" dir="rtl">
                    <div class="container">
                        <div class="row">
                            <div class="col text-center">
                                <span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="required">
                    <button  type="button"  disabled onclick="addToCartClick()" class="btn btn-outline-secondary " id="addToCart"  style="pointer-events: none;">  add  <i class="fas fa-shopping-basket"></i></button>
                  </span>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

OpenSizeRuler function opens another modal inside.

I hope you guies can help me.

UPDATE:

I found the problem but I dont know how to face it:

Inside the modal I have a dropdown which it's values are taken from another class. When I create an instance of the class inside the function that generate the dropdown- the modal stop working and not showes up.

the way I use the class:

```<code>function generateCityDD() {
    var citiy = new Schools();
    var cityArr = citiy.getCitiesArr();
    appendToDropDown(cityArr, "cityDiv");
    $(".location button").click(function() {
        $("#dropDownLocation").text($(this).text());
        selectLocation = $(this).text();
        $("#dropDownSchool").text("choose a school");
        selectSchool = null;
        validate();
        generateSchoolsDD();

    });

}
</code>```

any ideas?

答:
after hours I figured it out-
I had a problem with the class constructor :)</p>

Body:
I'm tring to open Bootstrap modal by clicking a button. I't works from my browser and from some galaxy devices, but it's not working from Iphone and from my Galaxy A70. (my friend also tried it from A70 and it works fine!!!)

I realy dont know what is going on because it works before and now I just changed the modal content.

In addition, when I write an alert inside this function-$("#exampleModalCenter").on("show.bs.modal") on my JS code, the alert is shown in my device.

If someone can help me I would be realy thankful!

my HTML code for triggering the modal:

<button type="button" style="font-size: medium ;" class="btn btn-outline-primary  btn-sm btn-block container-non-responsive" data-toggle="modal" data-target="#exampleModalCenter" data-title="T-shirt" data-tag="3">
    choose
    </button>

my modal:

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                      </button>

                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownQuantity" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                      </button>

                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownSize" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dir="rtl">

                      </button>

                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownColor" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dir="rtl">

                    </button>

                                            <button class="btn btn-default dropdown-toggle" type="button" id="dropDownSleeveColor" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" dir="rtl">

                    </button>

                                            <button class="btn btn-outline-primary  dropdown-toggle " type="button" id="dropDownSchool" style="margin-left: 40px;" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                            </button>

                                            <button class="btn btn-outline-primary  dropdown-toggle " type="button" id="dropDownLocation" style="margin-right: 10px;" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                </button>

                                else
                                <input type="text" class="form-control" name="schoolName" id="schoolNameElseInput" placeholder="add your school name" value="" required>

                                    required

                    open size ruler

                    <button  type="button"  disabled onclick="addToCartClick()" class="btn btn-outline-secondary " id="addToCart"  style="pointer-events: none;">  add  </button>

OpenSizeRuler function opens another modal inside.

I hope you guies can help me.

UPDATE:

I found the problem but I dont know how to face it:

Inside the modal I have a dropdown which it's values are taken from another class. When I create an instance of the class inside the function that generate the dropdown- the modal stop working and not showes up.

the way I use the class:

function generateCityDD() {
    var citiy = new Schools();
    var cityArr = citiy.getCitiesArr();
    appendToDropDown(cityArr, "cityDiv");
    $(".location button").click(function() {
        $("#dropDownLocation").text($(this).text());
        selectLocation = $(this).text();
        $("#dropDownSchool").text("choose a school");
        selectSchool = null;
        validate();
        generateSchoolsDD();

    });

}

any ideas?


问:
For a HTML Form, JavaScript or not? - Year 2020
Question 1:
I am building a website form that includes more than a few input boxes (text, email, tel, URL...), a text area, and more than a few checkboxes where the user can choose more than one option.  I used all of the HTML5 validation with "required" and so on.

I am afraid of using JavaScript in forms because I read it is a doorway for hackers and HTML5 is replacing this JavaScript with its own validation attributes like "required" and more.

Is this true?

I am confused because there are tutorials that still use JavaScript for validating and sending the form information.  However, everything looks like you only need HTML for the client-side scripting.

Question 2:
Can anyone tell me what is the update with JavaScript?

Question 3:
Can we make dynamic websites with pure CSS instead of JavaScript?

答:
HTML5 have some great 'new features' which involve an attribute called pattern You can include regex to do some client side validation.

More about the use of pattern attribute can be found here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

Is HTML5 replacing javascript?
Well not really. They both have pros and cons. Client side is always 'hackable' and if you use server side techniques to fetch the data you don't need to worry about HTML5 or Javascript being safer. Just make sure you use a SSL connect and validate/anti-SQL inject/ XSS your entries before you save them to your database.

Can we make dynamic websites with pure CSS instead of JavaScript?
You can style it and make it more visible to which fields are required or have an error, or make stuff visible or invisible when checking a checkbox but that's about it.

Simple example:

<form>

    Choose a username:
    <input type="text" id="uname" name="name" required size="45"
           pattern="[a-z]{4,8}" title="4 to 8 lowercase letters">

Usernames must be lowercase and 4-8 characters in length.

    <button>Submit</button>

</form>```

Body:
HTML5 have some great 'new features' which involve an attribute called pattern You can include regex to do some client side validation.

More about the use of pattern attribute can be found here:
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

Is HTML5 replacing javascript?
Well not really. They both have pros and cons. Client side is always 'hackable' and if you use server side techniques to fetch the data you don't need to worry about HTML5 or Javascript being safer. Just make sure you use a SSL connect and validate/anti-SQL inject/ XSS your entries before you save them to your database.

Can we make dynamic websites with pure CSS instead of JavaScript?
You can style it and make it more visible to which fields are required or have an error, or make stuff visible or invisible when checking a checkbox but that's about it.

Simple example:

<form>
  <div>
    <label for="uname">Choose a username: </label>
    <input type="text" id="uname" name="name" required size="45"
           pattern="[a-z]{4,8}" title="4 to 8 lowercase letters">
    <span class="validity"></span>
    <p>Usernames must be lowercase and 4-8 characters in length.</p>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>


问:
Temporarily disable window during a function call
Consider:

```<code>class Worker
{
public:
  void DoWork();
};

class MainWindow : public QMainWindow
{
Q_OBJECT

private:
  Worker MyWorker;

public:
  void DoWork();
};
</code>```

I want the DoWork function of my MainWindow to behave like:

```<code>void MainWindow::DoWork()
{
  setEnabled(false);

  std::future<void> Resu = std::async(std::launch::async, &Worker::DoWork, &MyWorker);

  while (Resu.wait_for(100ms) == std::future_status::timeout)
    qApp->processEvents();

  try
    { Resu.get(); }
  catch (Except const &MyExcept)
    { QMessageBox::critical(this, "Error", MyExcept.What()); }

   setEnabled(true);
 }
</code>```

This works as I want: (i) the window is disabled while doing the work,
 (ii) the window stays responsive while doing the work (can be moved and resized), and (iii) any
 Except thrown in Worker::DoWork is caught conveniently.

However, this solution relies upon std::future and qApp->processEvents(), the latter
not being recommended by this answer.

How can I write the above code properly in Qt?

So far, I have tried:

```<code>void MainWindow::DoWork()
{
  setEnabled(false);

  QFuture<void> Resu = QtConcurrent::run(std::bind(&Worker::DoWork, &MyWorker));

  try
    { while (Resu.isRunning()) qApp->processEvents(); }
  catch (Except const &MyExcept)
    { QMessageBox::critical(this, "Error", MyExcept.What()); }

   setEnabled(true);
 }
</code>```

and I found the drawbacks of consuming a whole thread (because the too frequent calls to qApp->processEvents()), and furthermore the exceptions are not properly caught.

答:
You can use a QFutureWatcher to receive notification about the completion of your QFuture without the need to be busy-waiting calling processEvents.

Basically you subscribe to the signal QFutureWatcher<void>::finished to know when the operation is complete.  In the associated slot you re-enable the widget.  Particularly important is to call future.waitForFinished() even if the computation is already complete, to force the transfer of any QException that was thrown in the worker thread see here.  It looks like a workaround but I don't know if there is a better solution for this.

After the subscription you call setFuture() function to start your doWork operation.  The computation will be carried out in its own thread.

In this way you should be able to do everything as you want:

the window is disabled while doing the work

the window stays responsive while doing the work (can be moved and resized)

any QException thrown in Worker::doWork is caught conveniently

Here is a minimal working example, based on your question.  It should show you what I mean...

```<code>#include <QApplication>
#include <QException>
#include <QMessageBox>
#include <QPushButton>
#include <QThread>
#include <QtConcurrent>

class Exception : public QException
{
public:
    Exception(const QString& message = "") : m_message {message} { }

    void raise() const override { throw *this; }

    Exception *clone() const override { return new Exception(*this); }

    QString message() { return m_message; }

private:
    QString m_message;
};

class Worker
{
public:
    void doWork() {
        QThread::sleep(5);
        // throw Exception {"something bad happened..."};
        QThread::sleep(5);
    }
};

class Button : public QPushButton
{
    Q_OBJECT

public:
    Button(QWidget* parent = nullptr) : QPushButton {parent} {
        resize(400, 300);
        setText("Click me to wait!");

        connect(this, &QPushButton::clicked,
                this, &Button::doWork);
    }

public slots:
    void doWork() {
        setEnabled(false);

        auto future {QtConcurrent::run(&m_worker, &Worker::doWork)};

        auto watcher {new QFutureWatcher<void> {}};
        connect(watcher, &QFutureWatcher<void>::finished,
                [=]() mutable {
                    try {
                        // Call this to force the transfer of any QException that was thrown in the worker thread
                        // (https://doc.qt.io/qt-5/qexception.html)
                        future.waitForFinished();
                    } catch (Exception& e) {
                        QMessageBox::critical(this, "Error", e.message());
                    }
                    setEnabled(true);
                });

        watcher->setFuture(future);
    }

private:
    Worker                  m_worker;
};

int main(int argc, char* argv[])
{
    QApplication app {argc, argv};

    auto button {new Button {}};
    button->show();

    return app.exec();
}

#include "main.moc"

</code>```

Body:
Consider:

class Worker
{
public:
  void DoWork();
};

class MainWindow : public QMainWindow
{
Q_OBJECT

private:
  Worker MyWorker;

public:
  void DoWork();
};

I want the DoWork function of my MainWindow to behave like:

void MainWindow::DoWork()
{
  setEnabled(false);

  std::future<void> Resu = std::async(std::launch::async, &Worker::DoWork, &MyWorker);

  while (Resu.wait_for(100ms) == std::future_status::timeout)
    qApp->processEvents();

  try
    { Resu.get(); }
  catch (Except const &MyExcept)
    { QMessageBox::critical(this, "Error", MyExcept.What()); }

   setEnabled(true);
 }

This works as I want: (i) the window is disabled while doing the work,
 (ii) the window stays responsive while doing the work (can be moved and resized), and (iii) any
 Except thrown in Worker::DoWork is caught conveniently.

However, this solution relies upon std::future and qApp->processEvents(), the latter
not being recommended by this answer.

How can I write the above code properly in Qt?

So far, I have tried:

void MainWindow::DoWork()
{
  setEnabled(false);

  QFuture<void> Resu = QtConcurrent::run(std::bind(&Worker::DoWork, &MyWorker));

  try
    { while (Resu.isRunning()) qApp->processEvents(); }
  catch (Except const &MyExcept)
    { QMessageBox::critical(this, "Error", MyExcept.What()); }

   setEnabled(true);
 }

and I found the drawbacks of consuming a whole thread (because the too frequent calls to qApp->processEvents()), and furthermore the exceptions are not properly caught.

Body:
You can use a QFutureWatcher to receive notification about the completion of your QFuture without the need to be busy-waiting calling processEvents.

Basically you subscribe to the signal QFutureWatcher<void>::finished to know when the operation is complete.  In the associated slot you re-enable the widget.  Particularly important is to call future.waitForFinished() even if the computation is already complete, to force the transfer of any QException that was thrown in the worker thread see here.  It looks like a workaround but I don't know if there is a better solution for this.

After the subscription you call setFuture() function to start your doWork operation.  The computation will be carried out in its own thread.

In this way you should be able to do everything as you want:

the window is disabled while doing the work

the window stays responsive while doing the work (can be moved and resized)

any QException thrown in Worker::doWork is caught conveniently

Here is a minimal working example, based on your question.  It should show you what I mean...

#include <QApplication>
#include <QException>
#include <QMessageBox>
#include <QPushButton>
#include <QThread>
#include <QtConcurrent>

class Exception : public QException
{
public:
    Exception(const QString& message = "") : m_message {message} { }

    void raise() const override { throw *this; }

    Exception *clone() const override { return new Exception(*this); }

    QString message() { return m_message; }

private:
    QString m_message;
};

class Worker
{
public:
    void doWork() {
        QThread::sleep(5);
        // throw Exception {"something bad happened..."};
        QThread::sleep(5);
    }
};

class Button : public QPushButton
{
    Q_OBJECT

public:
    Button(QWidget* parent = nullptr) : QPushButton {parent} {
        resize(400, 300);
        setText("Click me to wait!");

        connect(this, &QPushButton::clicked,
                this, &Button::doWork);
    }

public slots:
    void doWork() {
        setEnabled(false);

        auto future {QtConcurrent::run(&m_worker, &Worker::doWork)};

        auto watcher {new QFutureWatcher<void> {}};
        connect(watcher, &QFutureWatcher<void>::finished,
                [=]() mutable {
                    try {
                        // Call this to force the transfer of any QException that was thrown in the worker thread
                        // (https://doc.qt.io/qt-5/qexception.html)
                        future.waitForFinished();
                    } catch (Exception& e) {
                        QMessageBox::critical(this, "Error", e.message());
                    }
                    setEnabled(true);
                });

        watcher->setFuture(future);
    }

private:
    Worker                  m_worker;
};

int main(int argc, char* argv[])
{
    QApplication app {argc, argv};

    auto button {new Button {}};
    button->show();

    return app.exec();
}

#include "main.moc"


问:
Adding boost header files gives compile time errors
When i add the header file

```<code>  #include <boost/fusion/adapted/struct/adapt_struct.hpp>
</code>```

It gives couple of errors

```<code>error C2988: unrecognizable template declaration/definition
error C2143: syntax error: missing ';' before '<'
error C2913: explicit specialization; 'boost::type_of::id2type_impl' is not a specialization of a class template
error C2059: syntax error: '<'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body
</code>```

which point towards the line number 125 in typeof_impl.hpp file.

答:
It's unclear what file you mean:

```<code>custom/boost_1_72_0/boost/typeof/typeof_impl.hpp
custom/boost_1_72_0/boost/typeof/msvc/typeof_impl.hpp
custom/boost_1_72_0/boost/typeof/dmc/typeof_impl.hpp
</code>```

If you mean msvc/typeof_impl.hpp then most likely you have a preprocessor issue (where the source is mutated due to a redefined preprocessor token).

If there's no such file than @drescherjm's comment may be on point: there might be specific MSVC support missing in that version you're using.

Body:
When i add the header file

  #include <boost/fusion/adapted/struct/adapt_struct.hpp>

It gives couple of errors

error C2988: unrecognizable template declaration/definition
error C2143: syntax error: missing ';' before '<'
error C2913: explicit specialization; 'boost::type_of::id2type_impl' is not a specialization of a class template
error C2059: syntax error: '<'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body

which point towards the line number 125 in typeof_impl.hpp file.

Body:
It's unclear what file you mean:

custom/boost_1_72_0/boost/typeof/typeof_impl.hpp
custom/boost_1_72_0/boost/typeof/msvc/typeof_impl.hpp
custom/boost_1_72_0/boost/typeof/dmc/typeof_impl.hpp

If you mean msvc/typeof_impl.hpp then most likely you have a preprocessor issue (where the source is mutated due to a redefined preprocessor token).

If there's no such file than @drescherjm's comment may be on point: there might be specific MSVC support missing in that version you're using.


问:
Better way to write the following code in Kotlin?
I've this following function, which maps ids to a list of Strings

```<code>private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String>>  {
    var id = 4

    return resourcesList.map { resource ->
        id++
        id to resource
    }
}
</code>```

The id starts from 5 as you can see here. I can make this code look cleaner if id started from 0. Just like this

```<code>private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
    index to resource
}
</code>```

Is there some Kotlin function to achieve the first result without the use of var id. Maybe some function whose index starts at 5?

答:
From the comment by @al3c

```<code>private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
    index + 5 to resource
}
</code>```

This was probably easier than I thought.

Body:
I've this following function, which maps ids to a list of Strings

private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String>>  {
    var id = 4

    return resourcesList.map { resource ->
        id++
        id to resource
    }
}

The id starts from 5 as you can see here. I can make this code look cleaner if id started from 0. Just like this

private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
    index to resource
}

Is there some Kotlin function to achieve the first result without the use of var id. Maybe some function whose index starts at 5?

Body:
From the comment by @al3c

private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
    index + 5 to resource
}

This was probably easier than I thought.


问:
Is there a way in c++ to make sure that class member function isnt changing any of the class data members?
Lets say that I have a </p>

```<code>class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}
</code>```

<p>Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer. </p>

答:
declare your function as const:

void addWord(string word) const
{
/...
}

If you try to change any members inside the body, the compiler will give an error.
Also note that inside a method declared const, you can't call other methods that are not declared const.

ContentLicense: CC BY-SA 3.0

Body:
Lets say that I have a

class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}

Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer.


问:
how to remove null items from listView in Flutter
i am trying to retrieve data from firebase database, where i can display them as a list items, where user can select one item,

the listview retrieve items as much as i have in the collection in firebase, and according to the filter maybe there is 1 or 2 items only valid to display ,
the ListView taking the space as much as i have Items in the Databas.

```<code>return StreamBuilder(
  stream: _firestore.collection('trips').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return Text('Loading...');

    return ListView(
      children: snapshot.data.documents.map((document) {
        return Padding(
          padding: const EdgeInsets.all(15.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Text(
                  document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination)  ?'From : ' + document['currentLocation']:'x',
                  style: TextStyle(
                      fontWeight: FontWeight.w900, fontSize: 25.0),
                ),
                SizedBox(
                  height: 5.0,
                ),
                Text(

                  document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination)  ?     'To : ' + document['destination']:'x',
                  style: TextStyle(
                      fontWeight: FontWeight.w900, fontSize: 20.0),
                ),
                SizedBox(
                  height: 25.0,
                ),
                Text( document['time'].contains(ampm)&&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Trip Time     : ' + document['time']:'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? ' Trip Details : ' + document['details']:'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Driver Email  : ' + document['driverEmail']: 'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Trip Price      : ' + document['price'] + 'JD' :'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Avilable Seates : ' + document['avilableSeates'].toString()  :'x'),

                SizedBox(
                  height: 25.0,
                ),
                RoundedButton(
                  onPressed: document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ?() {
                    print(userInputTime);

                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                      // return object of type Dialog
                      return AlertDialog(
                        // todo some style on text Trip info
                        // todo check if the user had already selected the same trip. or he have a trip on the way
                        title:   Text('Trip Selected'),
                        content:   Text(document['currentLocation'] + ' to ' +  document['destination'] +' At ' + document['time'] +' ?' ),
                        actions: <Widget>[
                          // usually buttons at the bottom of the dialog
                            FlatButton(
                            child:   Text('Yes'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                          FlatButton(
                            child:   Text('No'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                        ],
                      );
                    });

                  } : null,
                  title:document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Select ' : 'No Trips Found !',
                  color: Colors.blueAccent,
</code>```

// todo close time trips
                    ),
                  ],
                ),
              ),
            );
          }).toList(),   //' Here I NEED TO REMOVE NULL TEXT WIDGTES ITEMS FROM THE LIST'
        );

答:
You can do something like this:

// ... inside your .map()
snapshot.data.documents.map((document) {
   if(document == null) return Wrap();
   // rest of map logic
}
```

Body:
i am trying to retrieve data from firebase database, where i can display them as a list items, where user can select one item,

the listview retrieve items as much as i have in the collection in firebase, and according to the filter maybe there is 1 or 2 items only valid to display ,
the ListView taking the space as much as i have Items in the Databas.

return StreamBuilder(
  stream: _firestore.collection('trips').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return Text('Loading...');

    return ListView(
      children: snapshot.data.documents.map((document) {
        return Padding(
          padding: const EdgeInsets.all(15.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Text(
                  document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination)  ?'From : ' + document['currentLocation']:'x',
                  style: TextStyle(
                      fontWeight: FontWeight.w900, fontSize: 25.0),
                ),
                SizedBox(
                  height: 5.0,
                ),
                Text(

                  document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination)  ?     'To : ' + document['destination']:'x',
                  style: TextStyle(
                      fontWeight: FontWeight.w900, fontSize: 20.0),
                ),
                SizedBox(
                  height: 25.0,
                ),
                Text( document['time'].contains(ampm)&&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Trip Time     : ' + document['time']:'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? ' Trip Details : ' + document['details']:'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Driver Email  : ' + document['driverEmail']: 'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Trip Price      : ' + document['price'] + 'JD' :'x'),
                SizedBox(
                  height: 15.0,
                ),
                Text(document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Avilable Seates : ' + document['avilableSeates'].toString()  :'x'),

                SizedBox(
                  height: 25.0,
                ),
                RoundedButton(
                  onPressed: document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ?() {
                    print(userInputTime);

                    showDialog(
                        context: context,
                        builder: (BuildContext context) {
                      // return object of type Dialog
                      return AlertDialog(
                        // todo some style on text Trip info
                        // todo check if the user had already selected the same trip. or he have a trip on the way
                        title:   Text('Trip Selected'),
                        content:   Text(document['currentLocation'] + ' to ' +  document['destination'] +' At ' + document['time'] +' ?' ),
                        actions: <Widget>[
                          // usually buttons at the bottom of the dialog
                            FlatButton(
                            child:   Text('Yes'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                          FlatButton(
                            child:   Text('No'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                        ],
                      );
                    });

                  } : null,
                  title:document['time'].contains(ampm) &&checkMatchLocationsAndDestinations(document['currentLocation'], document['destination'], uInputCurrentLocation, uInputDestination) ? 'Select ' : 'No Trips Found !',
                  color: Colors.blueAccent,

// todo close time trips
                    ),
                  ],
                ),
              ),
            );
          }).toList(),   //' Here I NEED TO REMOVE NULL TEXT WIDGTES ITEMS FROM THE LIST'
        );


问:
Runtime error while merging two sorted linked list
I am writing a c++ code to merge two sorted link lists.I am using two pointer method.I am getting a runtime error for the code below.I am unable to debug the code.

Error- Your submission stopped because of a runtime error. ex: division by zero, array index out of
       bounds, uncaught exception.

```<code>   /**
   * Definition for singly-linked list.
   * struct ListNode {
   *     int val;
   *     ListNode *next;
   *     ListNode(int x) : val(x), next(NULL) {}
   * };
   */
    ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) {

    ListNode* head1=new ListNode(-1);
    head1->next=A;
    ListNode* head2=new ListNode(-1);
    head2->next=B;

    ListNode* temp1=head1;
    ListNode* temp2=head2;

    while(temp1->next!=NULL || temp2->next!=NULL)
    {
        if(temp1->next->val <= temp2->next->oval)
        {
           // if(temp1->next==NULL) break;
           //else
            temp1=temp1->next;
        }
        else if(temp1->next->val > temp2->next->oval)
        {
            ListNode* temp=temp1->next;
            ListNode* t2=temp2->next->next;
            temp1->next=temp2->next;
            temp2->next=t2;
            temp1->next->next=temp;
            temp1=temp1->next;
        }
    }
    if(temp1->next==NULL)
    {
    temp1->next=temp2->next;
    temp2->next=NULL;
    }
    return head1->next;
}
</code>```

答:
This condition:

```<code>while(temp1->next!=NULL || temp2->next!=NULL)
</code>```

is incorrect, since you will be accessing invalid memory if exactly one of these pointers is NULL.

Instead, you need to do:

```<code>while(temp1->next!=NULL && temp2->next!=NULL)
</code>```

Also, you should use nullptr instead of NULL.

Body:
I am writing a c++ code to merge two sorted link lists.I am using two pointer method.I am getting a runtime error for the code below.I am unable to debug the code.

Error- Your submission stopped because of a runtime error. ex: division by zero, array index out of
       bounds, uncaught exception.

   /**
   * Definition for singly-linked list.
   * struct ListNode {
   *     int val;
   *     ListNode *next;
   *     ListNode(int x) : val(x), next(NULL) {}
   * };
   */
    ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) {

    ListNode* head1=new ListNode(-1);
    head1->next=A;
    ListNode* head2=new ListNode(-1);
    head2->next=B;

    ListNode* temp1=head1;
    ListNode* temp2=head2;

    while(temp1->next!=NULL || temp2->next!=NULL)
    {
        if(temp1->next->val <= temp2->next->oval)
        {
           // if(temp1->next==NULL) break;
           //else
            temp1=temp1->next;
        }
        else if(temp1->next->val > temp2->next->oval)
        {
            ListNode* temp=temp1->next;
            ListNode* t2=temp2->next->next;
            temp1->next=temp2->next;
            temp2->next=t2;
            temp1->next->next=temp;
            temp1=temp1->next;
        }
    }
    if(temp1->next==NULL)
    {
    temp1->next=temp2->next;
    temp2->next=NULL;
    }
    return head1->next;
}

Body:
This condition:

while(temp1->next!=NULL || temp2->next!=NULL)

is incorrect, since you will be accessing invalid memory if exactly one of these pointers is NULL.

Instead, you need to do:

while(temp1->next!=NULL && temp2->next!=NULL)

Also, you should use nullptr instead of NULL.


问:
Can't publish options with RabbitMQ message?
I'm using ampq.node for my RabbitMQ access in my Node code. I'm trying to use either the publish or sendToQueue methods to include some metadata with my published message (namely timestamp and content type), using the options parameter.

But whatever I'm passing to options is completely ignored. I think I'm missing some formatting, or a field name, but I cannot find any reliable documentation (beyond the one provided here which does not seem to do the job).

Below is my publish function code:

```<code>  var publish = function(queueName, message) {
    let content;
    let options = {
      persistent: true,
      noAck: false,
      timestamp: Date.now(),
      contentEncoding: 'utf-8'
    };
    if(typeof message === 'object') {
      content = new Buffer(JSON.stringify(message));
      options.contentType = 'application/json';
    }
    else if(typeof message === 'string') {
      content = new Buffer(message);
      options.contentType = 'text/plain';
    }
    else {  //message is already a buffer?
      content = message;
    }
    return Channel.sendToQueue(queueName, content, options); //Channel defined and opened elsewhere
  };
</code>```

What am I missing?

Update:
Turns out if you choose to use a ConfirmChannel, you must provide the callback function as the last parameter, or else, the options object is ignored. So once I changed the code to the following, I started seeing the options correctly:

Channel.sendToQueue(queueName, content, options, (err, result) => {...});

答: this may help others, but the key name to use for content type is contentType in the javascript code. Using the web Gui for rabbitMQ, they use content_type as the key name. different key names to declare options, so make sure to use the right one in the right context.

Body:
I'm using ampq.node for my RabbitMQ access in my Node code. I'm trying to use either the publish or sendToQueue methods to include some metadata with my published message (namely timestamp and content type), using the options parameter.

But whatever I'm passing to options is completely ignored. I think I'm missing some formatting, or a field name, but I cannot find any reliable documentation (beyond the one provided here which does not seem to do the job).

Below is my publish function code:

  var publish = function(queueName, message) {
    let content;
    let options = {
      persistent: true,
      noAck: false,
      timestamp: Date.now(),
      contentEncoding: 'utf-8'
    };
    if(typeof message === 'object') {
      content = new Buffer(JSON.stringify(message));
      options.contentType = 'application/json';
    }
    else if(typeof message === 'string') {
      content = new Buffer(message);
      options.contentType = 'text/plain';
    }
    else {  //message is already a buffer?
      content = message;
    }
    return Channel.sendToQueue(queueName, content, options); //Channel defined and opened elsewhere
  };

What am I missing?

Update:
Turns out if you choose to use a ConfirmChannel, you must provide the callback function as the last parameter, or else, the options object is ignored. So once I changed the code to the following, I started seeing the options correctly:

Channel.sendToQueue(queueName, content, options, (err, result) => {...});


问:
What is the working of .toObject() method in java?how do I convert documentsnapshot to a POJO object using it?explain
I want to convert my document snapshots to a pojo object. but I can't get the logic behind this .toObject() method. can someone explain it's working, i.e. arguments, how it works, how i should use it in firebase.

```<code>private ArrayList<POJO> mArrayList = new ArrayList<>();

public ArrayList<POJO> getmArrayList() {
    return mArrayList;
}
public void getListItems() {
    db.collection(collection_name).get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot documentSnapshots) {
                    if (documentSnapshots.isEmpty()) {
                        Log.d(TAG, "onSuccess: LIST EMPTY");
                        return;
                    } else {
                        // Convert the whole Query Snapshot to a list
                        // of objects directly! No need to fetch each
                        // document.
                        List<POJO> types = documentSnapshots.toObjects(POJO.class);

                        // Add all to your list
                        mArrayList.addAll(types);
                        Log.d(TAG, "onSuccess: " + mArrayList);
                    }
                }
            });
}
</code>```

my MainActivity file is this -

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FireStore mido= new FireStore();
    ArrayList<POJO> mArr = mido.getmArrayList();

    List<POJO> types = new ArrayList<>();
    mido.getListItems();
    types.addAll(mArr);
    String[] iranoutofnames= new String[2];
    int i = 0;
    for (POJO hello: types) {
        iranoutofnames[i] = hello.getName();
        i++;
    }
    for (int j = 0; j < 2; j++) {
        Toast.makeText(this, iranoutofnames[0], Toast.LENGTH_LONG).show();
        Toast.makeText(this, iranoutofnames[1], Toast.LENGTH_LONG).show();
    }
</code>```

答: .toObject() is used to convert some data to some POJO data type.</p>

Body:
I want to convert my document snapshots to a pojo object. but I can't get the logic behind this .toObject() method. can someone explain it's working, i.e. arguments, how it works, how i should use it in firebase.

private ArrayList<POJO> mArrayList = new ArrayList<>();

public ArrayList<POJO> getmArrayList() {
    return mArrayList;
}
public void getListItems() {
    db.collection(collection_name).get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot documentSnapshots) {
                    if (documentSnapshots.isEmpty()) {
                        Log.d(TAG, "onSuccess: LIST EMPTY");
                        return;
                    } else {
                        // Convert the whole Query Snapshot to a list
                        // of objects directly! No need to fetch each
                        // document.
                        List<POJO> types = documentSnapshots.toObjects(POJO.class);

                        // Add all to your list
                        mArrayList.addAll(types);
                        Log.d(TAG, "onSuccess: " + mArrayList);
                    }
                }
            });
}

my MainActivity file is this -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FireStore mido= new FireStore();
    ArrayList<POJO> mArr = mido.getmArrayList();

    List<POJO> types = new ArrayList<>();
    mido.getListItems();
    types.addAll(mArr);
    String[] iranoutofnames= new String[2];
    int i = 0;
    for (POJO hello: types) {
        iranoutofnames[i] = hello.getName();
        i++;
    }
    for (int j = 0; j < 2; j++) {
        Toast.makeText(this, iranoutofnames[0], Toast.LENGTH_LONG).show();
        Toast.makeText(this, iranoutofnames[1], Toast.LENGTH_LONG).show();
    }


问:
How to replace specific values that starts with some pattern in config.yml using sed
I have a file named config.yml, I want to replace all the values in YAML file which start with keyword config only

```<code>key1: "config/some_text"
key2: "some_text/config/"
</code>```

I want it like

```<code>key1: "my_new_text/some_text"
key2: "some_text/config/"
</code>```

I'm using the following command, this might be wrong as I'm not familiar with regex

```<code>sed -i 's:config/*$.:new_text:g' file_name
</code>```

and the output is

```<code>key1: "my_new_text"
key2: "some_text/my_new_text"
</code>```

答:
```<code>$ sed 's:"config/.*:"my_new_text":' file
key1: "my_new_text"
key2: "some_text/config"
</code>```

Body:
I have a file named config.yml, I want to replace all the values in YAML file which start with keyword config only

key1: "config/some_text"
key2: "some_text/config/"

I want it like

key1: "my_new_text/some_text"
key2: "some_text/config/"

I'm using the following command, this might be wrong as I'm not familiar with regex

sed -i 's:config/*$.:new_text:g' file_name

and the output is

key1: "my_new_text"
key2: "some_text/my_new_text"


Title: Pandas Dataframe split starting on a specific column

Body:
I have the following Pandas dataframe:

       a         b      c         d  Unnamed: 5
1  43.91 -0.041619  43.91 -0.041619       43.91
2  43.39  0.011913  43.91 -0.041619       43.91
3  45.56 -0.048801  43.91 -0.041619       43.91
4  45.43  0.002857  43.91 -0.041619       43.91
5  45.33  0.002204  43.91 -0.041619       43.91
6  45.68 -0.007692  43.91 -0.041619       43.91
7  46.37 -0.014992  43.91 -0.041619       43.91
8  48.04 -0.035381  43.91 -0.041619       43.91
9  48.38 -0.007053  43.91 -0.04161        43.91

And I would like to do divide this dataframe, by calling the name column d by name, and get the following output:

df1 =

      a         b      c
1  43.91 -0.041619  43.91
2  43.39  0.011913  43.91
3  45.56 -0.048801  43.91
4  45.43  0.002857  43.91
5  45.33  0.002204  43.91
6  45.68 -0.007692  43.91
7  46.37 -0.014992  43.91
8  48.04 -0.035381  43.91
9  48.38 -0.007053  43.91

df2 =

          d  Unnamed: 5
1  -0.041619       43.91
2  -0.041619       43.91
3  -0.041619       43.91
4  -0.041619       43.91
5  -0.041619       43.91
6  -0.041619       43.91
7  -0.041619       43.91
8  -0.041619       43.91
9  -0.04161        43.91

Is it possible to achieve this output using pandas library?

Body:
If need one DataFrame with excluded d column is used Index.get_loc for positions and selecting by DataFrame.iloc, for included is used seelcting by DataFrame.loc:

col = 'd'
df1 = df.iloc[:, :df.columns.get_loc(col)]
df2 = df.loc[:, col:]
print (df1)
       a         b      c
1  43.91 -0.041619  43.91
2  43.39  0.011913  43.91
3  45.56 -0.048801  43.91
4  45.43  0.002857  43.91
5  45.33  0.002204  43.91
6  45.68 -0.007692  43.91
7  46.37 -0.014992  43.91
8  48.04 -0.035381  43.91
9  48.38 -0.007053  43.91

print (df2)
          d  Unnamed: 5
1 -0.041619       43.91
2 -0.041619       43.91
3 -0.041619       43.91
4 -0.041619       43.91
5 -0.041619       43.91
6 -0.041619       43.91
7 -0.041619       43.91
8 -0.041619       43.91
9 -0.041610       43.91


问:
Error in SLURM cluster - Detected 1 oom-kill event(s): how to improve running jobs
I'm working in a SLURM cluster and I was running several processes at the same time (on several input files), and using the same bash script.

At the end of the job, the process was killed and this is the error I obtained.

```<code>slurmstepd: error: Detected 1 oom-kill event(s) in step 1090990.batch cgroup.
</code>```

My guess is that there is some issue with memory. But how can I know more about?
Did I not provide enough memory? or as user I was requesting more than what I have access to?

Any suggestion?

答:
The approved answer is correct but, to be more precise, error

```<code>slurmstepd: error: Detected 1 oom-kill event(s) in step 1090990.batch cgroup.
</code>```

indicates that you are low on Linux's CPU RAM memory.

If you were, for instance, running some computation on GPU, requesting more GPU memory than what is available will result in an error like this (example for PyTorch):

```<code>RuntimeError: CUDA out of memory. Tried to allocate 8.94 GiB (GPU 0; 15.90 GiB total capacity; 8.94 GiB already allocated; 6.34 GiB free; 0 bytes cached)
</code>```

Check out the explanation in this article for more details.

Solution:
Increase or add in your script parameter --mem-per-cpu.

If you are using sbatch: sbatch your_script.sh to run your script, add in it following line:

#SBATCH --mem-per-cpu=<value bigger than you've requested before>

If you are using srun: srun python3 your_script.py add this parameter like this:

srun --mem-per-cpu=<value bigger than you've requested before> python3 your_script.py

Body:
I'm working in a SLURM cluster and I was running several processes at the same time (on several input files), and using the same bash script.

At the end of the job, the process was killed and this is the error I obtained.

slurmstepd: error: Detected 1 oom-kill event(s) in step 1090990.batch cgroup.

My guess is that there is some issue with memory. But how can I know more about?
Did I not provide enough memory? or as user I was requesting more than what I have access to?

Any suggestion?

Body:
The approved answer is correct but, to be more precise, error

slurmstepd: error: Detected 1 oom-kill event(s) in step 1090990.batch cgroup.

indicates that you are low on Linux's CPU RAM memory.

If you were, for instance, running some computation on GPU, requesting more GPU memory than what is available will result in an error like this (example for PyTorch):

RuntimeError: CUDA out of memory. Tried to allocate 8.94 GiB (GPU 0; 15.90 GiB total capacity; 8.94 GiB already allocated; 6.34 GiB free; 0 bytes cached)

Check out the explanation in this article for more details.

Solution:
Increase or add in your script parameter --mem-per-cpu.

If you are using sbatch: sbatch your_script.sh to run your script, add in it following line:

#SBATCH --mem-per-cpu=<value bigger than you've requested before>

If you are using srun: srun python3 your_script.py add this parameter like this:

srun --mem-per-cpu=<value bigger than you've requested before> python3 your_script.py


问:
Django : changing browser zoom in production
The zoom level of my website is not the same in production as it is in development. I would like the zoom level to be the same as it is in development. That corresponds to a 75% zoom in production. Is there a way to do this with Django ? Maybe in the settings or in the templates ?

Thanks in advance !

答:
I know the question is already answered, there is one more way.

On the html page below the  tag, paste the below script

```<code><script type="text/javascript">

    var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
    // if zoom level is greater than 75
    if (browserZoomLevel>75){
        // find how much
        zoom_level = 100-(browserZoomLevel-75)
        // add percentage symbol with value
        zoom_percent = zoom_level+"%"
        // adjust the browser zoom level
        document.body.style.zoom = zoom_percent
      }

</script>
</code>```

If the browser zoom level is greater than 75 percent, the above code will auto adjust to 75%.

Hope this helps someone. Thanks

Body:
I know the question is already answered, there is one more way.

On the html page below the <body> tag, paste the below script

<script type="text/javascript">

    var browserZoomLevel = Math.round(window.devicePixelRatio * 100);
    // if zoom level is greater than 75
    if (browserZoomLevel>75){
        // find how much
        zoom_level = 100-(browserZoomLevel-75)
        // add percentage symbol with value
        zoom_percent = zoom_level+"%"
        // adjust the browser zoom level
        document.body.style.zoom = zoom_percent
      }

</script>

If the browser zoom level is greater than 75 percent, the above code will auto adjust to 75%.

Hope this helps someone. Thanks


问:
Multithread performance
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

```<code>#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}
</code>```

答: You may have 4 cores in your Core i5 750 machine, but you still have single data bus. All of the used data (13107200 * 3 * sizeof(float) = 157 MB) must pass through this data bus. And then there is a resulting vector of "mere" 13107200 * sizeof(float) = 52 MB, which takes the same resource. All this is heavy on the cache, and 4 cores spend a lot of time waiting for memory to be available for either read or write.</p>

Title: Multithread performance

Body:
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}


问:
How can I pass variables from awk to a shell command?
I am trying to run a shell command from within awk for each line of a file, and the shell command needs one input argument. I tried to use system(), but it didn't recognize the input argument.

Each line of this file is an address of a file, and I want to run a command to process that file. So, for a simple example I want to use 'wc' command for each line and pass $1to wc.

```<code>awk '{system("wc $1")}' myfile
</code>```

答:
I would suggest another solution:

```<code>awk '{print $1}' myfile | xargs wc
</code>```

the difference is that it executes wc once with multiple arguments. It often works (for example, with kill command)

Body:
I am trying to run a shell command from within awk for each line of a file, and the shell command needs one input argument. I tried to use system(), but it didn't recognize the input argument.

Each line of this file is an address of a file, and I want to run a command to process that file. So, for a simple example I want to use 'wc' command for each line and pass $1to wc.

awk '{system("wc $1")}' myfile

Body:
I would suggest another solution:

awk '{print $1}' myfile | xargs wc

the difference is that it executes wc once with multiple arguments. It often works (for example, with kill command)


问:
BIRT - how do I force a column to output values in "Decimal"?
I can do that easily on an existing report by double-clicking a column that has no customized expression for it (i.e. dataSetRow["NAME_OF_COLUMN"]) but when I run into a column with a customized expression, I have no access to its data type, as double-clicking on it only opens the "Expression Builder" window.

Is there a way to somehow "cast" the result of the customized expression, or perhaps feed it into a function that does the conversion? I looked around the various options and settings, but found nothing related to my case.

答:
To achieve the custom format for data, it is very helpful when you write Javascript which will format the column data dynamically.

There are other predefined methods are available which can be used to check if the value does not contains any decimal then you can add .00 to make decimal justified value.

```<code>If(!dataSetRow["NAME_OF_COLUMN"]).contains(".")) {
   var xcustomeformat = dataSetRow["NAME_OF_COLUMN"]) + ".00";
}
</code>```

Similary, if any value comes like 101.4 and you want out put as 101.40 then you can check the length of characters after decimal character and add additional ZEROs as needed.

Body:
To achieve the custom format for data, it is very helpful when you write Javascript which will format the column data dynamically.

There are other predefined methods are available which can be used to check if the value does not contains any decimal then you can add .00 to make decimal justified value.

If(!dataSetRow["NAME_OF_COLUMN"]).contains(".")) {
   var xcustomeformat = dataSetRow["NAME_OF_COLUMN"]) + ".00";
}

Similary, if any value comes like 101.4 and you want out put as 101.40 then you can check the length of characters after decimal character and add additional ZEROs as needed.


问:
Bounded Types in generics
Given an example below, why do I need to use doubleValue()(for which it's needed to extend Number class) in reciprocal(), Since there is auto unboxing feature in java which unboxes the numeric object stored in num and can calculate the reciprocal of num and return a double value?

```<code>class gen<T extends Number>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num.doubleValue()) ;
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}
</code>```

Also, why can't I write the same code as shown below?
 P.S. : The following code shows error in reciprocal() method:

```<code>class gen<T>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num) ;
         // it shows error in the above step. it says "operator / is undefined
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}
</code>```

答:
The description for unboxing in Oracle's documentation (https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) is:

The Java compiler applies unboxing when an object of a wrapper class
  is:

Passed as a parameter to a method that expects a value of the corresponding primitive type.

Assigned to a variable of the corresponding primitive type.

In your case, you are doing neither of these two.

Title: Bounded Types in generics

Body:
Given an example below, why do I need to use doubleValue()(for which it's needed to extend Number class) in reciprocal(), Since there is auto unboxing feature in java which unboxes the numeric object stored in num and can calculate the reciprocal of num and return a double value?

class gen<T extends Number>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num.doubleValue()) ;
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}

Also, why can't I write the same code as shown below?
 P.S. : The following code shows error in reciprocal() method:

class gen<T>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num) ;
         // it shows error in the above step. it says "operator / is undefined
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}


问:
Why .click event handler is not updated here?
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

```<code>function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }
</code>```

Any advices?

答:
I'm not a jQuery (or even javascript) pro but I think from your code, you are trying to set the value of the onclick attribute to the url.

```<code>.attr('onclick', url);
</code>```

I know that in a tag, the onclick attribute should be assigned a javascript function. I think the code is trying to create a tag like

```<code><a onclick=url>
</code>```

and I should url is a string object. Maybe that's why there are errors.

Body:
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }

Any advices?

Body:
I'm not a jQuery (or even javascript) pro but I think from your code, you are trying to set the value of the onclick attribute to the url.

.attr('onclick', url);

I know that in a tag, the onclick attribute should be assigned a javascript function. I think the code is trying to create a tag like

<a onclick=url>

and I should url is a string object. Maybe that's why there are errors.


问:
compare qqplot of a sample with a reference probability distribution in R
I have a weather dataset, i found a simple linear model for two columns Temperature and Humidity and  plotted the histogram of its residuals and calculated the mean and std.

```<code>model <- lm(Temperature..C. ~ Humidity, data = inputData)
model.res = resid(model)
hist(model.res)
mean(model.res)
sd(model.res)
</code>```

I should Plot QQ-plot of residuals versus a zero-mean normal distribution with estimated std. I used Kolmogorov-Smirnov to compare a sample with a reference probability distribution but i don't know how to plot it together:

```<code>ks<-ks.test(model.res, "pnorm", mean=0, sd=sd(model.res))
qqnorm(model.res, main="qqnorm")
qqline(model.res)
</code>```

Data example:

```<code>        Temperature..C. Humidity
1          9.472222     0.89
2          9.355556     0.86
3          9.377778     0.89
4          8.288889     0.83
5          8.755556     0.83
6          9.222222     0.85
7          7.733333     0.95
8          8.772222     0.89
9         10.822222     0.82
10        13.772222     0.72
11        16.016667     0.67
12        17.144444     0.54
13        17.800000     0.55
14        17.333333     0.51
15        18.877778     0.47
16        18.911111     0.46
17        15.388889     0.60
18        15.550000     0.63
19        14.255556     0.69
20        13.144444     0.70
</code>```

答:
Here is a solution using ggplot2

ggplot(model, aes(sample = rstandard(model))) +
  geom_qq() +
  stat_qq_line(dparams=list(sd=sd(model.res)), color="red") +
  stat_qq_line()
```

<p>The red line represents the qqline with your sample sd, the blackline a sd of 1.</p>

<p>You did not ask for that, but you could also add a smoothed qqplot:</p>

```data_model <- model
data_model$theo <- unlist(qqnorm(data_model$residuals)[1])

ggplot(data_model, aes(sample = rstandard(data_model))) +
  geom_qq() +
  stat_qq_line(dparams=list(sd=sd(model.res)), color="red") +
  geom_smooth(aes(x=data_model$theo, y=data_model$residuals), method = "loess")
```

Body:
I have a weather dataset, i found a simple linear model for two columns Temperature and Humidity and  plotted the histogram of its residuals and calculated the mean and std.

model <- lm(Temperature..C. ~ Humidity, data = inputData)
model.res = resid(model)
hist(model.res)
mean(model.res)
sd(model.res)

I should Plot QQ-plot of residuals versus a zero-mean normal distribution with estimated std. I used Kolmogorov-Smirnov to compare a sample with a reference probability distribution but i don't know how to plot it together:

ks<-ks.test(model.res, "pnorm", mean=0, sd=sd(model.res))
qqnorm(model.res, main="qqnorm")
qqline(model.res)

Data example:

        Temperature..C. Humidity
1          9.472222     0.89
2          9.355556     0.86
3          9.377778     0.89
4          8.288889     0.83
5          8.755556     0.83
6          9.222222     0.85
7          7.733333     0.95
8          8.772222     0.89
9         10.822222     0.82
10        13.772222     0.72
11        16.016667     0.67
12        17.144444     0.54
13        17.800000     0.55
14        17.333333     0.51
15        18.877778     0.47
16        18.911111     0.46
17        15.388889     0.60
18        15.550000     0.63
19        14.255556     0.69
20        13.144444     0.70

Body:
Here is a solution using ggplot2

ggplot(model, aes(sample = rstandard(model))) +
  geom_qq() +
  stat_qq_line(dparams=list(sd=sd(model.res)), color="red") +
  stat_qq_line()

The red line represents the qqline with your sample sd, the blackline a sd of 1.

You did not ask for that, but you could also add a smoothed qqplot:

data_model <- model
data_model$theo <- unlist(qqnorm(data_model$residuals)[1])

ggplot(data_model, aes(sample = rstandard(data_model))) +
  geom_qq() +
  stat_qq_line(dparams=list(sd=sd(model.res)), color="red") +
  geom_smooth(aes(x=data_model$theo, y=data_model$residuals), method = "loess")