问:
Finding a maximum sum contiguous sub array
I am writing a code to find the maximum sum contiguous sub array in C. The logic seems fine according to me, but still the output is not correct. Please look into the code. The algorithm divides a bigger array into 2 sub-arrays. It then checks for maximum sum sub-array by examining the left array , right array and also the array containing the midpoint (It will check right and left from the midpoint and then return the maximum sum sub-array containing the midpoint). </p>

```<code>int* cross_max(int arr[], int low, int mid, int high)
{
    int left_max, left_sum = -2000;
    int sum = 0;
    int i;
    for(i=mid; i>=low;i--)
    {
        sum = sum + arr[i];
        if(sum > left_sum)
        {
            left_sum = sum;
            left_max = i;
        }
    }

    int right_max, right_sum = -2000;

    for(i=mid+1; i<=high;i++)
    {
        sum = sum + arr[i];
        if(sum > right_sum)
        {
            right_sum = sum;
            right_max = i;
        }
    }

    // 0 - sum
    // indices - 1,2

    int temp_arr[3] = {0,0,0};
    temp_arr[0] = left_sum + right_sum;
    temp_arr[1] = left_max;
    temp_arr[2] = right_max;

    int *p = temp_arr;

    printf("\n Maximum sum = %d\n",*p);
    printf("\n low = %d\n",*(p+1));
    printf("\n high = %d\n",*(p+2));

    return p;

}

int* find_max(int arr[], int low, int high)
{
    int temp_arr[3] = {0,0,0};
    if(low == high)
    {
        temp_arr[0] = arr[low];
        temp_arr[1] = low;
        temp_arr[2] = low;

        int *q = temp_arr;
        return q;
    }

    int mid = (low + high)/2;

    int* a1 =  find_max(arr,low,mid);
    int* a2 =  find_max(arr,mid+1,high);
    int* a3 =  cross_max(arr,low,mid,high);

    if (*a1 > *a2 && *a1 > *a3)
        return a1;

    else if (*a2 > *a1 && *a2 > *a3)
        return a2;

    else
        return a3;

}

int main()
{
    int arr[8] = {1,1,2,-2,3,3,4,-4};

    int *point = find_max(arr,0,7);

    printf("\n Maximum sum = %d\n",*point);
    printf("\n low = %d\n",*(point+1));
    printf("\n high = %d\n",*(point+2));
    return 0;
}
</code>```

答:
this is helper to get the max value.

```<code>int maxcmp(int a, int b) {
    return a >= b ? a : b;
}
</code>```

The idea is as you iterate over the nums, you add them together. If your cur_sum is less than 0 up to that point, you eliminate all the numbers so far. Because adding negative value after that point is not going to increase the total sum for the rest of nums.

```<code>int maxSubArray(int* nums, int numsSize){
    int maxSoFar = nums[0],
    cur_sum = 0;
    for(int i = 0; i < numsSize; i++) {
        if (cur_sum<0){
            cur_sum=0;
        }
        cur_sum=cur_sum+nums[i];
        maxSoFar=maxcmp(maxSoFar,cur_sum);
    }
    return maxSoFar;
}`enter code here`
</code>```

Body:
I am writing a code to find the maximum sum contiguous sub array in C. The logic seems fine according to me, but still the output is not correct. Please look into the code. The algorithm divides a bigger array into 2 sub-arrays. It then checks for maximum sum sub-array by examining the left array , right array and also the array containing the midpoint (It will check right and left from the midpoint and then return the maximum sum sub-array containing the midpoint).

int* cross_max(int arr[], int low, int mid, int high)
{
    int left_max, left_sum = -2000;
    int sum = 0;
    int i;
    for(i=mid; i>=low;i--)
    {
        sum = sum + arr[i];
        if(sum > left_sum)
        {
            left_sum = sum;
            left_max = i;
        }
    }

    int right_max, right_sum = -2000;

    for(i=mid+1; i<=high;i++)
    {
        sum = sum + arr[i];
        if(sum > right_sum)
        {
            right_sum = sum;
            right_max = i;
        }
    }

    // 0 - sum
    // indices - 1,2

    int temp_arr[3] = {0,0,0};
    temp_arr[0] = left_sum + right_sum;
    temp_arr[1] = left_max;
    temp_arr[2] = right_max;

    int *p = temp_arr;

    printf("\n Maximum sum = %d\n",*p);
    printf("\n low = %d\n",*(p+1));
    printf("\n high = %d\n",*(p+2));

    return p;

}

int* find_max(int arr[], int low, int high)
{
    int temp_arr[3] = {0,0,0};
    if(low == high)
    {
        temp_arr[0] = arr[low];
        temp_arr[1] = low;
        temp_arr[2] = low;

        int *q = temp_arr;
        return q;
    }

    int mid = (low + high)/2;

    int* a1 =  find_max(arr,low,mid);
    int* a2 =  find_max(arr,mid+1,high);
    int* a3 =  cross_max(arr,low,mid,high);

    if (*a1 > *a2 && *a1 > *a3)
        return a1;

    else if (*a2 > *a1 && *a2 > *a3)
        return a2;

    else
        return a3;

}

int main()
{
    int arr[8] = {1,1,2,-2,3,3,4,-4};

    int *point = find_max(arr,0,7);

    printf("\n Maximum sum = %d\n",*point);
    printf("\n low = %d\n",*(point+1));
    printf("\n high = %d\n",*(point+2));
    return 0;
}

Body:
this is helper to get the max value.

int maxcmp(int a, int b) {
    return a >= b ? a : b;
}

The idea is as you iterate over the nums, you add them together. If your cur_sum is less than 0 up to that point, you eliminate all the numbers so far. Because adding negative value after that point is not going to increase the total sum for the rest of nums.

int maxSubArray(int* nums, int numsSize){
    int maxSoFar = nums[0],
    cur_sum = 0;
    for(int i = 0; i < numsSize; i++) {
        if (cur_sum<0){
            cur_sum=0;
        }
        cur_sum=cur_sum+nums[i];
        maxSoFar=maxcmp(maxSoFar,cur_sum);
    }
    return maxSoFar;
}`enter code here`


来源: stackexchange

问:
Passing a parameter via URL to SQL Server Reporting Services
I'm trying to pass a userId (string) in the URL which will be passed to the database and used by a query in SSRS.

base URL:

```<code>http://blah/Reports/Pages/Report.aspx?ItemPath=MyReport
</code>```

I tried this, but it doesn't work:

```<code>http://blah/Reports/Pages/Report.aspx?ItemPath=MyReport&UserId=fred
</code>```

Any ideas?

答:
Use the URL, mentioned below to open the report in a new window with dynamic parameters.</p>
```<code>="javascript:void(window.open('http://Servername/ReportServer?/Foldername/Reportname&rs:Commnd=Render&parameter1=" & Fields!A.Value & "&parameter2=" & Fields!B.Value & "'))"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to pass a userId (string) in the URL which will be passed to the database and used by a query in SSRS.

base URL:

http://blah/Reports/Pages/Report.aspx?ItemPath=MyReport

I tried this, but it doesn't work:

http://blah/Reports/Pages/Report.aspx?ItemPath=MyReport&UserId=fred

Any ideas?

Body:
Use the URL, mentioned below to open the report in a new window with dynamic parameters.

="javascript:void(window.open('http://Servername/ReportServer?/Foldername/Reportname&rs:Commnd=Render&parameter1=" & Fields!A.Value & "&parameter2=" & Fields!B.Value & "'))"


问:
How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)
I'm just learning JSF 2 thanks to this site I had learned a lot in such a short time.

My question is regarding how to implement a common layout to all my JSF 2 pages and have only the content part of the page refresh not the whole page whenever I click a link/menu from a different panel.  I am using the Facelets approach it does what I want except that each time I click a link from a panel (e.g. menu items from left  panel)  the whole page is refreshed.  What I am looking for is a way to refresh only the content part of my page.  To illustrate this below is my target pagelayout.

  Did not post my code because I'm not sure if Facelets can do this .  Are there other approach more suited for my requirement other than Facelets?

答: If you only want to refresh part of the page, there are only 2 ways to go (for the web in general, not just JSF). You have to use frames or Ajax. JSF 2 supports ajax natively, check out the f:ajax tag to update just 1 component without reloading the entire page.</p>

ContentLicense: CC BY-SA 3.0


问:
Is it possible to create a C# Windows Service that detects new file creation on Windows XP?
I have a folder that will contain a temporary file that will be created by web service. I want the file to be converted by .exe program I have via command line. Now, I have already generated web service that will create file and store in one specific folder.

Here is the scenario:

Web service receive amr byte data from my mobile app.

Web service deletes all files existing in the folder. (to remove .amr file and .mp3 file that was generated from the previous round)

Web service create new .amr file in the folder.

Windows Service detects that there is a new file created. It call converter.exe. Once complete, it creates .mp3 file in the same folder.

Now, I have no problem with step1-3. The problem is step4, which I need to convert .amr file to .mp3 file. In order to do this, I need to pass some dos-command to converter.exe. I found that it is impossible for me to do it from my web service, so I am thinking of creating C# Windows Service that will watch the folder storing the files. Is it possible to create Windows Service that is able to detect new file creation and run converter.exe as soon as a new file is created ? I did search on the Internet and found that I may be create Windows Service with FileSystemWatcher, but i am just not sure if it will be possible.

The reason I found when trying to execute converter.exe from web service is about permission. I did everything but still can't make it success.(Using Web Service, converter.exe is shown on the process list in task manager as local system, but it will not be executed because of some security reason...) Hope there will be no security problem when I try to execute converter.exe using Windows Service.

Thanks in advance for all answers and suggestions :)

答: System.IO.FileSystemWatcher will do the trick. The Created event will tell you when a file has been created in the directory you're watching. To start your conversion program, take a look at the System.Diagnostics.Process.Start method. Both of these should work fine in a Windows service.


问:
Does JavaScript 'Set' work for HTMLStyleElement objects?
In my website there are some duplicated  but they have rules in element.sheet.cssRules inserted with insertRule (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule). I am wondering if Set works for these types of Style as well.

Body:
A Set contains values that are unique via the Object.is algorithm, which is nearly the same as how === works.

Separate <style> objects on the page, regardless of content are not ===, so you'll get a Set with all <style>s on the page with your current code.

The same is true for any HTMLElement, and even true for plain objects.

const set = new Set();
const obj1 = {};
const obj2 = {};
set.add(obj1);
set.add(obj2);
console.log(set.size);

If you want to de-duplicate, you will have to go another route - such as iterating through the rules of each style.


问:
How to update the contents of one cell based on the contents inputted inside another cell?
I want a cell to automatically update when the contents in another cell are changed so that the data in both the cells fit a function. For example I have some data in B2 and some other data in B3, I want there to be a kind of restrain of B2+B3 = 29. Suppose that B2 has a data of value x and B3 has a data of value y,so if I change B1 from say x to x+7, then the data in B2 should go from y to y-7.</p>

答:
You can make this constraint easily if you only need to input into B2 and never manually write into B3:

A
B
C

1

2

20

3

=29-B2

If you need to manually enter values into both B2 and B3 you could set up a validating function:

A
B
C

1

2

20

3

9

4

=If(B2+B3=29,"","B2 and B3 must sum to 29!")

You could also set up a conditional formatting rule to highlight invalid selections.

To automatically enter the other value to keep the total 29, you'd need VBA.


问:
MongoDB - Aggregate (join two collection) with nested array as join key
I have two collections. (updated)

I need to join them and return only a few fields.
As I understand, I should use aggregate and projection features.
I try to find examples, but can't find the right, in my case foreign key is placed in the array in the nested field.

It is not easy for me, I’m new at this, and I couldn’t win against this MongoDB query.

In the code block below I wrote the simplified equivalent models (doc1, doc2) and expected results.

Does anyone have any ideas?

```<code>db.doc1.deleteMany({});
db.doc2.deleteMany({});

// tow related documents

db.doc1.insert( [
    {
    "version" : 123456,
    "doc" : {
      "code":"A1",
      "name":"some document A1",
      "doc2CodeArray":[
          {"code":"B01"},
          {"code":"B02"},
          {"code":"B03"},
          {"code":"B04"},
          {"code":"B05"},
          {"code":"B06"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":[
          {"code":"B07"},
          {"code":"B08"},
          {"code":"B09"},
          {"code":"B10"},
          {"code":"B11"},
          {"code":"B12"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":null
      }
    }

]);

db.doc2.insert( [
    {
        "version" : 567890,
        "doc" : {
          "code":"B01",
          "valueArray":[{"valueType":"int","valueData":"1"}],
          "doc2Type":{"code":"C1"}
        }
    },
    {"version" : 567890,"doc" : { "code":"B02", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B03", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B04", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B05", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B06", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false},
                                                              {"valueType":"str","valueData":"F","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},

    {"version" : 567890,"doc" : { "code":"B07", "valueArray":[{"valueType":"int","valueData":"1","isDefault":false}],"doc2Type":{"code":"C1","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B08", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B09", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B10", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B11", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B12", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},
    ]);
</code>```

The result that I want

```<code>  I need join collections and select only few props
  {
      "doc":{code:"A1"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"3"}},
        {"code":"C3", "value":{"value":"4"}},
      ]
  },
  {
      "doc":{code:"A2"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"2"}},
        {"code":"C3", "value":{"value":"3"}},
        {"code":"C4", "value":{"value":"4"}},
      ]
  }
</code>```

答:
$lookup - Join doc1 with doc2.

Pipeline:

1.1. $match - Matching doc.code (from doc2) is within the doc.doc2CodeArray.code array (from doc1).

1.2. $project - Decorate output document to be returned in doc2Items.

$project - Decorate output document.

```<code>db.doc1.aggregate([
  {
    $lookup: {
      from: "doc2",
      let: {
        doc2CodeArray: "$doc.doc2CodeArray.code"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$doc.code",
                "$$doc2CodeArray"
              ]
            }
          }
        },
        {
          $project: {
            _id: 0,
            "doc2TypeCode": "$doc.doc2Type.code",
            "doc2ValueArray": "$doc.valueArray"
          }
        }
      ],
      as: "doc2Items"
    }
  },
  {
    $project: {
      _id: 0,
      "doc1Code": "$doc.code",
      "doc1Name": "$doc.name",
      "doc2Items": "$doc2Items"
    }
  }
])
</code>```

Sample Mongo Playground

Body:
I have two collections. (updated)

I need to join them and return only a few fields.
As I understand, I should use aggregate and projection features.
I try to find examples, but can't find the right, in my case foreign key is placed in the array in the nested field.

It is not easy for me, I’m new at this, and I couldn’t win against this MongoDB query.

In the code block below I wrote the simplified equivalent models (doc1, doc2) and expected results.

Does anyone have any ideas?

db.doc1.deleteMany({});
db.doc2.deleteMany({});

// tow related documents

db.doc1.insert( [
    {
    "version" : 123456,
    "doc" : {
      "code":"A1",
      "name":"some document A1",
      "doc2CodeArray":[
          {"code":"B01"},
          {"code":"B02"},
          {"code":"B03"},
          {"code":"B04"},
          {"code":"B05"},
          {"code":"B06"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":[
          {"code":"B07"},
          {"code":"B08"},
          {"code":"B09"},
          {"code":"B10"},
          {"code":"B11"},
          {"code":"B12"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":null
      }
    }

]);

db.doc2.insert( [
    {
        "version" : 567890,
        "doc" : {
          "code":"B01",
          "valueArray":[{"valueType":"int","valueData":"1"}],
          "doc2Type":{"code":"C1"}
        }
    },
    {"version" : 567890,"doc" : { "code":"B02", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B03", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B04", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B05", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B06", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false},
                                                              {"valueType":"str","valueData":"F","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},

    {"version" : 567890,"doc" : { "code":"B07", "valueArray":[{"valueType":"int","valueData":"1","isDefault":false}],"doc2Type":{"code":"C1","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B08", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B09", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B10", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B11", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B12", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},
    ]);

The result that I want

  I need join collections and select only few props
  {
      "doc":{code:"A1"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"3"}},
        {"code":"C3", "value":{"value":"4"}},
      ]
  },
  {
      "doc":{code:"A2"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"2"}},
        {"code":"C3", "value":{"value":"3"}},
        {"code":"C4", "value":{"value":"4"}},
      ]
  }

Body:
$lookup - Join doc1 with doc2.

Pipeline:

1.1. $match - Matching doc.code (from doc2) is within the doc.doc2CodeArray.code array (from doc1).

1.2. $project - Decorate output document to be returned in doc2Items.

$project - Decorate output document.

db.doc1.aggregate([
  {
    $lookup: {
      from: "doc2",
      let: {
        doc2CodeArray: "$doc.doc2CodeArray.code"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$doc.code",
                "$$doc2CodeArray"
              ]
            }
          }
        },
        {
          $project: {
            _id: 0,
            "doc2TypeCode": "$doc.doc2Type.code",
            "doc2ValueArray": "$doc.valueArray"
          }
        }
      ],
      as: "doc2Items"
    }
  },
  {
    $project: {
      _id: 0,
      "doc1Code": "$doc.code",
      "doc1Name": "$doc.name",
      "doc2Items": "$doc2Items"
    }
  }
])

Sample Mongo Playground


问:
Bootstrap 4 Collapse state with Font Awesome icon
I have a Bootstrap-table with Expand / Collapse but the start icon is not good.
The start icon when collapsed is "minus" and should be "plus", but if it's cliked 2 times, everything is OK.

I have used this example : Bootstrap 4 Collapse show state with Font Awesome icon

my code : https://jsfiddle.net/d7ycu6ne/

Thanks for your help

答:
Your CSS:

[data-toggle="collapse"].collapsed .fa:before {
  content: "\f067"; /*plus*/
}
```
<p>requires the row to have a class called "<code>collapsed</code>" in order to show the plus. But you haven't given it that class:</p>
<pre class="lang-html prettyprint-override"><code><td data-toggle="collapse" data-target="#accordion1"
    class="clickable" style="cursor:pointer">
</code>```

If you use your browser's dev tools to look at the DOM, you will see that the Bootstrap library is adding that "collapsed" class whenever you click the minus to collapse (beginning with the second click).

So of course you should start the element with that class already applied:

```

Body:
Your CSS:

[data-toggle="collapse"].collapsed .fa:before {
  content: "\f067"; /*plus*/
}

requires the row to have a class called "collapsed" in order to show the plus. But you haven't given it that class:

<td data-toggle="collapse" data-target="#accordion1"
    class="clickable" style="cursor:pointer">

If you use your browser's dev tools to look at the DOM, you will see that the Bootstrap library is adding that "collapsed" class whenever you click the minus to collapse (beginning with the second click).

So of course you should start the element with that class already applied:

<td data-toggle="collapse" data-target="#accordion1"
    class="clickable collapsed" style="cursor:pointer">


问:
Pinned SliverPersistentHeader overlaps with Android StatusBar
I'm working with Slivers. I have an SliverAppBar, then a SliverPersistentHeader and finally a SliverList.

The behavior I want to achieve is that the SliverAppBar scrolls off the screen but the SliverPersistentHeader to remain pinned at the top of the screen.

I am able to do that but the SliverPersistentHeader overlaps with the android status bar. Any idea on how can I fix this?

Finally this is the code

```<code>class ExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          title: Text('SliverAppBar'),
          pinned: false,
          floating: true,
          snap: true,
          elevation: 0.0,
        ),
        SliverPersistentHeader(
          pinned: true,
          delegate: _SliverAppBarDelegate(
            child: PreferredSize(
            preferredSize: Size.fromHeight(40.0),
            child: Container(
              color: Theme.of(context).primaryColor,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text('SliverPersistentHeader', style: TextStyle(color: Colors.white, fontSize: 20.0))
                  ],
                ),
              ),
            ),
          )
          ),
        ),
        SliverFixedExtentList(
        itemExtent: 150.0,
        delegate: SliverChildListDelegate(
          [
            Container(color: Colors.red),
            Container(color: Colors.purple),
            Container(color: Colors.green),
            Container(color: Colors.orange),
            Container(color: Colors.yellow),
            Container(color: Colors.pink),
          ],
        ),
      ),
      ],
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final PreferredSize child;

  _SliverAppBarDelegate({ this.child });

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    // TODO: implement build
    return child;
  }

  @override
  // TODO: implement maxExtent
  double get maxExtent => child.preferredSize.height;

  @override
  // TODO: implement minExtent
  double get minExtent => child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    // TODO: implement shouldRebuild
    return false;
  }

}
</code>```

