问:
highlighting gridview rows for striped gridview from checkbox
Within the gridview I have, I'm trying to make it so when the user checks a check box for the row the row is highlighted.  Now, this GridView is striped (meaning even rows have one background color and odd rows have another).  This code to do it is floating around the net in various forms...

```<code>
var color = '';
function changeColor(obj) {
  var rowObject = getParentRow(obj);
  var parentTable = document.getElementById("gvCategories");
  if(color == ''){
    color = getRowColor();
  }
  if(obj.checked){
    rowObject.style.backgroundColor = 'Yellow';
  }
  else{
    rowObject.style.backgroundColor = color;
    color = '';
  }

  // private method
  function getRowColor(){
  if(rowObject.style.backgroundColor == '') return parentTable.style.backgroundColor;
  else return rowObject.style.backgroundColor;
  }
}

// This method returns the parent row of the object
function getParentRow(obj){
  do{
    obj = obj.parentElement;
  }
  while(obj.tagName != "TR")
  return obj;
}
</code>```

That's a straight copy and paste from here...
http://aspadvice.com/blogs/azamsharp/archive/2007/06/26/Highlight-GridView-Rows-Using-CheckBox.aspx

This is fine if your GridView isn't striped.  However, as I mentioned earlier mine is striped.  The problem here is if you uncheck a box depending on the order in which you selected items the row background color can revert to the incorrect color.

I've tried thinking of some algorithm to do this but I've had little luck.  My initial thought was some trickery with a stack, but I quickly realized that would require users to uncheck back in the reverse order they checked items.

The only other thing I can think of is somehow checking if the row index is odd or even, and if it's odd revert to a specific color and if it's even revert to a specific color.  However, I'm not sure how to check for specific indexes of a gridview from javascript.

I'm ultimately going to be using jQuery for this so any advice regarding javascript with or without jquery is fine.  Any ideas at all on how to achieve this?

EDIT:  So I'm still not having any luck, I thought I'd post what I currently have.

```<code>
function highlightRow(object) {
    if ($(object).attr("checked") == true) {
        alert('is checked!'); // this will fire
        $(object).parent('tr').addClass("highlightedRow");
    }
    else {
        alert('is not checked!');
        $(object).parent('tr').removeClass("highlightedRow");
    }
}
</code>```

As the comment there says, I can tell if an item is being checked or not but the class toggle just doesn't seem to be being applied.  The highlighted row is declared after the classes it should be overriding in the CSS file.  Does this provide any extra info as to what may be going wrong?

答:
I finally had some time to come back to this issue and I figured it out.  For some reason this bit here...

```<code>$(object).parent('tr')
</code>```

wasn't grabbing the row.  I honestly didn't investigate much into why since this led me to the real issue.

What was happening was the already set background color styling was not being overridden by the styling being set via...

```<code>.addClass('highlight');
</code>```

So, giving the 'highlight' class background styling the important tag did the trick.

```<code>.SpatialDataHighlightedRow {
    background-color: #DDDDDD !important;
}
</code>```

OwnerDisplayName: Carter

Body:
Within the gridview I have, I'm trying to make it so when the user checks a check box for the row the row is highlighted.  Now, this GridView is striped (meaning even rows have one background color and odd rows have another).  This code to do it is floating around the net in various forms...

var color = '';
function changeColor(obj) {
  var rowObject = getParentRow(obj);
  var parentTable = document.getElementById("gvCategories");
  if(color == ''){
    color = getRowColor();
  }
  if(obj.checked){
    rowObject.style.backgroundColor = 'Yellow';
  }
  else{
    rowObject.style.backgroundColor = color;
    color = '';
  }

  // private method
  function getRowColor(){
  if(rowObject.style.backgroundColor == '') return parentTable.style.backgroundColor;
  else return rowObject.style.backgroundColor;
  }
}

// This method returns the parent row of the object
function getParentRow(obj){
  do{
    obj = obj.parentElement;
  }
  while(obj.tagName != "TR")
  return obj;
}

That's a straight copy and paste from here...
http://aspadvice.com/blogs/azamsharp/archive/2007/06/26/Highlight-GridView-Rows-Using-CheckBox.aspx

This is fine if your GridView isn't striped.  However, as I mentioned earlier mine is striped.  The problem here is if you uncheck a box depending on the order in which you selected items the row background color can revert to the incorrect color.

I've tried thinking of some algorithm to do this but I've had little luck.  My initial thought was some trickery with a stack, but I quickly realized that would require users to uncheck back in the reverse order they checked items.

The only other thing I can think of is somehow checking if the row index is odd or even, and if it's odd revert to a specific color and if it's even revert to a specific color.  However, I'm not sure how to check for specific indexes of a gridview from javascript.

I'm ultimately going to be using jQuery for this so any advice regarding javascript with or without jquery is fine.  Any ideas at all on how to achieve this?

EDIT:  So I'm still not having any luck, I thought I'd post what I currently have.

function highlightRow(object) {
    if ($(object).attr("checked") == true) {
        alert('is checked!'); // this will fire
        $(object).parent('tr').addClass("highlightedRow");
    }
    else {
        alert('is not checked!');
        $(object).parent('tr').removeClass("highlightedRow");
    }
}

As the comment there says, I can tell if an item is being checked or not but the class toggle just doesn't seem to be being applied.  The highlighted row is declared after the classes it should be overriding in the CSS file.  Does this provide any extra info as to what may be going wrong?

LastEditorDisplayName: Carter

Body:
I finally had some time to come back to this issue and I figured it out.  For some reason this bit here...

$(object).parent('tr')

wasn't grabbing the row.  I honestly didn't investigate much into why since this led me to the real issue.

What was happening was the already set background color styling was not being overridden by the styling being set via...

.addClass('highlight');

So, giving the 'highlight' class background styling the important tag did the trick.

.SpatialDataHighlightedRow {
    background-color: #DDDDDD !important;
}


来源: stackexchange

问:
android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
The app is crashing when I'm trying to open a file. It works below Android Nougat, but on Android Nougat it crashes. It only crashes when I try to open a file from the SD card, not from the system partition. Some permission problem?

Sample code:

```<code>File file = new File("/storage/emulated/0/test.txt");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); // Crashes on this line
</code>```

Log:

android.os.FileUriExposedException:
  file:///storage/emulated/0/test.txt exposed beyond app through
  Intent.getData()

Edit:

When targeting Android Nougat, file:// URIs are not allowed anymore. We should use content:// URIs instead. However, my app needs to open files in root directories. Any ideas?

答:
i put this method so imageuri path easily get in content.</p>

```<code>enter code here
public Uri getImageUri(Context context, Bitmap inImage)
{
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(context.getContentResolver(),
    inImage, "Title", null);
    return Uri.parse(path);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The app is crashing when I'm trying to open a file. It works below Android Nougat, but on Android Nougat it crashes. It only crashes when I try to open a file from the SD card, not from the system partition. Some permission problem?

Sample code:

File file = new File("/storage/emulated/0/test.txt");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); // Crashes on this line

Log:

android.os.FileUriExposedException:
  file:///storage/emulated/0/test.txt exposed beyond app through
  Intent.getData()

Edit:

When targeting Android Nougat, file:// URIs are not allowed anymore. We should use content:// URIs instead. However, my app needs to open files in root directories. Any ideas?

Body:
i put this method so imageuri path easily get in content.

enter code here
public Uri getImageUri(Context context, Bitmap inImage)
{
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(context.getContentResolver(),
    inImage, "Title", null);
    return Uri.parse(path);
}

ContentLicense: CC BY-SA 4.0


问:
Android Studio - Gradle sync failed: Already disposed
After updating to Android Studio 3.2 Beta 1, I started getting the following error for two different projects:

```<code>Gradle sync failed: Already disposed!
</code>```

There is no error with Android Studio 3.1.3, and there was no error with various canary versions of Android Studio 3.2 before updating to beta 1.

I already tried everything I can think of (e.g. complete cleaning of project, including all generated .gradle/.iml/.idea files/folders, as well as a complete invalidate cache and restart of Android Studio) without success. The build works as expected from command line using Gradle.

This is not a duplicate of Android Studio Gradle Already disposed Module

EDIT

The event log is showing

```<code>Unable to save plugin settings: The plugin org.jetbrains.android failed to save settings and has been disabled. Please restart Android Studio
</code>```

In the "IDE Fatal Errors" window, I am seeing the following exception:

```<code>'Gradle: backport-util-concurrent:backport-util-concurrent:3.1@jar' already disposed: --------------Creation trace:
java.lang.Throwable
    at com.intellij.openapi.util.TraceableDisposable.<init>(TraceableDisposable.java:45)
    at com.intellij.openapi.roots.impl.libraries.LibraryImpl.<init>(LibraryImpl.java:103)
    at com.intellij.openapi.roots.impl.libraries.LibraryImpl.<init>(LibraryImpl.java:69)
    at com.intellij.openapi.roots.impl.libraries.LibraryTableBase$LibraryModel.readExternal(LibraryTableBase.java:327)
    at com.intellij.openapi.roots.impl.libraries.LibraryTableBase.loadState(LibraryTableBase.java:64)
    at com.intellij.openapi.roots.impl.libraries.LibraryTableBase.loadState(LibraryTableBase.java:30)
    at com.intellij.configurationStore.ComponentStoreImpl.doInitComponent(ComponentStoreImpl.kt:375)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:331)
    at com.intellij.configurationStore.ComponentStoreImpl.initPersistenceStateComponent(ComponentStoreImpl.kt:121)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:96)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.initializeComponent(PlatformComponentManagerImpl.java:54)
