问:
How to get date from year and semeter format ('YYYY-SX') using pandas
I have a pandas column called time and it contains the year and semester. For instance in format ('YYYYSX') 2018S1. I want to convert the time format in YYYYSX into date

Input

```<code>   time
1  2019S2
2  2019S2
3  2020S1

</code>```

output

```<code>   time
1  2019-09-30
2  2019-10-31
3  2020-01-31

</code>```

答:
```<code>def convert(time):
    year = time[:4]
    semester = time[4:]
    conversions = {'S1': '-01-31' , 'S2': '-06-03', 'S3': '-09-30'}
    return pd.to_datetime(year + conversions[semester])

df['time'] = df.time.apply(convert)
</code>```

returns :

```<code>    time
0   2019-06-03
1   2019-06-03
2   2020-01-31
</code>```

I think there were some inconsistencies in your expected output, but you just need to put whatever semesters/dates you want in the conversions dictionary.

Body:
I have a pandas column called time and it contains the year and semester. For instance in format ('YYYYSX') 2018S1. I want to convert the time format in YYYYSX into date

Input

   time
1  2019S2
2  2019S2
3  2020S1

output

   time
1  2019-09-30
2  2019-10-31
3  2020-01-31

Body:
def convert(time):
    year = time[:4]
    semester = time[4:]
    conversions = {'S1': '-01-31' , 'S2': '-06-03', 'S3': '-09-30'}
    return pd.to_datetime(year + conversions[semester])

df['time'] = df.time.apply(convert)

returns :

    time
0   2019-06-03
1   2019-06-03
2   2020-01-31

I think there were some inconsistencies in your expected output, but you just need to put whatever semesters/dates you want in the conversions dictionary.


来源: stackexchange

问:
is it safe to do setState for undefined values in react
is it safe if I will do this

```<code>this.setState({
                    data: data
                });
</code>```

without adding data in constructor method in react -

```<code>constructor(props) {
        super(props);
        this.state = {
            data:null
        };
    }
</code>```

Because without declaring in state also it works fine, but when I say

```<code>constructor(props) {
            super(props);
            this.state = {
                data
            };
        }
</code>```

this gives error.

If I will not add data inside state in constructor it works fine, is it safe ?

答:
It is best practice to declare the state before using.
And here this.state = { data }; means this.state = { data: data } so it will occurs data is undefined.

ContentLicense: CC BY-SA 4.0

Body:
is it safe if I will do this

this.setState({
                    data: data
                });

without adding data in constructor method in react -

constructor(props) {
        super(props);
        this.state = {
            data:null
        };
    }

Because without declaring in state also it works fine, but when I say

constructor(props) {
            super(props);
            this.state = {
                data
            };
        }

this gives error.

If I will not add data inside state in constructor it works fine, is it safe ?


问:
Where is the python workspace path located in PyCharm?
I created a Python project using PyCharm (2019.3.3) in folder F:\FolderA then I realized I meant to create it in F:\FolderB. So I copied my project from FolderA to FolderB. Now when I try to install a package, PyCharm says:

```<code>Cannot start process, the working directory 'F:\Projects\FolderA\MyProject\venv\Scripts' does not exist
</code>```

I come from C# background, and everything project related is saved in .csproj file. Does Python have a similar file where it writes project/workspace information? So I can point to the correct path?

答:
Inside /venv/scripts folder there are three "Activate" files. It holds the path to the old directory.

Replace the old paths with new paths

Restart PyCharm

Install package

Here's a screenshot of the path to the files:

Body:
I created a Python project using PyCharm (2019.3.3) in folder F:\FolderA then I realized I meant to create it in F:\FolderB. So I copied my project from FolderA to FolderB. Now when I try to install a package, PyCharm says:

Cannot start process, the working directory 'F:\Projects\FolderA\MyProject\venv\Scripts' does not exist

I come from C# background, and everything project related is saved in .csproj file. Does Python have a similar file where it writes project/workspace information? So I can point to the correct path?


答:
This give errors because is this case data is not a property of state object but a variable you assign inside state object

```<code> constructor(props) {
                super(props);
                this.state = {
                    data
                };
            }
</code>```

Title: is it safe to do setState for undefined values in react

Body:
This give errors because is this case data is not a property of state object but a variable you assign inside state object

 constructor(props) {
                super(props);
                this.state = {
                    data
                };
            }


问:
Angular Change Component Declarations Location
this might be a dumb question but there it goes:

In my angular project i want to change my components declarations from angular.module.ts to modules/modules.modules.ts.

In order to make my src/app structure look like:

```<code>src/
   app/
   .  modules/
   .  .  about/...
   .  .  banner/...
   .  .  contact/...
   .  .  portfolio/...
   .  .  services/...
   .  .  testimonial/...
   .  .  modules.module.ts
   .  app-routing.module.ts
   .  app.component.html
   .  app.component.scss
   .  app.component.spec.ts
   .  app.component.ts
   .  app.module.ts
</code>```

In Resume want to move all my component declarations to modules/modules.module.ts

This is my best attemp so far:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// Modules Components
import { BannerComponent } from './banner/banner.component';
import { ServicesComponent } from './services/services.component';
import { PortfolioComponent } from './portfolio/portfolio.component';
import { TestimonialComponent } from './testimonial/testimonial.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  imports: [CommonModule],
  declarations: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
  exports: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
})
export class ModulesModule {}
</code>```

app.module.ts:

```<code>// Angular CLI
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// App Component
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

// Pages Components
import { HomePageComponent } from './pages/home-page/home-page.component';
import { AboutPageComponent } from './pages/about-page/about-page.component';
import { ServicesPageComponent } from './pages/services-page/services-page.component';
import { PortfolioPageComponent } from './pages/portfolio-page/portfolio-page.component';
import { PortfolioSinglePageComponent } from './pages/portfolio-single-page/portfolio-single-page.component';
import { ContactPageComponent } from './pages/contact-page/contact-page.component';

// Modules Components
//import { BannerComponent } from './modules/banner/banner.component';
//import { ServicesComponent } from './modules/services/services.component';
//import { PortfolioComponent } from './modules/portfolio/portfolio.component';
//import { TestimonialComponent } from './modules/testimonial/testimonial.component';
//import { AboutComponent } from './modules/about/about.component';
//import { ContactComponent } from './modules/contact/contact.component';
import { ModulesModule } from './modules/modules.module';

// Angular Material
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';

// Third Party
import { OwlModule } from 'ngx-owl-carousel';
import { NgxSpinnerModule } from 'ngx-spinner';

// PWA
import { ServiceWorkerModule } from '@angular/service-worker';

// Environment
import { environment } from '../environments/environment';

// Firebase
import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    AboutPageComponent,
    ServicesPageComponent,
    ContactPageComponent,
    PortfolioPageComponent,
    PortfolioSinglePageComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ModulesModule, // here
    BrowserAnimationsModule,
    MaterialModule,
    OwlModule,
    NgxSpinnerModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: true, //environment.production,
    }),
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireDatabaseModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}
</code>```

Please note that i just changes the names to simplify the question. And it was fully working when the declarations wore in the app.module.ts

答:
According to your error you need to:

Import RouterModule in your ModulesModule

Import OwlModule in your ModulesModule

Since I am old and my eyesight is not the best I might have missed some :)

Body:
this might be a dumb question but there it goes:

In my angular project i want to change my components declarations from angular.module.ts to modules/modules.modules.ts.

In order to make my src/app structure look like:

src/
   app/
   .  modules/
   .  .  about/...
   .  .  banner/...
   .  .  contact/...
   .  .  portfolio/...
   .  .  services/...
   .  .  testimonial/...
   .  .  modules.module.ts
   .  app-routing.module.ts
   .  app.component.html
   .  app.component.scss
   .  app.component.spec.ts
   .  app.component.ts
   .  app.module.ts

In Resume want to move all my component declarations to modules/modules.module.ts

This is my best attemp so far:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// Modules Components
import { BannerComponent } from './banner/banner.component';
import { ServicesComponent } from './services/services.component';
import { PortfolioComponent } from './portfolio/portfolio.component';
import { TestimonialComponent } from './testimonial/testimonial.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  imports: [CommonModule],
  declarations: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
  exports: [
    AboutComponent,
    BannerComponent,
    ContactComponent,
    PortfolioComponent,
    ServicesComponent,
    TestimonialComponent,
  ],
})
export class ModulesModule {}

app.module.ts:

// Angular CLI
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// App Component
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

// Pages Components
import { HomePageComponent } from './pages/home-page/home-page.component';
import { AboutPageComponent } from './pages/about-page/about-page.component';
import { ServicesPageComponent } from './pages/services-page/services-page.component';
import { PortfolioPageComponent } from './pages/portfolio-page/portfolio-page.component';
import { PortfolioSinglePageComponent } from './pages/portfolio-single-page/portfolio-single-page.component';
import { ContactPageComponent } from './pages/contact-page/contact-page.component';

// Modules Components
//import { BannerComponent } from './modules/banner/banner.component';
//import { ServicesComponent } from './modules/services/services.component';
//import { PortfolioComponent } from './modules/portfolio/portfolio.component';
//import { TestimonialComponent } from './modules/testimonial/testimonial.component';
//import { AboutComponent } from './modules/about/about.component';
//import { ContactComponent } from './modules/contact/contact.component';
import { ModulesModule } from './modules/modules.module';

// Angular Material
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';

// Third Party
import { OwlModule } from 'ngx-owl-carousel';
import { NgxSpinnerModule } from 'ngx-spinner';

// PWA
import { ServiceWorkerModule } from '@angular/service-worker';

// Environment
import { environment } from '../environments/environment';

// Firebase
import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';

@NgModule({
  declarations: [
    AppComponent,
    HomePageComponent,
    AboutPageComponent,
    ServicesPageComponent,
    ContactPageComponent,
    PortfolioPageComponent,
    PortfolioSinglePageComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ModulesModule, // here
    BrowserAnimationsModule,
    MaterialModule,
    OwlModule,
    NgxSpinnerModule,
    ServiceWorkerModule.register('ngsw-worker.js', {
      enabled: true, //environment.production,
    }),
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFireDatabaseModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Please note that i just changes the names to simplify the question. And it was fully working when the declarations wore in the app.module.ts


问:
html flexbox 2 elements vertical and one on the left
I am totally lost with flexbox for css3, and I cannot seem to figure out how to get it correctly working :(.

I want a layout like:

```<code>|-----| |----|
------- |----|
|-----| |----|
</code>```

(Where |----| on the left are 2 divs an on the right its one)

And on mobile I want the right div to below the other 2 divs...
And I cannot seem to figure it out.

It just will not line up correctly, or the 2 divs on the left will not be as large as the one on the right.

I am using bootstrap 4.0 for this... so maybe that is something?

The following code I am currently at:

There is a container div around it

            <form>

                xxx
                <input type="text" class="form-control date" id="birthdatepicker" data-toggle="daterangepicker" data-single-date-picker="true">

              <button type="submit" class="btn btn-primary waves-effect waves-light">{{ __('Submit') }}</button>
            </form>

{{ __('Progress') }}

xx

            xx

```

答:
here is a simple example of what i think you wish to achive.

.flexbox{
  display: flex;
  flex-direction: row;
  width: 400px;
  height: 400px;
}
@media only screen and (max-width: 478px){
  .flexbox{
    flex-direction: column;
  }
}
.left{
  width: 50%;
  height: 100%;
}
.top-left{
  height: 50%;
  width: 100%;
  position: relative;
  background: red;
}
.bottom-left{
  height: 50%;
  width: 100%;
  position: relative;
  background: green;
}
.right{
  width:50%;
  height:100%;
}
.center-right{
  width: 100%;
  height: 100%;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox">
  <div class="left">
    <div class="top-left">

    </div>
    <div  class="bottom-left">

    </div>
  </div>
  <div class="right">
    <div class="center-right">

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

Body:
I am totally lost with flexbox for css3, and I cannot seem to figure out how to get it correctly working :(.

I want a layout like:

|-----| |----|
------- |----|
|-----| |----|

(Where |----| on the left are 2 divs an on the right its one)

And on mobile I want the right div to below the other 2 divs...
And I cannot seem to figure it out.

It just will not line up correctly, or the 2 divs on the left will not be as large as the one on the right.

I am using bootstrap 4.0 for this... so maybe that is something?

The following code I am currently at:

There is a container div around it

            <form>

                xxx
                <input type="text" class="form-control date" id="birthdatepicker" data-toggle="daterangepicker" data-single-date-picker="true">

              <button type="submit" class="btn btn-primary waves-effect waves-light">{{ __('Submit') }}</button>
            </form>

{{ __('Progress') }}

xx

            xx

Body:
here is a simple example of what i think you wish to achive.

.flexbox{
  display: flex;
  flex-direction: row;
  width: 400px;
  height: 400px;
}
@media only screen and (max-width: 478px){
  .flexbox{
    flex-direction: column;
  }
}
.left{
  width: 50%;
  height: 100%;
}
.top-left{
  height: 50%;
  width: 100%;
  position: relative;
  background: red;
}
.bottom-left{
  height: 50%;
  width: 100%;
  position: relative;
  background: green;
}
.right{
  width:50%;
  height:100%;
}
.center-right{
  width: 100%;
  height: 100%;
  background: blue;
}

<div class="flexbox">
  <div class="left">
    <div class="top-left">

    </div>
    <div  class="bottom-left">

    </div>
  </div>
  <div class="right">
    <div class="center-right">

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


问:
Getting error while using ngbModule in angular
```<code>Here is my module.ts code

import { NgModule,ModuleWithProviders  } from '@angular/core';'

import { CommonModule } from '@angular/common';

import { Routes, RouterModule } from '@angular/router';

import { HeaderModule } from '../../static/header/header.module';

import { AdminDashboardModule } from '../../static/admin-dashboard/admin-dashboard.module';

import { TabsModule } from 'ngx-tabset';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { JournalistEarningsComponent } from './journalist-earnings.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

const routes: Routes = [{

    path: '',

    component: JournalistEarningsComponent,

  }];

@NgModule({

  imports: [

    NgbModule,

    RouterModule.forChild(routes),

    HeaderModule,

    AdminDashboardModule,

    TabsModule,

    FormsModule,

    ReactiveFormsModule,

    CommonModule

  ],
  declarations: [JournalistEarningsComponent],
})

Component.ts

page: any;

  pageSize: any

  items = [];

  constructor(

    private modalService: BsModalService,

    private router: Router,

    private httpService: LoginService,

  ) {

    for (let i = 1; i <= 100; i++) {

      this.items.push({ Name: 'Shop ' + i });

    }

  }

component.html

 <table>

            <tr *ngFor="let item of items | slice: (page-1) * pageSize : (page-1) * pageSize + pageSize">

              <td>{{item.Name}}</td>

            </tr>

         </table>

         <ngb-pagination [collectionSize]="items.length" [(page)]="page" [maxSize]="5" [rotate]="true" [ellipses]="false" [boundaryLinks]="true"></ngb-pagination>
</code>```

I am getting this error. I have tried another answer but it is not working. If any user is working on angular 8 then please provide your insight. I have also searched for ngbpagination and implemented other solutions for ngbPaginationConfig but it doesn't seem to work.

I have a Angular8 app with a component where I have a table. Table is generated via *ngFor directive. Each row of the table is an object with some fields that is being loaded from the backend when the component is initialized.

```<code>**StaticInjectorError(AppModule)[NgbPagination -> NgbPaginationConfig]:

  StaticInjectorError(Platform: core)[NgbPagination -> NgbPaginationConfig]:

    NullInjectorError: No provider for NgbPaginationConfig!**
</code>```

答:
You must import them module with PaginationModule.forRoot():

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PaginationModule } from 'ng2-bootstrap';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    AppRoutingModule,
    BrowserModule,
    PaginationModule.forRoot()
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
</code>```

ref: github issus

Body:
Here is my module.ts code

import { NgModule,ModuleWithProviders  } from '@angular/core';'

import { CommonModule } from '@angular/common';

import { Routes, RouterModule } from '@angular/router';

import { HeaderModule } from '../../static/header/header.module';

import { AdminDashboardModule } from '../../static/admin-dashboard/admin-dashboard.module';

import { TabsModule } from 'ngx-tabset';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { JournalistEarningsComponent } from './journalist-earnings.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

const routes: Routes = [{

    path: '',

    component: JournalistEarningsComponent,

  }];

@NgModule({

  imports: [

    NgbModule,

    RouterModule.forChild(routes),

    HeaderModule,

    AdminDashboardModule,

    TabsModule,

    FormsModule,

    ReactiveFormsModule,

    CommonModule

  ],
  declarations: [JournalistEarningsComponent],
})

Component.ts

page: any;

  pageSize: any

  items = [];

  constructor(

    private modalService: BsModalService,

    private router: Router,

    private httpService: LoginService,

  ) {

    for (let i = 1; i <= 100; i++) {

      this.items.push({ Name: 'Shop ' + i });

    }

  }

component.html

              {{item.Name}}

         <ngb-pagination [collectionSize]="items.length" [(page)]="page" [maxSize]="5" [rotate]="true" [ellipses]="false" [boundaryLinks]="true"></ngb-pagination>

I am getting this error. I have tried another answer but it is not working. If any user is working on angular 8 then please provide your insight. I have also searched for ngbpagination and implemented other solutions for ngbPaginationConfig but it doesn't seem to work.

I have a Angular8 app with a component where I have a table. Table is generated via *ngFor directive. Each row of the table is an object with some fields that is being loaded from the backend when the component is initialized.

**StaticInjectorError(AppModule)[NgbPagination -> NgbPaginationConfig]:

  StaticInjectorError(Platform: core)[NgbPagination -> NgbPaginationConfig]:

    NullInjectorError: No provider for NgbPaginationConfig!**

Body:
You must import them module with PaginationModule.forRoot():

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PaginationModule } from 'ng2-bootstrap';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    AppRoutingModule,
    BrowserModule,
    PaginationModule.forRoot()
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

ref: github issus


问:
Address offset in RISC-V load instructions hardcoded or not?
For educational purposes I used https://godbolt.org/z/7F-Lhm to translate

```<code>// C++ code
char i = 3;
char A[] = {0,1,2,3,4,5};
int myfunction() {
    return A[i];
}
</code>```

into

```<code># RISC-V instructions
myfunction():                        # @myfunction()
        lui     a0, %hi(i)
        lbu     a0, %lo(i)(a0)
        lui     a1, %hi(A)
        addi    a1, a1, %lo(A)
        add     a0, a0, a1
        lbu     a0, 0(a0)
        ret
i:
        .byte   3                       # 0x3

A:
        .ascii  "\000\001\002\003\004\005"
</code>```

But why is A[i] loaded with add a0, a0, a1, lbu a0, 0(a0) and not just with lbu a0, a0(a1)?

It would make sense if for lbu dest, offset(baseAdress) only dest and baseAdresse are allowed to be register adresses, whereas offset is a hardcoded number in the instruction word itself. But in the same code above I see lbu a0, %lo(i)(a0) so offset can apparently also be "somewhat variable"?

Maybe the reason I don't understand this is because I don't really understand why this $hi $lo thing is necessary in the first place. Why are we doing lui a0, %hi(i), lbu a0, %lo(i)(a0) instead of just lbu a0, 0(i)?

答:
and not just with lbu a0, a0(a1)?

RISC V (and MIPS) do not have a base register + base register addressing mode — they both have only one and that is base register + immediate.

So the register + register operation required for A+i has to be done with a separate add instruction.

instead of just lbu a0, 0(i)?

There is not enough room in the 32-bit instruction to hold the address of a global, so multiple instructions are used.

You have declared the variables as globals, therefore some of this code is about accessing the globals.

```<code>myfunction():                        # @myfunction()
        lui     a0, %hi(i)      <--- 1st part of 2 instructions for the char i global
        lbu     a0, %lo(i)(a0)  <--- 2nd instruction for fetching the char i global
        lui     a1, %hi(A)      <--- 1st part of 2 instructions for A global array
        addi    a1, a1, %lo(A)  <--- 2nd instruction for fetching addr of A global

        add     a0, a0, a1      <--- the array indexing A + i
        lbu     a0, 0(a0)       <--- the dereference *(A+i)
        ret
i:
        .byte   3                       # 0x3

A:
        .ascii  "\000\001\002\003\004\005"
</code>```

If you try a different approach you'll see some of this disappear so you can see the array reference more directly:

```<code>int myfunction(char A [], int i) {
    return A[i];
}
</code>```

```<code>myfunction(char*, int):                      # @myfunction(char*, int)
    add     a0, a0, a1
    lbu     a0, 0(a0)
    ret
</code>```

Body:
For educational purposes I used https://godbolt.org/z/7F-Lhm to translate

// C++ code
char i = 3;
char A[] = {0,1,2,3,4,5};
int myfunction() {
    return A[i];
}

into

# RISC-V instructions
myfunction():                        # @myfunction()
        lui     a0, %hi(i)
        lbu     a0, %lo(i)(a0)
        lui     a1, %hi(A)
        addi    a1, a1, %lo(A)
        add     a0, a0, a1
        lbu     a0, 0(a0)
        ret
i:
        .byte   3                       # 0x3

A:
        .ascii  "\000\001\002\003\004\005"

But why is A[i] loaded with add a0, a0, a1, lbu a0, 0(a0) and not just with lbu a0, a0(a1)?

It would make sense if for lbu dest, offset(baseAdress) only dest and baseAdresse are allowed to be register adresses, whereas offset is a hardcoded number in the instruction word itself. But in the same code above I see lbu a0, %lo(i)(a0) so offset can apparently also be "somewhat variable"?

Maybe the reason I don't understand this is because I don't really understand why this $hi $lo thing is necessary in the first place. Why are we doing lui a0, %hi(i), lbu a0, %lo(i)(a0) instead of just lbu a0, 0(i)?

Body:
and not just with lbu a0, a0(a1)?

RISC V (and MIPS) do not have a base register + base register addressing mode — they both have only one and that is base register + immediate.

So the register + register operation required for A+i has to be done with a separate add instruction.

instead of just lbu a0, 0(i)?

There is not enough room in the 32-bit instruction to hold the address of a global, so multiple instructions are used.

You have declared the variables as globals, therefore some of this code is about accessing the globals.

myfunction():                        # @myfunction()
        lui     a0, %hi(i)      <--- 1st part of 2 instructions for the char i global
        lbu     a0, %lo(i)(a0)  <--- 2nd instruction for fetching the char i global
        lui     a1, %hi(A)      <--- 1st part of 2 instructions for A global array
        addi    a1, a1, %lo(A)  <--- 2nd instruction for fetching addr of A global

        add     a0, a0, a1      <--- the array indexing A + i
        lbu     a0, 0(a0)       <--- the dereference *(A+i)
        ret
i:
        .byte   3                       # 0x3

A:
        .ascii  "\000\001\002\003\004\005"

If you try a different approach you'll see some of this disappear so you can see the array reference more directly:

int myfunction(char A [], int i) {
    return A[i];
}

myfunction(char*, int):                      # @myfunction(char*, int)
    add     a0, a0, a1
    lbu     a0, 0(a0)
    ret


问:
Multiple rows to one comma-separated value in sql
We want to display multiple column value into the single column with comma separated value
below is the my table data

Below is the SQL query i am trying:

```<code>    select
         name,
         STUFF((SELECT '; ' + facilty FROM leads Name FOR XML PATH('')),1,2,'')
 as facilty,
         address
    from leads
</code>```

Query Result

Now when I execute the query in SQL Server, I want reuslt to be like:

答:
Use string_agg():

```<code>select max(name), string_agg(facility, ','), max(address)
from leads
group by leadid;
</code>```

Body:
We want to display multiple column value into the single column with comma separated value
below is the my table data

Below is the SQL query i am trying:

    select
         name,
         STUFF((SELECT '; ' + facilty FROM leads Name FOR XML PATH('')),1,2,'')
 as facilty,
         address
    from leads

Query Result

Now when I execute the query in SQL Server, I want reuslt to be like:

Body:
Use string_agg():

select max(name), string_agg(facility, ','), max(address)
from leads
group by leadid;


问:
Algorithm for color quantization/reduced image color palette in JavaScript?
I'm writing a web app that takes a user-submitted image, gets the pixel data via a canvas element, does some processing, and then renders the image using vector shapes (using Protovis). It's working well, but I end up with several thousand colors, and I'd like to let the user pick a target palette size and reduce the color palette to that size.

At the point where I want to reduce the color space, I'm working with an array of RGB pixel data, like this:

```<code>[[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207], ...]
</code>```

I tried the naive option of just removing least-significant bits from the colors, but the results were pretty bad. I've done some research on color quantization algorithms, but have yet to find a clear description of how to implement one. I could probably work out a cludgy way to send this to the server, run it though an image processing program, and send the resulting palette back, but I'd prefer to do it in JavaScript on the client side.

Does anyone have an example of a clearly explained algorithm that would work here? The goal is to reduce a palette of several thousand colors to a smaller palette optimized for this specific image.

Edit (7/25/11): I took @Pointy's suggestion and implemented (most of) Leptonica's MMCQ (modified median cut quantization) in JavaScript. If you're interested, you can see the code here.

Edit (8/5/11): The clusterfck library looks like another great option for this (though I think it's a bit slower than my implementation).

答:
With the caveat that I don't claim any expertise at all in any field of image processing: I read over the Wikipedia article you linked, and from there found Dan Bloomberg's Leptonica.  From there you can download the sources for the algorithms discussed and explained.

The source code is in C, which hopefully is close enough to JavaScript (at least in the core "formula" parts) to be understandable.  The basic ideas behind the "MMCQ" algorithm don't seem super-complicated. It's really just some heuristic tricks for splitting up the 3-dimensional color space into sub-cubes based on the way colors in an image clump together.

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a web app that takes a user-submitted image, gets the pixel data via a canvas element, does some processing, and then renders the image using vector shapes (using Protovis). It's working well, but I end up with several thousand colors, and I'd like to let the user pick a target palette size and reduce the color palette to that size.

At the point where I want to reduce the color space, I'm working with an array of RGB pixel data, like this:

[[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207], ...]

I tried the naive option of just removing least-significant bits from the colors, but the results were pretty bad. I've done some research on color quantization algorithms, but have yet to find a clear description of how to implement one. I could probably work out a cludgy way to send this to the server, run it though an image processing program, and send the resulting palette back, but I'd prefer to do it in JavaScript on the client side.

Does anyone have an example of a clearly explained algorithm that would work here? The goal is to reduce a palette of several thousand colors to a smaller palette optimized for this specific image.

Edit (7/25/11): I took @Pointy's suggestion and implemented (most of) Leptonica's MMCQ (modified median cut quantization) in JavaScript. If you're interested, you can see the code here.

Edit (8/5/11): The clusterfck library looks like another great option for this (though I think it's a bit slower than my implementation).


问:
MassTransit.AmazonSQS: Is it possible to subscribe an already existing SQS queue in a receiveendpoint to a SNS Topic after the Bus has been started?
I'm running a MassTransit configuration with AmazonSQS. In my program I start by creating a receiveenpoint with the queue "input-queue1", I subscribe this SQS queue to an SNS topic named "topic1" and associate a consumer to this receiveendpoint that does some standard printing of the messages it receives. After starting the bus i want to subscribe the already created queue "input-queue1" to another SNS topic, named "topic2", but I couldn't find a way of doing this after starting the Bus (It's important to me that i can do this after the Bus is started). Is there a way of doing this and i'm just missing something, or is it not possible at all? (I tried with the commented portion of the code but it didn't work)</p>

```<code>class Program
    {
        static async Task Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingAmazonSqs(x =>
            {
                x.Host(Constants.Region, h =>
                {
                    h.AccessKey(Constants.AccesskeyId);
                    h.SecretKey(Constants.SecretAccessKey);
                });

                x.ReceiveEndpoint("input-queue1", e =>
                {
                    e.Subscribe("topic1", callback => { });

                    e.Consumer(() => new Handler());
                });

            });

            bus.StartAsync().Wait();

            /*var handle = bus.ConnectReceiveEndpoint("input-queue1", e => {
                e.Subscribe("topic2", callback => { });
            });
            var ready = await handle.Ready;*/

            Console.WriteLine("Listening to messages...");
            Console.WriteLine("Press enter to quit");
            Console.ReadLine();
        }
    }
