问:
array filter in python?
For example, I have two lists

```<code> A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements
</code>```

Is there a built-in function in python to do this?

答:
Yes, the filter function:

```<code>filter(lambda x: x not in subset_of_A, A)
</code>```

Title: array filter in python?

Body:
For example, I have two lists

 A           = [6, 7, 8, 9, 10, 11, 12]
subset_of_A  = [6, 9, 12]; # the subset of A

the result should be [7, 8, 10, 11]; the remaining elements

Is there a built-in function in python to do this?

Body:
Yes, the filter function:

filter(lambda x: x not in subset_of_A, A)


来源: stackexchange

问:
Insert Data Between Two Dates in Database using C#
I need help. We need to insert data between two dates in the database using C# on button click

For example, we have two calendars, Calendar1 & Calendar2.

Now from Calendar1, we choose date 01/12/2018

And from Calendar2, we choose date 30/12/2018

When we click the "Submit" button, we need to insert the data into the database

01/12/2018 to 30/12/2018

Ex.

```<code>01/12/2018
02/12/2018
03/12/2018
</code>```

答:
You can generate a table between two dates using recursive CTEs:

```<code>with dates as (
      select @startdate as dte
      union all
      select dateadd(day, 1, dte)
      from dates
      where dte < @enddate
     )
select *
from dates
option (maxrecursion 0);
</code>```

That said, if you need to do this for a user interface, then I think you really need a calendar table, with one row per date.  Then you can simply do:

```<code>select c.dte
from calendar c
where c.dte >= @startdate and c.dte <= @enddate;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need help. We need to insert data between two dates in the database using C# on button click

For example, we have two calendars, Calendar1 & Calendar2.

Now from Calendar1, we choose date 01/12/2018

And from Calendar2, we choose date 30/12/2018

When we click the "Submit" button, we need to insert the data into the database

01/12/2018 to 30/12/2018

Ex.

01/12/2018
02/12/2018
03/12/2018

Body:
You can generate a table between two dates using recursive CTEs:

with dates as (
      select @startdate as dte
      union all
      select dateadd(day, 1, dte)
      from dates
      where dte < @enddate
     )
select *
from dates
option (maxrecursion 0);

That said, if you need to do this for a user interface, then I think you really need a calendar table, with one row per date.  Then you can simply do:

select c.dte
from calendar c
where c.dte >= @startdate and c.dte <= @enddate;


问:
How to have text closer to image?
I've been fiddling around with Css and got to have my text and image be responsive on mobile. When I shrink my browser the image the text shrinks to show the image, but now my lorem ipsum text is pushed down. I'm not using padding or margin for this to happen, I'm trying to keep all of my text in a div but there seems to be alot of margin on text.

I've looked over my code and couldn't find anything that would cause this, and delete each segment of code to try and see if it fixes the problem. Nothing seems to work.

html:

```<code><body>

    <table >
    <tr>
        <td >Home</td> <!--Made 8 boxes, 100%/8boxes is 12.5, so to make them even just assign 12.5%-->
        <td >About Us</td> <!--Can see how CSS comes in handy...could just call td{width:12.5%; align:center;-->
        <td`enter code here` >Contact Us</td>
        <td >Menus</td>
        <td >Varieties</td>
        <td >Feedback</td>
        <td >SignUp</td>
        <td >Login</td>
    </tr>
    </table>

    <p id="mainWall"></p>
    <h1 class="mImageText">Paratore's Pizza</h1>

    <p>
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
    </p>

</body>
</html>

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    height: 75vh;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    top: 50%;
    transform: translateY(-175%);
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }
</code>```

I expect the text to come closer to the image instead of being all the way down requiring a scroll

答:
I am not sure about some of your rules. I have removed the following 2 rules - those are making the problem:

```<code>top: 50%;
transform: translateY(-175%);
</code>```

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>

    <table >
    <tr>
        <td >Home</td> <!--Made 8 boxes, 100%/8boxes is 12.5, so to make them even just assign 12.5%-->
        <td >About Us</td> <!--Can see how CSS comes in handy...could just call td{width:12.5%; align:center;-->
        <td>Contact Us</td>
        <td >Menus</td>
        <td >Varieties</td>
        <td >Feedback</td>
        <td >SignUp</td>
        <td >Login</td>
    </tr>
    </table>

    <p id="mainWall"></p>
    <h1 class="mImageText">Paratore's Pizza</h1>

    <p>
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
    </p>

</body>
</html></code>```

Title: How to have text closer to image?

Body:
I've been fiddling around with Css and got to have my text and image be responsive on mobile. When I shrink my browser the image the text shrinks to show the image, but now my lorem ipsum text is pushed down. I'm not using padding or margin for this to happen, I'm trying to keep all of my text in a div but there seems to be alot of margin on text.

I've looked over my code and couldn't find anything that would cause this, and delete each segment of code to try and see if it fixes the problem. Nothing seems to work.

html:

        Home
        About Us
        <td`enter code here` >Contact Us
        Menus
        Varieties
        Feedback
        SignUp
        Login

Paratore's Pizza

        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    height: 75vh;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    top: 50%;
    transform: translateY(-175%);
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }

I expect the text to come closer to the image instead of being all the way down requiring a scroll

Body:
I am not sure about some of your rules. I have removed the following 2 rules - those are making the problem:

top: 50%;
transform: translateY(-175%);

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }

<html>
<body>

    <table >
    <tr>
        <td >Home</td> <!--Made 8 boxes, 100%/8boxes is 12.5, so to make them even just assign 12.5%-->
        <td >About Us</td> <!--Can see how CSS comes in handy...could just call td{width:12.5%; align:center;-->
        <td>Contact Us</td>
        <td >Menus</td>
        <td >Varieties</td>
        <td >Feedback</td>
        <td >SignUp</td>
        <td >Login</td>
    </tr>
    </table>

    <p id="mainWall"></p>
    <h1 class="mImageText">Paratore's Pizza</h1>

    <p>
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
    </p>

</body>
</html>


问:
Java 8 int array to map
I want to convert int array to

```<code>Map<Integer,Integer>
</code>```

using Java 8 stream api

```<code>int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
                .stream(nums)
                .collect(Collectors.toMap(e->e,1));
</code>```

I want to get a map like below, key will be integer value, value will be total count of each key

map={2->3, 7->1, 11->2, 15->1}

compiler complains "no instance(s) of type variable(s) T, U exist so that Integer confirms to Function"

appreciate any pointers to resolve this

答:
You need to box the IntStream and then use groupingBy value to get the count:

```<code>Map<Integer, Long> map = Arrays
        .stream(nums)
        .boxed() // this
        .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
</code>```

or use reduce as:

```<code>Map<Integer, Integer> map = Arrays
        .stream(nums)
        .boxed()
        .collect(Collectors.groupingBy(e -> e,
                Collectors.reducing(0, e -> 1, Integer::sum)));
</code>```

Title: Java 8 int array to map

Body:
I want to convert int array to

Map<Integer,Integer>

using Java 8 stream api

int[] nums={2, 7, 11, 15, 2, 11, 2};
Map<Integer,Integer> map=Arrays
                .stream(nums)
                .collect(Collectors.toMap(e->e,1));

I want to get a map like below, key will be integer value, value will be total count of each key

map={2->3, 7->1, 11->2, 15->1}

compiler complains "no instance(s) of type variable(s) T, U exist so that Integer confirms to Function"

appreciate any pointers to resolve this

Body:
You need to box the IntStream and then use groupingBy value to get the count:

Map<Integer, Long> map = Arrays
        .stream(nums)
        .boxed() // this
        .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

or use reduce as:

Map<Integer, Integer> map = Arrays
        .stream(nums)
        .boxed()
        .collect(Collectors.groupingBy(e -> e,
                Collectors.reducing(0, e -> 1, Integer::sum)));


问:
Getting Can't bind to 'routerLink' since it isn't a known property of 'a'. error in spite of referencing router moudule
I am implementing basic routing in my angular 4 application and getting the following error when loading the application on the browser. I have defined the routes in approuting.module as also referenced the router module in Ngmodule as well approuting.module. Not sure what the problem is

```<code>Can't bind to 'routerLink' since it isn't a known property of 'a'.

Can't bind to 'routerLink' since it isn't a known property of 'a'. ("ew" [hidden]="!dataItem.isVisibleView">
                                                        <a [ERROR ->][routerLink]="['/view', dataItem.movieId, 'responses']" routerLinkActive="active"><i class="fa fa-fil"): ng:///MovieModule/MovieComponent.html@85:59
Can't bind to 'routerLink' since it isn't a known property of 'a'. ("it" [hidden]="!dataItem.isVisibleEdit">
                                                        <a [ERROR ->][routerLink]="['edit', dataItem.movieId]" routerLinkActive="active"><i class="fa fa-pencil" aria-hidd"): ng:///MovieModule/MovieComponent.html@92:59
</code>```

Below is the source code of my application

snippet of the kendo grid in movie.component.html

```<code>  </kendo-grid-column>
                                             <kendo-grid-column title="View" headerClass="kendoGridHeader" class="kendoGridControlCell">
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="View" [hidden]="!dataItem.isVisibleView">
                                                        <a [routerLink]="['/view', dataItem.movieId, 'responses']" routerLinkActive="active"><i class="fa fa-file-text" aria-hidden="true"></i></a>
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column title="Edit" headerClass="kendoGridHeader" class="kendoGridControlCell">
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="Edit" [hidden]="!dataItem.isVisibleEdit">
                                                        <a [routerLink]="['edit', dataItem.movieId]" routerLinkActive="active"><i class="fa fa-pencil" aria-hidden="true"></i></a>
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column title="Delete" headerClass="kendoGridHeader" class="kendoGridControlCell">
                                                <ng-template kendoGridCellTemplate let-dataItem>
                                                    <span data-title="Delete" [hidden]="!dataItem.isVisibleDelete">
                                                        <a data-toggle="dropdown" class="dropdown-toggle" href="">
                                                            <i class="fa fa-times" aria-hidden="true"></i>
                                                        </a>
                                                        <ul class="dropdown-menu table-popup-delete">
                                                            <li>Are you sure you want to delete this?</li>
                                                            <br>
                                                            <li><button class="button" (click)="deleteWorkflow(dataItem.movieId)" style="width:100%;">Delete</button></li>
                                                            <br>
                                                            <li><button class="button" style="width:100%;">Cancel</button></li>
                                                        </ul>
                                                    </span>
                                                </ng-template>
                                            </kendo-grid-column>
</code>```

approuting.module.ts

```<code>import {NgModule} from '@angular/core';
import {Routes,RouterModule} from '@angular/router';
import {MovieComponent} from './movie/movie.component';
import {HomeComponent}  from '../app/home/home.component';
import {NotFoundComponent} from './not-found/not-found.component';
import {NewmovieComponent} from './movie/new/newmovie.component';
import {EditmovieComponent} from './movie/edit/editmovie.component';
import {ViewmovieComponent} from './movie/view/viewmovie.component';

export const routes: Routes = [
{path : '', component : HomeComponent},
{path: 'movie', component : MovieComponent},
{path : 'new' , component : NewmovieComponent },
{path : 'edit' , component : EditmovieComponent },
{path : 'view' , component : ViewmovieComponent },
{path: '**',component : NotFoundComponent}

];

@NgModule({
     imports: [RouterModule.forRoot(routes,{useHash: true})],
     exports: [RouterModule]

})

export class AppRoutingModule{}
</code>```

app.module

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './approuting.module';
import {HomeModule} from './home/home.module';
import {MovieModule} from './movie/movie.module';
import { MRDBCommonService } from './shared/services/mrdb.common.service';
import { NotFoundComponent } from './not-found/not-found.component';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [
    AppComponent,
    FooterbarComponent,
    TopbarComponent,
    NavbarComponent,
    NotFoundComponent
  ],
  imports: [
    AppRoutingModule,
    HomeModule,
    MovieModule,
    BrowserModule,
    HttpModule,
    SharedModule

  ],
  providers: [MRDBGlobalConstants,
              MRDBCommonService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
Import RouterModule

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

```<code>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

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

import { LayoutComponent } from './layout/layout.component';

@NgModule({
  imports: [
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  declarations: [
    LayoutComponent
  ],
  exports: [
    FormsModule,
    ReactiveFormsModule,
  ],
  entryComponents: []
})
export class SharedModule { }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am implementing basic routing in my angular 4 application and getting the following error when loading the application on the browser. I have defined the routes in approuting.module as also referenced the router module in Ngmodule as well approuting.module. Not sure what the problem is

Can't bind to 'routerLink' since it isn't a known property of 'a'.

Can't bind to 'routerLink' since it isn't a known property of 'a'. ("ew" [hidden]="!dataItem.isVisibleView">
                                                        ][routerLink]="['/view', dataItem.movieId, 'responses']" routerLinkActive="active">
                                                        ][routerLink]="['edit', dataItem.movieId]" routerLinkActive="active"><i class="fa fa-pencil" aria-hidd"): ng:///MovieModule/MovieComponent.html@92:59

Below is the source code of my application

snippet of the kendo grid in movie.component.html

  </kendo-grid-column>
                                             <kendo-grid-column title="View" headerClass="kendoGridHeader" class="kendoGridControlCell">
                                                <ng-template kendoGridCellTemplate let-dataItem>

                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column title="Edit" headerClass="kendoGridHeader" class="kendoGridControlCell">
                                                <ng-template kendoGridCellTemplate let-dataItem>

                                                </ng-template>
                                            </kendo-grid-column>
                                            <kendo-grid-column title="Delete" headerClass="kendoGridHeader" class="kendoGridControlCell">
                                                <ng-template kendoGridCellTemplate let-dataItem>

Are you sure you want to delete this?

<button class="button" (click)="deleteWorkflow(dataItem.movieId)" style="width:100%;">Delete</button>

<button class="button" style="width:100%;">Cancel</button>

                                                </ng-template>
                                            </kendo-grid-column>

approuting.module.ts

import {NgModule} from '@angular/core';
import {Routes,RouterModule} from '@angular/router';
import {MovieComponent} from './movie/movie.component';
import {HomeComponent}  from '../app/home/home.component';
import {NotFoundComponent} from './not-found/not-found.component';
import {NewmovieComponent} from './movie/new/newmovie.component';
import {EditmovieComponent} from './movie/edit/editmovie.component';
import {ViewmovieComponent} from './movie/view/viewmovie.component';

export const routes: Routes = [
{path : '', component : HomeComponent},
{path: 'movie', component : MovieComponent},
{path : 'new' , component : NewmovieComponent },
{path : 'edit' , component : EditmovieComponent },
{path : 'view' , component : ViewmovieComponent },
{path: '**',component : NotFoundComponent}

];

@NgModule({
     imports: [RouterModule.forRoot(routes,{useHash: true})],
     exports: [RouterModule]

})

export class AppRoutingModule{}

app.module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/mrdb.global.constants';
import {AppRoutingModule} from './approuting.module';
import {HomeModule} from './home/home.module';
import {MovieModule} from './movie/movie.module';
import { MRDBCommonService } from './shared/services/mrdb.common.service';
import { NotFoundComponent } from './not-found/not-found.component';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [
    AppComponent,
    FooterbarComponent,
    TopbarComponent,
    NavbarComponent,
    NotFoundComponent
  ],
  imports: [
    AppRoutingModule,
    HomeModule,
    MovieModule,
    BrowserModule,
    HttpModule,
    SharedModule

  ],
  providers: [MRDBGlobalConstants,
              MRDBCommonService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
Import RouterModule

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

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

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

import { LayoutComponent } from './layout/layout.component';

@NgModule({
  imports: [
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  declarations: [
    LayoutComponent
  ],
  exports: [
    FormsModule,
    ReactiveFormsModule,
  ],
  entryComponents: []
})
export class SharedModule { }


问:
How to use intersect in a query?
I have 2 tables. I want to check the very last data inserted in the tables.
So, I want to retrieve the last data from both tables and then check if that last data from both tables are same or not.

```<code>$q1 =   "SELECT * ".
        "FROM `admin`, `student` ".
        "ORDER BY `admin`.`id` DESC  LIMIT 1 ".
        "INTERSECT".
        "SELECT *".
        "FROM `admin`, `student`".
        "WHERE `admin`.`pcode` = `student`.`code` AND
`admin`.`puser_name` = `student`.`puser_name`";
</code>```

I cannot use intersect operator so I am getting difficulty in changing in other form.

答:
Try this Query:

```<code>$q1 = "SELECT * FROM admin
WHERE admin.pcode = student.code
INTERSECT
SELECT *FROM student
WHERE admin.puser_name = student.puser_name
ORDER BY admin.id DESC  LIMIT 1";
</code>```

The INTERSECT operator compares the result of two queries and returns the distinct rows that are output by both left and right queries.

Title: How to use intersect in a query?

Body:
I have 2 tables. I want to check the very last data inserted in the tables.
So, I want to retrieve the last data from both tables and then check if that last data from both tables are same or not.

$q1 =   "SELECT * ".
        "FROM `admin`, `student` ".
        "ORDER BY `admin`.`id` DESC  LIMIT 1 ".
        "INTERSECT".
        "SELECT *".
        "FROM `admin`, `student`".
        "WHERE `admin`.`pcode` = `student`.`code` AND
`admin`.`puser_name` = `student`.`puser_name`";

I cannot use intersect operator so I am getting difficulty in changing in other form.

Body:
Try this Query:

$q1 = "SELECT * FROM admin
WHERE admin.pcode = student.code
INTERSECT
SELECT *FROM student
WHERE admin.puser_name = student.puser_name
ORDER BY admin.id DESC  LIMIT 1";

The INTERSECT operator compares the result of two queries and returns the distinct rows that are output by both left and right queries.


问:
Why I can not see two layers using pandas bokeh?
I am trying to use pandas_bokeh as suggested here

```<code>import geopandas as gpd
import pandas_bokeh
pandas_bokeh.output_notebook()

# Read in GeoJSONs from URL:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/states/states.geojson")
df_cities = gpd.read_file(
    r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/populated%20places/ne_10m_populated_places_simple_bigcities.geojson"
)
df_cities["size"] = df_cities.pop_max / 400000

#Plot shapes of US states (pass figure options to this initial plot):
figure = df_states.plot_bokeh(
    figsize=(800, 450),
    simplify_shapes=10000,
    show_figure=False,
    xlim=[-170, -80],
    ylim=[10, 70],
    category="REGION",
    colormap="Dark2",
    legend="States",
    show_colorbar=False,
)

#Plot cities as points on top of the US states layer by passing the figure:
df_cities.plot_bokeh(
    figure=figure,         # <== pass figure here!
    category="pop_max",
    colormap="Viridis",
    colormap_uselog=True,
    size="size",
    hovertool_string="""<h1>@name</h1>
                        <h3>Population: @pop_max </h3>""",
    marker="inverted_triangle",
    legend="Cities",
)
</code>```

However this my output where the layer State is not visible

答:
This is a known bug that started occurring with Bokeh 1.1 (https://github.com/PatrikHlobil/Pandas-Bokeh/issues/22). In the current development version the bug is fixed. You can install it using:

```<code>pip install git+https://github.com/PatrikHlobil/Pandas-Bokeh.git
</code>```

Hope this fixes your problem.

Body:
I am trying to use pandas_bokeh as suggested here

import geopandas as gpd
import pandas_bokeh
pandas_bokeh.output_notebook()

# Read in GeoJSONs from URL:
df_states = gpd.read_file(r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/states/states.geojson")
df_cities = gpd.read_file(
    r"https://raw.githubusercontent.com/PatrikHlobil/Pandas-Bokeh/master/Documentation/Testdata/populated%20places/ne_10m_populated_places_simple_bigcities.geojson"
)
df_cities["size"] = df_cities.pop_max / 400000

#Plot shapes of US states (pass figure options to this initial plot):
figure = df_states.plot_bokeh(
    figsize=(800, 450),
    simplify_shapes=10000,
    show_figure=False,
    xlim=[-170, -80],
    ylim=[10, 70],
    category="REGION",
    colormap="Dark2",
    legend="States",
    show_colorbar=False,
)

#Plot cities as points on top of the US states layer by passing the figure:
df_cities.plot_bokeh(
    figure=figure,         # <== pass figure here!
    category="pop_max",
    colormap="Viridis",
    colormap_uselog=True,
    size="size",
    hovertool_string="""
@name

Population: @pop_max
""",
    marker="inverted_triangle",
    legend="Cities",
)

However this my output where the layer State is not visible

Body:
This is a known bug that started occurring with Bokeh 1.1 (https://github.com/PatrikHlobil/Pandas-Bokeh/issues/22). In the current development version the bug is fixed. You can install it using:

pip install git+https://github.com/PatrikHlobil/Pandas-Bokeh.git

Hope this fixes your problem.


答:
Assuming your expected output doesn't intentionally skip a value as shown, the following will print groups of 34 elements in a single line:

```<code>wholeLines = len(integer) // 34 * 34
for i in range( 0,wholeLines,34 ):
    print(integer[i:i+34])
print( integer[wholeLines:] )
</code>```

If you do not need to print out the remaining portion of the final line then you can omit the last line of code.

Title: Is there another way to print multiple list elements where the list index increases by a given amount with each print?

Body:
I have a list containing hundreds of integers. I need to take 34 integers at a time, starting from the beginning of the list and print the integers in separate rows of 34.

The problem is that I have to use multiple print (list[x:y]) and continuously change the value for x and y.

I've tried specifying each index within the list to be printed, however, this is impractical since the list may contain hundreds of values.

integer = [
    3,23,12,34,2,4,7,11,14,1,9,17,12,1,0,5,4,3,2,4,8,1,12,15,18,17,14,23,12,0,0
    ,12,34,2,21,22,24,23,1,0,4,7,3,13,16,15,3,5,11,22,9,14,20,16,3,6,2,0,10,1,12
    ,18,9,9,23,6,2,18,14,1,0,3,5,17,13,12,5,6,9,0,1,2,19,20,2,3,5,7,15,19,2,4,10
    ,15,18,17,2,6,5,3,6,12,15,18,12,15,6,20,0,9,4,1,5,4,3,7,9,0,12,3,5,7,8,17,19
    ,21,0,1,2,7,7,7,5,4,3,8,19,12,16,0,2,4,7,8,4,12,12,9,3,20,2,21,3,5,8,9,12,17
    ,8,7,3,4,6,3,14,18,21,4,3,9,19,19,3,6,8,7,13,14,18,13,15,3,4,8,7,12
]

print (integer[0:34])
print (integer[35:69])
print (integer[70:104])

Output:

[3, 23, 12, 34, 2, 4, 7, 11, 14, 1, 9, 17, 12, 1, 0, 5, 4, 3, 2, 4, 8, 1, 12, 15, 18, 17, 14, 23, 12, 0, 0, 12, 34, 2]
[22, 24, 23, 1, 0, 4, 7, 3, 13, 16, 15, 3, 5, 11, 22, 9, 14, 20, 16, 3, 6, 2, 0, 10, 1, 12, 18, 9, 9, 23, 6, 2, 18, 14]
[0, 3, 5, 17, 13, 12, 5, 6, 9, 0, 1, 2, 19, 20, 2, 3, 5, 7, 15, 19, 2, 4, 10, 15, 18, 17, 2, 6, 5, 3, 6, 12, 15, 18]

Body:
Assuming your expected output doesn't intentionally skip a value as shown, the following will print groups of 34 elements in a single line:

wholeLines = len(integer) // 34 * 34
for i in range( 0,wholeLines,34 ):
    print(integer[i:i+34])
print( integer[wholeLines:] )

If you do not need to print out the remaining portion of the final line then you can omit the last line of code.


问:
Why does Angular show result from successfull http post request as "undefined"
I'm developing a MEAN stack app on Windows10 environment, using Mongoose (v4.4.5) to connect to MongoDB.  One of the http post requests in my code executes successfully and writes to MongoDB.  But the response returned from the post request shows up as "undefined" on the angular side (in the browser console).  This doesn't happen all the time though.  There are times when the response actually shows exactly what was written to MongoDB (which is what I'd expect to see all the time).  Code shown below:

Angular component code:

```<code>import { Component, OnInit, ViewChildren, Renderer2 } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { contactUsInterface } from '../../models/contact-us';
import { HttpClient } from '@angular/common/http';
import { ContactUsService } from '../../services/contact-us.service';
import { ErrorMessageService } from '../../services/error-message.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-contact-us',
  templateUrl: './contact-us.component.html',
  styleUrls: ['./contact-us.component.css'],
  })

export class ContactUsComponent implements OnInit {
  contactUsForm = new FormGroup({
    subject: new FormControl(''),
    message: new FormControl('', Validators.required),
    senderEmail: new FormControl('', [Validators.required, Validators.email]),
  });
  messageFromUser: contactUsInterface;
  response: any;
  successMessage = "Message successfully sent";
  displayMessage = this.successMessage;
  isVisible = "invisible"; //used for successMessage after on submitting form
  submitted = false;
  invalidControlArray = [];

  @ViewChildren("formControl") varInputBoxes;

  constructor(private renderer: Renderer2,
              private contactUsService: ContactUsService,
              private errorMessageService: ErrorMessageService) {}

  ngOnInit() {}

  onSubmit(){
    this.submitted = true;
    if(this.contactUsForm.valid){
      this.messageFromUser = {
        subject: this.contactUsForm.value['subject'],
        message: this.contactUsForm.value['message'],
        senderEmail: this.contactUsForm.value['senderEmail'],
      };
      this.saveMessage();
    }
  };

      saveMessage(){
        this.contactUsService.addMessage(this.messageFromUser)
        .subscribe((data: contactUsInterface) => {this.response = {...data},
                    error => this.displayMessage = this.errorMessageService.convertErrorToMessage(error, this.successMessage)});
//This is where the problem occurs.  "this.resopnse" below shows "undefined"
                    console.log('Response: ', this.response);
     };

  get message() { return this.contactUsForm.get('message'); }
  get senderEmail() { return this.contactUsForm.get('senderEmail'); }
}
</code>```

Angular service code which has the addMessage function called above by saveMessage():

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap, retry } from 'rxjs/operators';
import { contactUsInterface } from '../models/contact-us';

@Injectable({
  providedIn: 'root'
})

export class ContactUsService {
  private url = '/api/contactus';
  private result: any;
  message: string;

addMessage(messageFromUser: contactUsInterface): Observable<contactUsInterface> {
  return this.http.post<contactUsInterface>(this.url, messageFromUser)
  .pipe(retry(0));
};

constructor(private http: HttpClient) { }
};
</code>```

Express code which listens to the http request:

```<code>var express = require('express');
var router = express.Router();
var contactUsMessage = require('../models/contact_us_message');

  router.route('/')
    .get(function(req,res,next){
      res.send(req)
    })
    .post(function(req,res,next){
      contactUsMessage.create(
        req.body, function(err,result){
          if (err) {
            next(err);
          } else {
            res.send(result);
          }
        }
    )
  })

module.exports = router;
</code>```

I would have expected that when the express code writes to MongoDB (this part works) and returns "result", that result is what gets returned by addMessage (in the Angular service code) and is assigned to "response" in the Angular component.  But that's not how it appears to work.

答:
The link posted in comments by R. Richards provides the perfect explanation to my issue.  I modified my angular component code as follows (basically, by placing console.log inside the subscribe section) and it works as intended.  Still, if you have a similar issue, the chosen answer in the link provided by R. Richards is a must read.</p>

```<code>saveMessage(){
        this.contactUsService.addMessage(this.messageFromUser)
        .subscribe((data: contactUsInterface) => {this.response = {...data},
                    error => this.displayMessage = this.errorMessageService.convertErrorToMessage(error, this.successMessage);
                    console.log('Response: ', this.response);
     }
   )
 }
</code>```

Body:
I'm developing a MEAN stack app on Windows10 environment, using Mongoose (v4.4.5) to connect to MongoDB.  One of the http post requests in my code executes successfully and writes to MongoDB.  But the response returned from the post request shows up as "undefined" on the angular side (in the browser console).  This doesn't happen all the time though.  There are times when the response actually shows exactly what was written to MongoDB (which is what I'd expect to see all the time).  Code shown below:

Angular component code:

import { Component, OnInit, ViewChildren, Renderer2 } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { contactUsInterface } from '../../models/contact-us';
import { HttpClient } from '@angular/common/http';
import { ContactUsService } from '../../services/contact-us.service';
import { ErrorMessageService } from '../../services/error-message.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-contact-us',
  templateUrl: './contact-us.component.html',
  styleUrls: ['./contact-us.component.css'],
  })

export class ContactUsComponent implements OnInit {
  contactUsForm = new FormGroup({
    subject: new FormControl(''),
    message: new FormControl('', Validators.required),
    senderEmail: new FormControl('', [Validators.required, Validators.email]),
  });
  messageFromUser: contactUsInterface;
  response: any;
  successMessage = "Message successfully sent";
  displayMessage = this.successMessage;
  isVisible = "invisible"; //used for successMessage after on submitting form
  submitted = false;
  invalidControlArray = [];

  @ViewChildren("formControl") varInputBoxes;

  constructor(private renderer: Renderer2,
              private contactUsService: ContactUsService,
              private errorMessageService: ErrorMessageService) {}

  ngOnInit() {}

  onSubmit(){
    this.submitted = true;
    if(this.contactUsForm.valid){
      this.messageFromUser = {
        subject: this.contactUsForm.value['subject'],
        message: this.contactUsForm.value['message'],
        senderEmail: this.contactUsForm.value['senderEmail'],
      };
      this.saveMessage();
    }
  };

      saveMessage(){
        this.contactUsService.addMessage(this.messageFromUser)
        .subscribe((data: contactUsInterface) => {this.response = {...data},
                    error => this.displayMessage = this.errorMessageService.convertErrorToMessage(error, this.successMessage)});
//This is where the problem occurs.  "this.resopnse" below shows "undefined"
                    console.log('Response: ', this.response);
     };

  get message() { return this.contactUsForm.get('message'); }
  get senderEmail() { return this.contactUsForm.get('senderEmail'); }
}

Angular service code which has the addMessage function called above by saveMessage():

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap, retry } from 'rxjs/operators';
import { contactUsInterface } from '../models/contact-us';

@Injectable({
  providedIn: 'root'
})

export class ContactUsService {
  private url = '/api/contactus';
  private result: any;
  message: string;

addMessage(messageFromUser: contactUsInterface): Observable<contactUsInterface> {
  return this.http.post<contactUsInterface>(this.url, messageFromUser)
  .pipe(retry(0));
};

constructor(private http: HttpClient) { }
};

Express code which listens to the http request:

var express = require('express');
var router = express.Router();
var contactUsMessage = require('../models/contact_us_message');

  router.route('/')
    .get(function(req,res,next){
      res.send(req)
    })
    .post(function(req,res,next){
      contactUsMessage.create(
        req.body, function(err,result){
          if (err) {
            next(err);
          } else {
            res.send(result);
          }
        }
    )
  })

module.exports = router;

I would have expected that when the express code writes to MongoDB (this part works) and returns "result", that result is what gets returned by addMessage (in the Angular service code) and is assigned to "response" in the Angular component.  But that's not how it appears to work.

Body:
The link posted in comments by R. Richards provides the perfect explanation to my issue.  I modified my angular component code as follows (basically, by placing console.log inside the subscribe section) and it works as intended.  Still, if you have a similar issue, the chosen answer in the link provided by R. Richards is a must read.

saveMessage(){
        this.contactUsService.addMessage(this.messageFromUser)
        .subscribe((data: contactUsInterface) => {this.response = {...data},
                    error => this.displayMessage = this.errorMessageService.convertErrorToMessage(error, this.successMessage);
                    console.log('Response: ', this.response);
     }
   )
 }


问:
Regexp_like working on a debugger website but not working on Oracle SQL Developer
I'm at work for a trigger which provide a "domain" for column Molteplicità in a table called Partecipa using a function.

The trigger I've created is the following:

```<code>CREATE OR REPLACE TRIGGER dominioMolteplicità
BEFORE INSERT OR UPDATE ON partecipa
FOR EACH ROW
BEGIN
    IF moltepl_valido(:NEW.molteplicità) = 'f' THEN
        RAISE_APPLICATION_ERROR(-20002, 'Invalid type');
    END IF;
END;
</code>```

which uses the following function:

```<code>CREATE OR REPLACE FUNCTION moltepl_valido(mol VARCHAR2) RETURN CHAR IS
BEGIN
    IF regexp_like(LOWER(mol), '[\d]+\.\.[\*]|[\d]|[\*]') THEN
        RETURN 't';
    ELSE
        RETURN 'f';
    END IF;
END;
</code>```

Table Partecipa has the following columns:

```<code>CodP INT,
molteplicità VARCHAR2,
codAss INT,
className VARCHAR2,
PRIMARY KEY (codP),
FOREIGN KEY (className) REFERENCES class(name),
FOREIGN KEY (codAss) REFERENCES associazione(cod)
</code>```

When I execute the following statement

```<code>insert into Partecipa(molteplicità, className, codAss)
values ('2', 'Impiegato', 42);
</code>```

my trigger says "Invalid type" (function return false, but it should insert)

I get these errors:

ORA-20002 INVALID TYPE

ORA-06512: AT "dominioMolteplicità", line 3

ORA-04088: ERROR DURING EXECUTION OF TRIGGER "dominioMolteplicità"

More over
When I execute the following statement

```<code>insert into Partecipa(molteplicità, className, codAss)
values ('*..*', 'Impiegato', 42);
</code>```

it inserts properly (but it should not according to link

Relevant Edit:

I want my trigger to enforce the following values for column Molteplicità:

accept (only these cases):

```<code>'n..m' (where n>=0, m > 0 and n<m)
'*' (where * is literally the character *)
'n..*' (where n>=0 and * is literally the character *)
'n' (where n>0)
</code>```

do not accept:

```<code>'*..*' (where * is any character)
'*..n' (where * is literally the character * and for any value of n)
'n..m' (where n>=0, m > 0 and n>=m)
</code>```

答:
This works for the latest set of rules posted. Given that you want to validate the actual values of numbers when they're posted it is not possible to do this in a single regex expression (at least as far as I know):

```<code>CREATE OR REPLACE FUNCTION moltepl_valido(mol VARCHAR2) RETURN CHAR IS
BEGIN
    IF regexp_like(mol, '\d+\.\.\d+$')
        and to_number(regexp_substr(mol,'\d+', 1, 2)) > to_number(regexp_substr(mol,'\d+', 1, 1)) then
        RETURN 't';
    ELSIF regexp_like(mol, '^\d+$')
        and to_number(regexp_substr(mol,'\d+')) > 0 then
        RETURN 't';
    ELSIF regexp_like(LOWER(mol), '(^\d+)\.\.\*$|^\*$') THEN
        RETURN 't';
    ELSE
        RETURN 'f';
    END IF;
END;
/
</code>```

This accepts the following values of molteplicità ...

2..*

23..*

0..*

2

*

2..3

0..3

23..32

23

... and rejects ...

2..A

*..*

A..B

3..2

2..2

If these are not the rules you want to enforce please edit your question to include a complete set of requirements.

There is a demo on db<>fiddle.

Body:
I'm at work for a trigger which provide a "domain" for column Molteplicità in a table called Partecipa using a function.

The trigger I've created is the following:

CREATE OR REPLACE TRIGGER dominioMolteplicità
BEFORE INSERT OR UPDATE ON partecipa
FOR EACH ROW
BEGIN
    IF moltepl_valido(:NEW.molteplicità) = 'f' THEN
        RAISE_APPLICATION_ERROR(-20002, 'Invalid type');
    END IF;
END;

which uses the following function:

CREATE OR REPLACE FUNCTION moltepl_valido(mol VARCHAR2) RETURN CHAR IS
BEGIN
    IF regexp_like(LOWER(mol), '[\d]+\.\.[\*]|[\d]|[\*]') THEN
        RETURN 't';
    ELSE
        RETURN 'f';
    END IF;
END;

Table Partecipa has the following columns:

CodP INT,
molteplicità VARCHAR2,
codAss INT,
className VARCHAR2,
PRIMARY KEY (codP),
FOREIGN KEY (className) REFERENCES class(name),
FOREIGN KEY (codAss) REFERENCES associazione(cod)

When I execute the following statement

insert into Partecipa(molteplicità, className, codAss)
values ('2', 'Impiegato', 42);

my trigger says "Invalid type" (function return false, but it should insert)

I get these errors:

ORA-20002 INVALID TYPE

ORA-06512: AT "dominioMolteplicità", line 3

ORA-04088: ERROR DURING EXECUTION OF TRIGGER "dominioMolteplicità"

More over
When I execute the following statement

insert into Partecipa(molteplicità, className, codAss)
values ('*..*', 'Impiegato', 42);

it inserts properly (but it should not according to link

Relevant Edit:

I want my trigger to enforce the following values for column Molteplicità:

accept (only these cases):

'n..m' (where n>=0, m > 0 and n<m)
'*' (where * is literally the character *)
'n..*' (where n>=0 and * is literally the character *)
'n' (where n>0)

do not accept:

'*..*' (where * is any character)
'*..n' (where * is literally the character * and for any value of n)
'n..m' (where n>=0, m > 0 and n>=m)

Body:
This works for the latest set of rules posted. Given that you want to validate the actual values of numbers when they're posted it is not possible to do this in a single regex expression (at least as far as I know):

CREATE OR REPLACE FUNCTION moltepl_valido(mol VARCHAR2) RETURN CHAR IS
BEGIN
    IF regexp_like(mol, '\d+\.\.\d+$')
        and to_number(regexp_substr(mol,'\d+', 1, 2)) > to_number(regexp_substr(mol,'\d+', 1, 1)) then
        RETURN 't';
    ELSIF regexp_like(mol, '^\d+$')
        and to_number(regexp_substr(mol,'\d+')) > 0 then
        RETURN 't';
    ELSIF regexp_like(LOWER(mol), '(^\d+)\.\.\*$|^\*$') THEN
        RETURN 't';
    ELSE
        RETURN 'f';
    END IF;
END;
/

This accepts the following values of molteplicità ...

2..*

23..*

0..*

2

*

2..3

0..3

23..32

23

... and rejects ...

2..A

*..*

A..B

3..2

2..2

If these are not the rules you want to enforce please edit your question to include a complete set of requirements.

There is a demo on db<>fiddle.


答:
If you are just looking for an easy way to print chunks of size chunk_size of a list, use the following one-line list comprehension:

[print(data[chunk_size * index : chunk_size * index + chunk_size]) for index in range((len(data) // chunk_size) + 1)]

Change chunk_size to represent however large you would like your chunks to be.

Example:

In[2]: x = list(range(35))
In[3]: x
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]
In[4]: chunk_size = 9
In[5]: [print(x[chunk_size * index : chunk_size * index + chunk_size]) for index in range((len(x) // chunk_size) + 1)]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[9, 10, 11, 12, 13, 14, 15, 16, 17]
[18, 19, 20, 21, 22, 23, 24, 25, 26]
[27, 28, 29, 30, 31, 32, 33, 34]
```


问:
How to use Typescript Async/ await with promise in Node JS FS Module
How to use Typescript async / await function and return typescript default promises in node js FS module and call other function upon promise resolved.

Following is the code :

```<code>  if (value) {
     tempValue = value;
     fs.writeFile(FILE_TOKEN, value, WriteTokenFileResult);
            }

 function WriteTokenFileResult(err: any, data: any) {
        if (err) {
            console.log(err);
            return false;
        }
        TOKEN = tempValue;
        ReadGist(); // other FS read File call
    };
</code>```

答:
Since NodeJS 10.0.0 fsPromises module can be used to achieve this result. </p>

```<code>import { promises as fsPromises } from 'fs';
await fsPromises.writeFile('file.txt', 'data')
</code>```

Body:
How to use Typescript async / await function and return typescript default promises in node js FS module and call other function upon promise resolved.

Following is the code :

  if (value) {
     tempValue = value;
     fs.writeFile(FILE_TOKEN, value, WriteTokenFileResult);
            }

 function WriteTokenFileResult(err: any, data: any) {
        if (err) {
            console.log(err);
            return false;
        }
        TOKEN = tempValue;
        ReadGist(); // other FS read File call
    };

Body:
Since NodeJS 10.0.0 fsPromises module can be used to achieve this result.

import { promises as fsPromises } from 'fs';
await fsPromises.writeFile('file.txt', 'data')


问:
Docker: Jenkins-jdk11 fails to connect to Nexus due to JAXB-API has not been found
Get the following error while trying to connect jenkins-jdk11 to nexus3 containers running same network in docker-compose on JDK8 based host system. Afer clicking "Test Connection"

The error:

```<code>Nexus Repository Manager 3.x connection failed
javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:421)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
    at com.sonatype.nexus.api.zz.ex.a(SourceFile:33)
    at com.sonatype.nexus.api.zz.ex.b(SourceFile:24)
    at com.sonatype.nexus.api.zz.ez.handleResponse(SourceFile:54)
    at org.apache.http.impl.client.CloseableHttpClient.execute(SourceFile:223)
    at org.apache.http.impl.client.CloseableHttpClient.execute(SourceFile:165)
    at com.sonatype.nexus.api.zz.et.a(SourceFile:84)
    at com.sonatype.nexus.api.zz.es.getVersion(SourceFile:126)
    at com.sonatype.nexus.api.repository.v3.RepositoryManagerV3Client$getVersion.call(Unknown Source)
</code>```

docker-compose.yml

```<code>version: "3"
services:
  jenkins-jdk11:
    user: root
    image: 'jenkins/jenkins:jdk11'
    ports:
      - '10000:8080'
      - '50000:50000'
    environment:
      - TZ=Europe/Warsaw
      - "JAVA_OPTS=-Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory"
    links:
      - nexus3
    volumes:
      - 'jenkins-data:/var/jenkins_home'
      - '/var/run/docker.sock:/var/run/docker.sock'
    deploy:
      restart_policy:
         condition: on-failure
    networks:
      - backend
  nexus3:
    container_name: nexus3
    image: 'sonatype/nexus3'
    ports:
      - '50001:8081'
    volumes:
      - 'local-nexus-data-volume:/nexus-data'
    networks:
      - backend
volumes:
  jenkins-data:
    driver: local
  local-nexus-data-volume:
    driver: local
networks:
  backend:
    driver: overlay
</code>```

What seems to be the problem and how to successfully connect to Nexus?

EDIT
My JAXB plugin installed:

答:
It is an issue listed on Jenkins wiki for Jenkins compatability issues with Java 11. Here is the link.

One possible solution is to add -Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory in the JAVA_OPTS while running Jenkins. You can do this by passing env variables to container using --env option :

```<code>--env JAVA_OPTS=-Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory
</code>```

Or in docker compose using environment :

```<code>services:
  jenkins:
    image: 'jenkins/jenkins:jdk11'
    environment:
     - JAVA_OPTS=-Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory
</code>```

Body:
Get the following error while trying to connect jenkins-jdk11 to nexus3 containers running same network in docker-compose on JDK8 based host system. Afer clicking "Test Connection"

The error:

Nexus Repository Manager 3.x connection failed
javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:421)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
    at com.sonatype.nexus.api.zz.ex.a(SourceFile:33)
    at com.sonatype.nexus.api.zz.ex.b(SourceFile:24)
    at com.sonatype.nexus.api.zz.ez.handleResponse(SourceFile:54)
    at org.apache.http.impl.client.CloseableHttpClient.execute(SourceFile:223)
    at org.apache.http.impl.client.CloseableHttpClient.execute(SourceFile:165)
    at com.sonatype.nexus.api.zz.et.a(SourceFile:84)
    at com.sonatype.nexus.api.zz.es.getVersion(SourceFile:126)
    at com.sonatype.nexus.api.repository.v3.RepositoryManagerV3Client$getVersion.call(Unknown Source)

docker-compose.yml

version: "3"
services:
  jenkins-jdk11:
    user: root
    image: 'jenkins/jenkins:jdk11'
    ports:
      - '10000:8080'
      - '50000:50000'
    environment:
      - TZ=Europe/Warsaw
      - "JAVA_OPTS=-Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory"
    links:
      - nexus3
    volumes:
      - 'jenkins-data:/var/jenkins_home'
      - '/var/run/docker.sock:/var/run/docker.sock'
    deploy:
      restart_policy:
         condition: on-failure
    networks:
      - backend
  nexus3:
    container_name: nexus3
    image: 'sonatype/nexus3'
    ports:
      - '50001:8081'
    volumes:
      - 'local-nexus-data-volume:/nexus-data'
    networks:
      - backend
volumes:
  jenkins-data:
    driver: local
  local-nexus-data-volume:
    driver: local
networks:
  backend:
    driver: overlay

What seems to be the problem and how to successfully connect to Nexus?

EDIT
My JAXB plugin installed:

Body:
It is an issue listed on Jenkins wiki for Jenkins compatability issues with Java 11. Here is the link.

One possible solution is to add -Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory in the JAVA_OPTS while running Jenkins. You can do this by passing env variables to container using --env option :

--env JAVA_OPTS=-Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory

Or in docker compose using environment :

services:
  jenkins:
    image: 'jenkins/jenkins:jdk11'
    environment:
     - JAVA_OPTS=-Djavax.xml.bind.JAXBContextFactory=com.sun.xml.bind.v2.ContextFactory


问:
Error: Could not build Objective-C module 'Firebase'
When I compile the application I get an error equal to this:

Could not build Objective-C module 'Firebase'

This error appear in import Firebase of my file swift.

答:
I opened the project with .xcodeproj and I installed Firebase with cocoapods. I got the same error. But I just close the project and open it with .xcworkspace.

The alert has gone. Firebase was the first library on my project. So I kept using .xcodeproj file.


问:
UITableView Cell should not scroll horizontally swift iOS
I have a table view which has card kind of cells as shown in picture.
I have set the content Inset so that I can get the cells with 20px spacing in left,right and top.

    tableVw.contentInset = UIEdgeInsets(top: 20, left: 20, bottom: 0, right: 20)

Its displaying as I expected but the problem is, cells can be moved in all direction. But when I move it to right/top, it automatically comes back to original position. But when I move to left it just goes inside and don't scroll back to original position as shown in picture.

I don't want the cells to move at all or I want the cells to come back to centre if its dragged anywhere also. Please help!

答:
If you're using AutoLayout, by setting this only should work for you:

In code:

```<code>tableView.alwaysBounceVertical = false
</code>```

or In Interface Builder:
Just find this option and untick "Bounce Vertically" option.

Here's the reference:

If you're not using AutoLayout:

```<code>override func viewDidLayoutSubviews() {
    // Enable scrolling based on content height
    tableView.isScrollEnabled = tableView.contentSize.height > tableView.frame.size.height
 }
</code>```

and also try clipToBounds

```<code>tableview.clipsToBounds = true
</code>```

Body:
If you're using AutoLayout, by setting this only should work for you:

In code:

tableView.alwaysBounceVertical = false

or In Interface Builder:
Just find this option and untick "Bounce Vertically" option.

Here's the reference:

If you're not using AutoLayout:

override func viewDidLayoutSubviews() {
    // Enable scrolling based on content height
    tableView.isScrollEnabled = tableView.contentSize.height > tableView.frame.size.height
 }

and also try clipToBounds

tableview.clipsToBounds = true


问:
difference between variables inside and outside of __init__() (class and instance attributes)
Is there any difference at all between these classes besides the name?

```<code>class WithClass ():
    def __init__(self):
        self.value = "Bob"
    def my_func(self):
        print(self.value)

class WithoutClass ():
    value = "Bob"

    def my_func(self):
        print(self.value)
</code>```

Does it make any difference if I use or don't use the __init__ method  for declaring the variable value?

My main worry is that I'll be using it one way, when that'll cause me further problems down the road.

答:
This is very easy to understand if you track class and instance dictionaries.

```<code>class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)
</code>```

The result will be like this:

```<code>{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}
</code>```

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.

Body:
Is there any difference at all between these classes besides the name?

class WithClass ():
    def __init__(self):
        self.value = "Bob"
    def my_func(self):
        print(self.value)

class WithoutClass ():
    value = "Bob"

    def my_func(self):
        print(self.value)

Does it make any difference if I use or don't use the __init__ method  for declaring the variable value?

My main worry is that I'll be using it one way, when that'll cause me further problems down the road.

Body:
This is very easy to understand if you track class and instance dictionaries.

class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)

The result will be like this:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.


问:
React-native dismiss Keyboard when focus out / clicked somewhere else, outside textfield
I'm new to react-native. I have a textfield(Input). I want to the Keyboard to be dismissed when user clicks somewhere else except input field.
I tried several solutions suggested here like TouchableWithoudFeedback, but they did not work.
Also, the point which is not clear to me, I can use any function inside onFocus, on the other hand, nothing worked in onBlur or onEndEditing
Here is my code of Input component.

<InputGroup borderType='rounded' style={styles.inputGrp}>
                                    <Input placeholder={'Password'} secureTextEntry={true} style={styles.input}
                                           onChangeText={(pin1) => this.setState({pin1: pin1})}
                                           value={this.state.pin1}
                                           maxLength={8}
                                    />
```

答:
here is the solution to that above question: Hide keyboard in react native

```<code>import {Keyboard, TouchableWithoutFeedback} from 'react-native'
</code>```

wrap your root component with TouchableWithoutFeedback and trigger Keyboard.dismiss at onPress, like following

```<code><TouchableWithoutFeedback onPress={Keyboard.dismiss}>
    <View style={{flex: 1}}>
          ........
          //rest of the component
          ........
    </View>
</TouchableWithoutFeedback>
</code>```

Body:
here is the solution to that above question: Hide keyboard in react native

import {Keyboard, TouchableWithoutFeedback} from 'react-native'

wrap your root component with TouchableWithoutFeedback and trigger Keyboard.dismiss at onPress, like following

<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
    <View style={{flex: 1}}>
          ........
          //rest of the component
          ........
    </View>
</TouchableWithoutFeedback>


问:
How to make a splitscreen with a listview on one side
I want the right side of the activity to show different items depending which item of the listview on the left is selected. I was able to follow the Android ListView example where the listview  takes up the whole activity screen, but was unable to expand that to split screen. Here is my xml with the list view on the left and a simple button on the right for now. I'm having trouble figuring out the code that will populate my listview.

system_status.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/activity_system_status"
       android:title="@string/system_status"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="horizontal">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">

        <ListView
        android:id="@+id/my_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        </ListView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </LinearLayout>
    </LinearLayout>
</code>```

UPDATE:
I figured it out with the help of Scythe's post. Here is the code that got it working. The xml above works as is.

```<code>public class SystemStatusActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView lv = (ListView) findViewById(R.id.my_list);
    String[] stats = getResources().getStringArray(R.array.array_system_status);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stats));
}
}
</code>```

list_item.xml:

```<code>     <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>
</code>```

答:
From http://www.anddev.org/view-layout-resource-problems-f27/two-listviews-side-by-side-t11199.html

Pretty much just need to wrap what you have in a LinearLayout with android:orientation="horizonal".

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              >
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  >
        <ListView android:id="@+id/list"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:entries="@array/colors"
                  />
    </LinearLayout>
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  >
        <TextView android:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:text="Hello World, AndroidTest"
                  />
    </LinearLayout>
</LinearLayout>
</code>```

Body:
I want the right side of the activity to show different items depending which item of the listview on the left is selected. I was able to follow the Android ListView example where the listview  takes up the whole activity screen, but was unable to expand that to split screen. Here is my xml with the list view on the left and a simple button on the right for now. I'm having trouble figuring out the code that will populate my listview.

system_status.xml:

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/activity_system_status"
       android:title="@string/system_status"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="horizontal">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">

        <ListView
        android:id="@+id/my_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        </ListView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </LinearLayout>
    </LinearLayout>

UPDATE:
I figured it out with the help of Scythe's post. Here is the code that got it working. The xml above works as is.

public class SystemStatusActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView lv = (ListView) findViewById(R.id.my_list);
    String[] stats = getResources().getStringArray(R.array.array_system_status);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stats));
}
}

list_item.xml:

     <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

Body:
From http://www.anddev.org/view-layout-resource-problems-f27/two-listviews-side-by-side-t11199.html

Pretty much just need to wrap what you have in a LinearLayout with android:orientation="horizonal".

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              >
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  >
        <ListView android:id="@+id/list"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:entries="@array/colors"
                  />
    </LinearLayout>
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  >
        <TextView android:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:text="Hello World, AndroidTest"
                  />
    </LinearLayout>
</LinearLayout>


问:
How can I populate a tableView having embedded collectionViews in its rows and organize them by type or category?
I have an event/venue management app & a view receives data for events in json format where each event has a category or type. How do I populate & organize events in collectionViews embedded in TableView cells where each TableView Cell is a category or type to display. Answers in Swift if possible

答:
populate your tableview using JSON with categories and in cellForRowAt method pass single  category to collectionView (your tableview cell class is holding collectionView property) reload collectionView using

```<code>cell.singleCategory = categories[indexPath.row]
cell.collectionView.reloadData()
</code>```

Place your collectionView outlet and delegate in tableView Cell class and create property that holds single category data pass the  category data to that tableView Cell class and in cellForItemAt populate  single category data

Example:

```<code>class MyTeamTVC: UITableViewCell {

    @IBOutlet weak var collectionView: UICollectionView!
        var singleCategory = [Category]()
override func awakeFromNib() {

        collectionView.register(UINib(nibName: "cell", bundle: nil), forCellWithReuseIdentifier: "cell")

    }
    }

extension MyTeamTVC: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return category.types.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? StatsCVC else {return UICollectionViewCell()}

        cell.nameLabel.text = singleCategory.types[indexPath.row]
        return cell
    }

}
</code>```

Body:
populate your tableview using JSON with categories and in cellForRowAt method pass single  category to collectionView (your tableview cell class is holding collectionView property) reload collectionView using

cell.singleCategory = categories[indexPath.row]
cell.collectionView.reloadData()

Place your collectionView outlet and delegate in tableView Cell class and create property that holds single category data pass the  category data to that tableView Cell class and in cellForItemAt populate  single category data

Example:

class MyTeamTVC: UITableViewCell {

    @IBOutlet weak var collectionView: UICollectionView!
        var singleCategory = [Category]()
override func awakeFromNib() {

        collectionView.register(UINib(nibName: "cell", bundle: nil), forCellWithReuseIdentifier: "cell")

    }
    }

extension MyTeamTVC: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return category.types.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? StatsCVC else {return UICollectionViewCell()}

        cell.nameLabel.text = singleCategory.types[indexPath.row]
        return cell
    }

}


问:
Recursively reverse linked list
I am having hard time understanding how this recursive code works, I have made drawings and run the code through gdb.

```<code>void RecursiveReverse(struct node** headRef)
{
  struct node* first;
  struct node* rest;

  if (*headRef == NULL) return; // empty list base case

  first = *headRef; // suppose first = {1, 2, 3}
  rest = first->next; // rest = {2, 3}

  if (rest == NULL) return; // empty rest base case

  RecursiveReverse(&rest); // Recursively reverse the smaller {2, 3} case
                           // after: rest = {3, 2}

  first->next->next = first; // put the first element on the end of the list
  first->next = NULL;

  *headRef = rest; // fix the head pointer
}
</code>```

I understand that while the recursion call stack is being built up and once the list contains only {3}, empty rest base case if (rest == NULL) is true for the first time.

After this, the recursion call stack starts to break and hits first->next->next = first; for the first time, with {2, 3},

Before this line is executed, output in gdb:

```<code>(gdb)p *first
{data = 2, next = 0x1003001f0}

(gdb) p *rest
{data = 3, next = 0x0}
</code>```

After this line is executed,

```<code>(gdb) p *rest
{data = 3, next = 0x1003000a0}
</code>```

Continuing with code execution to hit first->next->next = first;, the second time:

```<code>(gdb) p **head_ref
{data = 1, next = 0x1003000a0}

(gdb) p *rest
{data = 3, next = 0x1003000a0} // expected p *rest to be 2
</code>```

Here I expected that the local pointer rest should point to node 2, because while building up recursion call stack, **headRef pointed to node 1 and after line rest = first->next;, got executed rest pointed to node 2.

After *headRef = rest;, is executed, shouldn't headRef point to node 2?

How come that local state is lost and rest points to node 3?

答:
Here is simplified pseudo code. It basically work like this:

```<code>RecursiveReverse(head):
    if head is empty:
        return
    RecursiveReverse(head->next)

    // When we come here, the whole list except the first
    // element has been reversed. So all that's left to do
    // is to reverse the final step

    head->next->next = head
    head->next = NULL
</code>```

The most important thing to realize here is that AFTER the recursive call, the whole list EXCEPT the first element has been reversed.

Title: Recursively reverse linked list

Body:
I am having hard time understanding how this recursive code works, I have made drawings and run the code through gdb.

void RecursiveReverse(struct node** headRef)
{
  struct node* first;
  struct node* rest;

  if (*headRef == NULL) return; // empty list base case

  first = *headRef; // suppose first = {1, 2, 3}
  rest = first->next; // rest = {2, 3}

  if (rest == NULL) return; // empty rest base case

  RecursiveReverse(&rest); // Recursively reverse the smaller {2, 3} case
                           // after: rest = {3, 2}

  first->next->next = first; // put the first element on the end of the list
  first->next = NULL;

  *headRef = rest; // fix the head pointer
}

I understand that while the recursion call stack is being built up and once the list contains only {3}, empty rest base case if (rest == NULL) is true for the first time.

After this, the recursion call stack starts to break and hits first->next->next = first; for the first time, with {2, 3},

Before this line is executed, output in gdb:

(gdb)p *first
{data = 2, next = 0x1003001f0}

(gdb) p *rest
{data = 3, next = 0x0}

After this line is executed,

(gdb) p *rest
{data = 3, next = 0x1003000a0}

Continuing with code execution to hit first->next->next = first;, the second time:

(gdb) p **head_ref
{data = 1, next = 0x1003000a0}

(gdb) p *rest
{data = 3, next = 0x1003000a0} // expected p *rest to be 2

Here I expected that the local pointer rest should point to node 2, because while building up recursion call stack, **headRef pointed to node 1 and after line rest = first->next;, got executed rest pointed to node 2.

After *headRef = rest;, is executed, shouldn't headRef point to node 2?

How come that local state is lost and rest points to node 3?

Body:
Here is simplified pseudo code. It basically work like this:

RecursiveReverse(head):
    if head is empty:
        return
    RecursiveReverse(head->next)

    // When we come here, the whole list except the first
    // element has been reversed. So all that's left to do
    // is to reverse the final step

    head->next->next = head
    head->next = NULL

The most important thing to realize here is that AFTER the recursive call, the whole list EXCEPT the first element has been reversed.


问:
What's the Java equivalent of .net's GC.KeepAlive?
.NET has a function called GC.KeepAlive(Object). Its sole purpose is to ensure the lifetime of the referenced object lasts until code flow reaches the call.

This is normally not necessary unless one is interoperating with native code.

I have a situation where I've got a graph of C++ objects accessed via JNI, where certain root objects need to be kept alive to keep the children alive. Both the root objects and the child objects have mirrors in JVM land. If the root object is collected and freed on the C++ side (by way of a SWIG-generated finalizer), however, the child objects will become invalid, since their C++ backing object will have been freed.

This can be solved by ensuring the local variables that root the object graph have a lifetime that exceeds the last use of a child object. So I need an idiomatic function that does nothing to an object, yet won't be optimized away or moved (e.g. hoisted out of a loop). That's what GC.KeepAlive(Object) does in .NET.

What is the approximate equivalent in Java?

PS: some possibly illustrative code:

```<code>class Parent {
    long ptr;
    void finalize() { free(ptr); }
    Child getChild() { return new Child(expensive_operation(ptr)); }
}

class Child {
    long ptr;
    void doStuff() { do_stuff(ptr); }
}

// BAD CODE with potential for SIGSEGV
for (Parent p : getParents()) {
    p.getChild().doStuff();
}
</code>```

The trouble is that the GC freeing Parent p will free the memory allocated for Child while doStuff is executing. GC has been observed to do this in practice. A potential fix if GC.KeepAlive was available:

```<code>// BAD CODE with potential for SIGSEGV
for (Parent p : getParents()) {
    p.getChild().doStuff();
    GC.KeepAlive(p);
}
</code>```

I could e.g. call toString on p, but I won't be doing anything with its output. I could poke p into an array temporarily, but how do I know the JVM won't discard the store? Etc.

答: Whenever the garbage collector is aggressive enough to claim the object while invoking a native method, and also in Java world little people seem to care to the point that either the problem doesn't exist or there's a lot bugged code around, this other SO answer seems to provide a reasonable alternative to use GC.KeepAlive(Object), that is by using non-static native JNI methods, reasonably preventing any possible garbage collection of the instance invoking these methods.

Body:
.NET has a function called GC.KeepAlive(Object). Its sole purpose is to ensure the lifetime of the referenced object lasts until code flow reaches the call.

This is normally not necessary unless one is interoperating with native code.

I have a situation where I've got a graph of C++ objects accessed via JNI, where certain root objects need to be kept alive to keep the children alive. Both the root objects and the child objects have mirrors in JVM land. If the root object is collected and freed on the C++ side (by way of a SWIG-generated finalizer), however, the child objects will become invalid, since their C++ backing object will have been freed.

This can be solved by ensuring the local variables that root the object graph have a lifetime that exceeds the last use of a child object. So I need an idiomatic function that does nothing to an object, yet won't be optimized away or moved (e.g. hoisted out of a loop). That's what GC.KeepAlive(Object) does in .NET.

What is the approximate equivalent in Java?

PS: some possibly illustrative code:

class Parent {
    long ptr;
    void finalize() { free(ptr); }
    Child getChild() { return new Child(expensive_operation(ptr)); }
}

class Child {
    long ptr;
    void doStuff() { do_stuff(ptr); }
}

// BAD CODE with potential for SIGSEGV
for (Parent p : getParents()) {
    p.getChild().doStuff();
}

The trouble is that the GC freeing Parent p will free the memory allocated for Child while doStuff is executing. GC has been observed to do this in practice. A potential fix if GC.KeepAlive was available:

// BAD CODE with potential for SIGSEGV
for (Parent p : getParents()) {
    p.getChild().doStuff();
    GC.KeepAlive(p);
}

I could e.g. call toString on p, but I won't be doing anything with its output. I could poke p into an array temporarily, but how do I know the JVM won't discard the store? Etc.


问:
Abuse report for an email message from amazonses.com
I'm an AWS SES user.

I'm getting emails from complaints@email-abuse.amazonses.com
with this message:

This is an email abuse report for an email message from amazonses.com

Based on this Why do I receive messages from complaints@email-abuse.amazonses.com?

I know that

When you receive such an email, you should verify that the complaining recipient is not included in your future email sends.  This will ensure that you have happy email recipients and fall under the good graces of Amazon SES.

Now, my question - what can I do to reverse this action? What if customer did it by mistake, or he did not think it through.

My business is selling coupons online, sometimes with subscription.
Now what if someone make my email as a spam? I need to notify this person that his email address will never be used for future emails and I need to offer people an option to resubscribe to our service if they did it by mistake.

1) What can I recommend them todo? What is the procedure for a customer to unmark my email address as SPAM?

2) How can I deliver this message if I'm not allowed to email?

3) Does it mean that only one email address of mine was blacklisted or whole domain?

Thanks

答:
What it says is someone whom you sent an email marked your email as spam, if you want to see who was that, you need to enable SNS notification for Complaint , SNS will tell you which recipient was it and you can remove it from the email list which you use to send emails.

1) What can I recommend them todo? What is the procedure for a customer to unmark my email address as SPAM?
This isn't in your control, you need to make sure your emails don't look like generic spam or marketing email. e.g: keep unsubscribe link so user can unsubscribe instead of marking it as spam.

2) How can I deliver this message if I'm not allowed to email?
You're still allowed to send emails but probably the email will end up in recipient junk box.

3) Does it mean that only one email address of mine was blacklisted or whole domain?
This is for only for one recipient mailbox but you need to control the complaint rate because if not the recipient, AWS can suspend your account if complaint rate goes high.


问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答:
How about using the T4 templating engine?

http://visualstudiomagazine.com/articles/2009/05/01/visual-studios-t4-code-generation.aspx

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.


答:
I'm not sure I understood what you want to do. If a new player registers, a new member is created?

But if number of member is fix you should take the second option. A database is made for search in and do some request. However, a loop in any language (ie PHP) is slow.

I hope it will helps,
Best regards !

Title: more columns or one array, what is better performance?

Body:
I want to make a game(minecraft) region database and player's permissions.

and these are my table ideas.

example1)

Column ---------------- Datatype

worldname ------------ 1 ----- (INT(10)) ----- PK , NN

regionname ----------- 1 ----- (INT(10)) ----- PK , NN

owner ------------------- 2 ----- (INT(10))

member ---------------- 5, 13, 54, 246, 38295, 564, 2535, 5364, 411, 9 ----- (VARCHAR(128))

this one and I receive 'member' and split by ', ' to array.

example2)

Column ---------------- Datatype

worldname ------------ 1 ----- (INT(10)) ----- PK , NN

regionname ----------- 1 ----- (INT(10)) ----- PK , NN

owner ------------------- 2 ----- (INT(10)

member1 -------------- 5 ----- (INT(10))

member2 -------------- 13 ----- (INT(10))

member3 -------------- 54 ----- (INT(10))

member4 -------------- 246 ----- (INT(10))

member5 -------------- 38295 ----- (INT(10))

member6 -------------- 564 ----- (INT(10))

member7 -------------- 2535 ----- (INT(10))

member8 -------------- 5364 ----- (INT(10))

member9 -------------- 411 ----- (INT(10))

member10 ------------- 9 ----- (INT(10))

which one is better performance?