</code>```

EDIT2:

More recent version of Android Studio 3.2 are having the same issue.

答:
Simple solution</p>

```<code>    1.Delete module folder and modules.xml file under .idea folder.
    2.Close Android Studio
    3.Reopen and sync
</code>```

Body:
After updating to Android Studio 3.2 Beta 1, I started getting the following error for two different projects:

Gradle sync failed: Already disposed!

There is no error with Android Studio 3.1.3, and there was no error with various canary versions of Android Studio 3.2 before updating to beta 1.

I already tried everything I can think of (e.g. complete cleaning of project, including all generated .gradle/.iml/.idea files/folders, as well as a complete invalidate cache and restart of Android Studio) without success. The build works as expected from command line using Gradle.

This is not a duplicate of Android Studio Gradle Already disposed Module

EDIT

The event log is showing

Unable to save plugin settings: The plugin org.jetbrains.android failed to save settings and has been disabled. Please restart Android Studio

In the "IDE Fatal Errors" window, I am seeing the following exception:

'Gradle: backport-util-concurrent:backport-util-concurrent:3.1@jar' already disposed: --------------Creation trace:
java.lang.Throwable
    at com.intellij.openapi.util.TraceableDisposable.<init>(TraceableDisposable.java:45)
    at com.intellij.openapi.roots.impl.libraries.LibraryImpl.<init>(LibraryImpl.java:103)
    at com.intellij.openapi.roots.impl.libraries.LibraryImpl.<init>(LibraryImpl.java:69)
    at com.intellij.openapi.roots.impl.libraries.LibraryTableBase$LibraryModel.readExternal(LibraryTableBase.java:327)
    at com.intellij.openapi.roots.impl.libraries.LibraryTableBase.loadState(LibraryTableBase.java:64)
    at com.intellij.openapi.roots.impl.libraries.LibraryTableBase.loadState(LibraryTableBase.java:30)
    at com.intellij.configurationStore.ComponentStoreImpl.doInitComponent(ComponentStoreImpl.kt:375)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:331)
    at com.intellij.configurationStore.ComponentStoreImpl.initPersistenceStateComponent(ComponentStoreImpl.kt:121)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:96)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.initializeComponent(PlatformComponentManagerImpl.java:54)

EDIT2:

More recent version of Android Studio 3.2 are having the same issue.

Body:
Simple solution

    1.Delete module folder and modules.xml file under .idea folder.
    2.Close Android Studio
    3.Reopen and sync


问:
how get the vertices that constitute a smaller triangle in terms of the barycentric coordinates?
this post is discussing the conversion from barycentric coordinates to Cartesian coordinates.

it seems that the figure (fig_1) only illustrates 3 points

B(0,0,1), A(0,1,0), C(1,0,0)

i am trying to understand the conversion, here is my code

```<code>x_inner = np.array([0.375, 0.5  , 0.625, 0.375])
y_inner = np.array([0.21650635, 0.4330127 , 0.21650635, 0.21650635])
x_outer = np.array([0. , 0.5, 1. , 0. ])
y_outer = np.array([0.       , 0.8660254, 0.       , 0.       ])
plt.plot(x_outer,y_outer)
plt.plot(x_inner,y_inner,c='tab:orange')
plt.scatter(x_outer, y_outer)
plt.scatter(x_inner, y_inner)
</code>```

the values constitute the coordinates array come from the original post.

here is the output.

the inner orange triangle consists of 3 vertices which correspond to the points (1/4,1/4,1/2), (1/4,1/2,1/4), (1/2,1/4,1/4) in original barycentric coordinates.

the question is, how to get a smaller triangle like 1/10 of the orange one.

ps:
sorry for fig_1 doesn't match the true values.

答:
Let we want to built small triangle similar to large one, centered at the same centroid. Centroid is point of median intersection, it divides them in ration 2:1, and has
B.C. (baricentric coordinates) (1/3, 1/3, 1/3).

Vertex of such small triangle at the first median has B.C. like (g,f,f), where g+f+f=1, at the second median (f,g,f), and (f,f,g) at the third one. We can see that for g=1/3 triangle size is zero (coefficient cf= 0), for g=1 triangle is equal to large triangle (cf = 0).

For intermediate values just make linear interpolation

```<code> cf = (g - 1/3) * 3/2 = 3/2 * g - 1/2 = (3 * g - 1) / 2
 vice versa
 g = (cf + 1/2) * 2/3 = (2 * cf + 1) / 3
 f = (1 - g) / 2
</code>```

So we can build, for example, triangle with half-size

```<code>cf = 1/2
g = 2/3
f = 1/6
(2/3, 1/6, 1/6)     (1/6, 2/3, 1/6)     (1/6, 1/6, 2/3)
</code>```

Note that for g<1/3 we'll get small triangle with inverted orientation (cf negative)

Body:
this post is discussing the conversion from barycentric coordinates to Cartesian coordinates.

it seems that the figure (fig_1) only illustrates 3 points

B(0,0,1), A(0,1,0), C(1,0,0)

i am trying to understand the conversion, here is my code

x_inner = np.array([0.375, 0.5  , 0.625, 0.375])
y_inner = np.array([0.21650635, 0.4330127 , 0.21650635, 0.21650635])
x_outer = np.array([0. , 0.5, 1. , 0. ])
y_outer = np.array([0.       , 0.8660254, 0.       , 0.       ])
plt.plot(x_outer,y_outer)
plt.plot(x_inner,y_inner,c='tab:orange')
plt.scatter(x_outer, y_outer)
plt.scatter(x_inner, y_inner)

the values constitute the coordinates array come from the original post.

here is the output.

the inner orange triangle consists of 3 vertices which correspond to the points (1/4,1/4,1/2), (1/4,1/2,1/4), (1/2,1/4,1/4) in original barycentric coordinates.

the question is, how to get a smaller triangle like 1/10 of the orange one.

ps:
sorry for fig_1 doesn't match the true values.

Body:
Let we want to built small triangle similar to large one, centered at the same centroid. Centroid is point of median intersection, it divides them in ration 2:1, and has
B.C. (baricentric coordinates) (1/3, 1/3, 1/3).

Vertex of such small triangle at the first median has B.C. like (g,f,f), where g+f+f=1, at the second median (f,g,f), and (f,f,g) at the third one. We can see that for g=1/3 triangle size is zero (coefficient cf= 0), for g=1 triangle is equal to large triangle (cf = 0).

For intermediate values just make linear interpolation

 cf = (g - 1/3) * 3/2 = 3/2 * g - 1/2 = (3 * g - 1) / 2
 vice versa
 g = (cf + 1/2) * 2/3 = (2 * cf + 1) / 3
 f = (1 - g) / 2

So we can build, for example, triangle with half-size

cf = 1/2
g = 2/3
f = 1/6
(2/3, 1/6, 1/6)     (1/6, 2/3, 1/6)     (1/6, 1/6, 2/3)

Note that for g<1/3 we'll get small triangle with inverted orientation (cf negative)


问:
SmartPointer : cast between base and derived classes
Say you have a function like this :

```<code>SmartPtr<A> doSomething(SmartPtr<A> a);
</code>```

And classes like this :

```<code>class A { }
class B : public A { }
</code>```

And now I do this :

```<code>SmartPtr<A> foo = new B();
doSomething(foo);
</code>```

Now, I would like to get back a SmartPtr object from doSomething.

```<code>SmartPtr<B> b = doSomething(foo);
</code>```

Is it possible ? What kind of casting do I have to do ?

Right now, I just found something I believe ugly :

```<code>B* b = (B*)doSomething().get()
</code>```

Important notes :  I do not have any access to SmartPtr and doSomething() code.

答:
Instead of doing that, you can do this :

```<code>B *b = dynamic_cast< B* >( doSomething.get() );
</code>```

but you have to check if b is NULL.

Body:
Say you have a function like this :

SmartPtr doSomething(SmartPtr a);

And classes like this :

class A { }
class B : public A { }

And now I do this :

SmartPtr foo = new B();
doSomething(foo);

Now, I would like to get back a SmartPtr object from doSomething.

SmartPtr b = doSomething(foo);

Is it possible ? What kind of casting do I have to do ?

Right now, I just found something I believe ugly :

B* b = (B*)doSomething().get()

Important notes :  I do not have any access to SmartPtr and doSomething() code.

Body:
Instead of doing that, you can do this :

B *b = dynamic_cast< B* >( doSomething.get() );

but you have to check if b is NULL.


问:
TimescaleDB query to select rows where column value changed from previous row
Just recently started using TimescaleDB with Postgres to handle most requests for data.

However I'm running into an issue where I have a horribly inefficient request for time series of data.

It's a data series that can be any length of time, with specific Integer values.

Most of the time the value will be the same unless there's an anomaly. So rather than fetching +10,000 rows of data. I would like to aggregate this into "time blocks".

Let's say there 97 items in a row where the value is 100 (new item for every 5 minutes) #98 the value is 48 for 5 items in a row and then it goes back up to 100 for another 2,900 rows.

I don't want to fetch 3002 items to display this data. I should only need to fetch 3 items.

1 item that says the value is 100 from a startDate

1 item that says the value is 48 from a startDate after #1

1 item that says the value is 100 again from a startDate after #2

But I'm having some trouble figuring out how I can do this with timescaledb.

basically, if the value is the same as the last value, aggregate it. That's all I need it to do.

Does anyone know how to construct a VIEW for this kind of situation in timescaleDB using continuous aggregation (or if there's a faster way) to fetch this?

答:
You can achieve the desired result with window functions and a subselect:

```<code>SELECT time, value FROM (
  SELECT
    time,
    value,
    value - LAG(value) OVER (ORDER BY time) as diff
  FROM hypertable) ht
