问:
How to fix invalid prop 'color' suplied to 'icon'?
I’m setting up a new component with an icon from the "react-native-vector-icons" and I got a yellow warning.

This is for a new feature of the icon

```<code>Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                // HERE IS THE PROBLEM //
            return <SSIcon name={'home'} size={20} color={focused ? GStyle.GREEN : Color(GStyle.BLACK).alpha(.45)} />

            },

        }
    },
</code>```

I expect for no yellow warning

答:
have you tried separating the color instead?</p>

```<code>const stackNav = createStackNavigator ({
Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => <SSIcon name={'home'} size={20} color={tintColor} />

        }

}}, {
  tabBarOptions: {
     activeTintColor:GStyle.GREEN,
     inactiveTintColor: Color(GStyle.BLACK).alpha(.45)
})
</code>```

Body:
I’m setting up a new component with an icon from the "react-native-vector-icons" and I got a yellow warning.

This is for a new feature of the icon

Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => {
                // HERE IS THE PROBLEM //
            return <SSIcon name={'home'} size={20} color={focused ? GStyle.GREEN : Color(GStyle.BLACK).alpha(.45)} />

            },

        }
    },

I expect for no yellow warning

Body:
have you tried separating the color instead?

const stackNav = createStackNavigator ({
Dashboard: {
        screen: DashboardStack,
        navigationOptions: {
            title: 'HOME',
            tabBarOnPress: ({ navigation, defaultHandler }) => handleTabPress(navigation, defaultHandler),
            tabBarIcon: ({ focused, tintColor }) => <SSIcon name={'home'} size={20} color={tintColor} />

        }

}}, {
  tabBarOptions: {
     activeTintColor:GStyle.GREEN,
     inactiveTintColor: Color(GStyle.BLACK).alpha(.45)
})


来源: stackexchange

问:
How to filter b-table rows using a custom filter-function?
I'm trying to filter out some rows in a bootstrap-vue table using a custom filter function.

I wrote a function that takes two arguments - a row object and an empty filter argument, and returns true or false, as in the documentation.

I have tried to use the code provided in this and this answers, but they doesn't work either.

I've also tried to put console.log(row, filter) into the filterTable method but it doesn't write anything to the console.

<template>

</template>
```

<pre class="lang-js prettyprint-override"><code>export default {
    data() {
      return {
        items: [
          { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          { age: 89, first_name: 'Geneva', last_name: 'Wilson' },
          { age: 38, first_name: 'Jami', last_name: 'Carney' }
        ]
      }
    },

    methods: {
      filterTable(row) {
        if (row.age >= 40) {
          return false;
        } else {
          return true;
        }
      }
    }
}
</code>```

It's supposed to display people who are younger than 40 years old, but it displays all the records instead.

答:
The criteria you pass to the filter function must be placed on the filter property in order to be reactive. For example you can add a new property e.g. criteria to your data object and assign it to :filter. The filter property expects a value of type String, RegExp, Object or Array. If you assign a number to it, you will get a warning. The criteria for your filter function will be passed as a second argument.

See example below:

new Vue({
  el: "#app",
  data() {
    return {
      criteria: "40",
      items: [{
          age: 40,
          first_name: 'Dickerson',
          last_name: 'Macdonald'
        },
        {
          age: 21,
          first_name: 'Larsen',
          last_name: 'Shaw'
        },
        {
          age: 89,
          first_name: 'Geneva',
          last_name: 'Wilson'
        },
        {
          age: 38,
          first_name: 'Jami',
          last_name: 'Carney'
        }
      ]
    }
  },

  methods: {
    filterTable(row, filter) {
      if (row.age >= filter) {
        return false;
      } else {
        return true;
      }
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://unpkg.com/bootstrap-vue@2.0.0-rc.21/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap@4.3.1/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.0.0-rc.21/dist/bootstrap-vue.js"></script>

<div id="app">
  <div>
    <b-table striped hover :items="items" :filter="criteria" :filter-function="filterTable">
    </b-table>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to filter out some rows in a bootstrap-vue table using a custom filter function.

I wrote a function that takes two arguments - a row object and an empty filter argument, and returns true or false, as in the documentation.

I have tried to use the code provided in this and this answers, but they doesn't work either.

I've also tried to put console.log(row, filter) into the filterTable method but it doesn't write anything to the console.

<template>

</template>

export default {
    data() {
      return {
        items: [
          { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          { age: 89, first_name: 'Geneva', last_name: 'Wilson' },
          { age: 38, first_name: 'Jami', last_name: 'Carney' }
        ]
      }
    },

    methods: {
      filterTable(row) {
        if (row.age >= 40) {
          return false;
        } else {
          return true;
        }
      }
    }
}

It's supposed to display people who are younger than 40 years old, but it displays all the records instead.

Body:
The criteria you pass to the filter function must be placed on the filter property in order to be reactive. For example you can add a new property e.g. criteria to your data object and assign it to :filter. The filter property expects a value of type String, RegExp, Object or Array. If you assign a number to it, you will get a warning. The criteria for your filter function will be passed as a second argument.

See example below:

new Vue({
  el: "#app",
  data() {
    return {
      criteria: "40",
      items: [{
          age: 40,
          first_name: 'Dickerson',
          last_name: 'Macdonald'
        },
        {
          age: 21,
          first_name: 'Larsen',
          last_name: 'Shaw'
        },
        {
          age: 89,
          first_name: 'Geneva',
          last_name: 'Wilson'
        },
        {
          age: 38,
          first_name: 'Jami',
          last_name: 'Carney'
        }
      ]
    }
  },

  methods: {
    filterTable(row, filter) {
      if (row.age >= filter) {
        return false;
      } else {
        return true;
      }
    }
  }
})

<link href="https://unpkg.com/bootstrap-vue@2.0.0-rc.21/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap@4.3.1/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.0.0-rc.21/dist/bootstrap-vue.js"></script>

<div id="app">
  <div>
    <b-table striped hover :items="items" :filter="criteria" :filter-function="filterTable">
    </b-table>
  </div>
</div>


问:
New MQL5 calendar functions - no values?
I can't seem to get any economic event values with MQL5's new calendar functions (see https://www.metatrader5.com/en/releasenotes).

Specifically...

```<code>MqlCalendarValue value[9999999];

ulong changeID=33212160;

int OnInit()

  {

   CalendarValueLastByEvent(840040003,changeID,value);

   ArrayPrint(value);

   return(INIT_SUCCEEDED);

  }
</code>```

...does work but it only returns 0-values for datetime 1970 01 01.

Any solutions?

Thanks!

答: The error was on MetaQuotes' side and they fixed it with a new MetaTrader build realease. My above code now works. Thanks, MetaQuotes!</p>

Body:
I can't seem to get any economic event values with MQL5's new calendar functions (see https://www.metatrader5.com/en/releasenotes).

Specifically...

MqlCalendarValue value[9999999];

ulong changeID=33212160;

int OnInit()

  {

   CalendarValueLastByEvent(840040003,changeID,value);

   ArrayPrint(value);

   return(INIT_SUCCEEDED);

  }

...does work but it only returns 0-values for datetime 1970 01 01.

Any solutions?

Thanks!


问:
UCrop from a fragment no requestCode being sent
I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.

The following is the code of the fragment that is using UCrop:

```<code>public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == CAMERA_PERMISSIONS) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // All good so launch take picture from here
            dispatchTakePictureIntent();
        } else {
            // Permission denied. Warn the user and kick out of app
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.permsDeniedCameraTitle);
            builder.setMessage(R.string.permsDeniedCameraMessage);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Objects.requireNonNull(getActivity()).finishAffinity();
                }
            });
            builder.create().show();
        }
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        Uri starturi = Uri.fromFile(new File(currentPhotoPath));
        Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
        UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
        UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
    }

    Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);

    // On result from cropper add to imageview
    getActivity();
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        final Uri resultUri = UCrop.getOutput(data);
        assert resultUri != null;
        File imgFile = new File(resultUri.getPath());
        Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
        builder.listener(new Picasso.Listener() {
            @Override
            public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                exception.printStackTrace();
            }
        });
        builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
            @Override
            public void onSuccess() {
                btnSettingsSaveImage.setEnabled(true);
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = preferences.edit();
    View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
    imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
    ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
    btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);

    imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });

    imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });

    btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editor.putString("driver_picture", currentPhotoPath);
            editor.apply();
        }
    });

    Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
    builder.listener(new Picasso.Listener() {
        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
            exception.printStackTrace();
        }
    });

    Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));

    builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);

    return view;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.d("IMAGE CREATION", ex.toString());
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(getActivity(),
                    "com.mytestapp.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    String imageFileName = "didimage_" + timeStamp + "_";
    File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,
            ".png",
            storageDir
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}
</code>```

}

The same code from a normal activity works without any issues. Any help appreciated.

答:
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:

```<code>UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
</code>```

so

```<code>.start(Context, Fragment)
</code>```

This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.

Body:
I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.

The following is the code of the fragment that is using UCrop:

public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == CAMERA_PERMISSIONS) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // All good so launch take picture from here
            dispatchTakePictureIntent();
        } else {
            // Permission denied. Warn the user and kick out of app
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.permsDeniedCameraTitle);
            builder.setMessage(R.string.permsDeniedCameraMessage);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Objects.requireNonNull(getActivity()).finishAffinity();
                }
            });
            builder.create().show();
        }
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        Uri starturi = Uri.fromFile(new File(currentPhotoPath));
        Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
        UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
        UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
    }

    Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);

    // On result from cropper add to imageview
    getActivity();
    if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        final Uri resultUri = UCrop.getOutput(data);
        assert resultUri != null;
        File imgFile = new File(resultUri.getPath());
        Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
        builder.listener(new Picasso.Listener() {
            @Override
            public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                exception.printStackTrace();
            }
        });
        builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
            @Override
            public void onSuccess() {
                btnSettingsSaveImage.setEnabled(true);
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = preferences.edit();
    View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
    imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
    ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
    btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);

    imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });

    imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });

    btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editor.putString("driver_picture", currentPhotoPath);
            editor.apply();
        }
    });

    Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
    builder.listener(new Picasso.Listener() {
        @Override
        public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
            exception.printStackTrace();
        }
    });

    Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));

    builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);

    return view;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.d("IMAGE CREATION", ex.toString());
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(getActivity(),
                    "com.mytestapp.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    String imageFileName = "didimage_" + timeStamp + "_";
    File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,
            ".png",
            storageDir
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

}

The same code from a normal activity works without any issues. Any help appreciated.

Body:
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:

UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));

so

.start(Context, Fragment)

This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.


问:
Blatant floating point error in C++ program
I am assigning a double literal to a double variable.
The variable's value gets truncated, otherwise I cannot understand why, for example the difference diff is 0.0.

Sorry for the code duplication at setprecision but I am really pissed off.

```<code>#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>

int main()
{
    long double d = 1300010000000000000144.5700788999;
    long double d1 = 1300010000000000000000.0;
    long double diff = d - d1; // shall be 144.5700788999!!!
    long double d2 = 0.5700788999;

    std::cout << "d = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d << '\n';
    std::cout << "d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d1 << '\n';
    std::cout << "d - d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << diff << '\n';
    std::cout << "d2 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d2 << '\n';
}
</code>```

This is the output:

```<code>d = 1300009999999999900000.0000000000000000
d1 = 1300009999999999900000.0000000000000000
d - d1 = 0.0000000000000000
d2 = 0.5700788999000001
</code>```

I am expecting diff to be 144.5700788999 but it is 0.0

So, how to deal with it? (Window 7 and higher, VS 2013)

...To use two doubles, one for high values and one for low values?
Like, instead using d to use d1 and d2?

答:
80-bit long double (not sure about its size in MSVS) can store around 18 significant decimal digits without loss of precision. 1300010000000000000144.5700788999 has 32 significant decimal digits and cannot be stored exactly as long double.

Read Number of Digits Required For Round-Trip Conversions for more details.

Body:
I am assigning a double literal to a double variable.
The variable's value gets truncated, otherwise I cannot understand why, for example the difference diff is 0.0.

Sorry for the code duplication at setprecision but I am really pissed off.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>

int main()
{
    long double d = 1300010000000000000144.5700788999;
    long double d1 = 1300010000000000000000.0;
    long double diff = d - d1; // shall be 144.5700788999!!!
    long double d2 = 0.5700788999;

    std::cout << "d = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d << '\n';
    std::cout << "d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d1 << '\n';
    std::cout << "d - d1 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << diff << '\n';
    std::cout << "d2 = " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << d2 << '\n';
}

This is the output:

d = 1300009999999999900000.0000000000000000
d1 = 1300009999999999900000.0000000000000000
d - d1 = 0.0000000000000000
d2 = 0.5700788999000001

I am expecting diff to be 144.5700788999 but it is 0.0

So, how to deal with it? (Window 7 and higher, VS 2013)

...To use two doubles, one for high values and one for low values?
Like, instead using d to use d1 and d2?


问:
nHibernate is trying to SQL UPDATE an entity I just created, rather than INSERT?
A projectparticipant may be a member of many groups and a group may have many projectparticipants

I'm finding that when I create 2 ProjectParticipants (this works) and then populate the Project.Groups collection with 3 new groups and add the participants to the relevant groups (Group A has participant 1, Group B has participant 2, Group C has participants 1 and 2), I encounter a "StaleStateException - Batch update returned unexpected row count from update; actual row count: 0, expected: 3". I would expect nHibernate to INSERT the new groups but it's running an UPDATE query and balking that they don't exist. It doesn't get as far as assigning the the participants to the groups

Here are the mappings:

```<code>//ProjectMap: A Project..
        Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);
        HasMany(x => x.Participants)
            .Table("ProjectParticipants")
            .KeyColumn("ProjectId")
            .ApplyFilter(DeletedDateFilter.FilterName)
            .Cascade.AllDeleteOrphan()
            .Inverse();

        HasMany(x => x.Groups)
            .Table("ProjectGroups")
            .KeyColumn("ProjectId")
            .Cascade.AllDeleteOrphan()
            .Inverse();

//ProjectParticipantMap: A ProjectParticipant…
        Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);
        References(x => x.Project)
            .Column("ProjectId")
            .LazyLoad(Laziness.Proxy);
        HasManyToMany(x => x.Groups)
            .Table("ProjectGroupParticipants")
            .ParentKeyColumn("ProjectParticipantId")
            .ChildKeyColumn("ProjectGroupId");

//GroupMap: A Group...
        Id(e => e.Id).GeneratedBy.Assigned().UnsavedValue(Guid.Empty);
        References(e => e.Project)
            .Column("ProjectId")
            .LazyLoad(Laziness.Proxy);
        HasManyToMany(x => x.Participants)
            .Table("ProjectGroupParticipants")
            .ParentKeyColumn("ProjectGroupId")
            .ChildKeyColumn("ProjectParticipantId")
            .ApplyChildFilter(DeletedDateFilter.FilterName);
</code>```

The tables are:

```<code>[ProjectParticipants] 1-->M [ProjectGroupParticipants] M<--1 [ProjectGroups]
              M                                                   M
              \---------------->1 [Project] 1<--------------------/
</code>```

Here are the SQLs being run by nHibernate:

```<code>--presume this is adding the first participant - I find him in the db
INSERT INTO ProjectParticipants (CreatedDate, ModifiedDate, DeletedDate, FirstName, LastName, Timezone, Email, Pseudonym, Role, ProjectId, UserId, MobileNumber, Id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

--presume this is adding the second participant - I find her in the DB
INSERT INTO ProjectParticipants (CreatedDate, ModifiedDate, DeletedDate, FirstName, LastName, Timezone, Email, Pseudonym, Role, ProjectId, UserId, MobileNumber, Id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

--not sure what this is doing
UPDATE Projects SET CreatedDate = ?, ModifiedDate = ?, LogoUrl = ?, LogoFilename = ?, Client = ?, Name = ?, Description = ?, LastAccessedDate = ? WHERE Id = ?

--not sure what this operation is for, but at this point in time NO GROUP EXISTs for this project ID
SELECT … FROM ProjectGroups groups0_ WHERE groups0_.ProjectId=?

--not sure what this is for either?
UPDATE Projects SET CreatedDate = ?, ModifiedDate = ?, LogoUrl = ?, LogoFilename = ?, Client = ?, Name = ?, Description = ?, LastAccessedDate = ? WHERE Id = ?

-- I've no idea why this is an UPDATE instead of an INSERT, but it will certainly update 0 rows instead of X, because no groups exist
UPDATE ProjectGroups SET CreatedDate = ?, ModifiedDate = ?, DeletedDate = ?, Name = ?, ProjectId = ? WHERE Id = ?
Exception thrown: 'NHibernate.StaleStateException' in NHibernate.dll
Batch update returned unexpected row count from update; actual row count: 0; expected: 3
[ UPDATE ProjectGroups SET CreatedDate = @p0, ModifiedDate = @p1, DeletedDate = @p2, Name = @p3, ProjectId = @p4 WHERE Id = @p5 ]
</code>```

So why did nHibernate come to think that its local entity had already ben saved and was hence available to UPDATE? The SQL generated should be an insert, but I'm not sure how it manages sync between local cache and DB to know if entities already exist or not

Slightly puzzled, that this used to work in NH 2.x, but since an upgrade to latest (5.x) this exception has started appearing.

答:
Slightly puzzled, that this used to work in NH 2.x,

Handling of unsaved-value was indeed changed in 5.2 with this pull request.
If I understand correctly this PR fixed some cases where provided unsaved-value mapping was ignored for assigned identifiers.

So it seems you have incorrect unsaved-value mapping for your entities with assigned identifier. From given data it's unclear how your expect NHibernate to determine if entity is transient. With your mapping if Id is not equal to Guid.Empty NHibernate will trigger UPDATE statement for all cascaded entities and it seems that's exact behavior you see.
If you want it to check database when entity is not present in session - set it to "undefined" instead:

```<code>Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue("undefined");
</code>```

If you want it to always save entity - set it to "any".

Read spec with explanations for all other possible values. Also check this similar issue.

Body:
A projectparticipant may be a member of many groups and a group may have many projectparticipants

I'm finding that when I create 2 ProjectParticipants (this works) and then populate the Project.Groups collection with 3 new groups and add the participants to the relevant groups (Group A has participant 1, Group B has participant 2, Group C has participants 1 and 2), I encounter a "StaleStateException - Batch update returned unexpected row count from update; actual row count: 0, expected: 3". I would expect nHibernate to INSERT the new groups but it's running an UPDATE query and balking that they don't exist. It doesn't get as far as assigning the the participants to the groups

Here are the mappings:

//ProjectMap: A Project..
        Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);
        HasMany(x => x.Participants)
            .Table("ProjectParticipants")
            .KeyColumn("ProjectId")
            .ApplyFilter(DeletedDateFilter.FilterName)
            .Cascade.AllDeleteOrphan()
            .Inverse();

        HasMany(x => x.Groups)
            .Table("ProjectGroups")
            .KeyColumn("ProjectId")
            .Cascade.AllDeleteOrphan()
            .Inverse();

//ProjectParticipantMap: A ProjectParticipant…
        Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue(Guid.Empty);
        References(x => x.Project)
            .Column("ProjectId")
            .LazyLoad(Laziness.Proxy);
        HasManyToMany(x => x.Groups)
            .Table("ProjectGroupParticipants")
            .ParentKeyColumn("ProjectParticipantId")
            .ChildKeyColumn("ProjectGroupId");

//GroupMap: A Group...
        Id(e => e.Id).GeneratedBy.Assigned().UnsavedValue(Guid.Empty);
        References(e => e.Project)
            .Column("ProjectId")
            .LazyLoad(Laziness.Proxy);
        HasManyToMany(x => x.Participants)
            .Table("ProjectGroupParticipants")
            .ParentKeyColumn("ProjectGroupId")
            .ChildKeyColumn("ProjectParticipantId")
            .ApplyChildFilter(DeletedDateFilter.FilterName);

The tables are:

[ProjectParticipants] 1-->M [ProjectGroupParticipants] M<--1 [ProjectGroups]
              M                                                   M
              \---------------->1 [Project] 1<--------------------/

Here are the SQLs being run by nHibernate:

--presume this is adding the first participant - I find him in the db
INSERT INTO ProjectParticipants (CreatedDate, ModifiedDate, DeletedDate, FirstName, LastName, Timezone, Email, Pseudonym, Role, ProjectId, UserId, MobileNumber, Id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

--presume this is adding the second participant - I find her in the DB
INSERT INTO ProjectParticipants (CreatedDate, ModifiedDate, DeletedDate, FirstName, LastName, Timezone, Email, Pseudonym, Role, ProjectId, UserId, MobileNumber, Id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

--not sure what this is doing
UPDATE Projects SET CreatedDate = ?, ModifiedDate = ?, LogoUrl = ?, LogoFilename = ?, Client = ?, Name = ?, Description = ?, LastAccessedDate = ? WHERE Id = ?

--not sure what this operation is for, but at this point in time NO GROUP EXISTs for this project ID
SELECT … FROM ProjectGroups groups0_ WHERE groups0_.ProjectId=?

--not sure what this is for either?
UPDATE Projects SET CreatedDate = ?, ModifiedDate = ?, LogoUrl = ?, LogoFilename = ?, Client = ?, Name = ?, Description = ?, LastAccessedDate = ? WHERE Id = ?

-- I've no idea why this is an UPDATE instead of an INSERT, but it will certainly update 0 rows instead of X, because no groups exist
UPDATE ProjectGroups SET CreatedDate = ?, ModifiedDate = ?, DeletedDate = ?, Name = ?, ProjectId = ? WHERE Id = ?
Exception thrown: 'NHibernate.StaleStateException' in NHibernate.dll
Batch update returned unexpected row count from update; actual row count: 0; expected: 3
[ UPDATE ProjectGroups SET CreatedDate = @p0, ModifiedDate = @p1, DeletedDate = @p2, Name = @p3, ProjectId = @p4 WHERE Id = @p5 ]

So why did nHibernate come to think that its local entity had already ben saved and was hence available to UPDATE? The SQL generated should be an insert, but I'm not sure how it manages sync between local cache and DB to know if entities already exist or not

Slightly puzzled, that this used to work in NH 2.x, but since an upgrade to latest (5.x) this exception has started appearing.

Body:
Slightly puzzled, that this used to work in NH 2.x,

Handling of unsaved-value was indeed changed in 5.2 with this pull request.
If I understand correctly this PR fixed some cases where provided unsaved-value mapping was ignored for assigned identifiers.

So it seems you have incorrect unsaved-value mapping for your entities with assigned identifier. From given data it's unclear how your expect NHibernate to determine if entity is transient. With your mapping if Id is not equal to Guid.Empty NHibernate will trigger UPDATE statement for all cascaded entities and it seems that's exact behavior you see.
If you want it to check database when entity is not present in session - set it to "undefined" instead:

Id(x => x.Id).GeneratedBy.GuidComb().UnsavedValue("undefined");

If you want it to always save entity - set it to "any".

Read spec with explanations for all other possible values. Also check this similar issue.


问:
Regexp JS from referrer
I need to check if a referrer has word "profile" i need to put profile/(.*?) in a var. How can I do it in js?</p>

```<code><script type="text/javascript">
var ref = document.referrer;
if( ~ref.indexOf("profile") ) {
  alert('coincidence found!');
}

 </script>
</code>```

答:
```<code>var ref = document.referrer;
ref.match(/(?:profile).+/,(match)=> {
    console.log(match)
})
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regexp JS from referrer


问:
How to fix "ValueError: not enough values to unpack (expected 2, got 1)"
I am trying to make a music app using tkinter and python, but I am not able to get rid of "ValueError: not enough values to unpack (expected 2, got 1)" bug. Have a look at my code and you'd be much clear with what I am dealing. </p>

<p>The mechanism is pretty simple, I, at first, display the song options via dictionary(list), and after taking the input, corresponding value of "j",(example, if input is 1 then j is one and corresponding value of j is i) to be saved as the name of the song and execute the program by playing the music.  </p>

```<code>list = {
    '1':'Say You Won t Let Go.mp3','2':'In the Jungle the mighty jungle.mp3'
}
lost = ''
print(list)
print("which one?")
this_one = int(input(''))
for j,i in list:
    if j == this_one:
        lost = i
</code>```

答:
Here you go,

```<code>songs = {"1": "Say You Won t Let Go.mp3",
         "2": "In the Jungle the mighty jungle.mp3"}
lost = ''
print(songs)
this_one = int(input("Which One? "))

for number, song in songs.items():
    if number == this_one:
        lost = song
</code>```

dict.items() returns a tuple of 2 objects, (Keys, values).

Body:
I am trying to make a music app using tkinter and python, but I am not able to get rid of "ValueError: not enough values to unpack (expected 2, got 1)" bug. Have a look at my code and you'd be much clear with what I am dealing.

The mechanism is pretty simple, I, at first, display the song options via dictionary(list), and after taking the input, corresponding value of "j",(example, if input is 1 then j is one and corresponding value of j is i) to be saved as the name of the song and execute the program by playing the music.

list = {
    '1':'Say You Won t Let Go.mp3','2':'In the Jungle the mighty jungle.mp3'
}
lost = ''
print(list)
print("which one?")
this_one = int(input(''))
for j,i in list:
    if j == this_one:
        lost = i

Body:
Here you go,

songs = {"1": "Say You Won t Let Go.mp3",
         "2": "In the Jungle the mighty jungle.mp3"}
lost = ''
print(songs)
this_one = int(input("Which One? "))

for number, song in songs.items():
    if number == this_one:
        lost = song

dict.items() returns a tuple of 2 objects, (Keys, values).


问:
Notification is set immediately in Android
Call to method:

```<code>initNotificatie(endDate.getTime());
            Log.d("temp", "end: " + endDate.toGMTString()); // end: 13 Apr 2011 12:45:00 GMT
</code>```

The method:

```<code>    public void initNotificatie(long when)      {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.herinnering_button_dropdown;
        String contentTitleString = getString(R.string.notification_title);
        String contentTekstString = getString(R.string.notification_tekst);
        CharSequence tickerText = "NotificationTekst";

        Notification notification = new Notification(icon, tickerText, when);

        Context context = getApplicationContext();
        CharSequence contentTitle = contentTitleString;
        CharSequence contentText = contentTekstString;
        Intent notificationIntent = new Intent(this, MapDashboardActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        final int HELLO_ID = 1;
        mNotificationManager.notify(HELLO_ID, notification);
}
</code>```

How come this notification is set immediately while the notification is set for tomorrow? Is this because the notification constructor I'm using is deprecated? I can only use that one because I'm programming on level 4.

答: The when parameter refers to the time to be shown in the time field. It is not the time at which notification should be shown. In order to do that, use AlarmManager.

Body:
Call to method:

initNotificatie(endDate.getTime());
            Log.d("temp", "end: " + endDate.toGMTString()); // end: 13 Apr 2011 12:45:00 GMT

The method:

    public void initNotificatie(long when)      {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.herinnering_button_dropdown;
        String contentTitleString = getString(R.string.notification_title);
        String contentTekstString = getString(R.string.notification_tekst);
        CharSequence tickerText = "NotificationTekst";

        Notification notification = new Notification(icon, tickerText, when);

        Context context = getApplicationContext();
        CharSequence contentTitle = contentTitleString;
        CharSequence contentText = contentTekstString;
        Intent notificationIntent = new Intent(this, MapDashboardActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        final int HELLO_ID = 1;
        mNotificationManager.notify(HELLO_ID, notification);
}

How come this notification is set immediately while the notification is set for tomorrow? Is this because the notification constructor I'm using is deprecated? I can only use that one because I'm programming on level 4.


问:
Combine rows in postgres
I have a table with the following columns: date, type, area, district
I want the select output to look like this: date, type1_area, type2_area, district
I understand the first step is a groupby over date and district but I don’t know how to combine the values into a single row.

Any help will be greatly appreciated.

答:
Your textual description seems to imply that you want a query along these lines:</p>

```<code>select
    date,
    string_agg(type || '_' || area, ', ' order by type) type_area,
    district
from your_table
group by
    date,
    area,
    district;
</code>```

Title: Combine rows in postgres

Body:
Your textual description seems to imply that you want a query along these lines:

select
    date,
    string_agg(type || '_' || area, ', ' order by type) type_area,
    district
from your_table
group by
    date,
    area,
    district;


问:
Do not able to link fxml and controller file variable in javafx
There are two files user.fxml and userListPaneFx.java. in this scenario the error is come from userListView variable.  i have written things right but the error comes for null pointer exception. so what can i do for this problem. There is no miss match between spells of two variables.

Error statement

```<code>Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$358(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 48 more
Caused by: java.lang.NullPointerException
    at com.automated.chat_app.UserListPaneFx.<init>(UserListPaneFx.java:38)
    at com.automated.chat_app.LoginController.Login(LoginController.java:28)
    ... 58 more

</code>```

Code of userListPaneFx.java

```<code> package com.automated.chat_app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.collections.*;
import javafx.fxml.*;

public class UserListPaneFx implements UserStatusListner {

    private ChatClient client;
    @FXML
    public javafx.scene.control.ListView userListView;

    public UserListPaneFx(final ChatClient client) throws IOException
    {
        this.client = client;
        this.client.online_user(this);
        ObservableList<String> userList = FXCollections.observableArrayList();
        System.out.println("Hello World");
         Parent root = FXMLLoader.load(getClass().getResource("user.fxml"));
         Stage primaryStage = new Stage();
          primaryStage.setTitle("UserList");
          primaryStage.setScene(new Scene(root,315,557));
          primaryStage.show();
          userList.addAll("Hello World","HiiMohan");
          System.out.println(userListView);
          userListView.getItems().addAll(userList);
    }

    public UserListPaneFx()
    {

    }

    @Override
    public void online(String login) {
        userListView.getItems().add(login);
    }

    @Override
    public void offline(String login) {
        userListView.getItems().remove(login);
    }

}

</code>```

code user.fxml file

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="485.0" prefWidth="279.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.automated.chat_app.UserListPaneFx">
   <children>
      <ListView id="userListView" fx:id="userListView" prefHeight="485.0" prefWidth="279.0" />
   </children>
</AnchorPane>

</code>```

答: You can define a sepreate controller and can manage things easily. in your scenario From FXMLLodar you are calling another instance of the same class so that's way this scenario is giving NPE.</p>

Body:
There are two files user.fxml and userListPaneFx.java. in this scenario the error is come from userListView variable.  i have written things right but the error comes for null pointer exception. so what can i do for this problem. There is no miss match between spells of two variables.

Error statement

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$358(GlassViewEventHandler.java:432)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$152(WinApplication.java:177)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 48 more
Caused by: java.lang.NullPointerException
    at com.automated.chat_app.UserListPaneFx.<init>(UserListPaneFx.java:38)
    at com.automated.chat_app.LoginController.Login(LoginController.java:28)
    ... 58 more

Code of userListPaneFx.java

 package com.automated.chat_app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.collections.*;
import javafx.fxml.*;

public class UserListPaneFx implements UserStatusListner {

    private ChatClient client;
    @FXML
    public javafx.scene.control.ListView userListView;

    public UserListPaneFx(final ChatClient client) throws IOException
    {
        this.client = client;
        this.client.online_user(this);
        ObservableList<String> userList = FXCollections.observableArrayList();
        System.out.println("Hello World");
         Parent root = FXMLLoader.load(getClass().getResource("user.fxml"));
         Stage primaryStage = new Stage();
          primaryStage.setTitle("UserList");
          primaryStage.setScene(new Scene(root,315,557));
          primaryStage.show();
          userList.addAll("Hello World","HiiMohan");
          System.out.println(userListView);
          userListView.getItems().addAll(userList);
    }

    public UserListPaneFx()
    {

    }

    @Override
    public void online(String login) {
        userListView.getItems().add(login);
    }

    @Override
    public void offline(String login) {
        userListView.getItems().remove(login);
    }

}

code user.fxml file

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="485.0" prefWidth="279.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.automated.chat_app.UserListPaneFx">
   <children>
      <ListView id="userListView" fx:id="userListView" prefHeight="485.0" prefWidth="279.0" />
   </children>
</AnchorPane>


问:
Continuously running Python code for Pimoroni buttonshim on Raspberry Pi causing freezing
I am using a Raspberry Pi 3B+ to display a website/websites on a screen, and recently attached a Pimoroni Button-Shim.

Since writing some Python code (below) I have had the buttons working, but the Raspberry Pi seems to freeze after about 18 hours. I've never been around to see it happen, but on returning it has now been frozen three times.

It never did this before I wrote this code, and assume it probably has something to do with poorly written code, rather than the soldering itself.

I have a bit of experience with Python, but never with continuously running programs, and handlers are a new concept for me.

The code is Python 3, using the library provided by Pimoroni, and starts via LXDE-pi/autostart.

If you have any idea on how to help that would be greatly appreciated, I've had a bit of a google, but don't really know any resources or what to type in to find a solution.

It works immediately on hard reboot, and I'm not really sure where to go next.

#!usr/bin/python3
import buttonshim
from time import sleep
import os

sleep(10)
os.system('chromium-browser --noerrdialogs --incognito --kiosk  url1')
buttonshim.set_pixel(221,36,33)

@buttonshim.on_press(buttonshim.BUTTON_A)
def handler(button, pressed):
    os.system('pkill chromium-browser')
    os.system('chromium-browser --noerrdialogs --incognito --kiosk https://www.nytimes.com')
    buttonshim.set_pixel(33, 106, 224)

@buttonshim.on_press(buttonshim.BUTTON_B)
def handler(button, pressed):
    os.system('pkill chromium-browser')
    os.system('chromium-browser --noerrdialogs --incognito --kiosk url1')
    buttonshim.set_pixel(0xFF, 0x00, 0xFF)

@buttonshim.on_press(buttonshim.BUTTON_C)
def handler(button, pressed):
    os.system('vcgencmd display_power 0')

@buttonshim.on_press(buttonshim.BUTTON_D)
def handler(button, pressed):
    os.system('vcgencmd display_power 1')

while True:
    sleep(10)
```

The code works as expected at the start, but eventually doesn't.

答:
Follow up:

I increased sleep length significantly - to 2000 and followed the instructions in another discussion about the numpy library taking up a large amount of CPU - link

since then I have not had trouble with freezing

Body:
I am using a Raspberry Pi 3B+ to display a website/websites on a screen, and recently attached a Pimoroni Button-Shim.

Since writing some Python code (below) I have had the buttons working, but the Raspberry Pi seems to freeze after about 18 hours. I've never been around to see it happen, but on returning it has now been frozen three times.

It never did this before I wrote this code, and assume it probably has something to do with poorly written code, rather than the soldering itself.

I have a bit of experience with Python, but never with continuously running programs, and handlers are a new concept for me.

The code is Python 3, using the library provided by Pimoroni, and starts via LXDE-pi/autostart.

If you have any idea on how to help that would be greatly appreciated, I've had a bit of a google, but don't really know any resources or what to type in to find a solution.

It works immediately on hard reboot, and I'm not really sure where to go next.

#!usr/bin/python3
import buttonshim
from time import sleep
import os

sleep(10)
os.system('chromium-browser --noerrdialogs --incognito --kiosk  url1')
buttonshim.set_pixel(221,36,33)

@buttonshim.on_press(buttonshim.BUTTON_A)
def handler(button, pressed):
    os.system('pkill chromium-browser')
    os.system('chromium-browser --noerrdialogs --incognito --kiosk https://www.nytimes.com')
    buttonshim.set_pixel(33, 106, 224)

@buttonshim.on_press(buttonshim.BUTTON_B)
def handler(button, pressed):
    os.system('pkill chromium-browser')
    os.system('chromium-browser --noerrdialogs --incognito --kiosk url1')
    buttonshim.set_pixel(0xFF, 0x00, 0xFF)

@buttonshim.on_press(buttonshim.BUTTON_C)
def handler(button, pressed):
    os.system('vcgencmd display_power 0')

@buttonshim.on_press(buttonshim.BUTTON_D)
def handler(button, pressed):
    os.system('vcgencmd display_power 1')

while True:
    sleep(10)

The code works as expected at the start, but eventually doesn't.


问:
How to attribution values of javascript arraylist to java arraylist in the same html page
I have a javascript Arraylist like this:

```<code>var javaScriptArray = $('#sortable').sortable("toArray"); // array of sortable elements
</code>```

And I want to send this javascript Arraylist to java arrayList in the same jsp page

```<code><% List <String> javaList ;
   javaList = javaScriptArray;
%>
</code>```

How can I do that?

答:
I think you are doing it in a wrong way. As I have understand from your description and I want to send this javascript Arraylist to java arrayList in the same jsp page you want to pass a value from javascript directly to your jsp variable that is on the same page.

Always remember, JSP(JSF, other)/Pearl/Python/PHP and a like were server script(Server side) while Javascript is a client script(Client side).

This mean that you can pass the value from the server script to client script(Not a good practice) BEFORE the response/page were rendered to the client using <%= "Hello" %> or similar. But you CANNOT pass the value from the client to server which have ALREADY rendered the page to the client where the server is not aware of what is happening on the client.

It is like, when you order pizza from phone, the one that does the packing knows exactly what are on the box. But He/she will not know what will be added to it once it reaches you(the one who ordered it).

And to address your problem of passing of value from client to server. You have to pass the value from client to server using GET, POST, and other HTTP methods. This way, the server will be notified that the value of JavaScript changed. This is only good in passing value to notify the server to save/update/delete a record from the server.

This image will be helpful on how Client/Server interact to each other.

Body:
I have a javascript Arraylist like this:

var javaScriptArray = $('#sortable').sortable("toArray"); // array of sortable elements

And I want to send this javascript Arraylist to java arrayList in the same jsp page

<% List <String> javaList ;
   javaList = javaScriptArray;
%>

How can I do that?


问:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 360-362: ordinal not in range(128)
I tried running python via PHP I kept getting

UnicodeEncodeError: 'ascii' codec can't encode characters in position 360-362: ordinal not in range(128)

I tried

php

```<code>$command = "python ".public_path().'/python/start_clientsim.py 2>&1';
$result = exec($command);
</code>```

python (start_clientsim.py)

```<code>import paramiko
import time
import sys
import os
import pdb

# Note
# sudo pip install --user paramiko

ip = "172.1.1.1"
un = "root"
pw = "123"
key_filename='/Users/keys/id_rsa'

def ssh_con (ip, un, pw):
    global ssh
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=un, password=pw, key_filename=key_filename)

def cmd_io (command):
    global ssh_cmd
    ssh_cmd.send("%s \n" %command)
    time.sleep(1)
    output = ssh_cmd.recv(10000).decode("utf-8")
    print (output)

ssh_con(ip,un,pw)
ssh_cmd = ssh.invoke_shell()

cmd_io("clientsim cli")
cmd_io("start subscriber-group dth-sub start-traffic udp")
cmd_io("exit")
</code>```

答:
Please check LANG in environmental variables as followed.

```<code>function runCommand($cmd, &$retval) {
  syslog(LOG_WARNING, $cmd);
  $retval = array();
  exec($cmd, $retval);
  $log = implode("\n", $retval);
  syslog(LOG_WARNING, $log);
  return $log;
}
echo(runCommand("env", $retval));
</code>```

I checked my server on Ubuntu 18.04, it returned LANG=C. So I added an environmental setting for LANG.

```<code>runCommand("LANG=en_US.UTF-8 PYTHONIOENCODING=utf-8 python yourcode.py", $retval);
</code>```

Body:
I tried running python via PHP I kept getting

UnicodeEncodeError: 'ascii' codec can't encode characters in position 360-362: ordinal not in range(128)

I tried

php

$command = "python ".public_path().'/python/start_clientsim.py 2>&1';
$result = exec($command);

python (start_clientsim.py)

import paramiko
import time
import sys
import os
import pdb

# Note
# sudo pip install --user paramiko

ip = "172.1.1.1"
un = "root"
pw = "123"
key_filename='/Users/keys/id_rsa'

def ssh_con (ip, un, pw):
    global ssh
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=un, password=pw, key_filename=key_filename)

def cmd_io (command):
    global ssh_cmd
    ssh_cmd.send("%s \n" %command)
    time.sleep(1)
    output = ssh_cmd.recv(10000).decode("utf-8")
    print (output)

ssh_con(ip,un,pw)
ssh_cmd = ssh.invoke_shell()

cmd_io("clientsim cli")
cmd_io("start subscriber-group dth-sub start-traffic udp")
cmd_io("exit")

Body:
Please check LANG in environmental variables as followed.

function runCommand($cmd, &$retval) {
  syslog(LOG_WARNING, $cmd);
  $retval = array();
  exec($cmd, $retval);
  $log = implode("\n", $retval);
  syslog(LOG_WARNING, $log);
  return $log;
}
echo(runCommand("env", $retval));

I checked my server on Ubuntu 18.04, it returned LANG=C. So I added an environmental setting for LANG.

runCommand("LANG=en_US.UTF-8 PYTHONIOENCODING=utf-8 python yourcode.py", $retval);


问:
How to check whether the first array entry is empty in VBA
The below VBA code sets a range of cells as commentArray, removes any blanks from the array and creates a new, blank free array, called commentResults. I then want to declare the array.

There is a possibility, depending on my source data, that the array could then still be empty so the below doesn't work to declare

```<code>thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
</code>```

So I thought I would add a check (the if statement after the debug.print), that only declared the array if array(0) wasn't empty but I continuously get an error 9 which I can't resolve.

```<code>Dim commentArray(4) As Variant
    commentArray(0) = Cells(24, 4).Value
    commentArray(1) = Cells(25, 3).Value
    commentArray(2) = Cells(26, 3).Value
    commentArray(3) = Cells(27, 3).Value

'a and b as array loops
Dim a As Long, b As Long
Dim commentResults() As Variant

'loops through the array to remove blanks - rewrites array without blanks into commentArray
For a = LBound(commentArray) To UBound(commentArray)
    If commentArray(a) <> vbNullString Then
        ReDim Preserve commentResults(b)
        commentResults(b) = commentArray(a)
        b = b + 1
    End If
Next a

Debug.Print b

If IsError(Application.Match("*", (commentResults), 0)) Then
Else
    thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
    b = 0
End If
</code>```

Any thoughts on why this might not work?

I have also tried:

```<code>If commentResults(0) <> vbNullString Then
    thisws.Cells(i, 27).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
End If
</code>```

答:
```<code>Sub CommentArray()

Dim Comments As Range, c As Range
Set Comments = Union(Cells(24, 4), Range(Cells(25, 3), Cells(27, 3)))

Dim commentResults() As Variant
Dim i As Long

i = 0
For Each cell In Comments
    If cell.Value <> "" Then
        ReDim Preserve commentResults(i)
        commentResults(i) = cell.Value
        i = i + 1
    End If
Next cell

Dim debugStr As String

For i = LBound(commentResults) To UBound(commentResults)
    debugStr = debugStr & commentResults(i) & Chr(10)
Next i

MsgBox debugStr

End Sub
</code>```

Body:
The below VBA code sets a range of cells as commentArray, removes any blanks from the array and creates a new, blank free array, called commentResults. I then want to declare the array.

There is a possibility, depending on my source data, that the array could then still be empty so the below doesn't work to declare

thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults

So I thought I would add a check (the if statement after the debug.print), that only declared the array if array(0) wasn't empty but I continuously get an error 9 which I can't resolve.

Dim commentArray(4) As Variant
    commentArray(0) = Cells(24, 4).Value
    commentArray(1) = Cells(25, 3).Value
    commentArray(2) = Cells(26, 3).Value
    commentArray(3) = Cells(27, 3).Value

'a and b as array loops
Dim a As Long, b As Long
Dim commentResults() As Variant

'loops through the array to remove blanks - rewrites array without blanks into commentArray
For a = LBound(commentArray) To UBound(commentArray)
    If commentArray(a) <> vbNullString Then
        ReDim Preserve commentResults(b)
        commentResults(b) = commentArray(a)
        b = b + 1
    End If
Next a

Debug.Print b

If IsError(Application.Match("*", (commentResults), 0)) Then
Else
    thisws.Cells(i, 19).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
    b = 0
End If

Any thoughts on why this might not work?

I have also tried:

If commentResults(0) <> vbNullString Then
    thisws.Cells(i, 27).Resize(columnsize:=UBound(commentResults) - LBound(commentResults) + 1).Value = commentResults
End If


问:
how could i get date from varchar column in mysql
I want to get date from VARCHAR column.

(eg: 4/14/2018 12:00:00 AM)

How do I display only date

(eg: 4/14/2018)?

```<code>SELECT date(created_at) from self_balance
</code>```

here created_at(varchar)

this returns NULL value

答:
You can fetch date like a normal string from the database then you need to use strtotime which parses an English textual DateTime into a Unix timestamp. Then you can use
date function which returns the formatted date string.
I have passed a static string. You can pass your string variable which you are fetching from the database
$time = strtotime($date_string_from_database);

```<code><?php
$time = strtotime('4/14/2018 12:00:00 AM');

$newformat = date('m/d/Y',$time);

echo $newformat;
?>
</code>```

You can see the live demo here

Body:
I want to get date from VARCHAR column.

(eg: 4/14/2018 12:00:00 AM)

How do I display only date

(eg: 4/14/2018)?

SELECT date(created_at) from self_balance

here created_at(varchar)

this returns NULL value

Body:
You can fetch date like a normal string from the database then you need to use strtotime which parses an English textual DateTime into a Unix timestamp. Then you can use
date function which returns the formatted date string.
I have passed a static string. You can pass your string variable which you are fetching from the database
$time = strtotime($date_string_from_database);

<?php
$time = strtotime('4/14/2018 12:00:00 AM');

$newformat = date('m/d/Y',$time);

echo $newformat;
?>

You can see the live demo here


问:
Configuring mail sender using Java configuration in Spring Cloud AWS
I want to send emails using Amazon SES, Spring Cloud AWS and Spring Boot 2.1.5.

In the documentation, it provides XML to configure the mail sender. Is there any way to use Java config instead of XML?

答:
Got it to work, here's what I did.

Build dependencies

```<code>    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.cloud:spring-cloud-starter-aws'
    implementation 'com.amazonaws:aws-java-sdk-ses'
</code>```

Config bean

```<code>@Configuration
public class AwsConfig {

    @Bean
    public AmazonSimpleEmailService amazonSimpleEmailService(AWSCredentialsProvider credentialsProvider) {
         return AmazonSimpleEmailServiceClientBuilder.standard()
            .withCredentials(credentialsProvider)
            .withRegion(Regions.EU_WEST_1).build();
    }

    @Bean
    public MailSender mailSender(AmazonSimpleEmailService ses) {
        return new SimpleEmailServiceMailSender(ses);
    }
}
</code>```

NotificationService

```<code>@Service
public class NotificationService {

    @Autowired
    private MailSender mailSender;

    public void sendMailMessage() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("sender@mail.com");
        simpleMailMessage.setTo("to@mail.com");
        simpleMailMessage.setSubject("test subject");
        simpleMailMessage.setText("test text");
        this.mailSender.send(simpleMailMessage);
    }
}
</code>```

application.yml

```<code>cloud:
  aws:
    credentials:
      accessKey: <YOUR_ACCESS_KEY>
      secretKey: <YOUR_SECRET_KEY>
    stack:
      auto: false
</code>```

Hope this helps.

Body:
Got it to work, here's what I did.

Build dependencies

    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.cloud:spring-cloud-starter-aws'
    implementation 'com.amazonaws:aws-java-sdk-ses'

Config bean

@Configuration
public class AwsConfig {

    @Bean
    public AmazonSimpleEmailService amazonSimpleEmailService(AWSCredentialsProvider credentialsProvider) {
         return AmazonSimpleEmailServiceClientBuilder.standard()
            .withCredentials(credentialsProvider)
            .withRegion(Regions.EU_WEST_1).build();
    }

    @Bean
    public MailSender mailSender(AmazonSimpleEmailService ses) {
        return new SimpleEmailServiceMailSender(ses);
    }
}

NotificationService

@Service
public class NotificationService {

    @Autowired
    private MailSender mailSender;

    public void sendMailMessage() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("sender@mail.com");
        simpleMailMessage.setTo("to@mail.com");
        simpleMailMessage.setSubject("test subject");
        simpleMailMessage.setText("test text");
        this.mailSender.send(simpleMailMessage);
    }
}

application.yml

cloud:
  aws:
    credentials:
      accessKey: <YOUR_ACCESS_KEY>
      secretKey: <YOUR_SECRET_KEY>
    stack:
      auto: false

Hope this helps.


问:
Adding React-Redux to a helper function
I have a helper function which is utilized by two components in my React app. And this helper function dispatches a set of Redux actions. How do I connect React-Redux to this helper function so that it can dispatch actions?

My helper looks like this:

```<code>export default const helper = () => {
   //dispatch some actions
   // I would like to do something similar to  this: this.props.dispatch()
   //do something else(produce some JSX)
}
</code>```

My component look like this:

```<code> import helper from './helper.js';

 export default class Example extends React.Component {
   return (
      {helper()}
   );
 }
</code>```

My component 1 look like this when the helper is defined inside the component itself:

```<code> import { setTime } from '../actions/setTime.js';

 class Example1 extends React.Component {
   helper() {
     //actions are synchronous
     this.props.setTime('10:00PM');

     return (<h1>hello</h1>);
   }

   render() {
     return (
      <h1>something</h1>
      {helper()}
     );
   }
 }

 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

 export default connect(null, mapDispatchToProps)(Example1);
</code>```

My component 2 look like this when the helper is defined inside the component itself:

```<code> import { setTime } from '../actions/setTime.js';

 class Example2 extends React.Component {
   helper() {
     //actions are synchronous
     this.props.setTime('10:00PM');

     return (<h1>hello</h1>);
   }

   render() {
     return (
      {helper()}
     );
   }
 }

 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

 export default connect(null, mapDispatchToProps)(Example2);
</code>```

Example1 and Example2 renders based on Route change. You might be thinking I can use the higher order component but I cannot because these two components have different state and renders different things.

Please note that I want to have access to the dispatch function in the helper method and I am not accessing Redux state from that component so I do not have to worry about state change(mapStateToProps is not in use).

答:
I had a similar problem, i resolve it by passing this to helper function.
If u need to dispatch it by action something like example could help.

```<code>export default const helper = (that) => {
   return <button onClick={()=>that.props.YourDispatch()}/>
}

import helper from './helper.js';

export default class Example extends React.Component {
   return (
      {helper(this)}
   );
}
</code>```

Title: Adding React-Redux to a helper function

Body:
I have a helper function which is utilized by two components in my React app. And this helper function dispatches a set of Redux actions. How do I connect React-Redux to this helper function so that it can dispatch actions?

My helper looks like this:

export default const helper = () => {
   //dispatch some actions
   // I would like to do something similar to  this: this.props.dispatch()
   //do something else(produce some JSX)
}

My component look like this:

 import helper from './helper.js';

 export default class Example extends React.Component {
   return (
      {helper()}
   );
 }

My component 1 look like this when the helper is defined inside the component itself:

 import { setTime } from '../actions/setTime.js';

 class Example1 extends React.Component {
   helper() {
     //actions are synchronous
     this.props.setTime('10:00PM');

     return (
hello
);
   }

   render() {
     return (

something

      {helper()}
     );
   }
 }

 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

 export default connect(null, mapDispatchToProps)(Example1);

My component 2 look like this when the helper is defined inside the component itself:

 import { setTime } from '../actions/setTime.js';

 class Example2 extends React.Component {
   helper() {
     //actions are synchronous
     this.props.setTime('10:00PM');

     return (
hello
);
   }

   render() {
     return (
      {helper()}
     );
   }
 }

 const mapDispatchToProps = (dispatch) => {
   return {
      setTime: (time) => (dispatch(setTime(time)))
   };
 }

 export default connect(null, mapDispatchToProps)(Example2);

Example1 and Example2 renders based on Route change. You might be thinking I can use the higher order component but I cannot because these two components have different state and renders different things.

Please note that I want to have access to the dispatch function in the helper method and I am not accessing Redux state from that component so I do not have to worry about state change(mapStateToProps is not in use).

Body:
I had a similar problem, i resolve it by passing this to helper function.
If u need to dispatch it by action something like example could help.

export default const helper = (that) => {
   return <button onClick={()=>that.props.YourDispatch()}/>
}

import helper from './helper.js';

export default class Example extends React.Component {
   return (
      {helper(this)}
   );
}


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答: You could try storing the document files in a separate database and use the Simple Recovery Model.  Then you can easily back up the documents database without worrying about  your backups ballooning in size.</p>

OwnerDisplayName: Patrick

ContentLicense: CC BY-SA 2.5

Title: Storing word documents

OwnerDisplayName: ifwdev


问:
Need JS to keep the hover link active
I have a dropdown menu and i need help getting the hover link to stay active when i hover over it so it blends with the dropdown.

I have put the code on JSF

http://jsfiddle.net/JmR87/2/

Thanks

答:
You can fix it by changing this:

```<code>#nav-container li a:hover span {
    display: block;
    background-image: url(http://i.stack.imgur.com/sTqNy.gif);
    background-repeat: repeat-x;
}
</code>```

to this:

```<code>#nav-container li:hover span {
    display: block;
    background-image: url(http://i.stack.imgur.com/sTqNy.gif);
    background-repeat: repeat-x;
    color: #000
}
</code>```

See: http://jsfiddle.net/JmR87/5/

Title: Need JS to keep the hover link active

Body:
You can fix it by changing this:

#nav-container li a:hover span {
    display: block;
    background-image: url(http://i.stack.imgur.com/sTqNy.gif);
    background-repeat: repeat-x;
}

to this:

#nav-container li:hover span {
    display: block;
    background-image: url(http://i.stack.imgur.com/sTqNy.gif);
    background-repeat: repeat-x;
    color: #000
}

See: http://jsfiddle.net/JmR87/5/


问:
why C++ std::min_element library function accepts functor that takes function object of bool return type rather than int like in C?
The C++ standard library function std::min_element() accepts a function object as is last argument, and that object's return type is bool. Why is it not int?

With true or false, we have only two options: < or >, but what if two entries are the same i.e. ==?

In C, this situation is handled by choosing the return type as int. But this is not done for std::min_element() in C++.

What is the reason for this?

答:
What would you gain from that information? The function is supposed to return the smallest element (hence the name min_element). It doesn't need to care about equality, what would you gain from it in the end result? A boolean value is sufficient to tell whether one element is smaller than another. How you handle equality is up to your implementation of that callable.

In the words of cppreference:

```<code>bool cmp(const Type1 &a, const Type2 &b);
</code>```

comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if a is less than b.

Body:
What would you gain from that information? The function is supposed to return the smallest element (hence the name min_element). It doesn't need to care about equality, what would you gain from it in the end result? A boolean value is sufficient to tell whether one element is smaller than another. How you handle equality is up to your implementation of that callable.

In the words of cppreference:

bool cmp(const Type1 &a, const Type2 &b);

comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if a is less than b.


问:
Entity Framework core navigation property between two contexts
There are similar questions with this issue, but not for EF Core. Not a duplicate of Entity Framework Core Using multiple DbContexts . That one is related to not being able to access the database at all from the second context, and the two contexts use different databases. This question is about a single database and the issue is related to migrations

I have two EF core db contexts using the same SQL Server database.

In the first context I have many entities, one of them is User.

In the second one there is a single entity called UserExt which has a navigational property to User

```<code>public class UserExt
{
    [Key]
    public long UserID { get; set; }
    public virtual User User { get; set; }

    [Required]
    public string Address { get; set; }
}
</code>```

The issue is that when creating the migration for UserExt using 'add-migration', all entities from the first context are also included.

Tried providing the context, but same result

```<code>add-migration --context SecondContext
</code>```

With EF 6 it was possible to solve this using ContextKey (https://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigrationsconfiguration.contextkey(v=vs.113).aspx) but has not been ported to EF Core

Is there a way to make this work so that the migrations in the second context would contain only its entities ?

答:
Solved using database context inheritance. This way I can have separate migrations.

public class SecondDbContext : FirstDbContext
{
    public virtual DbSet<UserExt> ExtendedUsers { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
       optionsBuilder.UseSqlServer("connectionString", options =>
            options
               .MigrationsAssembly("SecondDbContextAssemblyName")
               .MigrationsHistoryTable("__SecondEFMigrationsHistory") // separate table to store migration history to avoid conflicts
       );
    }
}
```

Because SecondDbContext is inherited from FirstDbContext, every entity change made in the base context will be inherited. Which means that when a new migration is added to the second context, it will try to apply the changes again from the first context again. Workaround is to:

Add a new migration (for example Add-Migration Inherit_FirstDbContext)

Delete everything from the migration's Up and Down methods

Apply the empty migration in the database. (Update-Database)

This ensures that the Entity Framework snapshot will contain the changes, without actually having to re-apply them in the database.

Body:
There are similar questions with this issue, but not for EF Core. Not a duplicate of Entity Framework Core Using multiple DbContexts . That one is related to not being able to access the database at all from the second context, and the two contexts use different databases. This question is about a single database and the issue is related to migrations

I have two EF core db contexts using the same SQL Server database.

In the first context I have many entities, one of them is User.

In the second one there is a single entity called UserExt which has a navigational property to User

public class UserExt
{
    [Key]
    public long UserID { get; set; }
    public virtual User User { get; set; }

    [Required]
    public string Address { get; set; }
}

The issue is that when creating the migration for UserExt using 'add-migration', all entities from the first context are also included.

Tried providing the context, but same result

add-migration --context SecondContext

With EF 6 it was possible to solve this using ContextKey (https://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigrationsconfiguration.contextkey(v=vs.113).aspx) but has not been ported to EF Core

Is there a way to make this work so that the migrations in the second context would contain only its entities ?

Body:
Solved using database context inheritance. This way I can have separate migrations.

public class SecondDbContext : FirstDbContext
{
    public virtual DbSet<UserExt> ExtendedUsers { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
       optionsBuilder.UseSqlServer("connectionString", options =>
            options
               .MigrationsAssembly("SecondDbContextAssemblyName")
               .MigrationsHistoryTable("__SecondEFMigrationsHistory") // separate table to store migration history to avoid conflicts
       );
    }
}

Because SecondDbContext is inherited from FirstDbContext, every entity change made in the base context will be inherited. Which means that when a new migration is added to the second context, it will try to apply the changes again from the first context again. Workaround is to:

Add a new migration (for example Add-Migration Inherit_FirstDbContext)

Delete everything from the migration's Up and Down methods

Apply the empty migration in the database. (Update-Database)

This ensures that the Entity Framework snapshot will contain the changes, without actually having to re-apply them in the database.


问:
How to insert a row in Javascript with a loop?
I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?

Json file:

```<code>{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
 }
</code>```

My code:

```<code>    var jdata = {};
    jdata.cols = [
        {
            "id": "1",
            "label": "name",
            "type": "string"
        },
        {
            "id": "2",
            "label": "country",
            "type":"string"
        }
    ];

    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.insertRow(row);
    }
</code>```

Edit: Add expected output: change the json file to the following structure.

```<code>[
    ['lily', 'china'],
    ['mike', 'japan'],
    ['lucy', 'korea'],
  ]
</code>```

答:
I guess you need push (Or concat / push(...elements) if you want to add array of rows)</p>

```<code>    jdata.rows = [];
    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.push(row);
        // for elements from row
        // jdata.rows.push(...row)
    }
</code>```

Body:
I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?

Json file:

{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
 }

My code:

    var jdata = {};
    jdata.cols = [
        {
            "id": "1",
            "label": "name",
            "type": "string"
        },
        {
            "id": "2",
            "label": "country",
            "type":"string"
        }
    ];

    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.insertRow(row);
    }

Edit: Add expected output: change the json file to the following structure.

[
    ['lily', 'china'],
    ['mike', 'japan'],
    ['lucy', 'korea'],
  ]

Body:
I guess you need push (Or concat / push(...elements) if you want to add array of rows)

    jdata.rows = [];
    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.push(row);
        // for elements from row
        // jdata.rows.push(...row)
    }