问:
Action when an element from collection get scrolled by
I have an unknown number of section blocks.
I use the titles of these automaticaly generated sections to populate the "tabs" container who follow the scroll (using sticky position).

What I need, is when I pass by one of the title contained in the sections, the same title from the "tabs" bar get the class "selected"so I indicate where the user is.

But what I've tried so far is only working partialy.
Here's a working example:

let titles = [];
    $.each($('section>h3'),function(){
        titles.push($(this).offset().top);
    });
    $(document).on('mousewheel DOMMouseScroll',function(e){
    let winscrollpos = $(window).scrollTop();
        $.each(titles,function(i,v){
            if(winscrollpos >= v && winscrollpos < v+100) {
                $('.deco-tab-title').eq(i).add('.selected').toggleClass('selected');
            }
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}</code>```

title1

title2

title3

title4

title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

```

as you can see, the first title lose the class if you scroll to the end. But nothing else. And when you go back, the second title get the class. And overall, it doesn't work so well.

答:
I have made the following fixes in your code:

add('.selected').toggleClass('selected'): chaining both functions this way cannot work. That's the reason why your titles were somehow blinking when selected. I've replaced this with the use of this version of toggleClass

I've added another list, nextTitlePos, in order to store, for each title, the position of the next one. For the last one, you can use any value greater than the end of your container (I've used Number.MAX_VALUE here to keep it simple, but if needed, you can use the end of the container as well.)

In the HTML code, there was also an extra
 tag, which was empty. This one was preventing title2 from being highlighted properly.

EDIT: I've replaced the event mousewheel with scroll as well (as mentioned by Shridhar Sharma in a comment below - thanks)

    let titles = [];
    $.each($('section>h3'),function(){
        titles.push($(this).offset().top);
    });
    let nextTitlePos = [];
    $.each(titles, function(i, v) {
          if(i != 0) {
              nextTitlePos.push(v);
          }
    });
    nextTitlePos.push(Number.MAX_VALUE);
    $(document).on('scroll DOMMouseScroll',function(e){
    let winscrollpos = $(window).scrollTop();
        $.each(titles,function(i,v){
            let isSelected = winscrollpos >= v && winscrollpos < nextTitlePos[i];
            $('div.tabs>h3.deco-tab-title').eq(i).toggleClass('selected', isSelected);
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}</code>```

title1

title2

title3

title4

title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

```

Body:
I have an unknown number of section blocks.
I use the titles of these automaticaly generated sections to populate the "tabs" container who follow the scroll (using sticky position).

What I need, is when I pass by one of the title contained in the sections, the same title from the "tabs" bar get the class "selected"so I indicate where the user is.

But what I've tried so far is only working partialy.
Here's a working example:

let titles = [];
    $.each($('section>h3'),function(){
        titles.push($(this).offset().top);
    });
    $(document).on('mousewheel DOMMouseScroll',function(e){
    let winscrollpos = $(window).scrollTop();
        $.each(titles,function(i,v){
            if(winscrollpos >= v && winscrollpos < v+100) {
                $('.deco-tab-title').eq(i).add('.selected').toggleClass('selected');
            }
        });
    });

.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}

title1

title2

title3

title4

title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

title4

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.

as you can see, the first title lose the class if you scroll to the end. But nothing else. And when you go back, the second title get the class. And overall, it doesn't work so well.

Body:
I have made the following fixes in your code:

add('.selected').toggleClass('selected'): chaining both functions this way cannot work. That's the reason why your titles were somehow blinking when selected. I've replaced this with the use of this version of toggleClass

I've added another list, nextTitlePos, in order to store, for each title, the position of the next one. For the last one, you can use any value greater than the end of your container (I've used Number.MAX_VALUE here to keep it simple, but if needed, you can use the end of the container as well.)

In the HTML code, there was also an extra <h3> tag, which was empty. This one was preventing title2 from being highlighted properly.

EDIT: I've replaced the event mousewheel with scroll as well (as mentioned by Shridhar Sharma in a comment below - thanks)

    let titles = [];
    $.each($('section>h3'),function(){
        titles.push($(this).offset().top);
    });
    let nextTitlePos = [];
    $.each(titles, function(i, v) {
          if(i != 0) {
              nextTitlePos.push(v);
          }
    });
    nextTitlePos.push(Number.MAX_VALUE);
    $(document).on('scroll DOMMouseScroll',function(e){
    let winscrollpos = $(window).scrollTop();
        $.each(titles,function(i,v){
            let isSelected = winscrollpos >= v && winscrollpos < nextTitlePos[i];
            $('div.tabs>h3.deco-tab-title').eq(i).toggleClass('selected', isSelected);
        });
    });

.filler {
  height:800px;
}

.selected {
  color:red;
}

.tabs {
  background-color:#eee;
  position:sticky;
  top:0;
}

p {
  width:200px
}

.tabs h3 {
  display:inline;
  margin-left:50px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='main'>
  <div class='filler'>

  </div>
  <div class='wrapper'>
  <div class='tabs'><h3 class='deco-tab-title selected'>title1</h3><!-- REMOVED <h3 class='deco-tab-title'></h3> --><h3 class='deco-tab-title'>title2</h3><h3 class='deco-tab-title'>title3</h3><h3 class='deco-tab-title'>title4</h3></div>
  <div class='core'>
    <section>
      <h3 class='deco-tab-title'>title1</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    <section>
      <h3 class='deco-tab-title'>title2</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    <section>
      <h3 class='deco-tab-title'>title3</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
    <section>
      <h3 class='deco-tab-title'>title4</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur ligula sem, elementum a leo in, aliquam blandit orci. Ut scelerisque auctor tincidunt. Phasellus at dui eget nisl varius porttitor. Quisque fermentum nisi a quam consectetur, non malesuada urna maximus. Phasellus vehicula ante a felis molestie gravida vel ac augue. Duis ullamcorper malesuada nibh. Etiam non pulvinar ex. Proin rhoncus sagittis pulvinar. Suspendisse ac urna dui. Proin nec tempus augue, at molestie libero. Duis ut libero ut diam mollis pharetra et ac dui.</p>
    </section>
  </div>
  </div>
</div>


来源: stackexchange

问:
How to update Angular 7 to Angular 8 by ng update
I try update Angular project from version 7.2.5 to 8 of the core framework and CLI by running ng update @angular/cli @angular/core in terminal.

Response from terminal was 'We analyzed your package.json and everything seems to be in order. Good work!'

My version list:

```<code>$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.3.9
Node: 11.14.0
OS: darwin x64
Angular: 7.2.15
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.13.9
@angular-devkit/build-angular      0.13.9
@angular-devkit/build-ng-packagr   0.13.9
@angular-devkit/build-optimizer    0.13.9
@angular-devkit/build-webpack      0.13.9
@angular-devkit/core               7.3.9
@angular-devkit/schematics         7.3.9
@angular/cdk                       7.3.7
@angular/cli                       7.3.9
@angular/material                  7.3.7
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.3.9
@schematics/angular                7.3.9 (cli-only)
@schematics/update                 0.13.9
ng-packagr                         5.2.0
rxjs                               6.5.2
typescript                         3.2.4
webpack                            4.29.0
</code>```

答:
As of today, Angular 8 is not a stable version.

But if you really wish to update non stable version use @next at the end of the package name.

ng update @angular/cli@next @angular/core@next

ContentLicense: CC BY-SA 4.0

Body:
I try update Angular project from version 7.2.5 to 8 of the core framework and CLI by running ng update @angular/cli @angular/core in terminal.

Response from terminal was 'We analyzed your package.json and everything seems to be in order. Good work!'

My version list:

$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.3.9
Node: 11.14.0
OS: darwin x64
Angular: 7.2.15
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.13.9
@angular-devkit/build-angular      0.13.9
@angular-devkit/build-ng-packagr   0.13.9
@angular-devkit/build-optimizer    0.13.9
@angular-devkit/build-webpack      0.13.9
@angular-devkit/core               7.3.9
@angular-devkit/schematics         7.3.9
@angular/cdk                       7.3.7
@angular/cli                       7.3.9
@angular/material                  7.3.7
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.3.9
@schematics/angular                7.3.9 (cli-only)
@schematics/update                 0.13.9
ng-packagr                         5.2.0
rxjs                               6.5.2
typescript                         3.2.4
webpack                            4.29.0


问:
A memory-efficient SHA1 implementation
I'm working with a very restrictive embedded processor, which only has 128 bytes of ram. I'd like to implement SHA1 on it. RFC3174 describes, in 'method 2', a way of implementing SHA1 that doesn't require allocating an array of 80 32-bit words (which, at 320 bytes, is obviously not practical), and seems like it ought to be usable on my processor. I'm unable to find any implementations of 'method 2', though, and the sample code in the RFC only implements the default method.

Is anyone aware of a memory-efficient implementation of SHA1 in C or C++?

答: All things considered, looking at your requirements, I think you are going to have to change your specs. Either a bigger chip, or a simpler algorithm. Even implementing SHA-1 (without HMAC) would be a challenge, but it should be doable.</p>

ContentLicense: CC BY-SA 3.0

Title: A memory-efficient SHA1 implementation


问:
Kubernetes RBAC default user
I'm reading myself currently into RBAC and am using Docker For Desktop with a local Kubernetes cluster enabled.

If I run kubectl auth can-i get pods which user or group or serviceaccount is used by default?

Is it the same call like:

kubectl auth can-i get pods --as docker-for-desktop --as-group system:serviceaccounts ?

kubectl config view shows:

```<code>contexts:
- context:
    cluster: docker-for-desktop-cluster
    namespace: default
    user: docker-for-desktop
  name: docker-for-desktop
...
users:
- name: docker-for-desktop
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED
</code>```

But simply calling kubectl auth can-i get pods --as docker-for-desktop returns NO.

Thanks,
Kim

答:
To answer your question

If I run kubectl auth can-i get pods which user or group or serviceaccount is used by default?

As you can read on Configure Service Accounts for Pods:

When you (a human) access the cluster (for example, using kubectl), you are authenticated by the apiserver as a particular User Account (currently this is usually admin, unless your cluster administrator has customized your cluster). Processes in containers inside pods can also contact the apiserver. When they do, they are authenticated as a particular Service Account (for example, default).

You can use kubectl get serviceaccount to see what serviceaccounts are setup in the cluster.
Try checking which contexts you have available and switching into a which ever you need:

kubectl config get-contexts

kubectl config use-context docker-for-desktop

If you are experiencing an issue with missing Role please check Referring to Resources to set  they correctly for docker-for-desktop

Title: Kubernetes RBAC default user

Body:
I'm reading myself currently into RBAC and am using Docker For Desktop with a local Kubernetes cluster enabled.

If I run kubectl auth can-i get pods which user or group or serviceaccount is used by default?

Is it the same call like:

kubectl auth can-i get pods --as docker-for-desktop --as-group system:serviceaccounts ?

kubectl config view shows:

contexts:
- context:
    cluster: docker-for-desktop-cluster
    namespace: default
    user: docker-for-desktop
  name: docker-for-desktop
...
users:
- name: docker-for-desktop
  user:
    client-certificate-data: REDACTED
    client-key-data: REDACTED

But simply calling kubectl auth can-i get pods --as docker-for-desktop returns NO.

Thanks,
Kim


问:
Javascript - Group by one property of object in an array of objects
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

```<code>const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]
</code>```

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

```<code>{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}
</code>```

I have tried to group by without sorting:

```<code>const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})
</code>```

And with sorting, not successful but you know what I mean:

```<code>const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})
</code>```

Any suggestions are appreciated

答:
You could take the index directly without later sorting.

const
    lists = [{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 }, { groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 }, { groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 }, { groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }],
    result = lists.reduce((r, { groupKey, ...rest }) => {
        r[groupKey] = r[groupKey] || [];
        r[groupKey][rest.index] = rest;
        return r
    }, {});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:

const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]

Result should be grouped by groupKey and sorted by index

(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).

This should look like:

{
  ABC: [
    {  key: 'q8', timestamp: '2012', index: 0 },
    {  key: 'w8', timestamp: '2013', index: 1 },
    {  key: 'r8', timestamp: '2014', index: 2 }
  ],
  CDE: [
    { key: 'r7', timestamp: '2019', index: 0 }
  ]
}

I have tried to group by without sorting:

const result = lists.reduce((r, item) => {
      let { groupKey, ...rest } = item
      r[item.groupKey] = [...(r[item.groupKey] || []), rest]
      return r
    }, {})

And with sorting, not successful but you know what I mean:

const result = lists.reduce((r, item) => {
          let { groupKey, ...rest } = item
          r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
          return r
        }, {})

Any suggestions are appreciated

Body:
You could take the index directly without later sorting.

const
    lists = [{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 }, { groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 }, { groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 }, { groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }],
    result = lists.reduce((r, { groupKey, ...rest }) => {
        r[groupKey] = r[groupKey] || [];
        r[groupKey][rest.index] = rest;
        return r
    }, {});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Stuck with a ValueError, How to solve it?
I am doing a assignment and I need to extract text from PDF using PyPDF2 and while trying to do that am getting this error. How to fix this?
can someone help me? thank you in advance.</p>

```<code>import PyPDF2
textFile = open('foo.txt', 'w')
file = open('foo.pdf','rb')
readpdf = PyPDF2.PdfFileReader(file)
print(readpdf.getNumPages())
1
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())

--------------------------------------------------------------------------
ValueError                                Traceback (most recent call
last)
<ipython-input-42-5a892ea3012b> in <module>
----> 1 textFile.write(read_pdf.extractText())

ValueError: I/O operation on closed file.

file.close
textFile.close()
</code>```

答:
using with open you dont need to handle the exception and closing file, it handle this by itself

```<code>import PyPDF2
with open('foo.txt','w') textFile:
    with open('foo.pdf','rb') as file:
        readpdf = PyPDF2.PdfFileReader(file)
        print(readpdf.getNumPages())
        read_pdf = readpdf.getPage(0)
        textFile.write(read_pdf.extractText())
</code>```

Body:
I am doing a assignment and I need to extract text from PDF using PyPDF2 and while trying to do that am getting this error. How to fix this?
can someone help me? thank you in advance.

import PyPDF2
textFile = open('foo.txt', 'w')
file = open('foo.pdf','rb')
readpdf = PyPDF2.PdfFileReader(file)
print(readpdf.getNumPages())
1
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())

--------------------------------------------------------------------------
ValueError                                Traceback (most recent call
last)
<ipython-input-42-5a892ea3012b> in <module>
----> 1 textFile.write(read_pdf.extractText())

ValueError: I/O operation on closed file.

file.close
textFile.close()

Body:
using with open you dont need to handle the exception and closing file, it handle this by itself

import PyPDF2
with open('foo.txt','w') textFile:
    with open('foo.pdf','rb') as file:
        readpdf = PyPDF2.PdfFileReader(file)
        print(readpdf.getNumPages())
        read_pdf = readpdf.getPage(0)
        textFile.write(read_pdf.extractText())


问:
Ruby - free up memory used by required gems?
Is there a way to free up memory used by required gems? My Rails app grows in memory usage and I would like to use gems only when I need them and after that free them up, IF this is possible.

Thanks!

答: The Garbage Collector do it this best to you. There are no better solution. Check all part where you can have some memory leak and avoid it. Use less of gems too.</p>


问:
Detect browser refresh in an Angular project
I want to detect when a page is refreshed using a router  in my single-page application (Angular project).

Is there an alternate way?

答:
An Angular application is a single-page application, and in the context of a single-page application the full app is loaded once, and data or screens are refreshed as the user uses your application.

A browser refresh is the equivalent of shutting down your application and launching it again.  There isn’t any default way to respond to this inside your Angular application.

You might be able to mock something up using onBeforeUnload() to log that the application was reloaded; and then check that log in your application's initialization routine to perform some special action.


问:
How to partition and typecast a List in Kotlin
In Kotlin I can:

```<code>val (specificMembers, regularMembers) = members.partition {it is SpecificMember}
</code>```

However to my knowledge I can not do something like:

```<code>val (specificMembers as List<SpecificMember>, regularMembers) = members.partition {it is SpecificMember}
</code>```

My question would be - is there's an idiomatic way to partition iterable by class and typecast it those partitioned parts if needed.

答:
The partition function will return a Pair<List<T>, List<T>> with T being the generic type of your Iterable. You can transform the partitioned values again using e.g. let:

```<code>val (specificMembers, regularMembers) = lists
    .partition { it is SpecificMember }
    .let { Pair(it.first as List<SpecificMember>, it.second) }
</code>```

Body:
In Kotlin I can:

val (specificMembers, regularMembers) = members.partition {it is SpecificMember}

However to my knowledge I can not do something like:

val (specificMembers as List<SpecificMember>, regularMembers) = members.partition {it is SpecificMember}

My question would be - is there's an idiomatic way to partition iterable by class and typecast it those partitioned parts if needed.

Body:
The partition function will return a Pair<List<T>, List<T>> with T being the generic type of your Iterable. You can transform the partitioned values again using e.g. let:

val (specificMembers, regularMembers) = lists
    .partition { it is SpecificMember }
    .let { Pair(it.first as List<SpecificMember>, it.second) }


问:
How to make recyclerview hight same as tallest item when multiline text present?
I am using recyclerview where item can have multiline text.the problem arise when one item has single line text and other has multiple lines of text.one item get bigger than other.

I want item height will be same as talles item.How i can achive this?

答:
You can give fixed height to TextView. Like

```<code>android:layout_height="50dp"
</code>```

Or you can set fix number of lines of TextView

```<code>android:lines="2"
</code>```

Body:
You can give fixed height to TextView. Like

android:layout_height="50dp"

Or you can set fix number of lines of TextView

android:lines="2"


问:
Generating Invoice Number
I am using a separate table to generate invoice numbers.

The code i am using is :

```<code>Branch::where('id', $branch_id)->update([
    'piref' => DB::raw('piref+1')
    ]);
$piref = Branch::where('id', $branch_id)->get('piref');
$piref = $piref[0]['piref'];
</code>```

My question is if the code is wrapped in a transaction. Is this approach safe ?
I tried to use Laravel Increments() but it does not return the newly generated number.

答:
Model method increment() increments property of model and column value in database.

```<code>$branch = Branch::find($branch_id);
$branch->increment('piref');
$piref = $branch->piref;
</code>```

Title: Generating Invoice Number

Body:
I am using a separate table to generate invoice numbers.

The code i am using is :

Branch::where('id', $branch_id)->update([
    'piref' => DB::raw('piref+1')
    ]);
$piref = Branch::where('id', $branch_id)->get('piref');
$piref = $piref[0]['piref'];

My question is if the code is wrapped in a transaction. Is this approach safe ?
I tried to use Laravel Increments() but it does not return the newly generated number.

Body:
Model method increment() increments property of model and column value in database.

$branch = Branch::find($branch_id);
$branch->increment('piref');
$piref = $branch->piref;


问:
Create widget select type field based on 3rd party API response
We started to develop a site in Apostrophe CMS based on a 3rd party API and stuck on the following issue:

we need a widget which has a select (on admin side).

the options from it are generated based on an API response.

the Admin user will select an option when he/she sets up the widget parameters (server side).

based on this selection we will call another API, and based on that response will generate some HTML (client side; images, texts, etc.)

The scenario is the following: the admin chooses a product from a list and on the front-end we will show information based on that selection.

```<code>const request = require( 'request-promise' );

module.exports = {
    extend: 'apostrophe-widgets',
    label: 'Preloaded list widget',
    addFields: [
        {
            label: 'Product',
            name: 'product',
            type: 'select',
            required: true,
            choices: "getChoices"
        }
    ],

    getChoices: async function( req )
    {
        const products = await request( {
            uri: "http://API_for_product_list",
            json: true
        } );

        var choiceList = [];
        for( idx = 0; idx < products.totalRecords; idx++ )
        {
            var option =
            {
                label: products.items[ idx ].label,
                value: products.items[ idx ].value
            };

            choiceList.push( option );
        }

        return choiceList;
    }
};

</code>```

When I start the application i got the following warning:
"widget type preloadedlist, field name product:
When using showFields, field.choices must be an array"
And the list shows empty. The getChoices function is never called.

I'm missing something but I don't know what. We did everything according to the documentation.

答:
You have to attach your getChoices function to the module itself so that it can be referenced later.

```<code>const request = require('request-promise');

module.exports = {
  extend: 'apostrophe-widgets',
  label: 'Preloaded list widget',
  addFields: [{
    label: 'Product',
    name: 'product',
    type: 'select',
    required: true,
    choices: 'getChoices'
  }],
  construct: function(self, options) {
    self.getChoices = async function (req) {
      const products = await request({
        uri: "http://API_for_product_list",
        json: true
      });

      var choiceList = [];
      for (idx = 0; idx < products.totalRecords; idx++) {
        var option = {
          label: products.items[idx].label,
          value: products.items[idx].value
        };

        choiceList.push(option);
      }
      return choiceList;
    }
  }
};
</code>```

Body:
We started to develop a site in Apostrophe CMS based on a 3rd party API and stuck on the following issue:

we need a widget which has a select (on admin side).

the options from it are generated based on an API response.

the Admin user will select an option when he/she sets up the widget parameters (server side).

based on this selection we will call another API, and based on that response will generate some HTML (client side; images, texts, etc.)

The scenario is the following: the admin chooses a product from a list and on the front-end we will show information based on that selection.

const request = require( 'request-promise' );

module.exports = {
    extend: 'apostrophe-widgets',
    label: 'Preloaded list widget',
    addFields: [
        {
            label: 'Product',
            name: 'product',
            type: 'select',
            required: true,
            choices: "getChoices"
        }
    ],

    getChoices: async function( req )
    {
        const products = await request( {
            uri: "http://API_for_product_list",
            json: true
        } );

        var choiceList = [];
        for( idx = 0; idx < products.totalRecords; idx++ )
        {
            var option =
            {
                label: products.items[ idx ].label,
                value: products.items[ idx ].value
            };

            choiceList.push( option );
        }

        return choiceList;
    }
};

When I start the application i got the following warning:
"widget type preloadedlist, field name product:
When using showFields, field.choices must be an array"
And the list shows empty. The getChoices function is never called.

I'm missing something but I don't know what. We did everything according to the documentation.

Body:
You have to attach your getChoices function to the module itself so that it can be referenced later.

const request = require('request-promise');

module.exports = {
  extend: 'apostrophe-widgets',
  label: 'Preloaded list widget',
  addFields: [{
    label: 'Product',
    name: 'product',
    type: 'select',
    required: true,
    choices: 'getChoices'
  }],
  construct: function(self, options) {
    self.getChoices = async function (req) {
      const products = await request({
        uri: "http://API_for_product_list",
        json: true
      });

      var choiceList = [];
      for (idx = 0; idx < products.totalRecords; idx++) {
        var option = {
          label: products.items[idx].label,
          value: products.items[idx].value
        };

        choiceList.push(option);
      }
      return choiceList;
    }
  }
};


问:
How to extract matching keywords from two columns in a pandas dataframe?
I have two columns in a dataframe both are strings where column1 have some matching keywords in column2. I want to extract those matching keyword from column1 and column2 in a new column.

```<code>df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]
</code>```

I am expecting the output something like this

```<code>column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color
</code>```

答:
Another solution using the intersection (&) of sets:

```<code>df['column3'] = df.apply(lambda x: ' '.join(set(x['column1'].split()) &
                                            set(x['column2'].split())), axis=1)
</code>```

[out]

```<code>                     column1                column2         column3
0  A girl is going to market     girl market school     market girl
1  A girl is going to school     girl market school     girl school
2   The sky is blue in color  sky blue orange color  sky color blue
</code>```

Body:
I have two columns in a dataframe both are strings where column1 have some matching keywords in column2. I want to extract those matching keyword from column1 and column2 in a new column.

df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]

I am expecting the output something like this

column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color

Body:
Another solution using the intersection (&) of sets:

df['column3'] = df.apply(lambda x: ' '.join(set(x['column1'].split()) &
                                            set(x['column2'].split())), axis=1)

[out]

                     column1                column2         column3
0  A girl is going to market     girl market school     market girl
1  A girl is going to school     girl market school     girl school
2   The sky is blue in color  sky blue orange color  sky color blue


问:
Opening UIDatePicker under UITextView
I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.

I am just starting with IOS app development and I hope someone can help me.

```<code>datePicker = UIDatePicker
</code>```

and

```<code>inputTextfield = UITextField
</code>```

myCode:

```<code>//Function to create the datepicker
func createDatePicker(){
            //create instance of the datepicker
            datePicker = UIDatePicker()
            //sets format, so only day month and year can be selected
            //datePicker?.datePickerMode = .date
            datePicker?.backgroundColor = .white
            datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
            //to limit the datepicker, you can not pick a date older than yesterday
            let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
            datePicker?.minimumDate = yesterday
            datePicker?.minuteInterval = 30
            let loc = Locale(identifier: "de")
            datePicker?.locale = loc

            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))

            view.addGestureRecognizer(tapGesture)

            inputTextfield.inputView = datePicker

            //create a toolbar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()

            //add done button to the toolbar
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
            toolbar.setItems([doneButton], animated: true)

            inputTextfield.inputAccessoryView = toolbar
        }

        //function to select a date
        @objc func dateChanged(datePicker: UIDatePicker){

            //selected date by the user
            let dateFormate = DateFormatter()
            //Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
            dateFormate.dateFormat = "MM/dd/yyyy"
            inputTextfield.text = dateFormate.string(from: datePicker.date)
        }

        //function to close the datepicker, when tapping on the inputText again -handler method
        @objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
            view.endEditing(true)
        }

        //function to close the datepicker when clicking on the done button
        @objc func doneClicked(){
            self.view.endEditing(true)
        }
</code>```

答:
Here is a third party library which I guess will meet your expectation :

https://github.com/angelopino/APJTextPickerView

This subclasses the UITextField and very useful. Refer the example for more details.

Title: Opening UIDatePicker under UITextView

Body:
I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.

I am just starting with IOS app development and I hope someone can help me.

datePicker = UIDatePicker

and

inputTextfield = UITextField

myCode:

//Function to create the datepicker
func createDatePicker(){
            //create instance of the datepicker
            datePicker = UIDatePicker()
            //sets format, so only day month and year can be selected
            //datePicker?.datePickerMode = .date
            datePicker?.backgroundColor = .white
            datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
            //to limit the datepicker, you can not pick a date older than yesterday
            let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
            datePicker?.minimumDate = yesterday
            datePicker?.minuteInterval = 30
            let loc = Locale(identifier: "de")
            datePicker?.locale = loc

            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))

            view.addGestureRecognizer(tapGesture)

            inputTextfield.inputView = datePicker

            //create a toolbar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()

            //add done button to the toolbar
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
            toolbar.setItems([doneButton], animated: true)

            inputTextfield.inputAccessoryView = toolbar
        }

        //function to select a date
        @objc func dateChanged(datePicker: UIDatePicker){

            //selected date by the user
            let dateFormate = DateFormatter()
            //Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
            dateFormate.dateFormat = "MM/dd/yyyy"
            inputTextfield.text = dateFormate.string(from: datePicker.date)
        }

        //function to close the datepicker, when tapping on the inputText again -handler method
        @objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
            view.endEditing(true)
        }

        //function to close the datepicker when clicking on the done button
        @objc func doneClicked(){
            self.view.endEditing(true)
        }


