问:
dplyr change many data types
I have a data.frame:

```<code>dat <- data.frame(fac1 = c(1, 2),
                  fac2 = c(4, 5),
                  fac3 = c(7, 8),
                  dbl1 = c('1', '2'),
                  dbl2 = c('4', '5'),
                  dbl3 = c('6', '7')
                  )
</code>```

To change data types I can use something like

```<code>l1 <- c("fac1", "fac2", "fac3")
l2 <- c("dbl1", "dbl2", "dbl3")
dat[, l1] <- lapply(dat[, l1], factor)
dat[, l2] <- lapply(dat[, l2], as.numeric)
</code>```

with dplyr

```<code>dat <- dat %>% mutate(
    fac1 = factor(fac1), fac2 = factor(fac2), fac3 = factor(fac3),
    dbl1 = as.numeric(dbl1), dbl2 = as.numeric(dbl2), dbl3 = as.numeric(dbl3)
)
</code>```

is there a more elegant (shorter) way in dplyr?

thx
Christof

答:
For future readers, if you are ok with dplyr guessing the column types, you can convert the col types of an entire df as if you were originally reading it in with readr and col_guess() with

```<code>library(tidyverse)
df %>% type_convert()
</code>```

Title: dplyr change many data types

Body:
I have a data.frame:

dat <- data.frame(fac1 = c(1, 2),
                  fac2 = c(4, 5),
                  fac3 = c(7, 8),
                  dbl1 = c('1', '2'),
                  dbl2 = c('4', '5'),
                  dbl3 = c('6', '7')
                  )

To change data types I can use something like

l1 <- c("fac1", "fac2", "fac3")
l2 <- c("dbl1", "dbl2", "dbl3")
dat[, l1] <- lapply(dat[, l1], factor)
dat[, l2] <- lapply(dat[, l2], as.numeric)

with dplyr

dat <- dat %>% mutate(
    fac1 = factor(fac1), fac2 = factor(fac2), fac3 = factor(fac3),
    dbl1 = as.numeric(dbl1), dbl2 = as.numeric(dbl2), dbl3 = as.numeric(dbl3)
)

is there a more elegant (shorter) way in dplyr?

thx
Christof

Body:
For future readers, if you are ok with dplyr guessing the column types, you can convert the col types of an entire df as if you were originally reading it in with readr and col_guess() with

library(tidyverse)
df %>% type_convert()


来源: stackexchange

问:
Laravel eloquent with() nested relationship fields in parent unnested
the elequent query i have is:

```<code>$rows = ProjectLogin::with(
    'User:PRIVATE,naam',
    'Project:PRIVATE,naam',
    'Queue:PRIVATE,queue_naam',
    'AgentStatus:PRIVATE,status'
)
->limit(10)->get();
</code>```

this will return this array if i do $rows->toArray():

```<code>array:10 [▼
  0 => array:18 [▶]
  1 => array:18 [▼
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "user" => array:2 [▼
      "PRIVATE" => PRIVATE
      "naam" => "SOME NAME"
    ]
    "project" => array:2 [▼
      "PRIVATE" => PRIVATE
      "naam" => "SOME PROJECT NAME"
    ]
    "queue" => null
    "agent_status" => array:2 [▼
      "PRIVATE" => PRIVATE
      "status" => "SOME STATUS"
    ]
  ]
  2 => array:18 [▶]
  3 => array:18 [▶]
  4 => array:18 [▶]
  5 => array:18 [▶]
  6 => array:18 [▶]
  7 => array:18 [▶]
  8 => array:18 [▶]
  9 => array:18 [▶]
]
</code>```

the withs are in a array, but i dont want nested arrays, plus it contains the foreign keys which i dont need.

i want the array to look like for example:

```<code>array:10 [▼
  0 => array:18 [▶]
  1 => array:18 [▼
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "user_naam" => 'SOME NAME'
    "project_naam" => 'SOME NAME'
    "agent_status_status" => 'SOME STATUS'

  ]
  2 => array:18 [▶]
  3 => array:18 [▶]
  4 => array:18 [▶]
  5 => array:18 [▶]
  6 => array:18 [▶]
  7 => array:18 [▶]
  8 => array:18 [▶]
  9 => array:18 [▶]
]
</code>```

How can i get specifics columns from a query that uses with() in the main array instead of nested arrays?

答:
To answer the question "How can i get specifics columns from a query that uses with()?"

Try writing with()  with a callback function like this:

```<code>$rows = ProjectLogin::with( 'User:PRIVATE,naam', function($query){
    $query->select('column_name');
})
->with( 'Project:PRIVATE,naam', function($query){
    $query->select('column_name');
})
->with( 'Queue:PRIVATE,queue_naam', function($query){
    $query->select('column_name');
})
-> with( 'AgentStatus:PRIVATE,status', function($query){
    $query->select('column_name');
})
</code>```

Notice how i separated the with() into different lines, this is because when you pass a callback function to the function it can only take one parameter.

On the issue of the array format, I'm not sure this will work, but try putting them into a collection and flatten that collection to give you the desired state.

```<code>$flattened = $collection->flaten()
</code>```

The variable $collection holding your eloquent collection results.

ContentLicense: CC BY-SA 4.0

Body:
the elequent query i have is:

$rows = ProjectLogin::with(
    'User:PRIVATE,naam',
    'Project:PRIVATE,naam',
    'Queue:PRIVATE,queue_naam',
    'AgentStatus:PRIVATE,status'
)
->limit(10)->get();

this will return this array if i do $rows->toArray():

array:10 [▼
  0 => array:18 [▶]
  1 => array:18 [▼
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "user" => array:2 [▼
      "PRIVATE" => PRIVATE
      "naam" => "SOME NAME"
    ]
    "project" => array:2 [▼
      "PRIVATE" => PRIVATE
      "naam" => "SOME PROJECT NAME"
    ]
    "queue" => null
    "agent_status" => array:2 [▼
      "PRIVATE" => PRIVATE
      "status" => "SOME STATUS"
    ]
  ]
  2 => array:18 [▶]
  3 => array:18 [▶]
  4 => array:18 [▶]
  5 => array:18 [▶]
  6 => array:18 [▶]
  7 => array:18 [▶]
  8 => array:18 [▶]
  9 => array:18 [▶]
]

the withs are in a array, but i dont want nested arrays, plus it contains the foreign keys which i dont need.

i want the array to look like for example:

array:10 [▼
  0 => array:18 [▶]
  1 => array:18 [▼
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => "PRIVATE"
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "PRIVATE" => PRIVATE
    "user_naam" => 'SOME NAME'
    "project_naam" => 'SOME NAME'
    "agent_status_status" => 'SOME STATUS'

  ]
  2 => array:18 [▶]
  3 => array:18 [▶]
  4 => array:18 [▶]
  5 => array:18 [▶]
  6 => array:18 [▶]
  7 => array:18 [▶]
  8 => array:18 [▶]
  9 => array:18 [▶]
]

How can i get specifics columns from a query that uses with() in the main array instead of nested arrays?

Body:
To answer the question "How can i get specifics columns from a query that uses with()?"

Try writing with()  with a callback function like this:

$rows = ProjectLogin::with( 'User:PRIVATE,naam', function($query){
    $query->select('column_name');
})
->with( 'Project:PRIVATE,naam', function($query){
    $query->select('column_name');
})
->with( 'Queue:PRIVATE,queue_naam', function($query){
    $query->select('column_name');
})
-> with( 'AgentStatus:PRIVATE,status', function($query){
    $query->select('column_name');
})

Notice how i separated the with() into different lines, this is because when you pass a callback function to the function it can only take one parameter.

On the issue of the array format, I'm not sure this will work, but try putting them into a collection and flatten that collection to give you the desired state.

$flattened = $collection->flaten()

The variable $collection holding your eloquent collection results.


问:
flutter remove left side gap from CarouselSlider
I am using CarouselSlider to slide my containers but issue is its showing lot of padding on the left side.

My code

```<code>class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    double statusbar = MediaQuery.of(context).padding.top;

    final DateTime now = DateTime.now();
    final DateFormat formatter = DateFormat('E, MMM d, y');
    final String formatted = formatter.format(now);
    print(formatted); // something like 2013-04-20

    return Scaffold(
      backgroundColor: Color(0xFF612c58),
      body: Column(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(40), bottomRight: Radius.circular(40)),
            child: Container(
              color: Colors.white,
              height: height * 0.52,
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: statusbar * 2,
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 30, right: 30),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          'Popular',
                          style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold),
                        ),
                        Text("$formatted")
                      ],
                    ),
                  ),
                  CarouselSlider(
                    options: CarouselOptions(height: height * 0.39,
                      enableInfiniteScroll: false,

                    ),
                    items: [0, 1, 2, 3, 4].map((i) {
                      return Builder(
                        builder: (BuildContext context) {
                          return _popular(i);
                        },
                      );
                    }).toList(),
                  ),

                  Container(
                    height: height * 0.006,
                    width: width * 0.1,
                    color: Colors.grey,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: height * 0.02,),
          Container(
            padding: EdgeInsets.only(left: 20),
              width: double.infinity,child: Text('Recent Stories', style: TextStyle(color: Colors.white, fontSize: 21, fontWeight: FontWeight.bold),))
        ],
      ),
    );
  }

  Widget _popular(int index) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    double statusbar = MediaQuery.of(context).padding.top;

    return Container(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: height * 0.02,),
        ClipRRect(
          borderRadius: BorderRadius.circular(70.0),

          child: Container(
            height: height * 0.25,
            width: width * 0.7,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                  'assets/images/1.png',
                ),
              ),
            ),
          ),
        ),
        SizedBox(height: height * 0.01,),
        Container(
          padding: EdgeInsets.only(left: 15),
            width: double.infinity,
            child: Text(
              'Amazing lesson Story',
              style: TextStyle(fontWeight: FontWeight.bold),
            )),
        SizedBox(height: height * 0.01,),
        Container(
            padding: EdgeInsets.only(left: 15),
            width: double.infinity,
            child: Text(
              'Post By Marco - 10 min',
            )),

      ],
    ));
  }
}
</code>```

As you can see its showing gap on left side i need to remove this and need to set padding between the slides. I also check the documentation but there is no option showing for padding or i maybe its have any option but i am not able to find it. Can any one please tell how can i just remove the padding and add gap between sldies Thanks :)

答:
One option could be adding alignment to the container that wraps your child in the itemBuilder :

```<code>      @override
  Widget build(BuildContext context) {
    return CarouselSlider.builder(
      carouselController: carouselController,
      options: CarouselOptions(
        disableCenter: false,
        viewportFraction: 0.8,
        enlargeCenterPage: false,
        height: getProportionateScreenHeight(defaultCarouselHeight),
        enableInfiniteScroll: false,
        initialPage: 0,
        onPageChanged: onPageChanged,
        enlargeStrategy: CenterPageEnlargeStrategy.height,
      ),
      itemCount: model.topNewsList.length,
      itemBuilder: (context, index, realindex) => Container(
        alignment: const Alignment(-1.5, -1.0),
        child: CarouselCell(
          news: model.topNewsList[index],
          onNewsPress: () => Get.to(
            () => DetailScreen(),
            arguments: model.topNewsList[index],
          ),
        ),
      ),
    );
  }
</code>```

as you see, I added the alignment to -1,5 for the left - right, and -1 for the top - bottom, according to this explanation : https://youtu.be/g2E7yl3MwMk

I know this is not the cleanest way to do that, so if anybody else finds another solution, that would be helpful for all :)

Body:
I am using CarouselSlider to slide my containers but issue is its showing lot of padding on the left side.

My code

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    double statusbar = MediaQuery.of(context).padding.top;

    final DateTime now = DateTime.now();
    final DateFormat formatter = DateFormat('E, MMM d, y');
    final String formatted = formatter.format(now);
    print(formatted); // something like 2013-04-20

    return Scaffold(
      backgroundColor: Color(0xFF612c58),
      body: Column(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(40), bottomRight: Radius.circular(40)),
            child: Container(
              color: Colors.white,
              height: height * 0.52,
              child: Column(
                children: <Widget>[
                  SizedBox(
                    height: statusbar * 2,
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 30, right: 30),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          'Popular',
                          style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold),
                        ),
                        Text("$formatted")
                      ],
                    ),
                  ),
                  CarouselSlider(
                    options: CarouselOptions(height: height * 0.39,
                      enableInfiniteScroll: false,

                    ),
                    items: [0, 1, 2, 3, 4].map((i) {
                      return Builder(
                        builder: (BuildContext context) {
                          return _popular(i);
                        },
                      );
                    }).toList(),
                  ),

                  Container(
                    height: height * 0.006,
                    width: width * 0.1,
                    color: Colors.grey,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: height * 0.02,),
          Container(
            padding: EdgeInsets.only(left: 20),
              width: double.infinity,child: Text('Recent Stories', style: TextStyle(color: Colors.white, fontSize: 21, fontWeight: FontWeight.bold),))
        ],
      ),
    );
  }

  Widget _popular(int index) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    double statusbar = MediaQuery.of(context).padding.top;

    return Container(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: height * 0.02,),
        ClipRRect(
          borderRadius: BorderRadius.circular(70.0),

          child: Container(
            height: height * 0.25,
            width: width * 0.7,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                  'assets/images/1.png',
                ),
              ),
            ),
          ),
        ),
        SizedBox(height: height * 0.01,),
        Container(
          padding: EdgeInsets.only(left: 15),
            width: double.infinity,
            child: Text(
              'Amazing lesson Story',
              style: TextStyle(fontWeight: FontWeight.bold),
            )),
        SizedBox(height: height * 0.01,),
        Container(
            padding: EdgeInsets.only(left: 15),
            width: double.infinity,
            child: Text(
              'Post By Marco - 10 min',
            )),

      ],
    ));
  }
}

As you can see its showing gap on left side i need to remove this and need to set padding between the slides. I also check the documentation but there is no option showing for padding or i maybe its have any option but i am not able to find it. Can any one please tell how can i just remove the padding and add gap between sldies Thanks :)

Body:
One option could be adding alignment to the container that wraps your child in the itemBuilder :

      @override
  Widget build(BuildContext context) {
    return CarouselSlider.builder(
      carouselController: carouselController,
      options: CarouselOptions(
        disableCenter: false,
        viewportFraction: 0.8,
        enlargeCenterPage: false,
        height: getProportionateScreenHeight(defaultCarouselHeight),
        enableInfiniteScroll: false,
        initialPage: 0,
        onPageChanged: onPageChanged,
        enlargeStrategy: CenterPageEnlargeStrategy.height,
      ),
      itemCount: model.topNewsList.length,
      itemBuilder: (context, index, realindex) => Container(
        alignment: const Alignment(-1.5, -1.0),
        child: CarouselCell(
          news: model.topNewsList[index],
          onNewsPress: () => Get.to(
            () => DetailScreen(),
            arguments: model.topNewsList[index],
          ),
        ),
      ),
    );
  }

as you see, I added the alignment to -1,5 for the left - right, and -1 for the top - bottom, according to this explanation : https://youtu.be/g2E7yl3MwMk

I know this is not the cleanest way to do that, so if anybody else finds another solution, that would be helpful for all :)


问:
How to print a list of tuples with no brackets in Python
I'm looking for a way to print elements from a tuple with no brackets.

Here is my tuple:

```<code>mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)]
</code>```

I converted this to a list to make it easier to work with

```<code>mylist = list(mytuple)
</code>```

Then I did the following

```<code>for item in mylist:
    print(item.strip())
</code>```

But I get the following error

```<code>AttributeError: 'tuple' object has no attribute 'strip'
</code>```

Which is strange because I thought I converted to a list?

What I expect to see as the final result is something like:

```<code>1.0,
25.34,
2.4,
7.4
</code>```

or

```<code>1.0, ,23.43, ,2.4, ,7.4
</code>```

答:
One can generalize to any complex structure with use of recursion:

```<code>def flatten(o):
    if not isinstance(o, (list, tuple, dict)):
        return str(o)
    elif isinstance(o, (list, tuple)):
        return "\n".join(flatten(e) for e in o)
    elif isinstance(o, (dict)):
        return "\n".join(e + ": " + flatten(o[e]) for e in o)
</code>```

Example:

```<code>>>> flatten((1, [21, {'a': 'aaa', 'b': 'bbb'}], 3))
'1, 21, a: aaa\nb: bbb, 3'
</code>```

Body:
I'm looking for a way to print elements from a tuple with no brackets.

Here is my tuple:

mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)]

I converted this to a list to make it easier to work with

mylist = list(mytuple)

Then I did the following

for item in mylist:
    print(item.strip())

But I get the following error

AttributeError: 'tuple' object has no attribute 'strip'

Which is strange because I thought I converted to a list?

What I expect to see as the final result is something like:

1.0,
25.34,
2.4,
7.4

or

1.0, ,23.43, ,2.4, ,7.4

Body:
One can generalize to any complex structure with use of recursion:

def flatten(o):
    if not isinstance(o, (list, tuple, dict)):
        return str(o)
    elif isinstance(o, (list, tuple)):
        return "\n".join(flatten(e) for e in o)
    elif isinstance(o, (dict)):
        return "\n".join(e + ": " + flatten(o[e]) for e in o)

Example:

>>> flatten((1, [21, {'a': 'aaa', 'b': 'bbb'}], 3))
'1, 21, a: aaa\nb: bbb, 3'


问:
How to create range slider in angular 5
I tried ng2-ion-range-slider and ng2-nouislider using documentation described in github.
When i add these component it showing "it is not a known element of ngModule"
I import ng2-nouislider, ng2-ion-range-slider in my app module

APP MODULE

```<code>import 'hammerjs';
import {SharedModule} from './core/modules/shared.module';
import {AppComponent} from './app.component';
import {VoifinityMainModule} from './main/main.module';
import {FuseSplashScreenService} from './core/services/splash-screen.service';
import {VoifinityConfigService} from './core/services/config.service';
import {FuseNavigationService} from './core/components/navigation/navigation.service';
import {AppRoutingModule} from './app-routing.module';
import {AuthenticationModule} from './authentication/authentication.module';
import {VoifinityAuthInterceptor} from './core/auth/voifinity-auth.interceptor';
import {AuthService} from './core/auth/auth.service';
import {AuthGuardService} from './core/auth/auth-guard.service';
import {SimpleNotificationsModule} from 'angular2-notifications';
import {AppService} from './app.service';
import {NgHttpLoaderModule} from 'ng-http-loader/ng-http-loader.module';
import {IonRangeSliderModule} from 'ng2-ion-range-slider';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports     : [
        BrowserModule,
        HttpClientModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        SharedModule,
        SimpleNotificationsModule.forRoot(),
        AuthenticationModule,
        VoifinityMainModule,
        NgHttpLoaderModule,
        IonRangeSliderModule
    ],
    providers   : [
      AuthService,
      AppService,
      AuthGuardService,
      {
        provide: HTTP_INTERCEPTORS,
        useClass: VoifinityAuthInterceptor,
        multi: true
      },
        FuseSplashScreenService,
        VoifinityConfigService,
        FuseNavigationService
    ],
    bootstrap   : [
        AppComponent
    ]
})
export class AppModule
{
}
</code>```

app.component.html, added ion-range slider component. but it shows template parse error.  ion-range-slider is not a known element

```<code><ion-range-slider #sliderElement
          type="double"
          [min]="myMinVar"
          max="100"
          from="28"
          from_min="10"
          from_max="30"
          from_shadow="true"
          to="40"
          to_min="40"
          to_max="90"
          to_shadow="true"
          grid="true"
          grid_num="10"
          prefix="Weight: "
          postfix=" million pounds"
          decorate_both="false"
          (onUpdate)="myOnUpdate($event)"
          (onChange)="myOnChange($event)"
          (onFinish)="myOnFinish($event)"></ion-range-slider>
</code>```

答:
 giphy animated gif link

I have developed a range slider but it uses html css and angular (typescript).  You may have to modify code slightly but it works by using a CSS circle, placing the number value at a position in that circle, and placing that over the input range.

html section

```<code><div class="row small-margin"><div class="col-lg-8 small-padding">
<div class="form-group has-success">
  <label>Credit Score</label>
  <br />
  <div class="ui medium-padding">
    <div class="slidecontainer">
      <input #creditSlider (input)="updateCreditSlider()"  (change)="updateCreditSlider()" type="range" min="300" max="850" value="{{ creditSliderValue }}" class="slider" id="myRange">
    </div>
  </div>
  <div #creditSliderSpan class="sliderValue circle" >
    <span class="noselect">{{ creditSliderValue }}</span>
  </div>
  <div #creditSliderTrack class="sliderTrack" ></div>
</div>
</code>```

typescript section   (In the angular component class)

```<code>creditSliderValue : any;
@ViewChild('creditSlider') creditSlider;
@ViewChild('creditSliderSpan') creditSliderSpan;
.
.
.
updateCreditSlider() {
      let horizontalOffset:number = 0;
      //values from 300 to 850 - Next value needs to be adjusted based on your placement of slider object
      horizontalOffset =  ( (Number.parseInt(this.creditSlider.nativeElement.value )- 280)/2.45);
      this.creditSliderSpan.nativeElement.style.left = ( horizontalOffset )+ 'px';
      this.creditSliderSpan.nativeElement.style.top = this.creditSliderSpan.nativeElement.style.top  + 'px';
      this.creditSliderValue = this.creditSlider.nativeElement.value;
    }
</code>```

css section

```<code>.smallPadding {
  margin-bottom: 0px;
  padding: 4px;
}

.slidecontainer {
    width: 100%; /* Width of the outside container */
}

/* The slider itself */
.slider {
    position: relative;
    -webkit-appearance: none;  /* Override default CSS styles */
    appearance: none;
    width:275px;
    //width: 100%; /* Full-width */
    height: 15px;
    border-radius: 5px;
    //background: #d3d3d3; /* Grey background */
    background: rgba(211,211,211, 0.00);

    outline: none; /* Remove outline */
    opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
    -webkit-transition: .2s; /* 0.2 seconds transition on hover */
    transition: opacity .2s;
    z-index: 20;
}

/* Mouse-over effects */
.slider:hover {
    //opacity: 1; /* Fully shown on mouse-over */
}

/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
.slider::-webkit-slider-thumb {
    position: relative;
    -webkit-appearance: none; /* Override default look */
    appearance: none;
    width: 50px; /* Set a specific slider handle width */
    height: 50px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.slider::-moz-range-thumb {
    width: 25px; /* Set a specific slider handle width */
    height: 25px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.sliderValue {
    position: absolute;
    top: 25px;
    left: 0px;
    width: 100%; /* Width of the outside container */
    z-index: 15;

}
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}

@media screen and (max-width: 992px) {

}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 14pt;
  color: black;
  line-height: 46px;
  text-align: center;
  background: white;
  vertical-align: center;
  //display: table-cell;
  border-style: solid;
  border-color: #7E7E7E;
}

.medium-padding {
  padding-top: 14px;
  padding-bottom: 14px;
}
.sliderTrack {
  position: relative;
  width: 220px;
  height: 10px;
  background-color: #E0E1E2;
  vertical-align: center;
  border-radius: 5px;
  top: -35px;
  left: 25px;
  //display: table-cell;
  //border-style: solid;
  //border-color: #7E7E7E;
}
.left-padding {
  padding-left: 14px;

}

.small-margin {
  margin-left: 4px;
}
.medium-margin {
  margin-left: 10px;
}
.small-padding{
  padding: 4px;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to create range slider in angular 5

Body:
I tried ng2-ion-range-slider and ng2-nouislider using documentation described in github.
When i add these component it showing "it is not a known element of ngModule"
I import ng2-nouislider, ng2-ion-range-slider in my app module

APP MODULE

import 'hammerjs';
import {SharedModule} from './core/modules/shared.module';
import {AppComponent} from './app.component';
import {VoifinityMainModule} from './main/main.module';
import {FuseSplashScreenService} from './core/services/splash-screen.service';
import {VoifinityConfigService} from './core/services/config.service';
import {FuseNavigationService} from './core/components/navigation/navigation.service';
import {AppRoutingModule} from './app-routing.module';
import {AuthenticationModule} from './authentication/authentication.module';
import {VoifinityAuthInterceptor} from './core/auth/voifinity-auth.interceptor';
import {AuthService} from './core/auth/auth.service';
import {AuthGuardService} from './core/auth/auth-guard.service';
import {SimpleNotificationsModule} from 'angular2-notifications';
import {AppService} from './app.service';
import {NgHttpLoaderModule} from 'ng-http-loader/ng-http-loader.module';
import {IonRangeSliderModule} from 'ng2-ion-range-slider';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports     : [
        BrowserModule,
        HttpClientModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        SharedModule,
        SimpleNotificationsModule.forRoot(),
        AuthenticationModule,
        VoifinityMainModule,
        NgHttpLoaderModule,
        IonRangeSliderModule
    ],
    providers   : [
      AuthService,
      AppService,
      AuthGuardService,
      {
        provide: HTTP_INTERCEPTORS,
        useClass: VoifinityAuthInterceptor,
        multi: true
      },
        FuseSplashScreenService,
        VoifinityConfigService,
        FuseNavigationService
    ],
    bootstrap   : [
        AppComponent
    ]
})
export class AppModule
{
}

app.component.html, added ion-range slider component. but it shows template parse error.  ion-range-slider is not a known element

<ion-range-slider #sliderElement
          type="double"
          [min]="myMinVar"
          max="100"
          from="28"
          from_min="10"
          from_max="30"
          from_shadow="true"
          to="40"
          to_min="40"
          to_max="90"
          to_shadow="true"
          grid="true"
          grid_num="10"
          prefix="Weight: "
          postfix=" million pounds"
          decorate_both="false"
          (onUpdate)="myOnUpdate($event)"
          (onChange)="myOnChange($event)"
          (onFinish)="myOnFinish($event)"></ion-range-slider>

Body:
 giphy animated gif link

I have developed a range slider but it uses html css and angular (typescript).  You may have to modify code slightly but it works by using a CSS circle, placing the number value at a position in that circle, and placing that over the input range.

html section

<div class="row small-margin"><div class="col-lg-8 small-padding">
<div class="form-group has-success">
  <label>Credit Score</label>
  <br />
  <div class="ui medium-padding">
    <div class="slidecontainer">
      <input #creditSlider (input)="updateCreditSlider()"  (change)="updateCreditSlider()" type="range" min="300" max="850" value="{{ creditSliderValue }}" class="slider" id="myRange">
    </div>
  </div>
  <div #creditSliderSpan class="sliderValue circle" >
    <span class="noselect">{{ creditSliderValue }}</span>
  </div>
  <div #creditSliderTrack class="sliderTrack" ></div>
</div>

typescript section   (In the angular component class)

creditSliderValue : any;
@ViewChild('creditSlider') creditSlider;
@ViewChild('creditSliderSpan') creditSliderSpan;
.
.
.
updateCreditSlider() {
      let horizontalOffset:number = 0;
      //values from 300 to 850 - Next value needs to be adjusted based on your placement of slider object
      horizontalOffset =  ( (Number.parseInt(this.creditSlider.nativeElement.value )- 280)/2.45);
      this.creditSliderSpan.nativeElement.style.left = ( horizontalOffset )+ 'px';
      this.creditSliderSpan.nativeElement.style.top = this.creditSliderSpan.nativeElement.style.top  + 'px';
      this.creditSliderValue = this.creditSlider.nativeElement.value;
    }

css section

.smallPadding {
  margin-bottom: 0px;
  padding: 4px;
}

.slidecontainer {
    width: 100%; /* Width of the outside container */
}

/* The slider itself */
.slider {
    position: relative;
    -webkit-appearance: none;  /* Override default CSS styles */
    appearance: none;
    width:275px;
    //width: 100%; /* Full-width */
    height: 15px;
    border-radius: 5px;
    //background: #d3d3d3; /* Grey background */
    background: rgba(211,211,211, 0.00);

    outline: none; /* Remove outline */
    opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
    -webkit-transition: .2s; /* 0.2 seconds transition on hover */
    transition: opacity .2s;
    z-index: 20;
}

/* Mouse-over effects */
.slider:hover {
    //opacity: 1; /* Fully shown on mouse-over */
}

/* The slider handle (use -webkit- (Chrome, Opera, Safari, Edge) and -moz- (Firefox) to override default look) */
.slider::-webkit-slider-thumb {
    position: relative;
    -webkit-appearance: none; /* Override default look */
    appearance: none;
    width: 50px; /* Set a specific slider handle width */
    height: 50px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.slider::-moz-range-thumb {
    width: 25px; /* Set a specific slider handle width */
    height: 25px;
    border-radius: 50%;
    border-style: none;
    //background: #4CAF50; /* Green background */
    background: rgba(76,175,80, 0.00);
    cursor: pointer; /* Cursor on hover */

}

.sliderValue {
    position: absolute;
    top: 25px;
    left: 0px;
    width: 100%; /* Width of the outside container */
    z-index: 15;

}
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}

@media screen and (max-width: 992px) {

}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 14pt;
  color: black;
  line-height: 46px;
  text-align: center;
  background: white;
  vertical-align: center;
  //display: table-cell;
  border-style: solid;
  border-color: #7E7E7E;
}

.medium-padding {
  padding-top: 14px;
  padding-bottom: 14px;
}
.sliderTrack {
  position: relative;
  width: 220px;
  height: 10px;
  background-color: #E0E1E2;
  vertical-align: center;
  border-radius: 5px;
  top: -35px;
  left: 25px;
  //display: table-cell;
  //border-style: solid;
  //border-color: #7E7E7E;
}
.left-padding {
  padding-left: 14px;

}

.small-margin {
  margin-left: 4px;
}
.medium-margin {
  margin-left: 10px;
}
.small-padding{
  padding: 4px;
}


问:
How to find any 10% drop for a certain period?
This task is overwhelming for me.
I have a db with :

```<code>subject  date value
A        UNIX  6
B        UNIX  2
D        UNIX  4
A        UNIX  7
B        UNIX  9
</code>```

Where each subject is a different time series with all dates of the year and values. (so each subject contain all unix dates)

I need to find for subject A and C, when did they dropped 10% in value.
or:

during 2020 find when A or C fall 10% in value

I would usually use lag with a window like:

```<code>LAG(value,5) OVER (PARTITION BY name ORDER BY date_num)
</code>```

but this will help to find a slop based on a certain window.

I need to find the 10% slop on any possible window between certain dates, and get the first time we have a 10% drop (in case it kept falling to 20%).

答:
This will anchor your "drops" to each possible starting date and then return only the first successive date where the value had fallen relative to the anchor. If such drops occurs for different anchor dates they'll all be returned. There won't be checks to see if there are overlaps in those date ranges.

```<code>select t1.subject, t1.dt as date1, min(t2.dt) as date2
from T t1 inner join T t2
    on t2.subject = t1.subject and t2.dt > t1.dt
        and t2.value <= 0.9 * t1.value
where t1.subject in ('A', 'C')
group by t1.subject, t1.dt
</code>```

A lateral join works pretty well to get all the values back:

```<code>select t1.subject, t1.dt as date1, date2, t1.value as value1, t2.value2,
    (t1.value - value2) * 1.0 / t1.value as pct
from T t1 inner join lateral (
    select distinct
        min(t2.dt) over () as date2,
        first_value(t2.value) over (order by t2.dt) as value2
    from T t2
    where t2.subject = t1.subject and t2.dt > t1.dt and t2.value <= 0.9 * t1.value
) t2 on true
where t1.subject in ('A', 'C')
order by t1.subject, t1.dt
</code>```

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=abe57498a15abcb53794818f32ae444e

Body:
This task is overwhelming for me.
I have a db with :

subject  date value
A        UNIX  6
B        UNIX  2
D        UNIX  4
A        UNIX  7
B        UNIX  9

Where each subject is a different time series with all dates of the year and values. (so each subject contain all unix dates)

I need to find for subject A and C, when did they dropped 10% in value.
or:

during 2020 find when A or C fall 10% in value

I would usually use lag with a window like:

LAG(value,5) OVER (PARTITION BY name ORDER BY date_num)

but this will help to find a slop based on a certain window.

I need to find the 10% slop on any possible window between certain dates, and get the first time we have a 10% drop (in case it kept falling to 20%).

Body:
This will anchor your "drops" to each possible starting date and then return only the first successive date where the value had fallen relative to the anchor. If such drops occurs for different anchor dates they'll all be returned. There won't be checks to see if there are overlaps in those date ranges.

select t1.subject, t1.dt as date1, min(t2.dt) as date2
from T t1 inner join T t2
    on t2.subject = t1.subject and t2.dt > t1.dt
        and t2.value <= 0.9 * t1.value
where t1.subject in ('A', 'C')
group by t1.subject, t1.dt

A lateral join works pretty well to get all the values back:

select t1.subject, t1.dt as date1, date2, t1.value as value1, t2.value2,
    (t1.value - value2) * 1.0 / t1.value as pct
from T t1 inner join lateral (
    select distinct
        min(t2.dt) over () as date2,
        first_value(t2.value) over (order by t2.dt) as value2
    from T t2
    where t2.subject = t1.subject and t2.dt > t1.dt and t2.value <= 0.9 * t1.value
) t2 on true
where t1.subject in ('A', 'C')
order by t1.subject, t1.dt

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=abe57498a15abcb53794818f32ae444e


问:
Inner rounded shadows inside div
I have a div which looks something like this:

.box{
 box-sizing: border-box;
 border: solid 0.01rem #2e2e2e;
 border-radius: 3px;
 width:100px;
 height:100px;
 background:red;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"/></code>```

And I'm trying to achieve this effect. How can I make this box look with such shadows from the inside of the div?

答:
CSS box-shadow

I think the answer posted by @isherwood works as the best one for your use-case. But, there is a way to make the shadow show on the inside of the element by setting the last parameter of box-shadow as inset.
There are a few catches for this solution though. A few things which I could not achieve:

I am unable to implement linear gradient to the shadow.

I am unable to give a border-radius to the inner boundary of the shadow.

div.box {
  background: linear-gradient(90deg, hsl(26, 68%, 26%), hsl(26, 68%, 45%));
  height: 100px;
  width: 100px;
  box-shadow: 0 0 0 12px hsl(26, 68%, 35%) inset;
  border-radius: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

Reference: How to create an inner shadow using CSS

Title: Inner rounded shadows inside div

Body:
I have a div which looks something like this:

.box{
 box-sizing: border-box;
 border: solid 0.01rem #2e2e2e;
 border-radius: 3px;
 width:100px;
 height:100px;
 background:red;
 }

And I'm trying to achieve this effect. How can I make this box look with such shadows from the inside of the div?

Body:
CSS box-shadow

I think the answer posted by @isherwood works as the best one for your use-case. But, there is a way to make the shadow show on the inside of the element by setting the last parameter of box-shadow as inset.
There are a few catches for this solution though. A few things which I could not achieve:

I am unable to implement linear gradient to the shadow.

I am unable to give a border-radius to the inner boundary of the shadow.

div.box {
  background: linear-gradient(90deg, hsl(26, 68%, 26%), hsl(26, 68%, 45%));
  height: 100px;
  width: 100px;
  box-shadow: 0 0 0 12px hsl(26, 68%, 35%) inset;
  border-radius: 10px;
}

<div class="box"></div>

Reference: How to create an inner shadow using CSS


问:
Something missing or additional in my Do While loop, how do i fix it
```<code>            String message = "Hello " + name + ", Do you know what day it is today?";
            answer = JOptionPane.showConfirmDialog(frame, message);
            JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?",
                    JOptionPane.INFORMATION_MESSAGE);

        } while (answer == JOptionPane.NO_OPTION);

        if (answer == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}
</code>```

When i press No, it will say "come on think a little harder" and loop back to 'do you know what day it is' but when i press yes, it still says 'come on think a little harder" and then only says "great'

What i want it to say when i press yes is only 'great'

I think i may have misplaced something that should not/should be in the while loop im not really sure..

答:
You're showing the no message before the determination has been made that it is a no message:</p>
```<code> while (true) {
        String message = "Hello " + name + ", Do you know what day it is today?";
        int answer = JOptionPane.showConfirmDialog(null, message);
        if (answer == JOptionPane.NO_OPTION) {
            JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?", JOptionPane.INFORMATION_MESSAGE);
        } else if (answer == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
            break;
        } else {
            break;
        }
    }
</code>```

Body:
            String message = "Hello " + name + ", Do you know what day it is today?";
            answer = JOptionPane.showConfirmDialog(frame, message);
            JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?",
                    JOptionPane.INFORMATION_MESSAGE);

        } while (answer == JOptionPane.NO_OPTION);

        if (answer == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

When i press No, it will say "come on think a little harder" and loop back to 'do you know what day it is' but when i press yes, it still says 'come on think a little harder" and then only says "great'

What i want it to say when i press yes is only 'great'

I think i may have misplaced something that should not/should be in the while loop im not really sure..

Body:
You're showing the no message before the determination has been made that it is a no message:

 while (true) {
        String message = "Hello " + name + ", Do you know what day it is today?";
        int answer = JOptionPane.showConfirmDialog(null, message);
        if (answer == JOptionPane.NO_OPTION) {
            JOptionPane.showMessageDialog(null, "Come on think a little harder", "Are you new here?", JOptionPane.INFORMATION_MESSAGE);
        } else if (answer == JOptionPane.YES_OPTION) {
            JOptionPane.showMessageDialog(null, "Great!", "Yay", JOptionPane.INFORMATION_MESSAGE);
            break;
        } else {
            break;
        }
    }


问:
How can i get State from my store in Appjs?
I would like to see the state in my App.js
i am importing like this

```<code>import configureStore from './src/configureStore'
let store = configureStore()
</code>```

so i am injecting in my App.js

```<code><Provider store={store} theme={theme}>
  {console.log('11111',store)}
  <NavigationContainer>
</code>```

in console only i can see this:
{dispatch: ƒ, subscribe: ƒ, getState: ƒ, replaceReducer: ƒ, @@observable: ƒ}

how can i see the state?

btw: configureStore is:

```<code>import {createStore, applyMiddleware} from 'redux';
import Reducers from './reducers'
import thunk from 'redux-thunk'

export default function configureStore () {
    let store = createStore(Reducers, applyMiddleware(thunk))
    return store
}
</code>```

答:
You can simply call store.getState() method to get the current state tree of your application. It is equal to the last value returned by the store's reducer.</p>
```<code><Provider store={store} theme={theme}>
  {console.log('11111',store.getState())}
  <NavigationContainer>
</code>```

Body:
I would like to see the state in my App.js
i am importing like this

import configureStore from './src/configureStore'
let store = configureStore()

so i am injecting in my App.js

<Provider store={store} theme={theme}>
  {console.log('11111',store)}
  <NavigationContainer>

in console only i can see this:
{dispatch: ƒ, subscribe: ƒ, getState: ƒ, replaceReducer: ƒ, @@observable: ƒ}

how can i see the state?

btw: configureStore is:

import {createStore, applyMiddleware} from 'redux';
import Reducers from './reducers'
import thunk from 'redux-thunk'

export default function configureStore () {
    let store = createStore(Reducers, applyMiddleware(thunk))
    return store
}

Body:
You can simply call store.getState() method to get the current state tree of your application. It is equal to the last value returned by the store's reducer.

<Provider store={store} theme={theme}>
  {console.log('11111',store.getState())}
  <NavigationContainer>


问:
Getting My Prometheus instances to show up with labels instead of their instance IP:PORT
I am using Kubernetes and exposing my spring boot services to Prometheus by adding annotations in the deployment.yaml, i have a great dashboard (as seen in the screen shot) the problem I have is when I go to the instance drop down menu to select a different service to view its giving me internal kubernetes IP and Port, i know there are labels attached, is there a way to show a label instead of the IP:PORT as it makes it difficult to figure out what service is what.

In the prometheus UI i see tags and using one other than instance would make more sense.

答: You can use https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config to map your instance:port to meaningful label you need. You would also require to update your query in dashboard accordingly based on what you are relabelling it to</p>


问:
Location of the error token always starts at 0
I'm writing a parser with error handling. I would like to output to the user the exact location of the parts of the input that couldn't be parsed.

However, the location of the error token always starts at 0, even if before it were parts that were parsed successfully.

Here's a heavily simplified example of what I did.
(The problematic part is probably in the parser.yy.)

Location.hh:

#pragma once
#include <string>

// The full version tracks position in bytes, line number and offset in the current line.
// Here however, I've shortened it to line number only.
struct Location
{
    int beginning, ending;
    operator std::string() const { return std::to_string(beginning) + '-' + std::to_string(ending); }
};
```
<p><em>LexerClass.hh</em>:</p>
<pre class="lang-cc prettyprint-override"><code>#pragma once
#include <istream>
#include <string>
#if ! defined(yyFlexLexerOnce)
    #include <FlexLexer.h>
#endif
#include "Location.hh"

class LexerClass : public yyFlexLexer
{
    int currentPosition = 0;
protected:
    std::string *yylval = nullptr;
    Location *yylloc = nullptr;
public:
    LexerClass(std::istream &in) : yyFlexLexer(&in) {}
    [[nodiscard]] int yylex(std::string *const lval, Location *const lloc);
    void onNewLine() { yylloc->beginning = yylloc->ending = ++currentPosition; }
};
</code>```

lexer.ll:

```<code>%{
    #include "./parser.hh"
    #include "./LexerClass.hh"

    #undef  YY_DECL
    #define YY_DECL int LexerClass::yylex(std::string *const lval, Location *const lloc)
%}

%option c++ noyywrap
%option yyclass="LexerClass"

%%

%{
    yylval = lval;
    yylloc = lloc;
%}

[[:blank:]] ;
\n          { onNewLine(); }
[0-9]       { return yy::Parser::token::DIGIT; }
.           { return yytext[0]; }
</code>```

parser.yy:

```<code>%language "c++"

%code requires {
    #include "LexerClass.hh"
    #include "Location.hh"
}

%define api.parser.class {Parser}
%define api.value.type {std::string}
%define api.location.type {Location}
%parse-param {LexerClass &lexer}
%defines

%code {
    template<typename RHS>
    void calcLocation(Location &current, const RHS &rhs, const int n);
    #define YYLLOC_DEFAULT(Cur, Rhs, N) calcLocation(Cur, Rhs, N)

    #define yylex lexer.yylex
}

%token DIGIT

%%

numbers:
      %empty
    | numbers number ';' { std::cout << std::string(@number) << "\tnumber" << std::endl; }
    | error ';' { yyerrok; std::cerr << std::string(@error) << "\terror context" << std::endl; }
    ;

number:
      DIGIT {}
    | number DIGIT {}
    ;

%%

#include <iostream>

template<typename RHS>
inline void calcLocation(Location &current, const RHS &rhs, const int n)
{
    current = (n <= 1)
        ? YYRHSLOC(rhs, n)
        : Location{YYRHSLOC(rhs, 1).beginning, YYRHSLOC(rhs, n).ending};
}

void yy::Parser::error(const Location &location, const std::string &message)
{
    std::cout << std::string(location) << "\terror: " << message << std::endl;
}

int main()
{
    LexerClass lexer(std::cin);
    yy::Parser parser(lexer);
    return parser();
}
</code>```

For the input:

```<code>123
456
789;
123;
089
xxx
123;
765
432;
</code>```

expected output:

```<code>0-2 number
3-3 number
5-5 error: syntax error
4-6 error context
7-8 number
</code>```

actual output:

```<code>0-2 number
3-3 number
5-5 error: syntax error
0-6 error context
7-8 number
</code>```

答:
I'm building upon the rici's answer, so read that one first.

Let's consider the rule:

```<code>numbers:
      %empty
    | numbers number ';'
    | error ';' { yyerrok; }
    ;
</code>```

This means the nonterminal numbers can be one of these three things:

It may be empty.

It may be a number preceded by any valid numbers.

It may be an error.

Do you see the problem yet?
The whole numbers has to be an error, from the beginning; there is no rule saying that anything else allowed before it.
Of course Bison obediently complies to your wishes and makes the error start at the very beginning of the nonterminal numbers.
It can do that because error is a jack of all trades and there can be no rule about what can be included inside of it. Bison, to fulfill your rule, needs to extend the error over all previous numbers.

When you understand the problem, fixing it is rather easy. You just need to tell Bison that numbers are allowed before the error:

```<code>numbers:
      %empty
    | numbers number ';'
    | numbers error ';' { yyerrok; }
    ;
</code>```

This is IMO the best solution. There is another approach, though.

You can move the error token to the number:

```<code>numbers:
      %empty
    | numbers number ';' { yyerrok; }
    ;

number:
      DIGIT
    | number DIGIT
    | error
    ;
</code>```

Notice that yyerrok needs to stay in numbers because the parser would enter an infinite loop if you place it next to a rule that ends with token error.

A disadvantage of this approach is that if you place an action next to this error, it will be triggered multiple times (more or less once per every illegal terminal).
Maybe in some situations this is preferable but generally I suggest using the first way of solving the issue.

Body:
I'm writing a parser with error handling. I would like to output to the user the exact location of the parts of the input that couldn't be parsed.

However, the location of the error token always starts at 0, even if before it were parts that were parsed successfully.

Here's a heavily simplified example of what I did.
(The problematic part is probably in the parser.yy.)

Location.hh:

#pragma once
#include <string>

// The full version tracks position in bytes, line number and offset in the current line.
// Here however, I've shortened it to line number only.
struct Location
{
    int beginning, ending;
    operator std::string() const { return std::to_string(beginning) + '-' + std::to_string(ending); }
};

LexerClass.hh:

#pragma once
#include <istream>
#include <string>
#if ! defined(yyFlexLexerOnce)
    #include <FlexLexer.h>
#endif
#include "Location.hh"

class LexerClass : public yyFlexLexer
{
    int currentPosition = 0;
protected:
    std::string *yylval = nullptr;
    Location *yylloc = nullptr;
public:
    LexerClass(std::istream &in) : yyFlexLexer(&in) {}
    [[nodiscard]] int yylex(std::string *const lval, Location *const lloc);
    void onNewLine() { yylloc->beginning = yylloc->ending = ++currentPosition; }
};

lexer.ll:

%{
    #include "./parser.hh"
    #include "./LexerClass.hh"

    #undef  YY_DECL
    #define YY_DECL int LexerClass::yylex(std::string *const lval, Location *const lloc)
%}

%option c++ noyywrap
%option yyclass="LexerClass"

%%

%{
    yylval = lval;
    yylloc = lloc;
%}

[[:blank:]] ;
\n          { onNewLine(); }
[0-9]       { return yy::Parser::token::DIGIT; }
.           { return yytext[0]; }

parser.yy:

%language "c++"

%code requires {
    #include "LexerClass.hh"
    #include "Location.hh"
}

%define api.parser.class {Parser}
%define api.value.type {std::string}
%define api.location.type {Location}
%parse-param {LexerClass &lexer}
%defines

%code {
    template<typename RHS>
    void calcLocation(Location &current, const RHS &rhs, const int n);
    #define YYLLOC_DEFAULT(Cur, Rhs, N) calcLocation(Cur, Rhs, N)

    #define yylex lexer.yylex
}

%token DIGIT

%%

numbers:
      %empty
    | numbers number ';' { std::cout << std::string(@number) << "\tnumber" << std::endl; }
    | error ';' { yyerrok; std::cerr << std::string(@error) << "\terror context" << std::endl; }
    ;

number:
      DIGIT {}
    | number DIGIT {}
    ;

%%

#include <iostream>

template<typename RHS>
inline void calcLocation(Location &current, const RHS &rhs, const int n)
{
    current = (n <= 1)
        ? YYRHSLOC(rhs, n)
        : Location{YYRHSLOC(rhs, 1).beginning, YYRHSLOC(rhs, n).ending};
}

void yy::Parser::error(const Location &location, const std::string &message)
{
    std::cout << std::string(location) << "\terror: " << message << std::endl;
}

int main()
{
    LexerClass lexer(std::cin);
    yy::Parser parser(lexer);
    return parser();
}

For the input:

123
456
789;
123;
089
xxx
123;
765
432;

expected output:

0-2 number
3-3 number
5-5 error: syntax error
4-6 error context
7-8 number

actual output:

0-2 number
3-3 number
5-5 error: syntax error
0-6 error context
7-8 number

Body:
I'm building upon the rici's answer, so read that one first.

Let's consider the rule:

numbers:
      %empty
    | numbers number ';'
    | error ';' { yyerrok; }
    ;

This means the nonterminal numbers can be one of these three things:

It may be empty.

It may be a number preceded by any valid numbers.

It may be an error.

Do you see the problem yet?
The whole numbers has to be an error, from the beginning; there is no rule saying that anything else allowed before it.
Of course Bison obediently complies to your wishes and makes the error start at the very beginning of the nonterminal numbers.
It can do that because error is a jack of all trades and there can be no rule about what can be included inside of it. Bison, to fulfill your rule, needs to extend the error over all previous numbers.

When you understand the problem, fixing it is rather easy. You just need to tell Bison that numbers are allowed before the error:

numbers:
      %empty
    | numbers number ';'
    | numbers error ';' { yyerrok; }
    ;

This is IMO the best solution. There is another approach, though.

You can move the error token to the number:

numbers:
      %empty
    | numbers number ';' { yyerrok; }
    ;

number:
      DIGIT
    | number DIGIT
    | error
    ;

Notice that yyerrok needs to stay in numbers because the parser would enter an infinite loop if you place it next to a rule that ends with token error.

A disadvantage of this approach is that if you place an action next to this error, it will be triggered multiple times (more or less once per every illegal terminal).
Maybe in some situations this is preferable but generally I suggest using the first way of solving the issue.


问:
Jest gives `Cannot find module` when importing components with absolute paths
Receiving the following error when running Jest

```<code>Cannot find module 'src/views/app' from 'index.jsx'

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
  at Object.<anonymous> (src/index.jsx:4:12)
</code>```

index.jsx

```<code>import AppContainer from 'src/views/app';
</code>```

package.json

```<code>  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,mjs}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
    ],
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node",
      "mjs"
    ]
  },
</code>```

My tests that run files that only contain relative paths in the tree run correctly.

To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.

答:
This can also be caused by absolute imports present in the globalSetup file (or any files it references).

It seems like moduleNameMappers do not get applied to globalSetup files. I fixed this by just switching to relative imports for those specific files.

Body:
Receiving the following error when running Jest

Cannot find module 'src/views/app' from 'index.jsx'

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
  at Object.<anonymous> (src/index.jsx:4:12)

index.jsx

import AppContainer from 'src/views/app';

package.json

  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,mjs}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
    ],
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node",
      "mjs"
    ]
  },

My tests that run files that only contain relative paths in the tree run correctly.

To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.


问:
How to make a simple Boolean condition
What am I doing wrong with my code?

I'm trying to get it so when I run happy_home it comes out true when there is at least one cat and no dogs.

```<code>cat_count = 2
dog_count = 0

if cat_count > 0:
    has_cat = True

if dog_count > 0:
    has_dog = False

happy_home = (has_cat and has_dog)

happy_home
</code>```

答:
You really only need this.</p>
```<code>cat_count = 2
dog_count = 0

print(cat_count > 0 and dog_count == 0)
</code>```

Title: How to make a simple Boolean condition

Body:
What am I doing wrong with my code?

I'm trying to get it so when I run happy_home it comes out true when there is at least one cat and no dogs.

cat_count = 2
dog_count = 0

if cat_count > 0:
    has_cat = True

if dog_count > 0:
    has_dog = False

happy_home = (has_cat and has_dog)

happy_home

Body:
You really only need this.

cat_count = 2
dog_count = 0

print(cat_count > 0 and dog_count == 0)


问:
Best way to transfer struct from one process to another?
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

```<code>typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;
</code>```

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.

答:
WM_COPYDATA is specifically meant for transferring structs between processes. Check it out.

You mentioned pointers though - and no, you cannot expect pointers to work between processes. If you have variable-length arrays or pointers, it's probably necessary to serialize the data, for example with BSON or XML.

Body:
I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:

typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.


答:
Why would you have has_cat and has_dog attributes with two if statements? You can simply check both of them at the same if statement. Please check out the code at below:</p>
```<code>#!/bin/python3

cat_count = 2
dog_count = 0

happy_home = False

if cat_count > 0 and dog_count == 0:
    happy_home = True

print(happy_home)
</code>```

Title: How to make a simple Boolean condition

Body:
Why would you have has_cat and has_dog attributes with two if statements? You can simply check both of them at the same if statement. Please check out the code at below:

#!/bin/python3

cat_count = 2
dog_count = 0

happy_home = False

if cat_count > 0 and dog_count == 0:
    happy_home = True

print(happy_home)


问:
IF(A2>A3, 1, 0) Excel formula in Pandas
I am trying to create a column with zeros and ones based on values from 1st column.
If the value of upper cell is bigger, then write 1, else 0.
Example code would look like this:

```<code>df = pd.Dataframe({'col1': [1, 2, 1, 3, 0]})
df['col2'] =  ...python version of excel formula IF(A2>A3, 1, 0)...
</code>```

expected output:

I have tried:

```<code>while True:
    for index, rows in df.iterrows():
        df['col1'] = np.where(df['col1'] > df['col1'][index+1], 1, 0)
</code>```

but this is very slow and gives wrong results.
Thanks in advance!

答:
Here is the final solution I came up with:</p>
```<code>df['col2] = (df['col1'<df['col1'].shift()).astype(int).shift(periods=-1).fillna(0)
</code>```

Title: IF(A2>A3, 1, 0) Excel formula in Pandas

Body:
I am trying to create a column with zeros and ones based on values from 1st column.
If the value of upper cell is bigger, then write 1, else 0.
Example code would look like this:

df = pd.Dataframe({'col1': [1, 2, 1, 3, 0]})
df['col2'] =  ...python version of excel formula IF(A2>A3, 1, 0)...

expected output:

I have tried:

while True:
    for index, rows in df.iterrows():
        df['col1'] = np.where(df['col1'] > df['col1'][index+1], 1, 0)

but this is very slow and gives wrong results.
Thanks in advance!

Body:
Here is the final solution I came up with:

df['col2] = (df['col1'<df['col1'].shift()).astype(int).shift(periods=-1).fillna(0)


问:
Reduce custom object using RxJava
I'm using RxJava, I have a list of Point and i want to calculate the distance between each point and get the sum.

The point class look like this

```<code>public class Point {
    public double x;
    public double y;
}
</code>```

So i need to map and reduce at same time, but i didn't found a solution.

```<code>public Observable<Double> totalDistance(Observable<List<Point>> obs) {
 return obs.reduceMap(new ArrayList<Integer>, (list, pointA, pointB) -> distance(pointA, pointB)). ?
}
</code>```

What its the most efficient way to do it (or at least a solution that works) ? Which operator should i use ?

To give a more concrete example, here is what I have and what I want:

```<code>Point a (45, 32)
Point b (56, 75)
Point c (44, 53)
Point d (42, 54)
Point e (42, 55)

a to b = 10m
b to c = 15m
c to d = 25m
d to e = 10m

Result = 60m
</code>```

In reality my points are GPS positions and I use the haversine formula to calculate the distance between two positions.

I use observables because the list of points to be calculated is updated sometime. In fact every x points the user has reached, I have an instruction to send. After sending the instruction, a new list of points until the next instruction is emit.

答:
You can use the map() method to convert the values of an Observable<List<Point>> to values for an Observable<Double>. The code can look like this:

```<code>public static void main(String[] args) throws Exception {
    Point a = new Point(45, 32);
    Point b = new Point(56, 75);
    Point c = new Point(44, 53);
    Point d = new Point(42, 54);
    Point e = new Point(42, 55);

    List<Point> points = new ArrayList<Point>();
    points.add(a);
    points.add(b);
    points.add(c);
    points.add(d);
    points.add(e);

    Subject<List<Point>> subjectOfListOfPoints = PublishSubject.create();

    Observable<List<Point>> observable = subjectOfListOfPoints;

    Observable<Double> doubleObservable = observable.map(it -> {
        return calculateSumOfDistances(it); });

    doubleObservable.subscribe(it -> {
        System.out.println("The sum is: "+it);
    });

    subjectOfListOfPoints.onNext(points);
}

private static double calculateSumOfDistances(List<Point> points) {
    List<Double> distances = new ArrayList<Double>();
    for (int i=0; i<points.size()-1; i++) {
        double distance = distance(points.get(i), points.get(i+1));
        System.out.println("Distance is: "+distance);
        distances.add(distance);
    }
    double sum = 0;
    for (Double d: distances) {
        sum += d;
    }
    return sum;
}

private static double distance(Point a, Point b) {
    return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
</code>```

This will create the following output:

```<code>Distance is: 44.384682042344295
Distance is: 25.059928172283335
Distance is: 2.23606797749979
Distance is: 1.0
The sum is: 72.68067819212742
</code>```

Title: Reduce custom object using RxJava

Body:
I'm using RxJava, I have a list of Point and i want to calculate the distance between each point and get the sum.

The point class look like this

public class Point {
    public double x;
    public double y;
}

So i need to map and reduce at same time, but i didn't found a solution.

public Observable<Double> totalDistance(Observable<List<Point>> obs) {
 return obs.reduceMap(new ArrayList<Integer>, (list, pointA, pointB) -> distance(pointA, pointB)). ?
}

What its the most efficient way to do it (or at least a solution that works) ? Which operator should i use ?

To give a more concrete example, here is what I have and what I want:

Point a (45, 32)
Point b (56, 75)
Point c (44, 53)
Point d (42, 54)
Point e (42, 55)

a to b = 10m
b to c = 15m
c to d = 25m
d to e = 10m

Result = 60m

In reality my points are GPS positions and I use the haversine formula to calculate the distance between two positions.

I use observables because the list of points to be calculated is updated sometime. In fact every x points the user has reached, I have an instruction to send. After sending the instruction, a new list of points until the next instruction is emit.

Body:
You can use the map() method to convert the values of an Observable<List<Point>> to values for an Observable<Double>. The code can look like this:

public static void main(String[] args) throws Exception {
    Point a = new Point(45, 32);
    Point b = new Point(56, 75);
    Point c = new Point(44, 53);
    Point d = new Point(42, 54);
    Point e = new Point(42, 55);

    List<Point> points = new ArrayList<Point>();
    points.add(a);
    points.add(b);
    points.add(c);
    points.add(d);
    points.add(e);

    Subject<List<Point>> subjectOfListOfPoints = PublishSubject.create();

    Observable<List<Point>> observable = subjectOfListOfPoints;

    Observable<Double> doubleObservable = observable.map(it -> {
        return calculateSumOfDistances(it); });

    doubleObservable.subscribe(it -> {
        System.out.println("The sum is: "+it);
    });

    subjectOfListOfPoints.onNext(points);
}

private static double calculateSumOfDistances(List<Point> points) {
    List<Double> distances = new ArrayList<Double>();
    for (int i=0; i<points.size()-1; i++) {
        double distance = distance(points.get(i), points.get(i+1));
        System.out.println("Distance is: "+distance);
        distances.add(distance);
    }
    double sum = 0;
    for (Double d: distances) {
        sum += d;
    }
    return sum;
}

private static double distance(Point a, Point b) {
    return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}

This will create the following output:

Distance is: 44.384682042344295
Distance is: 25.059928172283335
Distance is: 2.23606797749979
Distance is: 1.0
The sum is: 72.68067819212742


问:
What would be the correct algorithm to solve our problem in Neo4j database?
Our problem:

Given a one start point (node) or more (nodes) we want to create a directed tree (hierarchical) graph in Neo4j. We have the restriction that all directions are always one-way. Further we know what nodes are connected, but we don't know the end nodes.

We are looking for an algorithm which can find inside graph in a way that given the start point all end points can be reached.

答:
I think Minimum Weight Spanning Tree would meet your requirement.

Create your in-memory graph with undirected relationships, and give all relationships a weight of 1. Pass the node id for node 100 as the startNodeId parameter.


问:
How to improve the performance of multiple left joins in MySQL?
I have a trouble performance when I made multiples left joins in a query.
There are 10 left joins in my query, if I show the information of 5 left joins works so fast but if I show information more of 5 left joins (6,7,8,etc.) takes 30 seconds to show the information. Example:

This is my original query that takes 32 seconds

```<code>SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       `subgrupo_sevens`.`name` AS `subgrupo_7`,
       `subgrupo_eights`.`name` AS `subgrupo_8`,
       `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....
</code>```

If I comment some information like this, takes 0.18 seconds

```<code>SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       -- `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       -- `subgrupo_sevens`.`name` AS `subgrupo_7`,
       -- `subgrupo_eights`.`name` AS `subgrupo_8`,
       -- `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....
</code>```

If I uncomment one information like this, takes 32 - 34 seconds

```<code>SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       -- `subgrupo_sevens`.`name` AS `subgrupo_7`,
       -- `subgrupo_eights`.`name` AS `subgrupo_8`,
       -- `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....
</code>```

If I comment one information and uncomment other information like this, takes 0.18 seconds

```<code>SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       -- `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       -- `subgrupo_sevens`.`name` AS `subgrupo_7`,
       -- `subgrupo_eights`.`name` AS `subgrupo_8`,
       -- `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....
</code>```

I saw that If I get 5 information of my left joins works well but if I get 6 o more information of my left joins takes to time, no matter which information I get always take too long time if I get more than 6 left joins.
Its crazy!!

*** EDITED
I put the original query

```<code>SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       `subgrupo_sevens`.`name` AS `subgrupo_7`,
       `subgrupo_eights`.`name` AS `subgrupo_8`,
       `subgrupo_nines`.`name`  AS `subgrupo_9`
FROM   `users`
       LEFT JOIN `directions`
              ON `users`.`direction_id` = `directions`.`id`
                 AND `directions`.`deleted_at` IS NULL
       LEFT JOIN `positions`
              ON `users`.`position_id` = `positions`.`id`
                 AND `positions`.`deleted_at` IS NULL
       LEFT JOIN `sites`
              ON `users`.`site_id` = `sites`.`id`
                 AND `sites`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_fours`
              ON `users`.`subgrupo_4` = `subgrupo_fours`.`id`
                 AND `subgrupo_fours`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_fives`
              ON `users`.`subgrupo_5` = `subgrupo_fives`.`id`
                 AND `subgrupo_fives`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_sixes`
              ON `users`.`subgrupo_6` = `subgrupo_sixes`.`id`
                 AND `subgrupo_sixes`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_sevens`
              ON `users`.`subgrupo_7` = `subgrupo_sevens`.`id`
                 AND `subgrupo_sevens`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_eights`
              ON `users`.`subgrupo_8` = `subgrupo_eights`.`id`
                 AND `subgrupo_eights`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_nines`
              ON `users`.`subgrupo_9` = `subgrupo_nines`.`id`
                 AND `subgrupo_nines`.`deleted_at` IS NULL
WHERE  `users`.`user_profile_id` = 4
       AND users.id IN (SELECT patient_vaccinations.user_id
                        FROM   `patient_vaccinations`
                        WHERE  `patient_vaccinations`.`deleted_at` IS NULL)
       AND `users`.`deleted_at` IS NULL
GROUP  BY `users`.`id`
LIMIT  100 offset 0
</code>```

答:
You only provided the select clause, which usually does not contribute significantly to the performance problems your query may have. The select clause may also be slow in some cases, if it has to fill a lot of memory, but you can find out whether the select clause is your culprit by removing all columns and leaving the joins as they were:

```<code>select 1
from <your ten joined tables>;
</code>```

If this is slow, which is probably the case, then you need to focus on the from and join clauses.

We know that some of the last five tables are making it slow. So, you will need to find out which table is the culprit. Try it with six tables (without the last 4) and then with seven tables and so on. If it was quick for n tables and is slow for n + 1 tables, then the (n + 1)th table is the culprit. Try indexing the fields you are using for your join. Also, it may be the case that there are too many records in the table which represents the culprit.

So, as a general rule, you will need to find what the culprit is, ignoring any further complications for the time being and try and optimize the culprit. If you are successful and the query is still slow, then find the next culprit and so on.

If you conclude that this is impossible, then structural or strategic changes might be needed, depending on your schema and project.

Body:
I have a trouble performance when I made multiples left joins in a query.
There are 10 left joins in my query, if I show the information of 5 left joins works so fast but if I show information more of 5 left joins (6,7,8,etc.) takes 30 seconds to show the information. Example:

This is my original query that takes 32 seconds

SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       `subgrupo_sevens`.`name` AS `subgrupo_7`,
       `subgrupo_eights`.`name` AS `subgrupo_8`,
       `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....

If I comment some information like this, takes 0.18 seconds

SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       -- `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       -- `subgrupo_sevens`.`name` AS `subgrupo_7`,
       -- `subgrupo_eights`.`name` AS `subgrupo_8`,
       -- `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....

If I uncomment one information like this, takes 32 - 34 seconds

SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       -- `subgrupo_sevens`.`name` AS `subgrupo_7`,
       -- `subgrupo_eights`.`name` AS `subgrupo_8`,
       -- `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....

If I comment one information and uncomment other information like this, takes 0.18 seconds

SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       -- `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       -- `subgrupo_sevens`.`name` AS `subgrupo_7`,
       -- `subgrupo_eights`.`name` AS `subgrupo_8`,
       -- `subgrupo_nines`.`name`  AS `subgrupo_9`
       ....
       ....

I saw that If I get 5 information of my left joins works well but if I get 6 o more information of my left joins takes to time, no matter which information I get always take too long time if I get more than 6 left joins.
Its crazy!!

*** EDITED
I put the original query

SELECT `users`.id,
       `directions`.`name`      AS `subgrupo_1`,
       `positions`.`name`       AS `subgrupo_2`,
       `sites`.`name`           AS `subgrupo_3`,
       `subgrupo_fours`.`name`  AS `subgrupo_4`,
       `subgrupo_fives`.`name`  AS `subgrupo_5`,
       `subgrupo_sixes`.`name`  AS `subgrupo_6`,
       `subgrupo_sevens`.`name` AS `subgrupo_7`,
       `subgrupo_eights`.`name` AS `subgrupo_8`,
       `subgrupo_nines`.`name`  AS `subgrupo_9`
FROM   `users`
       LEFT JOIN `directions`
              ON `users`.`direction_id` = `directions`.`id`
                 AND `directions`.`deleted_at` IS NULL
       LEFT JOIN `positions`
              ON `users`.`position_id` = `positions`.`id`
                 AND `positions`.`deleted_at` IS NULL
       LEFT JOIN `sites`
              ON `users`.`site_id` = `sites`.`id`
                 AND `sites`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_fours`
              ON `users`.`subgrupo_4` = `subgrupo_fours`.`id`
                 AND `subgrupo_fours`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_fives`
              ON `users`.`subgrupo_5` = `subgrupo_fives`.`id`
                 AND `subgrupo_fives`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_sixes`
              ON `users`.`subgrupo_6` = `subgrupo_sixes`.`id`
                 AND `subgrupo_sixes`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_sevens`
              ON `users`.`subgrupo_7` = `subgrupo_sevens`.`id`
                 AND `subgrupo_sevens`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_eights`
              ON `users`.`subgrupo_8` = `subgrupo_eights`.`id`
                 AND `subgrupo_eights`.`deleted_at` IS NULL
       LEFT JOIN `subgrupo_nines`
              ON `users`.`subgrupo_9` = `subgrupo_nines`.`id`
                 AND `subgrupo_nines`.`deleted_at` IS NULL
WHERE  `users`.`user_profile_id` = 4
       AND users.id IN (SELECT patient_vaccinations.user_id
                        FROM   `patient_vaccinations`
                        WHERE  `patient_vaccinations`.`deleted_at` IS NULL)
       AND `users`.`deleted_at` IS NULL
GROUP  BY `users`.`id`
LIMIT  100 offset 0

Body:
You only provided the select clause, which usually does not contribute significantly to the performance problems your query may have. The select clause may also be slow in some cases, if it has to fill a lot of memory, but you can find out whether the select clause is your culprit by removing all columns and leaving the joins as they were:

select 1
from <your ten joined tables>;

If this is slow, which is probably the case, then you need to focus on the from and join clauses.

We know that some of the last five tables are making it slow. So, you will need to find out which table is the culprit. Try it with six tables (without the last 4) and then with seven tables and so on. If it was quick for n tables and is slow for n + 1 tables, then the (n + 1)th table is the culprit. Try indexing the fields you are using for your join. Also, it may be the case that there are too many records in the table which represents the culprit.

So, as a general rule, you will need to find what the culprit is, ignoring any further complications for the time being and try and optimize the culprit. If you are successful and the query is still slow, then find the next culprit and so on.

If you conclude that this is impossible, then structural or strategic changes might be needed, depending on your schema and project.


问:
How can I delete a remote tag?
How can I delete a Git tag that has already been pushed?</p>

答:
This two steps works fine:</p>
```<code># delete local tag '1.0.0'
git tag -d 1.0.0

# delete remote tag '1.0.0' (eg, GitHub version too)
git push origin :refs/tags/1.0.0
</code>```

Title: How can I delete a remote tag?

Body:
This two steps works fine:

# delete local tag '1.0.0'
git tag -d 1.0.0

# delete remote tag '1.0.0' (eg, GitHub version too)
git push origin :refs/tags/1.0.0


答:
The problem of switching labels comes from geom_text() not knowing how the information should be split for the purposes of dodging.  The solution is to supply a group= aesthetic to geom_text() that matches the fill= aesthetic specified for geom_col().

In the case of geom_col(), you specify aes(fill=feature).  The height of the different columns is therefore grouped automatically by corr$feature.  You can supply a group= aesthetic as well, but it's unnecessary and the dodging will happen as you expect.

In the case of geom_text(), there is no obvious way to group the data.  When you do not specify a group= aesthetic, ggplot2 chooses one of the columns (in this case, the first column number) for grouping.  For dodging to work here, you need to specify how the label information is grouped.  If you don't have a specific legend-associated aesthetic to choose here, you can use the group= aesthetic to specify group=feature.  This let's ggplot2 know that the text labels should be sorted and dodged by grouping according to this column in the data:

```<code>ggplot(data=corr, aes(x=factor(dimension), y=score)) +
  geom_col(aes(fill=feature),position=position_dodge2(width=1,preserve='single')) +
  facet_grid(~`sample length`, scales='free_x',space='free_x') +
  labs(x="Dimension", y="Correlation Coefficient (Abs. value)") +
  geom_text(aes(label=measure, group=feature),position=position_dodge2(width=0.9, preserve='single'), angle=90,
            size=4,hjust=2.5,color='white')
</code>```

As a side note, you don't have to specify the group= aesthetic if you assign a color-based aesthetic (or one that would result in a legend).  If we set color=feature with geom_text(), it works without group=. To see the labels, you need to set the alpha for the columns a bit lower, but this should illustrate the point well:

```<code>ggplot(data=corr, aes(x=factor(dimension), y=score)) +
  geom_col(aes(fill=feature),position=position_dodge2(width=1,preserve='single'), alpha=0.2) +
  facet_grid(~`sample length`, scales='free_x',space='free_x') +
  labs(x="Dimension", y="Correlation Coefficient (Abs. value)") +
  geom_text(aes(label=measure, color=feature),position=position_dodge2(width=0.9, preserve='single'), angle=90,
            size=4,hjust=2.5)
</code>```

Title: Labels on wrong dodged columns in geom_col

Body:
I want to create a simple barplot of my data frame:

> dput(corr)
structure(list(`sample length` = structure(c(2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = c("3s", "10s"), class = "factor"),
    feature = structure(c(1L, 1L, 5L, 5L, 2L, 5L, 6L, 5L, 5L,
    4L, 1L, 1L, 1L, 1L, 1L, 2L, 5L, 5L, 3L, 4L, 1L, 1L, 1L, 1L
    ), .Label = c("f0", "f1", "f2", "f3", "f2 prime", "f2-f1"
    ), class = "factor"), measure = c("meanf0 longterm", "meanf0 longterm st",
    "f2' Fant", "f2' Carlson", "F1meanERB", "F2meanERB", "f2-f1 ERB",
    "f2' Fant", "f2' Carlson", "F3meanERB", "meanf0 3secs", "meanf0 3secs st",
    "meanf0 10secs", "meanf0 longterm", "meanf0 longterm st",
    "F1meanERB", "f2' Fant", "f2' Carlson", "F2meanERB", "F3meanERB",
    "meanf0 longterm", "meanf0 longterm st", "meanf0 3secs",
    "meanf0 3s st"), score = c(0.574361009949897, 0.592472685498182,
    0.597453479834514, 0.529641256460457, 0.585994252821649,
    0.618734735308094, 0.517715270144259, 0.523916918327387,
    0.616237363007349, 0.732926257362305, 0.649505366093518,
    0.626628120773466, 0.522527636952945, 0.53968850323167, 0.548664887822775,
    0.648294358978928, 0.650806695307235, 0.696797693503567,
    0.621298393945597, 0.57140950987443, 0.606634531002859, 0.597064217305556,
    0.582534743353082, 0.572808145210493), dimension = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L), .Label = c("1", "2", "3",
    "4"), class = "factor")), row.names = c(NA, -24L), class = c("tbl_df",
"tbl", "data.frame"))

I have tried the following code:

ggplot(data=corr, aes(x=factor(dimension), y=score)) +
  geom_col(aes(fill=feature),position=position_dodge2(width=1,preserve='single')) +
  facet_grid(~`sample length`, scales='free_x',space='free_x') +
  labs(x="Dimension", y="Correlation Coefficient (Abs. value)") +
  geom_text(aes(label=measure),position=position_dodge2(width=0.9, preserve='single'), angle=90,
            size=4,hjust=2.5,color='white')

Giving the following barplot:

However, the labels for 'measure' are being incorrectly assigned to the columns. E.g. for 3s facet plot, under 'dimension 2', the two light blue bars should be labelled as 'f2' Carlson' and 'f2' Fant' but they have been swapped with the other two labels.

I think the levels must be wrong, but I don't understand how!

Any help much appreciated, ta

Body:
The problem of switching labels comes from geom_text() not knowing how the information should be split for the purposes of dodging.  The solution is to supply a group= aesthetic to geom_text() that matches the fill= aesthetic specified for geom_col().

In the case of geom_col(), you specify aes(fill=feature).  The height of the different columns is therefore grouped automatically by corr$feature.  You can supply a group= aesthetic as well, but it's unnecessary and the dodging will happen as you expect.

In the case of geom_text(), there is no obvious way to group the data.  When you do not specify a group= aesthetic, ggplot2 chooses one of the columns (in this case, the first column number) for grouping.  For dodging to work here, you need to specify how the label information is grouped.  If you don't have a specific legend-associated aesthetic to choose here, you can use the group= aesthetic to specify group=feature.  This let's ggplot2 know that the text labels should be sorted and dodged by grouping according to this column in the data:

ggplot(data=corr, aes(x=factor(dimension), y=score)) +
  geom_col(aes(fill=feature),position=position_dodge2(width=1,preserve='single')) +
  facet_grid(~`sample length`, scales='free_x',space='free_x') +
  labs(x="Dimension", y="Correlation Coefficient (Abs. value)") +
  geom_text(aes(label=measure, group=feature),position=position_dodge2(width=0.9, preserve='single'), angle=90,
            size=4,hjust=2.5,color='white')

As a side note, you don't have to specify the group= aesthetic if you assign a color-based aesthetic (or one that would result in a legend).  If we set color=feature with geom_text(), it works without group=. To see the labels, you need to set the alpha for the columns a bit lower, but this should illustrate the point well:

ggplot(data=corr, aes(x=factor(dimension), y=score)) +
  geom_col(aes(fill=feature),position=position_dodge2(width=1,preserve='single'), alpha=0.2) +
  facet_grid(~`sample length`, scales='free_x',space='free_x') +
  labs(x="Dimension", y="Correlation Coefficient (Abs. value)") +
  geom_text(aes(label=measure, color=feature),position=position_dodge2(width=0.9, preserve='single'), angle=90,
            size=4,hjust=2.5)


问:
Sorting date column in python from csv file - string indices must be integers
I have a csv file which looks like this:

```<code>Name,City,Date
"Bobby","NY","20210925"
"Henry","Boston","20210521"
"Linda","Phoenix","20201114"
</code>```

I'm trying to sort based on date:

```<code>csvfile = open(filename,'r')
data = sorted(csvfile, key = lambda row: datetime.strptime(row["Date"], "%Y%m%d"))
for row in data:
    print(row)
</code>```

However, I'm getting the error below.  Can someone tell me what I'm doing wrong? Thank you!

Message=string indices must be integers

Source=C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py
StackTrace:   File
"C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py",
line 29, in
data = sorted(csvfile, key = lambda row: datetime.strptime(row["Date"], "%Y%m%d"))   File
"C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py",
line 29, in main
data = sorted(csvfile, key = lambda row: datetime.strptime(row["Date"], "%Y%m%d"))   File
"C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py",
line 34, in  (Current frame)
main()

答:
you can use pandas pd.read_csv and it will work for you

```<code>import pandas as pd
filename = "/content/untitled"
pd.read_csv(filename)

</code>```
```<code>    Name    City    Date
0   Bobby   NY  20210925
1   Henry   Boston  20210521
2   Linda   Phoenix 20201114
</code>```

you can change the date to be in better format

```<code>Name,City,Date
"Bobby","NY","2021/09/25"
"Henry","Boston","2021/05/21"
"Linda","Phoenix","2020/11/14"

</code>```
```<code>from datetime import datetime
import pandas as pd
filename = "/content/untitled"
df = pd.read_csv(filename)
df['Date']= pd.to_datetime(df['Date'])
df
#output

    Name    City    Date
0   Bobby   NY  2021-09-25
1   Henry   Boston  2021-05-21
2   Linda   Phoenix 2020-11-14

</code>```

Body:
I have a csv file which looks like this:

Name,City,Date
"Bobby","NY","20210925"
"Henry","Boston","20210521"
"Linda","Phoenix","20201114"

I'm trying to sort based on date:

csvfile = open(filename,'r')
data = sorted(csvfile, key = lambda row: datetime.strptime(row["Date"], "%Y%m%d"))
for row in data:
    print(row)

However, I'm getting the error below.  Can someone tell me what I'm doing wrong? Thank you!

Message=string indices must be integers

Source=C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py
StackTrace:   File
"C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py",
line 29, in
data = sorted(csvfile, key = lambda row: datetime.strptime(row["Date"], "%Y%m%d"))   File
"C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py",
line 29, in main
data = sorted(csvfile, key = lambda row: datetime.strptime(row["Date"], "%Y%m%d"))   File
"C:\Users\Henry\source\repos\PythonApplication1\PythonApplication1\module1.py",
line 34, in  (Current frame)
main()

Body:
you can use pandas pd.read_csv and it will work for you

import pandas as pd
filename = "/content/untitled"
pd.read_csv(filename)

    Name    City    Date
0   Bobby   NY  20210925
1   Henry   Boston  20210521
2   Linda   Phoenix 20201114

you can change the date to be in better format

Name,City,Date
"Bobby","NY","2021/09/25"
"Henry","Boston","2021/05/21"
"Linda","Phoenix","2020/11/14"

from datetime import datetime
import pandas as pd
filename = "/content/untitled"
df = pd.read_csv(filename)
df['Date']= pd.to_datetime(df['Date'])
df
#output

    Name    City    Date
0   Bobby   NY  2021-09-25
1   Henry   Boston  2021-05-21
2   Linda   Phoenix 2020-11-14