问:
Elasticsearch Java API filter by string in array
I am trying to build an Elasticsearch bool query that filters on whether an array contains a string.

For example, one of my docs:

```<code>{
  "id": 1,
  "bar": ["foo"]
}
</code>```

What I am trying is this:

```<code>String[] matchThese = Arrays.asList("foo");
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.filter(QueryBuilders.termsQuery("bar", matchThese));
</code>```

Needless to say, this does not work - I get no results.
Is there some thing I am missing?

EDIT:

I eventually solved this using a string query in case anybody has this exact problem.

```<code>List<String> exactMatchThese = Stream.of("foo", "spam", "eggs")
    .map(str -> "\"" + str + "\"")
    .collect(Collectors.toList());
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.filter(QueryBuilders
    .queryStringQuery(String.join(" OR ", exactMatchThese))
    .field("bar"));
</code>```

答:
I was facing a similar issue.
Solved it using "QueryBuilders.MatchPhraseQuery"

For ex.

```<code>boolQueryBuilder.should(QueryBuilders.matchPhraseQuery(
              (ARRAY_FIELD),
              keyword_to_search
          ));
</code>```

Body:
I am trying to build an Elasticsearch bool query that filters on whether an array contains a string.

For example, one of my docs:

{
  "id": 1,
  "bar": ["foo"]
}

What I am trying is this:

String[] matchThese = Arrays.asList("foo");
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.filter(QueryBuilders.termsQuery("bar", matchThese));

Needless to say, this does not work - I get no results.
Is there some thing I am missing?

EDIT:

I eventually solved this using a string query in case anybody has this exact problem.

List<String> exactMatchThese = Stream.of("foo", "spam", "eggs")
    .map(str -> "\"" + str + "\"")
    .collect(Collectors.toList());
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.filter(QueryBuilders
    .queryStringQuery(String.join(" OR ", exactMatchThese))
    .field("bar"));

Body:
I was facing a similar issue.
Solved it using "QueryBuilders.MatchPhraseQuery"

For ex.

boolQueryBuilder.should(QueryBuilders.matchPhraseQuery(
              (ARRAY_FIELD),
              keyword_to_search
          ));


来源: stackexchange

问:
Why, in Ansible, I can't have same key in many children groups?
I want to make some clean stuff with my ansible hosts file.

If i use ansible-playbook --limit calendar -i hosts update_common.yml

Ansible execute my playbook on all hosts, even on hostname in other groups.

Apparently, it seems to comme from my keys dev and prod :

all:
  children:
    gitlab:
      children:
        dev:
          hosts:
            gitlab-dev:  # Stretch
        prod:
          hosts:
            gitlab-A:   # Stretch
            gitlab-B:   # Stretch
            gitlab-C.mysociety.fr:
              ansible_port: 22
    intranet:
      children:
        dev:
          hosts:
            intra-dev:      # Buster
            wordpress-dev:  # Buster
        prod:
          hosts:
            intra-prod:     # Buster
    calendar:
      children:
        dev:
          hosts:
            calendar-dev:
        prod:
          hosts:
            calendar:
```

答:
Ansible doesn't store the group's tree. The structure is a flat list of all groups. Each group comprises a cumulative list of hosts. If you run the play below

- hosts: all
  tasks:
    - debug:
        msg: "{{ groups[item] }}"
      loop: "{{ groups.keys()|list }}"
      run_once: true
```
<p>you'll see that the groups <em>gitlab</em>, <em>intranet</em>, and <em>calendar</em> are identical because they comprise all the hosts from the groups <em>dev</em> and <em>prod</em>. Next, you'll see that the group <em>dev</em> comprises all four hosts, and the group <em>prod</em> comprises all five hosts.</p>
<p>See Ansible: Intersection of two host groups using yaml inventory.</p>
<hr>
<p>Flatten the structure to achieve what you want, e.g.</p>
<pre class="lang-yaml prettyprint-override"><code>all:
  children:
    gitlab_dev:
      hosts:
        gitlab-dev:  # Stretch
    gitlab_prod:
      hosts:
        gitlab-A:   # Stretch
        gitlab-B:   # Stretch
        gitlab-C.mysociety.fr:
          ansible_port: 22
    intranet_dev:
      hosts:
        intra-dev:      # Buster
        wordpress-dev:  # Buster
    intranet_prod:
      hosts:
        intra-prod:     # Buster
    calendar_dev:
      hosts:
        calendar-dev:
    calendar_prod:
      hosts:
        calendar:
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Ansible doesn't store the group's tree. The structure is a flat list of all groups. Each group comprises a cumulative list of hosts. If you run the play below

- hosts: all
  tasks:
    - debug:
        msg: "{{ groups[item] }}"
      loop: "{{ groups.keys()|list }}"
      run_once: true

you'll see that the groups gitlab, intranet, and calendar are identical because they comprise all the hosts from the groups dev and prod. Next, you'll see that the group dev comprises all four hosts, and the group prod comprises all five hosts.

See Ansible: Intersection of two host groups using yaml inventory.

Flatten the structure to achieve what you want, e.g.

all:
  children:
    gitlab_dev:
      hosts:
        gitlab-dev:  # Stretch
    gitlab_prod:
      hosts:
        gitlab-A:   # Stretch
        gitlab-B:   # Stretch
        gitlab-C.mysociety.fr:
          ansible_port: 22
    intranet_dev:
      hosts:
        intra-dev:      # Buster
        wordpress-dev:  # Buster
    intranet_prod:
      hosts:
        intra-prod:     # Buster
    calendar_dev:
      hosts:
        calendar-dev:
    calendar_prod:
      hosts:
        calendar:


问:
Validate select field with valid using chosen-select
When validating the form, using chosen-select does not validate the selects, but removing ochosen-select already works. I show the example:

$("#validate").on("click",function(){
    if(!$(".alerta").valid());
  });

  $(".alerta").validate({
      messages: {
        Tipo: "Tipo de alerta obrigatório",
        Prioridade: {
              required: "Prioridade obrigatório"
          }
      }
  });

$(".chosen-select").chosen({
    disable_search_threshold: 5,
    no_results_text: "Sem resultados",
      placeholder_text_multiple: "Selecione opções",
    width: "100%"
});
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>

<form method="POST" class="row g-3 alerta">
  <div class="col-md-4">
    <label for="Tipo" class="form-label">TIPO DE ALERTA <span style="color: red;">*</span></label>
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option></option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>
  </div>

  <div class="col-md-4">
    <label for="Tipo" class="form-label">Prioridade <span style="color: red;">*</span></label>
    <select class="form-select" name="Prioridade" id="Prioridade" required>
    <option></option>
    <option value="1">Prioridade</option>
    <option value="2">Prioridade1</option>
    </select>
  </div>
  <div class="col-12">
    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar <i class="metismenu-icon pe-7s-paper-plane"></i></button>
  </div>
</form></code>```

In the select in which I use chosen-select, there is no value selected, but it does not show the message to the user as the field is mandatory.

答:
Chosen-select adds visibility:hidden attribute in select box.

You have to validate chosen-select forcefully.

```<code>$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
</code>```

Please add above line just before (".alerta").validate() method.

Body:
When validating the form, using chosen-select does not validate the selects, but removing ochosen-select already works. I show the example:

$("#validate").on("click",function(){
    if(!$(".alerta").valid());
  });

  $(".alerta").validate({
      messages: {
        Tipo: "Tipo de alerta obrigatório",
        Prioridade: {
              required: "Prioridade obrigatório"
          }
      }
  });

$(".chosen-select").chosen({
    disable_search_threshold: 5,
    no_results_text: "Sem resultados",
      placeholder_text_multiple: "Selecione opções",
    width: "100%"
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">

<form method="POST" class="row g-3 alerta">

    TIPO DE ALERTA *
    <select class="form-select chosen-select" name="Tipo" id="Tipo" required>
    <option></option>
    <option value="1">Teste</option>
    <option value="2">Teste1</option>
    </select>

    Prioridade *
    <select class="form-select" name="Prioridade" id="Prioridade" required>
    <option></option>
    <option value="1">Prioridade</option>
    <option value="2">Prioridade1</option>
    </select>

    <button type="button" class="btn-wide btn btn-success" style="float: right; margin-right: 5%; margin-top: 1%;" id="validate"> Enviar </button>

</form>

In the select in which I use chosen-select, there is no value selected, but it does not show the message to the user as the field is mandatory.

Body:
Chosen-select adds visibility:hidden attribute in select box.

You have to validate chosen-select forcefully.

$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })

Please add above line just before (".alerta").validate() method.


问:
Adding 2 IconButtons next to the image
I'm having a problem with my project. I need confirmation from the user for the location of this image. I want to make an object like this, would you be an investor?enter image description here</p>

答:
It could be coded like this. And see working example try it out! </p>
```<code>Column(children: [
  Container(
    padding: EdgeInsets.all(10),
    child: Text('Here Image'),
    color: Colors.orangeAccent,
  ),
  Row(
    children: [
      Container(
        padding: EdgeInsets.all(10),
        child: Text('First Button'),
        color: Colors.orangeAccent,
      ),
      Container(
        padding: EdgeInsets.all(10),
        child: Text('Second Button'),
        color: Colors.orangeAccent,
      ),
    ],
    mainAxisAlignment: MainAxisAlignment.center,
    mainAxisSize: MainAxisSize.min,
  )
])
</code>```

Title: Adding 2 IconButtons next to the image

Body:
It could be coded like this. And see working example try it out!

Column(children: [
  Container(
    padding: EdgeInsets.all(10),
    child: Text('Here Image'),
    color: Colors.orangeAccent,
  ),
  Row(
    children: [
      Container(
        padding: EdgeInsets.all(10),
        child: Text('First Button'),
        color: Colors.orangeAccent,
      ),
      Container(
        padding: EdgeInsets.all(10),
        child: Text('Second Button'),
        color: Colors.orangeAccent,
      ),
    ],
    mainAxisAlignment: MainAxisAlignment.center,
    mainAxisSize: MainAxisSize.min,
  )
])


问:
Call to undefined function Intervention\Image\Gd\imagecreatefromjpeg() Laravel 8 + Docker desktop 4.4.4
This is my docker file:

```<code>FROM php:8.0-fpm-buster

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    git \
    curl \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libjpeg62-turbo-dev \
    jpegoptim optipng pngquant gifsicle \
    libonig-dev \
    libxml2-dev \
    zip \
    sudo \
    unzip \
    npm \
    nodejs \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
</code>```

but I have an error

Call to undefined function Intervention\Image\Gd\imagecreatefromjpeg()

when i try to upload a jpg image.Even I change it to:

```<code>docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-gd --with-freetype --with-jpeg \
</code>```

but I have below error when I build and the above error in Laravel

configure: error: unrecognized options: --with-freetype-dir,
--with-jpeg-dir, --with-gd
------ failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c apt-get update && apt-get install -y

build-essential     git     curl     libpng-dev     libjpeg-dev

libfreetype6-dev     libjpeg62-turbo-dev     jpegoptim optipng
pngquant gifsicle     libonig-dev     libxml2-dev     zip     sudo

unzip     npm     nodejs     && docker-php-ext-configure gd
--with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-gd --with-freetype --with-jpeg     && docker-php-ext-install -j$(nproc) gd]: exit code: 1

how can I fix this?

答:
I fix it by enabling the GD lib,
here is my Dockerfile configs:</p>
```<code>FROM php:8.0-fpm-buster

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    git \
    curl \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libjpeg62-turbo-dev \
    libmcrypt-dev \
    libgd-dev \
    jpegoptim optipng pngquant gifsicle \
    libonig-dev \
    libxml2-dev \
    zip \
    sudo \
    unzip \
    npm \
    nodejs

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-configure gd --enable-gd --with-freetype --with-jpeg
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd
</code>```

Body:
This is my docker file:

FROM php:8.0-fpm-buster

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    git \
    curl \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libjpeg62-turbo-dev \
    jpegoptim optipng pngquant gifsicle \
    libonig-dev \
    libxml2-dev \
    zip \
    sudo \
    unzip \
    npm \
    nodejs \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

but I have an error

Call to undefined function Intervention\Image\Gd\imagecreatefromjpeg()

when i try to upload a jpg image.Even I change it to:

docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-gd --with-freetype --with-jpeg \

but I have below error when I build and the above error in Laravel

configure: error: unrecognized options: --with-freetype-dir,
--with-jpeg-dir, --with-gd
------ failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c apt-get update && apt-get install -y

build-essential     git     curl     libpng-dev     libjpeg-dev

libfreetype6-dev     libjpeg62-turbo-dev     jpegoptim optipng
pngquant gifsicle     libonig-dev     libxml2-dev     zip     sudo

unzip     npm     nodejs     && docker-php-ext-configure gd
--with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-gd --with-freetype --with-jpeg     && docker-php-ext-install -j$(nproc) gd]: exit code: 1

how can I fix this?

Body:
I fix it by enabling the GD lib,
here is my Dockerfile configs:

FROM php:8.0-fpm-buster

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    git \
    curl \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libjpeg62-turbo-dev \
    libmcrypt-dev \
    libgd-dev \
    jpegoptim optipng pngquant gifsicle \
    libonig-dev \
    libxml2-dev \
    zip \
    sudo \
    unzip \
    npm \
    nodejs

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-configure gd --enable-gd --with-freetype --with-jpeg
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd


问:
Flutter - auto_route _CustomNavigatorState error
I'm using the auto_route package in order to route my app and until 2 days ago everything worked just fine, until now.
For some reason, I'm getting the following error.

SYSTEM:

flutter: 1.22

dart: 2.10.0

auto_route: ^0.6.7

ERROR:

```<code>../../.pub-cache/hosted/pub.dartlang.org/custom_navigator-0.3.0/lib/custom_navigator.dart:60:7: Error: The non-abstract class '_CustomNavigatorState' is missing implementations for these members:
 - WidgetsBindingObserver.didPushRouteInformation
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

class _CustomNavigatorState extends State<CustomNavigator>
      ^^^^^^^^^^^^^^^^^^^^^
/opt/flutter/packages/flutter/lib/src/widgets/binding.dart:122:16: Context: 'WidgetsBindingObserver.didPushRouteInformation' is defined here.
  Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
</code>```

main.dart

```<code>import 'package:device_simulator/device_simulator.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'Test.gr.dart' as r;
void main() => runApp(MyApp());

const bool debugEnableDeviceSimulator = true;

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    builder: ExtendedNavigator.builder<r.Router>(
      router: r.Router(),
      builder: (context, extendedNav) => DeviceSimulator(
        enable: debugEnableDeviceSimulator,
        child:
            Scaffold(body: extendedNav, backgroundColor: Colors.red ),
      ),
    ),
    );
  }
}
</code>```

Also, I should mention, because of some update of flutter I guess, now I need to use r.Router instead of just Router.

Test.dart

```<code>import 'package:auto_route/auto_route_annotations.dart';

@MaterialAutoRouter(
  routes: <AutoRoute>[],
)
class $Router {}
</code>```

And also if has any importance here it's the generated file

Test.gr.dart

```<code>// GENERATED CODE - DO NOT MODIFY BY HAND

// **************************************************************************
// AutoRouteGenerator
// **************************************************************************

// ignore_for_file: public_member_api_docs

import 'package:auto_route/auto_route.dart';

class Routes {
  static const all = <String>{};
}

class Router extends RouterBase {
  @override
  List<RouteDef> get routes => _routes;
  final _routes = <RouteDef>[];
  @override
  Map<Type, AutoRouteFactory> get pagesMap => _pagesMap;
  final _pagesMap = <Type, AutoRouteFactory>{};
}
</code>```

Do you have any idea what's going one here or how can I fix this? Or if I can't fix this, what can I use instead of the auto_route package which will offer me the same benefice?

答:
Find the place where the error is generating. Add the following function below there. I did the same and my problem is solved.</p>
```<code>Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
return didPushRoute(routeInformation.location);
}
</code>```

Body:
I'm using the auto_route package in order to route my app and until 2 days ago everything worked just fine, until now.
For some reason, I'm getting the following error.

SYSTEM:

flutter: 1.22

dart: 2.10.0

auto_route: ^0.6.7

ERROR:

../../.pub-cache/hosted/pub.dartlang.org/custom_navigator-0.3.0/lib/custom_navigator.dart:60:7: Error: The non-abstract class '_CustomNavigatorState' is missing implementations for these members:
 - WidgetsBindingObserver.didPushRouteInformation
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

class _CustomNavigatorState extends State<CustomNavigator>
      ^^^^^^^^^^^^^^^^^^^^^
/opt/flutter/packages/flutter/lib/src/widgets/binding.dart:122:16: Context: 'WidgetsBindingObserver.didPushRouteInformation' is defined here.
  Future<bool> didPushRouteInformation(RouteInformation routeInformation) {

main.dart

import 'package:device_simulator/device_simulator.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'Test.gr.dart' as r;
void main() => runApp(MyApp());

const bool debugEnableDeviceSimulator = true;

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    builder: ExtendedNavigator.builder<r.Router>(
      router: r.Router(),
      builder: (context, extendedNav) => DeviceSimulator(
        enable: debugEnableDeviceSimulator,
        child:
            Scaffold(body: extendedNav, backgroundColor: Colors.red ),
      ),
    ),
    );
  }
}

Also, I should mention, because of some update of flutter I guess, now I need to use r.Router instead of just Router.

Test.dart

import 'package:auto_route/auto_route_annotations.dart';

@MaterialAutoRouter(
  routes: <AutoRoute>[],
)
class $Router {}

And also if has any importance here it's the generated file

Test.gr.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

// **************************************************************************
// AutoRouteGenerator
// **************************************************************************

// ignore_for_file: public_member_api_docs

import 'package:auto_route/auto_route.dart';

class Routes {
  static const all = <String>{};
}

class Router extends RouterBase {
  @override
  List<RouteDef> get routes => _routes;
  final _routes = <RouteDef>[];
  @override
  Map<Type, AutoRouteFactory> get pagesMap => _pagesMap;
  final _pagesMap = <Type, AutoRouteFactory>{};
}

Do you have any idea what's going one here or how can I fix this? Or if I can't fix this, what can I use instead of the auto_route package which will offer me the same benefice?

Body:
Find the place where the error is generating. Add the following function below there. I did the same and my problem is solved.

Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
return didPushRoute(routeInformation.location);
}


问:
How to reference to packages from Maven local repository?
In my project I need to reference to the package installed by Maven to local repository. I've added the dependency to pom.xml, but the project doesn't want to build as it wouldn't even see the package. Here's the pom.xml fragment with dependencies:

```<code><dependencies>
  ...
  <dependency>
    <groupId>libraryweb</groupId>
    <artifactId>classes</artifactId>
    <version>1.0SNAPSHOT</version>
  </dependency>
</dependencies>
</code>```

When I try to import the package "libraryweb" I get

Cannot resolve symbol 'libraryweb'

error. What can I do to use the package?

Edit: Intellij prompts me classes from the package when I try to use them, but I still get "cannot resolve symbol" error.

答: I solved the problem by linking the .jar file with IntelliJ projects settings instead of using Maven to do it.</p>

Body:
In my project I need to reference to the package installed by Maven to local repository. I've added the dependency to pom.xml, but the project doesn't want to build as it wouldn't even see the package. Here's the pom.xml fragment with dependencies:

<dependencies>
  ...
  <dependency>
    <groupId>libraryweb</groupId>
    <artifactId>classes</artifactId>
    <version>1.0SNAPSHOT</version>
  </dependency>
</dependencies>

When I try to import the package "libraryweb" I get

Cannot resolve symbol 'libraryweb'

error. What can I do to use the package?

Edit: Intellij prompts me classes from the package when I try to use them, but I still get "cannot resolve symbol" error.


问:
ElasticSearch date format to get last Sunday
I know for ES now means today

Is there any way to get last Sunday using some combination of now?

Context: We use Kibana and want to create a dashboard with a filter such that everyday it shows data for date ranges from last Sunday to today.

答:
You can simply use below range query:

Here, now/w will give result from Monday to today and now/w-1d will give result from Sunday to today.

POST timeindex/_search
{
  "query": {
    "range": {
      "timestamp": {
        "gte": "now/w-1d"
      }
    }
  }
}
```


问:
How to adjust Bulma Column height when one changes?
is it possible to make a column adjust its height when others change?
I have all columns at the same height using flex but when I change one of them dynamically, the others stay the same...
Any way to fix that?

Thanks!!

答:
You can add a specific class to those components and add that class onChange using js and make sure to have the css for that class.
Happy Programming!</p>


问:
Good references for ARIA use?
Does anyone have any trusted references for ARIA use? I'm looking for something to base my markup on, but can't really find that many examples from trusted sources.

Right now I'm pretty much going from the ARIA spec and from this site, but would love a couple more good references to make sure I'm doing this correctly.

答: Try http://dev.opera.com/articles/view/introduction-to-wai-aria/ and http://www.w3.org/TR/wai-aria-practices/</p>

ContentLicense: CC BY-SA 3.0

Title: Good references for ARIA use?


问:
How do I stop contents of my ListView extending beyond its boundaries when scrolling in Flutter?
I have a strange problem with a ListView in my Flutter app.

I have a ListView sitting within a SizedBox of 220 pixels height. When the list items exceed the available height, then they bleed over into surrounding screen elements.

Weirdly there is ONE property of the ListTile's that DO clip and that's the title! but everything else, the color and shape etc... bleeds into the rest of the screen so I get a load of blue boxes extending beyond my container.

Can anyone advise how I can have the ENTIRE ListTile clip when it meets the edge of its container?

Please reference the screenshot to see what I mean and i'll paste my code below the image

Here's my build method...

```<code>    @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.transparent,
          leading: const CloseButton(),
          actions: [
            ElevatedButton.icon(
              label: const Text('SAVE'),
              icon: const Icon(Icons.done),
              onPressed: () async {
                Navigator.pop(context);
                widget.resolution?.wasSaved = true;
                setState(() {
                  resolution.title = titleController.text;
                });
                widget.onSaved(resolution);
              },
              style: ElevatedButton.styleFrom(
                primary: Colors.transparent,
                elevation: 0,
              ),
            ),
          ],
        ),
        body: Container(
          // height: size.height,
          padding: const EdgeInsets.all(12),
          child: Column(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('RESOLUTION', style: kInputFieldHeader),
                  const SizedBox(height: 4),
                  Card(
                    elevation: 2,
                    child: TextFormField(
                      style: kInputFieldText,
                      controller: titleController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          suffixIcon: titleController.text.isEmpty
                              ? Container(
                                  width: 0,
                                )
                              : IconButton(
                                  onPressed: () => titleController.clear(),
                                  icon: Icon(Icons.close))),
                      onFieldSubmitted: (fieldText) {
                        setState(() {
                          resolution.title = fieldText;
                        });
                        ;
                      },
                      validator: (value) => value != null && value.isEmpty
                          ? 'Please enter something'
                          : null,
                    ),
                  ),
                  DatePickers(
                    resolution: resolution,
                    startDateCallback: (startDate) {
                      setState(() {
                        resolution.startDate = startDate;
                      });
                    },
                    endDateCallback: (endDate) {
                      setState(() {
                        resolution.endDate = endDate;
                      });
                    },
                  ),
                  CustomColorPicker(
                    resolution: resolution,
                    colorCallback: (color) =>
                        setState(() => resolution.color = color),
                  ),
                  CustomProgressIndicator(
                      resolution: resolution, isCommitment: false),
                ],
              ),
              Expanded(
                child: Stack(
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text('COMMITMENTS', style: kInputFieldHeader),
                        const SizedBox(height: 10),
                        Expanded(
                          child: SizedBox(
                            height: 220,
                            child: Container(
                              child: commitments.isNotEmpty
                                  ? _buildCommitmentsList()
                                  : _buildEmptyCommitments(),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                border:
                                    Border.all(width: 1, color: Colors.grey),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Positioned(
                        bottom: 10,
                        right: 10,
                        child: FloatingActionButton(
                            heroTag: const Text('newCommitment'),
                            child: const Icon(Icons.add, size: 30),
                            onPressed: () => _commitmentScreenNew())),
                  ],
                ),
              ),
              TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    widget.onDeleted(resolution);
                  },
                  child: const Text(
                    'DELETE RESOLUTION',
                  )),
            ],
          ),
        ),
      ),
    );
  }
</code>```

And here's the listView builder method...

```<code>  _buildCommitmentsList() {
    return ListView.builder(
      itemCount: commitments.length,
      physics: const BouncingScrollPhysics(),
      itemBuilder: (context, index) {
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
          child: ListTile(
            title: Text(commitments[index].description),
            tileColor: resolution.color,
            onTap: () => _commitmentScreenEdit(commitments[index]),
            onLongPress: () => _removeCommitment(commitments[index]),
          ),
        );
      },
    );
  }
</code>```

Any help would be greatly appreciated :)

答: Just for the record, I eventually resolved this by replacing the ListTiles with coloured containers.</p>

Body:
I have a strange problem with a ListView in my Flutter app.

I have a ListView sitting within a SizedBox of 220 pixels height. When the list items exceed the available height, then they bleed over into surrounding screen elements.

Weirdly there is ONE property of the ListTile's that DO clip and that's the title! but everything else, the color and shape etc... bleeds into the rest of the screen so I get a load of blue boxes extending beyond my container.

Can anyone advise how I can have the ENTIRE ListTile clip when it meets the edge of its container?

Please reference the screenshot to see what I mean and i'll paste my code below the image

Here's my build method...

    @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.transparent,
          leading: const CloseButton(),
          actions: [
            ElevatedButton.icon(
              label: const Text('SAVE'),
              icon: const Icon(Icons.done),
              onPressed: () async {
                Navigator.pop(context);
                widget.resolution?.wasSaved = true;
                setState(() {
                  resolution.title = titleController.text;
                });
                widget.onSaved(resolution);
              },
              style: ElevatedButton.styleFrom(
                primary: Colors.transparent,
                elevation: 0,
              ),
            ),
          ],
        ),
        body: Container(
          // height: size.height,
          padding: const EdgeInsets.all(12),
          child: Column(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('RESOLUTION', style: kInputFieldHeader),
                  const SizedBox(height: 4),
                  Card(
                    elevation: 2,
                    child: TextFormField(
                      style: kInputFieldText,
                      controller: titleController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          suffixIcon: titleController.text.isEmpty
                              ? Container(
                                  width: 0,
                                )
                              : IconButton(
                                  onPressed: () => titleController.clear(),
                                  icon: Icon(Icons.close))),
                      onFieldSubmitted: (fieldText) {
                        setState(() {
                          resolution.title = fieldText;
                        });
                        ;
                      },
                      validator: (value) => value != null && value.isEmpty
                          ? 'Please enter something'
                          : null,
                    ),
                  ),
                  DatePickers(
                    resolution: resolution,
                    startDateCallback: (startDate) {
                      setState(() {
                        resolution.startDate = startDate;
                      });
                    },
                    endDateCallback: (endDate) {
                      setState(() {
                        resolution.endDate = endDate;
                      });
                    },
                  ),
                  CustomColorPicker(
                    resolution: resolution,
                    colorCallback: (color) =>
                        setState(() => resolution.color = color),
                  ),
                  CustomProgressIndicator(
                      resolution: resolution, isCommitment: false),
                ],
              ),
              Expanded(
                child: Stack(
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text('COMMITMENTS', style: kInputFieldHeader),
                        const SizedBox(height: 10),
                        Expanded(
                          child: SizedBox(
                            height: 220,
                            child: Container(
                              child: commitments.isNotEmpty
                                  ? _buildCommitmentsList()
                                  : _buildEmptyCommitments(),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                border:
                                    Border.all(width: 1, color: Colors.grey),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Positioned(
                        bottom: 10,
                        right: 10,
                        child: FloatingActionButton(
                            heroTag: const Text('newCommitment'),
                            child: const Icon(Icons.add, size: 30),
                            onPressed: () => _commitmentScreenNew())),
                  ],
                ),
              ),
              TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    widget.onDeleted(resolution);
                  },
                  child: const Text(
                    'DELETE RESOLUTION',
                  )),
            ],
          ),
        ),
      ),
    );
  }

And here's the listView builder method...

  _buildCommitmentsList() {
    return ListView.builder(
      itemCount: commitments.length,
      physics: const BouncingScrollPhysics(),
      itemBuilder: (context, index) {
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
          child: ListTile(
            title: Text(commitments[index].description),
            tileColor: resolution.color,
            onTap: () => _commitmentScreenEdit(commitments[index]),
            onLongPress: () => _removeCommitment(commitments[index]),
          ),
        );
      },
    );
  }

Any help would be greatly appreciated :)


问:
C# Make Assert Print Expression Being Asserted
When Debug.Assert fails, it shows a very unhelpful error:
Assertion failed

This can be improved to get at least some information about the location of the error, like function name, file, and line number like this:

```<code>public static void MyAssert(bool expr,
    [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
    [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
    [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    string message = $"Assertion failed in {memberName} ({sourceFilePath}:{sourceLineNumber})";
    Debug.Assert(expr, message);
}
</code>```

This helps, but what would be really cool was to be able to see the expression the caller wanted to assert, something like this:

```<code>public static void MyAssert(bool expr,
    [PreviousCallerArgumentAsString] string argument)  /* wish this worked */
{
    string message = $"Assertion '{argument}' failed";
    Debug.Assert(expr, message);
}
</code>```

I am just transitioning to C# but in C++ this could be done using a macro like this:

```<code>#define ASSERT(Expr) Debug.Assert(Expr, "Assertion " #Expr " failed.")

ASSERT(1 + 1 == 3);
/* would expand to */
Debug.Assert(1 + 1 == 3, "Assertion 1 + 1 == 3 failed.");
</code>```

In my code, I use asserts pretty liberally and having to retype the expression slows you down a ton.

Is there a way something like this could be achieved in C#?

答:
You're in luck! This functionality was implemented in C# 10, using [CallerArgumentExpression].

For example:

```<code>public static class Debug
{
    public static void Assert(bool condition, [CallerArgumentExpression("condition")] string message = null)
    {
        if (!condition)
        {
            Console.WriteLine($"Assert failed! {message}");
        }
    }
}
</code>```

When used with:

```<code>Debug.Assert(true == false);
</code>```

Prints:

Assert failed! true == false

See it on SharpLab.

Body:
When Debug.Assert fails, it shows a very unhelpful error:
Assertion failed

This can be improved to get at least some information about the location of the error, like function name, file, and line number like this:

public static void MyAssert(bool expr,
    [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
    [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
    [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    string message = $"Assertion failed in {memberName} ({sourceFilePath}:{sourceLineNumber})";
    Debug.Assert(expr, message);
}

This helps, but what would be really cool was to be able to see the expression the caller wanted to assert, something like this:

public static void MyAssert(bool expr,
    [PreviousCallerArgumentAsString] string argument)  /* wish this worked */
{
    string message = $"Assertion '{argument}' failed";
    Debug.Assert(expr, message);
}

I am just transitioning to C# but in C++ this could be done using a macro like this:

#define ASSERT(Expr) Debug.Assert(Expr, "Assertion " #Expr " failed.")

ASSERT(1 + 1 == 3);
/* would expand to */
Debug.Assert(1 + 1 == 3, "Assertion 1 + 1 == 3 failed.");

In my code, I use asserts pretty liberally and having to retype the expression slows you down a ton.

Is there a way something like this could be achieved in C#?

Body:
You're in luck! This functionality was implemented in C# 10, using [CallerArgumentExpression].

For example:

public static class Debug
{
    public static void Assert(bool condition, [CallerArgumentExpression("condition")] string message = null)
    {
        if (!condition)
        {
            Console.WriteLine($"Assert failed! {message}");
        }
    }
}

When used with:

Debug.Assert(true == false);

Prints:

Assert failed! true == false

See it on SharpLab.


问:
Silverstripe 4 save variable in database
Is posible to save SS template variable in database from CMS  and after execute it in template?

Okay lets see example:
In CMS i have settings where i put social media links and contact informatios.
Also in CMS i have module where i create HTML block-s which after that i loop in website.

In that html block i want to put existing $SiteConfig.Email variable.

I Try that but that is rendered in template like $SiteConfig.Email not show real email?

Is this posible to do or i need some extra modification?

Check photo

答:
The question you have written makes no sense to me, but I understand the screenshot.

So, SilverStripe renders .ss files with a class called SSViewer. Basically it reads the file as string and then runs it through SSViewer to generate the HTML output.

But, as you saw, the output of variables is not processed.

I can think of 3 ways to get what you want:

Run the variables through SSViewer aswell (in this example, use $RenderedHTMLContent in the template)

class MyDataObject extends DataObject {
  private static array $db = [
    'Title' => DBVarchar::class,
    'HTMLContent' => DBText::class,
  ];

  public function Foobar() { return "hello from foobar"; }

  public function RenderedHTMLContent() {
    $template = \SilverStripe\View\SSViewer::fromString($this->HTMLContent);
    // using $this->renderWith() will allow you access to all things of $this in the template. so eg $ID, $Title or $Foobar. Probably also $SiteConfig because it's global
    return $this->renderWith($template);
    // if you want to add extra variables that are not part of $this, you can also do:
    return $this->renderWith($template, ["ExtraVariable" => "Hello from extra variable"]);
    // if you do not want $this, you can do:
    return (new ArrayData(["MyVariable" => "my value"]))->renderWith($template);
  }
}
```
<p><strong>Please be aware of the security implications this thing brings. SilverStripe is purposely built to not allow content authors to write template files. A content author can not only call the currently scoped object but also all global template variables. This includes $SiteConfig, $List, .... Therefore a "bad" content author can write a template like <code><% loop $List('SilverStripe\Security\Member') %>$ID $FirstName $LastName $Email $Salt $Password<% end_loop %></code> or perhaps might access methods that have file access. So only do this if you trust your content authors</strong></p>
<ol start="2">
<li><p>Use shortcodes instead of variables. But I never liked shortcodes, so I don't remember how they work. You'll have to lookup the docs for that.</p>
</li>
<li><p>Build your own mini template system with str_replace.</p>
</li>
</ol>
<pre class="lang-php prettyprint-override"><code>class MyDataObject extends DataObject {
  private static array $db = [
    'Title' => DBVarchar::class,
    'HTMLContent' => DBText::class,
  ];

  public function Foobar() { return "hello from foobar"; }

  public function RenderedHTMLContent() {
    return str_replace(
       [
         '$SiteConfig.Title',
         '$SiteConfig.Tagline',
         '$Title',
         '$Foobar',
       ],
       [
         SiteConfig::current_site_config()->Title,
         SiteConfig::current_site_config()->Tagline,
         $this->Title,
         $this->Foobar(),
       ],
       $this->HTMLContent
    );
  }
}
</code>```

Body:
The question you have written makes no sense to me, but I understand the screenshot.

So, SilverStripe renders .ss files with a class called SSViewer. Basically it reads the file as string and then runs it through SSViewer to generate the HTML output.

But, as you saw, the output of variables is not processed.

I can think of 3 ways to get what you want:

Run the variables through SSViewer aswell (in this example, use $RenderedHTMLContent in the template)

class MyDataObject extends DataObject {
  private static array $db = [
    'Title' => DBVarchar::class,
    'HTMLContent' => DBText::class,
  ];

  public function Foobar() { return "hello from foobar"; }

  public function RenderedHTMLContent() {
    $template = \SilverStripe\View\SSViewer::fromString($this->HTMLContent);
    // using $this->renderWith() will allow you access to all things of $this in the template. so eg $ID, $Title or $Foobar. Probably also $SiteConfig because it's global
    return $this->renderWith($template);
    // if you want to add extra variables that are not part of $this, you can also do:
    return $this->renderWith($template, ["ExtraVariable" => "Hello from extra variable"]);
    // if you do not want $this, you can do:
    return (new ArrayData(["MyVariable" => "my value"]))->renderWith($template);
  }
}

Please be aware of the security implications this thing brings. SilverStripe is purposely built to not allow content authors to write template files. A content author can not only call the currently scoped object but also all global template variables. This includes $SiteConfig, $List, .... Therefore a "bad" content author can write a template like <% loop $List('SilverStripe\Security\Member') %>$ID $FirstName $LastName $Email $Salt $Password<% end_loop %> or perhaps might access methods that have file access. So only do this if you trust your content authors

Use shortcodes instead of variables. But I never liked shortcodes, so I don't remember how they work. You'll have to lookup the docs for that.

Build your own mini template system with str_replace.

class MyDataObject extends DataObject {
  private static array $db = [
    'Title' => DBVarchar::class,
    'HTMLContent' => DBText::class,
  ];

  public function Foobar() { return "hello from foobar"; }

  public function RenderedHTMLContent() {
    return str_replace(
       [
         '$SiteConfig.Title',
         '$SiteConfig.Tagline',
         '$Title',
         '$Foobar',
       ],
       [
         SiteConfig::current_site_config()->Title,
         SiteConfig::current_site_config()->Tagline,
         $this->Title,
         $this->Foobar(),
       ],
       $this->HTMLContent
    );
  }
}


问:
How to use virtual on a nested field in mongoose
I am using mongoose in node.js. I have the following Schema.

```<code>const CustomerSchema = new mongoose.Schema({
    ...
    email: {
        type: String,
        required: true,
        lowercase: true,
        trim: true
    },
    addresses: [
        {
            addressType: {
                type: String,
                enum: [ 'personal', 'shipping', 'billing' ]
            },
            street: {
                type: String,
                required: true,
                trim: true
            },
            streetNumber: {
                type: String,
                trim: true
            },
            floor: {
                type: String,
                trim: true
            },
            apartament: {
                type: String,
                trim: true
            },
            cp: {
                type: String,
                required: true,
                trim: true
            },
            district: {
                type: String,
                trim: true
            },
            city: {
                type: mongoose.Schema.ObjectId,
                ref: 'City',
                required: true
            }
        }
    ]

});
</code>```

I want to use "virtuals" to "add" a new field in every object in the array addresses?

How I can do this using virtuals? Is it possible?

I can achieve the same result using, but I would like to use virtuals.

```<code>const customerDB = await Customer.findById(idCustomer).lean()

        customerDB.addresses = customerDB.addresses.map((address) => ({
            ...address,
            addressDesc: mapTypeAddressDescription(address.addressType)
        }));

</code>```

Many Thanks!

答:
As the name suggests virtuals are not added to the MongoDB documents. They are used for computed properties on documents.

Suppose you have a User model. Every user has an email, but you also want the email's domain. For example, the domain portion of 'test@gmail.com' is 'gmail.com'.

Below is one way to implement the domain property using a virtual. You define virtuals on a schema using the Schema#virtual() function.

```<code>const userSchema = mongoose.Schema({
  email: String
});
// Create a virtual property `domain` that's computed from `email`.
userSchema.virtual('domain').get(function() {
  return this.email.slice(this.email.indexOf('@') + 1);
});
const User = mongoose.model('User', userSchema);

let doc = await User.create({ email: 'test@gmail.com' });
// `domain` is now a property on User documents.
doc.domain; // 'gmail.com'
</code>```

You should check the documentation for more details.

You can do something like this:

```<code>CustomerSchema.path('addresses').schema.virtual('fullAddr').get(function() {
  return 'foo'
})
</code>```

Also, it is useful to check this answer on stackoverflow if the above one doesn't work.

Body:
I am using mongoose in node.js. I have the following Schema.

const CustomerSchema = new mongoose.Schema({
    ...
    email: {
        type: String,
        required: true,
        lowercase: true,
        trim: true
    },
    addresses: [
        {
            addressType: {
                type: String,
                enum: [ 'personal', 'shipping', 'billing' ]
            },
            street: {
                type: String,
                required: true,
                trim: true
            },
            streetNumber: {
                type: String,
                trim: true
            },
            floor: {
                type: String,
                trim: true
            },
            apartament: {
                type: String,
                trim: true
            },
            cp: {
                type: String,
                required: true,
                trim: true
            },
            district: {
                type: String,
                trim: true
            },
            city: {
                type: mongoose.Schema.ObjectId,
                ref: 'City',
                required: true
            }
        }
    ]

});

I want to use "virtuals" to "add" a new field in every object in the array addresses?

How I can do this using virtuals? Is it possible?

I can achieve the same result using, but I would like to use virtuals.

const customerDB = await Customer.findById(idCustomer).lean()

        customerDB.addresses = customerDB.addresses.map((address) => ({
            ...address,
            addressDesc: mapTypeAddressDescription(address.addressType)
        }));

Many Thanks!

Body:
As the name suggests virtuals are not added to the MongoDB documents. They are used for computed properties on documents.

Suppose you have a User model. Every user has an email, but you also want the email's domain. For example, the domain portion of 'test@gmail.com' is 'gmail.com'.

Below is one way to implement the domain property using a virtual. You define virtuals on a schema using the Schema#virtual() function.

const userSchema = mongoose.Schema({
  email: String
});
// Create a virtual property `domain` that's computed from `email`.
userSchema.virtual('domain').get(function() {
  return this.email.slice(this.email.indexOf('@') + 1);
});
const User = mongoose.model('User', userSchema);

let doc = await User.create({ email: 'test@gmail.com' });
// `domain` is now a property on User documents.
doc.domain; // 'gmail.com'

You should check the documentation for more details.

You can do something like this:

CustomerSchema.path('addresses').schema.virtual('fullAddr').get(function() {
  return 'foo'
})

Also, it is useful to check this answer on stackoverflow if the above one doesn't work.


问:
layout gets chopped off in a lower resolution screen
In my android app, I have a RelativeLayout with listview and 4 buttons in the bottom. Selecting any item in a listview will make four hidden buttons visible. I have followed the best practices from the http://developer.android.com/guide/practices/screens_support.html. It works fine in the emulator for WVGA800 and in the actual device. I was in a process of testing my app on different screen size. Looks like for QVGA(240x320), the buttons in the bottom gets chopped off.
Here is the xml

```<code><?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout android:id="@+id/listViewrelativeLayout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"  >
  <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/info_tv_id" android:textSize="10sp" android:layout_marginLeft="10dip"></TextView>
  <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:choiceMode="singleChoice" android:layout_marginTop="25dip" android:layout_below="@id/info_tv_id">
  </ListView>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="bottom" android:layout_alignParentBottom="true" android:id="@+id/relativekeybuttons" android:layout_below="@+id/listView1" android:visibility="gone">"
               <Button android:id="@+id/setasdefault" android:text="@string/default_btn_text" android:layout_marginTop="10dip"
                android:layout_height="50sp" android:layout_width="75sp">
               </Button>
               <Button android:id="@+id/changepassphrase" android:layout_marginTop="10dip" android:text="@string/passphrase_btn_text" android:layout_width="75sp" android:layout_height="50sp"
                android:layout_toRightOf="@+id/setasdefault"></Button>
               <Button android:id="@+id/rename" android:text="@string/rename_btn_text" android:layout_marginTop="10dip" android:layout_width="75sp"  android:layout_height="50sp"
                android:layout_toRightOf="@+id/changepassphrase"></Button>
               <Button android:id="@+id/delete" android:layout_width="75sp" android:layout_marginTop="10dip" android:layout_height="50sp" android:text="@string/delete_btn_text"
               android:layout_toRightOf="@+id/rename"></Button>
  </RelativeLayout>
</RelativeLayout>
</code>```

Also, I want the listview to occupy a fixed length in the layout. Eg: atleast 70% of the screen, so that the length of the listview is not dependent on the items in the listview.

Thanks in advance

答:
I have some modifications to ur layout. This might work.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/listViewrelativeLayout"
    android:orientation="vertical">
    <TextView android:layout_height="wrap_content" android:layout_width="fill_parent"
        android:id="@+id/info_tv_id" android:text="Click Me" android:textSize="18sp"
        android:layout_marginLeft="10dip" android:gravity="center"/>
    <FrameLayout android:layout_width="fill_parent" android:layout_height="0dip"
        android:layout_weight="1.0">
        <ListView android:id="@+id/listView1" android:layout_width="fill_parent"
            android:layout_height="fill_parent" android:choiceMode="singleChoice"
            android:layout_below="@id/info_tv_id"/>
        <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:id="@+id/relativekeybuttons" android:orientation="horizontal"
            android:layout_gravity="bottom" android:visibility="gone">
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Default" android:layout_marginLeft="1dip"
                android:textSize="11sp"/>
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Passphrase"
                android:textSize="11sp"/>
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Rename"
                android:textSize="11sp"/>
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Delete" android:layout_marginRight="1dip"
                android:textSize="11sp"/>
        </LinearLayout>
    </FrameLayout>
</LinearLayout>
</code>```

Try not to use exact width and heights as it might not work on all phones.

Body:
In my android app, I have a RelativeLayout with listview and 4 buttons in the bottom. Selecting any item in a listview will make four hidden buttons visible. I have followed the best practices from the http://developer.android.com/guide/practices/screens_support.html. It works fine in the emulator for WVGA800 and in the actual device. I was in a process of testing my app on different screen size. Looks like for QVGA(240x320), the buttons in the bottom gets chopped off.
Here is the xml

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout android:id="@+id/listViewrelativeLayout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"  >
  <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/info_tv_id" android:textSize="10sp" android:layout_marginLeft="10dip"></TextView>
  <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:choiceMode="singleChoice" android:layout_marginTop="25dip" android:layout_below="@id/info_tv_id">
  </ListView>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="bottom" android:layout_alignParentBottom="true" android:id="@+id/relativekeybuttons" android:layout_below="@+id/listView1" android:visibility="gone">"
               <Button android:id="@+id/setasdefault" android:text="@string/default_btn_text" android:layout_marginTop="10dip"
                android:layout_height="50sp" android:layout_width="75sp">
               </Button>
               <Button android:id="@+id/changepassphrase" android:layout_marginTop="10dip" android:text="@string/passphrase_btn_text" android:layout_width="75sp" android:layout_height="50sp"
                android:layout_toRightOf="@+id/setasdefault"></Button>
               <Button android:id="@+id/rename" android:text="@string/rename_btn_text" android:layout_marginTop="10dip" android:layout_width="75sp"  android:layout_height="50sp"
                android:layout_toRightOf="@+id/changepassphrase"></Button>
               <Button android:id="@+id/delete" android:layout_width="75sp" android:layout_marginTop="10dip" android:layout_height="50sp" android:text="@string/delete_btn_text"
               android:layout_toRightOf="@+id/rename"></Button>
  </RelativeLayout>
</RelativeLayout>

Also, I want the listview to occupy a fixed length in the layout. Eg: atleast 70% of the screen, so that the length of the listview is not dependent on the items in the listview.

Thanks in advance

Body:
I have some modifications to ur layout. This might work.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/listViewrelativeLayout"
    android:orientation="vertical">
    <TextView android:layout_height="wrap_content" android:layout_width="fill_parent"
        android:id="@+id/info_tv_id" android:text="Click Me" android:textSize="18sp"
        android:layout_marginLeft="10dip" android:gravity="center"/>
    <FrameLayout android:layout_width="fill_parent" android:layout_height="0dip"
        android:layout_weight="1.0">
        <ListView android:id="@+id/listView1" android:layout_width="fill_parent"
            android:layout_height="fill_parent" android:choiceMode="singleChoice"
            android:layout_below="@id/info_tv_id"/>
        <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:id="@+id/relativekeybuttons" android:orientation="horizontal"
            android:layout_gravity="bottom" android:visibility="gone">
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Default" android:layout_marginLeft="1dip"
                android:textSize="11sp"/>
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Passphrase"
                android:textSize="11sp"/>
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Rename"
                android:textSize="11sp"/>
            <Button android:layout_width="0dip" android:layout_height="wrap_content"
                android:layout_weight="1.0" android:text="Delete" android:layout_marginRight="1dip"
                android:textSize="11sp"/>
        </LinearLayout>
    </FrameLayout>
</LinearLayout>

Try not to use exact width and heights as it might not work on all phones.


Title: split a dataframe into equal parts and store the results

Body:
I'm relatively new to R.
I have a large dataframe which I would like to split into multiple dataframes around different values.

structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("Bangladesh", "Barbados", "Benin", "Burundi",
"Cameroon", "Chile", "Cyprus", "Ecuador", "Equatorial Guinea",
"Gabon", "Ghana", "Guatemala", "Guinea", "Guyana", "Haiti", "India",
"Jordan", "Lebanon", "Liberia", "Madagascar", "Mali", "Mexico",
"Morocco", "Mozambique", "Nepal", "Nicaragua", "Niger", "Oman",
"Pakistan", "Panama", "Peru", "Rwanda", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Sri Lanka", "Sudan", "Togo", "Tunisia",
"Turkey", "Uganda", "Zambia"), class = c("pseries", "factor")),
    date = structure(12:36, .Label = c("1965", "1966", "1967",
    "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975",
    "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983",
    "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991",
    "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999",
    "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
    "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
    "2016", "2017", "2018"), class = c("pseries", "factor")),
    oda_gdp = c(0.15080885502447, 0.1744123099839, 0.199176897551553,
    0.193616875061556, 0.186942991013889, 0.164744452026834,
    0.192609744294439, 0.13752013069625, 0.156186721262664, 0.137192335225767,
    0.131167382827501, 0.139945790928319, 0.112553104508006,
    0.1172188903714, 0.120991133274215, 0.0940867931618562, 0.0857724612850372,
    0.0653099752359248, 0.0714189688493898, 0.0470115150264598,
    0.0446068588203229, 0.0414522297087586, 0.0450866627292532,
    0.0435203084091358, 0.0404623996092304), entry = c(0, 0,
    1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0)), row.names = c(NA, 25L), class = "data.frame")

I would like to split this into multiple dataframes around the points where entry==1. More concretely, I would like each new dataframe to contain 2 rows before entry==1 and 7 rows after entry==1.

Output should look like this

df1=structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = c("Bangladesh", "Barbados", "Benin",
"Burundi", "Cameroon", "Chile", "Cyprus", "Ecuador", "Equatorial Guinea",
"Gabon", "Ghana", "Guatemala", "Guinea", "Guyana", "Haiti", "India",
"Jordan", "Lebanon", "Liberia", "Madagascar", "Mali", "Mexico",
"Morocco", "Mozambique", "Nepal", "Nicaragua", "Niger", "Oman",
"Pakistan", "Panama", "Peru", "Rwanda", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Sri Lanka", "Sudan", "Togo", "Tunisia",
"Turkey", "Uganda", "Zambia"), class = c("pseries", "factor")),
    date = structure(12:21, .Label = c("1965", "1966", "1967",
    "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975",
    "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983",
    "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991",
    "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999",
    "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
    "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
    "2016", "2017", "2018"), class = c("pseries", "factor")),
    oda_gdp = c(0.15080885502447, 0.1744123099839, 0.199176897551553,
    0.193616875061556, 0.186942991013889, 0.164744452026834,
    0.192609744294439, 0.13752013069625, 0.156186721262664, 0.137192335225767
    ), entry = c(0, 0, 1, 0, 0, 0, 1, 0, 0, 0)), row.names = c(NA,
10L), class = "data.frame")

For the first case where entry=1

df2=structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = c("Bangladesh", "Barbados", "Benin",
"Burundi", "Cameroon", "Chile", "Cyprus", "Ecuador", "Equatorial Guinea",
"Gabon", "Ghana", "Guatemala", "Guinea", "Guyana", "Haiti", "India",
"Jordan", "Lebanon", "Liberia", "Madagascar", "Mali", "Mexico",
"Morocco", "Mozambique", "Nepal", "Nicaragua", "Niger", "Oman",
"Pakistan", "Panama", "Peru", "Rwanda", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Sri Lanka", "Sudan", "Togo", "Tunisia",
"Turkey", "Uganda", "Zambia"), class = c("pseries", "factor")),
    date = structure(16:25, .Label = c("1965", "1966", "1967",
    "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975",
    "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983",
    "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991",
    "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999",
    "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
    "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
    "2016", "2017", "2018"), class = c("pseries", "factor")),
    oda_gdp = c(0.186942991013889, 0.164744452026834, 0.192609744294439,
    0.13752013069625, 0.156186721262664, 0.137192335225767, 0.131167382827501,
    0.139945790928319, 0.112553104508006, 0.1172188903714), entry = c(0,
    0, 1, 0, 0, 0, 0, 0, 0, 0)), row.names = 5:14, class = "data.frame")

For the second case where entry=1

I'm guessing split might be the way to go, but I can't figure out a way to include the conditions.
Notice that all newly created dataframes should be the same size.
Any help is much appreciated!

Body:
I don't think split is the right tool here. Instead, you can do:

lapply(which(df$entry == 1), function(i) df[(i-2):(i+7),])
#> [[1]]
#>       country date   oda_gdp entry
#> 1  Bangladesh 1976 0.1508089     0
#> 2  Bangladesh 1977 0.1744123     0
#> 3  Bangladesh 1978 0.1991769     1
#> 4  Bangladesh 1979 0.1936169     0
#> 5  Bangladesh 1980 0.1869430     0
#> 6  Bangladesh 1981 0.1647445     0
#> 7  Bangladesh 1982 0.1926097     1
#> 8  Bangladesh 1983 0.1375201     0
#> 9  Bangladesh 1984 0.1561867     0
#> 10 Bangladesh 1985 0.1371923     0
#>
#> [[2]]
#>       country date   oda_gdp entry
#> 5  Bangladesh 1980 0.1869430     0
#> 6  Bangladesh 1981 0.1647445     0
#> 7  Bangladesh 1982 0.1926097     1
#> 8  Bangladesh 1983 0.1375201     0
#> 9  Bangladesh 1984 0.1561867     0
#> 10 Bangladesh 1985 0.1371923     0
#> 11 Bangladesh 1986 0.1311674     0
#> 12 Bangladesh 1987 0.1399458     0
#> 13 Bangladesh 1988 0.1125531     0
#> 14 Bangladesh 1989 0.1172189     0
#>
#> [[3]]
#>       country date    oda_gdp entry
#> 13 Bangladesh 1988 0.11255310     0
#> 14 Bangladesh 1989 0.11721889     0
#> 15 Bangladesh 1990 0.12099113     1
#> 16 Bangladesh 1991 0.09408679     0
#> 17 Bangladesh 1992 0.08577246     0
#> 18 Bangladesh 1993 0.06530998     0
#> 19 Bangladesh 1994 0.07141897     0
#> 20 Bangladesh 1995 0.04701152     0
#> 21 Bangladesh 1996 0.04460686     0
#> 22 Bangladesh 1997 0.04145223     0

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
Auto Select Checkbox triggered by another checkbox
I am trying to auto select a checkbox if any another checkbox is selected. All this checkboxes are on the same sheet and basically i want check box 7 to tick if checkbox 3,4 or 5 is selected.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Sheets("Start Page").CheckBox3 = True Or Sheets("Start Page").CheckBox4 = True Or
Sheets("Start Page").CheckBox5 = True Then
Sheets("Start Page").CheckBox7 = True
Else
End If

End Sub
</code>```

Any help would be greatly appreciated.

答:
Even if your checkboxes are linked to a cell (LinkedCell-property), the Worksheet-Change-event is not triggered when you click on a Checkbox.

You need to catch the Click-Event of the checkboxes. For every checkbox, put a Click-event routine into the sheet module. To prevent that the logic if or if not to set the "calculated" checkbox is repeated, let those event handler call a common routine that does the calculation.

```<code>Private Sub CheckBox3_Click()
    Call SetMyCheckBox
End Sub

Private Sub CheckBox4_Click()
    Call SetMyCheckBox
End Sub

Private Sub CheckBox5_Click()
    Call SetMyCheckBox
End Sub

Sub SetMyCheckBox()
    Me.CheckBox7.Value = Me.CheckBox3.Value Or Me.CheckBox4.Value Or Me.CheckBox5.Value
End Sub
</code>```

You should, by the way, consider to give your checkboxes more meaningful names.

Body:
I am trying to auto select a checkbox if any another checkbox is selected. All this checkboxes are on the same sheet and basically i want check box 7 to tick if checkbox 3,4 or 5 is selected.

Private Sub Worksheet_Change(ByVal Target As Range)

If Sheets("Start Page").CheckBox3 = True Or Sheets("Start Page").CheckBox4 = True Or
Sheets("Start Page").CheckBox5 = True Then
Sheets("Start Page").CheckBox7 = True
Else
End If

End Sub

Any help would be greatly appreciated.

Body:
Even if your checkboxes are linked to a cell (LinkedCell-property), the Worksheet-Change-event is not triggered when you click on a Checkbox.

You need to catch the Click-Event of the checkboxes. For every checkbox, put a Click-event routine into the sheet module. To prevent that the logic if or if not to set the "calculated" checkbox is repeated, let those event handler call a common routine that does the calculation.

Private Sub CheckBox3_Click()
    Call SetMyCheckBox
End Sub

Private Sub CheckBox4_Click()
    Call SetMyCheckBox
End Sub

Private Sub CheckBox5_Click()
    Call SetMyCheckBox
End Sub

Sub SetMyCheckBox()
    Me.CheckBox7.Value = Me.CheckBox3.Value Or Me.CheckBox4.Value Or Me.CheckBox5.Value
End Sub

You should, by the way, consider to give your checkboxes more meaningful names.


问:
Std::nth_element is not giving the correct element
I don't know why in this case the function std::nth_element is not giving me the correct median for the X axis.

For this test I created a vector of point: std::vector<Point> points = {Point {70, 70}, Point {50, 30}, Point {35, 45}};

The function call is:

```<code>int median = (start + end) / 2;
Point split = get(points.begin() + start, points.begin() + median, points.begin() + end);
</code>```

Where start = 0; end = 2; In my mind the correct median for the X axis is Point(50, 30), instead this code gives me Point(70, 70).

Below there is the code for finding the median:

```<code>template <typename Iterator>
    Point get(Iterator start, Iterator median, Iterator end)
    {
        std::nth_element(
            start,
            median,
            end,
            [](const Point &point1, const Point &point2) {
                return point1.getX() < point2.getX();
            }
        );

        std::vector<Point>::iterator iter = median;
        std::cout << *iter << std::endl;
        return *iter;
    }
</code>```

答:
If you carefully read the description of the function in the CPP reference here, then you will see:

nth_element is a partial sorting algorithm that rearranges elements in [first, last) such that: The element pointed at by nth is changed to whatever element would occur in that position if [first, last) were sorted.

Important for your problem is [first, last) which denotes a half open range.

And per definition a half-open range is one which includes the first element, but NOT the last one. The last is not included. If you want to include it, you need to go one step further. In your case: last+1.

So, you simply call the function with a wrong parameter. No issue.

The correct code could be something like this:

```<code>#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

struct Point {
    int x{};
    int y{};
    int getX() const { return x; }
    int getY() const { return y; }

    friend std::ostream& operator << (std::ostream& os, const Point& p) {
        return os << p.x << ' ' << p.y;
    }
};

template <typename Iterator>
Point get(Iterator start, Iterator median, Iterator end)
{
    std::nth_element(
        start,
        median,
        end,
        [](const Point& point1, const Point& point2) {
            return point1.getX() < point2.getX();
        }
    );

    std::vector<Point>::iterator iter = median;
    return *iter;
}

int main() {
    std::vector<Point> points = { Point {70, 70}, Point {50, 30}, Point {35, 45} };

    int start = 0, end = 2;
    int median = (start + end) / 2;
    Point split = get(points.begin() + start, points.begin() + median, points.begin()+end+1);
    std::cout << split << '\n';
}
</code>```

Body:
I don't know why in this case the function std::nth_element is not giving me the correct median for the X axis.

For this test I created a vector of point: std::vector<Point> points = {Point {70, 70}, Point {50, 30}, Point {35, 45}};

The function call is:

int median = (start + end) / 2;
Point split = get(points.begin() + start, points.begin() + median, points.begin() + end);

Where start = 0; end = 2; In my mind the correct median for the X axis is Point(50, 30), instead this code gives me Point(70, 70).

Below there is the code for finding the median:

template <typename Iterator>
    Point get(Iterator start, Iterator median, Iterator end)
    {
        std::nth_element(
            start,
            median,
            end,
            [](const Point &point1, const Point &point2) {
                return point1.getX() < point2.getX();
            }
        );

        std::vector<Point>::iterator iter = median;
        std::cout << *iter << std::endl;
        return *iter;
    }

Body:
If you carefully read the description of the function in the CPP reference here, then you will see:

nth_element is a partial sorting algorithm that rearranges elements in [first, last) such that: The element pointed at by nth is changed to whatever element would occur in that position if [first, last) were sorted.

Important for your problem is [first, last) which denotes a half open range.

And per definition a half-open range is one which includes the first element, but NOT the last one. The last is not included. If you want to include it, you need to go one step further. In your case: last+1.

So, you simply call the function with a wrong parameter. No issue.

The correct code could be something like this:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

struct Point {
    int x{};
    int y{};
    int getX() const { return x; }
    int getY() const { return y; }

    friend std::ostream& operator << (std::ostream& os, const Point& p) {
        return os << p.x << ' ' << p.y;
    }
};

template <typename Iterator>
Point get(Iterator start, Iterator median, Iterator end)
{
    std::nth_element(
        start,
        median,
        end,
        [](const Point& point1, const Point& point2) {
            return point1.getX() < point2.getX();
        }
    );

    std::vector<Point>::iterator iter = median;
    return *iter;
}

int main() {
    std::vector<Point> points = { Point {70, 70}, Point {50, 30}, Point {35, 45} };

    int start = 0, end = 2;
    int median = (start + end) / 2;
    Point split = get(points.begin() + start, points.begin() + median, points.begin()+end+1);
    std::cout << split << '\n';
}


问:
Create a JSON string from column values
How do I mutate a Pandas DataFrame with a series of dictionaries.

Given the following DataFrame:

```<code>data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# add dict series
df = df.assign(my_dict="{}")
df.my_dict = df.my_dict.apply(json.loads)
</code>```

Name
Age
my_dict

tom
10
{}

nick
15
{}

juli
14
{}

How would I operate on column my_dict and mutate it as follows:

Age > 10

Name
Age
my_dict

tom
10
{"age>10": false}

nick
15
{"age>10": true}

juli
14
{"age>10": true}

And then mutate again:

Name = "tom":

Name
Age
my_dict

tom
10
{"age>10": false, "name=tom": true}

nick
15
{"age>10": true, "name=tom", false}

juli
14
{"age>10": true, "name=tom", false}

I'm interested in the process of mutating the dictionary, the rules are arbitrary examples.

答:
You can use:

```<code>df['my_dict'] = df.apply(lambda x: x['my_dict'] | {'Age': x['Age'] > 10}, axis=1)
print(df)

# Output
   Name  Age         my_dict
0   tom   10  {'Age': False}
1  nick   15   {'Age': True}
2  juli   14   {'Age': True}
</code>```

Add a new condition:

```<code>df['my_dict'] = df.apply(lambda x: x['my_dict'] | {'Name': x['Name'] == 'tom'}, axis=1)
print(df)

# Output
   Name  Age                       my_dict
0   tom   10  {'Age': False, 'Name': True}
1  nick   15  {'Age': True, 'Name': False}
2  juli   14  {'Age': True, 'Name': False}
</code>```

Obviously if you want to convert to json, use:

```<code>>>> df['my_dict'].apply(json.dumps)
0    {"Age": false, "Name": true}
1    {"Age": true, "Name": false}
2    {"Age": true, "Name": false}
Name: my_dict, dtype: object
</code>```

Title: Create a JSON string from column values

Body:
How do I mutate a Pandas DataFrame with a series of dictionaries.

Given the following DataFrame:

data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

# add dict series
df = df.assign(my_dict="{}")
df.my_dict = df.my_dict.apply(json.loads)

Name
Age
my_dict

tom
10
{}

nick
15
{}

juli
14
{}

How would I operate on column my_dict and mutate it as follows:

Age > 10

Name
Age
my_dict

tom
10
{"age>10": false}

nick
15
{"age>10": true}

juli
14
{"age>10": true}

And then mutate again:

Name = "tom":

Name
Age
my_dict

tom
10
{"age>10": false, "name=tom": true}

nick
15
{"age>10": true, "name=tom", false}

juli
14
{"age>10": true, "name=tom", false}

I'm interested in the process of mutating the dictionary, the rules are arbitrary examples.

Body:
You can use:

df['my_dict'] = df.apply(lambda x: x['my_dict'] | {'Age': x['Age'] > 10}, axis=1)
print(df)

# Output
   Name  Age         my_dict
0   tom   10  {'Age': False}
1  nick   15   {'Age': True}
2  juli   14   {'Age': True}

Add a new condition:

df['my_dict'] = df.apply(lambda x: x['my_dict'] | {'Name': x['Name'] == 'tom'}, axis=1)
print(df)

# Output
   Name  Age                       my_dict
0   tom   10  {'Age': False, 'Name': True}
1  nick   15  {'Age': True, 'Name': False}
2  juli   14  {'Age': True, 'Name': False}

Obviously if you want to convert to json, use:

>>> df['my_dict'].apply(json.dumps)
0    {"Age": false, "Name": true}
1    {"Age": true, "Name": false}
2    {"Age": true, "Name": false}
Name: my_dict, dtype: object


问:
problem with request dispatcher from servlets to jsp
I recently started studying JSP and Servlets. I am facing problems forwarding the dataList (rows from database) to JSP using requestdispatcher. In fact I have error in my JSP page which I couldn't figure out. Since I am learning I couldnt find where the error is:

Thank you!

The following is the error I get

```<code>org.apache.jasper.JasperException: An exception occurred processing JSP page /dataPage.jsp at line 29

26:         %>
27:         <tr>
28:             <td width="100"><%=itr.next()%></td>
29:             <td width="100"><%=itr.next()%></td>
30:             <td width="100"><%=itr.next()%></td>
31:             <td width="100"><%=itr.next()%></td>
32:         </tr>

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:519)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:428)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    AuthenticationServlet.doPost(AuthenticationServlet.java:60)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
</code>```

my code in JSP is:

```<code><table border="1" width="400">
        <tr>
            <td width="100"><b>Name</b>
            </td>
            <td width="100"><b>Contact No</b>
            </td>
            <td width="100"><b>SSN</b>
            </td>
            <td width="100"><b>Date of Birth</b>
            </td>
        </tr>

        <%
            List<String> data = (List<String>)request.getAttribute("data");
            Iterator<String> itr = data.iterator();
            while (itr.hasNext()) {
        %>
        <tr>
            <td width="100"><%=itr.next()%></td>
            <td width="100"><%=itr.next()%></td>
            <td width="100"><%=itr.next()%></td>
            <td width="100"><%=itr.next()%></td>
        </tr>
        <%
            }
        %>
    </table>
</code>```

My code in servlets is

```<code>List<String> dataList = new ArrayList<String>();

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url);
            conn.createStatement();

            stmt = conn.prepareStatement("SELECT name,password FROM employeeinfo WHERE name=? AND password=?");
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();

            if(rs != null) {
                while(rs.next()) {
                    int i = rs.getRow();
                    if(i == 1) {
                        dataList.add(rs.getString("name"));
                        dataList.add(rs.getString("contactno"));
                        dataList.add(rs.getString("ssn"));
                        dataList.add(rs.getString("dob"));
                    }
                }
            } else {
                out.println("Invalid User !!");
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("data", dataList);
        // Dispatch the request
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);
        if(dispatcher != null) {
            dispatcher.forward(request, response);
        }
</code>```

答:
As @Kal correctly said that you forgot to add the data to the list, hence when you try to use itr.next(), it finds nothing and hence the Exception.

The Better approach will be to check the value of itr.hasNext() before using itr.next(). You may also prefer using a temporary variable to store the value returned by itr.next() if you want to use the same value over and over again.

Body:
I recently started studying JSP and Servlets. I am facing problems forwarding the dataList (rows from database) to JSP using requestdispatcher. In fact I have error in my JSP page which I couldn't figure out. Since I am learning I couldnt find where the error is:

Thank you!

The following is the error I get

org.apache.jasper.JasperException: An exception occurred processing JSP page /dataPage.jsp at line 29

26:         %>
27:

28:             <%=itr.next()%>
29:             <%=itr.next()%>
30:             <%=itr.next()%>
31:             <%=itr.next()%>
32:

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:519)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:428)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    AuthenticationServlet.doPost(AuthenticationServlet.java:60)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

my code in JSP is:

            Name

            Contact No

            SSN

            Date of Birth

        <%
            List<String> data = (List<String>)request.getAttribute("data");
            Iterator<String> itr = data.iterator();
            while (itr.hasNext()) {
        %>

            <%=itr.next()%>
            <%=itr.next()%>
            <%=itr.next()%>
            <%=itr.next()%>

        <%
            }
        %>

My code in servlets is

List<String> dataList = new ArrayList<String>();

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url);
            conn.createStatement();

            stmt = conn.prepareStatement("SELECT name,password FROM employeeinfo WHERE name=? AND password=?");
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();

            if(rs != null) {
                while(rs.next()) {
                    int i = rs.getRow();
                    if(i == 1) {
                        dataList.add(rs.getString("name"));
                        dataList.add(rs.getString("contactno"));
                        dataList.add(rs.getString("ssn"));
                        dataList.add(rs.getString("dob"));
                    }
                }
            } else {
                out.println("Invalid User !!");
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("data", dataList);
        // Dispatch the request
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);
        if(dispatcher != null) {
            dispatcher.forward(request, response);
        }


问:
Deleting a row by condition if the number in the field is less than what was before and after it (pandas)
I have a dataset that collects data from text. This is time series data and sometimes it is in error. I need to remove rows from them by condition: when the number is between two numbers that are greater than it. You also need to take into account the date, which may coincide with the value from the string. Here is an example entry and what I want to get (dataframe):

```<code>     date        infected_in_all

369  14-01-2021  722487.0
370  14-01-2021  19.0
371  13-01-2021  715438.0
546  29-07-2020  176437.0
547  28-07-2020  1.0
548  28-07-2020  175812.0
549  27-07-2020  1.0
550  27-07-2020  174985.0
551  26-07-2020  174721.0

     date       infected_in_all

369  14-01-2021  722487.0
371  13-01-2021  715438.0
546  29-07-2020  176437.0
548  28-07-2020  175812.0
550  27-07-2020  174985.0
551  26-07-2020  174721.0
</code>```

Need help writing a condition.

答:
You can use a rolling mean to filter the data points relative the days around:

```<code># ensure datetime type
df['date'] = pd.to_datetime(df['date'])

# computing a rolling mean on ± 1 day
roll = (df.set_index('date')['infected_in_all']
          .rolling('3d', center=True,  min_periods=1).mean()
          .bfill()
          .values # as array
        )

# Is the value within 50% of the values around (arbitrary threshold for example)
df2 = df[df['infected_in_all'].div(roll).gt(0.5)]
</code>```

output:

```<code>          date  infected_in_all
369 2021-01-14         722487.0
371 2021-01-13         715438.0
546 2020-07-29         176437.0
548 2020-07-28         175812.0
550 2020-07-27         174985.0
551 2020-07-26         174721.0
</code>```

Body:
I have a dataset that collects data from text. This is time series data and sometimes it is in error. I need to remove rows from them by condition: when the number is between two numbers that are greater than it. You also need to take into account the date, which may coincide with the value from the string. Here is an example entry and what I want to get (dataframe):

     date        infected_in_all

369  14-01-2021  722487.0
370  14-01-2021  19.0
371  13-01-2021  715438.0
546  29-07-2020  176437.0
547  28-07-2020  1.0
548  28-07-2020  175812.0
549  27-07-2020  1.0
550  27-07-2020  174985.0
551  26-07-2020  174721.0

     date       infected_in_all

369  14-01-2021  722487.0
371  13-01-2021  715438.0
546  29-07-2020  176437.0
548  28-07-2020  175812.0
550  27-07-2020  174985.0
551  26-07-2020  174721.0

Need help writing a condition.

Body:
You can use a rolling mean to filter the data points relative the days around:

# ensure datetime type
df['date'] = pd.to_datetime(df['date'])

# computing a rolling mean on ± 1 day
roll = (df.set_index('date')['infected_in_all']
          .rolling('3d', center=True,  min_periods=1).mean()
          .bfill()
          .values # as array
        )

# Is the value within 50% of the values around (arbitrary threshold for example)
df2 = df[df['infected_in_all'].div(roll).gt(0.5)]

output:

          date  infected_in_all
369 2021-01-14         722487.0
371 2021-01-13         715438.0
546 2020-07-29         176437.0
548 2020-07-28         175812.0
550 2020-07-27         174985.0
551 2020-07-26         174721.0


问:
Three.js basics – Can't find variable – GLTFLoader animation
I’ve got very basic knowledge of JS. Following three.js docs Loading 3D models I have succesfully rendered 3D object and centered it:

```<code>const loader = new GLTFLoader();

loader.load( 'Duck.gltf', function ( duck ) {

    const model = duck.scene
    const box = new THREE.Box3().setFromObject( model );
    const center = new THREE.Vector3();
    box.getCenter( center );
    model.position.sub( center ); // center the model
    scene.add( model );

}, undefined, function ( error ) {

    console.error( error );

} );
</code>```

I would like to animate it now, begining with simple rotation:

```<code>/**
 * Animate
 */

const clock = new THREE.Clock()

const tick = () =>
{

    const elapsedTime = clock.getElapsedTime()

    // Update objects
    model.rotation.y = .5 * elapsedTime

    // Update Orbital Controls
    // controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()
</code>```

But the problem is console returns:

```<code>ReferenceError: Can't find variable: model
</code>```

答:
You have declared model variable inside the functional scope, try to declare it outside

```<code>const loader = new GLTFLoader();
let model, box, center;

loader.load( 'Duck.gltf', function ( duck ) {

    model = duck.scene
    box = new THREE.Box3().setFromObject( model );
    center = new THREE.Vector3();
    box.getCenter( center );
    model.position.sub( center ); // center the model
    scene.add( model );

}, undefined, function ( error ) {
    console.error( error );
} );
</code>```

Hopefully, this will work!

Edited

as @prisoner849 suggested in the comments

```<code>const clock = new THREE.Clock()
const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()
    // Update objects
    if (model) {
       model.rotation.y = .5 * elapsedTime
    }
    // Update Orbital Controls
    // controls.update()
    // Render
    renderer.render(scene, camera)
    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()
</code>```

Body:
I’ve got very basic knowledge of JS. Following three.js docs Loading 3D models I have succesfully rendered 3D object and centered it:

const loader = new GLTFLoader();

loader.load( 'Duck.gltf', function ( duck ) {

    const model = duck.scene
    const box = new THREE.Box3().setFromObject( model );
    const center = new THREE.Vector3();
    box.getCenter( center );
    model.position.sub( center ); // center the model
    scene.add( model );

}, undefined, function ( error ) {

    console.error( error );

} );

I would like to animate it now, begining with simple rotation:

/**
 * Animate
 */

const clock = new THREE.Clock()

const tick = () =>
{

    const elapsedTime = clock.getElapsedTime()

    // Update objects
    model.rotation.y = .5 * elapsedTime

    // Update Orbital Controls
    // controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

But the problem is console returns:

ReferenceError: Can't find variable: model

Body:
You have declared model variable inside the functional scope, try to declare it outside

const loader = new GLTFLoader();
let model, box, center;

loader.load( 'Duck.gltf', function ( duck ) {

    model = duck.scene
    box = new THREE.Box3().setFromObject( model );
    center = new THREE.Vector3();
    box.getCenter( center );
    model.position.sub( center ); // center the model
    scene.add( model );

}, undefined, function ( error ) {
    console.error( error );
} );

Hopefully, this will work!

Edited

as @prisoner849 suggested in the comments

const clock = new THREE.Clock()
const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()
    // Update objects
    if (model) {
       model.rotation.y = .5 * elapsedTime
    }
    // Update Orbital Controls
    // controls.update()
    // Render
    renderer.render(scene, camera)
    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()