</code>```

答:
You can't change the topology of a receive endpoint once it has been created. This means that no new topic subscriptions can be created, and existing subscriptions cannot be removed.

If you need to change the configuration of the receive endpoint, you would need to do it yourself by using the SNS API to add the subscription yourself. I would question why you would want to do this though. If the consumer isn't able to consume the message forwarded to the queue, it would be moved to the skipped queue.

Body:
I'm running a MassTransit configuration with AmazonSQS. In my program I start by creating a receiveenpoint with the queue "input-queue1", I subscribe this SQS queue to an SNS topic named "topic1" and associate a consumer to this receiveendpoint that does some standard printing of the messages it receives. After starting the bus i want to subscribe the already created queue "input-queue1" to another SNS topic, named "topic2", but I couldn't find a way of doing this after starting the Bus (It's important to me that i can do this after the Bus is started). Is there a way of doing this and i'm just missing something, or is it not possible at all? (I tried with the commented portion of the code but it didn't work)

class Program
    {
        static async Task Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingAmazonSqs(x =>
            {
                x.Host(Constants.Region, h =>
                {
                    h.AccessKey(Constants.AccesskeyId);
                    h.SecretKey(Constants.SecretAccessKey);
                });

                x.ReceiveEndpoint("input-queue1", e =>
                {
                    e.Subscribe("topic1", callback => { });

                    e.Consumer(() => new Handler());
                });

            });

            bus.StartAsync().Wait();

            /*var handle = bus.ConnectReceiveEndpoint("input-queue1", e => {
                e.Subscribe("topic2", callback => { });
            });
            var ready = await handle.Ready;*/

            Console.WriteLine("Listening to messages...");
            Console.WriteLine("Press enter to quit");
            Console.ReadLine();
        }
    }


问:
Inserting large amounts of data in sqlite
I am making an inverted index lookup table for my database in sqlite3. The database I have consists of certain bloggers and their posts.

I have a table post which has the columns id, text, blogger_id. This table consists of ~680 000 posts. And I want to make a table Blogger_Post_Word with the columns blogger_id, post_id, word_position, word_id.

I am using Python for this and I have tried a 2 ways before but both have their problems.

I saw online that the best way to insert large amounts of data is with a bulk insert. This means that I have to fetch all the posts and for each word in a post I have to store that locally so I can do a bulk insert later. This requires way to much memory that I don't have.

I have also tried inserting each word one by one but this just takes way to long.

Is there an efficient way to solve this problem or an sql statement that does this in one go?

Edit:
This is my the code I'm using now:

```<code>@lru_cache()
def get_word_id(_word: str) -> int:
    word_w_id = db.get_one('Word', ['word'], (word,))
    if word_w_id is None:
        db.insert_one('Word', ['word'], (word,))
        word_w_id = db.get_one('Word', ['word'], (word,))
    return word_w_id[0]

for post_id, text, creation_date, blogger_id in db.get_all('Post'):
    split_text = text.split(' ')

    for word_position, word in enumerate(split_text):
        word_id = get_word_id(word)

        db.insert_one('Blogger_Post_Word',
                      ['blogger_id', 'post_id', 'word_position', 'word_id'],
                      (blogger_id, post_id, word_position, word_id))
</code>```

The db is a class I wrote to handle the database, these are the functions in that class I use:

```<code>def get(self, table: str, where_cols: list = None, where_vals: tuple = None):
    query = 'SELECT * FROM ' + table

    if where_cols is not None and where_vals is not None:
        where_cols = [w + '=?' for w in where_cols]
        query += ' WHERE ' + ' and '.join(where_cols)

        return self.c.execute(query, where_vals)

    return self.c.execute(query)

def get_one(self, table: str, where_cols: list = None, where_vals: tuple = None):
    self.get(table, where_cols, where_vals)
    return self.c.fetchone()

def insert_one(self, table: str, columns: list, values: tuple):
    query = self.to_insert_query(table, columns)
    self.c.execute(query, values)
    self.conn.commit()

def to_insert_query(self, table: str, columns: list):
    return 'INSERT INTO ' + table + '(' + ','.join(columns) + ')' + ' VALUES (' + ','.join(['?' for i in columns]) + ')'

</code>```

答:
Okay I hope this helps anyone.

The problem was that indeed that insert one is too slow and I didn't have enough memory to store the whole list locally.

Instead I used a hybrid of the two and insert them into the database incrementaly.

I displayed the size of my list to determine the bottleneck. It seemed that 150 000 posts of the 680 000 was about my bottleneck. The total size of the list was about 4.5 GB.

```<code>from pympler.asizeof import asizeof
print(asizeof(indexed_data))

>>> 4590991936
</code>```

I decide on an increment of 50 000 posts to keep everything running smooth.

This is now my code:

```<code># get all posts
c.execute('SELECT * FROM Post')
all_posts = c.fetchall()

increment = 50000

start = 0
end = increment

while start < len(all_posts):
    indexed_data = []

    print(start, ' -> ', end)

    for post_id, text, creation_date, blogger_id in all_posts[start:end]:
        split_text = text.split(' ')

        # for each word in the post add a tuple with blogger id, post id, word position in the post and the word to indexed_data
        indexed_data.extend([(blogger_id, post_id, word_position, word) for word_position, word in enumerate(split_text)])

    print('saving...')
    c.executemany('''
    INSERT INTO Inverted_index (blogger_id, post_id, word_position, word)
    VALUES (?, ?, ?, ?)
    ''', indexed_data)

    start += increment
    if end + increment > len(all_posts):
        end = len(all_posts)
    else:
        end += increment
</code>```

Body:
I am making an inverted index lookup table for my database in sqlite3. The database I have consists of certain bloggers and their posts.

I have a table post which has the columns id, text, blogger_id. This table consists of ~680 000 posts. And I want to make a table Blogger_Post_Word with the columns blogger_id, post_id, word_position, word_id.

I am using Python for this and I have tried a 2 ways before but both have their problems.

I saw online that the best way to insert large amounts of data is with a bulk insert. This means that I have to fetch all the posts and for each word in a post I have to store that locally so I can do a bulk insert later. This requires way to much memory that I don't have.

I have also tried inserting each word one by one but this just takes way to long.

Is there an efficient way to solve this problem or an sql statement that does this in one go?

Edit:
This is my the code I'm using now:

@lru_cache()
def get_word_id(_word: str) -> int:
    word_w_id = db.get_one('Word', ['word'], (word,))
    if word_w_id is None:
        db.insert_one('Word', ['word'], (word,))
        word_w_id = db.get_one('Word', ['word'], (word,))
    return word_w_id[0]

for post_id, text, creation_date, blogger_id in db.get_all('Post'):
    split_text = text.split(' ')

    for word_position, word in enumerate(split_text):
        word_id = get_word_id(word)

        db.insert_one('Blogger_Post_Word',
                      ['blogger_id', 'post_id', 'word_position', 'word_id'],
                      (blogger_id, post_id, word_position, word_id))

The db is a class I wrote to handle the database, these are the functions in that class I use:

def get(self, table: str, where_cols: list = None, where_vals: tuple = None):
    query = 'SELECT * FROM ' + table

    if where_cols is not None and where_vals is not None:
        where_cols = [w + '=?' for w in where_cols]
        query += ' WHERE ' + ' and '.join(where_cols)

        return self.c.execute(query, where_vals)

    return self.c.execute(query)

def get_one(self, table: str, where_cols: list = None, where_vals: tuple = None):
    self.get(table, where_cols, where_vals)
    return self.c.fetchone()

def insert_one(self, table: str, columns: list, values: tuple):
    query = self.to_insert_query(table, columns)
    self.c.execute(query, values)
    self.conn.commit()

def to_insert_query(self, table: str, columns: list):
    return 'INSERT INTO ' + table + '(' + ','.join(columns) + ')' + ' VALUES (' + ','.join(['?' for i in columns]) + ')'

Body:
Okay I hope this helps anyone.

The problem was that indeed that insert one is too slow and I didn't have enough memory to store the whole list locally.

Instead I used a hybrid of the two and insert them into the database incrementaly.

I displayed the size of my list to determine the bottleneck. It seemed that 150 000 posts of the 680 000 was about my bottleneck. The total size of the list was about 4.5 GB.

from pympler.asizeof import asizeof
print(asizeof(indexed_data))

>>> 4590991936

I decide on an increment of 50 000 posts to keep everything running smooth.

This is now my code:

# get all posts
c.execute('SELECT * FROM Post')
all_posts = c.fetchall()

increment = 50000

start = 0
end = increment

while start < len(all_posts):
    indexed_data = []

    print(start, ' -> ', end)

    for post_id, text, creation_date, blogger_id in all_posts[start:end]:
        split_text = text.split(' ')

        # for each word in the post add a tuple with blogger id, post id, word position in the post and the word to indexed_data
        indexed_data.extend([(blogger_id, post_id, word_position, word) for word_position, word in enumerate(split_text)])

    print('saving...')
    c.executemany('''
    INSERT INTO Inverted_index (blogger_id, post_id, word_position, word)
    VALUES (?, ?, ?, ?)
    ''', indexed_data)

    start += increment
    if end + increment > len(all_posts):
        end = len(all_posts)
    else:
        end += increment


问:
How to resolve invalid issue in template driven form angular 8
In template driven form i am getting below the error:

```<code>ERROR TypeError: Cannot read property 'invalid' of undefined
</code>```

I do not know why i am getting this.How to resolve this issue?

app.component.html:

```<code><form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
                <label for="categoryName">Category Name:</label>
                <input type="text" class="form-control" name="categoryName" [(ngModel)]="cate.categoryName" minlength="5" #categoryname="ngModel" [ngClass]="{ 'is-invalid': f.submitted && categoryName.invalid }" required/>
                <div *ngIf="f.submitted && categoryName.invalid" class="invalid-feedback">
                    <div *ngIf="categoryName.errors.required">
                        Category Name is required
                    </div>
                </div>
                <div *ngIf="categoryName?.touched && categoryName?.errors.minlength" class="invalid-feedback">
                    Category Name must be at least 5 characters long.
                </div>
            </div>
</form>
</code>```

app.component.ts:

```<code>  cate: any = {};
  onSubmit() {
      alert(this.cate.categoryName);
  }
</code>```

答:
In your template:

```<code>categoryName.invalid
</code>```

But I can't see any place where categoryName is set to something.

You could "fix" it like so

```<code> categoryName?.invalid
</code>```

Note that #categoryname and categoryName are not the same (lower case vs upper case "n").

Body:
In template driven form i am getting below the error:

ERROR TypeError: Cannot read property 'invalid' of undefined

I do not know why i am getting this.How to resolve this issue?

app.component.html:

<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>

                Category Name:
                <input type="text" class="form-control" name="categoryName" [(ngModel)]="cate.categoryName" minlength="5" #categoryname="ngModel" [ngClass]="{ 'is-invalid': f.submitted && categoryName.invalid }" required/>

                        Category Name is required

                    Category Name must be at least 5 characters long.

</form>

app.component.ts:

  cate: any = {};
  onSubmit() {
      alert(this.cate.categoryName);
  }

Body:
In your template:

categoryName.invalid

But I can't see any place where categoryName is set to something.

You could "fix" it like so

 categoryName?.invalid

Note that #categoryname and categoryName are not the same (lower case vs upper case "n").


答:
Use where clause :</p>

```<code>select name , STUFF((SELECT '; ' + facilty
                     FROM leads
                     FOR XML PATH('')
                    ),1,2,'') as facilty, address
from leads
where name is not null;
</code>```

Title: Multiple rows to one comma-separated value in sql

Body:
Use where clause :

select name , STUFF((SELECT '; ' + facilty
                     FROM leads
                     FOR XML PATH('')
                    ),1,2,'') as facilty, address
from leads
where name is not null;


问:
Overlay polygon on top of image in Python
Say I have an image in PIL

```<code>from PIL import Image
Image.open(path_to_my_image)
</code>```

and two lists of x points and y points

```<code>x = ['10', '30', '70']
y = ['15', '45', '90']
</code>```

Is there a way to overlay my polygon with transparency on this image?

Also, is PIL a good library for this? Or should I use a different one? (e.g. scikits.image, or render in an image with pylab).

答:
To do that you can use Shapely and OpenCV like this:</p>

```<code>import cv2
import numpy as np
from shapely.geometry import Polygon

x = [10, 30, 70]
y = [15, 45, 90]
alpha = 0.5 # that's your transparency factor
path = 'path_to_image.jpg'

polygon = Polygon([(x[0], y[0]), (x[1], y[1]), (x[2], y[2]), (x[0], y[2])])
int_coords = lambda x: np.array(x).round().astype(np.int32)
exterior = [int_coords(polygon.exterior.coords)]

image = cv2.imread(path)
overlay = image.copy()
cv2.fillPoly(overlay, exterior, color=(255, 255, 0))
cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0, image)
cv2.imshow("Polygon", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Body:
Say I have an image in PIL

from PIL import Image
Image.open(path_to_my_image)

and two lists of x points and y points

x = ['10', '30', '70']
y = ['15', '45', '90']

Is there a way to overlay my polygon with transparency on this image?

Also, is PIL a good library for this? Or should I use a different one? (e.g. scikits.image, or render in an image with pylab).

Body:
To do that you can use Shapely and OpenCV like this:

import cv2
import numpy as np
from shapely.geometry import Polygon

x = [10, 30, 70]
y = [15, 45, 90]
alpha = 0.5 # that's your transparency factor
path = 'path_to_image.jpg'

polygon = Polygon([(x[0], y[0]), (x[1], y[1]), (x[2], y[2]), (x[0], y[2])])
int_coords = lambda x: np.array(x).round().astype(np.int32)
exterior = [int_coords(polygon.exterior.coords)]

image = cv2.imread(path)
overlay = image.copy()
cv2.fillPoly(overlay, exterior, color=(255, 255, 0))
cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0, image)
cv2.imshow("Polygon", image)
cv2.waitKey(0)
cv2.destroyAllWindows()


问:
dplyr::mutate with an external function- returning 0
this is my second time posting, I hope this code is more reproducible.
I am trying to make a list of keywords and amount of PUBMED publications for each. I have created a function that uses Entrez library. However,
so far the function works if handled manually, but when i am trying to run it on the df it returns zeros..

```<code>##librarires
#install.packages("rentrez")
library(tidyverse)
library(rentrez)

keywords <- structure(list(keyword = c("×“×\231×¡×§×¦×\231×” 1 â\200“ ×’×‘",
                                       "Netterâ\200\231s atlas (6th edition): Plates 171", "Grant's dissector (12 edition): pages 129-135",
                                       "Back â\200“", "trapezius muscle", "deltoid muscle", "teres major/minor muscle",
                                       "latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
                                       "levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
                                       "thoracolumbar fascia.", "Bone â\200“", "Clavicle", "acromial/sternal end",
                                       "shaft body", "subclavian groove", "conoid tubercle", "trapezoid line"
)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))

articles_number <- function(trm) {
  trm<- paste(trm,"[All Fields]")
  pkg_search <- entrez_search(db="pubmed",
                              term=trm
  )
  return(pkg_search$count) }
pubmed_count <- keywords %>%
  mutate(cnt = articles_number(keywords))

##As an example, running this function only on clavicle reruns a non zero number
articles_number("Clavicle")
</code>```

I have a second problem when running this with a bigger datasets but i'll upload that later..
Any thoughts? Many thanks and help is appreciated

答:
There were two problems. The first was a typo. Your keywords data frame does not have a column called keywords. It is called keyword, so the mutate call won't find keywords. Secondly, your articles_number function isn't vectorized, so it needs to go in an sapply:

```<code>pubmed_count <- keywords %>% mutate(cnt = sapply(keyword, articles_number))

pubmed_count
#> pubmed_count
#> # A tibble: 20 x 2
#>    keyword                                                cnt
#>    <chr>                                                <int>
#>  1 ×“×™×¡×§×¦×™×” 1 â€“ ×’×‘                                0
#>  2 Netterâ€™s atlas (6th edition): Plates 171               0
#>  3 Grant's dissector (12 edition): pages 129-135            0
#>  4 Back â€“                                               273
#>  5 trapezius muscle                                      4129
#>  6 deltoid muscle                                        3216
#>  7 teres major/minor muscle                                10
#>  8 latissimus dorsi muscle                               4580
#>  9 serratus anterior/posterior superior/inferior muscle     0
#> 10 levator scapulae                                      1406
#> 11 rhomboid major/minor muscle                              4
#> 12 erector spinae muscle                                  335
#> 13 thoracolumbar fascia.                                 9228
#> 14 Bone â€“                                               212
#> 15 Clavicle                                              8946
#> 16 acromial/sternal end                                     9
#> 17 shaft body                                            1386
#> 18 subclavian groove                                        5
#> 19 conoid tubercle                                         15
#> 20 trapezoid line                                           1
</code>```

Body:
this is my second time posting, I hope this code is more reproducible.
I am trying to make a list of keywords and amount of PUBMED publications for each. I have created a function that uses Entrez library. However,
so far the function works if handled manually, but when i am trying to run it on the df it returns zeros..

##librarires
#install.packages("rentrez")
library(tidyverse)
library(rentrez)

keywords <- structure(list(keyword = c("×“×\231×¡×§×¦×\231×” 1 â\200“ ×’×‘",
                                       "Netterâ\200\231s atlas (6th edition): Plates 171", "Grant's dissector (12 edition): pages 129-135",
                                       "Back â\200“", "trapezius muscle", "deltoid muscle", "teres major/minor muscle",
                                       "latissimus dorsi muscle", "serratus anterior/posterior superior/inferior muscle",
                                       "levator scapulae", "rhomboid major/minor muscle", "erector spinae muscle",
                                       "thoracolumbar fascia.", "Bone â\200“", "Clavicle", "acromial/sternal end",
                                       "shaft body", "subclavian groove", "conoid tubercle", "trapezoid line"
)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"))

articles_number <- function(trm) {
  trm<- paste(trm,"[All Fields]")
  pkg_search <- entrez_search(db="pubmed",
                              term=trm
  )
  return(pkg_search$count) }
pubmed_count <- keywords %>%
  mutate(cnt = articles_number(keywords))

##As an example, running this function only on clavicle reruns a non zero number
articles_number("Clavicle")

I have a second problem when running this with a bigger datasets but i'll upload that later..
Any thoughts? Many thanks and help is appreciated

Body:
There were two problems. The first was a typo. Your keywords data frame does not have a column called keywords. It is called keyword, so the mutate call won't find keywords. Secondly, your articles_number function isn't vectorized, so it needs to go in an sapply:

pubmed_count <- keywords %>% mutate(cnt = sapply(keyword, articles_number))

pubmed_count
#> pubmed_count
#> # A tibble: 20 x 2
#>    keyword                                                cnt
#>    <chr>                                                <int>
#>  1 ×“×™×¡×§×¦×™×” 1 â€“ ×’×‘                                0
#>  2 Netterâ€™s atlas (6th edition): Plates 171               0
#>  3 Grant's dissector (12 edition): pages 129-135            0
#>  4 Back â€“                                               273
#>  5 trapezius muscle                                      4129
#>  6 deltoid muscle                                        3216
#>  7 teres major/minor muscle                                10
#>  8 latissimus dorsi muscle                               4580
#>  9 serratus anterior/posterior superior/inferior muscle     0
#> 10 levator scapulae                                      1406
#> 11 rhomboid major/minor muscle                              4
#> 12 erector spinae muscle                                  335
#> 13 thoracolumbar fascia.                                 9228
#> 14 Bone â€“                                               212
#> 15 Clavicle                                              8946
#> 16 acromial/sternal end                                     9
#> 17 shaft body                                            1386
#> 18 subclavian groove                                        5
#> 19 conoid tubercle                                         15
#> 20 trapezoid line                                           1


问:
Why does the docker-compose healthcheck of my mongo container always fail?
I'm using docker-compose to stand up an Express/React/Mongo app.  I can currently stand up everything using retry logic in the express app.  However, I would prefer to use Docker's healthcheck to prevent the string of errors when the containers initially spin up.  However, when I add a healthcheck in my docker-compose.yml, it hangs for the interval/retry time limit and exits with:

```<code>ERROR: for collector  Container "70e7aae49c64" is unhealthy.

ERROR: for server  Container "70e7aae49c64" is unhealthy.
ERROR: Encountered errors while bringing up the project.
</code>```

It seems that my healthcheck never returns a healthy status, and I'm not entirely sure why.  The entirety of my docker-compose.yml:

```<code>version: "2.1"
services:
  mongo:
    image: mongo
    volumes:
      - ./data/mongodb/db:/data/db
    ports:
      - "${DB_PORT}:${DB_PORT}"
    healthcheck:
      test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1
      interval: 10s
      timeout: 10s
      retries: 5
  collector:
    build: ./collector/
    environment:
      - DB_HOST=${DB_HOST}
      - DB_PORT=${DB_PORT}
      - DB_NAME=${DB_NAME}
    volumes:
      - ./collector/:/app
    depends_on:
      mongo:
        condition: service_healthy
  server:
    build: .
    environment:
      - SERVER_PORT=$SERVER_PORT
    volumes:
      - ./server/:/app
    ports:
      - "${SERVER_PORT}:${SERVER_PORT}"
    depends_on:
      mongo:
        condition: service_healthy
</code>```

For the test, I've also tried:

```<code>["CMD", "nc", "-z", "localhost", "27017"]
</code>```

And:

```<code>["CMD", "bash", "/mongo-healthcheck"]
</code>```

I've also tried ditching the healthcheck altogether, following the advice of this guy.  Everything stands up, but I get the dreaded errors in the output before a successful connection:

```<code>collector_1  | MongoDB connection error: MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect
ECONNREFUSED 172.21.0.2:27017]
collector_1  | MongoDB connection with retry
collector_1  | MongoDB connection error: MongoNetworkError: failed to connect to server [mongo:27017] on first connect
</code>```

The ultimate goal is a clean startup output when running the docker-compose up --build.  I've also looked into some of the solutions in this question, but I haven't had much luck with wait-for-it either.  What's the correct way to wait for Mongo to be up and running before starting the other containers, and achieving a clean startup?

答:
We can use MongoDB's serverStatus command to do the health check, as the MongoDB document puts it this way:

Monitoring applications can run this command at a regular interval to collect statistics about the instance.

Because this command serverStatus requires authentication, you need setup the health check similar to the configuration shown below:

```<code>version: '3.4'

services:
  mongo:
    image: mongo
    restart: always
    healthcheck:
      test: echo 'db.runCommand({serverStatus:1}).ok' | mongo admin -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD --quiet | grep 1
      interval: 10s
      timeout: 10s
      retries: 3
      start_period: 20s
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

</code>```

That's it. If your MongoDB instance is healthy, you will see something similar to mine:

```<code>$ docker ps
CONTAINER ID  IMAGE  COMMAND                 CREATED         STATUS                   PORTS      NAMES
01ed0e02aa70  mongo  "docker-entrypoint.s…"  11 minutes ago  Up 11 minutes (healthy)  27017/tcp  demo_mongo_1
</code>```

Body:
I'm using docker-compose to stand up an Express/React/Mongo app.  I can currently stand up everything using retry logic in the express app.  However, I would prefer to use Docker's healthcheck to prevent the string of errors when the containers initially spin up.  However, when I add a healthcheck in my docker-compose.yml, it hangs for the interval/retry time limit and exits with:

ERROR: for collector  Container "70e7aae49c64" is unhealthy.

ERROR: for server  Container "70e7aae49c64" is unhealthy.
ERROR: Encountered errors while bringing up the project.

It seems that my healthcheck never returns a healthy status, and I'm not entirely sure why.  The entirety of my docker-compose.yml:

version: "2.1"
services:
  mongo:
    image: mongo
    volumes:
      - ./data/mongodb/db:/data/db
    ports:
      - "${DB_PORT}:${DB_PORT}"
    healthcheck:
      test: echo 'db.runCommand("ping").ok' | mongo mongo:27017/test --quiet 1
      interval: 10s
      timeout: 10s
      retries: 5
  collector:
    build: ./collector/
    environment:
      - DB_HOST=${DB_HOST}
      - DB_PORT=${DB_PORT}
      - DB_NAME=${DB_NAME}
    volumes:
      - ./collector/:/app
    depends_on:
      mongo:
        condition: service_healthy
  server:
    build: .
    environment:
      - SERVER_PORT=$SERVER_PORT
    volumes:
      - ./server/:/app
    ports:
      - "${SERVER_PORT}:${SERVER_PORT}"
    depends_on:
      mongo:
        condition: service_healthy

For the test, I've also tried:

["CMD", "nc", "-z", "localhost", "27017"]

And:

["CMD", "bash", "/mongo-healthcheck"]

I've also tried ditching the healthcheck altogether, following the advice of this guy.  Everything stands up, but I get the dreaded errors in the output before a successful connection:

collector_1  | MongoDB connection error: MongoNetworkError: failed to connect to server [mongo:27017] on first connect [MongoNetworkError: connect
ECONNREFUSED 172.21.0.2:27017]
collector_1  | MongoDB connection with retry
collector_1  | MongoDB connection error: MongoNetworkError: failed to connect to server [mongo:27017] on first connect

The ultimate goal is a clean startup output when running the docker-compose up --build.  I've also looked into some of the solutions in this question, but I haven't had much luck with wait-for-it either.  What's the correct way to wait for Mongo to be up and running before starting the other containers, and achieving a clean startup?

Body:
We can use MongoDB's serverStatus command to do the health check, as the MongoDB document puts it this way:

Monitoring applications can run this command at a regular interval to collect statistics about the instance.

Because this command serverStatus requires authentication, you need setup the health check similar to the configuration shown below:

version: '3.4'

services:
  mongo:
    image: mongo
    restart: always
    healthcheck:
      test: echo 'db.runCommand({serverStatus:1}).ok' | mongo admin -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD --quiet | grep 1
      interval: 10s
      timeout: 10s
      retries: 3
      start_period: 20s
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

That's it. If your MongoDB instance is healthy, you will see something similar to mine:

$ docker ps
CONTAINER ID  IMAGE  COMMAND                 CREATED         STATUS                   PORTS      NAMES
01ed0e02aa70  mongo  "docker-entrypoint.s…"  11 minutes ago  Up 11 minutes (healthy)  27017/tcp  demo_mongo_1


问:
AttributeError: 'list' object has no attribute 'find_element' while trying to crawl subway.co.kr
I have been trying to scrape subway store and create a table filled with addresses, names, and phone numbers. However, my code keeps giving error-filled results. Below is my code

```<code>import time
import requests
import csv
from selenium.webdriver.common.by   import By
from selenium.webdriver             import ActionChains
from bs4        import BeautifulSoup
from selenium   import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(5)
url1 = 'http://subway.co.kr/storeSearch?page='
url2 = '&rgn1Nm=&rgn2Nm=#storeList'

addresses = []
names = []
phones = []

for i in range(41):
    driver.get(url1 + str(i) + url2)
    lst = driver.find_elements_by_xpath('/html/body/div/div[2]/div[2]/div[3]/div/div/div[1]/table/tbody/tr')
    for row in lst:
        addresses.append(lst.find_element(By.XPATH, './td[2]/div/a').text)
        names.append(lst.find_element(By.XPATH, './td[1]/a').text)
        phones.append(lst.find_element(By.XPATH, './td[4]/div').text)

stores = [{
    'address'   : props[0],
    'name'      : props[1],
    'phone'     : props[2]
} for props in zip(addresses, names, phones)]

with open('stores.csv', 'w') as csvfile:
    csvout = csv.DictWriter(csvfile, ['address', 'name', 'phone'])
    csvout.writeheader()
    csvout.writerows(stores)
</code>```

so how do I access each elements(address, name, phone) in each row? I am also adding an image of a page of set of pages I am trying to crawl.

答:
You are calling find_element on the list object, I suspect you want to to use row instead, which are the elements you a looping over. Change

```<code>addresses.append(lst.find_element(
</code>```

to

```<code>addresses.append(row.find_element(
</code>```

And the same for names and phones

Body:
I have been trying to scrape subway store and create a table filled with addresses, names, and phone numbers. However, my code keeps giving error-filled results. Below is my code

import time
import requests
import csv
from selenium.webdriver.common.by   import By
from selenium.webdriver             import ActionChains
from bs4        import BeautifulSoup
from selenium   import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(5)
url1 = 'http://subway.co.kr/storeSearch?page='
url2 = '&rgn1Nm=&rgn2Nm=#storeList'

addresses = []
names = []
phones = []

for i in range(41):
    driver.get(url1 + str(i) + url2)
    lst = driver.find_elements_by_xpath('/html/body/div/div[2]/div[2]/div[3]/div/div/div[1]/table/tbody/tr')
    for row in lst:
        addresses.append(lst.find_element(By.XPATH, './td[2]/div/a').text)
        names.append(lst.find_element(By.XPATH, './td[1]/a').text)
        phones.append(lst.find_element(By.XPATH, './td[4]/div').text)

stores = [{
    'address'   : props[0],
    'name'      : props[1],
    'phone'     : props[2]
} for props in zip(addresses, names, phones)]

with open('stores.csv', 'w') as csvfile:
    csvout = csv.DictWriter(csvfile, ['address', 'name', 'phone'])
    csvout.writeheader()
    csvout.writerows(stores)

so how do I access each elements(address, name, phone) in each row? I am also adding an image of a page of set of pages I am trying to crawl.

Body:
You are calling find_element on the list object, I suspect you want to to use row instead, which are the elements you a looping over. Change

addresses.append(lst.find_element(

to

addresses.append(row.find_element(

And the same for names and phones


问:
Publish to Azure Service Bus using MassTransit is causing errors
I am new to both MassTransit and Azure Service Bus. I am attempting to use an architecture where either RabbitMq or Azure Service Bus is used in a .NET Core 3.1 API. I have the RabbitMq portion working and just started on the Azure Service Bus. I have an API that will take an incoming payload and publish it to a queue. When I attempt to publish via the Azure Service Bus approach, I get an error "SubCode=40000. Cannot operate on type Topic because the namespace 'servicehubqa' is using 'Basic' tier.

I am attempting to use a queue approach and am hoping to create the queue as messages are published. Currently, the service bus is using a Basic pricing tier as the documentation says that I can play with queues at that level. I am not sure if I need to manually create the queue (I had to do this approach using RabbitMq since no queue would be created if no consumer exists). Is topic the default approach if nothing is specified? How do I specify queue vs topic?

My code is as follows below.

Startup - ConfigureServices

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(Configuration);

        services.AddScoped<IMassTransitRabbitMqTransport, MassTransitRabbitMqTransport>();
        services.AddScoped<IMassTransitAzureServiceBusTransport, MassTransitAzureServiceBusTransport>();

        var messageProvider = ConfigProvider.GetConfig("MessageService", "Messaging_Service");
        switch (messageProvider)
        {
            case "AzureServiceBus":
                services.AddScoped<IMessagingService, MassTransitAzureServiceBusMessagingService>();
                break;
            case "RabbitMq":
                services.AddScoped<IMessagingService, MassTransitRabbitMqMessagingService>();
                break;
            default:
                throw new ArgumentException("Invalid message service");
        };

        services.AddControllers();
    }
</code>```

Controller

```<code>public class ListenerController : ControllerBase
{
    readonly ILogger<ListenerController> logger;
    readonly IMessagingService messenger;

    public ListenerController(
        ILogger<ListenerController> logger,
        IMessagingService messenger)
    {
        this.logger = logger;
        this.messenger = messenger;
    }

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        var payload = new
        {
            ...
        };

        await messenger.Publish(payload);

        return Ok();
    }
}
</code>```

IMessagingService

```<code>public interface IMessagingService
{
    Task Publish(object payload);
}
</code>```

IMassTransitTransport

```<code>public interface IMassTransitTransport
{
    IBusControl BusControl { get; }
}

public interface IMassTransitRabbitMqTransport : IMassTransitTransport { }

public interface IMassTransitAzureServiceBusTransport : IMassTransitTransport { }
</code>```

MassTransitAzureServiceBusTransport

```<code>public sealed class MassTransitAzureServiceBusTransport : IMassTransitAzureServiceBusTransport
{
    public IBusControl BusControl { get; }

    public MassTransitAzureServiceBusTransport()
    {
        BusControl = ConfigureBus();
        BusControl.StartAsync();
    }

    IBusControl ConfigureBus()
    {
        return Bus.Factory.CreateUsingAzureServiceBus(config => {
            var host = config.Host(ConfigProvider.GetConfig("AzureServiceBus", "AzureServiceBus_ConnStr"), host => { });
        });
    }
}
</code>```

MassTransitAzureServiceBusMessagingService

```<code>public class MassTransitAzureServiceBusMessagingService : IMessagingService
{
    readonly IMassTransitAzureServiceBusTransport massTransitTransport;

    public MassTransitAzureServiceBusMessagingService(IMassTransitAzureServiceBusTransport massTransitTransport)
    {
        //transport bus config already happens in massTransitTransport constructor
        this.massTransitTransport = massTransitTransport;
    }

    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                //IRegisterCommandUpdateStatus is an interface specifying the properties needed
                await massTransitTransport.BusControl.Publish<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }
}
</code>```

答:
The MassTransit documentation does state that if you want to use a Topic (i.e. the ability to publish to multiple subscriptions at the same time), you use the publish.
If you want to send a message to a queue (the message is routed to a specific location), you use the send and provide the correct information.

Topics require standard pricing and Queues can use basic pricing.

With this information, the MassTransitAzureServiceBusMessagingService would be modified as follows:

Basic Pricing - Queues

```<code>    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                var queueUri = new Uri(massTransitTransport.BusControl.Address, "registration.updatestatus");
                var endpoint = await massTransitTransport.BusControl.GetSendEndpoint(queueUri);
                await endpoint.Send<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }
</code>```

Standard Pricing - Topics/Subscriptions

```<code>    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                await massTransitTransport.BusControl.Publish<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }
</code>```

Body:
I am new to both MassTransit and Azure Service Bus. I am attempting to use an architecture where either RabbitMq or Azure Service Bus is used in a .NET Core 3.1 API. I have the RabbitMq portion working and just started on the Azure Service Bus. I have an API that will take an incoming payload and publish it to a queue. When I attempt to publish via the Azure Service Bus approach, I get an error "SubCode=40000. Cannot operate on type Topic because the namespace 'servicehubqa' is using 'Basic' tier.

I am attempting to use a queue approach and am hoping to create the queue as messages are published. Currently, the service bus is using a Basic pricing tier as the documentation says that I can play with queues at that level. I am not sure if I need to manually create the queue (I had to do this approach using RabbitMq since no queue would be created if no consumer exists). Is topic the default approach if nothing is specified? How do I specify queue vs topic?

My code is as follows below.

Startup - ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(Configuration);

        services.AddScoped<IMassTransitRabbitMqTransport, MassTransitRabbitMqTransport>();
        services.AddScoped<IMassTransitAzureServiceBusTransport, MassTransitAzureServiceBusTransport>();

        var messageProvider = ConfigProvider.GetConfig("MessageService", "Messaging_Service");
        switch (messageProvider)
        {
            case "AzureServiceBus":
                services.AddScoped<IMessagingService, MassTransitAzureServiceBusMessagingService>();
                break;
            case "RabbitMq":
                services.AddScoped<IMessagingService, MassTransitRabbitMqMessagingService>();
                break;
            default:
                throw new ArgumentException("Invalid message service");
        };

        services.AddControllers();
    }

Controller

public class ListenerController : ControllerBase
{
    readonly ILogger<ListenerController> logger;
    readonly IMessagingService messenger;

    public ListenerController(
        ILogger<ListenerController> logger,
        IMessagingService messenger)
    {
        this.logger = logger;
        this.messenger = messenger;
    }

    [HttpPost]
    public async Task<IActionResult> Post()
    {
        var payload = new
        {
            ...
        };

        await messenger.Publish(payload);

        return Ok();
    }
}

IMessagingService

public interface IMessagingService
{
    Task Publish(object payload);
}

IMassTransitTransport

public interface IMassTransitTransport
{
    IBusControl BusControl { get; }
}

public interface IMassTransitRabbitMqTransport : IMassTransitTransport { }

public interface IMassTransitAzureServiceBusTransport : IMassTransitTransport { }

MassTransitAzureServiceBusTransport

public sealed class MassTransitAzureServiceBusTransport : IMassTransitAzureServiceBusTransport
{
    public IBusControl BusControl { get; }

    public MassTransitAzureServiceBusTransport()
    {
        BusControl = ConfigureBus();
        BusControl.StartAsync();
    }

    IBusControl ConfigureBus()
    {
        return Bus.Factory.CreateUsingAzureServiceBus(config => {
            var host = config.Host(ConfigProvider.GetConfig("AzureServiceBus", "AzureServiceBus_ConnStr"), host => { });
        });
    }
}

MassTransitAzureServiceBusMessagingService

public class MassTransitAzureServiceBusMessagingService : IMessagingService
{
    readonly IMassTransitAzureServiceBusTransport massTransitTransport;

    public MassTransitAzureServiceBusMessagingService(IMassTransitAzureServiceBusTransport massTransitTransport)
    {
        //transport bus config already happens in massTransitTransport constructor
        this.massTransitTransport = massTransitTransport;
    }

    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                //IRegisterCommandUpdateStatus is an interface specifying the properties needed
                await massTransitTransport.BusControl.Publish<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }
}

Body:
The MassTransit documentation does state that if you want to use a Topic (i.e. the ability to publish to multiple subscriptions at the same time), you use the publish.
If you want to send a message to a queue (the message is routed to a specific location), you use the send and provide the correct information.

Topics require standard pricing and Queues can use basic pricing.

With this information, the MassTransitAzureServiceBusMessagingService would be modified as follows:

Basic Pricing - Queues

    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                var queueUri = new Uri(massTransitTransport.BusControl.Address, "registration.updatestatus");
                var endpoint = await massTransitTransport.BusControl.GetSendEndpoint(queueUri);
                await endpoint.Send<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }

Standard Pricing - Topics/Subscriptions

    public async Task Publish(object payload)
    {
        var jsn = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
        var cmd = JObject.Parse(jsn)["Command"];

        switch (cmd.ToString())
        {
            case "UPDATESTATUS":
                await massTransitTransport.BusControl.Publish<IRegisterCommandUpdateStatus>(payload);
                break;
            default: break;
        }
    }


问:
Unit Tests not discovered in Visual Studio 2017
I have been struggling with VS 2017 since I installed it. Now it seems Unit Tests will only run from the command line "dotnet test."

My project is .NET Core 1.1.1. I have the SDK and the framework update for 1.1.1 installed.

I have tried the sample at MSDN (https://msdn.microsoft.com/en-us/library/ms182532.aspx) which also fails exactly the same way.

All NuGet packages for the tests and the main project are current. And both the test project and the main project build without errors. An the tests run successfully from the command line.

Has anyone gotten Unit Tests to run in VS 2017, if so how?

Thanks,
John

Update - Extend

Here is an example of a simple test project that is not working on GitHub. This is an example with xUnit but I have tried NUnit and visual studio built in MS tests. No matter what testing or what changes I make I cannot get the VS test runner to find any tests.

What I've Tried

Deleting VS test cache files DEL %TEMP%\VisualStudioTestExplorerExtensions

Restarting VS

Closing/Opening test explorer

for xUnit installed Microsoft.DotNet.InternalAbstractions (see SO post)

for NUnit ensure adapter installed and same version (3) as NUnit package

test -> test settings -> default processor architecture is set to x86

The Question

Can anyone please provide a working example of a .Net Core 1.1.0 solution in VS2017 (.csproj project files) where the VS test explorer successfully finds the unit tests OR show me the issue in the example given.

答:
For me, I needed to run this, which updated all the nunit adapter links for the unit test projects:</p>
```<code>Install-Package Nunit3TestAdapter
</code>```

Body:
For me, I needed to run this, which updated all the nunit adapter links for the unit test projects:

Install-Package Nunit3TestAdapter


问:
Analyzing data in order of column and then row in R
I have a dataset of logged data at 5 minutes intervals that also includes data at 1 minute intervals denoted by _1 - _5 in the header.
Each row represents a 5 minute interval.

```<code>datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
20190710 09:00:00   21    13       14       26       29       32
20190710 09:05:00   21    28       28       29       38       12
20190710 09:10:00   20    8        15       29       30       19
20190711 11:12:00   18    6        9        18       51       49
20190711 11:17:00   17    49       48       48       30       10
</code>```

The actual dataset has an additional 25 columns of data logged at 5 minute intervals and consists of approximately 25000 rows.

I'm looking for an efficient way of analyzing the speed for each day.
For example, if I wanted to plot the speed for each day it would take speed_1 to speed_5 from the earliest entry on a particular day, say 09:00:00, then speed_1 to speed_5 from the next time, 09:05:00, and so on for the whole day.

Currently I have created an additional dataframe for the speed that fills in the times to give:

```<code>datetime            speed
20190710 09:00:00   13
20190710 09:01:00   14
20190710 09:02:00   26
20190710 09:03:00   29
20190710 09:04:00   32
</code>```

This results in having a second df of 125000 entries. I was wondering if there was a more memory efficient way of analyzing the original dataset as the datasets may grow considerably in the future.

Edit: Reproducible code added

structure(list(time = structure(1:3, .Label = c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00"), class = "factor"), temp = c(21, 21, 20), speed_1 = c(13, 28, 8), speed_2 = c(14, 28, 15), speed_3 = c(26, 29, 29), speed_4 = c(29, 38, 30), speed_5 = c(32, 12, 19)), .Names = c("time", "temp", "speed_1", "speed_2", "speed_3", "speed_4", "speed_5"), row.names = c(NA, -3L), class = "data.frame")

Body:
I have a dataset of logged data at 5 minutes intervals that also includes data at 1 minute intervals denoted by _1 - _5 in the header.
Each row represents a 5 minute interval.

datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
20190710 09:00:00   21    13       14       26       29       32
20190710 09:05:00   21    28       28       29       38       12
20190710 09:10:00   20    8        15       29       30       19
20190711 11:12:00   18    6        9        18       51       49
20190711 11:17:00   17    49       48       48       30       10

The actual dataset has an additional 25 columns of data logged at 5 minute intervals and consists of approximately 25000 rows.

I'm looking for an efficient way of analyzing the speed for each day.
For example, if I wanted to plot the speed for each day it would take speed_1 to speed_5 from the earliest entry on a particular day, say 09:00:00, then speed_1 to speed_5 from the next time, 09:05:00, and so on for the whole day.

Currently I have created an additional dataframe for the speed that fills in the times to give:

datetime            speed
20190710 09:00:00   13
20190710 09:01:00   14
20190710 09:02:00   26
20190710 09:03:00   29
20190710 09:04:00   32

This results in having a second df of 125000 entries. I was wondering if there was a more memory efficient way of analyzing the original dataset as the datasets may grow considerably in the future.

Edit: Reproducible code added

structure(list(time = structure(1:3, .Label = c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00"), class = "factor"), temp = c(21, 21, 20), speed_1 = c(13, 28, 8), speed_2 = c(14, 28, 15), speed_3 = c(26, 29, 29), speed_4 = c(29, 38, 30), speed_5 = c(32, 12, 19)), .Names = c("time", "temp", "speed_1", "speed_2", "speed_3", "speed_4", "speed_5"), row.names = c(NA, -3L), class = "data.frame")

Body:
Here is a dplyr version:

library(tidyverse)
library(lubridate)

df <- read.table(text='datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
"20190710 09:00:00"   21    13       14       26       29       32
"20190710 09:05:00"   21    28       28       29       38       12
"20190710 09:10:00"   20    8        15       29       30       19
"20190711 11:12:00"   18    6        9        18       51       49
"20190711 11:17:00"   17    49       48       48       30       10',header=T)

# we take our dataframe
df %>%
    # ...then we put all the speed columns in one column
    pivot_longer(starts_with("speed_")
                 , names_to = "minute"
                 , values_to = "speed") %>%
    # ...then we...
    mutate(datetime = ymd_hms(datetime) #...turn the "datetime" column actually into a datetime format
           , minute = gsub("speed_", "", minute) %>% as.numeric() # ...remove "speed_" from the former column names (which are now in column "speed")
           , datetime = datetime + minutes(minute - 1)) # ...and add the minute to our datetime...

...to get this:

# A tibble: 25 x 4
   datetime             temp minute speed
   <dttm>              <int>  <dbl> <int>
 1 2019-07-10 09:00:00    21      1    13
 2 2019-07-10 09:01:00    21      2    14
 3 2019-07-10 09:02:00    21      3    26
 4 2019-07-10 09:03:00    21      4    29
 5 2019-07-10 09:04:00    21      5    32
 6 2019-07-10 09:05:00    21      1    28
 7 2019-07-10 09:06:00    21      2    28
 8 2019-07-10 09:07:00    21      3    29
 9 2019-07-10 09:08:00    21      4    38
10 2019-07-10 09:09:00    21      5    12
# ... with 15 more rows


问:
Slow Performance Custom Script GAS
So, I've written (for lack of answers + improving my skills) a search script that would do basically what .indexOf does.

```<code>function search(ref, data) {

  var x
  var y
  var result = []

  if (data == '' || data == null) {
  } else {
    for (x = 0; x < data.length; x++) {
      if (data[x] == ref[0]) {                //achando match inicial
        var proto = [];
        for (y = 0; y < ref.length; y++) {
          if (data[x+y] == ref[y]) {          //gravando tentativas de match completo
          proto.push(data[x+y])
          }
        }
        var proto2 = proto.join('')
        if (proto2 == ref) {                   //testando match completo
            result.push(x)
        }
      }
    }
  }
  if (result == '' || result == null) {
  } else {
    return result[0]
  }
}
</code>```

It works fine within other little codes and custom functions that do not require too much looping, but when I wrote a more robust script I found that my code is roughly 3000x slower than the native .indeOf.

Why would I incur in such a difference?

答:
Issue:

Your function is comparing each character from ref separately with a data character, in an inner loop, pushing each character match inside an array (proto) and using join to transform the array back to a string (proto2), before comparing it to the original ref.

This is extremely inefficient and could be greatly simplified, so no question this function is much slower than String.prototype.indexOf().

Solution:

You could have a single loop instead, iterating through data, and for each iteration, retrieve a slice of data with the same length as ref, before comparing this slice with ref. If both values match, the string ref has been found in data, and the corresponding index is returned:

function searchString(ref, data) {
  for (let i = 0; i <= data.length - ref.length; i++) {
    if (ref === data.slice(i, i + ref.length)) return i;
  }
  return -1;
}
```

While using this function, I get similar execution times than with indexOf.

Reference:

String.prototype.indexOf()

String.prototype.slice()

Title: Slow Performance Custom Script GAS

Body:
So, I've written (for lack of answers + improving my skills) a search script that would do basically what .indexOf does.

function search(ref, data) {

  var x
  var y
  var result = []

  if (data == '' || data == null) {
  } else {
    for (x = 0; x < data.length; x++) {
      if (data[x] == ref[0]) {                //achando match inicial
        var proto = [];
        for (y = 0; y < ref.length; y++) {
          if (data[x+y] == ref[y]) {          //gravando tentativas de match completo
          proto.push(data[x+y])
          }
        }
        var proto2 = proto.join('')
        if (proto2 == ref) {                   //testando match completo
            result.push(x)
        }
      }
    }
  }
  if (result == '' || result == null) {
  } else {
    return result[0]
  }
}

It works fine within other little codes and custom functions that do not require too much looping, but when I wrote a more robust script I found that my code is roughly 3000x slower than the native .indeOf.

Why would I incur in such a difference?

Body:
Issue:

Your function is comparing each character from ref separately with a data character, in an inner loop, pushing each character match inside an array (proto) and using join to transform the array back to a string (proto2), before comparing it to the original ref.

This is extremely inefficient and could be greatly simplified, so no question this function is much slower than String.prototype.indexOf().

Solution:

You could have a single loop instead, iterating through data, and for each iteration, retrieve a slice of data with the same length as ref, before comparing this slice with ref. If both values match, the string ref has been found in data, and the corresponding index is returned:

function searchString(ref, data) {
  for (let i = 0; i <= data.length - ref.length; i++) {
    if (ref === data.slice(i, i + ref.length)) return i;
  }
  return -1;
}

While using this function, I get similar execution times than with indexOf.

Reference:

String.prototype.indexOf()

String.prototype.slice()


问:
How to remove the first character of a variable
HI All,

In my js file i am getting an array of records (negetive values ) like this

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });
</code>```

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

答:
Easy solution is multiply the values by -1 which make value + for you

example

```<code>var a = -12345 * -1;
   a = 12345;
</code>```

Body:
HI All,

In my js file i am getting an array of records (negetive values ) like this

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

Body:
Easy solution is multiply the values by -1 which make value + for you

example

var a = -12345 * -1;
   a = 12345;


问:
Variable Not In Scope for Lambda
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver].  I think that the clocks have not been configured or synced between the processor.  I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument.  I have made three changes.  I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out.  I'm building with gcc 4.8.5 on CentOS 7.5.

The code is as follows:

```<code>// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>

int main(int argc, const char** argv) {
  unsigned num_cpus = std::thread::hardware_concurrency();
  std::cout << "Launching " << num_cpus << " threads\n";

  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_cpus);
  for (unsigned i = 0; i < num_cpus; ++i)
  {
    threads[i] = std::thread([&iomutex, i]
    {
       // Simulate important work done by the tread by sleeping for a bit...
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      {
         std::chrono::time_point ti = std::chrono::system_clock::now();
         // Use a lexical scope and lock_guard to safely lock the mutex only for
         // the duration of std::cout usage.
         std::lock_guard<std::mutex> iolock(iomutex);
         std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
       }
    });
  }

  for (auto& t : threads) {
      t.join();
  }
  return 0;
}
</code>```

I build with make:

```<code>CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread

clock-check: clock-check.cpp
    $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
</code>```

GCC gives me the following error:

```<code>[user@sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
      std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
                                                               ^
make: *** [clock-check] Error 1
</code>```

ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining.  I have not found any restrictions on variables local to the lambda.  Most of what I have found has been references to captures.

答:
Class template deduction is not available until c++17, so you need to specify your template parameters for chrono::timepoint. Alternatively, use auto:

```<code> auto ti = std::chrono::system_clock::now();
</code>```

Furthermore, you attempt to stream a chrono::duration type, which is not possible. Use ti.time_since_epoch().count().

Live example

Title: Variable Not In Scope for Lambda

Body:
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver].  I think that the clocks have not been configured or synced between the processor.  I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument.  I have made three changes.  I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out.  I'm building with gcc 4.8.5 on CentOS 7.5.

The code is as follows:

// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>

int main(int argc, const char** argv) {
  unsigned num_cpus = std::thread::hardware_concurrency();
  std::cout << "Launching " << num_cpus << " threads\n";

  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_cpus);
  for (unsigned i = 0; i < num_cpus; ++i)
  {
    threads[i] = std::thread([&iomutex, i]
    {
       // Simulate important work done by the tread by sleeping for a bit...
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      {
         std::chrono::time_point ti = std::chrono::system_clock::now();
         // Use a lexical scope and lock_guard to safely lock the mutex only for
         // the duration of std::cout usage.
         std::lock_guard<std::mutex> iolock(iomutex);
         std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
       }
    });
  }

  for (auto& t : threads) {
      t.join();
  }
  return 0;
}

I build with make:

CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread

clock-check: clock-check.cpp
    $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)

GCC gives me the following error:

[user@sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
      std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
                                                               ^
make: *** [clock-check] Error 1

ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining.  I have not found any restrictions on variables local to the lambda.  Most of what I have found has been references to captures.

Body:
Class template deduction is not available until c++17, so you need to specify your template parameters for chrono::timepoint. Alternatively, use auto:

 auto ti = std::chrono::system_clock::now();

Furthermore, you attempt to stream a chrono::duration type, which is not possible. Use ti.time_since_epoch().count().

Live example