答:
Additionally, you may need to hold your scroll widgets with an scaffold:</p>
```<code>return Scaffold(
           body: SafeArea(
                 child: CustomScrollView...
</code>```

Body:
I'm working with Slivers. I have an SliverAppBar, then a SliverPersistentHeader and finally a SliverList.

The behavior I want to achieve is that the SliverAppBar scrolls off the screen but the SliverPersistentHeader to remain pinned at the top of the screen.

I am able to do that but the SliverPersistentHeader overlaps with the android status bar. Any idea on how can I fix this?

Finally this is the code

class ExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          title: Text('SliverAppBar'),
          pinned: false,
          floating: true,
          snap: true,
          elevation: 0.0,
        ),
        SliverPersistentHeader(
          pinned: true,
          delegate: _SliverAppBarDelegate(
            child: PreferredSize(
            preferredSize: Size.fromHeight(40.0),
            child: Container(
              color: Theme.of(context).primaryColor,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text('SliverPersistentHeader', style: TextStyle(color: Colors.white, fontSize: 20.0))
                  ],
                ),
              ),
            ),
          )
          ),
        ),
        SliverFixedExtentList(
        itemExtent: 150.0,
        delegate: SliverChildListDelegate(
          [
            Container(color: Colors.red),
            Container(color: Colors.purple),
            Container(color: Colors.green),
            Container(color: Colors.orange),
            Container(color: Colors.yellow),
            Container(color: Colors.pink),
          ],
        ),
      ),
      ],
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final PreferredSize child;

  _SliverAppBarDelegate({ this.child });

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    // TODO: implement build
    return child;
  }

  @override
  // TODO: implement maxExtent
  double get maxExtent => child.preferredSize.height;

  @override
  // TODO: implement minExtent
  double get minExtent => child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    // TODO: implement shouldRebuild
    return false;
  }

}

Body:
Additionally, you may need to hold your scroll widgets with an scaffold:

return Scaffold(
           body: SafeArea(
                 child: CustomScrollView...


问:
How to convert mixed time formats with strings to military time?
I have a variable that needs to be converted to military time. This variable is very messy because it lacks consistency in the format.

Here is an example of what might be found in the variable.

```<code>x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")
</code>```

So far I had some success in getting everything in a more consistent format with RegEx:

```<code>x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")
</code>```

As you can see I get: "0.9305555555555547", "1520", "1000", "0.125", "1525"

The problem is the decimals need to be multiplied by 2400 to get back to military time but I also don't want to multiply integers (since those are already in military time).

x is essentially a variable in a dataframe.

I was thinking about using if/else logic but I don't know how to implement that.

To clarify, I want:

Input: "0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 15:25"

Output: "2233", "1520", "1000", "0300", "1525"

答:
I followed your logic literally and got the exact same result.

Numeric conversion

Multiply by 2400 and back to character

for loop to detect dots in the character and delete after that

for loop to put 0 in front of numbers with less than 4 characters

```<code>x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")

x <- as.numeric(x)

x <- as.character(ifelse(x<1,x*2400,x))

for(i in 1:length(x)){

  ii <- stri_locate_first_regex(x[i],"\\.")[1]

  if(!is.na(ii)){

    x[i] <- str_sub(x[i],1,ii-1)

  }

}

for(i in 1:length(x)){

  while (nchar(x[i])<4) {

    x[i] <- paste0("0",x[i])

  }

}

x
[1] "2233" "1520" "1000" "0300" "1525"
>
</code>```

Body:
I have a variable that needs to be converted to military time. This variable is very messy because it lacks consistency in the format.

Here is an example of what might be found in the variable.

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

So far I had some success in getting everything in a more consistent format with RegEx:

x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")

As you can see I get: "0.9305555555555547", "1520", "1000", "0.125", "1525"

The problem is the decimals need to be multiplied by 2400 to get back to military time but I also don't want to multiply integers (since those are already in military time).

x is essentially a variable in a dataframe.

I was thinking about using if/else logic but I don't know how to implement that.

To clarify, I want:

Input: "0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 15:25"

Output: "2233", "1520", "1000", "0300", "1525"

Body:
I followed your logic literally and got the exact same result.

Numeric conversion

Multiply by 2400 and back to character

for loop to detect dots in the character and delete after that

for loop to put 0 in front of numbers with less than 4 characters

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")

x <- as.numeric(x)

x <- as.character(ifelse(x<1,x*2400,x))

for(i in 1:length(x)){

  ii <- stri_locate_first_regex(x[i],"\\.")[1]

  if(!is.na(ii)){

    x[i] <- str_sub(x[i],1,ii-1)

  }

}

for(i in 1:length(x)){

  while (nchar(x[i])<4) {

    x[i] <- paste0("0",x[i])

  }

}

x
[1] "2233" "1520" "1000" "0300" "1525"
>


问:
Does MySQL always run foreign key constraint checks when a row is updated? Or only when a relevant column is changed?
I have this question and I haven't found specific documentation to confirm the behavior and am unaware of how to manually check this myself.

Consider I have table A with b_id foreign key to table B. If I run an update on a row in table A, does mysql always run the foreign key constraint check on table B even if A's b_id goes unchanged or isn't passed in the update statement? such as (select 1 from B where id = ?)

Example:

UPDATE A set A.name = "x", A.b_id = 1 where A.id = 1 I know this runs the foreign key check on B

UPDATE A set A.name = "x" where A.id = 1 But does this also run the foreign key check even though b_id goes unchanged since it was not passed?

UPDATE A set A.name = "x" A.b_id = A.b_id where A.id = 1 And what about this? b_id gets passed in with same existing value. Does the fk check run?

Any supporting documentation or help would be appreciated, as well as tips on how I can test this sort of behavior myself since using EXPLAIN doesn't help.

Edit: this is for INNODB engine and mysql 8.0

答:
When you add a foreign key constraint, MySQL requires an index:

MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.

To clarify, this is an index in the referencing table (in your example A), not the referenced table (in your example B). The index in table B you have to provide yourself, otherwise you will get an error message.

Given this index, the answer to your question can be summarized to:

The foreign key constraint will be verified (e.g. the check if the row exists in the referenced table) whenever this index will be modified.

Since it may not be completely obvious when this happens, some examples: for a sample table of

```<code>CREATE TABLE A (id int primary key, b_id int, c int,
    FOREIGN KEY (b_id) REFERENCES B(id))
</code>```

the foreign key (e.g. if the value exists in the referenced table B) is checked for (assuming that such a row exists):

```<code>update A set id = 2 where id = 1
</code>```

as it modifies the primary key, which is part of every index, so that hidden index gets modified, thus the verification will be executed, and

```<code>update A set b_id = 3 where b_id = 2
</code>```

as it modifies the column b_id, which is part of the hidden index, so that hidden index gets modified.

It does NOT get checked for

```<code>update A set id = 2 where id = 2
update A set b_id = 3 where b_id = 3
update A set b_id = b_id
</code>```

as those do not modify the index content (because nothing changes).

Notably

```<code>update A set c = 2 where c = 3
</code>```

also does not modify the index (as c is not part of the index), so the foreign key constraint is not verified even though the row itself changes.

To make things a bit more complicated, you can use your own index:

```<code>CREATE TABLE A (id int primary key, b_id int, c int,
    INDEX b_c (b_id, c),
    FOREIGN KEY (b_id) REFERENCES B(id))
</code>```

If you do that, MySQL can use this index for your foreign key and doesn't have to add its own hidden index. The effects of the updates mentioned above will not change, except for

```<code>update A set c = 2 where c = 3
</code>```

as now, c is a column of the index that MySQL uses for the foreign key constraint, abd this update requires a modification of the index content - and thus triggers a verification. This is actually a verification that logically would not be required - it just happens because of how MySQL implemented it. So if you really want to prevent every unnecessary check, you could add an index on just column b_id yourself, then MySQL won't use the index on (b_id, c). But that would be extreme micro-optimization and you really should not do it just for this.

Please note that, while this may be an interesting technical detail to know, it should not have any impact on what you actually do with the database. You should not write your queries differently with that knowledge. If you need to update a row, you have to update the row. Also, adding an index just to prevent a check will most certainly not help. Also, since the behaviour is not specified, it can also change at any time (e.g. by you if you find and implement a better solution).

Body:
When you add a foreign key constraint, MySQL requires an index:

MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.

To clarify, this is an index in the referencing table (in your example A), not the referenced table (in your example B). The index in table B you have to provide yourself, otherwise you will get an error message.

Given this index, the answer to your question can be summarized to:

The foreign key constraint will be verified (e.g. the check if the row exists in the referenced table) whenever this index will be modified.

Since it may not be completely obvious when this happens, some examples: for a sample table of

CREATE TABLE A (id int primary key, b_id int, c int,
    FOREIGN KEY (b_id) REFERENCES B(id))

the foreign key (e.g. if the value exists in the referenced table B) is checked for (assuming that such a row exists):

update A set id = 2 where id = 1

as it modifies the primary key, which is part of every index, so that hidden index gets modified, thus the verification will be executed, and

update A set b_id = 3 where b_id = 2

as it modifies the column b_id, which is part of the hidden index, so that hidden index gets modified.

It does NOT get checked for

update A set id = 2 where id = 2
update A set b_id = 3 where b_id = 3
update A set b_id = b_id

as those do not modify the index content (because nothing changes).

Notably

update A set c = 2 where c = 3

also does not modify the index (as c is not part of the index), so the foreign key constraint is not verified even though the row itself changes.

To make things a bit more complicated, you can use your own index:

CREATE TABLE A (id int primary key, b_id int, c int,
    INDEX b_c (b_id, c),
    FOREIGN KEY (b_id) REFERENCES B(id))

If you do that, MySQL can use this index for your foreign key and doesn't have to add its own hidden index. The effects of the updates mentioned above will not change, except for

update A set c = 2 where c = 3

as now, c is a column of the index that MySQL uses for the foreign key constraint, abd this update requires a modification of the index content - and thus triggers a verification. This is actually a verification that logically would not be required - it just happens because of how MySQL implemented it. So if you really want to prevent every unnecessary check, you could add an index on just column b_id yourself, then MySQL won't use the index on (b_id, c). But that would be extreme micro-optimization and you really should not do it just for this.

Please note that, while this may be an interesting technical detail to know, it should not have any impact on what you actually do with the database. You should not write your queries differently with that knowledge. If you need to update a row, you have to update the row. Also, adding an index just to prevent a check will most certainly not help. Also, since the behaviour is not specified, it can also change at any time (e.g. by you if you find and implement a better solution).


问:
How important is optimization?
I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.

My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".

What does the StackOverflow.com community think?

答:
I think the premature optimization quote is used by too many to avoid thinking about the hard stuff concerning how well the application will run. I guarantee the users want you to think about how to design it so it will run as fast as possible.

This is not to say you should be timing everything, but the design phase is the easiest place to optimize and not cost lots of time later.

There are often several ways to do anything, you should pick in the design phase the one which is most likely to perform the best (if it turns out to be one of the times when it isn't the best, then optimize later). This should trump the need to have easy to read code.

If you aren't considering performance in the design phase, you aren't going to have a well designed system. That doesn't mean it should be the only concern (although in a database I'd rate it as 3rd in importance, right after data integrity and security), but trying to fix a system where poorly performing techniques were used throughout because the developers thought they were easier to understand is a nightmare. Being a user of such a system where you have to wait for minutes everytime you want to move from one screen to another is a nightmare (developers reallly should spend all day everyday for at least a week, using their systems!) for everyone who is stuck with the badly designed system. It costs less to design properly  than to fix later and considering performance is critical to designing properly.

I work somewhere where the orginal developers drank the koolaid about premature optimization and did everything the way they thought was simplest (but which in almost every case was the wrong choice from a performance perspective). Now we are at 10 times the size we were three years ago and every screen on every website takes 30 seconds or so to load (or worse times out) and we are losing customers because of it. But changing it will be too hard because at the base they designed the database without considering how it would perform and redesigning a database with many many gigabytes of data into a new structure is way too time consuming and costly. If it had been designed to perform from the start it would be both easier to maintain and faster for the clients. We aren't talking about the need to performance tune the top 10 slowest queries here, we are talking about the fact that the overall structure requires a drastic change (one that would affect virtually every query against the system) to perform well.

Yes don't do micro optimization until you nmeed to, but please do the macro stuff. Consider if is this the best way before you commit to the path. Don't write cursors to hit tables with millions of records when a set-based statement will do. Don't try to have as few tables as possible becasue that seems to be a more elegant solution when the tables are storing disparate items (such as people, places, and vehicles) causing every single query to hit the same table and causing every delete to check all sorts of foreign key tables that will not ever have a record for that type of entity (it takes minutes to delete one record from the main table in our database, it's a real joy when something goes wrong in an import (bad data from a client usually) and we have to delete 200,000 let me tell you).

OwnerDisplayName: dicroce

ContentLicense: CC BY-SA 2.5

Title: How important is optimization?

LastEditorDisplayName: jpalecek

OwnerDisplayName: HLGEM


问:
How to avoid repeated SendMessage
I have a problem: I use SendMessage from a procedure in a DLL to communicate with the main window; procedure is a hook procedure that allows main window to know when mouse right button is clicked in a editbox; it sends also handle of the editbox. It works well, except for this bug: when program is running without breakpoints main window receives twice the same message (in this case WM_APP), while if I put a breakpoint in the hook procedure or in the block that handles WM_APP messages the message is considered once. For further descriptions ask me. Following the code of the hook procedure and of the block that handles WM_APP messages. Thanks

Hook procedure

```<code>MYDLL_API LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// processes the message
if(nCode >= 0)
{
    // if user clicked with mouse right button
    if(wParam != NULL && (wParam == WM_RBUTTONDOWN || wParam == WM_RBUTTONUP))
    {
        wchar_t *s = (wchar_t*) malloc(CLASSNAMELEN*sizeof(wchar_t));
        //MessageBox(mainHwnd, (LPCWSTR)L"Captured mouse right button", (LPCWSTR)L"Test", MB_OK);
        MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
        GetClassName(m->hwnd, (LPWSTR) s, CLASSNAMELEN);
        //MessageBox(mainHwnd, (LPCWSTR) s, (LPCWSTR)L"Test", MB_OK);
        // only if user clicked on a edit box
        if(wcsncmp(s, L"Edit", 4) == 0)
            SendMessage(mainHwnd, WM_APP, 0, (LPARAM) lParam);
        free(s);
        s = NULL;
    }
}

// calls next hook in chain
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
</code>```

block in main program that handles WM_APP messages

```<code>case WM_APP:
    {
        //MessageBox(hWnd, (LPCWSTR)L"Received WM_APP", (LPCWSTR)L"Test", MB_OK);
        // copies text from the edit box
        MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
        int n = GetWindowTextLength(m->hwnd);
        // if text has been inserted
        if(n > 0 && n < 1024)
        {
            wchar_t *s = (wchar_t*) malloc((n+1)*sizeof(wchar_t));
            // gets text
            GetWindowText(m->hwnd, (LPWSTR) s, n+1);
            s[n] = (wchar_t) 0;
            //MessageBox(hWnd, (LPCWSTR)s, (LPCWSTR)L"Test", MB_OK);
            // saves text in database
            stateClassPointer->insertInList(s);
        }
    }
    break;
</code>```

答:
It is probably because you are sending the message for WM_RBUTTONDOWN and WM_RBUTTONUP, that is when the right button is pressed and when it is released.

When you are debugging the WM_RBUTTONUP is eaten by the debugger so you don't get it.

PS: Shouldn't you use PostMessage() instead of SendMessage(), just to be safe?

Title: How to avoid repeated SendMessage

Body:
I have a problem: I use SendMessage from a procedure in a DLL to communicate with the main window; procedure is a hook procedure that allows main window to know when mouse right button is clicked in a editbox; it sends also handle of the editbox. It works well, except for this bug: when program is running without breakpoints main window receives twice the same message (in this case WM_APP), while if I put a breakpoint in the hook procedure or in the block that handles WM_APP messages the message is considered once. For further descriptions ask me. Following the code of the hook procedure and of the block that handles WM_APP messages. Thanks

Hook procedure

MYDLL_API LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// processes the message
if(nCode >= 0)
{
    // if user clicked with mouse right button
    if(wParam != NULL && (wParam == WM_RBUTTONDOWN || wParam == WM_RBUTTONUP))
    {
        wchar_t *s = (wchar_t*) malloc(CLASSNAMELEN*sizeof(wchar_t));
        //MessageBox(mainHwnd, (LPCWSTR)L"Captured mouse right button", (LPCWSTR)L"Test", MB_OK);
        MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
        GetClassName(m->hwnd, (LPWSTR) s, CLASSNAMELEN);
        //MessageBox(mainHwnd, (LPCWSTR) s, (LPCWSTR)L"Test", MB_OK);
        // only if user clicked on a edit box
        if(wcsncmp(s, L"Edit", 4) == 0)
            SendMessage(mainHwnd, WM_APP, 0, (LPARAM) lParam);
        free(s);
        s = NULL;
    }
}

// calls next hook in chain
return CallNextHookEx(NULL, nCode, wParam, lParam);
}

block in main program that handles WM_APP messages

case WM_APP:
    {
        //MessageBox(hWnd, (LPCWSTR)L"Received WM_APP", (LPCWSTR)L"Test", MB_OK);
        // copies text from the edit box
        MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
        int n = GetWindowTextLength(m->hwnd);
        // if text has been inserted
        if(n > 0 && n < 1024)
        {
            wchar_t *s = (wchar_t*) malloc((n+1)*sizeof(wchar_t));
            // gets text
            GetWindowText(m->hwnd, (LPWSTR) s, n+1);
            s[n] = (wchar_t) 0;
            //MessageBox(hWnd, (LPCWSTR)s, (LPCWSTR)L"Test", MB_OK);
            // saves text in database
            stateClassPointer->insertInList(s);
        }
    }
    break;


问:
How to Test & Prove my custom Map is thread safe
I was recently asked in an interview to implement a thread safe implementation of Map class in java and assume that no thread safe library exists.

```<code>interface Map{
        void put(String key, String value);
        String get(String key);
        String delete(string key);
 }
</code>```

I wrapped the HashMap and just made the functions synchronized.
Here is my implementation:

```<code>class MyMap{

     Map<String, String> map;

     public MyMap(){
           map = new HashMap<>();
     }

     public synchronized void put(String key, String value){
           map.put(key, value);
     }

     public String get(String key){
           return map.get(key);
     }

    public synchronized String delete(String key){
           return map.remove(key);
     }
</code>```

}

While adding synchronized allows thread safety, I really don't know how to prove if this is correct or not.

I tried writing the following unit test but couldn't really convince that my map is thread safe as I don't know if the get will happen first or put will happen first.

```<code>Thread t1 = new Thread(()->{ map.put("testKey1", "testValue1") });
Thread t2 = new Thread(()->{ map.put("testKey2", "testValue2") });

t1.start();
t2.start();

Thread t3 = new Thread(()->{ System.out.println(map.get("testKey1")) });
Thread t4 = new Thread(()->{ System.out.println(map.get("testKey2")) });

t3.start();
t4.start();

</code>```

I saw the ConcurrentHashMap class' implementation and looks like they use Segments which are too complicated to tell in an interview.

Can someone suggest if my implementation is thread safe, and if yes how to have a test to prove it.

答: Your test should make sure you are not able to add the same element twice, and you are not able to delete the same element twice. In each of the cases there should be an exception thrown in the second thread whichever it is. I don't see any reason to make get synchonous.</p>

Body:
I was recently asked in an interview to implement a thread safe implementation of Map class in java and assume that no thread safe library exists.

interface Map{
        void put(String key, String value);
        String get(String key);
        String delete(string key);
 }

I wrapped the HashMap and just made the functions synchronized.
Here is my implementation:

class MyMap{

     Map<String, String> map;

     public MyMap(){
           map = new HashMap<>();
     }

     public synchronized void put(String key, String value){
           map.put(key, value);
     }

     public String get(String key){
           return map.get(key);
     }

    public synchronized String delete(String key){
           return map.remove(key);
     }

}

While adding synchronized allows thread safety, I really don't know how to prove if this is correct or not.

I tried writing the following unit test but couldn't really convince that my map is thread safe as I don't know if the get will happen first or put will happen first.

Thread t1 = new Thread(()->{ map.put("testKey1", "testValue1") });
Thread t2 = new Thread(()->{ map.put("testKey2", "testValue2") });

t1.start();
t2.start();

Thread t3 = new Thread(()->{ System.out.println(map.get("testKey1")) });
Thread t4 = new Thread(()->{ System.out.println(map.get("testKey2")) });

t3.start();
t4.start();

I saw the ConcurrentHashMap class' implementation and looks like they use Segments which are too complicated to tell in an interview.

Can someone suggest if my implementation is thread safe, and if yes how to have a test to prove it.


问:
Matrix multiplied by a vector without using numpy
Without using numpy in python

I am running into the error "object of type 'int' has no len()" when running the code below when multiplying the matrix C with the vector A.

Any help would be appreciated

```<code>A = [3, 4, 8]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]

def MM(C, A):
  c = []
  for i in range(0, len(C)):
    temp=[]
    for j in range(0, len(A[0])):
        s = 0
        for k in range(0, len(C[0])):
            s += C[i][k] * A[k][j]
        temp.append(s)
    c.append(temp)
  return c
print("Matrix C multiplied by vector A is: \n", MM(C, A))
</code>```

答:
The problem is here:

```<code>for j in range(0, len(A[0])):
</code>```

A[0] is 3, which is an integer and has no attribute len. A is also a 1D array so A[k][j] will also raise an error.

Body:
Without using numpy in python

I am running into the error "object of type 'int' has no len()" when running the code below when multiplying the matrix C with the vector A.

Any help would be appreciated

A = [3, 4, 8]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]

def MM(C, A):
  c = []
  for i in range(0, len(C)):
    temp=[]
    for j in range(0, len(A[0])):
        s = 0
        for k in range(0, len(C[0])):
            s += C[i][k] * A[k][j]
        temp.append(s)
    c.append(temp)
  return c
print("Matrix C multiplied by vector A is: \n", MM(C, A))

Body:
The problem is here:

for j in range(0, len(A[0])):

A[0] is 3, which is an integer and has no attribute len. A is also a 1D array so A[k][j] will also raise an error.


问:
Add fixed spacing between two internal elements of a list
I am working on building a basic to-do list.

I have a list of elements with delete option for each element next to it.

I am facing issues with having proper spacing between the list elements namely "to-do text" and "Delete" icon.

Note: I'm new to Web programming.

答:
You could set a fixed width on the container element and then use flex box:

<!DOCTYPE HTML>

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

sample text

delete icon

long sample text for illustration purposes.

delete icon

```

Body:
You could set a fixed width on the container element and then use flex box:

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            .container {
                display: flex;
                background-color: grey;
                border: 1px solid darkGrey;
                width: 300px;
                padding: 10px 15px;
            }
            .title {
                flex: 1;
                padding-right: 3px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="title">sample text</div>
            <div>delete icon</div>
        </div>
        <div class="container">
            <div class="title">long sample text for illustration purposes.</div>
            <div>delete icon</div>
        </div>
    </body>
</html>


问:
Why does this closure require inlining or `dyn`? What does `dyn` do here?
I'm confused about what's going on with lifetimes below:

struct Foo{}
impl Foo {
    fn foo(&self, _s: &str) {}
}

fn main() {
    let foo = &Foo{};
    let closure = |s| foo.foo(s);

    // Part 1: error message about wrong lifetime in FnOnce
    take_closure(closure);

    // Part 2: no error when inlined
    take_closure(|s| foo.foo(s));

    // Part 3: no error when `dyn`d and given explicit signature
    let closure: &dyn Fn(&str) -> _ = &|s| foo.foo(s);
    take_closure(closure);
}

fn take_closure(f: impl Fn(&str) -> ()) {
    let s = get_string();
    f(&s)
}

fn get_string() -> String {
    "".to_string()
}
```

playground

Why does Part 1 error?

Why does Part 2 not error?

Why does Part 3 not error and what actually happens in part 3? Does Rust make a vtable? The LLVM outputs differ between 2 and 3

Is there a better way? Inlining is ugly and dyn is both ugly and makes me wonder about what it actually does.

答:
Why does Part 1 error?

Rust's type inference is not great at deciding what type a closure should have, when the closure is declared separately from where it is used. When the closure accepts references, the compiler often assumes that there is some specific lifetime that will be involved, not “any lifetime the caller cares to provide” as is actually required here.

In fact, there's an active Rust RFC to improve this by adding another way to specify lifetime parameters on closures. (The RFC also contains an example where making the opposite lifetime assumption would not work.)

what actually happens in part 3? Does Rust make a vtable?

Yes, there's a vtable involved whenever you use dyn. That's not especially relevant to the root cause here; it's just that the elided lifetime in dyn Fn(&str) got resolved the way you needed rather than the way you didn't.

Is there a better way? Inlining is ugly and dyn is both ugly and makes me wonder about what it actually does.

Placing a closure directly in the function call expression that uses it is very common Rust style, and I recommend you stick to it whenever possible, since it's also the way that works well with type inference.

As a workaround in the case where you need to use a closure more than once, you could pass the closure through a function that constrains its type:

fn string_acceptor<F: Fn(&str) -> ()>(f: F) -> F {
    f
}

...

    let foo = &Foo{};
    let closure = string_acceptor(|s| foo.foo(s));
```

Body:
I'm confused about what's going on with lifetimes below:

struct Foo{}
impl Foo {
    fn foo(&self, _s: &str) {}
}

fn main() {
    let foo = &Foo{};
    let closure = |s| foo.foo(s);

    // Part 1: error message about wrong lifetime in FnOnce
    take_closure(closure);

    // Part 2: no error when inlined
    take_closure(|s| foo.foo(s));

    // Part 3: no error when `dyn`d and given explicit signature
    let closure: &dyn Fn(&str) -> _ = &|s| foo.foo(s);
    take_closure(closure);
}

fn take_closure(f: impl Fn(&str) -> ()) {
    let s = get_string();
    f(&s)
}

fn get_string() -> String {
    "".to_string()
}

playground

Why does Part 1 error?

Why does Part 2 not error?

Why does Part 3 not error and what actually happens in part 3? Does Rust make a vtable? The LLVM outputs differ between 2 and 3

Is there a better way? Inlining is ugly and dyn is both ugly and makes me wonder about what it actually does.


问:
How to find the frequency of characters in a string in Haskell?
How can I count the frequency of characters in a string and then output them in sort of a table?

For example, if I input the word "happy" the result would be

```<code>h 1
a 1
p 2
y 1
</code>```

If this could be ordered in ASCII order too that would be brilliant.

I know I need to use the count function, any other hints would be appreciated.

EDIT: All the answers are brilliant, only I'm such a beginner at Haskell that I don't actually understand what they are doing.

答:
I'll scetch a solution step by step. A shorter solution is possible using standard functions.

You want a sorted result, therefore

```<code>result = sort cs
    where
</code>```

cs would be a list of tuples, where the first element is the character and the second element is the number of times it appears.

```<code>        cs = counts "happy"
        counts [] = []
        counts (c:cs) = (c, length otherc + 1) : counts nonc where
             (otherc, nonc) = partition (c==) cs
</code>```

That's all.

Interestingly, counts works on any list of items that support the == operator.

Body:
How can I count the frequency of characters in a string and then output them in sort of a table?

For example, if I input the word "happy" the result would be

h 1
a 1
p 2
y 1

If this could be ordered in ASCII order too that would be brilliant.

I know I need to use the count function, any other hints would be appreciated.

EDIT: All the answers are brilliant, only I'm such a beginner at Haskell that I don't actually understand what they are doing.

Body:
I'll scetch a solution step by step. A shorter solution is possible using standard functions.

You want a sorted result, therefore

result = sort cs
    where

cs would be a list of tuples, where the first element is the character and the second element is the number of times it appears.

        cs = counts "happy"
        counts [] = []
        counts (c:cs) = (c, length otherc + 1) : counts nonc where
             (otherc, nonc) = partition (c==) cs

That's all.

Interestingly, counts works on any list of items that support the == operator.


问:
DropDownMenu with icon flutter
New in flutter. Want to build the drop-down menu list with icon.
Doesn't show any error but stop emulator. Please help me to build like this.

[![Click here to see image][2]][2]
[![Error in Exceptions][1]][1]

    const catagoryItem = [
    CatagoryItem(name: 'Crypto', iconPath: 'assets/icons/crytoicon.png'),
    CatagoryItem(name: 'Crypto', iconPath: 'assets/icons/crytoicon.png'),
    CatagoryItem(name: 'Crypto', iconPath: 'assets/icons/crytoicon.png'),
    CatagoryItem(name: 'Crypto', iconPath: 'assets/icons/crytoicon.png'),
  ];

 //..
      DropdownButton(items: catagoryItem.map((e) => DropdownMenuItem(child: Row(
            children: [
              SizedBox(
                height: 5.h,
                width: 6.w,
                child: Image.asset(e.iconPath),),
                SizedBox(
                  width: 2.w,
                ),
                Text(e.name,style: TextStyle(fontSize: 16.sp),),

            ],

        ))).toList(), onChanged: null)

  [1]: https://i.stack.imgur.com/toPZp.png
  [2]: https://i.stack.imgur.com/M2V6A.png
```

答:
I tried your code (without the flutter_screenutil stuff), it works fine.

I suggest you start by removing those and see if it works, i.e. change width: 2.w to something like width: 8 and whatnot. Also try completely stopping the debug process and restart again, because it might be a hot reload issue too.

Title: DropDownMenu with icon flutter


答:
Edit: I realized this:

the decimals need to be multiplied by 2400 to get back to military time