WHERE diff IS NULL OR diff != 0;
</code>```

You use a window function to calculate the diff to the previous row and then filter all the rows where the diff is 0 in the outer query.

Body:
You can achieve the desired result with window functions and a subselect:

SELECT time, value FROM (
  SELECT
    time,
    value,
    value - LAG(value) OVER (ORDER BY time) as diff
  FROM hypertable) ht
WHERE diff IS NULL OR diff != 0;

You use a window function to calculate the diff to the previous row and then filter all the rows where the diff is 0 in the outer query.


问:
How can I clear previous output in Terminal in Mac OS X?
I know the clear command that 'clears' the current screen, but it does this just by printing lots of newlines - the cleared contents just get scrolled up.

Is there a way to completely wipe all previous output from the terminal so that I can't reach it even by scrolling up?

答:
To delete the last output only:

⌘ + L

To clear the terminal completely:

⌘ + K


问:
php delete only partial contents from a log file
In my recent application, i had to write a series of cronjobs and i use to log them to a custom log file, these log files contains details of exceptions and/or shows the status of each execution.

Problem is my log file is getting bulkier and i would like to clear some of the contents from the file and keep it slim.
Like say only keep last 10 days contents inside this file and clear the older contents.

My sample error log file is given below:

```<code>[2019-05-16 06:38:16 AM]: Catalog Import - Process started.
[2019-05-16 06:38:17 AM]: - Brands processed.
[2019-05-16 06:38:18 AM]: - Categories processed.
[2019-05-16 06:38:27 AM]: - Catalogues processed.
[2019-05-16 06:38:29 AM]: - CSV generated.
[2019-05-16 06:38:29 AM]: Catalog Import - Process completed.
[2019-05-16 06:38:29 AM]: =======================================================================
[2019-05-17 06:38:16 AM]: Catalog Import - Process started.
[2019-05-17 06:38:17 AM]: Exception - (json encoded response usually array stuffs)
[2019-05-17 06:38:18 AM]: - Categories processed.
[2019-05-17 06:38:27 AM]: - Catalogues processed.
[2019-05-17 06:38:29 AM]: Error - (json encoded response usually array stuffs)
[2019-05-17 06:38:29 AM]: Catalog Import - Process completed.
[2019-05-17 06:38:29 AM]: =======================================================================
</code>```

What would be the best way to delete the contents periodically in the log file?

答:
Open the file and loop the file.

When you find a date that is "too old" delete the line.

Then save the new data in the log file.

```<code>$log_file = 'catalog_import.log';
// get the file contents as array.
$lines = file( $log_file);
if (!empty($lines)) {
    foreach ($lines as $row => $line) {
        // if older than 10 days.
        if (time() - strtotime(substr($line, 1, 10)) > 60 * 60 * 24 * 10) {
            unset($lines[$row]);
        }
    }
}
//write the filtered data to the file.
file_put_contents($log_file, implode("", $lines));

die('logs cleared successfully.');
</code>```

Please do this on a copy first as it's untested code.

Body:
In my recent application, i had to write a series of cronjobs and i use to log them to a custom log file, these log files contains details of exceptions and/or shows the status of each execution.

Problem is my log file is getting bulkier and i would like to clear some of the contents from the file and keep it slim.
Like say only keep last 10 days contents inside this file and clear the older contents.

My sample error log file is given below:

[2019-05-16 06:38:16 AM]: Catalog Import - Process started.
[2019-05-16 06:38:17 AM]: - Brands processed.
[2019-05-16 06:38:18 AM]: - Categories processed.
[2019-05-16 06:38:27 AM]: - Catalogues processed.
[2019-05-16 06:38:29 AM]: - CSV generated.
[2019-05-16 06:38:29 AM]: Catalog Import - Process completed.
[2019-05-16 06:38:29 AM]: =======================================================================
[2019-05-17 06:38:16 AM]: Catalog Import - Process started.
[2019-05-17 06:38:17 AM]: Exception - (json encoded response usually array stuffs)
[2019-05-17 06:38:18 AM]: - Categories processed.
[2019-05-17 06:38:27 AM]: - Catalogues processed.
[2019-05-17 06:38:29 AM]: Error - (json encoded response usually array stuffs)
[2019-05-17 06:38:29 AM]: Catalog Import - Process completed.
[2019-05-17 06:38:29 AM]: =======================================================================

What would be the best way to delete the contents periodically in the log file?

Body:
Open the file and loop the file.

When you find a date that is "too old" delete the line.

Then save the new data in the log file.

$log_file = 'catalog_import.log';
// get the file contents as array.
$lines = file( $log_file);
if (!empty($lines)) {
    foreach ($lines as $row => $line) {
        // if older than 10 days.
        if (time() - strtotime(substr($line, 1, 10)) > 60 * 60 * 24 * 10) {
            unset($lines[$row]);
        }
    }
}
//write the filtered data to the file.
file_put_contents($log_file, implode("", $lines));

die('logs cleared successfully.');

Please do this on a copy first as it's untested code.


问:
why Textfield control not taking props (classes)?
I am trying to change my input field border when I focused to input field.currently it is showing blue.I want to change it to red or other color.

I tried using passing props

```<code>function Control(props) {
  console.log(props)
  return (
    <TextField
      fullWidth
      InputProps={{
        inputComponent,
        inputProps: {
          className: props.selectProps.classes.input,
          inputRef: props.innerRef,
          children: props.children,
         classes:{underline: props.selectProps.classes.underlineInput,
          root: props.selectProps.classes.inputRoot,
          focused: props.selectProps.classes.focusedLabel,},

          ...props.innerProps
        }
      }}
      {...props.selectProps.textFieldProps}
    />
  );
}
</code>```

underline: props.selectProps.classes.underlineInput tried to change my  input field border color.but it don't work why ?

here is my code
https://codesandbox.io/s/71267zp3l6

答:
Add this class on your CSS file. It uses !important for the override.

```<code>.MuiInput-underline-44:after {
    border-bottom: 2px solid #9f3063 !important;
}
</code>```

Body:
I am trying to change my input field border when I focused to input field.currently it is showing blue.I want to change it to red or other color.

I tried using passing props

function Control(props) {
  console.log(props)
  return (
    <TextField
      fullWidth
      InputProps={{
        inputComponent,
        inputProps: {
          className: props.selectProps.classes.input,
          inputRef: props.innerRef,
          children: props.children,
         classes:{underline: props.selectProps.classes.underlineInput,
          root: props.selectProps.classes.inputRoot,
          focused: props.selectProps.classes.focusedLabel,},

          ...props.innerProps
        }
      }}
      {...props.selectProps.textFieldProps}
    />
  );
}

underline: props.selectProps.classes.underlineInput tried to change my  input field border color.but it don't work why ?

here is my code
https://codesandbox.io/s/71267zp3l6

Body:
Add this class on your CSS file. It uses !important for the override.

.MuiInput-underline-44:after {
    border-bottom: 2px solid #9f3063 !important;
}


问:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction
Below is my hikariCP configuration :

```<code>spring.datasource.hikari.connection-timeout=10000

spring.datasource.hikari.maximum-pool-size=10

spring.datasource.hikari.minimum-idle=15

spring.datasource.hikari.pool-name=HikariConnectionPool
</code>```

While testing with JMeter, when I hit 500 threads I got following exception for some of the transactions.

```<code>org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
</code>```

答: Thanks ,I have change connection-timeout From 10 sec to 100 sec It Solved my issue. </p>

Body:
Below is my hikariCP configuration :

spring.datasource.hikari.connection-timeout=10000

spring.datasource.hikari.maximum-pool-size=10

spring.datasource.hikari.minimum-idle=15

spring.datasource.hikari.pool-name=HikariConnectionPool

While testing with JMeter, when I hit 500 threads I got following exception for some of the transactions.

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection


问:
Start an application at system start without login
We have a new server running and we got some new programs doing import routines. So far so good... But there is one program that is put into autostart folder. So it doesn't run until admin logs in and it stops if we logout.

I'd like to put this one into a seperate session so it may work without any interaction by simply starting it with the task scheduler at startup. Is this the right way to do this? Is it safe if I log in later and log out?

Many thanks!

Edit: The applications shows as a symbol in the task bar if running, it can be configured by this. Anything I must know about this if I change?

Edit: It is not my application, I cannot rewrite it as a service.

答:
Convert user application to Service and Register it using Regsvr32 or installutil.exe. It will start the service using  SYSTEM user account. Which is a high privilege account.
Note : You can`t run any Window based application. Even a Message only window.


问:
XCUITest coordinate(withNormalizedOffset:) explanation
I need the detailed information about coordinate(withNormalizedOffset:) method.

The information provided in the Apple's docs are very minimal.

This method is all about picking a specific point in the window. But how can I define dx & dy points for a specific point?

Consider the four corners of the window. Top Left, Top Right, Bottom Left, Bottom Right. Can someone provide details on this?

What is mean by normalizedOffset?

What is dx & dy and their range?

答:
Range of dx & dy is 0 to 1 allowing float values. Normalized Offset is the x and y coordinates w.r.to the width and height of the object respectively.

Say we have an object of width 245 and height 432, and we need coordinate (10, 34) on it. The normalized offset is (10 / 245, 34 / 432) i.e. (0.040816327, 0.078703704) where the actual offset is (10, 34).


问:
JavaScript Slot Machine: What Is A Simple Algorithm For Picking A Winner?
I'm developing a slot machine in JavaScript, and this slot machine has 3 reels.

Each reel is identical and contains 4 symbols: A bar, a 7, a bell, and a grape. The bar is displayed on the reel one time, the 7 two times, the bell three times, and the grape four times - for a total of 10 symbols per reel. And each symbol corresponds with a number from 0 - 9:

```<code>| bar | -> 9
|  7  | -> 8
|  7  | -> 7
| bell| -> 6
| bell| -> 5
| bell| -> 4
|grape| -> 3
|grape| -> 2
|grape| -> 1
|grape| -> 0
</code>```

I'm then randomly generating a number from 0 - 999, and based on that number I would like to potentially select a winner. For example, if the number is 999 that is three bars and the first jackpot, if the number is 210 that is three grapes and the fourth jackpot. If the number is 359 that is grape/bell/bar and no jackpot.

I had created an if/else to select the winner but realized it does not take into account the second winning situation of 210:

```<code>if (number == 999) {
    // Jackpot 1
} else if (number == 888) {
    // Jackpot 2
} else if (number == 777) {
    // Jackpot 2
} else if (number == 666) {
    // Jackpot 3
} else if (number == 555) {
    // Jackpot 3
} else if (number == 444) {
    // Jackpot 3
} else if (number == 333) {
    // Jackpot 4
} else if (number == 222) {
    // Jackpot 4
} else if (number == 111) {
    // Jackpot 4
} else if (number == 0) {
    // Jackpot 4
} else {
    // No jackpot
}
</code>```

Does anyone have any ideas for how I might devise a simple algorithm for selecting a winner, as opposed to a bunch of if/else's? Also, there needs to be a total of 10 possible outcomes per reel, as the top jackpot should have a probability of 10^3 => 1 in 1,000.

答:
You can check below code also using simple JavaScript which work for all browsers.

function checkJackpot(digit) {
    var jackpot = {
        "9": "1",
        "8": "2",
        "7": "2",
        "6": "3",
        "5": "3",
        "4": "3",
        "3": "4",
        "2": "4",
        "1": "4",
        "0": "4"
    }
    var number = digit.toString().split('');
    var count = [];
    for (var i = 0; i < number.length; i++) {
        var j = jackpot[number[i]]
        if (count.indexOf(j) == -1)
            count.push(jackpot[number[i]])
    }
    if (count.length == 1) {
        alert("Jackpot " + count[0])

    } else {
        alert("No jackpot")
    }
}
checkJackpot(219)
checkJackpot(999)
checkJackpot(110)```

Body:
I'm developing a slot machine in JavaScript, and this slot machine has 3 reels.

Each reel is identical and contains 4 symbols: A bar, a 7, a bell, and a grape. The bar is displayed on the reel one time, the 7 two times, the bell three times, and the grape four times - for a total of 10 symbols per reel. And each symbol corresponds with a number from 0 - 9:

| bar | -> 9
|  7  | -> 8
|  7  | -> 7
| bell| -> 6
| bell| -> 5
| bell| -> 4
|grape| -> 3
|grape| -> 2
|grape| -> 1
|grape| -> 0

I'm then randomly generating a number from 0 - 999, and based on that number I would like to potentially select a winner. For example, if the number is 999 that is three bars and the first jackpot, if the number is 210 that is three grapes and the fourth jackpot. If the number is 359 that is grape/bell/bar and no jackpot.

I had created an if/else to select the winner but realized it does not take into account the second winning situation of 210:

if (number == 999) {
    // Jackpot 1
} else if (number == 888) {
    // Jackpot 2
} else if (number == 777) {
    // Jackpot 2
} else if (number == 666) {
    // Jackpot 3
} else if (number == 555) {
    // Jackpot 3
} else if (number == 444) {
    // Jackpot 3
} else if (number == 333) {
    // Jackpot 4
} else if (number == 222) {
    // Jackpot 4
} else if (number == 111) {
    // Jackpot 4
} else if (number == 0) {
    // Jackpot 4
} else {
    // No jackpot
}

Does anyone have any ideas for how I might devise a simple algorithm for selecting a winner, as opposed to a bunch of if/else's? Also, there needs to be a total of 10 possible outcomes per reel, as the top jackpot should have a probability of 10^3 => 1 in 1,000.


问:
Type overloading macro
I have a bunch of printf debug helper macros and it would be pretty cool to have to not specify the type, is there anything you can do to allow something like macro overloading in c(can be gcc specific if its available in gcc 4.3). I thought maybe typeof but apparently that doesn't work.

example macro(I also have some ascii terminal color stuff that I can't remember of the top of my head)

```<code>#ifdef _DEBUG
#define DPRINT_INT(x) printf("int %s is equal to %i at line %i",#x,x,__LINE__);
.
.
.
#else
#define DPRINT_INT(x)
.
.
.
#endif
</code>```

答:
Try this; it uses gcc's __builtin methods, and automatically determines the type for you, as best it can, and makes for an easy DEBUG macro where you don't have to specify the type. Of course, you can compare typeof (x) to float, etc. etc.</p>

```<code>#define DEBUG(x)                                                 \
  ({                                                             \
    if (__builtin_types_compatible_p (typeof (x), int))          \
        fprintf(stderr,"%d\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char))    \
        fprintf(stderr,"%c\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char[]))  \
        fprintf(stderr,"%s\n",x);                                \
    else                                                         \
        fprintf(stderr,"unknown type\n");                        \

  })
</code>```

Title: Type overloading macro

Body:
I have a bunch of printf debug helper macros and it would be pretty cool to have to not specify the type, is there anything you can do to allow something like macro overloading in c(can be gcc specific if its available in gcc 4.3). I thought maybe typeof but apparently that doesn't work.

example macro(I also have some ascii terminal color stuff that I can't remember of the top of my head)

#ifdef _DEBUG
#define DPRINT_INT(x) printf("int %s is equal to %i at line %i",#x,x,__LINE__);
.
.
.
#else
#define DPRINT_INT(x)
.
.
.
#endif

Body:
Try this; it uses gcc's __builtin methods, and automatically determines the type for you, as best it can, and makes for an easy DEBUG macro where you don't have to specify the type. Of course, you can compare typeof (x) to float, etc. etc.

#define DEBUG(x)                                                 \
  ({                                                             \
    if (__builtin_types_compatible_p (typeof (x), int))          \
        fprintf(stderr,"%d\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char))    \
        fprintf(stderr,"%c\n",x);                                \
    else if (__builtin_types_compatible_p (typeof (x), char[]))  \
        fprintf(stderr,"%s\n",x);                                \
    else                                                         \
        fprintf(stderr,"unknown type\n");                        \

  })


问:
Routing(?) in Vanilla JS
I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?

My approach:

1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)

I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.

```<code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./js/main.js"></script>
</head>
<body>
    <script>
        const template= `
        <h1>Good Morning: ${goodmorning} </h1>
        <h2>Good Evening: ${goodevening} </h2>
        <h3>My name is: ${mynameis}</h3>`

        function markupAppend() {
        $('body').html(template);
        console.log('Markup loaded')
        }

        markupAppend()

    </script>

</body>
</html>

=========================
Main.js

var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");

if (FRString) {
  $('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}

if (ESString) {
  $('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}

=========================
FRENCHwords.js

const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';

=========================
SPANISHwords.js

const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';

No errors displayed, the page is just not rendering...
</code>```

答:
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.

Instead of:  domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

Title: Routing(?) in Vanilla JS

Body:
I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?

My approach:

1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)

I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

=========================
Main.js

var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");

if (FRString) {
  $('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}

if (ESString) {
  $('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}

=========================
FRENCHwords.js

const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';

=========================
SPANISHwords.js

const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';

No errors displayed, the page is just not rendering...


问:
Kill Python thread running a web server
I'm trying to reboot a web server written in Python during some integration testing. The server runs as a thread during the tests, so I can continue sending POST \ GET requests to it, and asserting the answers.

I tried killing the thread by force:

```<code>t = threading.Thread(name='server', target=main, daemon=True)
.....
t._tstate_lock = None
t._stop()
t.join()
</code>```

While debugging, I can actually see that the thread is stopped, but the webserver is still up, for some reason.

Any ideas?

答:
For future generations, here is the code I used to create a killable thread in Python.</p>

```<code>import threading
import inspect
import ctypes

def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class Thread(threading.Thread):
    def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        raise AssertionError("could not determine the thread's id")

    def raise_exc(self, exctype):
        """raises the given exception type in the context of this thread"""
        _async_raise(self._get_my_tid(), exctype)

    def terminate(self):
        """raises SystemExit in the context of the given thread, which should
        cause the thread to exit silently (unless caught)"""
        self.raise_exc(SystemExit)
</code>```

Title: Kill Python thread running a web server

Body:
I'm trying to reboot a web server written in Python during some integration testing. The server runs as a thread during the tests, so I can continue sending POST \ GET requests to it, and asserting the answers.

I tried killing the thread by force:

t = threading.Thread(name='server', target=main, daemon=True)
.....
t._tstate_lock = None
t._stop()
t.join()

While debugging, I can actually see that the thread is stopped, but the webserver is still up, for some reason.

Any ideas?

Body:
For future generations, here is the code I used to create a killable thread in Python.

import threading
import inspect
import ctypes

def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class Thread(threading.Thread):
    def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        raise AssertionError("could not determine the thread's id")

    def raise_exc(self, exctype):
        """raises the given exception type in the context of this thread"""
        _async_raise(self._get_my_tid(), exctype)

    def terminate(self):
        """raises SystemExit in the context of the given thread, which should
        cause the thread to exit silently (unless caught)"""
        self.raise_exc(SystemExit)


问:
Change concrete class binding on demand in Laravel Service Container
How do I change a concrete class binding dynamically.

I'm trying to test an artisan command that consumes an external API.

```<code>class ConsumeApiCommand extends Command
{
    public function __construct(ClientInterface $client)
    {
        parent::__construct();

        $this->client = $client;
    }

    public function handle()
    {
        $api_response = $this->client->request('POST', 'http://external.api/resource');

        $response = json_decode($api_response);

        if(isset($response['error'])) {
            $this->error($response['error']);
        } else {
            $this->status($response['status']);
        }
    }
}
</code>```

Currently; I can fake the concrete class in my tests.

```<code>class FakeServiceProvider extends AppServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ClientInterface::class, function () {
            return new class implements ClientInterface {
                public function request($method, $uri, $headers = [], $body = [])
                {
                    return json_encode(['status' => "You've reached us."]);
                }
            };
        });
    }
}
</code>```

Passing.

```<code>public function test_can_consume_api_if_authenticated()
{
    $this->artisan('consume:api')
         ->expectsOutput("You've reached us.")
         ->assertExitCode(0);
}
</code>```

Failing; returns initially binded class response You've reached us.

```<code>public function test_cant_consume_api_if_not_authenticated()
{
    $this->app->bind(ClientInterface::class, function () {
        return new class implements ClientInterface {
            public function request($method, $uri, $headers = [], $body = [])
            {
                return json_encode(['error' => "Unauthorized."]);
            }
        };
    });

    $this->artisan('consume:api')
         ->expectsOutput("Unauthorized.")
         ->assertExitCode(0);
}
</code>```

Is it possible to achieve the desire behavior this way? Or service container bindings can't change during the request lifetime?

答:
It's always allowed to bind new concrete class to interfaces in Laravel.
The problem I see here (and I faced in a similar scenario in the past) is that when you bind() the new concrete class, the artisan command has already been initialized (with the old binding).

In the setUp() method of your test case you should re-register the command so that it will take the new binding from the interface.

To test if this is a possible solution, just add dump() in the command's __construct() method and another one in the setUp of your test. If I am correct, you should see che command's one coming first and then the other.

Body:
How do I change a concrete class binding dynamically.

I'm trying to test an artisan command that consumes an external API.

class ConsumeApiCommand extends Command
{
    public function __construct(ClientInterface $client)
    {
        parent::__construct();

        $this->client = $client;
    }

    public function handle()
    {
        $api_response = $this->client->request('POST', 'http://external.api/resource');

        $response = json_decode($api_response);

        if(isset($response['error'])) {
            $this->error($response['error']);
        } else {
            $this->status($response['status']);
        }
    }
}

Currently; I can fake the concrete class in my tests.

class FakeServiceProvider extends AppServiceProvider
{
    public function register(): void
    {
        $this->app->bind(ClientInterface::class, function () {
            return new class implements ClientInterface {
                public function request($method, $uri, $headers = [], $body = [])
                {
                    return json_encode(['status' => "You've reached us."]);
                }
            };
        });
    }
}

Passing.

public function test_can_consume_api_if_authenticated()
{
    $this->artisan('consume:api')
         ->expectsOutput("You've reached us.")
         ->assertExitCode(0);
}

Failing; returns initially binded class response You've reached us.

public function test_cant_consume_api_if_not_authenticated()
{
    $this->app->bind(ClientInterface::class, function () {
        return new class implements ClientInterface {
            public function request($method, $uri, $headers = [], $body = [])
            {
                return json_encode(['error' => "Unauthorized."]);
            }
        };
    });

    $this->artisan('consume:api')
         ->expectsOutput("Unauthorized.")
         ->assertExitCode(0);
}

Is it possible to achieve the desire behavior this way? Or service container bindings can't change during the request lifetime?


问:
Unable to capture the checked , unchecked status of the checkbox in angular 7
I have a checkbox control in my angular 7 application and need to capture checked  unchecked value as and when the checkbox is selected or deselected.

```<code><td *ngIf="EditMode[f.Id] && c == ColumnNames[44]" class="tableItem">
    <label style="font-size: 13px;font-weight: normal;cursor: pointer">
        <input type="checkbox" #myId  (checked)="isHurdleRateSelected(s)" value="{{f.HurdleRate}}" style="width: 13px; height: 13px;" /> Yes
    </label>
</td>
</code>```

Component

```<code>isHurdleRateSelected(s) {
  this.isHurdle = s;
}
</code>```

At the moment, I tried using the checked and change event. When using change event, the value that is being captured in the code behind shows undefined while checked property doesnt seem to hit the break point.

Could somebody tell me how to go about it?

答:
Try this:

```<code><input type="checkbox" #myId  (checked)="isHurdleRateSelected($event)" value="{{f.HurdleRate}}" style="width: 13px; height: 13px;" /> Yes
</code>```

in the new isHurdleRateSelected($event):

now if you in .ts print the value:

```<code>isHurdleRateSelected(event) {
console.log(event);
     //   this.isHurdle = s;
    }
</code>```

After it prints you can read a lot of values and you can find checked attribute.

Body:
I have a checkbox control in my angular 7 application and need to capture checked  unchecked value as and when the checkbox is selected or deselected.

        <input type="checkbox" #myId  (checked)="isHurdleRateSelected(s)" value="{{f.HurdleRate}}" style="width: 13px; height: 13px;" /> Yes

Component

isHurdleRateSelected(s) {
  this.isHurdle = s;
}

At the moment, I tried using the checked and change event. When using change event, the value that is being captured in the code behind shows undefined while checked property doesnt seem to hit the break point.

Could somebody tell me how to go about it?

Body:
Try this:

<input type="checkbox" #myId  (checked)="isHurdleRateSelected($event)" value="{{f.HurdleRate}}" style="width: 13px; height: 13px;" /> Yes

in the new isHurdleRateSelected($event):

now if you in .ts print the value:

isHurdleRateSelected(event) {
console.log(event);
     //   this.isHurdle = s;
    }

After it prints you can read a lot of values and you can find checked attribute.


问:
can we use system.web.mail in wcf?
can we use system.web.mail in wcf library if yes then how can i get system.web.mail.dll </p>

答:
These classes have been deprecated, you should use System.Net.Mail instead.

But yes, you can use them from WCF.

Title: can we use system.web.mail in wcf?


问:
How to read excel file in Java when the file is located within the java project?
What should be the syntax when the excel file that I'm trying to call is imported within the project.

答:
Use :

```<code> public class ReadFileExcel
    {
        public static void main(String[] args) throws IOException
        {
            ClassLoader classLoader = new ReadFileExcel.getClass().getClassLoader();
            File file = new File(classLoader.getResource("./dashboards.xlsx").getFile());
            // replace the below one with the above but just change the name of the class
            var file = new FileInputStream("Dashboard.xlsx");
        }
    }
</code>```

Note : Build the project, otherwise classloader will not able to read.

Body:
Use :

 public class ReadFileExcel
    {
        public static void main(String[] args) throws IOException
        {
            ClassLoader classLoader = new ReadFileExcel.getClass().getClassLoader();
            File file = new File(classLoader.getResource("./dashboards.xlsx").getFile());
            // replace the below one with the above but just change the name of the class
            var file = new FileInputStream("Dashboard.xlsx");
        }
    }

Note : Build the project, otherwise classloader will not able to read.


问:
AttributeError: image_converter instance has no attribute
I need to use an RGB image from image Callback as well as a depth image from depth Callback. I am using ROS. I have declared global variables. In one case if I call my function abc() from RGB Callback I am getting this error:

'AttributeError: image_converter instance has no attribute cv_image

although the image in the opencv window is shown. And if instead I use call the abc() function in the depth Callback the image is shown properly without any error. My question is why?

```<code>class image_converter:
    def __init__(self):
        self.bridge = CvBridge()
        self.pose_sub = rospy.Subscriber("/camera/depth/image_rect_raw",Image,self.depthcallback)
        self.image_sub = rospy.Subscriber("/camera/color/image_raw",Image,self.rgbcallback)
        self.count = 0
        self.flag = False
        print(str(self.flag)+"  "+str(self.count))

    def rgbcallback(self,data):
        try:
            self.cv_image = self.bridge.imgmsg_to_cv2(data,"bgr8")
        except:
            print(e)
        # self.ptcldgen()

    def depthcallback(self,data):
        try:
            self.cv_depth = self.bridge.imgmsg_to_cv2(data,"16UC1")
        except:
            print(e)
        self.ptcldgen()

    def ptcldgen(self):
        cv2.imshow("image",self.cv_image)
        cv2.waitKey(3)

def main(args):
    ic = image_converter()
    rospy.init_node("image_converter",anonymous=True)
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("shut")
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main(sys.argv)

</code>```

答:
The problem is the attribute cv_image could not yet be available at calling using it in ptcldgen.

cv_image is only set in rgbcallback but also used in depthcallback. If depthcallback gets called before rgbcallback was called, the attribute simply does not exist (yet). The result is an Attribute Error.

To solve your problem you need to initialize the attribute at initializing your class __init__, for example by setting it to none like self.cv_image = None.

Body:
I need to use an RGB image from image Callback as well as a depth image from depth Callback. I am using ROS. I have declared global variables. In one case if I call my function abc() from RGB Callback I am getting this error:

'AttributeError: image_converter instance has no attribute cv_image

although the image in the opencv window is shown. And if instead I use call the abc() function in the depth Callback the image is shown properly without any error. My question is why?

class image_converter:
    def __init__(self):
        self.bridge = CvBridge()
        self.pose_sub = rospy.Subscriber("/camera/depth/image_rect_raw",Image,self.depthcallback)
        self.image_sub = rospy.Subscriber("/camera/color/image_raw",Image,self.rgbcallback)
        self.count = 0
        self.flag = False
        print(str(self.flag)+"  "+str(self.count))

    def rgbcallback(self,data):
        try:
            self.cv_image = self.bridge.imgmsg_to_cv2(data,"bgr8")
        except:
            print(e)
        # self.ptcldgen()

    def depthcallback(self,data):
        try:
            self.cv_depth = self.bridge.imgmsg_to_cv2(data,"16UC1")
        except:
            print(e)
        self.ptcldgen()

    def ptcldgen(self):
        cv2.imshow("image",self.cv_image)
        cv2.waitKey(3)

def main(args):
    ic = image_converter()
    rospy.init_node("image_converter",anonymous=True)
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("shut")
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main(sys.argv)


问:
How to send data from Adapter to ViewModel to Fragment
My structure is like this, in the Fragment I call the ViewModel which instantiate the Adapter

For each item of my RecyclerView, I have a button which I listen

```<code>binding.addItem.setOnClickListener(onAddItemClicked(product))

private fun onAddToQuoteClicked(product: Product): View.OnClickListener {
    return View.OnClickListener {
        // TODO add item
    }
}
</code>```

I don't know how to send this item data to the fragment, is there a way to do that?

Should I use interface between Adapter and ViewModel and between ViewModel and Fragment ?

Or Can I use RxEvent & RxBus ?

答:
First for navigation between ViewModel and Fragment -

you can use RxJava PublishSubject make it public and subscribe to it in your Fragment which can use public methods of ViewModel.

or you can use an interface, better in my opinion as using interface you are using simpler logic, much less errors in that case, and also it is more clean code as you can name methods in interface as you want - easier to read.

Second for communication between Adapter and Fragment - you can use same strategy as described above. In that case I recommend to use RxJava, as usually you would just need to handle one or few click listeners (so it is for example for observable which emits some data object).

  If you need some code examples text me in comments.

UPDATE - it is better practice to create your Adapter instance in View, as I assume you are using MVVM design pattern (where all UI related code must be located in View component).

Example Fragment - Adapter communication Rx - PublishSubject

In your Adapter

```<code>     private val publisher = PublishSubject.create<Product>()
fun getObservableProductItem(): Observable<Product> = publisher.hide()

binding.addItem.setOnClickListener(onAddItemClicked(product))
private fun onAddToQuoteClicked(product: Product): View.OnClickListener {
    return View.OnClickListener {
        publisherRideItem.onNext(items[adapterPosition])
    }
}

override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
    publisherRideItem.onComplete()
}
</code>```

And in your Fragment

```<code> compositeDisposable.add(adapter.getObservableProductItem().subscribe {
            //TODO do whatever you want with it
        })

  override fun onDestroy() {
    super.onDestroy()
    compositeDisposable.clear()
}
</code>```

Body:
My structure is like this, in the Fragment I call the ViewModel which instantiate the Adapter

For each item of my RecyclerView, I have a button which I listen

binding.addItem.setOnClickListener(onAddItemClicked(product))

private fun onAddToQuoteClicked(product: Product): View.OnClickListener {
    return View.OnClickListener {
        // TODO add item
    }
}

I don't know how to send this item data to the fragment, is there a way to do that?

Should I use interface between Adapter and ViewModel and between ViewModel and Fragment ?

Or Can I use RxEvent & RxBus ?

Body:
First for navigation between ViewModel and Fragment -

you can use RxJava PublishSubject make it public and subscribe to it in your Fragment which can use public methods of ViewModel.

or you can use an interface, better in my opinion as using interface you are using simpler logic, much less errors in that case, and also it is more clean code as you can name methods in interface as you want - easier to read.

Second for communication between Adapter and Fragment - you can use same strategy as described above. In that case I recommend to use RxJava, as usually you would just need to handle one or few click listeners (so it is for example for observable which emits some data object).

  If you need some code examples text me in comments.

UPDATE - it is better practice to create your Adapter instance in View, as I assume you are using MVVM design pattern (where all UI related code must be located in View component).

Example Fragment - Adapter communication Rx - PublishSubject

In your Adapter

     private val publisher = PublishSubject.create<Product>()
fun getObservableProductItem(): Observable<Product> = publisher.hide()

binding.addItem.setOnClickListener(onAddItemClicked(product))
private fun onAddToQuoteClicked(product: Product): View.OnClickListener {
    return View.OnClickListener {
        publisherRideItem.onNext(items[adapterPosition])
    }
}

override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
    publisherRideItem.onComplete()
}

And in your Fragment

 compositeDisposable.add(adapter.getObservableProductItem().subscribe {
            //TODO do whatever you want with it
        })

  override fun onDestroy() {
    super.onDestroy()
    compositeDisposable.clear()
}


问:
Group multidimensional array by key and sum values in PHP
There are similar questions on Stack Overflow but nothing quite like mine, and I also want to double check that I am doing this the most efficient way (resource wise).

I have surveys that are submitted and I want to tally the results. Each survey is saved in a multidimensional array like so:

Array ( [name] => Clark Kent [rating] => 5 )

These are coming from a loop as they are separate database entries.

So I am beginning by creating a new array with all these combined:

```<code>$mods = array();
$index = -1;
foreach($fields as $field) {
  $index++;
  $mods[$index]['name'] = $field['name'];
  $mods[$index]['rating'] = $field['rating'];
}
</code>```

Then I am grouping these so that all the ratings for the same name are together, so I can sum them later.

```<code>$groups = array();
foreach ($mods as $value) {
  $groups[$value['name']][] = $value;
}
</code>```

This produces the following:

```<code>Array (
  [Clark Kent] => Array (
    [0] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    [1] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    )
[Peter Parker] => Array (
    [0] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    [1] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    )
[Bruce Wayne] => Array (
    [0] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    )
[Bruce Banner] => Array (
    [0] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    )
)
</code>```

What I am trying to accomplish would be something like this:

```<code><table>
  <tr>
    <td>Clark Kent</td>
    <td>{average of all ratings}</td>
  </tr>
</table>
</code>```

I'm most of the way there, but I am stuck! I'm not sure how to get the grouped name that doesn't have any type of index or key so I can use that value for my table. Then I need to sum each grouped values.

答:
To get average you can do something like:</p>

```<code>foreach ($groups as $name => $group) {
    $average = array_sum(array_column($group, 'rating')) / count($group);
    echo $name;
}
</code>```

Body:
There are similar questions on Stack Overflow but nothing quite like mine, and I also want to double check that I am doing this the most efficient way (resource wise).

I have surveys that are submitted and I want to tally the results. Each survey is saved in a multidimensional array like so:

Array ( [name] => Clark Kent [rating] => 5 )

These are coming from a loop as they are separate database entries.

So I am beginning by creating a new array with all these combined:

$mods = array();
$index = -1;
foreach($fields as $field) {
  $index++;
  $mods[$index]['name'] = $field['name'];
  $mods[$index]['rating'] = $field['rating'];
}

Then I am grouping these so that all the ratings for the same name are together, so I can sum them later.

$groups = array();
foreach ($mods as $value) {
  $groups[$value['name']][] = $value;
}

This produces the following:

Array (
  [Clark Kent] => Array (
    [0] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    [1] => Array (
        [name] => Clark Kent
        [rating] => 5
        )
    )
[Peter Parker] => Array (
    [0] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    [1] => Array (
        [name] => Peter Parker
        [rating] => 5
        )
    )
[Bruce Wayne] => Array (
    [0] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Wayne
        [rating] => 5
        )
    )
[Bruce Banner] => Array (
    [0] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    [1] => Array (
        [name] => Bruce Banner
        [rating] => 5
        )
    )
)

What I am trying to accomplish would be something like this:

    Clark Kent
    {average of all ratings}

I'm most of the way there, but I am stuck! I'm not sure how to get the grouped name that doesn't have any type of index or key so I can use that value for my table. Then I need to sum each grouped values.

Body:
To get average you can do something like:

foreach ($groups as $name => $group) {
    $average = array_sum(array_column($group, 'rating')) / count($group);
    echo $name;
}


问:
Getting stack trace from NullPointerException
my servlet is throwing a NullPointerException. I want to show the full stack call trace so that I can find out the line number the exception is being thrown at.

How can I do that? I have already used fillInStackTrace(). it is not printing the line number.

答:
Assuming you are getting stacktraces without line numbers (which is what the last sentence of the Question seems to be saying), then the problem is that your code has been compiled without debug information.  You will need to recompile it ...

If you are building using Maven, you should get debug information by default.  Check the maven.compile.debug and maven.compile.debuglevel properties in the java plugin configs; see http://maven.apache.org/maven-1.x/plugins/java/properties.html

If you are building using Ant, make sure that the <javac> task has debug='true' and check the debuglevel attribute.

If you are building by running javac directory, you should get line numbers by default. Check the -g options against the javac manual page.


问:
StartActivityForResult is not working with Kotlin extension functions?
This is the extension function which i had created for starting activities for obtaining result, however the activity is getting started, but I'm not getting a call on onActivityResult

```<code>inline fun <reified T : Any> Activity.launchActivity(
requestCode: Int = -1,
noinline init: Intent.() -> Unit = {}
) {
val intent = Intent(this, T::class.java)
intent.init()
startActivityForResult(intent, requestCode)
}
</code>```

onActivityResult callback

```<code>override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    Timber.d("onActivityResult".plus(OrderProductFragment::class.java.simpleName))
</code>```

Calling the extension inside a Fragment

```<code>(context as Activity).launchActivity<CartActivity> (1234) {
                putParcelableArrayListExtra(getString(R.string.cart_items_key), cartItems)
            }