答:
See this: This would be helpfull for you.
https://blog.apoorvmote.com/change-textfield-input-to-datepicker/</p>

Title: Opening UIDatePicker under UITextView


问:
Use result of async library once it’s done
I’m using the FileProvider library to look for files on my FTP server and Swift 5’s basic functionality to look for files in the “Documents“ folder of the device:

```<code>func lookForFiles() { //runs on a background thread
    var ftpExists = false
    var localExists = false

    let ftpFile:FileObject = lookForFTPFile()
    let localFile:FileObject = lookForLocalFile()

    //Compare,... files
}

func lookForFTPFile() -> FileObject? {
    var found:FileObject?

    ftpProvider?.contentsOfDirectory(path: mypath, completionHandler: { (contents, error) in
        //Look for ftp file
    }) //This is run in an async task according to documentation

    return found
}
</code>```

This of course always returns "nil" because of the task in "contentsOfDirectory" (I also can't return the file from within).

Question: How do I wait for lookForFTPFile to finish before returning the result (which might be nil because it simply didn't find anything) - without just setting up a timer?
I'd prefer to not mess with how the library sets up its asynchronous work.

Something like

```<code>var waitingbool = false
var found:FileObject?

func lookForFiles() { //runs on a background thread
    //Rest of code
    lookForFTPFile()
    while !waitingbool {}
    //Use "found"
}

func lookForFTPFile() {
    ftpProvider?.contentsOfDirectory(path: mypath, completionHandler: { (contents, error) in
        //Look for ftp file and save result in "found"
        self.waitingbool = true
    })
}
</code>```

looks like might work but at the same time it seems to be breaking a lot of unwritten rules.

答:
Everyone who hasn't done async in Swift runs into the same problem. If you return a value from a method without a closure (as you are doing it), it must return sync. Since your completion handler runs async as you have noticed, we have a problem. You shouldreturn a value from a async method with a completion handler block.

I would have rewritten your method as follows:

```<code>func find(content: @escaping (FileObject?) -> ()) {
    var found: FileObject?

    // init the found variabel somewhere

    ftpProvider?.contentsOfDirectory(path: mypath, completionHandler: { (contents, error) in
    // You are in a closure completion block here also!

    // send a callback to our waiting function...
    content(contents)
    })
    // If ftpProvider is nil, please call the content completion handler block with nil also!
}
</code>```

Calling side:

```<code>find { contents in // Capture self as unowned/weak maybe?
     // Use contents.
}
</code>```

Body:
I’m using the FileProvider library to look for files on my FTP server and Swift 5’s basic functionality to look for files in the “Documents“ folder of the device:

func lookForFiles() { //runs on a background thread
    var ftpExists = false
    var localExists = false

    let ftpFile:FileObject = lookForFTPFile()
    let localFile:FileObject = lookForLocalFile()

    //Compare,... files
}

func lookForFTPFile() -> FileObject? {
    var found:FileObject?

    ftpProvider?.contentsOfDirectory(path: mypath, completionHandler: { (contents, error) in
        //Look for ftp file
    }) //This is run in an async task according to documentation

    return found
}

This of course always returns "nil" because of the task in "contentsOfDirectory" (I also can't return the file from within).

Question: How do I wait for lookForFTPFile to finish before returning the result (which might be nil because it simply didn't find anything) - without just setting up a timer?
I'd prefer to not mess with how the library sets up its asynchronous work.

Something like

var waitingbool = false
var found:FileObject?

func lookForFiles() { //runs on a background thread
    //Rest of code
    lookForFTPFile()
    while !waitingbool {}
    //Use "found"
}

func lookForFTPFile() {
    ftpProvider?.contentsOfDirectory(path: mypath, completionHandler: { (contents, error) in
        //Look for ftp file and save result in "found"
        self.waitingbool = true
    })
}

looks like might work but at the same time it seems to be breaking a lot of unwritten rules.

Body:
Everyone who hasn't done async in Swift runs into the same problem. If you return a value from a method without a closure (as you are doing it), it must return sync. Since your completion handler runs async as you have noticed, we have a problem. You shouldreturn a value from a async method with a completion handler block.

I would have rewritten your method as follows:

func find(content: @escaping (FileObject?) -> ()) {
    var found: FileObject?

    // init the found variabel somewhere

    ftpProvider?.contentsOfDirectory(path: mypath, completionHandler: { (contents, error) in
    // You are in a closure completion block here also!

    // send a callback to our waiting function...
    content(contents)
    })
    // If ftpProvider is nil, please call the content completion handler block with nil also!
}

Calling side:

find { contents in // Capture self as unowned/weak maybe?
     // Use contents.
}


问:
InnoSetup - Check if visual studio 2010 crt redist is installed, if not then run installer
I currently have this in this part of Inno script

```<code>[Run]
Filename: {app}\bin\vcredist_x86.exe; Parameters: "/q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; WorkingDir: {app}\bin; StatusMsg: Installing Visual Studio 2010 C++ CRT Libraries...
</code>```

It will run vcredist installer during app installation. But the problem with this is that if the user has it already installed it throws things like

Repair/Remove

Already newer version detected

Is there any way to avoid this and only run this installer if needed? What should i add to Inno script?

EDIT:

With the help of @John links i made it witht he following function added

I also used this site for refference to get visual studio 2010 crt++ product code and used Uninstall folder in registry to detect if its installed.

```<code>function InitializeSetup(): Boolean;
var
  ErrorCode: Integer;
  RedistInstalled : Boolean;
  Result1 : Boolean;
begin
  RedistInstalled := RegKeyExists(HKLM,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{196BB40D-1578-3D01-B289-BEFC77A11A1E}');
  if RedistInstalled then
  begin
    Result := true;
  end else
  begin
    RedistInstalled := RegKeyExists(HKLM,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{196BB40D-1578-3D01-B289-BEFC77A11A1E}');
    if RedistInstalled then
    begin
      Result := true;
    end else
    begin
      Result1 := MsgBox('This setup requires Microsoft Visual C++ 2010 Redistributable Package (x86). Please install Visual C++ 2010 Redistributable Package (x86) and run this setup again.  '#13#10' '#13#10'Do you want to download Microsoft Visual C++ 2010 Redistributable Package (x86) now?',
        mbConfirmation, MB_YESNO) = idYes;
      if Result1 =false then
      begin
        Result:=false;
      end else
      begin
        Result:=false;
        ShellExec('open',
          'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe',
          '','',SW_SHOWNORMAL,ewNoWait,ErrorCode);
      end;
    end;
  end;
end;
</code>```

It would still be nice if however installer would continue after downloading/installing or that i could somehow adapt my previous code that runs included(with setup) installer:

```<code> [Run]
    Filename: {app}\bin\vcredist_x86.exe; Parameters: "/q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; WorkingDir: {app}\bin; StatusMsg: Installing Visual Studio 2010 C++ CRT Libraries...
</code>```

but this is still good enough.

答:
Maybe you can use HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs. You can found all versions has been installed. DLL has special name depends of c++ Retribuitable installation:

90: Visual Studio 2008 (Version 9.0)  (atl90.dll, msvcr90.dll, msvcp90.dll)

100: Visual Studio 2010 (Version 10.0) (atl100.dll, msvcr100.dll, msvcp100.dll)

110: Visual Studio 2012 (Version 11.0)   …110

120: Visual Studio 2013 (Version 12.0)   …120

140: Visual Studio 2015 (Version 14.0)   …140

150: Visual Studio 2017 (Version 15.0)   (atl150.dll, msvcr150.dll, msvcp150.dll)

160: Visual Studio 2019 (Version 16.0) (atl160.dll, msvcr160.dll, msvcp160.dll)

Regards,

Body:
I currently have this in this part of Inno script

[Run]
Filename: {app}\bin\vcredist_x86.exe; Parameters: "/q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; WorkingDir: {app}\bin; StatusMsg: Installing Visual Studio 2010 C++ CRT Libraries...

It will run vcredist installer during app installation. But the problem with this is that if the user has it already installed it throws things like

Repair/Remove

Already newer version detected

Is there any way to avoid this and only run this installer if needed? What should i add to Inno script?

EDIT:

With the help of @John links i made it witht he following function added

I also used this site for refference to get visual studio 2010 crt++ product code and used Uninstall folder in registry to detect if its installed.

function InitializeSetup(): Boolean;
var
  ErrorCode: Integer;
  RedistInstalled : Boolean;
  Result1 : Boolean;
begin
  RedistInstalled := RegKeyExists(HKLM,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{196BB40D-1578-3D01-B289-BEFC77A11A1E}');
  if RedistInstalled then
  begin
    Result := true;
  end else
  begin
    RedistInstalled := RegKeyExists(HKLM,'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{196BB40D-1578-3D01-B289-BEFC77A11A1E}');
    if RedistInstalled then
    begin
      Result := true;
    end else
    begin
      Result1 := MsgBox('This setup requires Microsoft Visual C++ 2010 Redistributable Package (x86). Please install Visual C++ 2010 Redistributable Package (x86) and run this setup again.  '#13#10' '#13#10'Do you want to download Microsoft Visual C++ 2010 Redistributable Package (x86) now?',
        mbConfirmation, MB_YESNO) = idYes;
      if Result1 =false then
      begin
        Result:=false;
      end else
      begin
        Result:=false;
        ShellExec('open',
          'http://download.microsoft.com/download/5/B/C/5BC5DBB3-652D-4DCE-B14A-475AB85EEF6E/vcredist_x86.exe',
          '','',SW_SHOWNORMAL,ewNoWait,ErrorCode);
      end;
    end;
  end;
end;

It would still be nice if however installer would continue after downloading/installing or that i could somehow adapt my previous code that runs included(with setup) installer:

 [Run]
    Filename: {app}\bin\vcredist_x86.exe; Parameters: "/q:a /c:""VCREDI~3.EXE /q:a /c:""""msiexec /i vcredist.msi /qn"""" """; WorkingDir: {app}\bin; StatusMsg: Installing Visual Studio 2010 C++ CRT Libraries...

but this is still good enough.


问:
Return from two tables in single query
I have a query that inserts into two tables at once (required because of foreign key constraints linking them) and would like to return the result of both inserts at the same level but I am not sure how that would be done, or if it is even possible.

The inserts look like this and work fine:

```<code>with org_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<organisation UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), org_eb as (
    insert into public.entity_base (
        id
    )
    values ('<organisation UUID/>')
    returning *
), org as (
    insert into public.organisation_data (
        id,
        armicus_name
    )
    values ('<organisation UUID/>', 'Stack Overflow')
    returning *
), use_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<user UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), use_eb as (
    insert into public.entity_base (
        id
    )
    values ('<user UUID/>')
    returning *
), use as (
    insert into public.user_account_data (
        id,
        email
    )
    values ('<user UUID/>', 'stack@overflow.com')
    returning *
)
</code>```

What I would like is to return it something like this:

```<code>select to_json(
    select org_b.id, org_b.organisation_id, org_b.created_date, org_b.last_modified_date, org_b.last_modified_by, org_b.armicus_data, org.armicus_name
    from org_b
    join org on org_b.id = org.id
) as organisation, to_json(
    select use_b.id, use_b.organisation_id, use_b.created_date, use_b.last_modified_date, use_b.last_modified_by, use_b.armicus_data, use.email
    from use_b
    join use on use_b.id = use.id
) as user
from org_b
</code>```

But this throws a syntax error, is there a way to achieve this? I can also upload the SQL to create the tables if that would help.

Edited to add SQL to create tables and constraints:

Create base table:

```<code>CREATE TABLE base (
    id uuid PRIMARY KEY,
    organisation_id uuid NOT NULL,
    created_date timestamptz NOT NULL DEFAULT now(),
    last_modified_date timestamptz NOT NUll,
    last_modified_by uuid NOT NULL,
    armicus_data jsonb
);
</code>```

Create entity base:

```<code>CREATE TABLE entity_base (
    id uuid PRIMARY KEY REFERENCES base(id) ON DELETE CASCADE,
    template_id uuid
);
</code>```

Create organisation data:

```<code>CREATE TABLE organisation_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    armicus_name TEXT
);
</code>```

Create user account data:

```<code>CREATE TABLE user_account_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    email text NOT NULL
);
</code>```

Add organisation id foreign key:

```<code>ALTER TABLE base ADD CONSTRAINT base_organisation_id_fkey FOREIGN KEY (organisation_id) REFERENCES organisation_data(id);
</code>```

Add last modified by foreign key:

```<code>ALTER TABLE base ADD CONSTRAINT base_last_modified_by_fkey FOREIGN KEY (last_modified_by) REFERENCES user_account_data(id);
</code>```

答:
Solved the problem of missing column names with this:</p>

```<code>SELECT (
    SELECT to_json(o)
    FROM (
        SELECT org_b.id, org_b.organisation_id, org_b.created_date, org_b.last_modified_date, org_b.last_modified_by, org_b.armicus_data, org.armicus_name
        FROM org_b
        JOIN org on org_b.id = org.id
    ) o
) AS organisation, (
    SELECT to_json(u)
    FROM (
        SELECT use_b.id, use_b.organisation_id, use_b.created_date, use_b.last_modified_date, use_b.last_modified_by, use_b.armicus_data, use.email
        FROM use_b
        JOIN use on use_b.id = use.id
    ) u
) AS user
FROM org_b
</code>```

Title: Return from two tables in single query

Body:
I have a query that inserts into two tables at once (required because of foreign key constraints linking them) and would like to return the result of both inserts at the same level but I am not sure how that would be done, or if it is even possible.

The inserts look like this and work fine:

with org_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<organisation UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), org_eb as (
    insert into public.entity_base (
        id
    )
    values ('<organisation UUID/>')
    returning *
), org as (
    insert into public.organisation_data (
        id,
        armicus_name
    )
    values ('<organisation UUID/>', 'Stack Overflow')
    returning *
), use_b as (
    insert into public.base (
        id,
        organisation_id,
        last_modified_by
    )
    values ('<user UUID/>', '<organisation UUID/>', '<user UUID/>')
    returning *
), use_eb as (
    insert into public.entity_base (
        id
    )
    values ('<user UUID/>')
    returning *
), use as (
    insert into public.user_account_data (
        id,
        email
    )
    values ('<user UUID/>', 'stack@overflow.com')
    returning *
)

What I would like is to return it something like this:

select to_json(
    select org_b.id, org_b.organisation_id, org_b.created_date, org_b.last_modified_date, org_b.last_modified_by, org_b.armicus_data, org.armicus_name
    from org_b
    join org on org_b.id = org.id
) as organisation, to_json(
    select use_b.id, use_b.organisation_id, use_b.created_date, use_b.last_modified_date, use_b.last_modified_by, use_b.armicus_data, use.email
    from use_b
    join use on use_b.id = use.id
) as user
from org_b

But this throws a syntax error, is there a way to achieve this? I can also upload the SQL to create the tables if that would help.

Edited to add SQL to create tables and constraints:

Create base table:

CREATE TABLE base (
    id uuid PRIMARY KEY,
    organisation_id uuid NOT NULL,
    created_date timestamptz NOT NULL DEFAULT now(),
    last_modified_date timestamptz NOT NUll,
    last_modified_by uuid NOT NULL,
    armicus_data jsonb
);

Create entity base:

CREATE TABLE entity_base (
    id uuid PRIMARY KEY REFERENCES base(id) ON DELETE CASCADE,
    template_id uuid
);

Create organisation data:

CREATE TABLE organisation_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    armicus_name TEXT
);

Create user account data:

CREATE TABLE user_account_data (
    id uuid PRIMARY KEY REFERENCES entity_base(id) ON DELETE CASCADE,
    email text NOT NULL
);

Add organisation id foreign key:

ALTER TABLE base ADD CONSTRAINT base_organisation_id_fkey FOREIGN KEY (organisation_id) REFERENCES organisation_data(id);

Add last modified by foreign key:

ALTER TABLE base ADD CONSTRAINT base_last_modified_by_fkey FOREIGN KEY (last_modified_by) REFERENCES user_account_data(id);

Body:
Solved the problem of missing column names with this:

SELECT (
    SELECT to_json(o)
    FROM (
        SELECT org_b.id, org_b.organisation_id, org_b.created_date, org_b.last_modified_date, org_b.last_modified_by, org_b.armicus_data, org.armicus_name
        FROM org_b
        JOIN org on org_b.id = org.id
    ) o
) AS organisation, (
    SELECT to_json(u)
    FROM (
        SELECT use_b.id, use_b.organisation_id, use_b.created_date, use_b.last_modified_date, use_b.last_modified_by, use_b.armicus_data, use.email
        FROM use_b
        JOIN use on use_b.id = use.id
    ) u
) AS user
FROM org_b


问:
How to remove headers (colnames) after combining several csv files
I want to combine data from several csv files with the same format so I can analyse them, but I cannot remove the headers/column names from the several combined files.

I have used the lapply function in order to take a list of the context of all these files and it looks something like:

```<code>ID X1 X2 ---> header of 1st csv file
1  5  6
2  6  9
.......
10 7  8
</code>```

.

```<code>ID X1 X2 --> headers 2nd csv file
1  5  6
2  6  9
.......
10 7  8
e.t.c
</code>```

How can I remove the header characters in order to apply mathematical operations to these data?

My code:

```<code>data<-lapply(files, read.csv)
mean <-(mean(data$column2, na.rm=TRUE))
</code>```

I also tried read.csv(headers=FALSE) but R do not accept this when the function is inside the lapply

I expect the mean of the data frame of the combined files but I get the error:

In mean.default(data$column2, na.rm = TRUE) :   argument is not
  numeric or logical: returning NA

答:
If you have read the data correctly with headers I think what you'll need to do is first extract the columns and then take the mean.

You can extract the column

1) By name

```<code>mean(sapply(data, `[[`, 'column2'), na.rm = TRUE)
</code>```

2) By position

```<code>mean(sapply(data, `[[`, 2), na.rm = TRUE)
</code>```

With lapply you need to unlist the data first

```<code>mean(unlist(lapply(data, `[[`, 'column2')), na.rm = TRUE)
</code>```

Body:
I want to combine data from several csv files with the same format so I can analyse them, but I cannot remove the headers/column names from the several combined files.

I have used the lapply function in order to take a list of the context of all these files and it looks something like:

ID X1 X2 ---> header of 1st csv file
1  5  6
2  6  9
.......
10 7  8

.

ID X1 X2 --> headers 2nd csv file
1  5  6
2  6  9
.......
10 7  8
e.t.c

How can I remove the header characters in order to apply mathematical operations to these data?

My code:

data<-lapply(files, read.csv)
mean <-(mean(data$column2, na.rm=TRUE))

I also tried read.csv(headers=FALSE) but R do not accept this when the function is inside the lapply

I expect the mean of the data frame of the combined files but I get the error:

In mean.default(data$column2, na.rm = TRUE) :   argument is not
  numeric or logical: returning NA

Body:
If you have read the data correctly with headers I think what you'll need to do is first extract the columns and then take the mean.

You can extract the column

1) By name

mean(sapply(data, `[[`, 'column2'), na.rm = TRUE)

2) By position

mean(sapply(data, `[[`, 2), na.rm = TRUE)

With lapply you need to unlist the data first

mean(unlist(lapply(data, `[[`, 'column2')), na.rm = TRUE)


问:
Error adding Firestore documents to Pickerview
I've recently changed a lot on my iOS application and now I got stuck.

I'm trying to insert data from Firestore which looks like this:

So, as you can see I've 6 different names in here.

And here is the code to insert into pickerView.

```<code> func getPerson()
{
    let authentication = Auth.auth().currentUser?.uid
    db.collection("users").document(authentication!).collection("person").getDocuments { (QuerySnapshot, err) in

        //If error is not equal to nil
        if err != nil
        {
            print("Error getting documents: \(String(describing: err))");
        }
            //Succeded
        else
        {
            //For-loop
            for _ in QuerySnapshot!.documents
            {
                //Cleaning the array for the new values
                self.personArray.removeAll()

                let document = QuerySnapshot!.documents
                let data = document.data() //HERE IS THE ERROR

                data.forEach { (item) in
                    if let person1Data = data["name"] as? String
                    {
                        self.personArray.append(person1Data)
                        print(self.personArray)
                    }
                }
            }
            self.pickerView.reloadAllComponents()

        }
    }
}
</code>```

I'm getting the error:

Value of type '[QueryDocumentSnapshot]' has no member 'data'

It used to have QuerySnapshot!.documents.first
but it does not work anymore when I've changed the Firestore data.

Edit:

So. the output is now:

["Joche"] ["Joche", "Joche"] ["Putte"] ["Putte", "Putte"] ["Rebecca"]
  ["Rebecca", "Rebecca"] ["Fredrik"] ["Fredrik", "Fredrik"] ["Anna"]
  ["Anna", "Anna"] ["Vickan"] ["Vickan", "Vickan"]

which means it adds everything but x3. How to solve this problem?

答:
data is an instance method of a single QueryDocumentSnapshot not an array , You need

```<code>self.personArray.removeAll()
for elem in querySnapshot!.documents {
    let data = elem.document.data()
    data.forEach {
        if let person1Data = $0["name"] as? String {
            self.personArray.append(person1Data)
            print(self.personArray)
        }
    }
}
</code>```

Body:
I've recently changed a lot on my iOS application and now I got stuck.

I'm trying to insert data from Firestore which looks like this:

So, as you can see I've 6 different names in here.

And here is the code to insert into pickerView.

 func getPerson()
{
    let authentication = Auth.auth().currentUser?.uid
    db.collection("users").document(authentication!).collection("person").getDocuments { (QuerySnapshot, err) in

        //If error is not equal to nil
        if err != nil
        {
            print("Error getting documents: \(String(describing: err))");
        }
            //Succeded
        else
        {
            //For-loop
            for _ in QuerySnapshot!.documents
            {
                //Cleaning the array for the new values
                self.personArray.removeAll()

                let document = QuerySnapshot!.documents
                let data = document.data() //HERE IS THE ERROR

                data.forEach { (item) in
                    if let person1Data = data["name"] as? String
                    {
                        self.personArray.append(person1Data)
                        print(self.personArray)
                    }
                }
            }
            self.pickerView.reloadAllComponents()

        }
    }
}

I'm getting the error:

Value of type '[QueryDocumentSnapshot]' has no member 'data'

It used to have QuerySnapshot!.documents.first
but it does not work anymore when I've changed the Firestore data.

Edit:

So. the output is now:

["Joche"] ["Joche", "Joche"] ["Putte"] ["Putte", "Putte"] ["Rebecca"]
  ["Rebecca", "Rebecca"] ["Fredrik"] ["Fredrik", "Fredrik"] ["Anna"]
  ["Anna", "Anna"] ["Vickan"] ["Vickan", "Vickan"]

which means it adds everything but x3. How to solve this problem?

Body:
data is an instance method of a single QueryDocumentSnapshot not an array , You need

self.personArray.removeAll()
for elem in querySnapshot!.documents {
    let data = elem.document.data()
    data.forEach {
        if let person1Data = $0["name"] as? String {
            self.personArray.append(person1Data)
            print(self.personArray)
        }
    }
}


问:
powershell select-string output for loop foreach
I'm traditional bash user therefore i don't understand how to work foreach in powershell.

Powershell

I need output

```<code>Vasya
http://192.168.10.61:8085/data.json
Misha
http://192.168.10.82:8085/data.json
</code>```

but I receive another output

```<code>Vasya
Misha
http://192.168.10.61:8085/data.json
http://192.168.10.82:8085/data.json
</code>```

Script

$pspath="E:\monitor.ps1"
$txtpath="E:\temp.txt"
$user1="Vasya"
$user2="Misha"
$ip1="http://192.168.10.61:8085/data.json"
$ip2="http://192.168.10.82:8085/data.json"

$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

foreach ($zab in $list)
{
    $regex_url = 'http://\d+.\d+.\d+.\d+:\d+/data.json'
    $regex_name = "([A-Z]|[a-z])\w+"
    $name =  echo $zab |%{$_.split('-')} |sls -pattern $regex_name -AllMatches |%{$_.Matches -notmatch 'http|json|data'} |%{$_.Value}
    $url = echo $zab |%{$_.split('-')} |sls -pattern $regex_url -AllMatches |%{$_.Matches} |%{$_.Value}
    echo $name
    echo $url
}
```

<h3>Bash</h3>

<p>In bash work's perfect.</p>

<ul>
<li>Script</li>
</ul>

<pre class="lang-perl prettyprint-override"><code>
#!/bin/bash
users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

for zab in $users; do
    name=$(echo $zab |cut -f 1 -d -)
    url=$(echo $zab |cut -f 2 -d -)
    echo $name
    echo $url

done
exit 0
</code>```

Help guys my hands are tied.

答:
This:

```<code>$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@
</code>```

is a single multi-line string, so the foreach loop is redundant.

Split the string before running Select-String:

```<code>foreach($zab in $list -split '\r?\n'){
    ...
}
</code>```

Body:
I'm traditional bash user therefore i don't understand how to work foreach in powershell.

Powershell

I need output

Vasya
http://192.168.10.61:8085/data.json
Misha
http://192.168.10.82:8085/data.json

but I receive another output

Vasya
Misha
http://192.168.10.61:8085/data.json
http://192.168.10.82:8085/data.json

Script

$pspath="E:\monitor.ps1"
$txtpath="E:\temp.txt"
$user1="Vasya"
$user2="Misha"
$ip1="http://192.168.10.61:8085/data.json"
$ip2="http://192.168.10.82:8085/data.json"

$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

foreach ($zab in $list)
{
    $regex_url = 'http://\d+.\d+.\d+.\d+:\d+/data.json'
    $regex_name = "([A-Z]|[a-z])\w+"
    $name =  echo $zab |%{$_.split('-')} |sls -pattern $regex_name -AllMatches |%{$_.Matches -notmatch 'http|json|data'} |%{$_.Value}
    $url = echo $zab |%{$_.split('-')} |sls -pattern $regex_url -AllMatches |%{$_.Matches} |%{$_.Value}
    echo $name
    echo $url
}

Bash

In bash work's perfect.

Script

#!/bin/bash
users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

for zab in $users; do
    name=$(echo $zab |cut -f 1 -d -)
    url=$(echo $zab |cut -f 2 -d -)
    echo $name
    echo $url

done
exit 0

Help guys my hands are tied.

Body:
This:

$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

is a single multi-line string, so the foreach loop is redundant.

Split the string before running Select-String:

foreach($zab in $list -split '\r?\n'){
    ...
}


问:
How to authenticate https client certificates using Dancer/Starman or Mojolicious/Daemon?
I am trying to perform Authentication using HTTPS client certificates using perl Dancer framework.
I would like to accept requests sent with/without certificate and do validation on the certificate CN to proceed with the valid response
(https://medium.com/@sevcsik/authentication-using-https-client-certificates-3c9d270e8326, the link shows how to do it in node.js, need something very similar for perl Dancer/Starman/Plackup)

I have setup ssl using Dancer/Plackup, but have not found a way to get details about the peer certificate to perform validation in Dancer framework

I would like to achieve the following:

If the request is sent

without certificate => 401

with certificate but client has self-signed (CN doesn't match with server cert CN) => 401

with certificate but client cert has been signed using server cert (CN matches server cert CN) => 200

答:
In Dancer you can get the IO::Socket::SSL object with request->env->{'psgix.io'}, but that does not help you because you have no opportunity to configure it for client verification. IO::Socket::SSL::set_defaults does not run early enough, either.

This means it's best to set up Apache httpd or nginx to terminate TLS. Pass on the certificate info you need (e.g. client verification result) in environment variables to the Dancer application.


问:
Spring-Boot Jersey: allow Jersey to serve static content
The application uses JDK 8, Spring Boot & Spring Boot Jersey starter and is packaged as a WAR (although it is locally run via Spring Boot Maven plugin).

What I would like to do is to get the documentation I generate on the fly (at build time) as a welcome page.

I tried several approaches:

letting Jersey serving the static contents by configuring in application.properties the proper init parameter as described here

introduce a metadata-complete=false web.xml in order to list the generated HTML document as a welcome-file.

None of that worked out.

I would like to avoid having to enable Spring MVC or creating a Jersey resource just for serving a static file.

Any idea?

Here is the Jersey configuration class (I unsuccessfully tried to add a ServletProperties.FILTER_STATIC_CONTENT_REGEX there):

```<code>@ApplicationPath("/")
@ExposedApplication
@Component
public class ResourceConfiguration extends ResourceConfig {

   public ResourceConfiguration() {
      packages("xxx.api");
      packages("xxx.config");
      property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true);
      property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
   }
}
</code>```

And here is Spring Boot application class (I tried adding an application.properties with spring.jersey.init.jersey.config.servlet.filter.staticContentRegex=/.*html but it didn't work, I'm not exactly sure what the property key should be here):

```<code>@SpringBootApplication
@ComponentScan
@Import(DataConfiguration.class)
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

答:
Below setup worked for me

Set

```<code>spring .jersey.type: filter
</code>```

set FILTER_FORWARD_ON_404

```<code>@Configuration
        public class MyResourceConfig extends ResourceConfig  {

            public MyResourceConfig () {
                try {
                    register(XXX.class);
                    property(ServletProperties.FILTER_FORWARD_ON_404, true);

                } catch (Exception e) {
                    LOGGER.error("Exception: ", e);
                }
            }

        }
</code>```

Note: Use @Configuration  instead of @component

Body:
The application uses JDK 8, Spring Boot & Spring Boot Jersey starter and is packaged as a WAR (although it is locally run via Spring Boot Maven plugin).

What I would like to do is to get the documentation I generate on the fly (at build time) as a welcome page.

I tried several approaches:

letting Jersey serving the static contents by configuring in application.properties the proper init parameter as described here

introduce a metadata-complete=false web.xml in order to list the generated HTML document as a welcome-file.

None of that worked out.

I would like to avoid having to enable Spring MVC or creating a Jersey resource just for serving a static file.

Any idea?

Here is the Jersey configuration class (I unsuccessfully tried to add a ServletProperties.FILTER_STATIC_CONTENT_REGEX there):

@ApplicationPath("/")
@ExposedApplication
@Component
public class ResourceConfiguration extends ResourceConfig {

   public ResourceConfiguration() {
      packages("xxx.api");
      packages("xxx.config");
      property(ServerProperties.BV_DISABLE_VALIDATE_ON_EXECUTABLE_OVERRIDE_CHECK, true);
      property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
   }
}

And here is Spring Boot application class (I tried adding an application.properties with spring.jersey.init.jersey.config.servlet.filter.staticContentRegex=/.*html but it didn't work, I'm not exactly sure what the property key should be here):

@SpringBootApplication
@ComponentScan
@Import(DataConfiguration.class)
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Body:
Below setup worked for me

Set

spring .jersey.type: filter

set FILTER_FORWARD_ON_404

@Configuration
        public class MyResourceConfig extends ResourceConfig  {

            public MyResourceConfig () {
                try {
                    register(XXX.class);
                    property(ServletProperties.FILTER_FORWARD_ON_404, true);

                } catch (Exception e) {
                    LOGGER.error("Exception: ", e);
                }
            }

        }

Note: Use @Configuration  instead of @component


问:
Why javascript array accepts string value index
Why does a Javascript array accept a string as an index, and when it accepts any string value as index then why doesn't it change its length?

I am new to Javascript and encountered this issue.

var newArr = [];
newArr[0] = 0;
newArr[1] = 1;
newArr["2"] = 3;
newArr[3] = 3;
newArr[4] = 4;
newArr["a"] = "a";
console.log(newArr);```
</div>
</div>
</p>

```(5) [0, 1, 3, 3, 4, a: "a"]
length: 5
__proto__: Array(0)
```

答:
Because

```<code>typeof Array() === 'object'
</code>```

therefore it is possible to add a new property to an array as you would on any plain object, that does not change the array length because it's not the same as actually adding (push) an element to the array.

Ref

Body:
Why does a Javascript array accept a string as an index, and when it accepts any string value as index then why doesn't it change its length?

I am new to Javascript and encountered this issue.

var newArr = [];
newArr[0] = 0;
newArr[1] = 1;
newArr["2"] = 3;
newArr[3] = 3;
newArr[4] = 4;
newArr["a"] = "a";
console.log(newArr);

(5) [0, 1, 3, 3, 4, a: "a"]
length: 5
__proto__: Array(0)

Body:
Because

typeof Array() === 'object'

therefore it is possible to add a new property to an array as you would on any plain object, that does not change the array length because it's not the same as actually adding (push) an element to the array.

Ref


问:
how to use session ids for authentication purpose
I am using just session variables $_SESSION['user_id'] and $_SESSION['passwd'] to store the id and password of user once when he logs in.

I am just checking these two variables with database each time the user moves to a new php page for authentication. Actually I didnt know about session_id() .

I dont think what i am doing for authentication is the right way. I feel that there is something to be done with session_id for security stuff.

and one more doubt- can these session variables be easily hacked when I use the session variables by the way i mentioned

What should I do?

答:
An attacker cannot easily change or read your $_SESSION variables, as long as there is no other vulnerability present, but it is general bad practice to store a password any longer than necessary on the server for several reasons.

It is sufficient to check the password once when the user logs in. Afterwards you only need to store the authenticated user_id in the session. You have to know who the session belongs to, to grant the necessary permissions to this specific user. But you do already know that the user submitted the correct password, otherwise you wouldn't have stored his user_id in the session in the first place.


问:
Custom ocmod modification not working in opencart version 3.0.2.0
I have successfully uploaded my customised .ocmod folder(.ocmode.zip) in the extension installer and got success message too. But this is not loading in the extensions.
I'm using opencart Version 3.0.3.2.

My files are in the structure:
 - upload
     - admin
     - catalog

Is there an alternative way to approach this?
Please help.

Thanks in advance.

答: You can upload manually, but have you made changes using install.xml file? </p>


问:
Problem displaying components of JList
I am trying to dsiplay the twitter timeline in a Jlist component. I have already fixed the size of my frame and the cell height and cell width of the JList too with the following code.

```<code>jlist.setFixedCellHeight(50);
jlist.setFixedCellWidth(70);
</code>```

I find that the height and width of each cell are fine but if the content of the tweet inside the cell exceeds the width it is not displaying the further part of the tweet.

For example: Assume that 70 width exactly fits the tweet "I am good"

Suppose if the tweet is "I am good and great" The tweet is getting displayed as "I am good....." The exceeded part of the tweet is not getting displayed.

What I want to do here is, I want the rest out part of the tweet to be displayed below the line as I do have sufficient height to display the tweet in a second line. In the same example, within the cell, I want the content to be displayed as

"I am good

and great"

How can I achieve this?

答: you need a custom ListCellRenderer which returns a component that supports multiple lines of text. The default renderer returns a JLabel with is single-line only. You can implement f.i a renderer which returns a JTextArea </p>

Title: Problem displaying components of JList

Body:
I am trying to dsiplay the twitter timeline in a Jlist component. I have already fixed the size of my frame and the cell height and cell width of the JList too with the following code.

jlist.setFixedCellHeight(50);
jlist.setFixedCellWidth(70);

I find that the height and width of each cell are fine but if the content of the tweet inside the cell exceeds the width it is not displaying the further part of the tweet.

For example: Assume that 70 width exactly fits the tweet "I am good"

Suppose if the tweet is "I am good and great" The tweet is getting displayed as "I am good....." The exceeded part of the tweet is not getting displayed.

What I want to do here is, I want the rest out part of the tweet to be displayed below the line as I do have sufficient height to display the tweet in a second line. In the same example, within the cell, I want the content to be displayed as

"I am good

and great"

How can I achieve this?


问:
How to make recyclerview hight same as tallest item when multiline text present?
I am using recyclerview where item can have multiline text.the problem arise when one item has single line text and other has multiple lines of text.one item get bigger than other.

I want item height will be same as talles item.How i can achive this?

答:
This will help you inside your Textview tag in the listItem

android:maxLines="1"
android:marqueeRepeatLimit="4"```

This will help text to scroll if its long engouh for one line

Body:
This will help you inside your Textview tag in the listItem

android:maxLines="1"
android:marqueeRepeatLimit="4"

This will help text to scroll if its long engouh for one line


问:
Why login page is blinking after login in Angular?
My issue is that after login I navigate my page to dashboard page and the URL seems to be http://localhost:4200/home but when I change my URL to http://localhost:4200 it shows me default Login page for some second and then after redirect to http://localhost:4200/home.

at time of login I used to generate the cookies and I want that login page should not display at all when cookies is available.

on app-routing.module.ts i have tried writing as

```<code>const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent },
 ];
</code>```

on AuthGuard I have written code as

```<code>export class AuthGuard implements CanActivate {

constructor(
private router: Router,
private Cookie: CookieService,
private commonser: CommonService
 ) { }
 readonly LocalStName = require('proxy.config.json');
 GetlocalStoragePermissison: any = [];

 async canActivate(
 next: ActivatedRouteSnapshot,
 state: RouterStateSnapshot): Promise<boolean> {
 if (this.Cookie.getCookie('usertoken')) {
   if (CommonService.GlobalVar === undefined || CommonService.GlobalVar.length === 0) {
    await this.commonser.getuserpermisison();
  }
  if (CommonService.GlobalVar !== undefined && CommonService.GlobalVar.length > 0) {
    for (const a of CommonService.GlobalVar) {
      if (state.url.replace('/', '').toLowerCase() === a.permissionname) {
        return true;
      }
    }
  }
   return false;
  } else {
     this.router.navigate(['/login']);
      return false;
   }
 }
}
</code>```

the this.commonser.getuserpermisison(); code is as below

```<code>async getuserpermisison() {
const data: any = await this.service.getuserpermisison();
if (data.length > 0) {
  data.push({
    isactive: 1,
    permissionid: null,
    permissionname: 'home',
    permissions: [2],
    total: 2,
    upmid: null
  }
  );
}
CommonService.GlobalVar = [];
this.SetlocalStoragePermissison = [];
for (const userper of data) {
  userper.permissionname = userper.permissionname.toLowerCase();
  if (userper.total > 0) {
    this.SetlocalStoragePermissison.push(Object.assign({}, userper));
  }
}
CommonService.GlobalVar = this.SetlocalStoragePermissison;
}
</code>```

on login.component.ts after login click below code is written

```<code>onSubmit(form: NgForm) {
  this.submitted = true;
  if (form.invalid) {
   return;
 }
this.service.userlogin(form.value.Username, sha512.sha512(form.value.Password)).subscribe(
  async (data: any) => {
    this.Cookie.setCookie('usertoken', data.Token, 1);
    await this.appmethod.getuserpermisison();
    await this.appmethod.getdetails();
    await this.appmethod.callingmethod();
  }, (err: HttpErrorResponse) => {
    if (err.error.message != null) {
      this.commonser.openSnackBarError(err.error.message, 'X');
    } else {
      this.commonser.openSnackBarError(err.message.toString(), 'X');
    }
  });
}
</code>```

The situation is that once I do successful login it redirect to home page and the URL is as http://localhost:4200/home but when I place URL http://localhost:4200 it doesn't show login page, instead it directly redirect to home page

答:
path: '' should redirect to home instead of login page.
You have authGuard from there you are redirecting to login page if user is not logged in.

```<code>const routes: Routes = [
      { path: 'login', component: LoginComponent },
      { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: '**', component: NotFoundComponent },
     ];
</code>```

Body:
My issue is that after login I navigate my page to dashboard page and the URL seems to be http://localhost:4200/home but when I change my URL to http://localhost:4200 it shows me default Login page for some second and then after redirect to http://localhost:4200/home.

at time of login I used to generate the cookies and I want that login page should not display at all when cookies is available.

on app-routing.module.ts i have tried writing as

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent },
 ];

on AuthGuard I have written code as

export class AuthGuard implements CanActivate {

constructor(
private router: Router,
private Cookie: CookieService,
private commonser: CommonService
 ) { }
 readonly LocalStName = require('proxy.config.json');
 GetlocalStoragePermissison: any = [];

 async canActivate(
 next: ActivatedRouteSnapshot,
 state: RouterStateSnapshot): Promise<boolean> {
 if (this.Cookie.getCookie('usertoken')) {
   if (CommonService.GlobalVar === undefined || CommonService.GlobalVar.length === 0) {
    await this.commonser.getuserpermisison();
  }
  if (CommonService.GlobalVar !== undefined && CommonService.GlobalVar.length > 0) {
    for (const a of CommonService.GlobalVar) {
      if (state.url.replace('/', '').toLowerCase() === a.permissionname) {
        return true;
      }
    }
  }
   return false;
  } else {
     this.router.navigate(['/login']);
      return false;
   }
 }
}

the this.commonser.getuserpermisison(); code is as below

async getuserpermisison() {
const data: any = await this.service.getuserpermisison();
if (data.length > 0) {
  data.push({
    isactive: 1,
    permissionid: null,
    permissionname: 'home',
    permissions: [2],
    total: 2,
    upmid: null
  }
  );
}
CommonService.GlobalVar = [];
this.SetlocalStoragePermissison = [];
for (const userper of data) {
  userper.permissionname = userper.permissionname.toLowerCase();
  if (userper.total > 0) {
    this.SetlocalStoragePermissison.push(Object.assign({}, userper));
  }
}
CommonService.GlobalVar = this.SetlocalStoragePermissison;
}

on login.component.ts after login click below code is written

onSubmit(form: NgForm) {
  this.submitted = true;
  if (form.invalid) {
   return;
 }
this.service.userlogin(form.value.Username, sha512.sha512(form.value.Password)).subscribe(
  async (data: any) => {
    this.Cookie.setCookie('usertoken', data.Token, 1);
    await this.appmethod.getuserpermisison();
    await this.appmethod.getdetails();
    await this.appmethod.callingmethod();
  }, (err: HttpErrorResponse) => {
    if (err.error.message != null) {
      this.commonser.openSnackBarError(err.error.message, 'X');
    } else {
      this.commonser.openSnackBarError(err.message.toString(), 'X');
    }
  });
}

The situation is that once I do successful login it redirect to home page and the URL is as http://localhost:4200/home but when I place URL http://localhost:4200 it doesn't show login page, instead it directly redirect to home page

Body:
path: '' should redirect to home instead of login page.
You have authGuard from there you are redirecting to login page if user is not logged in.

const routes: Routes = [
      { path: 'login', component: LoginComponent },
      { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: '**', component: NotFoundComponent },
     ];


问:
Sum entries per date when multiple entries of date exist
I have 1 column of dates and 1 column of 'wins' recording 1 and -1 as wins and losses. I need a quick way to tally the score across each date (so I can graph the win-rates). Eg. 5th May 7 wins, 6th may -2 wins, etc. I have multiple entries for each date and several days to work through so I can't do it manually. What would be the simplest approach/formula to solve this issue?

I'm working in Google Sheets. If someone has a simple workaround in Excel too, the solution is welcome.

答:
Try:

=SUMPRODUCT(($A$2:$A$12=$E$1)*($B$2:$B$12)) in cell E6

Data structure: