问:
Monitor executed search queries in elasticsearch
I am trying to create a pipeline for monitoring user executed queries in elasticsearch.

I followed this (somehow dated?) tutorial

https://www.elastic.co/blog/monitoring-the-search-queries

I successfully installed logstash, packetbeat and kibana. Both applications are configured locally right now and I am able to access all of them. I verified existence of new indices in elastisearch with a name logstash-2020.04.06-000001. I use pretty much same config as given in tutorial, the only difference is that my ip addresses are local, in this case, I am using 127.0.0.1 in place of 10.255.4.165, simply because it wasn't working otherwise. All applications work on default ports.

Whole setup seems to work perfectly fine, but I don't see any queries being saved anywhere.

Moreover, I cannot create Index Pattern in Kibana to track user queries. I can see that index exists both in Rest API and Kibana Index Managment, however, it's an empty index, without any documents. I already tried to restart all of services after configuration using systemd.

I am using Elasticsearch 7.6.2.

How can I fix it?

Is there maybe other solution for logging executed queries?

I don't necessarily need Kibana visualization, but I need to know user queries to fix relevance scores for results.

Packetbeat config file, /etc/packetbeat/packetbeat.yml:

```<code># Select the network interfaces to sniff the data. You can use the "any"
# keyword to sniff on all connected interfaces.
interfaces:
device: any

http:
# Configure the ports where to listen for HTTP traffic. You can disable
# the HTTP protocol by commenting out the list of ports.
  ports: [9200]
  send_request: true
  include_body_for: ["application/json", "x-www-form-urlencoded"]

#elasticsearch:
  # Array of hosts to connect to.
  # Scheme and port can be left out and will be set to the default (http and 9200)
  # In case you specify and additional path, the scheme is required: http://localhost:9200/path
  # IPv6 addresses should always be defined as: https://[2001:db8::1]:9200
  # hosts: ["Localhost:9200"]

### Logstash as output
logstash:
  # The Logstash hosts
  hosts: ["127.0.0.1:5044"]

output.logstash:
  hosts: ["127.0.0.1:5044"]
</code>```

This is my packetbeat console output:

```<code>user@host:/usr/share/packetbeat$ sudo ./bin/packetbeat -e -c /etc/packetbeat/packetbeat.yml -d "publish"
2020-04-07T15:59:50.855+0200    INFO    instance/beat.go:622    Home path: [/usr/share/packetbeat/bin] Config path: [/usr/share/packetbeat/bin] Data path: [/usr/share/packetbeat/bin/data] Logs path: [/usr/share/packetbeat/bin/logs]
2020-04-07T15:59:50.873+0200    INFO    instance/beat.go:630    Beat ID: 25a0570e-3395-4a8b-8dcf-38c19560eb44
2020-04-07T15:59:50.897+0200    INFO    [api]   api/server.go:62    Starting stats endpoint
2020-04-07T15:59:50.906+0200    INFO    [api]   api/server.go:64    Metrics endpoint listening on: 127.0.0.1:5066 (configured: localhost)
2020-04-07T15:59:50.907+0200    INFO    [seccomp]   seccomp/seccomp.go:124  Syscall filter successfully installed
2020-04-07T15:59:50.907+0200    INFO    [beat]  instance/beat.go:958    Beat info   {"system_info": {"beat": {"path": {"config": "/usr/share/packetbeat/bin", "data": "/usr/share/packetbeat/bin/data", "home": "/usr/share/packetbeat/bin", "logs": "/usr/share/packetbeat/bin/logs"}, "type": "packetbeat", "uuid": "25a0570e-3395-4a8b-8dcf-38c19560eb44"}}}
2020-04-07T15:59:50.907+0200    INFO    [beat]  instance/beat.go:967    Build info  {"system_info": {"build": {"commit": "d57bcf8684602e15000d65b75afcd110e2b12b59", "libbeat": "7.6.2", "time": "2020-03-26T05:09:32.000Z", "version": "7.6.2"}}}
2020-04-07T15:59:50.907+0200    INFO    [beat]  instance/beat.go:970    Go runtime info {"system_info": {"go": {"os":"linux","arch":"amd64","max_procs":8,"version":"go1.13.8"}}}
2020-04-07T15:59:50.908+0200    INFO    [beat]  instance/beat.go:974    Host info   {"system_info": {"host": {"architecture":"x86_64","boot_time":"2020-04-07T11:24:50+02:00","containerized":false,"name":"host","ip":["127.0.0.1/8","::1/128","192.168.1.11/24","fe80::dacb:8aff:fe80:d3f5/64","172.17.0.1/16"],"kernel_version":"4.9.0-12-amd64","mac":["XXXXXXXXXXXXXXX"],"os":{"family":"debian","platform":"debian","name":"Debian GNU/Linux","version":"9 (stretch)","major":9,"minor":0,"patch":0,"codename":"stretch"},"timezone":"CEST","timezone_offset_sec":7200,"id":"414bf25d70c54332b8cf4d2a82ee0108"}}}
2020-04-07T15:59:50.908+0200    INFO    [beat]  instance/beat.go:1003   Process info    {"system_info": {"process": {"capabilities": {"inheritable":null,"permitted":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend","audit_read"],"effective":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend","audit_read"],"bounding":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend","audit_read"],"ambient":null}, "cwd": "/usr/share/packetbeat", "exe": "/usr/share/packetbeat/bin/packetbeat", "name": "packetbeat", "pid": 9679, "ppid": 9678, "seccomp": {"mode":"filter"}, "start_time": "2020-04-07T15:59:50.259+0200"}}}
2020-04-07T15:59:50.908+0200    INFO    instance/beat.go:298    Setup Beat: packetbeat; Version: 7.6.2
2020-04-07T15:59:50.908+0200    INFO    [publisher] pipeline/module.go:110  Beat name: host
2020-04-07T15:59:50.908+0200    INFO    procs/procs.go:105  Process watcher disabled
2020-04-07T15:59:50.924+0200    INFO    [monitoring]    log/log.go:118  Starting metrics logging every 30s
2020-04-07T15:59:50.924+0200    INFO    instance/beat.go:439    packetbeat start running.
2020-04-07T16:00:20.926+0200    INFO    [monitoring]    log/log.go:145  Non-zero metrics in the last 30s    {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":40,"time":{"ms":44}},"total":{"ticks":160,"time":{"ms":172},"value":160},"user":{"ticks":120,"time":{"ms":128}}},"handles":{"limit":{"hard":4096,"soft":1024},"open":8},"info":{"ephemeral_id":"0634aeb9-6358-4947-a908-7043973876dc","uptime":{"ms":30132}},"memstats":{"gc_next":39455344,"memory_alloc":21608032,"memory_total":26051720,"rss":66273280},"runtime":{"goroutines":14}},"libbeat":{"config":{"module":{"running":0}},"output":{"type":"logstash"},"pipeline":{"clients":0,"events":{"active":0}}},"system":{"cpu":{"cores":8},"load":{"1":0.5,"15":0.64,"5":0.75,"norm":{"1":0.0625,"15":0.08,"5":0.0938}}}}}}
</code>```

Logstash config file, /usr/share/logstash/es-first-config.conf:

```<code>input {
  beats {
    port => 5044
  }
}
filter {
  if "search" in [request]{
    grok {
      match => { "request" => ".*\n\{(?<query_body>.*)"}
    }
    grok {
      match => { "path" => "\/(?<index>.*)\/_search"}
    }
    if [index] {
    }
    else {
      mutate {
        add_field  => { "index" => "All" }
      }
    }
    mutate {
      update  => { "query_body" => "{%{query_body}" }
    }
  }
}
output {
  if "search" in [request] and "ignore_unmapped" not in [query_body]{
    elasticsearch {
      hosts => "127.0.0.1:9200"
    }
  }
}

</code>```

This is my logstash console output:

```<code>user@host:/usr/share/logstash$ sudo ./bin/logstash --path.settings /etc/logstash -f es-first-config.conf
Sending Logstash logs to /var/log/logstash which is now configured via log4j2.properties
[2020-04-07T15:58:33,546][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2020-04-07T15:58:33,731][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"7.6.2"}
[2020-04-07T15:58:35,916][INFO ][org.reflections.Reflections] Reflections took 33 ms to scan 1 urls, producing 20 keys and 40 values
[2020-04-07T15:58:37,443][INFO ][logstash.outputs.elasticsearch][main] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://127.0.0.1:9200/]}}
[2020-04-07T15:58:37,630][WARN ][logstash.outputs.elasticsearch][main] Restored connection to ES instance {:url=>"http://127.0.0.1:9200/"}
[2020-04-07T15:58:37,688][INFO ][logstash.outputs.elasticsearch][main] ES Output version determined {:es_version=>7}
[2020-04-07T15:58:37,694][WARN ][logstash.outputs.elasticsearch][main] Detected a 6.x and above cluster: the `type` event field won't be used to determine the document _type {:es_version=>7}
[2020-04-07T15:58:37,789][INFO ][logstash.outputs.elasticsearch][main] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["//127.0.0.1:9200"]}
[2020-04-07T15:58:37,850][INFO ][logstash.outputs.elasticsearch][main] Using default mapping template
[2020-04-07T15:58:37,935][INFO ][logstash.outputs.elasticsearch][main] Attempting to install template {:manage_template=>{"index_patterns"=>"logstash-*", "version"=>60001, "settings"=>{"index.refresh_interval"=>"5s", "number_of_shards"=>1, "index.lifecycle.name"=>"logstash-policy", "index.lifecycle.rollover_alias"=>"logstash"}, "mappings"=>{"dynamic_templates"=>[{"message_field"=>{"path_match"=>"message", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false}}}, {"string_fields"=>{"match"=>"*", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false, "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}}}}], "properties"=>{"@timestamp"=>{"type"=>"date"}, "@version"=>{"type"=>"keyword"}, "geoip"=>{"dynamic"=>true, "properties"=>{"ip"=>{"type"=>"ip"}, "location"=>{"type"=>"geo_point"}, "latitude"=>{"type"=>"half_float"}, "longitude"=>{"type"=>"half_float"}}}}}}}
[2020-04-07T15:58:38,108][WARN ][org.logstash.instrument.metrics.gauge.LazyDelegatingGauge][main] A gauge metric of an unknown type (org.jruby.specialized.RubyArrayOneObject) has been created for key: cluster_uuids. This may result in invalid serialization.  It is recommended to log an issue to the responsible developer/development team.
[2020-04-07T15:58:38,114][INFO ][logstash.javapipeline    ][main] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>8, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50, "pipeline.max_inflight"=>1000, "pipeline.sources"=>["/usr/share/logstash/es-first-config.conf"], :thread=>"#<Thread:0x7437b24 run>"}
[2020-04-07T15:58:39,246][INFO ][logstash.inputs.beats    ][main] Beats inputs: Starting input listener {:address=>"0.0.0.0:5044"}
[2020-04-07T15:58:39,314][INFO ][logstash.javapipeline    ][main] Pipeline started {"pipeline.id"=>"main"}
[2020-04-07T15:58:39,388][INFO ][logstash.agent           ] Pipelines running {:count=>1, :running_pipelines=>[:main], :non_running_pipelines=>[]}
[2020-04-07T15:58:39,480][INFO ][org.logstash.beats.Server][main] Starting server on port: 5044
[2020-04-07T15:58:39,762][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
</code>```

答:
I am just like you, but a little more advanced. The problem occurs for the following, you are missing this piece of code:

```<code>packetbeat.flows:
   timeout: 30s
   period: 10s

processors:
- add_cloud_metadata: ~
</code>```

obviously packetbeat has to run on the same elastic node to capture port 9200

Without this, it doesn't start sending data to logstash, I don't know why, but try it (level stackoverflow, sorry)

Once the data is sent and you see it, you will have the body in a field, here comes the following:

You will need to amplify the capacity (using vector) of several fields so that it will not give error (mappings index--> request and http ... request field)

Later, this collapses my nodes, and there I am. Looking for updated information on monitoring search queries in elasticsearch in 2020.

Body:
I am trying to create a pipeline for monitoring user executed queries in elasticsearch.

I followed this (somehow dated?) tutorial

https://www.elastic.co/blog/monitoring-the-search-queries

I successfully installed logstash, packetbeat and kibana. Both applications are configured locally right now and I am able to access all of them. I verified existence of new indices in elastisearch with a name logstash-2020.04.06-000001. I use pretty much same config as given in tutorial, the only difference is that my ip addresses are local, in this case, I am using 127.0.0.1 in place of 10.255.4.165, simply because it wasn't working otherwise. All applications work on default ports.

Whole setup seems to work perfectly fine, but I don't see any queries being saved anywhere.

Moreover, I cannot create Index Pattern in Kibana to track user queries. I can see that index exists both in Rest API and Kibana Index Managment, however, it's an empty index, without any documents. I already tried to restart all of services after configuration using systemd.

I am using Elasticsearch 7.6.2.

How can I fix it?

Is there maybe other solution for logging executed queries?

I don't necessarily need Kibana visualization, but I need to know user queries to fix relevance scores for results.

Packetbeat config file, /etc/packetbeat/packetbeat.yml:

# Select the network interfaces to sniff the data. You can use the "any"
# keyword to sniff on all connected interfaces.
interfaces:
device: any

http:
# Configure the ports where to listen for HTTP traffic. You can disable
# the HTTP protocol by commenting out the list of ports.
  ports: [9200]
  send_request: true
  include_body_for: ["application/json", "x-www-form-urlencoded"]

#elasticsearch:
  # Array of hosts to connect to.
  # Scheme and port can be left out and will be set to the default (http and 9200)
  # In case you specify and additional path, the scheme is required: http://localhost:9200/path
  # IPv6 addresses should always be defined as: https://[2001:db8::1]:9200
  # hosts: ["Localhost:9200"]

### Logstash as output
logstash:
  # The Logstash hosts
  hosts: ["127.0.0.1:5044"]

output.logstash:
  hosts: ["127.0.0.1:5044"]

This is my packetbeat console output:

user@host:/usr/share/packetbeat$ sudo ./bin/packetbeat -e -c /etc/packetbeat/packetbeat.yml -d "publish"
2020-04-07T15:59:50.855+0200    INFO    instance/beat.go:622    Home path: [/usr/share/packetbeat/bin] Config path: [/usr/share/packetbeat/bin] Data path: [/usr/share/packetbeat/bin/data] Logs path: [/usr/share/packetbeat/bin/logs]
2020-04-07T15:59:50.873+0200    INFO    instance/beat.go:630    Beat ID: 25a0570e-3395-4a8b-8dcf-38c19560eb44
2020-04-07T15:59:50.897+0200    INFO    [api]   api/server.go:62    Starting stats endpoint
2020-04-07T15:59:50.906+0200    INFO    [api]   api/server.go:64    Metrics endpoint listening on: 127.0.0.1:5066 (configured: localhost)
2020-04-07T15:59:50.907+0200    INFO    [seccomp]   seccomp/seccomp.go:124  Syscall filter successfully installed
2020-04-07T15:59:50.907+0200    INFO    [beat]  instance/beat.go:958    Beat info   {"system_info": {"beat": {"path": {"config": "/usr/share/packetbeat/bin", "data": "/usr/share/packetbeat/bin/data", "home": "/usr/share/packetbeat/bin", "logs": "/usr/share/packetbeat/bin/logs"}, "type": "packetbeat", "uuid": "25a0570e-3395-4a8b-8dcf-38c19560eb44"}}}
2020-04-07T15:59:50.907+0200    INFO    [beat]  instance/beat.go:967    Build info  {"system_info": {"build": {"commit": "d57bcf8684602e15000d65b75afcd110e2b12b59", "libbeat": "7.6.2", "time": "2020-03-26T05:09:32.000Z", "version": "7.6.2"}}}
2020-04-07T15:59:50.907+0200    INFO    [beat]  instance/beat.go:970    Go runtime info {"system_info": {"go": {"os":"linux","arch":"amd64","max_procs":8,"version":"go1.13.8"}}}
2020-04-07T15:59:50.908+0200    INFO    [beat]  instance/beat.go:974    Host info   {"system_info": {"host": {"architecture":"x86_64","boot_time":"2020-04-07T11:24:50+02:00","containerized":false,"name":"host","ip":["127.0.0.1/8","::1/128","192.168.1.11/24","fe80::dacb:8aff:fe80:d3f5/64","172.17.0.1/16"],"kernel_version":"4.9.0-12-amd64","mac":["XXXXXXXXXXXXXXX"],"os":{"family":"debian","platform":"debian","name":"Debian GNU/Linux","version":"9 (stretch)","major":9,"minor":0,"patch":0,"codename":"stretch"},"timezone":"CEST","timezone_offset_sec":7200,"id":"414bf25d70c54332b8cf4d2a82ee0108"}}}
2020-04-07T15:59:50.908+0200    INFO    [beat]  instance/beat.go:1003   Process info    {"system_info": {"process": {"capabilities": {"inheritable":null,"permitted":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend","audit_read"],"effective":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend","audit_read"],"bounding":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend","audit_read"],"ambient":null}, "cwd": "/usr/share/packetbeat", "exe": "/usr/share/packetbeat/bin/packetbeat", "name": "packetbeat", "pid": 9679, "ppid": 9678, "seccomp": {"mode":"filter"}, "start_time": "2020-04-07T15:59:50.259+0200"}}}
2020-04-07T15:59:50.908+0200    INFO    instance/beat.go:298    Setup Beat: packetbeat; Version: 7.6.2
2020-04-07T15:59:50.908+0200    INFO    [publisher] pipeline/module.go:110  Beat name: host
2020-04-07T15:59:50.908+0200    INFO    procs/procs.go:105  Process watcher disabled
2020-04-07T15:59:50.924+0200    INFO    [monitoring]    log/log.go:118  Starting metrics logging every 30s
2020-04-07T15:59:50.924+0200    INFO    instance/beat.go:439    packetbeat start running.
2020-04-07T16:00:20.926+0200    INFO    [monitoring]    log/log.go:145  Non-zero metrics in the last 30s    {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":40,"time":{"ms":44}},"total":{"ticks":160,"time":{"ms":172},"value":160},"user":{"ticks":120,"time":{"ms":128}}},"handles":{"limit":{"hard":4096,"soft":1024},"open":8},"info":{"ephemeral_id":"0634aeb9-6358-4947-a908-7043973876dc","uptime":{"ms":30132}},"memstats":{"gc_next":39455344,"memory_alloc":21608032,"memory_total":26051720,"rss":66273280},"runtime":{"goroutines":14}},"libbeat":{"config":{"module":{"running":0}},"output":{"type":"logstash"},"pipeline":{"clients":0,"events":{"active":0}}},"system":{"cpu":{"cores":8},"load":{"1":0.5,"15":0.64,"5":0.75,"norm":{"1":0.0625,"15":0.08,"5":0.0938}}}}}}

Logstash config file, /usr/share/logstash/es-first-config.conf:

input {
  beats {
    port => 5044
  }
}
filter {
  if "search" in [request]{
    grok {
      match => { "request" => ".*\n\{(?<query_body>.*)"}
    }
    grok {
      match => { "path" => "\/(?<index>.*)\/_search"}
    }
    if [index] {
    }
    else {
      mutate {
        add_field  => { "index" => "All" }
      }
    }
    mutate {
      update  => { "query_body" => "{%{query_body}" }
    }
  }
}
output {
  if "search" in [request] and "ignore_unmapped" not in [query_body]{
    elasticsearch {
      hosts => "127.0.0.1:9200"
    }
  }
}

This is my logstash console output:

user@host:/usr/share/logstash$ sudo ./bin/logstash --path.settings /etc/logstash -f es-first-config.conf
Sending Logstash logs to /var/log/logstash which is now configured via log4j2.properties
[2020-04-07T15:58:33,546][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2020-04-07T15:58:33,731][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"7.6.2"}
[2020-04-07T15:58:35,916][INFO ][org.reflections.Reflections] Reflections took 33 ms to scan 1 urls, producing 20 keys and 40 values
[2020-04-07T15:58:37,443][INFO ][logstash.outputs.elasticsearch][main] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://127.0.0.1:9200/]}}
[2020-04-07T15:58:37,630][WARN ][logstash.outputs.elasticsearch][main] Restored connection to ES instance {:url=>"http://127.0.0.1:9200/"}
[2020-04-07T15:58:37,688][INFO ][logstash.outputs.elasticsearch][main] ES Output version determined {:es_version=>7}
[2020-04-07T15:58:37,694][WARN ][logstash.outputs.elasticsearch][main] Detected a 6.x and above cluster: the `type` event field won't be used to determine the document _type {:es_version=>7}
[2020-04-07T15:58:37,789][INFO ][logstash.outputs.elasticsearch][main] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["//127.0.0.1:9200"]}
[2020-04-07T15:58:37,850][INFO ][logstash.outputs.elasticsearch][main] Using default mapping template
[2020-04-07T15:58:37,935][INFO ][logstash.outputs.elasticsearch][main] Attempting to install template {:manage_template=>{"index_patterns"=>"logstash-*", "version"=>60001, "settings"=>{"index.refresh_interval"=>"5s", "number_of_shards"=>1, "index.lifecycle.name"=>"logstash-policy", "index.lifecycle.rollover_alias"=>"logstash"}, "mappings"=>{"dynamic_templates"=>[{"message_field"=>{"path_match"=>"message", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false}}}, {"string_fields"=>{"match"=>"*", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false, "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}}}}], "properties"=>{"@timestamp"=>{"type"=>"date"}, "@version"=>{"type"=>"keyword"}, "geoip"=>{"dynamic"=>true, "properties"=>{"ip"=>{"type"=>"ip"}, "location"=>{"type"=>"geo_point"}, "latitude"=>{"type"=>"half_float"}, "longitude"=>{"type"=>"half_float"}}}}}}}
[2020-04-07T15:58:38,108][WARN ][org.logstash.instrument.metrics.gauge.LazyDelegatingGauge][main] A gauge metric of an unknown type (org.jruby.specialized.RubyArrayOneObject) has been created for key: cluster_uuids. This may result in invalid serialization.  It is recommended to log an issue to the responsible developer/development team.
[2020-04-07T15:58:38,114][INFO ][logstash.javapipeline    ][main] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>8, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50, "pipeline.max_inflight"=>1000, "pipeline.sources"=>["/usr/share/logstash/es-first-config.conf"], :thread=>"#<Thread:0x7437b24 run>"}
[2020-04-07T15:58:39,246][INFO ][logstash.inputs.beats    ][main] Beats inputs: Starting input listener {:address=>"0.0.0.0:5044"}
[2020-04-07T15:58:39,314][INFO ][logstash.javapipeline    ][main] Pipeline started {"pipeline.id"=>"main"}
[2020-04-07T15:58:39,388][INFO ][logstash.agent           ] Pipelines running {:count=>1, :running_pipelines=>[:main], :non_running_pipelines=>[]}
[2020-04-07T15:58:39,480][INFO ][org.logstash.beats.Server][main] Starting server on port: 5044
[2020-04-07T15:58:39,762][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}

Body:
I am just like you, but a little more advanced. The problem occurs for the following, you are missing this piece of code:

packetbeat.flows:
   timeout: 30s
   period: 10s

processors:
- add_cloud_metadata: ~

obviously packetbeat has to run on the same elastic node to capture port 9200

Without this, it doesn't start sending data to logstash, I don't know why, but try it (level stackoverflow, sorry)

Once the data is sent and you see it, you will have the body in a field, here comes the following:

You will need to amplify the capacity (using vector) of several fields so that it will not give error (mappings index--> request and http ... request field)

Later, this collapses my nodes, and there I am. Looking for updated information on monitoring search queries in elasticsearch in 2020.


来源: stackexchange

问:
Is there a way to ignore "/r/n" in readingContext.rawrecord while reading using CSVHelper
I'm parsing a comma separated text file with some empty rows using CSVhelper. CSV helper ignores empty rows when it parses the records successfully.

But when there is a missing field exception, when I look at the  ReadingContext.RawRecord value, it has leading "\r\n" characters from previous empty line. Is there a way to ignore this in CSVHelper?
I need this because even when there is an exception, I still want to get the first value to be used as Primary key to store to a database. And it fails when I have these extra characters.

答:
you can configure this by setting a lambda expression for Configuration.ShouldSkipRecord</p>

```<code>csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("\r\n")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
you can configure this by setting a lambda expression for Configuration.ShouldSkipRecord

csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("\r\n")


问:
How can you disable the network connection in a Flutter Test?
I am making a call to a web server with the http package and I want to test this functionality when there is no internet connection. Is there a way to disable the connectivity in a test? Or should I mock the http package?</p>

答:
In my opinion, the easiest way to do that is to edit the emulator configuration. If you are running Android, that's where you find this config. You can change Signal strength to none. If you are running an iOS emulator, in the settings there should be a similar config.

I hope that helps


问:
Loop over a List getting an increasing number of elements each time
Let's say I have a list that looks like

```<code>{A, B, C, D, E}
</code>```

And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:

```<code>Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}
</code>```

Currently I am accomplishing this with:

```<code>(1 to list.size).foreach( n => {
  val elements = list.take(n)
  // Do something with elements
})
</code>```

But that feels messy. Is there a more 'scala' way of accomplishing this behavior?

答:
You can use foldLeft with a linked list to accumulate the elements.

However, this will reverse the order, so you'll need to call the .reverse function if you really care about the order, which wouldn't be efficient.

```<code>list.foldLeft(Nil : List[String]){(l, n) => {
  val elements = n :: l
  println(elements)
  elements
}}
</code>```

Output:

```<code>List(A)
List(B, A)
List(C, B, A)
List(D, C, B, A)
List(E, D, C, B, A)
</code>```

Here's a version that preserves order but uses a ListBuffer, which isn't great

```<code>val elems = ListBuffer[String]()
list.foreach{ s =>
  elems += s
  println(elems)
}
</code>```

The same, but with a fold

```<code>list.foldLeft(ListBuffer[String]()){(elems, s) =>
  elems += s
  println(elems)
  elems
}
</code>```

Output:

```<code>ListBuffer(A)
ListBuffer(A, B)
ListBuffer(A, B, C)
ListBuffer(A, B, C, D)
ListBuffer(A, B, C, D, E)
</code>```

Body:
Let's say I have a list that looks like

{A, B, C, D, E}

And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:

Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}

Currently I am accomplishing this with:

(1 to list.size).foreach( n => {
  val elements = list.take(n)
  // Do something with elements
})

But that feels messy. Is there a more 'scala' way of accomplishing this behavior?

Body:
You can use foldLeft with a linked list to accumulate the elements.

However, this will reverse the order, so you'll need to call the .reverse function if you really care about the order, which wouldn't be efficient.

list.foldLeft(Nil : List[String]){(l, n) => {
  val elements = n :: l
  println(elements)
  elements
}}

Output:

List(A)
List(B, A)
List(C, B, A)
List(D, C, B, A)
List(E, D, C, B, A)

Here's a version that preserves order but uses a ListBuffer, which isn't great

val elems = ListBuffer[String]()
list.foreach{ s =>
  elems += s
  println(elems)
}

The same, but with a fold

list.foldLeft(ListBuffer[String]()){(elems, s) =>
  elems += s
  println(elems)
  elems
}

Output:

ListBuffer(A)
ListBuffer(A, B)
ListBuffer(A, B, C)
ListBuffer(A, B, C, D)
ListBuffer(A, B, C, D, E)


问:
Problem with logo in a footer of Moodle website
I replaced Moodle logo with a logo of my web place keeping the same file name and file size and the new logo shows up when I run my website in Firefox or Edge, but the logo doesn't show up in Chrome, Brave and maybe other web browsers.
What I did:

I put my logo in this file: /pix/moodlelogo_grayhat.png

I changed logo link in: /lib/outputrenderers.php
If someone wants to take a look, this is my website.

Thank you in advance!

答:
Based on what @isherwood said, I fixed this problem.
I edited outputrenderers.php (/lib folder) where the filename was dynamically injected from.

It was:

```<code><img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a>
</code>```

I put instead:

```<code><a title="MyWeb" href="https://mywebplace.com/">
 <img alt="MyWeb" src="https://mywebplace.com/pix/moodlelogo_grayhat.png"></a>
</code>```

Thanks.

Body:
Based on what @isherwood said, I fixed this problem.
I edited outputrenderers.php (/lib folder) where the filename was dynamically injected from.

It was:

<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a>

I put instead:

<a title="MyWeb" href="https://mywebplace.com/">
 <img alt="MyWeb" src="https://mywebplace.com/pix/moodlelogo_grayhat.png"></a>

Thanks.


答:
you can use tidyr::crossing to obtained your desired result:

```<code>crossing(select(df, sub_date), period)
</code>```

Note that you are not looking for a join since you want every combination of sub_date combinded (or crossed) with every combination of period and forecast.

Title: Full Join in dplyr

Body:
I have a dataframe looking like:

library(tidyverse)
df <- tibble::tribble(
        ~sub_date, ~period,
        "2019-01",       1,
        "2019-01",       2,
        "2019-01",       3,
        "2019-02",       1,
        "2019-02",       2,
        "2019-03",       1,
        "2019-03",       2,
        "2019-03",       3,
        "2019-03",       4
        )

  sub_date period
  <chr>     <dbl>
1 2019-01       1
2 2019-01       2
3 2019-01       3
4 2019-02       1
5 2019-02       2
6 2019-03       1
7 2019-03       2
8 2019-03       3
9 2019-03       4

and another:

period <- tibble::tribble(
            ~period, ~forecast,
                  1,        10,
                  2,        20,
                  3,        30,
                  4,        40,
                  5,        50,
                  6,        60,
                  7,        70
            )

  period forecast
   <dbl>    <dbl>
1      1       10
2      2       20
3      3       30
4      4       40
5      5       50
6      6       60
7      7       70

I am struggling to join them in a way that in df I can fill the missing periods in the table period, aka the number of rows in period X the different sub_date in df.

as follows:

df_output <- tibble::tribble(
               ~sub_date, ~period, ~forecast,
               "2019-01",       1,        10,
               "2019-01",       2,        20,
               "2019-01",       3,        30,
               "2019-01",       4,        40,
               "2019-01",       5,        50,
               "2019-01",       6,        60,
               "2019-01",       7,        70,
               "2019-02",       1,        10,
               "2019-02",       2,        20,
               "2019-02",       3,        30,
               "2019-02",       4,        40,
               "2019-02",       5,        50,
               "2019-02",       6,        60,
               "2019-02",       7,        70,
               "2019-03",       1,        10,
               "2019-03",       2,        20,
               "2019-03",       3,        30,
               "2019-03",       4,        40,
               "2019-03",       5,        50,
               "2019-03",       6,        60,
               "2019-03",       7,        70
               )

# A tibble: 21 x 3
   sub_date period forecast
   <chr>     <dbl>    <dbl>
 1 2019-01       1       10
 2 2019-01       2       20
 3 2019-01       3       30
 4 2019-01       4       40
 5 2019-01       5       50
 6 2019-01       6       60
 7 2019-01       7       70
 8 2019-02       1       10
 9 2019-02       2       20
10 2019-02       3       30
# … with 11 more rows

I assumed it was a full join but I don't get the desired result.

Any help?

Body:
you can use tidyr::crossing to obtained your desired result:

crossing(select(df, sub_date), period)

Note that you are not looking for a join since you want every combination of sub_date combinded (or crossed) with every combination of period and forecast.


问:
Can Windows and Linux developers work together on the same project using C# and ASP.net?
If a group of developers are working on a project written using ASP.net and C# in a Windows environment with Visual Studio, is there any way a developer can join their team and work with them on the project in a Linux environment? I know about the open source, cross-platform development framework Mono, could this be an option or would the Windows developers have to use this as well for that to work? Is the best option for a Linux developer to just install a Windows partition or can he join them without doing so?</p>

答:
Is the best option for a Linux
  developer to just install a Windows
  partition

Yes, by far. Even better, just get a PC. I've run into so many headaches trying to develop in .NET on Linux. Mono isn't perfect, and never will be.

ContentLicense: CC BY-SA 3.0


问:
Filter products by name "LIKE" on a WC_Product_Query in WooCommerce
In WooCommerce using wc_get_products() function I would like to find a way to filter products by name using the LIKE operator.

Actually I am only able to filter products by a specific defined name with:

```<code>$args = array(
    'limit' => 5,
    'name' => 'Test',
);
$result = wc_get_products( $args );
</code>```

Is it possible to filter products where the name is LIKE 'test'?

答:
If you look to WooCommerce official documentation for WC_Product_Query at the end on the section "Adding Custom Parameter Support" you will see that you can manipulate the WC_Product_Query with a custom hooked function.

So to filter the query with a product name "LIKE" parameter, you can extend the query with the search "s" argument, that will do the trick as follow:

```<code>add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );
function handle_custom_query_var( $query, $query_vars ) {
    if ( isset( $query_vars['like_name'] ) && ! empty( $query_vars['like_name'] ) ) {
        $query['s'] = esc_attr( $query_vars['like_name'] );
    }

    return $query;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). tested and works.

USAGE example with custom argument "like_name":

```<code>$args = array(
    'limit' => 5,
    'like_name' => 'test',
);

wc_get_products( $args );
</code>```

Body:
In WooCommerce using wc_get_products() function I would like to find a way to filter products by name using the LIKE operator.

Actually I am only able to filter products by a specific defined name with:

$args = array(
    'limit' => 5,
    'name' => 'Test',
);
$result = wc_get_products( $args );

Is it possible to filter products where the name is LIKE 'test'?

Body:
If you look to WooCommerce official documentation for WC_Product_Query at the end on the section "Adding Custom Parameter Support" you will see that you can manipulate the WC_Product_Query with a custom hooked function.

So to filter the query with a product name "LIKE" parameter, you can extend the query with the search "s" argument, that will do the trick as follow:

add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );
function handle_custom_query_var( $query, $query_vars ) {
    if ( isset( $query_vars['like_name'] ) && ! empty( $query_vars['like_name'] ) ) {
        $query['s'] = esc_attr( $query_vars['like_name'] );
    }

    return $query;
}

Code goes in functions.php file of your active child theme (or active theme). tested and works.

USAGE example with custom argument "like_name":

$args = array(
    'limit' => 5,
    'like_name' => 'test',
);

wc_get_products( $args );


问:
Not able to pass data from HTTP post request to the javascript(expressjs) controller
I am using react at the frontend and expressjs at the backend. Creating a simple post request and passing json data to the back end via the front end. THe request consist of body{title:"some title", content:"some content"}. In the back end if I console.log(req.body), I am getting an empty object. Also If i use postman it works correctly.
Front end Code :

```<code>fetch(url, {
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: postData.title,
        content: postData.content
      })
    })
</code>```

BackEnd code:

```<code>const title = req.body.title;
  const content = req.body.content;
  console.log(req);
  res.status(201).json({
    message: 'created nicely',
    post: {
      _id: '78',
      title: title,
      content: content,
      creator: { name: 'mera naam' },
      createdAt: new Date()
    }
  });
</code>```

答:
The header property should be headers.

```<code>fetch(url, {
  method: method,
  headers: {
  //  ^^^
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: postData.title,
    content: postData.content,
  }),
})
</code>```

Because the Content-Type header isn't being sent due to the misspelling, body-parser or express.json() (whichever you're using) doesn't parse the request body.

Body:
I am using react at the frontend and expressjs at the backend. Creating a simple post request and passing json data to the back end via the front end. THe request consist of body{title:"some title", content:"some content"}. In the back end if I console.log(req.body), I am getting an empty object. Also If i use postman it works correctly.
Front end Code :

fetch(url, {
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: postData.title,
        content: postData.content
      })
    })

BackEnd code:

const title = req.body.title;
  const content = req.body.content;
  console.log(req);
  res.status(201).json({
    message: 'created nicely',
    post: {
      _id: '78',
      title: title,
      content: content,
      creator: { name: 'mera naam' },
      createdAt: new Date()
    }
  });

Body:
The header property should be headers.

fetch(url, {
  method: method,
  headers: {
  //  ^^^
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: postData.title,
    content: postData.content,
  }),
})

Because the Content-Type header isn't being sent due to the misspelling, body-parser or express.json() (whichever you're using) doesn't parse the request body.


问:
runn query in spring api
Hello stackoverflow team,

Im trying to calculate the conso duration of a given cod. and was getting error saying that id_client was not found in the resultSet. Does anyone knows how to fix it please?

The code below contains the 3 different parts:
model, repository and the Controller.

in my D1 model:

```<code>import javax.persistence.Column;
import javax.persistence.Id;

@Entity(name = "tmp.c1")
@Table(name = "c1", schema = "tmp")
public class D1 {

  @Id
  @Column(name = "id_client")
  private BigDecimal id_contrats;
  @Column(name = "cod")
  private BigDecimal cod;
  @Column(name = "name_client")
  private OffsetDateTime dat;
  @Column(name = "phone_client")
  private long phone_client;
  @Column(name = "funct")
  private string funct;
  @Column(name = "beg_consu")
  private OffsetDateTime beg_consu;
  @Column(name = "end_consu")
  private OffsetDateTime end_consu;

}
</code>```

In D1Repository

```<code>import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import io.A1.B1.api.P1.data.model.D1;

public interface D1Repository  {

  @Query(value = "SELECT (end_consu - beg_consu) FROM #{#entityName}" )
  T getConso(@Param("cod") BigDecimal cod);

}

}
</code>```

答:
You forgot to extend your interface:

```<code>...
public interface D1Repository extends JpaRepository<D1, BigDecimal> {

    @Query(value = "SELECT (end_consu - beg_consu) FROM #{#entityName}" )
    T getConso(@Param("cod") BigDecimal cod);

}
...
</code>```

And as a recommendation it would be better to use long instead of bigdecimal as the indetifier value. It is more efficient to use the smallest value capable of encompassing the largest possible value. You wouldn't use a tank to carry a liter of water right?

Best regards.

Title: runn query in spring api

Body:
Hello stackoverflow team,

Im trying to calculate the conso duration of a given cod. and was getting error saying that id_client was not found in the resultSet. Does anyone knows how to fix it please?

The code below contains the 3 different parts:
model, repository and the Controller.

in my D1 model:

import javax.persistence.Column;
import javax.persistence.Id;

@Entity(name = "tmp.c1")
@Table(name = "c1", schema = "tmp")
public class D1 {

  @Id
  @Column(name = "id_client")
  private BigDecimal id_contrats;
  @Column(name = "cod")
  private BigDecimal cod;
  @Column(name = "name_client")
  private OffsetDateTime dat;
  @Column(name = "phone_client")
  private long phone_client;
  @Column(name = "funct")
  private string funct;
  @Column(name = "beg_consu")
  private OffsetDateTime beg_consu;
  @Column(name = "end_consu")
  private OffsetDateTime end_consu;

}

In D1Repository

import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import io.A1.B1.api.P1.data.model.D1;

public interface D1Repository  {

  @Query(value = "SELECT (end_consu - beg_consu) FROM #{#entityName}" )
  T getConso(@Param("cod") BigDecimal cod);

}

}

Body:
You forgot to extend your interface:

...
public interface D1Repository extends JpaRepository<D1, BigDecimal> {

    @Query(value = "SELECT (end_consu - beg_consu) FROM #{#entityName}" )
    T getConso(@Param("cod") BigDecimal cod);

}
...

And as a recommendation it would be better to use long instead of bigdecimal as the indetifier value. It is more efficient to use the smallest value capable of encompassing the largest possible value. You wouldn't use a tank to carry a liter of water right?

Best regards.


问:
how to resolve the error GET http://localhost:8484/ 401
I am coding a login page using angular, spring security and spring boot.
the problem is that i get the following error when i click on the login button:

however I did put crossorgine in my backend part as you can see here:

```<code>package com.app.habilitation.controller;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {

    @GetMapping("/")
    public String login() {
        return "authenticaated succesfully";
    }

    @GetMapping("/getUsers")
    public String getUsers() {
        return "users";
    }
}
</code>```

and here is my "usercontroller" controller which manages authentication:

```<code>package com.app.habilitation.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure (HttpSecurity http) throws Exception {

        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").
        fullyAuthenticated().and().httpBasic();
    }

    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("{noop}hr").roles("USER");
    }
}
</code>```

and here is my routing in angular :

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';

const routes: Routes = [

  {path:'', redirectTo:"login", pathMatch:"full"},
  {path: "forgot", component: ForgotPasswordComponent},
  {path: 'login', component: LoginComponent},
  {path: 'inscription', component: InscriptionComponent},
  {path:'home-admin', component: HomeAdminComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

and this is my module :

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSliderModule } from '@angular/material/slider';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoginComponent } from './components/login/login.component';
import { MatCardModule } from '@angular/material/card';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {MatTabsModule} from '@angular/material/tabs';
import { MatFormFieldModule} from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { FormsModule } from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { RestapiService } from './restapi.service';
import { HttpClientModule } from '@angular/common/http';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ForgotPasswordComponent,
    InscriptionComponent,
    HomeAdminComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSliderModule,
    MDBBootstrapModule.forRoot(),
    MatCardModule,
    MatTabsModule,
    MatFormFieldModule,
    MatIconModule,
    MatCheckboxModule,
    MatInputModule,
    MatButtonModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [RestapiService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

and here is my service :

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  constructor(private http:HttpClient) { }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}
</code>```

this is my login.ts page :

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RestapiService } from 'src/app/restapi.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username:string;
  password:string;
  message:any
  constructor(private route: ActivatedRoute, private service:RestapiService, private router:Router) { }

  ngOnInit(): void {
  }

  doLogin() {
    let resp = this.service.login(this.username, this.password);
    resp.subscribe(data=> {
      this.message =data;
      this.router.navigate(["home-admin"])
    })
  }
}
</code>```

and this is my login.html page :

```<code><div class="cnx">
  <!-- Default form login -->
  <form class="text-center border border-light p-5">

    <p class="h4 mb-4">Authentification</p>

    <!-- Email -->
    <input type="text" id="defaultLoginFormEmail" class="form-control mb-4" placeholder="Login" name="login" [(ngModel)]="username">

    <!-- Password -->
    <input type="password" id="defaultLoginFormPassword" class="form-control mb-4" placeholder="Password" name="password" [(ngModel)]="password">

    <div class="d-flex justify-content-around">

      <div>
        <!-- Forgot password -->
        <a routerLink="/forgot">Mot de passe oublié ?</a>
      </div>
    </div>

    <!-- Sign in button -->
    <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-authentification" (click)="doLogin()">Se connecter</button>

    <!-- Register -->
    <p>Tu n'es pas un membre ?
      <a routerLink= "/inscription">Enregistre toi</a>
    </p>

  </form>
  <!-- Default form login -->

</div>
</code>```

(my spring boot server is running in port 8484 because I changed it in my application.properties file as you can see here):

```<code>spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel
spring.datasource.password=hr

server.port=8484
</code>```

can someone help me please ?

答:
It's a 401 Unauthorized error. It doesn't have anything to do with CORS. It seems you are missing a space after the 'Basic' string literal. Try the following

const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username + ":" + password)})
```

Notice an empty space after Basic.

Body:
I am coding a login page using angular, spring security and spring boot.
the problem is that i get the following error when i click on the login button:

however I did put crossorgine in my backend part as you can see here:

package com.app.habilitation.controller;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {

    @GetMapping("/")
    public String login() {
        return "authenticaated succesfully";
    }

    @GetMapping("/getUsers")
    public String getUsers() {
        return "users";
    }
}

and here is my "usercontroller" controller which manages authentication:

package com.app.habilitation.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure (HttpSecurity http) throws Exception {

        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").
        fullyAuthenticated().and().httpBasic();
    }

    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("{noop}hr").roles("USER");
    }
}

and here is my routing in angular :

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './components/login/login.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';

const routes: Routes = [

  {path:'', redirectTo:"login", pathMatch:"full"},
  {path: "forgot", component: ForgotPasswordComponent},
  {path: 'login', component: LoginComponent},
  {path: 'inscription', component: InscriptionComponent},
  {path:'home-admin', component: HomeAdminComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

and this is my module :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSliderModule } from '@angular/material/slider';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoginComponent } from './components/login/login.component';
import { MatCardModule } from '@angular/material/card';
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import {MatTabsModule} from '@angular/material/tabs';
import { MatFormFieldModule} from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { FormsModule } from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { InscriptionComponent } from './components/inscription/inscription.component';
import { RestapiService } from './restapi.service';
import { HttpClientModule } from '@angular/common/http';
import { HomeAdminComponent } from './components/home-admin/home-admin.component';
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ForgotPasswordComponent,
    InscriptionComponent,
    HomeAdminComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSliderModule,
    MDBBootstrapModule.forRoot(),
    MatCardModule,
    MatTabsModule,
    MatFormFieldModule,
    MatIconModule,
    MatCheckboxModule,
    MatInputModule,
    MatButtonModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [RestapiService],
  bootstrap: [AppComponent]
})
export class AppModule { }

and here is my service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  constructor(private http:HttpClient) { }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}

this is my login.ts page :

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RestapiService } from 'src/app/restapi.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username:string;
  password:string;
  message:any
  constructor(private route: ActivatedRoute, private service:RestapiService, private router:Router) { }

  ngOnInit(): void {
  }

  doLogin() {
    let resp = this.service.login(this.username, this.password);
    resp.subscribe(data=> {
      this.message =data;
      this.router.navigate(["home-admin"])
    })
  }
}

and this is my login.html page :

  <form class="text-center border border-light p-5">

Authentification

    <input type="text" id="defaultLoginFormEmail" class="form-control mb-4" placeholder="Login" name="login" [(ngModel)]="username">

    <input type="password" id="defaultLoginFormPassword" class="form-control mb-4" placeholder="Password" name="password" [(ngModel)]="password">

        Mot de passe oublié ?

    <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-authentification" (click)="doLogin()">Se connecter</button>

Tu n'es pas un membre ?
      Enregistre toi

  </form>

(my spring boot server is running in port 8484 because I changed it in my application.properties file as you can see here):

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel
spring.datasource.password=hr

server.port=8484

can someone help me please ?

Body:
It's a 401 Unauthorized error. It doesn't have anything to do with CORS. It seems you are missing a space after the 'Basic' string literal. Try the following

const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username + ":" + password)})

Notice an empty space after Basic.


问:
Assigning Alamofire result to array
I am trying to assign the result that is retrieved by Alamofire to an array, and have come across an issue.

I am using the Stripe API for products, it returns back a JSON object called "data:", I am trying to assign that data object only to that products array I have.

Here's my code

var products: [Product] = []
let stripeProducts = "stripe-products-api"

func createArray() {
  let stripeAuthHeader: HTTPHeaders = []

  AF.request(stripeProducts, headers: stripeAuthHeader).responseJSON {
     switch response.result {
     case .failure(let error):
       print(error)
     case .success:
       self.products = response.data \\ trying to access the data object from the JSON data
       print(self.products)
     }
  }
}
```

<p>JSON:</p>

```
 "object": "list",
  "data": [
    {
      "id": "prod_123456",
      "object": "product",
      "active": true,
      "attributes": [

      ],
      "created": 1590423835,
      "description": "Test",
      "images": [
        ""
      ],
      "livemode": false,
      "metadata": {
        "address": "Test"
      },
      "name": "Blue Jeans",
      "statement_descriptor": null,
      "type": "service",
      "unit_label": null,
      "updated": 1590653248
    }
]
```

Thank you for your help.

答:
You need to have Struct of Products </p>

```<code>  struct Datum: Decodable {
    let id, object: String
    let active: Bool
    let created: Int
    let datumDescription: String
    let images: [String]
    let livemode: Bool
    let metadata: Metadata
    let name: String
    let type: String
    let updated: Int

    enum CodingKeys: String, CodingKey {
        case id, object, active, created
        case datumDescription = "description"
        case images, livemode, metadata, name
        case type
        case updated
    }
}

// MARK: - Metadata
struct Metadata: Decodable {
    let address: String
}
</code>```

<p>Then parse it like this </p>

```<code>let products = try? newJSONDecoder().decode(Products.self, from: response.data)
</code>```

Title: Assigning Alamofire result to array

Body:
I am trying to assign the result that is retrieved by Alamofire to an array, and have come across an issue.

I am using the Stripe API for products, it returns back a JSON object called "data:", I am trying to assign that data object only to that products array I have.

Here's my code

var products: [Product] = []
let stripeProducts = "stripe-products-api"

func createArray() {
  let stripeAuthHeader: HTTPHeaders = []

  AF.request(stripeProducts, headers: stripeAuthHeader).responseJSON {
     switch response.result {
     case .failure(let error):
       print(error)
     case .success:
       self.products = response.data \\ trying to access the data object from the JSON data
       print(self.products)
     }
  }
}

JSON:

 "object": "list",
  "data": [
    {
      "id": "prod_123456",
      "object": "product",
      "active": true,
      "attributes": [

      ],
      "created": 1590423835,
      "description": "Test",
      "images": [
        ""
      ],
      "livemode": false,
      "metadata": {
        "address": "Test"
      },
      "name": "Blue Jeans",
      "statement_descriptor": null,
      "type": "service",
      "unit_label": null,
      "updated": 1590653248
    }
]

Thank you for your help.

Body:
You need to have Struct of Products

  struct Datum: Decodable {
    let id, object: String
    let active: Bool
    let created: Int
    let datumDescription: String
    let images: [String]
    let livemode: Bool
    let metadata: Metadata
    let name: String
    let type: String
    let updated: Int

    enum CodingKeys: String, CodingKey {
        case id, object, active, created
        case datumDescription = "description"
        case images, livemode, metadata, name
        case type
        case updated
    }
}

// MARK: - Metadata
struct Metadata: Decodable {
    let address: String
}

Then parse it like this

let products = try? newJSONDecoder().decode(Products.self, from: response.data)


问:
Creating a Rolling Mean with a Changing Window on Pandas
I have a Pandas dataframe as shown below. I am looking to creating a 7 day rolling mean for the temperature. I understand how to do this if it was one reading per day (dataset['rolling_temp'] = dataset.iloc[:,3].rolling(window=7).mean()) but the problem involves having a random number of readings per day. i.e. 1 day may be multiple rows.
 Any help would be much appreciated!

```<code>    day   temperature
1     1          18.0
2     1          19.0
3     2          18.0
4     3          17.0
5     4          18.5
6     4          19.0
7     5          18.0
8     6          19.0
9     7          18.5
10    8          17.5
11    9          17.0
12   10          18.0
13   11          19.0
14   12          19.5
15   13          16.5
16   13          17.0
</code>```

答:
How about doing a .groupby first and then doing .rolling? That solves the problem of having multiple days and gives you one value per day.

```<code>dataset = dataset.groupby('day')['temperature'].mean().reset_index().iloc[:,3].rolling(window=7).mean()
</code>```

Body:
I have a Pandas dataframe as shown below. I am looking to creating a 7 day rolling mean for the temperature. I understand how to do this if it was one reading per day (dataset['rolling_temp'] = dataset.iloc[:,3].rolling(window=7).mean()) but the problem involves having a random number of readings per day. i.e. 1 day may be multiple rows.
 Any help would be much appreciated!

    day   temperature
1     1          18.0
2     1          19.0
3     2          18.0
4     3          17.0
5     4          18.5
6     4          19.0
7     5          18.0
8     6          19.0
9     7          18.5
10    8          17.5
11    9          17.0
12   10          18.0
13   11          19.0
14   12          19.5
15   13          16.5
16   13          17.0

Body:
How about doing a .groupby first and then doing .rolling? That solves the problem of having multiple days and gives you one value per day.

dataset = dataset.groupby('day')['temperature'].mean().reset_index().iloc[:,3].rolling(window=7).mean()


问:
Why do undefined constants evaluate to true?
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

```<code><?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>
</code>```

The above example prints 'Huh?'

Thanks so much for your help! :)

答:
Undefined constants are treated as strings by PHP: docs.  Taking that fact, think it through in English language:

```<code>If "WHATEVER_THIS_ISNT_DEFINED", then do something.
</code>```

... it is logical that it is "true" - you aren't comparing anything to anything else.

That is why, when doing if statements, it is best practice to include a specific evaluation.  If you're checking for false, put it in the code: if (something === false) vs if (something).  If you're checking to see if it is set, use isset, and so on.

Also, this highlights the importance of developing with notices and warnings enabled.  Your server will throw a notice for this issue:

Notice:  Use of undefined constant
  MY_CONST - assumed 'MY_CONST' in
  some_script.php on line 5

Turn on notices and warnings to develop, turn them off for production.  Can only help!

Body:
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)

Body:
Undefined constants are treated as strings by PHP: docs.  Taking that fact, think it through in English language:

If "WHATEVER_THIS_ISNT_DEFINED", then do something.

... it is logical that it is "true" - you aren't comparing anything to anything else.

That is why, when doing if statements, it is best practice to include a specific evaluation.  If you're checking for false, put it in the code: if (something === false) vs if (something).  If you're checking to see if it is set, use isset, and so on.

Also, this highlights the importance of developing with notices and warnings enabled.  Your server will throw a notice for this issue:

Notice:  Use of undefined constant
  MY_CONST - assumed 'MY_CONST' in
  some_script.php on line 5

Turn on notices and warnings to develop, turn them off for production.  Can only help!


问:
Getting error on updating details if the user won't update the image in Android Studio
I have this fragment UserProfileFragment.java, Here I have a form with some fields also with one user profile Image-view where the user uploads its image, initially everything works fine but when the user wants to update the details after fetching its data from the server also fetching and setting the thumbnail of image on image-view, Here when the user updates the details without changing the current profile image of Image-view the app crashes giving the error as follows:

```<code>FATAL EXCEPTION: main
    Process: com.***.******, PID: 16313
    java.lang.NullPointerException
        at java.io.File.<init>(File.java:283)
        at com.***.*****.fragment.UserProfileFragment.Updatemyprofile(UserProfileFragment.java:576)
        at com.***.*****.fragment.UserProfileFragment.onClick(UserProfileFragment.java:343)
</code>```

When the user changes the profile image the app won't crash while updating.

My update user method as follows:

```<code>private void Updatemyprofile() {
//pass it like this
        File file = new File(picturePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
        RequestBody userid = RequestBody.create(MediaType.parse("multipart/form-data"), Constant.Userid);
        RequestBody role = RequestBody.create(MediaType.parse("multipart/form-data"), Constant.Role);
        RequestBody name = RequestBody.create(MediaType.parse("multipart/form-data"), edtfullName.getText().toString().trim());
        RequestBody pincode = RequestBody.create(MediaType.parse("multipart/form-data"), edtpincode.getText().toString().trim());
        RequestBody address = RequestBody.create(MediaType.parse("multipart/form-data"), edtaddress.getText().toString().trim());
        RequestBody gender = RequestBody.create(MediaType.parse("multipart/form-data"), Gender);
        RequestBody dob = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(epoch));

        apiInterface = RetrofitApiUtils.getAPIService();
        apiInterface.Updatemyprofile(Constant.AccessToken, userid, role, name, pincode, address, gender, dob, body ).enqueue(new Callback<UpdateUserProf>() {
            @Override
            public void onResponse(@NonNull Call<UpdateUserProf> call, @NonNull Response<UpdateUserProf> response) {
                try {
                    if (response.isSuccessful()) {
                        if (response.body() != null && response.body().getStatus().equals(true)) {
                            Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            UpdateUserProfData updateUserProfData = response.body().getData();
                            Log.d("Results ==>>...1", new GsonBuilder().setPrettyPrinting().create().toJson(updateUserProfData));
                            myprofile(Constant.Userid, Constant.Role);
                        } else {
                            Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        CallingToastMethod.showToast(getActivity());
                    }
                } catch (Exception e) {
                    try {
                        throw new IOException(e.toString());
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<UpdateUserProf> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
</code>```

Also I have tried this method for image validation:

```<code>  if (imgprofile.getDrawable() == null){
                        Toast.makeText(getActivity(), "Please select Image", Toast.LENGTH_SHORT).show();
                    }
</code>```

It works when the user enters its details for the first time but not working for updating it.

My interface class method as follows:

```<code>// Update My Profile
    @Multipart
    @POST("updatemyprofile.php")
        Call<UpdateUserProf> Updatemyprofile(@Header("Authorization") String authkey,
                                             @Part("id") RequestBody id,
                                             @Part("role") RequestBody role,
                                             @Part("name") RequestBody name,
                                             @Part("pincode") RequestBody pincode,
                                             @Part("address") RequestBody address,
                                             @Part("gender") RequestBody gender,
                                             @Part("dob") RequestBody dob,
                                             @Part MultipartBody.Part image);
</code>```

Please tell me how to do this I have been stuck on this for days and don't know how to do this...
Thank you! Be safe..

答:
May be your picturePath not found

Try inside  if condition:

```<code>if(picturePath != null){
File file = new File(picturePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
}```
```

Body:
I have this fragment UserProfileFragment.java, Here I have a form with some fields also with one user profile Image-view where the user uploads its image, initially everything works fine but when the user wants to update the details after fetching its data from the server also fetching and setting the thumbnail of image on image-view, Here when the user updates the details without changing the current profile image of Image-view the app crashes giving the error as follows:

FATAL EXCEPTION: main
    Process: com.***.******, PID: 16313
    java.lang.NullPointerException
        at java.io.File.<init>(File.java:283)
        at com.***.*****.fragment.UserProfileFragment.Updatemyprofile(UserProfileFragment.java:576)
        at com.***.*****.fragment.UserProfileFragment.onClick(UserProfileFragment.java:343)

When the user changes the profile image the app won't crash while updating.

My update user method as follows:

private void Updatemyprofile() {
//pass it like this
        File file = new File(picturePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
        RequestBody userid = RequestBody.create(MediaType.parse("multipart/form-data"), Constant.Userid);
        RequestBody role = RequestBody.create(MediaType.parse("multipart/form-data"), Constant.Role);
        RequestBody name = RequestBody.create(MediaType.parse("multipart/form-data"), edtfullName.getText().toString().trim());
        RequestBody pincode = RequestBody.create(MediaType.parse("multipart/form-data"), edtpincode.getText().toString().trim());
        RequestBody address = RequestBody.create(MediaType.parse("multipart/form-data"), edtaddress.getText().toString().trim());
        RequestBody gender = RequestBody.create(MediaType.parse("multipart/form-data"), Gender);
        RequestBody dob = RequestBody.create(MediaType.parse("multipart/form-data"), String.valueOf(epoch));

        apiInterface = RetrofitApiUtils.getAPIService();
        apiInterface.Updatemyprofile(Constant.AccessToken, userid, role, name, pincode, address, gender, dob, body ).enqueue(new Callback<UpdateUserProf>() {
            @Override
            public void onResponse(@NonNull Call<UpdateUserProf> call, @NonNull Response<UpdateUserProf> response) {
                try {
                    if (response.isSuccessful()) {
                        if (response.body() != null && response.body().getStatus().equals(true)) {
                            Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            UpdateUserProfData updateUserProfData = response.body().getData();
                            Log.d("Results ==>>...1", new GsonBuilder().setPrettyPrinting().create().toJson(updateUserProfData));
                            myprofile(Constant.Userid, Constant.Role);
                        } else {
                            Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        CallingToastMethod.showToast(getActivity());
                    }
                } catch (Exception e) {
                    try {
                        throw new IOException(e.toString());
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<UpdateUserProf> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

Also I have tried this method for image validation:

  if (imgprofile.getDrawable() == null){
                        Toast.makeText(getActivity(), "Please select Image", Toast.LENGTH_SHORT).show();
                    }

It works when the user enters its details for the first time but not working for updating it.

My interface class method as follows:

// Update My Profile
    @Multipart
    @POST("updatemyprofile.php")
        Call<UpdateUserProf> Updatemyprofile(@Header("Authorization") String authkey,
                                             @Part("id") RequestBody id,
                                             @Part("role") RequestBody role,
                                             @Part("name") RequestBody name,
                                             @Part("pincode") RequestBody pincode,
                                             @Part("address") RequestBody address,
                                             @Part("gender") RequestBody gender,
                                             @Part("dob") RequestBody dob,
                                             @Part MultipartBody.Part image);

Please tell me how to do this I have been stuck on this for days and don't know how to do this...
Thank you! Be safe..

Body:
May be your picturePath not found

Try inside  if condition:

if(picturePath != null){
File file = new File(picturePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
}```


问:
How to hide tab bar with animation in iOS?
So I have a button that is connected to a IBAction. When I press the button I want to hide the tab bar in my iOS app with a animation. This [self setTabBarHidden:hidden animated:NO];  or this [self.tabBarController setTabBarHidden:hidden animated:YES]; does not work. This is my code without the animation:

```<code>- (IBAction)picture1:(id)sender {
    [self.tabBarController.tabBar setHidden:YES];
}
</code>```

Any help would be greatly appreciated :D

答:
I went through the previous posts, so I came out with the solution below as subclass of UITabBarController

Main points are:

Written in Swift 5.1

Xcode 11.3.1

Tested on iOS 13.3

Simulated on iPhone 11 and iPhone 8 (so with and without notch)

Handles the cases where the user taps on the different tabs

Handles the cases where we programmatically change the value of selectedIndex

Handles the view controller orientation changes

Handles the corner casere where the app moved to background and back to foreground

Below the subclass TabBarController:

```<code>class TabBarController: UITabBarController {

    //MARK: Properties

    private(set) var isTabVisible:Bool = true
    private var visibleTabBarFrame:CGRect = .zero
    private var hiddenTabBarFrame:CGRect = .zero

    override var selectedIndex: Int {
        didSet { self.updateTabBarFrames() }
    }

    //MARK: View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.calculateTabBarFrames()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { (_) in }) { (_) in
            // when orientation changes, the tab bar frame changes, so we need to update it to the expected state
            self.calculateTabBarFrames()
            self.updateTabBarFrames()
        }
    }

    @objc private func appWillEnterForeground(_ notification:Notification){
        self.updateTabBarFrames()
    }

    //MARK: Private

    /// Calculates the frames of the tab bar and the expected bounds of the shown view controllers
    private func calculateTabBarFrames() {
        self.visibleTabBarFrame = self.tabBar.frame
        self.hiddenTabBarFrame = CGRect(x: self.visibleTabBarFrame.origin.x, y: self.visibleTabBarFrame.origin.y + self.visibleTabBarFrame.height, width: self.visibleTabBarFrame.width, height: self.visibleTabBarFrame.height)
    }

    /// Updates the tab bar and shown view controller frames based on the current expected tab bar visibility
    /// - Parameter tabIndex: if provided, it will update the view frame of the view controller for this tab bar index
    private func updateTabBarFrames(tabIndex:Int? = nil) {
        self.tabBar.frame = self.isTabVisible ? self.visibleTabBarFrame : self.hiddenTabBarFrame
        if let vc = self.viewControllers?[tabIndex ?? self.selectedIndex] {
            vc.additionalSafeAreaInsets.bottom = self.isTabVisible ? 0.0 : -(self.visibleTabBarFrame.height - self.view.safeAreaInsets.bottom)

        }
        self.view.layoutIfNeeded()
    }

    //MARK: Public

    /// Show/Hide the tab bar
    /// - Parameters:
    ///   - show: whether to show or hide the tab bar
    ///   - animated: whether the show/hide should be animated or not
    func showTabBar(_ show:Bool, animated:Bool = true) {
        guard show != self.isTabVisible else { return }
        self.isTabVisible = show
        guard animated else {
            self.tabBar.alpha = show ? 1.0 : 0.0
            self.updateTabBarFrames()
            return
        }
        UIView.animate(withDuration: 0.25, delay: 0.0, options: [.beginFromCurrentState,.curveEaseInOut], animations: {
            self.tabBar.alpha = show ? 1.0 : 0.0
            self.updateTabBarFrames()
        }) { (_) in }
    }

}

extension TabBarController: UITabBarControllerDelegate {
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if let tabIndex = self.tabBar.items?.firstIndex(of: item) {
            self.updateTabBarFrames(tabIndex: tabIndex)
        }
    }
}
</code>```

Sample usage from within a shown view controller:

```<code>// hide the tab bar animated (default)
(self.tabBarController as? TabBarController)?.showTabBar(false)
// hide the tab bar without animation
(self.tabBarController as? TabBarController)?.showTabBar(false, animated:false)
</code>```

Sample output iPhone 11

Sample output iPhone 8

EDIT :

Updated the code to respect the safe area bottom inset

If you're experiencing issues with this solution and your tab bar contains a navigation controller as direct child in the viewControllers array, you may want to make sure that the navigation controller topViewController has the property extendedLayoutIncludesOpaqueBars set to true (you can set this directly from the Storyboard). This should resolve the problem

Hope it helps someone :)

Body:
So I have a button that is connected to a IBAction. When I press the button I want to hide the tab bar in my iOS app with a animation. This [self setTabBarHidden:hidden animated:NO];  or this [self.tabBarController setTabBarHidden:hidden animated:YES]; does not work. This is my code without the animation:

- (IBAction)picture1:(id)sender {
    [self.tabBarController.tabBar setHidden:YES];
}

Any help would be greatly appreciated :D

Body:
I went through the previous posts, so I came out with the solution below as subclass of UITabBarController

Main points are:

Written in Swift 5.1

Xcode 11.3.1

Tested on iOS 13.3

Simulated on iPhone 11 and iPhone 8 (so with and without notch)

Handles the cases where the user taps on the different tabs

Handles the cases where we programmatically change the value of selectedIndex

Handles the view controller orientation changes

Handles the corner casere where the app moved to background and back to foreground

Below the subclass TabBarController:

class TabBarController: UITabBarController {

    //MARK: Properties

    private(set) var isTabVisible:Bool = true
    private var visibleTabBarFrame:CGRect = .zero
    private var hiddenTabBarFrame:CGRect = .zero

    override var selectedIndex: Int {
        didSet { self.updateTabBarFrames() }
    }

    //MARK: View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.calculateTabBarFrames()
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { (_) in }) { (_) in
            // when orientation changes, the tab bar frame changes, so we need to update it to the expected state
            self.calculateTabBarFrames()
            self.updateTabBarFrames()
        }
    }

    @objc private func appWillEnterForeground(_ notification:Notification){
        self.updateTabBarFrames()
    }

    //MARK: Private

    /// Calculates the frames of the tab bar and the expected bounds of the shown view controllers
    private func calculateTabBarFrames() {
        self.visibleTabBarFrame = self.tabBar.frame
        self.hiddenTabBarFrame = CGRect(x: self.visibleTabBarFrame.origin.x, y: self.visibleTabBarFrame.origin.y + self.visibleTabBarFrame.height, width: self.visibleTabBarFrame.width, height: self.visibleTabBarFrame.height)
    }

    /// Updates the tab bar and shown view controller frames based on the current expected tab bar visibility
    /// - Parameter tabIndex: if provided, it will update the view frame of the view controller for this tab bar index
    private func updateTabBarFrames(tabIndex:Int? = nil) {
        self.tabBar.frame = self.isTabVisible ? self.visibleTabBarFrame : self.hiddenTabBarFrame
        if let vc = self.viewControllers?[tabIndex ?? self.selectedIndex] {
            vc.additionalSafeAreaInsets.bottom = self.isTabVisible ? 0.0 : -(self.visibleTabBarFrame.height - self.view.safeAreaInsets.bottom)

        }
        self.view.layoutIfNeeded()
    }

    //MARK: Public

    /// Show/Hide the tab bar
    /// - Parameters:
    ///   - show: whether to show or hide the tab bar
    ///   - animated: whether the show/hide should be animated or not
    func showTabBar(_ show:Bool, animated:Bool = true) {
        guard show != self.isTabVisible else { return }
        self.isTabVisible = show
        guard animated else {
            self.tabBar.alpha = show ? 1.0 : 0.0
            self.updateTabBarFrames()
            return
        }
        UIView.animate(withDuration: 0.25, delay: 0.0, options: [.beginFromCurrentState,.curveEaseInOut], animations: {
            self.tabBar.alpha = show ? 1.0 : 0.0
            self.updateTabBarFrames()
        }) { (_) in }
    }

}

extension TabBarController: UITabBarControllerDelegate {
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if let tabIndex = self.tabBar.items?.firstIndex(of: item) {
            self.updateTabBarFrames(tabIndex: tabIndex)
        }
    }
}

Sample usage from within a shown view controller:

// hide the tab bar animated (default)
(self.tabBarController as? TabBarController)?.showTabBar(false)
// hide the tab bar without animation
(self.tabBarController as? TabBarController)?.showTabBar(false, animated:false)

Sample output iPhone 11

Sample output iPhone 8

EDIT :

Updated the code to respect the safe area bottom inset

If you're experiencing issues with this solution and your tab bar contains a navigation controller as direct child in the viewControllers array, you may want to make sure that the navigation controller topViewController has the property extendedLayoutIncludesOpaqueBars set to true (you can set this directly from the Storyboard). This should resolve the problem

Hope it helps someone :)


问:
TypeScript & runtime type-checking, simple solution in 2020
As we all know, TypeScript type-checks only at compile-time.

There are couple of existing approaches to add runtime checks, such as io-ts, but I'm left to wonder if there is a simpler way.

For example a Babel plugin that would transpile this:

type Todo = {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const resp = await fetch("https://jsonplaceholder.typicode.com/todos/1");

const data = await resp.json();

assert(data typeof Todo);
```

<p>to that:</p>

<pre class="lang-js prettyprint-override"><code>const __TodoType = {
  userId: Number;
  id: Number;
  title: String;
  completed: Boolean;
};
const __isTodoType = obj => (
  obj &&
  obj.constructor === Object &&
  Object.keys(obj).length === Object.keys(__TodoType).length &&
  Object.entries(obj)
    .every(([prop, val]) =>
      __TodoType[prop] && val &&
      __TodoType[prop] === val.constructor)
);

const resp = await fetch("https://jsonplaceholder.typicode.com/todos/1");

const data = await resp.json();

assert(__isTodoType(data));
</code>```

This would be a super simple solution and would cover many (if not most) uses cases. AFAICT, this would be enough for asserting serialization / data fetching.

Has someone managed to build such Babel plugin?

Edit - I know the existing libraries such as io-ts but I'm looking for something much simpler. The Babel Plugin I'm showcasing is vastly simpler (from the perspective of the plugin user) than anything else I've seen so far. I'm not sure why this hasn't been done before.

答: I was frustrated by this as well and ended up writing my own type guard generator called ‛ts-type-checked‛ available as an NPM module. It is a TypeScript transform that generates type guards based on your types.</p>

Body:
As we all know, TypeScript type-checks only at compile-time.

There are couple of existing approaches to add runtime checks, such as io-ts, but I'm left to wonder if there is a simpler way.

For example a Babel plugin that would transpile this:

type Todo = {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const resp = await fetch("https://jsonplaceholder.typicode.com/todos/1");

const data = await resp.json();

assert(data typeof Todo);

to that:

const __TodoType = {
  userId: Number;
  id: Number;
  title: String;
  completed: Boolean;
};
const __isTodoType = obj => (
  obj &&
  obj.constructor === Object &&
  Object.keys(obj).length === Object.keys(__TodoType).length &&
  Object.entries(obj)
    .every(([prop, val]) =>
      __TodoType[prop] && val &&
      __TodoType[prop] === val.constructor)
);

const resp = await fetch("https://jsonplaceholder.typicode.com/todos/1");

const data = await resp.json();

assert(__isTodoType(data));

This would be a super simple solution and would cover many (if not most) uses cases. AFAICT, this would be enough for asserting serialization / data fetching.

Has someone managed to build such Babel plugin?

Edit - I know the existing libraries such as io-ts but I'm looking for something much simpler. The Babel Plugin I'm showcasing is vastly simpler (from the perspective of the plugin user) than anything else I've seen so far. I'm not sure why this hasn't been done before.


问:
Count all unique values in list + their Total quantity and Total price per Item cost
I would like to have the following:

List of unique values from another list

Total occurrences of that value in the other list

Total price of the items per Item cost

Play here: https://docs.google.com/spreadsheets/d/11EHm7N4iK8N9oLb8VXrycTwPVHLmoBay4Z6dugaOr7I/edit?usp=sharing

Thank you in advance!

答:
Modify this example for your requirements.

Query:

=QUERY (A2:B7,"select A,sum(B) group by A")

Screenshot:


问:
How do I get the shard name?
I have created three shards. I want to add them to zones. But the API for adding to zones :

```<code>sh.addShardToZone(shard, zone)
</code>```

Requires a shard name. Now while defining config for the shards, I did not assign any name. I just specified the IP. Below is the extract from the sh.status command.

```<code> shards:
        {  "_id" : "ShardReplSet",  "host" : "ShardReplSet/localhost:27021,localhost:27022,localhost:27023",  "state" : 1 }
</code>```

What should I pass as shard name for adding shard to a zone?

答: According to https://docs.mongodb.com/manual/reference/method/sh.status/ shard name is the same as its _id (ShardReplSet in your output).

Title: How do I get the shard name?

Body:
I have created three shards. I want to add them to zones. But the API for adding to zones :

sh.addShardToZone(shard, zone)

Requires a shard name. Now while defining config for the shards, I did not assign any name. I just specified the IP. Below is the extract from the sh.status command.

 shards:
        {  "_id" : "ShardReplSet",  "host" : "ShardReplSet/localhost:27021,localhost:27022,localhost:27023",  "state" : 1 }

What should I pass as shard name for adding shard to a zone?


问:
How to model and create a custom deck of cards in rails?
I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):

```<code>class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end
</code>```

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.

A Deck model with

```<code>belongs_to :game
has_many :deck_cards
</code>```

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck

```<code>def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end
</code>```

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?

I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.

Any suggestions?

答:
```<code>class Deck < ActiveRecord::Base
  belongs_to :game
  has_many :deck_cards

  # To create new: Deck.new.build_deck
  def build_deck
    Card.find(:all).each do |card|
      self.deck_cards << DeckCard.new(:card => card)
    end
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):

class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.

A Deck model with

belongs_to :game
has_many :deck_cards

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck

def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?

I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.

Any suggestions?

OwnerDisplayName: Sarah Mei