</code>```

答:
You need to call this  setResult() when navigate back to fragment or activity where you are coming from
ie

```<code>setResult(Activity.RESULT_OK, intent)
</code>```

this will invoke the onActivityResult() in your activity or fragment class

Example

```<code>                    val intent = intent
                    intent.putExtra("key", "put values if you want")
                    setResult(Activity.RESULT_OK, intent)
                    finish()
</code>```

Body:
This is the extension function which i had created for starting activities for obtaining result, however the activity is getting started, but I'm not getting a call on onActivityResult

inline fun <reified T : Any> Activity.launchActivity(
requestCode: Int = -1,
noinline init: Intent.() -> Unit = {}
) {
val intent = Intent(this, T::class.java)
intent.init()
startActivityForResult(intent, requestCode)
}

onActivityResult callback

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    Timber.d("onActivityResult".plus(OrderProductFragment::class.java.simpleName))

Calling the extension inside a Fragment

(context as Activity).launchActivity<CartActivity> (1234) {
                putParcelableArrayListExtra(getString(R.string.cart_items_key), cartItems)
            }

Body:
You need to call this  setResult() when navigate back to fragment or activity where you are coming from
ie

setResult(Activity.RESULT_OK, intent)

this will invoke the onActivityResult() in your activity or fragment class

Example

                    val intent = intent
                    intent.putExtra("key", "put values if you want")
                    setResult(Activity.RESULT_OK, intent)
                    finish()


问:
STM32 Serial DMA - Finding the beginning of the Stream
I have a known serial stream format that I am capturing via the DMA. It has header and footer bytes. But sometimes the MCU starts capturing in the middle of the stream and then the sync is out because the DMA is looking for a set number of bytes. I have read of people using circular buffers, but I have struggled to grasp this concept.

Instead, I was thinking of disabling the DMA and enabling the a serial interrupt at the start up of the MCU. Then cycle through each byte that is captured by the interrupt to find the start byte. Then, once I have found the start byte, disable the serial interrupt capturing and enable the DMA to take over the capturing of the stream.

Does this sound feasible? Thanks for any input.

I am using STM32 HAL libs with the new STM32 IDE that includes STM32 CubeMX.

答:
If I understand your reference to circular buffers correctly, the concept is simple. You have a large buffer with a write pointer and a read pointer. The write function writes data into the buffer from the write pointer onward, taking care that once it reaches the end of the buffer, it wraps around and dumps the data at the beginning of the buffer and onward. Then you need a reader function that reads the data from the read pointer onward, and again, taking care of wrap around at the end of the buffer.

Both the read and write pointers start at the beginning of the buffer. The two conditions that you have to check are:
1) When the read pointer is at the same location as the write pointer, there is nothing (more) to read.
2) When the write pointer increments and runs into the read pointer location, you have a buffer overflow condition. This should never happen, so either you must use a larger buffer, or have the reader task runs more frequently, or you start throwing things out.

So in your scenario, the DMA just dumps data, and your reader task looks for the header bytes and processes the data until it finds the footer bytes.


问:
Gerrit prolog rule - setting accumulative voting adequately
I want to create the following rule:

The patch will become in submittable only there is 3 votes or more with +1, but THERE SHOULD NOT BE a vote with +2, only votes with +1 will be considered for this criterion.

The rule that i have is:

```<code>% rule      : 1+1+1=2 Code-Review
% rationale : introduce accumulative voting to determine if a change
%             is submittable or not and make the change submittable
%             if the total score is 3 or higher.

sum_list([], 0).
sum_list([H | Rest], Sum) :- sum_list(Rest,Tmp), Sum is H + Tmp.

add_category_min_score(In, Category, Min,  P) :-
    findall(X, gerrit:commit_label(label(Category,X),R),Z),
    sum_list(Z, Sum),
    Sum >= Min, !,
    gerrit:commit_label(label(Category, V), U),
    V >= 1,
    !,
    P = [label(Category,ok(U)) | In].

add_category_min_score(In, Category,Min,P) :-
    P = [label(Category,need(Min)) | In].

submit_rule(S) :-
    gerrit:default_submit(X),
    X =.. [submit | Ls],
    gerrit:remove_label(Ls,label('Code-Review',_),NoCR),
    add_category_min_score(NoCR,'Code-Review', 3, Labels),
    S =.. [submit | Labels].
</code>```

this rule does not works at all, the problem is with the +2 vote.
How can i rework this rule in order to works as i want?

答:
So you want to have min three reviewers that can add +1 and +2 is not allowed.

What if you remove developers rights to give +2 from project config and use prolog     cookbook example 13 with little modifications?

```<code>submit_rule(submit(CR)) :-
  sum(3, 'Code-Review', CR),
  % gerrit:max_with_block(-1, 1, 'Verified', V).

% Sum the votes in a category. Uses a helper function score/2
% to select out only the score values the given category.
sum(VotesNeeded, Category, label(Category, ok(_))) :-
  findall(Score, score(Category, Score), All),
  sum_list(All, Sum),
  Sum >= VotesNeeded,
  !.
sum(VotesNeeded, Category, label(Category, need(VotesNeeded))).

score(Category, Score) :-
  gerrit:commit_label(label(Category, Score), User).

% Simple Prolog routine to sum a list of integers.
sum_list(List, Sum)   :- sum_list(List, 0, Sum).
sum_list([X|T], Y, S) :- Z is X + Y, sum_list(T, Z, S).
sum_list([], S, S).
</code>```

Body:
I want to create the following rule:

The patch will become in submittable only there is 3 votes or more with +1, but THERE SHOULD NOT BE a vote with +2, only votes with +1 will be considered for this criterion.

The rule that i have is:

% rule      : 1+1+1=2 Code-Review
% rationale : introduce accumulative voting to determine if a change
%             is submittable or not and make the change submittable
%             if the total score is 3 or higher.

sum_list([], 0).
sum_list([H | Rest], Sum) :- sum_list(Rest,Tmp), Sum is H + Tmp.

add_category_min_score(In, Category, Min,  P) :-
    findall(X, gerrit:commit_label(label(Category,X),R),Z),
    sum_list(Z, Sum),
    Sum >= Min, !,
    gerrit:commit_label(label(Category, V), U),
    V >= 1,
    !,
    P = [label(Category,ok(U)) | In].

add_category_min_score(In, Category,Min,P) :-
    P = [label(Category,need(Min)) | In].

submit_rule(S) :-
    gerrit:default_submit(X),
    X =.. [submit | Ls],
    gerrit:remove_label(Ls,label('Code-Review',_),NoCR),
    add_category_min_score(NoCR,'Code-Review', 3, Labels),
    S =.. [submit | Labels].

this rule does not works at all, the problem is with the +2 vote.
How can i rework this rule in order to works as i want?

Body:
So you want to have min three reviewers that can add +1 and +2 is not allowed.

What if you remove developers rights to give +2 from project config and use prolog     cookbook example 13 with little modifications?

submit_rule(submit(CR)) :-
  sum(3, 'Code-Review', CR),
  % gerrit:max_with_block(-1, 1, 'Verified', V).

% Sum the votes in a category. Uses a helper function score/2
% to select out only the score values the given category.
sum(VotesNeeded, Category, label(Category, ok(_))) :-
  findall(Score, score(Category, Score), All),
  sum_list(All, Sum),
  Sum >= VotesNeeded,
  !.
sum(VotesNeeded, Category, label(Category, need(VotesNeeded))).

score(Category, Score) :-
  gerrit:commit_label(label(Category, Score), User).

% Simple Prolog routine to sum a list of integers.
sum_list(List, Sum)   :- sum_list(List, 0, Sum).
sum_list([X|T], Y, S) :- Z is X + Y, sum_list(T, Z, S).
sum_list([], S, S).


问:
Is there any tool to optimize MySQL Queries?
I am  undergoing the performance test on MySQL and i need your guidance.If there is any tool available to optimize the MySQL Queries.Please let me know.The tool i am  seeking for is one which would be useful to identify the query which causing the memory leak.

Thanks,

答:
using EXPLAIN in front of your query is a good starting point to understand what is going bad or too slow. So you can improve performances using primary/foreign keys and indexes.

A query, as Mitch Wheat said, doesn't produce a memory leak; maybe it takes a lot of time and consumes a lot of ram, but there are different reasons for this.


问:
URL rewrite apache
my problem today is to rewriting URL with apache on local wamp.

I've a page like:

```<code>localhost/TEST/index.php
</code>```

I would like this page like:

```<code>localhost/TEST/index
</code>```

I pass this step with:

```<code>Options +FollowSymLinks
RewriteEngine On
RewriteRule ^index$ /TEST/index.php [L,QSA,NC]
</code>```

The problem is I would like when I type localhost/TEST/index.php the url is redirect to localhost/TEST/index

How can i do that please?

Thx

答:
Did you resolve your problem? if not, try this :
RewriteRule ^Test/test$ Test/index.php [L]

Title: URL rewrite apache

Body:
my problem today is to rewriting URL with apache on local wamp.

I've a page like:

localhost/TEST/index.php

I would like this page like:

localhost/TEST/index

I pass this step with:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^index$ /TEST/index.php [L,QSA,NC]

The problem is I would like when I type localhost/TEST/index.php the url is redirect to localhost/TEST/index

How can i do that please?

Thx


问:
How to generate an array of unique objects from api?
I'm trying to disable booked times from calendar, depending on the date. My goal is to create an array, which holds objects with single date and array of booked times.
I have created an api, which outputs something like this:

```<code>"bookings": [
    {
     "_id": "5ce1b8792598adasf452",
     "workType": "Nail polishing",
     "client": "Mary Johnson",
     "date": "2019-05-31T00:00:00.000Z",
     "bookingTime": "09:00"
    },
    {
     "_id": "5ce1b8753hs53gasf452",
     "workType": "Makeup",
     "client": "Kate Bush",
     "date": "2019-05-31T00:00:00.000Z",
     "bookingTime": "10:00"
    }
]
</code>```

I've tried using Sets, filters, but I just can't seem to wrap my head around how to implement it to my own code.

Snippet of my code:

```<code>bookedTimes: []

fetchBookedTimes() {
      axios.get("http://localhost:8080/api/bookings").then(res => {
        for (var i = 0; i < res.data.bookings.length; i++) {
          this.bookedTimes.push({
            date: moment(res.data.bookings[i].date).format("YYYY-MM-DD"),
            times: [res.data.bookings[i].bookingTime.substring(0,2)]
          });
        }
      });
    }
</code>```

I expect the output to be

```<code>bookedTimes: [
        {
          date: "2019-05-31",
          times: ["09", "10"]
        },
        {
          date: "2019-06-01",
          times: ["10", "11"]
        }
      ]
</code>```

But the actual output is

```<code>bookedTimes: [
        {
          date: "2019-05-31",
          times: ["09"]
        },
        {
          date: "2019-05-31",
          times: ["10"]
        },
        {
          date: "2019-06-01",
          times: ["10"]
        },
        {
          date: "2019-06-01",
          times: ["11"]
        }
      ]
</code>```

答:
First, check if the date of already in the array. Check if 'times' already exist in 'object.times', if not, push it to the 'object.times' array.
Please see the code below.</p>

```<code>const date = moment(res.data.bookings[i].date).format("YYYY-MM-DD");
const times = res.data.bookings[i].bookingTime.substring(0, 2);

const arrayIndex = bookedTimes.findIndex(item => item.date === date);
//Check if date already exist in array
if (arrayIndex !== -1) {
  //Check if 'times' already exist in 'object.times'
  if (!bookedTimes[arrayIndex].times.includes(times)) {
    //Push 'times' in 'object.times'
    bookedTimes[arrayIndex].times.push(times);
  }
} else {
 //Push a new object into the array
  bookedTimes.push({
    date: date,
    times: [times]
  });
}
</code>```

Body:
I'm trying to disable booked times from calendar, depending on the date. My goal is to create an array, which holds objects with single date and array of booked times.
I have created an api, which outputs something like this:

"bookings": [
    {
     "_id": "5ce1b8792598adasf452",
     "workType": "Nail polishing",
     "client": "Mary Johnson",
     "date": "2019-05-31T00:00:00.000Z",
     "bookingTime": "09:00"
    },
    {
     "_id": "5ce1b8753hs53gasf452",
     "workType": "Makeup",
     "client": "Kate Bush",
     "date": "2019-05-31T00:00:00.000Z",
     "bookingTime": "10:00"
    }
]

I've tried using Sets, filters, but I just can't seem to wrap my head around how to implement it to my own code.

Snippet of my code:

bookedTimes: []

fetchBookedTimes() {
      axios.get("http://localhost:8080/api/bookings").then(res => {
        for (var i = 0; i < res.data.bookings.length; i++) {
          this.bookedTimes.push({
            date: moment(res.data.bookings[i].date).format("YYYY-MM-DD"),
            times: [res.data.bookings[i].bookingTime.substring(0,2)]
          });
        }
      });
    }

I expect the output to be

bookedTimes: [
        {
          date: "2019-05-31",
          times: ["09", "10"]
        },
        {
          date: "2019-06-01",
          times: ["10", "11"]
        }
      ]

But the actual output is

bookedTimes: [
        {
          date: "2019-05-31",
          times: ["09"]
        },
        {
          date: "2019-05-31",
          times: ["10"]
        },
        {
          date: "2019-06-01",
          times: ["10"]
        },
        {
          date: "2019-06-01",
          times: ["11"]
        }
      ]

Body:
First, check if the date of already in the array. Check if 'times' already exist in 'object.times', if not, push it to the 'object.times' array.
Please see the code below.

const date = moment(res.data.bookings[i].date).format("YYYY-MM-DD");
const times = res.data.bookings[i].bookingTime.substring(0, 2);

const arrayIndex = bookedTimes.findIndex(item => item.date === date);
//Check if date already exist in array
if (arrayIndex !== -1) {
  //Check if 'times' already exist in 'object.times'
  if (!bookedTimes[arrayIndex].times.includes(times)) {
    //Push 'times' in 'object.times'
    bookedTimes[arrayIndex].times.push(times);
  }
} else {
 //Push a new object into the array
  bookedTimes.push({
    date: date,
    times: [times]
  });
}


问:
PHP: compare substrings
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

```<code><?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>
</code>```

答:
```<code>if ( preg_match('/\\.cfg$/',$cal) ) echo "Hello ";
</code>```

should to it. (Assuming you want to match the end of the input string, otherwise, leave out the $)

Title: PHP: compare substrings

Body:
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

<?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>

Body:
if ( preg_match('/\\.cfg$/',$cal) ) echo "Hello ";

should to it. (Assuming you want to match the end of the input string, otherwise, leave out the $)