Isn't quite right. "2400" isn't a decimal number (technically it's sexagesimal, base 60), so decimal multiplication won't give a correct result. I've changed my code accordingly.

Rather than using the same regex on everything right out the gate, I would first determine the format of each element of x, then process the element accordingly.

I like the hms library for working with times and use it below, but you could also use the base POSIXct or POSIXlt class.

```<code>library(tidyverse)
library(hms)

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

# ----
# define functions for parsing each possible format in `x`
parse_decimal <- function(x) {
  hrs <- as.numeric(str_extract(x, "^0\\.\\d+")) * 24
  min <- (hrs %% 1) * 60
  hrs <- floor(hrs)
  hms(hours = hrs, minutes = min)
}

parse_timestring <- function(x) {
  out <- str_remove_all(x, "\\D")
  hr_digits <- if_else(str_length(out) == 3, 1, 2)
  hrs <- as.numeric(str_sub(out, end = hr_digits))
  hrs <- if_else(str_detect(str_to_upper(x), "P\\.?M"), hrs + 12, hrs)
  min <- as.numeric(str_sub(out, start = hr_digits + 1))
  hms(hours = hrs, minutes = min)
}

# ----
# test each element of x, and pass to appropriate parsing Fx
time <- case_when(
  str_detect(x, "^[01]$|^0\\.\\d") ~ parse_decimal(x),
  str_detect(x, "\\d{1,2}:?\\d{2}") ~ parse_timestring(x),
  TRUE ~ NA_real_
)

time
# 22:20:00.000000
# 15:20:00.000000
# 10:00:00.000000
# 03:00:00.000000
# 15:25:00.000000
</code>```

Title: How to convert mixed time formats with strings to military time?

Body:
Edit: I realized this:

the decimals need to be multiplied by 2400 to get back to military time

Isn't quite right. "2400" isn't a decimal number (technically it's sexagesimal, base 60), so decimal multiplication won't give a correct result. I've changed my code accordingly.

Rather than using the same regex on everything right out the gate, I would first determine the format of each element of x, then process the element accordingly.

I like the hms library for working with times and use it below, but you could also use the base POSIXct or POSIXlt class.

library(tidyverse)
library(hms)

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

# ----
# define functions for parsing each possible format in `x`
parse_decimal <- function(x) {
  hrs <- as.numeric(str_extract(x, "^0\\.\\d+")) * 24
  min <- (hrs %% 1) * 60
  hrs <- floor(hrs)
  hms(hours = hrs, minutes = min)
}

parse_timestring <- function(x) {
  out <- str_remove_all(x, "\\D")
  hr_digits <- if_else(str_length(out) == 3, 1, 2)
  hrs <- as.numeric(str_sub(out, end = hr_digits))
  hrs <- if_else(str_detect(str_to_upper(x), "P\\.?M"), hrs + 12, hrs)
  min <- as.numeric(str_sub(out, start = hr_digits + 1))
  hms(hours = hrs, minutes = min)
}

# ----
# test each element of x, and pass to appropriate parsing Fx
time <- case_when(
  str_detect(x, "^[01]$|^0\\.\\d") ~ parse_decimal(x),
  str_detect(x, "\\d{1,2}:?\\d{2}") ~ parse_timestring(x),
  TRUE ~ NA_real_
)

time
# 22:20:00.000000
# 15:20:00.000000
# 10:00:00.000000
# 03:00:00.000000
# 15:25:00.000000


问:
strtok never gets NULL value, and ignores code after the while loop
I am writing a program right now that tokenizes multiple strings from a text file.

I have a while loop that continues to run until the end of the file. And nested in that loop, I have another while loop using strtok() to tokenize strings.

But, in my nested while loop with strtok(), I test with an if statement to see if I get NULL at the end of a string, but I never receive the NULL value. After the nested loop, it seems to break out of both loops, and also skips code outside of the main while loop, and ends my program with return 0;.

```<code>#include<iostream>
#include<fstream>
#include<string.h>
#include<iomanip>

using namespace std;

int main(int argc, char* argv[])
{
    //variable declarations
    ifstream inputfile;
    ofstream outputfile;
    char line[100];
    char* ptr;

    //check how many arguments in command line
    cout << "argc: " << argc << endl << endl;

    //check if there is input and output command line argument
    if (argc < 3)
    {
        cout << "missing input and output files";
    }
    cout << argv[1] << endl;
    cout << argv[2] << endl << endl;
    //cout <<"Null: " << NULL << endl;

    //opens input file from command line argument
    inputfile.open(argv[1]);

    //opens output file from command line argument
    outputfile.open(argv[2]);

    //check if input file is open
    if (!inputfile)
    {
        cout << "file not open"<< endl;
    }

    //check for input
    while (!inputfile.eof())
    {

        //inputfile = input, getline, line = output, 100 = delimiter
        //grabs the line.
        inputfile.getline(line, 100);

        //check for line
        cout << line << endl;

        //grabs first word
        ptr = strtok(line, " ");
        cout << ptr << endl;

        //loops until null
        while(ptr!=NULL)
        {
            //grabs other words until end of line
            ptr = strtok(NULL, " ");
            cout << ptr << endl;

            if (ptr==NULL)
            {
                cout << "hit NULL" << endl;
            }

        }

        cout << "afterloop" << endl;

    }

    cout << "end";

    return 0;
}
</code>```

答:
As @chris's answer stated, you are invoking undefined behavior by passing NULL pointers to operator<<.

And, you should NOT use inputfile.eof() in a while loop.  Loop on inputfile.getline() instead and let it break the loop when it can't read another line.

You are also not validating things very well in general, and not exiting the program when pre-conditions are not satisfactory.

Try something more like this instead:

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>

using namespace std;

int main(int argc, char* argv[])
{
    //variable declarations
    ifstream inputfile;
    ofstream outputfile;
    char line[100];
    char* ptr;

    //check how many arguments in command line
    cout << "argc: " << argc << endl << endl;

    //check if there is input and output command line argument
    if (argc < 3)
    {
        cout << "missing input and output files";
        return 0;
    }

    cout << argv[1] << endl;
    cout << argv[2] << endl << endl;
    //cout << "Null: " << NULL << endl;

    //opens input file from command line argument
    inputfile.open(argv[1]);

    //opens output file from command line argument
    outputfile.open(argv[2]);

    //check if input file is open
    if (!inputfile.is_open())
    {
        cout << "input file not open" << endl;
        return 0;
    }

    //check if output file is open
    if (!outputfile.is_open())
    {
        cout << "output file not open" << endl;
        return 0;
    }

    //check for input
    while (inputfile.getline(line, 100))
    {
        //check for line
        cout << line << endl;

        //grabs first word
        ptr = strtok(line, " ");
        if (ptr != NULL)
        {
            do
            {
                cout << ptr << endl;

                //grabs other words until end of line
                ptr = strtok(NULL, " ");
            }
            while (ptr != NULL);

            cout << "hit NULL" << endl;
        }

        cout << "afterloop" << endl;
    }

    cout << "end";

    return 0;
}
</code>```

Body:
I am writing a program right now that tokenizes multiple strings from a text file.

I have a while loop that continues to run until the end of the file. And nested in that loop, I have another while loop using strtok() to tokenize strings.

But, in my nested while loop with strtok(), I test with an if statement to see if I get NULL at the end of a string, but I never receive the NULL value. After the nested loop, it seems to break out of both loops, and also skips code outside of the main while loop, and ends my program with return 0;.

#include<iostream>
#include<fstream>
#include<string.h>
#include<iomanip>

using namespace std;

int main(int argc, char* argv[])
{
    //variable declarations
    ifstream inputfile;
    ofstream outputfile;
    char line[100];
    char* ptr;

    //check how many arguments in command line
    cout << "argc: " << argc << endl << endl;

    //check if there is input and output command line argument
    if (argc < 3)
    {
        cout << "missing input and output files";
    }
    cout << argv[1] << endl;
    cout << argv[2] << endl << endl;
    //cout <<"Null: " << NULL << endl;

    //opens input file from command line argument
    inputfile.open(argv[1]);

    //opens output file from command line argument
    outputfile.open(argv[2]);

    //check if input file is open
    if (!inputfile)
    {
        cout << "file not open"<< endl;
    }

    //check for input
    while (!inputfile.eof())
    {

        //inputfile = input, getline, line = output, 100 = delimiter
        //grabs the line.
        inputfile.getline(line, 100);

        //check for line
        cout << line << endl;

        //grabs first word
        ptr = strtok(line, " ");
        cout << ptr << endl;

        //loops until null
        while(ptr!=NULL)
        {
            //grabs other words until end of line
            ptr = strtok(NULL, " ");
            cout << ptr << endl;

            if (ptr==NULL)
            {
                cout << "hit NULL" << endl;
            }

        }

        cout << "afterloop" << endl;

    }

    cout << "end";

    return 0;
}

Body:
As @chris's answer stated, you are invoking undefined behavior by passing NULL pointers to operator<<.

And, you should NOT use inputfile.eof() in a while loop.  Loop on inputfile.getline() instead and let it break the loop when it can't read another line.

You are also not validating things very well in general, and not exiting the program when pre-conditions are not satisfactory.

Try something more like this instead:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>

using namespace std;

int main(int argc, char* argv[])
{
    //variable declarations
    ifstream inputfile;
    ofstream outputfile;
    char line[100];
    char* ptr;

    //check how many arguments in command line
    cout << "argc: " << argc << endl << endl;

    //check if there is input and output command line argument
    if (argc < 3)
    {
        cout << "missing input and output files";
        return 0;
    }

    cout << argv[1] << endl;
    cout << argv[2] << endl << endl;
    //cout << "Null: " << NULL << endl;

    //opens input file from command line argument
    inputfile.open(argv[1]);

    //opens output file from command line argument
    outputfile.open(argv[2]);

    //check if input file is open
    if (!inputfile.is_open())
    {
        cout << "input file not open" << endl;
        return 0;
    }

    //check if output file is open
    if (!outputfile.is_open())
    {
        cout << "output file not open" << endl;
        return 0;
    }

    //check for input
    while (inputfile.getline(line, 100))
    {
        //check for line
        cout << line << endl;

        //grabs first word
        ptr = strtok(line, " ");
        if (ptr != NULL)
        {
            do
            {
                cout << ptr << endl;

                //grabs other words until end of line
                ptr = strtok(NULL, " ");
            }
            while (ptr != NULL);

            cout << "hit NULL" << endl;
        }

        cout << "afterloop" << endl;
    }

    cout << "end";

    return 0;
}


问:
Regular expression for anchor tag with all attributes
I'm trying to get a regular expression to replace all the links out of a text string for the value of the link.

A link may look like these:

```<code><a href="http://whatever" id="an_id" rel="a_rel">the link</a>
<a href="/absolute_url/whatever" id="an_id" rel="a_rel">the link</a>
</code>```

I want a regular expression that I get: the link

Body:
I'm trying to get a regular expression to replace all the links out of a text string for the value of the link.

A link may look like these:

the link
the link

I want a regular expression that I get: the link

Body:
I just added explicitly named groups:

<a.*href\s?=['"]*(?<href>[^'"]*)[^>]*>((?<text>(.(?!\<\/a\>))*.))<\/a>

https://regex101.com/r/sbtcYr/1


问:
How can I use React icons in Placeholder?
Is it possible to use React icons in placeholder attribute of input field i-e input text for example?

If yes can some one give me an example?

I do it like this but instead of Icon I got [object object] in placeholder

```<code>var  emailIcon = <FaEnvelopeO  size={10}  />;
<Field
 placeholder={emailIcon}
 name="email"
 type="text"
 component={this.renderField}
/>
</code>```

答: You can directly paste  (emoji) in placeholder just like react-icons website did. https://react-icons.github.io/react-icons/</p>

Body:
Is it possible to use React icons in placeholder attribute of input field i-e input text for example?

If yes can some one give me an example?

I do it like this but instead of Icon I got [object object] in placeholder

var  emailIcon = <FaEnvelopeO  size={10}  />;
<Field
 placeholder={emailIcon}
 name="email"
 type="text"
 component={this.renderField}
/>


问:
How to calculate the average of all vertical, horizontal and diagonal neighbours of a cell in a matrix (2D-list)?
Given a 2D-list of integers, how can I calculate the average of the vertical, horizontal and diagonal neighbors of each element? The results need to be printed as floating point numbers and in a matrix with every row on one line.

So an example 2D-list is:

```<code>matrix = [[3, 9, 0],
          [4, 1, 4],
          [3, 8, 5]]
</code>```

and the output for this one would then be:

```<code>[4.666666666666667, 2.4, 4.666666666666667]
[4.8, 4.5, 4.6]
[4.333333333333333, 3.4, 4.333333333333333]
</code>```

As further clarification. For the element in row and column 1 it would be:

(9+4+1)/3 = 4.667

答:
Okay, I have written the solution with try-except mechanism. The issue that can occur here is the fact, that in python it is possible to make negative indexing, so for your matrix the command matrix[-1][-1] returns 5.

Solution? Simple if clause.

```<code>matrix = [[1,2,3],[4,5,6],[7,8,9]]
rows=len(matrix)
cols=len(matrix[0])
sumation=[]
numbers=[]
for i in range(rows):
    for j in range(cols):
        print(i,j)
        val=0
        values=[]
        if (i-1>=0 and j-1>=0):
            val+=matrix[i-1][j-1]
            values.append(matrix[i-1][j-1])

        if (i-1>=0):
            val+=matrix[i-1][j]
            values.append(matrix[i-1][j])

        if (i-1>=0):
            try:
                val+=matrix[i-1][j+1]
                values.append(matrix[i-1][j+1])
            except IndexError:
                pass

        if (j-1>=0):
            val+=matrix[i][j-1]
            values.append(matrix[i][j-1])

        try:
            val+=matrix[i][j+1]
            values.append(matrix[i][j+1])
        except IndexError:
            pass

        if (j-1>=0):
            try:
                val+=matrix[i+1][j-1]
                values.append(matrix[i+1][j-1])
            except IndexError:
                pass
        try:
            val+=matrix[i+1][j]
            values.append(matrix[i+1][j])
        except IndexError:
            pass

        try:
            val+=matrix[i+1][j+1]
            values.append(matrix[i+1][j+1])
        except IndexError:
            pass
        sumation.append(val)
        numbers.append(values)
print(sumation)
print(numbers)
</code>```

There is the code to sum each neighbour elements of matrix element, i guess you will manage from here.

Body:
Given a 2D-list of integers, how can I calculate the average of the vertical, horizontal and diagonal neighbors of each element? The results need to be printed as floating point numbers and in a matrix with every row on one line.

So an example 2D-list is:

matrix = [[3, 9, 0],
          [4, 1, 4],
          [3, 8, 5]]

and the output for this one would then be:

[4.666666666666667, 2.4, 4.666666666666667]
[4.8, 4.5, 4.6]
[4.333333333333333, 3.4, 4.333333333333333]

As further clarification. For the element in row and column 1 it would be:

(9+4+1)/3 = 4.667

Body:
Okay, I have written the solution with try-except mechanism. The issue that can occur here is the fact, that in python it is possible to make negative indexing, so for your matrix the command matrix[-1][-1] returns 5.

Solution? Simple if clause.

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rows=len(matrix)
cols=len(matrix[0])
sumation=[]
numbers=[]
for i in range(rows):
    for j in range(cols):
        print(i,j)
        val=0
        values=[]
        if (i-1>=0 and j-1>=0):
            val+=matrix[i-1][j-1]
            values.append(matrix[i-1][j-1])

        if (i-1>=0):
            val+=matrix[i-1][j]
            values.append(matrix[i-1][j])

        if (i-1>=0):
            try:
                val+=matrix[i-1][j+1]
                values.append(matrix[i-1][j+1])
            except IndexError:
                pass

        if (j-1>=0):
            val+=matrix[i][j-1]
            values.append(matrix[i][j-1])

        try:
            val+=matrix[i][j+1]
            values.append(matrix[i][j+1])
        except IndexError:
            pass

        if (j-1>=0):
            try:
                val+=matrix[i+1][j-1]
                values.append(matrix[i+1][j-1])
            except IndexError:
                pass
        try:
            val+=matrix[i+1][j]
            values.append(matrix[i+1][j])
        except IndexError:
            pass

        try:
            val+=matrix[i+1][j+1]
            values.append(matrix[i+1][j+1])
        except IndexError:
            pass
        sumation.append(val)
        numbers.append(values)
print(sumation)
print(numbers)

There is the code to sum each neighbour elements of matrix element, i guess you will manage from here.


答:
I haven't stepped through your entire logic to fix the code, but I see the error.

In this line you try to take the length of A[0] for j in range(0, len(A[0]))

You have defined A as:
A = [3,4,8]

Therefore A[0] = 3 and is an integer, which doesn't have a len()

Title: Matrix multiplied by a vector without using numpy


问:
c++, pointers, references, passing from one to another function, std::vector, std::string
i have a specific problem with pointers and references, with std::vector and std::string. Some question are in the following code snipped, some below.

I have basically this code

```<code>//first of all: is this function declaration good?
//or shoudl I already pass the std::vector in another way?
//I'm only reading from it
void func(const std::vector<std::string>& vec)
{
    //I need to call otherFunc(void*) with  a single element from vec:
    //otherFunc(void* arg);
    //with arg being a void* to vec[0]
}
</code>```

My IDE tells me that only &*vec[0] works as parameter for otherFunc, but this doesn't compile...

How is the best way to do these kind of parameter passing?

答:
That is a good declaration, as long as the function is not intended to modify the vector. It's more efficient than passing by value, since it avoids copying the vector - an expensive operation requiring a memory allocation.

However, the other function requires a non-const pointer. How to handle this depends on whether it might modify the data.

If it won't (as you imply when you say "I'm only reading from it") then the options are:

Change it to otherFunc(void const * arg) to give a stronger guarantee that it won't, or

Remove the const qualification with a const_cast<void*> when calling it

Note that &*vec[0] won't compile; you want vec[0].c_str() to get a C-compatible pointer to the first string's data, assuming that's what you need.

If it might modify the vector, then you'll have to do something else, since there's no legal way to modify a std::string through a pointer to its data. Probably the best option is to use std::vector<char> rather than std::string, but that depends on exactly what the function does.

Body:
i have a specific problem with pointers and references, with std::vector and std::string. Some question are in the following code snipped, some below.

I have basically this code

//first of all: is this function declaration good?
//or shoudl I already pass the std::vector in another way?
//I'm only reading from it
void func(const std::vector<std::string>& vec)
{
    //I need to call otherFunc(void*) with  a single element from vec:
    //otherFunc(void* arg);
    //with arg being a void* to vec[0]
}

My IDE tells me that only &*vec[0] works as parameter for otherFunc, but this doesn't compile...

How is the best way to do these kind of parameter passing?


问:
Trigger automatic pull/push for submodule after new commit appear
I have a project A and I have added a submodule to another project B.

I see that the submodule used in A is referring to a particular commit, and I would like this to be updated every time a new commit appears in B.

Is it possible to trigger an automatic pull/push of the submodule in A when B is updated?

Or this procedure has to be done always by hand?

答:
You might consider:

making sure your submodule B, in repository A, follows a branch (main, for instance)

using a multi-project pipeline

You can set up GitLab CI/CD across multiple projects, so that a pipeline in one project can trigger a pipeline in another project. You can visualize the entire pipeline in one place, including all cross-project inter-dependencies.

Your first pipeline would be triggered only on pushes.

And it includes a trigger to your project A, which would then execute a git submodule update --remote, in order to update the submodule B.


问:
Install pre-commit on package install in setup.py file
I would like, when I install my python package with pip install ., that the command pre-commit install be run as well as everything else in the setup file.

Here is my setup.py file where I try to execute this:

```<code>from distutils.core import setup
from distutils.command.build import build as _build
from setuptools import find_packages, Command
import subprocess

class InstallPreCommit(Command):
    def run(self):
        subprocess.run(['pre-commit', 'install'])

# This class handles the pip install mechanism.
class build(_build):
    sub_commands = _build.sub_commands

setup(
    name="my-pkg",
    version="0.0.1",
    packages=find_packages(),
    install_requires=['pre-commit'],
    py_modules=["pkg"],
    cmdclass={
        'build': build,
        'install-pre-commit': InstallPreCommit
        }
)
</code>```

However, when I run this, pre-commit install does not get run. I'm mostly taking inspiration from this SO post and this setup.py file in Apache Beam.

Does anyone have a sense of how to make sure I am invoking the setup of my package as well as calling my custom command, which runs the pre-commit install command?

答:
you don't actually want to do this, and the packaging system tries very hard to prevent you from doing this.

the main hurdles:

pip usually only runs setup.py once and then caches the result as a wheel

pip will sometimes build your package in a directory unrelated to your git repository

sometimes the library or tool won't be available (ordering) at the time of installation

and last of all, something that does this subverts the expectations of the python community -- that installation should not have side-effects outside of making the package available

ignoring all of that, you can trudge onwards and hack around the bits that attempt to prevent you

the rough stages for that are:

prevent wheeling of your package -- during the attempted wheeling make sure to exit, pip will usually fall back to just installing without wheeling

attempt to find the original working directory (either $PWD or via assumptions of the running executable

attempt to find the git repository you're running in

and lastly, make sure the tool is available

I've done all the dirty work for you, and I would strongly recommend not doing this -- https://github.com/pre-commit/pre-commit-installed

disclaimer, I created pre-commit, I also created pre-commit-installed but purely as a joke / proof of concept

Body:
I would like, when I install my python package with pip install ., that the command pre-commit install be run as well as everything else in the setup file.

Here is my setup.py file where I try to execute this:

from distutils.core import setup
from distutils.command.build import build as _build
from setuptools import find_packages, Command
import subprocess

class InstallPreCommit(Command):
    def run(self):
        subprocess.run(['pre-commit', 'install'])

# This class handles the pip install mechanism.
class build(_build):
    sub_commands = _build.sub_commands

setup(
    name="my-pkg",
    version="0.0.1",
    packages=find_packages(),
    install_requires=['pre-commit'],
    py_modules=["pkg"],
    cmdclass={
        'build': build,
        'install-pre-commit': InstallPreCommit
        }
)

However, when I run this, pre-commit install does not get run. I'm mostly taking inspiration from this SO post and this setup.py file in Apache Beam.

Does anyone have a sense of how to make sure I am invoking the setup of my package as well as calling my custom command, which runs the pre-commit install command?


问:
How to parse the file name string from a file path in shell script?
I have files in directory  'new_kb'. I want to iterate on each file and execute a c++ binary on the file, like below:

```<code>kb_dir=./new_kb
for entry in "$kb_dir"/*
do
  echo "$entry"
   $file_name  = parse(entry)
  ./build "$file_name"/"$file_name".txt
  done
</code>```

One example of 'entry' is:

```<code>./new_kb/peopleObj.txt
</code>```

from the variable path 'entry', I need to parse the string below out:

```<code>'peopleObj'
</code>```

How to do this in a shell script?

答:
Use basename

```<code>$file_name=$(basename $entry .txt)
</code>```

Body:
I have files in directory  'new_kb'. I want to iterate on each file and execute a c++ binary on the file, like below:

kb_dir=./new_kb
for entry in "$kb_dir"/*
do
  echo "$entry"
   $file_name  = parse(entry)
  ./build "$file_name"/"$file_name".txt
  done

One example of 'entry' is:

./new_kb/peopleObj.txt

from the variable path 'entry', I need to parse the string below out:

'peopleObj'

How to do this in a shell script?

Body:
Use basename

$file_name=$(basename $entry .txt)


问:
Output live football scores (real time) via Bluetooth
I have a personal project in mind but I don't know where to start.

For example: Barcelona - Real Madrid.

When one of the teams scores a goal, I want to output this via my Bluetooth speaker. for example:

Barcelona scored 1 goal. it's 1-0 now.

答:
I have a rough idea. Try using python to scrape the live score from the internet. Then when that score is scraped, you can use a Text to speech package and connect that to your speaker. You can program the speaker to say different teams scores at different times.

Recap:
Scrape online scores with python, use text to speech on the scraped scores.


问:
Fast Algorithm for partial sums on a list
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

```<code>def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result
</code>```

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

答:
You could setup the resulting list starting with the total sum and progressively extend it reducing the last element by values in the original list:

```<code>ls = [1, 2, 3, 4, 5, 6]

r = [sum(ls)]
r.extend(r[-1]-n for n in ls)

print(r)
# [21, 20, 18, 15, 11, 6, 0]
</code>```

Or, using itertools, accumulate the sum backwards and reverse the result:

```<code>from itertools import accumulate

r = [*accumulate([0]+ls[::-1])][::-1]

print(r)
# [21, 20, 18, 15, 11, 6, 0]
</code>```

Body:
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

Body:
You could setup the resulting list starting with the total sum and progressively extend it reducing the last element by values in the original list:

ls = [1, 2, 3, 4, 5, 6]

r = [sum(ls)]
r.extend(r[-1]-n for n in ls)

print(r)
# [21, 20, 18, 15, 11, 6, 0]

Or, using itertools, accumulate the sum backwards and reverse the result:

from itertools import accumulate

r = [*accumulate([0]+ls[::-1])][::-1]

print(r)
# [21, 20, 18, 15, 11, 6, 0]


问:
Recursive division over a list
I'm looking to divide every element of an list recursivly like this.

a_list = [1, 2, 3, 4, 5]
so the returns would be 1/(2/(3/(4/5)))

```<code>def c(y):

    if not y:
        return 1  # division by 1 don't matter

    return c(y[1:])[0] / c(y[2:])[1]  # Not allowed
</code>```

答:
You could use simple recursion over the indices. For example:

```<code>a_list = [i + 1 for i in range(6)]

def divide(index: int = 0) -> float:
    if index == len(a_list):
        return 1
    return a_list[index] / divide(index + 1)

print(divide()) # 0.3125
</code>```

Or, an equivalent implementation but with the list passed as an argument:

```<code>def divide(a_list: list, index: int = 0) -> float:
    if index == len(a_list):
        return 1
    return a_list[index] / divide(a_list, index + 1)

a_list = [i + 1 for i in range(6)]
print(divide(a_list)) # 0.3125
</code>```

Or, using your original approach:

```<code>def divide(a_list: list) -> float:
    if not a_list:
        return 1
    n, *d = a_list
    return n / divide(d)

a_list = [i + 1 for i in range(6)]
print(divide(a_list)) # 0.3125
</code>```

Title: Recursive division over a list

Body:
I'm looking to divide every element of an list recursivly like this.

a_list = [1, 2, 3, 4, 5]
so the returns would be 1/(2/(3/(4/5)))

def c(y):

    if not y:
        return 1  # division by 1 don't matter

    return c(y[1:])[0] / c(y[2:])[1]  # Not allowed

Body:
You could use simple recursion over the indices. For example:

a_list = [i + 1 for i in range(6)]

def divide(index: int = 0) -> float:
    if index == len(a_list):
        return 1
    return a_list[index] / divide(index + 1)

print(divide()) # 0.3125

Or, an equivalent implementation but with the list passed as an argument:

def divide(a_list: list, index: int = 0) -> float:
    if index == len(a_list):
        return 1
    return a_list[index] / divide(a_list, index + 1)

a_list = [i + 1 for i in range(6)]
print(divide(a_list)) # 0.3125

Or, using your original approach:

def divide(a_list: list) -> float:
    if not a_list:
        return 1
    n, *d = a_list
    return n / divide(d)

a_list = [i + 1 for i in range(6)]
print(divide(a_list)) # 0.3125


答:
I think you need A = [[3], [4], [8]]. When the matrix is on the left side of the multiplication, you are multiplying it with a column vector instead of a row vector.

Keeping your code the same, but changing A as mentioned, I get the output:

```<code>[[98], [33], [67]]
</code>```

which corresponds to the 3x1 column vector you would expect to get by doing this matrix multiplication.

If you instead wanted A to be a row vector on the left side of the multiplication, you could set:

```<code>A = [[3, 4, 8]]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]
</code>```

and print

```<code>print("The vector A multiplied by the matrix C is: \n", MM(A, C))
</code>```

to give the output:

```<code>[[26, 91, 65]]
</code>```

This would be a 1x3 row vector multiplied by a 3x3 matrix to give a 1x3 result.

Body:
Without using numpy in python

I am running into the error "object of type 'int' has no len()" when running the code below when multiplying the matrix C with the vector A.

Any help would be appreciated

A = [3, 4, 8]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]

def MM(C, A):
  c = []
  for i in range(0, len(C)):
    temp=[]
    for j in range(0, len(A[0])):
        s = 0
        for k in range(0, len(C[0])):
            s += C[i][k] * A[k][j]
        temp.append(s)
    c.append(temp)
  return c
print("Matrix C multiplied by vector A is: \n", MM(C, A))

Body:
I think you need A = [[3], [4], [8]]. When the matrix is on the left side of the multiplication, you are multiplying it with a column vector instead of a row vector.

Keeping your code the same, but changing A as mentioned, I get the output:

[[98], [33], [67]]

which corresponds to the 3x1 column vector you would expect to get by doing this matrix multiplication.

If you instead wanted A to be a row vector on the left side of the multiplication, you could set:

A = [[3, 4, 8]]
C = [[2, 9, 7], [3, 4, 1], [1, 6, 5]]

and print

print("The vector A multiplied by the matrix C is: \n", MM(A, C))

to give the output:

[[26, 91, 65]]

This would be a 1x3 row vector multiplied by a 3x3 matrix to give a 1x3 result.


问:
Security function used is causing repainting pine script
This is my sample script which is causing repainting once I refresh the chart. Not sure what's wrong with it.

**
//@version=5
strategy('MyTrendStrategy', overlay=true)

//f_security(_sym, _res, _src, _rep) => request.security(_sym, _res, _src)

f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src, lookahead = barmerge.lookahead_on)
out1 = f_secureSecurity(syminfo.tickerid, "15", open)
out2 = f_secureSecurity(syminfo.tickerid, "15", close)

plot(out1, color=color.new(color.red, 0))
plot(out2, color=color.new(color.green, 0))

longCondition = ta.crossover(out2, out1)
if longCondition
strategy.entry('long', strategy.long, alert_message="GO LONG")
shortCondition = ta.crossunder(out2, out1)
if shortCondition
strategy.entry('short', strategy.short, alert_message="GO SHORT")
**

答:
this will sort you out. When using lookahead we need to use last bar info using the historical operator []. Otherwise it leaks future data on the historical set before it would have been possible in real world conditions.

```<code>f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
</code>```

For more info please see this link and this link

Cheers and best of luck with your coding and trading

Body:
this will sort you out. When using lookahead we need to use last bar info using the historical operator []. Otherwise it leaks future data on the historical set before it would have been possible in real world conditions.

f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)

For more info please see this link and this link

Cheers and best of luck with your coding and trading