text:
Q: Filebeat does not send logs to logstash So here's the big picture: my objective is to index large amounts of (.txt) data using the ELK stack + filebeat.
Basically, my problem is that filebeat seems to be unable to send logs to logstash. My guess is, some docker networking config is off...
The code for my project is available at https://github.com/mhyousefi/elk-docker.
THE ELK CONTAINER
To do so, I have one docker-compose.yml to run a container from the image sebp/elk, which looks like this:
version: '2'

services:
  elk:
    container_name: elk
    image: sebp/elk
    ports:
      - "5601:5601"
      - "9200:9200"
      - "5045:5044"
    volumes:
      - /path/to/volumed-folder:/logstash
    networks:
      - elk_net

networks:
  elk_net:
    driver: bridge

Once the container is created, I go to the container bash terminal and run the command:
/opt/logstash/bin/logstash --path.data /tmp/logstash/data -f /logstash/config/filebeat-config.conf

Running this command, I get the following logs and it will then just start waiting without printing any further logs:
$ /opt/logstash/bin/logstash --path.data /tmp/logstash/data -f /logstash/config/filebeat-config.conf
Sending Logstash's logs to /opt/logstash/logs which is now configured via log4j2.properties
[2018-08-14T11:51:11,693][INFO ][logstash.setting.writabledirectory] Creating directory {:setting=>"path.queue", :path=>"/tmp/logstash/data/queue"}
[2018-08-14T11:51:11,701][INFO ][logstash.setting.writabledirectory] Creating directory {:setting=>"path.dead_letter_queue", :path=>"/tmp/logstash/data/dead_letter_queue"}
[2018-08-14T11:51:12,194][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2018-08-14T11:51:12,410][INFO ][logstash.agent           ] No persistent UUID file found. Generating new UUID {:uuid=>"3646b6e4-d540-4c9c-a38d-2769aef5a05e", :path=>"/tmp/logstash/data/uuid"}
[2018-08-14T11:51:13,089][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"6.3.2"}
[2018-08-14T11:51:15,554][INFO ][logstash.pipeline        ] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>6, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50}
[2018-08-14T11:51:16,088][INFO ][logstash.outputs.elasticsearch] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://localhost:9200/]}}
[2018-08-14T11:51:16,101][INFO ][logstash.outputs.elasticsearch] Running health check to see if an Elasticsearch connection is working {:healthcheck_url=>http://localhost:9200/, :path=>"/"}
[2018-08-14T11:51:16,291][WARN ][logstash.outputs.elasticsearch] Restored connection to ES instance {:url=>"http://localhost:9200/"}
[2018-08-14T11:51:16,391][INFO ][logstash.outputs.elasticsearch] ES Output version determined {:es_version=>6}
[2018-08-14T11:51:16,398][WARN ][logstash.outputs.elasticsearch] Detected a 6.x and above cluster: the `type` event field won't be used to determine the document _type {:es_version=>6}
[2018-08-14T11:51:16,460][INFO ][logstash.outputs.elasticsearch] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["//localhost:9200"]}
[2018-08-14T11:51:16,515][INFO ][logstash.outputs.elasticsearch] Using mapping template from {:path=>nil}
[2018-08-14T11:51:16,559][INFO ][logstash.outputs.elasticsearch] Attempting to install template {:manage_template=>{"template"=>"logstash-*", "version"=>60001, "settings"=>{"index.refresh_interval"=>"5s"}, "mappings"=>{"_default_"=>{"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"}}}}}}}}
[2018-08-14T11:51:16,688][INFO ][logstash.outputs.elasticsearch] Installing elasticsearch template to _template/logstash
[2018-08-14T11:51:16,899][INFO ][logstash.inputs.beats    ] Beats inputs: Starting input listener {:address=>"0.0.0.0:5045"}
[2018-08-14T11:51:16,925][INFO ][logstash.pipeline        ] Pipeline started successfully {:pipeline_id=>"main", :thread=>"#<Thread:0x54ab986e run>"}
[2018-08-14T11:51:17,170][INFO ][org.logstash.beats.Server] Starting server on port: 5045
[2018-08-14T11:51:17,187][INFO ][logstash.agent           ] Pipelines running {:count=>1, :running_pipelines=>[:main], :non_running_pipelines=>[]}
[2018-08-14T11:51:17,637][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9601}

Now, this is what the filebeat-config.conf looks like:
input {
  beats {
    port => "5044"
  }
}

output {
  elasticsearch {
    hosts => [ "localhost:9200" ]
    index => "%{[@metadata][beat]}"
  }
}

THE FILEBEAT CONTAINER
My filebeat container is created using the bellow docker-compose.yml file:
version: "2"

services:
  filebeat:
    container_name: filebeat
    hostname: filebeat
    image: docker.elastic.co/beats/filebeat:6.3.0
    user: root
    # command: ./filebeat -c /usr/share/filebeat-volume/config/filebeat.yml -E name=mybeat
    volumes:
      # "volumed-folder" lies under ${PROJECT_DIR}/filebeat or could be anywhere else you wish
      - /path/to/volumed-folder:/usr/share/filebeat/filebeat-volume:ro
    networks:
      - filebeat_net

networks:
  filebeat_net:
    external: true

Once the container is created, I go to the container bash terminal, replace the existing filebeat.yml under /usr/share/filebeat with the one I have volumed, and run the command:
./filebeat -e -c ./filebeat.yml -E name="mybeat"

The terminal immediately displays the following logs:
root@filebeat filebeat]# ./filebeat -e -c ./filebeat.yml -E name="mybeat"
2018-08-14T12:13:16.325Z        INFO    instance/beat.go:492    Home path: [/usr/share/filebeat] Config path: [/usr/share/filebeat] Data path: [/usr/share/filebeat/data] Logs path: [/usr/share/filebeat/logs]
2018-08-14T12:13:16.325Z        INFO    instance/beat.go:499    Beat UUID: 3b4b3897-ef77-43ad-b982-89e8f690a96e
2018-08-14T12:13:16.325Z        INFO    [beat]  instance/beat.go:716    Beat info       {"system_info": {"beat": {"path": {"config": "/usr/share/filebeat", "data": "/usr/share/filebeat/data", "home": "/usr/share/filebeat", "logs": "/usr/share/filebeat/logs"}, "type": "filebeat", "uuid": "3b4b3897-ef77-43ad-b982-89e8f690a96e"}}}
2018-08-14T12:13:16.325Z        INFO    [beat]  instance/beat.go:725    Build info      {"system_info": {"build": {"commit": "a04cb664d5fbd4b1aab485d1766f3979c138fd38", "libbeat": "6.3.0", "time": "2018-06-11T22:34:44.000Z", "version": "6.3.0"}}}
2018-08-14T12:13:16.325Z        INFO    [beat]  instance/beat.go:728    Go runtime info {"system_info": {"go": {"os":"linux","arch":"amd64","max_procs":6,"version":"go1.9.4"}}}
2018-08-14T12:13:16.327Z        INFO    [beat]  instance/beat.go:732    Host info       {"system_info": {"host": {"architecture":"x86_64","boot_time":"2018-08-04T17:34:15Z","containerized":true,"hostname":"filebeat","ips":["127.0.0.1/8","172.28.0.2/16"],"kernel_version":"4.4.0-116-generic","mac_addresses":["02:42:ac:1c:00:02"],"os":{"family":"redhat","platform":"centos","name":"CentOS Linux","version":"7 (Core)","major":7,"minor":5,"patch":1804,"codename":"Core"},"timezone":"UTC","timezone_offset_sec":0}}}
2018-08-14T12:13:16.328Z        INFO    [beat]  instance/beat.go:761    Process info    {"system_info": {"process": {"capabilities": {"inheritable":["chown","dac_override","fowner","fsetid","kill","setgid","setuid","setpcap","net_bind_service","net_raw","sys_chroot","mknod","audit_write","setfcap"],"permitted":["chown","dac_override","fowner","fsetid","kill","setgid","setuid","setpcap","net_bind_service","net_raw","sys_chroot","mknod","audit_write","setfcap"],"effective":["chown","dac_override","fowner","fsetid","kill","setgid","setuid","setpcap","net_bind_service","net_raw","sys_chroot","mknod","audit_write","setfcap"],"bounding":["chown","dac_override","fowner","fsetid","kill","setgid","setuid","setpcap","net_bind_service","net_raw","sys_chroot","mknod","audit_write","setfcap"],"ambient":null}, "cwd": "/usr/share/filebeat", "exe": "/usr/share/filebeat/filebeat", "name": "filebeat", "pid": 93, "ppid": 28, "seccomp": {"mode":"filter"}, "start_time": "2018-08-14T12:13:15.530Z"}}}
2018-08-14T12:13:16.328Z        INFO    instance/beat.go:225    Setup Beat: filebeat; Version: 6.3.0
2018-08-14T12:13:16.329Z        INFO    pipeline/module.go:81   Beat name: mybeat
2018-08-14T12:13:16.329Z        WARN    [cfgwarn]       beater/filebeat.go:61   DEPRECATED: prospectors are deprecated, Use `inputs` instead. Will be removed in version: 7.0.0
2018-08-14T12:13:16.330Z        INFO    [monitoring]    log/log.go:97   Starting metrics logging every 30s
2018-08-14T12:13:16.330Z        INFO    instance/beat.go:315    filebeat start running.
2018-08-14T12:13:16.330Z        INFO    registrar/registrar.go:112      Loading registrar data from /usr/share/filebeat/data/registry
2018-08-14T12:13:16.330Z        INFO    registrar/registrar.go:123      States Loaded from registrar: 0
2018-08-14T12:13:16.331Z        WARN    beater/filebeat.go:354  Filebeat is unable to load the Ingest Node pipelines for the configured modules because the Elasticsearch output is not configured/enabled. If you have already loaded the Ingest Node pipelines or are using Logstash pipelines, you can ignore this warning.
2018-08-14T12:13:16.331Z        INFO    crawler/crawler.go:48   Loading Inputs: 1
2018-08-14T12:13:16.331Z        INFO    log/input.go:111        Configured paths: [/usr/share/filebeat-volume/data/Shakespeare.txt]
2018-08-14T12:13:16.331Z        INFO    input/input.go:87       Starting input of type: log; ID: 1899165251698784346
2018-08-14T12:13:16.331Z        INFO    crawler/crawler.go:82   Loading and starting Inputs completed. Enabled inputs: 1

And the every 30 seconds, it displays the following:
2018-08-14T12:13:46.334Z        INFO    [monitoring]    log/log.go:124  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":20,"time":{"ms":24}},"total":{"ticks":30,"time":{"ms":36},"value":30},"user":{"ticks":10,"time":{"ms":12}}},"info":{"ephemeral_id":"16c484f0-0cf8-4c10-838d-b39755284af9","uptime":{"ms":30017}},"memstats":{"gc_next":4473924,"memory_alloc":3040104,"memory_total":3040104,"rss":21061632}},"filebeat":{"harvester":{"open_files":0,"running":0}},"libbeat":{"config":{"module":{"running":0}},"output":{"type":"logstash"},"pipeline":{"clients":1,"events":{"active":0}}},"registrar":{"states":{"current":0}},"system":{"cpu":{"cores":6},"load":{"1":1.46,"15":1.52,"5":1.66,"norm":{"1":0.2433,"15":0.2533,"5":0.2767}}}}}}

And no index-patterns are created in Kibana.
This is what my filebeat.yml looks like:
filebeat.inputs:
- type: log
  paths:
    - /path/to/a/log/file

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

setup.kibana:
  host: "localhost:5601"

I have used this stackoverflow question to define the networks section of my docker-compose files, so that my containers can talk to each other using their container_names.
So, when I do
output.logstash:
  hosts: ["elk:5044"]

I expect filebeat to send logs to port 5044 of the elk container, where logstash is listening for incoming messages.
After I run filebeat inside its terminal, I actually do see the following logs in the terminal in which I did docker-compose up elk:
elk    |
elk    | ==> /var/log/elasticsearch/elasticsearch.log <==
elk    | [2018-08-14T11:51:16,974][INFO ][o.e.c.m.MetaDataIndexTemplateService] [fZr_LDR] adding template [logstash] for index patterns [logstash-*]

which I am assuming some sort of communication has been made between logstash and filebeat.
However, on the other hand, despite following the mentioned stackoverflow response, I cannot do ping elk in my filebeat container. The hostname is not resolved.
I appreciate any help!
UPDATE (Aug 15, 2018)
I think I don't even need to open a port for my ELK container. What happens is that Logstash is listening on port 5044 inside the container. As long as the filebeat.yml file inside theFilebeat container can resolve the ELK host and then send its logs over to 5044 port there ("elk:5044"), they should all work fine.
That's why I deleted the "5045:5044" line, and fixed the networks section inside the docker-compose.yml file for my Filebeatcontainer to include the following:
networks:
  filebeat_net:
    external:
      name: elk_elk_net

And it seems to work, since when I do ping elk, I am getting a connection.
While the networking issue is resolved (I can ping!), the connection between Logstash and Filebeat remains troublesome, and keep getting the following message every 30 seconds.
2018-08-14T12:13:46.334Z        INFO    [monitoring]    log/log.go:124  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":20,"time":{"ms":24}},"total":{"ticks":30,"time":{"ms":36},"value":30},"user":{"ticks":10,"time":{"ms":12}}},"info":{"ephemeral_id":"16c484f0-0cf8-4c10-838d-b39755284af9","uptime":{"ms":30017}},"memstats":{"gc_next":4473924,"memory_alloc":3040104,"memory_total":3040104,"rss":21061632}},"filebeat":{"harvester":{"open_files":0,"running":0}},"libbeat":{"config":{"module":{"running":0}},"output":{"type":"logstash"},"pipeline":{"clients":1,"events":{"active":0}}},"registrar":{"states":{"current":0}},"system":{"cpu":{"cores":6},"load":{"1":1.46,"15":1.52,"5":1.66,"norm":{"1":0.2433,"15":0.2533,"5":0.2767}}}}}}

In the terminal of my filebeat container, I am also getting the following logs periodically when running the filebeat command in verbose mode:
2018-08-15T16:26:41.986Z        DEBUG   [input] input/input.go:124      Run input
2018-08-15T16:26:41.986Z        DEBUG   [input] log/input.go:147        Start next scan
2018-08-15T16:26:41.986Z        DEBUG   [input] log/input.go:168        input states cleaned up. Before: 0, After: 0, Pending: 0

A: I was finally able to resolve my problem. First, the issue with container connection was resolved as mentioned in the UPDATE (Aug 15, 2018) section of my question.
The problem with Filebeat not sending logs over to Logstash was due to the fact that I had not explicitly specified my input/output configurations to be enabled (which is a frustrating fact to me since it is not clearly mentioned in the docs). So, changing my filebeat.yml file the following fixed did the trick.
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - ${PWD}/filebeat-volume/data/*.txt

output.logstash:
  enabled: true
  hosts: ["elk:5044"]
  index: "your cusotm index"

setup.kibana:
  host: "elk:5601"

A: Networking in namespaced in containers by default, which means each container gets it's own private ip, and localhost in a container is local to just that container.
That means you need to specify the DNS entry of the elastic server, not localhost in your config file. With compose and swarm mode, the service name is automatically setup with a DNS entry pointing to your containers:
input {
  beats {
    port => "5044"
  }
}

output {
  elasticsearch {
    hosts => [ "elk:9200" ]
    index => "%{[@metadata][beat]}"
  }
}

This also requires that you share a common network between the containers. You get this by default when creating everything in the same compose file. When you have multiple stacks/projects being deployed, you'll need to define a common external network in at least one file. Since I can't tell your elk project name to know the full network name, here is the change you can make to elk to connect it to filebeat_net instead:
version: '2'

services:
  elk:
    container_name: elk
    image: sebp/elk
    ports:
      - "5601:5601"
      - "9200:9200"
      - "5045:5044"
    volumes:
      - /path/to/volumed-folder:/logstash
    networks:
      - elk_net
      - filebeat_net

networks:
  elk_net:
    driver: bridge
  filebeat_net:
    external: true

A: I had a similar problem, but what happened to me was that my port was not being exposed to the application outside the container.
What I did was just to expose the port for the other applications.
I did it at the time I was installing the docker with the option -p 5044, 5044 is the port which is going to listen the requests.
docker run -d --name logstash
-p 5044:5044
--restart=always
-e "XPACK.MONITORING.ELASTICSEARCH.URL=http://ELASTIC_IP:9200"
docker.elastic.co/logstash/logstash:7.0.0


text:
Q: left hand/foot rule in SQL Server 2016 I have seen that SQL Server uses left hand/foot rule while creating polygons. But the articles I have read are talking about SQL Server 2012 and I am not sure if it's the case with SQL Server 2016 as well. Do we have to start specifying the points in counter clock wise direction for left hand/foot rule to generate polygons.

A: In SQL, I understand that if we specify points in clockwise direction, it takes all the points in the entire world except the region of the polygon whereas if we specify in counter clockwise direction, we get the expected region.

redpajama_set_name: RedPajamaStackExchange


text:
Q: (Hide Video)CSS display: none not working with @media query for iPhone I'm trying to use a @media query to hide a video which auto-plays on loop as a landing page. I want to replace the hidden video with a short, full width, responsive .gif background.
Here is a copy of the CSS in use: http://pastie.org/private/dhi4c4dxvysne0r9fkg8g#1
I'm trying to use
@media (max-width: 767px) {
.fullscreen-bg {
background: url('landing.gif') center center / cover no-repeat;
}

.fullscreen-bg__video {
display:none!important;

}

I have succeeded in replacing the video with a looping gif, but the large play button still appears on ios devices even though the video itself isn't visible.
Does anyone know of a workaround or fix for this?
EDIT: The large play button is rendered by Safari and apparently you aren't able to hide it. This means that hiding the video will not cut the mustard for responsive-ness.
So how would I go about requesting that the video doesn't load at all with a media query?

A: .video-container {
  background: transparent;
}
.video-container .video {
  display: block;
}
@media (max-width: 767px) {
  .video-container {
    background: url('landing.gif') center center / cover no-repeat;
  }
  .video-container .video {
    display: none;
  }
}


text:
Q: Remove data with non-datetime input in DataFrame I have a dataframe and I would like to filter the data based on the 'timestamp' column. Supposedly, if there are non-numerical data (which also mean string) in the timestamp column, I would like to extract the entire row of data and save it into another file.

A: You can check if the values in the timestamps columns are timestamps by using the isinstance() function. This will allow you to store them in a list. Here is a way you could do it :
import datetime

df = pd.DataFrame({'Timestamp' : [datetime.datetime(2020, 1, 1), 'aer', datetime.datetime(2019, 3, 1)]})

timestamps = [x for x in df['Timestamp'] if not(isinstance(x, datetime.date)) ]
new_df = pd.DataFrame({'Timestamp' : timestamps }))

Out :
Timestamp
0   aer


text:
Q: How can I safely delete the old kernel version from the /boot partition on Ubuntu? I am not so into Linux and I have the following problem related to the fact that my /boot partition seems to be full and it seems to cause a problem trying to install a program.
I am using Ubuntu Ubuntu 16.04.1 LTS
I try to explain in detail my doubts because I am not so into system engineering (I am a software developer).
1) Performing the lsblk statment lists information about all available or the specified block devices.
Empirically I think that it should show the list of all the partitions/mounted disks or something like this. What exactly means with the terms block devices?
So if I perform this statment on my Ubuntu system I obtain:
root@MyServer-VPS:~# lsblk
NAME           MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
fd0              2:0    1    4K  0 disk
sda              8:0    0   20G  0 disk
├─sda1           8:1    0  476M  0 part /boot
├─sda2           8:2    0    1K  0 part
├─sda3           8:3    0   10G  0 part
│ └─vg-lv_root 252:0    0 18.6G  0 lvm  /
└─sda5           8:5    0  9.5G  0 part
  ├─vg-lv_root 252:0    0 18.6G  0 lvm  /
  └─vg-lv_swap 252:1    0  952M  0 lvm  [SWAP]
sr0             11:0    1 1024M  0 rom

So what is the difference between disk, part (it should be a partition of the parent disk), lvm and rom?
A specific partition is boot, this one:
sda1           8:1    0  476M  0 part /boot

that is a sda disk partition.
From what I know it should contains the Linux Kernel downloaded versions. Is it?
Ok, the mount point is /boot so I think that it is the /boot directory into my system (is it?), this is the content:
root@MyServer-VPS:/boot# ls
abi-4.4.0-21-generic  config-4.4.0-21-generic  grub                         System.map-4.4.0-21-generic  vmlinuz-4.4.0-21-generic
abi-4.4.0-31-generic  config-4.4.0-31-generic  initrd.img-4.4.0-21-generic  System.map-4.4.0-31-generic  vmlinuz-4.4.0-31-generic
abi-4.4.0-34-generic  config-4.4.0-34-generic  initrd.img-4.4.0-31-generic  System.map-4.4.0-34-generic  vmlinuz-4.4.0-34-generic
abi-4.4.0-38-generic  config-4.4.0-38-generic  initrd.img-4.4.0-34-generic  System.map-4.4.0-38-generic  vmlinuz-4.4.0-38-generic
abi-4.4.0-42-generic  config-4.4.0-42-generic  initrd.img-4.4.0-38-generic  System.map-4.4.0-42-generic  vmlinuz-4.4.0-42-generic
abi-4.4.0-45-generic  config-4.4.0-45-generic  initrd.img-4.4.0-42-generic  System.map-4.4.0-45-generic  vmlinuz-4.4.0-45-generic
abi-4.4.0-47-generic  config-4.4.0-47-generic  initrd.img-4.4.0-45-generic  System.map-4.4.0-47-generic  vmlinuz-4.4.0-47-generic
abi-4.4.0-51-generic  config-4.4.0-51-generic  initrd.img-4.4.0-47-generic  System.map-4.4.0-51-generic  vmlinuz-4.4.0-51-generic
abi-4.4.0-53-generic  config-4.4.0-53-generic  initrd.img-4.4.0-51-generic  System.map-4.4.0-53-generic  vmlinuz-4.4.0-53-generic
abi-4.4.0-57-generic  config-4.4.0-57-generic  initrd.img-4.4.0-53-generic  System.map-4.4.0-57-generic  vmlinuz-4.4.0-57-generic
abi-4.4.0-59-generic  config-4.4.0-59-generic  lost+found                   System.map-4.4.0-59-generic  vmlinuz-4.4.0-59-generic

So what these contents exactly represents? Are the differents Linux kernel versions downloaded on this system?
What are the difference between the abi-, config-, initrd.img-, System.map- and vmlinuz-4 files?
How can I detect the used kernel version?
2) Performing the df -h statment I obtain this output:
root@MyServer-VPS:~# df -h
Filesystem              Size  Used Avail Use% Mounted on
udev                    477M     0  477M   0% /dev
tmpfs                   100M   16M   84M  16% /run
/dev/mapper/vg-lv_root   19G   12G  6.3G  64% /
tmpfs                   497M     0  497M   0% /dev/shm
tmpfs                   5.0M     0  5.0M   0% /run/lock
tmpfs                   497M     0  497M   0% /sys/fs/cgroup
/dev/sda1               461M  458M     0 100% /boot
tmpfs                   100M     0  100M   0% /run/user/0

In particular I have that:
/dev/sda1               461M  458M     0 100% /boot

So it means that my /boot partition is completly full?
My problem is: can I saftly deetect delete all the old kernel version (the not used one) to free up space in the /boot ?
How can I do it?

A: old stuff is deleted using
sudo apt-get autoremove

this will keep you only 2 kernel.


text:
Q: Whether the flash size of cobalt including run-time resource will keep increasing? For coablt 10.56829, the built out cobalt binary(QA) has about 21 MB flash size, and the content resource has about 53M flash size, totally about 74 MB, it means it needs about 74M flash size at run time, so is there a chance to reduce the flash size of cobalt? And whether it would keep a limit to avoid the flash size of cobalt which may be keeping increasing in future?

A: we're actively monitoring Cobalt's package size and trying to keep it as low as possible.  That said, as development occurs, it may of course fluctuate.
If you're interested in reducing your package's total size, one option to explore is to adjust the font package used with your build.  You can set this by adjusting the value of 'cobalt_font_package' in your gyp_configuration.gypi file.  See https://cobalt.googlesource.com/cobalt/+/master/src/cobalt/build/config/base.gypi#97 for more information.


text:
Q: internal server error while trying to load content into xdocument     XDocument xDoc = new XDocument();
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
    req.Timeout = 1000 * 60 * 5;
    WebResponse res = req.GetResponse();
    Stream responseStream = res.GetResponseStream();
    xDoc = XDocument.Load(responseStream);
    responseStream.Close();

I am trying to use the above code to load a uri into an xdocument. I am using the HttpWebRequest and WebResponse to avoid the timeout error.
Now the problem is that most of the times the code does work but at the point where I was getting a "timeout" error before, now I am facing an "Internal server error (500)" when trying to use the above code. Any clues as to how to solve this issue? Code examples would be of great help.
Thanks!

A: I might be mistaken, but the Http 500 Interal server error is being generated by the server hosting the uri that you call.  Your code might be correct, but the server is returning an error.  You need to debug the server script (if you control it) or alternatively handle the http 500 error in your code.
You should call the uri directly from a browser to see if that triggers the http 500 internal server error.  If so (and you control the web server) you could check the server log for more details.
Hope this helps.


text:
Q: getDeclaredMethod keeps giving NoSuchMethodException I have seen some posts about the NoSuchMethodException with getDeclaredMethod but I still can't get rid of the problem.
I isolated the problem to a bare bones, can someone make this working:
public class MainMethodTest {

    public static void main(String[] args) {

        try {
            //Method m = MainMethodTest.class.getDeclaredMethod("main");
            Method m = MainMethodTest.class.getDeclaredMethod("main", MainMethodTest.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

}

A: Method m = MainMethodTest.class.getDeclaredMethod("main", MainMethodTest.class);

Is trying to find main(MainMethodTest argument) method which you don't have in your code.
If you want to get main(String[] argument) method use
Method m = MainMethodTest.class.getDeclaredMethod("main", String[].class);

A: the second parameter of the method getDeclaredMethod is the arguments of the method that you want to get. In your case, it is the main. So you have to specify the arg Parameters.
    Class[] argTypes = new Class[] { String[].class };
    Method main = MainMethodTest.class.getDeclaredMethod("main", argTypes);

Check this code on how to invoke the main method.


text:
Q: javascript filter and include method usage in nested array object       const post =  {
      title: 'New Title',
      _id: '5e5782c4f695d70b6e376c7b',
      content: '',
      data: [],
      images: [
        {
          data: [],
          _id: '5e5782c4f695d70b6e376c7c',
          width: 473,
          height: 1000
        },
        {
          data: [],
          _id: '5e5782e7f695d70b6e376c82',
          width: 601,
          height: 1000
        }
      ],
      timestamp: 1582793412754
    }
    const rec_id = '5e5782c4f695d70b6e376c7c';

 const myId = '5e5782c4f695d70b6e376d4d';

   if(post.images.some(img => img._id === rec_id)) {

    const data = post.images.data.filter(id => id.toString() !== myId.toString());

        let isData = false;
        if (data.length === post.data.length) {
          data.push(myId);
          isData = true;
        }
        post.image.data = data;
     }
    console.log(post)

Here, rec_id is match by post.images._id, I want to add myId inside post.images.data array if myId is found same inside post.images.data array then toggle the value add and remove base on rec_id if other myId found it should push value. Tried this way doesn't get success can you please guide how to make this.
Thanks
Output should be
const post =  {
  title: 'New Title',
  _id: '5e5782c4f695d70b6e376c7b',
  content: '',
  data: [],
  images: [
    {
      data: ['5e5782c4f695d70b6e376d4d'],
      _id: '5e5782c4f695d70b6e376c7c',
      width: 473,
      height: 1000
    },
    {
      data: [],
      _id: '5e5782e7f695d70b6e376c82',
      width: 601,
      height: 1000
    }
  ],
  timestamp: 1582793412754
}

A: You could try this way also
const post = {
    title: 'New Title',
    _id: '5e5782c4f695d70b6e376c7b',
    content: '',
    data: [],
    images: [{
            data: [],
            _id: '5e5782c4f695d70b6e376c7c',
            width: 473,
            height: 1000
        },
        {
            data: [],
            _id: '5e5782e7f695d70b6e376c82',
            width: 601,
            height: 1000
        }
    ],
    timestamp: 1582793412754
}

const doc_id = '5e5782c4f695d70b6e376c7c';

const myId = '5e5782c4f695d70b6e376d4d';

if (post.images.some(img => img._id == doc_id)) {
    post.images.forEach(function (e, i) {
        if (post.images[i]._id == doc_id) {
            data = post.images[i].data.filter(userId => userId.toString() !== myId.toString());
            let isData = false;
            if (data.length === post.images[i].data.length) {
                data.push(myId);
                isData = true;
            }
            post.images[i].data = data;
            return data;
        }
    })
}
console.log(post);

A: If myId is not found under post.image.data array, then we need to push myId in the array.
Below is the working snippet with above logic:
 const post =  {
  title: 'New Title',
  _id: '5e5782c4f695d70b6e376c7b',
  content: '',
  data: [],
  images: [
    {
      data: [],
      _id: '5e5782c4f695d70b6e376c7c',
      width: 473,
      height: 1000
    },
    {
      data: [],
      _id: '5e5782e7f695d70b6e376c82',
      width: 601,
      height: 1000
    }
  ],
  timestamp: 1582793412754
}
  const rec_id = '5e5782c4f695d70b6e376c7c';
  const myId = '5e5782c4f695d70b6e376d4d';

 if(post.images.some(img => img._id === rec_id)) {
   post.images.forEach(function(e,i){
   if (post.images[i]._id == rec_id) { //myid is added only if rec_id matches
     if (post.images[i].data.length==0){
            post.images[i].data.push(myId);
      }
     else{
             const data = post.images[i].data.filter(id => id.toString() !== myId.toString());
              if (data.length>0)  post.images[i].data.push(myId);
      }
     }
    });
  }
 console.log(post)


text:
Q: Bash character class parameter expansion inconsistent behavior Here are all the steps which seems to suggest to me a bug in bash.
Version and platform information
--> cat /etc/os-release
NAME="Ubuntu"
VERSION="14.04.5 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.5 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
--> bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Detailed steps of the issue:
--> ls
--> touch a aa aaa b bb bbb
--> ls *[:alpha:]
a  aa  aaa
--> rm a aa aaa
--> ls *[:alpha:]
ls: cannot access *[:alpha:]: No such file or directory

Why would '*[:alpha:]' list 'a*' filenames and not 'b*' ones?
For those who wonder, to get proper behavior, one has to use *([[:alpha:]]). But that doesn't explain the inconsistency shown up here.

A: There is no inconsistency. With the duplicate characters removed, [:alpha:] is equivalent to [:alph].
And so ls *[:alpha:] is really equivalent to ls *[:alph], and only a, aa and aaa match that, so that's what you got as output.
After you deleted those files,
ls *[:alph] will find no matches, hence the error you received.
If you want to use the [:alpha:] character class,
you need to write as [[:alpha:]].


text:
Q: Получить имя пользователя Windows. PHP, JS. Перечитал интернеты, вроде никак.
Тогда как запустить пакетный файл средствами PHP или JS?
Вообще чем угодно, главное запустить bat с веб страницы?
Ибо echo %username% запросто пишет требуемое.


text:
Q: Intellij Maven default annotation processors configuration getting lost I configured my Maven project to work with a Annotation processor options in IntelliJ Idea 2017.1 by adding two options that correspond to two compilerArg of maven-compiler-plugin.
My problem : IntelliJ reset the annotation processing configuration every time the pom.xml is modified. Is there any way to keep the configuration ?

A: Fixed with the new version of the Maven compiler plugin
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${mapstruct.version}</version>
            </path>
        </annotationProcessorPaths>
        <compilerArgs>
            <arg>-Amapstruct.defaultComponentModel=${mapstruct.defaultComponentModel}</arg>
        </compilerArgs>
    </configuration>
</plugin>

The previous configuration was
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${mapstruct.version}</version>
            </path>
        </annotationProcessorPaths>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <compilerArgs>
            <compilerArg>
                -Amapstruct.defaultComponentModel=${mapstruct.defaultComponentModel}
            </compilerArg>
        </compilerArgs>
    </configuration>
</plugin>


text:
Q: Blog post is redirecting to home page It wasn't doing this before, and I'm not sure what has caused this to change.
I have tried:

*

*clearing cache

*changing permalink structure, saving, and setting back again

*unpublishing and republishing

So far nothing has worked. The blog post shows up on the /blog page, however when I click on the 'read more' link, it redirects to the home page. If I try navigating directly, it will also navigate to the home page.


text:
Q: UUID field in fresh Postgresql DB failing ValidationError: ["'1' is not a valid UUID."] Wondering if anyone can shed some light on what this error may be coming from.  I have just moved to Postgresql from sqllite and at the same time changed my ID fields to UUID.  For most of the models it works however I have isolated a few which are causing the migration to fail.
The error is:

AttributeError: 'int' object has no attribute 'replace'
  django.core.exceptions.ValidationError: ["'1' is not a valid UUID."]

As I said this is a new db and am not aware of any code that would create rows upon migration so not sure where the 1 would be coming from.
This question appears quite similar however the asker is explicitly setting the integer and trying to pass it as a UUID
Model
import uuid

class Question(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

Trace

        Running migrations:
      Applying survey.0001_initial...Traceback (most recent call last):
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2363, in to_python
        return uuid.UUID(value)
      File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/uuid.py", line 137, in __init__
        hex = hex.replace('urn:', '').replace('uuid:', '')
    AttributeError: 'int' object has no attribute 'replace'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "manage.py", line 15, in
        execute_from_command_line(sys.argv)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
        utility.execute()
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
        self.execute(*args, **cmd_options)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
        output = self.handle(*args, **options)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
        fake_initial=fake_initial,
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
        state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
        state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
        state = migration.apply(state, schema_editor)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
        operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
        field,
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 407, in add_field
        definition, params = self.column_sql(model, field, include_default=True)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 152, in column_sql
        default_value = self.effective_default(field)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 224, in effective_default
        default = field.get_db_prep_save(default, self.connection)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/related.py", line 936, in get_db_prep_save
        return self.target_field.get_db_prep_save(value, connection=connection)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 767, in get_db_prep_save
        return self.get_db_prep_value(value, connection=connection, prepared=False)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2354, in get_db_prep_value
        value = self.to_python(value)
      File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2368, in to_python
        params={'value': value},
    django.core.exceptions.ValidationError: ["'1' is not a valid UUID."]


text:
Q: Ember Data cannot read property 'async' of undefined Using Ember v1.8 beta 3+ with Ember Data 1.0 beta 10- you receive this error:
Error while processing route: index Cannot read property 'async' of undefined TypeError: Cannot read property 'async' of undefined
    at Relationship [as _super$constructor] (http://builds.emberjs.com/canary/ember-data.js:9523:46)
    at new BelongsToRelationship (http://builds.emberjs.com/canary/ember-data.js:9736:12)
    at createRelationshipFor (http://builds.emberjs.com/canary/ember-data.js:9840:16)
    at http://builds.emberjs.com/canary/ember-data.js:6366:41
    at http://builds.emberjs.com/canary/ember-data.js:9307:20
    at cb (http://builds.emberjs.com/ember-latest.js:15907:13)
    at OrderedSet.forEach (http://builds.emberjs.com/ember-latest.js:15703:13)
    at Map.forEach (http://builds.emberjs.com/ember-latest.js:15911:19)
    at Function.Model.reopenClass.eachRelationship (http://builds.emberjs.com/canary/ember-data.js:9306:42)
    at Ember.Object.extend._setup (http://builds.emberjs.com/canary/ember-data.js:6365:26)

Despite your models being set up correctly:
App.Color = DS.Model.extend({
  color: DS.attr(),
  foo: DS.belongsTo('foo', {async:true})
});

App.Foo = DS.Model.extend({
  foo: DS.attr()
});

Example: http://emberjs.jsbin.com/OxIDiVU/1111/edit

A: This is a bug with Ember/Ember-data versions.  Ember changed its Map implementation in Ember 1.8 beta 3 breaking any version of Ember Data less than 1.0 beta 10.
Here's the github issue: https://github.com/emberjs/data/issues/2323
It's fixed in 1.0.0-beta.11+canary.2997e47034 or above.


text:
Q: After Upgrade magento 2.1.8 to 2.2.1 got below error 1 exception(s):
Exception #0 (Magento\Framework\Config\Dom\ValidationException): Element 'head': Character content other than whitespace is not allowed because the content type is 'element-only'.
Line: 49

Element 'block', attribute 'class': [facet 'pattern'] The value '\\Magento\Framework\View\Element\Template' is not accepted by the pattern '[A-Z][a-zA-Z\d]*(\\[A-Z][a-zA-Z\d]*)*'.
Line: 735

Element 'block', attribute 'class': '\\Magento\Framework\View\Element\Template' is not a valid value of the atomic type 'blockClassType'.
Line: 735

Element 'remove', attribute 'src_type': The attribute 'src_type' is not allowed.
Line: 778

Element 'block', attribute 'remove': The attribute 'remove' is not allowed.
Line: 824

Element 'block', attribute 'class': [facet 'pattern'] The value '\\Magento\Framework\View\Element\Template' is not accepted by the pattern '[A-Z][a-zA-Z\d]*(\\[A-Z][a-zA-Z\d]*)*'.
Line: 838

Element 'block', attribute 'class': '\\Magento\Framework\View\Element\Template' is not a valid value of the atomic type 'blockClassType'.
Line: 838

Element 'move', attribute 'name': The attribute 'name' is not allowed.
Line: 890

Element 'move', attribute 'name': The attribute 'name' is not allowed.
Line: 891

Element 'remove': This element is not expected. Expected is one of ( block, container, referenceBlock, referenceContainer, uiComponent ).
Line: 909

Element 'move': This element is not expected. Expected is one of ( action, arguments, block, container, referenceBlock, uiComponent ).
Line: 1293

Element 'move', attribute 'name': The attribute 'name' is not allowed.
Line: 1317

Element 'move', attribute 'name': The attribute 'name' is not allowed.
Line: 1318

A: About: [facet 'pattern']

Element 'block', attribute 'class': [facet 'pattern'] The value '\Magento\Framework\View\Element\Template' is not accepted by the pattern '[A-Z][a-zA-Z\d](\[A-Z][a-zA-Z\d])*'.

This file contain the pattern:
/vendor/magento/framework/View/Layout/etc/elements.xsd:133
'[a-zA-Z][a-zA-Z\d\-_]*(\s[a-zA-Z][a-zA-Z\d\-_]*)*'
Probably you have double spaces in somewhere, just remove it.
You can use this link https://regex101.com/ to teste your css classes added on container or block
About: The attribute 'src_type'

Element 'remove', attribute 'src_type': The attribute 'src_type' is not allowed.

According with Magento DevDocs just use remove attribute on reference block or container. So is unnecessary the attribute src_type.
Read the documentation: Magento DevDocs - Remove elements
Example:
<referenceBlock name="catalog.compare.sidebar" remove="true" />
About Rearrange elements

Element 'move', attribute 'name': The attribute 'name' is not allowed.

Read the documentation: Magento DevDocs - Rearrange elements
name is not part of attributes of <move> element. Check the structure: <move element="" destination="" after=""/>

A: This is a known issue that many faces when upgrading from 2.1.8 to 2.2.0.
The validation of templates didn't work before. Now it works and all module and layout updates needs to follow the validation rules.
See those threads:
https://github.com/magento/magento2/issues/11194
https://github.com/magento/magento2/issues/11116
Do you happen to use Fooman analytics module? If so, their proposal is to update to a later version. Read more here:  http://magento2-support.fooman.co.nz/article/1562-xsd-template-validation-error?

A: this exception occurs because you are using an invalid attribute for the element, for example:
Example 1:
<move name = "form.subscribe"/>

Error: the name attribute is not allowed in the move element
Solution: remove the attribute 'name' if use into move element
Example 2:
<remove name="form.subscribe"/>

Error: the remove attribute is not valid
Solution:
<referenceBlock name="form.subscribe" remove="true" />

See the list of allowed attributes in: https://devdocs.magento.com/guides/v2.2/frontend-dev-guide/layouts/xml-instructions.html#fedg_layout_xml-instruc_ex_rem

A: I had the same issue.
If you can still access the webadmin Go into the admin and look for those block IDs. Copy those blocks names and contents into their own text file.
Then, delete those blocks from the admin. If you can't access via admin, you can copy and delete them via phpmyadmin or other database method.
Then run these commands in order
php bin/magento setup:upgrade

php bin/magento cache:flush

php bin/magento indexer:reindex

php bin/magento deploy:mode:set production -s

php bin/magento setup:di:compile

php bin/magento setup:static-content:deploy -s standard

I was then able to complete the update to 2.2.1 and then just added the blocks I needed back into the store.
The blocks causing the issue for me were calling product lists via widgets, hope it works for you.


text:
Q: In Java Swing, is there a way to save files to some sort of 'lib' folder? Right now, I can save a file based on a word processor I made in Java Swing. When they press the save button, JFileChooser asks where they would like to save it to. I would like it so that every time the user saves, that a backup is generated in a lib folder, so that the user may revert back to a previous copy. Is there a way I can say generate a folder inside a bin folder for each respective file that the user has, and inside that folder generates the copies. For example, the user creates a file called MyDoc.rtf and inside lib generates a folder called MyDoc and inside has all the copies of the saved versions copy1, copy2,, copy3, etc.
So, there are two parts to the question. How do I generate a cache folder for each file saved? And how do I generate those copies?
The way I save the file using JFileChooser is as follows
public class SaveContent {
String formattedText;

public void save(JTextPane text){
    if(text.getText().length() > 0){
        JFileChooser chooser = new JFileChooser();
        chooser.setMultiSelectionEnabled(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("RICH TEXT FORMAT", "rtf", "rtf");
        chooser.setFileFilter(filter);

        int option = chooser.showSaveDialog(null);
        String filePath = chooser.getSelectedFile().getPath();

        if(!chooser.getSelectedFile().getPath().toLowerCase().endsWith(".rtf")){
            filePath=chooser.getSelectedFile().getPath() + ".rtf";
        }

        if(option == JFileChooser.APPROVE_OPTION){
            StyledDocument doc = (StyledDocument)text.getDocument();
            HTMLEditorKit kit = new HTMLEditorKit();
            BufferedOutputStream out;

            try{
                out = new BufferedOutputStream(new FileOutputStream(filePath));
                kit.write(out,doc,doc.getStartPosition().getOffset(), doc.getLength());
            } catch(FileNotFoundException e){

            } catch(IOException e){

            } catch(BadLocationException e){

            }
        } else{
            System.out.println("SAVE CANCCELED");
        }
    }
}

}

A: For creating a directory that doesn't already exist, I can simply do mkdirs() and then use Files to write to a path. Alternatively, I can use FileWriter, BufferedWriter, and FileOutputStream.
          if(textListiner != null) {
                textListiner.textEmitted("GOodeye\n");

                //Add a folder
                File f = new File("../Swing1/backups/testDir");
                if(!f.exists()) {
                    boolean success = (new File("../Swing1/backups/testDir")).mkdirs();
                    if (!success) {
                        // Directory creation failed
                        System.out.println("FAIL CREATE DIR");
                    }
                }
                else {
                    System.out.println("ALREADY EXISTS");
                }
            }

                //Add the file to the folder (without JFileChooser and showSaveDialog)
                // COuld use FileWriter, BufferedWriter FIleOutputStream, or Files
                //Lookup: https://www.journaldev.com/878/java-write-to-file
                String data;
                try {
                    Files.write(Paths.get("../Swing1/backups/testDir/copy1.txt"), data.getBytes());
                } catch (IOException eIO) {
                    eIO.printStackTrace();
                }


text:
Q: How to monitor CPU usage automatically and return results when it reaches a threshold I am new to shell script , i want to write a script to monitor CPU usage and if the CPU usage reaches a threshold it should print the CPU usage by top command ,here is my script , which is giving me error bad number and also not storing any value in the log files
while sleep 1;do if [ "$(top -n1 | grep -i ^cpu | awk '{print $2}')">>sy.log - ge "$Threshold" ]; then echo "$(top -n1)">>sys.log;fi;done

A: Your script HAS to be indented and stored to a file, especially if you are new to shell !
#!/bin/sh

while sleep 1
do
    if [ "$(top -n1 | grep -i ^cpu | awk '{print $2}')">>sy.log - ge "$Threshold" ]
then
    echo "$(top -n1)"  >>  sys.log
fi
done

Your condition looks a bit odd. It may work, but it looks really complex. Store intermediate results in variables, and evaluate them.
Then, you will immediately see the syntax error on the "-ge".
You HAVE to store logfiles within an absolute path for security reasons. Use variables to simplify the reading.
#!/bin/sh

LOGFILE=/absolute_path/sy.log
WHOLEFILE=/absolute_path/sys.log
Thresold=80

while sleep 1
do
   TOP="$(top -n1)"
   CPU="$(echo $TOP | grep -i ^cpu | awk '{print $2}')"
   echo $CPU >> $LOGFILE
   if [ "$CPU" -ge "$Threshold" ] ; then
       echo "$TOP"  >>  $WHOLEFILE
   fi
done

A: You have a couple of errors.

*

*If you write output to sy.log with a redirection then that output is no longer available to the shell.  You can work around this with tee.

*The dash before -ge must not be followed by a space.

Also, a few stylistic remarks:

*

*grep x | awk '{y}' is a useless use of grep; this can usefully and more economically (as well as more elegantly) be rewritten as awk '/x/{y}'

*echo "$(command)" is a useless use of echo -- not a deal-breaker, but you simply want command; there is no need to capture what it prints to standard output just so you can print that text to standard output.

*If you are going to capture the output of top -n 1 anyway, there is no need really to run it twice.

Further notes:

*

*If you know the capitalization of the field you want to extract, maybe you don't need to search case-insensitively. (I could not find a version of top which prints a CPU prefix with the load in the second field -- it the expression really correct?)

*The shell only supports integer arithmetic. Is this a bug? Maybe you want to use Awk (which has floating-point support) to perform the comparison?  This also allows for a moderately tricky refactoring.  We make Awk output an exit code of 1 if the comparison fails, and use that as the condition for the if.

#!/bin/sh

while sleep 1
do
    if top=$(top -n 1 |
        awk -v thres="$Threshold" '1; # print every line
            tolower($1) ~ /^cpu/ { print $2 >>"sy.log";
                exitcode = ($2 >= thres ? 0 : 1) }
            END { exit exitcode }')
    then
        echo "$top" >>sys.log
    fi
done

Do you really mean to have two log files with nearly the same name, or is that a typo? Including a time stamp in the log might be useful both for troubleshooting and for actually using the log files.


text:
Q: Will magnets lose strength over time when coupled to another magnet? Will magnets lose strength over time when coupled to another magnet ?
Im designing a part (c. 200g) which needs to be held in place, but also be removable, so looking into a pair of magnets (neodymium or other) to do this, the magnets will for >99% of their life be coupled to one another, but wondered if over time the strength of the magnets would decrease / diminish ?

A: My answer is, in general, no.  Ferromagnetic materials usually, on a microscopic level, have domains in which the magnetic moments are all aligned in one direction.  There is a famous picture from R. W. DeBlois that shows domains within a sample of nickel (the arrows indicate the domain orientation):

Kittel (Introduction to Solid State Physics) tells us that an external magnetic field can increase the magnetic moment of a specimen such as this by:

*

*In weak fields, increasing the volume of domains favorably oriented with respect to the external field by shrinking those unfavorably oriented, and

*In stronger fields, actually rotating the magnetization of domains.
Your magnets will already have a general N-S orientation meaning there are already large domains with that orientation.  I am assuming in your design, you are coupling your magnets in a N-S/N-S order - in other words, you are not orienting them with opposing fields.  So you may find that your magnets get stronger over time as the smaller domains grow and re-orient.  I think as long as you stay below the Curie temperature, you will not see any decrease in magnetic strength.
Anyway, these are my thoughts.
Edit: I did look at a couple of magnet suppliers and they indicate an increase in strength when coupling two or more together.  See question #22 in the link below.  But they do not discuss the strength over time.
https://buymagnets.com/faq/#:~:text=Yes%2C%20stacking%20two%20or%20more,holding%20force%20is%20slightly%20reduced.

A: Magnets   lose a very little fraction of their strength even if they are coupled to another magnet and are below the Curie temperature. But since the magnets are going to be used in a window frame which is opened and closed, there is mechanical stress which can cause high temperatures(reason at the end) and also wear and tear(speaking from personal experience, especially at rims) neodymium magnets are very susceptible to corrosion. So you need to take care of these factors.
(Sometimes while playing with neodymium discs   I would let the magnets collide, a little bit of the magnet  would get detached and even produce a spark in the process:)

A: If we are talking about human-life timescales, in other words any practical application then no they shouldn't. Unless there are other factors, such as mechanical wear, reorientation due to elevated temperatures, or constantly changing magnetic fields. However if you talk about extremely long theoretical timescales then magnets will lose their magnetism slowly, especially when there's a change in the field. So having them stay coupled should not affect them, pulling them off and putting them back millions and millions of times will decrease their strength. On extremely long timescales the magnetism will also be lost naturally but this takes so long that it's hard to even observe a loss in your lifetime (spontaneous random reorientation).
Again for any application in the real world you normally don't have to worry about this, especially when the magnets don't experience strong changing fields regularly.


text:
Q: Unicorn periodically fails to restart after deploy - stale PID I've been trying to solve this problem on my own for sometime and have not had any luck. It occurs when I redeploy my rails app about 10% of the time. The other 90% of the time the deploy goes smoothly.
I've tried and tried again, but have not succeeded. So I'm turning to the SO masses for some help.
A little about my stack: I'm using chef to generate my instance on vagrant running on Ubuntu 14.04 and using upstart to oversea unicorn.
The error:
srv/www/rails/releases/ef6a792a19f8bb9d36ef4d0ab15ee38ca91a0cd1/vendor/bundle/ruby/2.1.0/gems/unicorn-4.8.3/lib/unicorn/http_server.rb:206:in `pid=': Already running on PID:17694 (or pid=/srv/www/rails/shared/pids/unicorn.pid is stale) (ArgumentError)
from /srv/www/rails/releases/ef6a792a19f8bb9d36ef4d0ab15ee38ca91a0cd1/vendor/bundle/ruby/2.1.0/gems/unicorn-4.8.3/lib/unicorn/http_server.rb:135:in `start'
from /srv/www/rails/releases/ef6a792a19f8bb9d36ef4d0ab15ee38ca91a0cd1/vendor/bundle/ruby/2.1.0/gems/unicorn-4.8.3/bin/unicorn:126:in `<top (required)>'
from /srv/www/rails/releases/ef6a792a19f8bb9d36ef4d0ab15ee38ca91a0cd1/vendor/bundle/ruby/2.1.0/bin/unicorn:23:in `load'
from /srv/www/rails/releases/ef6a792a19f8bb9d36ef4d0ab15ee38ca91a0cd1/vendor/bundle/ruby/2.1.0/bin/unicorn:23:in `<main>'

My unicorn upstart script is here. And my unicorn configuration file can be viewed here.
Please let me know if you need any more information. And above thanks for your help and time.

A: I've been running into this too.  You need to clear out the old PID file in your upstart script, before you try running Unicorn.
rm /srv/www/rails/shared/pids/unicorn.pid

Alternatively, take a look at https://github.com/tablexi/capistrano3-unicorn for ways to determine server state and start/restart Unicorn appropriately.


text:
Q: How can i set the default values of controller parameters? I have a customers table on my database and a column named as "last_updated_by" . I want to add current users name as a plain text in this field.
I got devise installed on my app so it gives me the current_user parameter.I tried to add current_user.name to the customers_controllers permitted parameters but it did not worked.
1-
def customer_params
params.require(:customer).permit(:name, :last_updated_by=>current_user.name)
end

2-
def customer_params
  params[:last_updated_by] = current_user.name
  params.require(:customer).permit(:name, :last_updated_by)
end

3-
def customer_params
  last_updated_by = current_user.name
  params.require(:customer).permit(:name, :last_updated_by=>current_user.name)
end

How can i set some default values in controller.

A: Since you're asking about setting a default value I suggest using the with_defaults method, which is simply an (more expressive) alias for reverse_merge.
def customer_params
  params
    .require(:customer)
    .permit(:name, :last_updated_by)
    .with_defaults(last_updated_by: current_user.name)
end

reverse_merge does the same thing as merge, the only difference is what happens for conflicting keys. merge uses the value of the hash passed through the parameters, whereas reverse_merge prefers the value of the receiver.
params = { a: 1, b: 2 }
defaults = { a: 4, c: 5 }
params.merge(defaults)         #=> { a: 4, b: 2, c: 5 }
params.reverse_merge(defaults) #=> { a: 1, b: 2, c: 5 }
#       ^ aka with_defaults

A: If you need the last_updated_by param to go within the customer_params (customer hash key for ActionController::Parameters), then:
before_action :set_last_updated_by_param, only: :create

private

def set_last_updated_by_param
  params[:customer][:last_updated_by] = params.dig(:customer, :name)
end

The before_action callback adds the new key last_updated_by on the customer params only before the create action is executed.
Notice, no need to modify the customer_params to permit it.

As showed by @JohanWentholt, with_defaults seems to be the best way. Go for it.
Waiting the OP chooses the correct answer.

A: If you need a default value only if params[:last_updated_by] is not present in the body of your request, you can try:
def create
  params[:last_updated_by] = params[:last_updated_by].blank? ? 'Default value' : params[:last_updated_by]
  Customer.new(params)
  # finish your controller method
end

def customer_params
  params.require(:customer).permit(:name, :last_updated_by)
end

Now if you need to set a default value on every create and update if last_updated_by is nil, you should do this on Customer model:
after_save :set_last_updated_by

def set_last_updated_by
  self.last_updated_by = self.last_updated_by.blank? ? 'Default value' : self.last_updated_by
end

A: As method params.permit method is used to filter the parameter you want to create the object with, you can use any of the solution given above, but if you want to modify params in def customer_params then i would like to modify your 2nd solution
def customer_params
  params[:customer][:last_updated_by] = current_user.name
  params.require(:customer).permit(:name, :last_updated_by)
end


text:
Q: Trouble undestanding a piece of python code I was going through a code and i cant quiet understand this piece of code
def filter_orgs(source):
orgs = [org for o in source["orgs"] if (org := filter_orgs(o))]
if orgs or source["available"]:
    return {
        "org_name": source["org_name"],
        "orgs": orgs
    }

Usage:
source = {
"org_name": "1",
"available": True,
"orgs": [
    {
        "org_name": "2",
        "available": False,
        "orgs": []
    },
    {
        "org_name": "3",
        "available": False,
        "orgs": []
    },
    {
        "org_name": "4",
        "available": True,
        "orgs": []
    },
    {
        "org_name": "5",
        "available": False,
        "orgs": [
            {
                "org_name": "6",
                "available": False,
                "orgs": []
            },
            {
                "org_name": "7",
                "available": False,
                "orgs": []
            },
            {
                "org_name": "8",
                "available": False,
                "orgs": [
                    {
                        "org_name": "9",
                        "available": False,
                        "orgs": []
                    },
                    {
                        "org_name": "10",
                        "available": True,
                        "orgs": []
                    }
                ]
            }
        ]
    }
]
}

filtered_source = filter_orgs(source)

Output:
{
"org_name": "1",
"orgs": [
    {
        "org_name": "4",
        "orgs": []
    },
    {
        "org_name": "5",
        "orgs": [
            {
                "org_name": "8",
                "orgs": [
                    {
                        "org_name": "10",
                        "orgs": []
                    }
                ]
            }
        ]
    }
]
}

I am new to programming. I know its a recursive function but I cant quiet get what's happening
especially orgs = [org for o in source["orgs"] if (org := filter_orgs(o))]
can some one care to explain .. Please, Thank you:)

A: // Function which takes a source of type Dictionary
def filter_orgs_simplified(source: dict) -> dict:
orgs_source: list = source['orgs']
orgs: list = []

for o in orgs_source:
    org = filter_orgs(o)

    if not org:
        continue

    orgs.append(org)

if orgs or source["available"]:
return {
    "org_name": source["org_name"],
    "orgs": orgs
}

This is the simplified version of the above code.
Actually the function takes a source of type Dictionary and and returns a filtered Dictionary back.


text:
Q: Is it possible to assign global variable value with local variable value in PLSQL
I have attached code snippet. I want to change the value of Global variable from a function variable. Is it possible?
create or replace package pack_testing
as
function f1(n in number) return number ;
end;

create or replace package body pack_testing
as
n number:=1;
function f1(n in number) RETURN number
is
z number:=n;
begin
 for i in 1..10 loop
                     z:=z+1;
                     if n<3 then dbms_output.put_line(i+'o');
                     else dbms_output.put_line(i);
                     end if;
                     return(i);
                     begin
                     n:=z;   --this line giving error . I am assigning global variable value with local variable
                      end;
             end loop;
end;
end;

A: If a subunit redeclares a global variable, you can reference the global variable by using the name of the unit that holds the global variable. In your case, just add the package name in front of the variable:
pack_testing.n:=z;

But it is best to avoid this situation entirely by using more descriptive names, not re-using names, or having a variable prefix policy. The rules around variable scope and precedence get trickier when SQL is involved, so I typically prefix every PL/SQL variable with G_ for global, C_ for constant, P_ for paramter, and V_ for (local) variable.

A: Do not use the same name n for two objects: package global variable and input paramter of function f1
As the matter of variable scope, your local input paramter of function f1 will have more prioritize than your n global variable.
And your n paramter is IN, not OUT or IN OUT, it cannot be assign value z, so that oracle raise error. If you have a global variable n, then change your IN parameter to n1 or sth else, for e.g FUNCTION f1( n1 IN NUMBER)
CREATE OR REPLACE PACKAGE pack_testing
AS
    FUNCTION f1(n1 IN NUMBER) RETURN NUMBER;
END;

CREATE OR REPLACE PACKAGE BODY pack_testing
AS
    n NUMBER := 1;

    FUNCTION f1(n1 IN NUMBER) RETURN NUMBER
    AS
        z NUMBER := n1;
    BEGIN
        FOR i IN 1..10
        LOOP
            z := z + 1;

            IF n < 3
            THEN
                dbms_output.put_line(i + 'o');
            ELSE
                dbms_output.put_line(i);
            END IF;

            RETURN i;

            BEGIN
                n := z;
            END;
        END LOOP;
    END;
END;

And your test code seem never reach the line n := z; because it always end at previous line RETURN i;. So for the LOOP


text:
Q: Convert java rest request to php code How can I convert this java code to php.
server = new URL(url);
    HttpURLConnection urlConnection  = (HttpURLConnection) server.openConnection() ;
    urlConnection.setRequestMethod( method );
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type",mimeType );
    if( requestParameter != null)
    {
        CyberoamLogger.appLog.debug(MODULE+":"+METHOD+"Request parameter: "+requestParameter.toString());
        out = new BufferedWriter( new OutputStreamWriter( urlConnection.getOutputStream() ) );
        out.write(requestParameter.toString());
        out.flush();
        out.close() ;
    }

    urlConnection.connect();
    strbuf = new StringBuffer();
     is= urlConnection.getInputStream()   ;
    byte[] buffer = new byte[1024 * 4];
    int n = 0;
    while (-1 != (n = is.read(buffer)))
        strbuf.append(new String(buffer, 0, n));
    is.close();
    strResponse=strbuf.toString();
    CyberoamLogger.appLog.debug(MODULE+METHOD+ " WS Responce in String  : "+strResponse);
    urlConnection.disconnect();

When I try following php code I get The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (). error
$curl = curl_init();
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_URL, $url);

    echo curl_exec($curl);

A: Try setting the content type header with your curl:
$mimeType = "application/json";
curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-Type: $mimeType"));
// equivalent to your java urlConnection.setRequestProperty("Content-Type",mimeType );

And here is an example of preparing json:
$data = array(
    'name' => 'alex',
    'value' => '100'
);
$json_data = json_encode($data); // {"name":"alex","value":"100"}


text:
Q: Href Interpolation Failed in NextJs button I have this code to create a button that makes the app change the language from English to Spanish (just add the 'es' after the root):
  const { locale, locales, push, isReady } = useRouter()
  const handleClick = l => () => {
      push(`${currentPath}`, undefined, {locale:l})

this is the button code:
  {locales.map(l => (
     <button className="px-6 py-2 font-bold" key={l} onClick={handleClick(l)}>
       {l}
     </button>
   ))}

I click the language button in example.com/guides the app change the language to example.com/es/guides; but when I go to the dynamic path route example.com/guides/[url_en] and try to change the language, the following error it shows:
Unhandled Runtime Error
Error: The provided href (/guides/[url_en]) value is missing query values (url_en) to be interpolated properly. Read more: https://nextjs.org/docs/messages/href-interpolation-failed.


text:
Q: Firefox doesn't import all history from Chrome When importing history from Google Chrome 89.0.4389.90 to Firefox 86.0.1, the latter doesn't import all items. Only last month's history is there while I have been using Chrome for over a year.
How to import all items, without truncating to Firefox from Chrome ?

A: To change the behaviour, open about:config in Firefox and change

*

*browser.migrate.chrome.history.limit to a large number like 1 million.

*browser.migrate.chrome.history.maxAgeInDays to something like 3650
Then do the import.


text:
Q: Wrong dns suffix is appended I use Win7 inside a vpn, and my organization have a few dns suffixes that are used:
a.myorg
b.myorg
c.myorg

and I'm using the server server.c.myorg.
And some of the time when I do ping server, the correct suffix is appended, and the correct ip is resolved.
but on other times, ping server will try to ping server.a.myorg, get a weird ip (10.10.10.10) and fail.
I did nslookup to the dns servers with those results:
server -> correct ip
server.c.myorg -> correct ip
server.a.myorg -> non existing domain
I'm trying to figure why some of the time the incorrect suffix is being appended.


text:
Q: Linking to Other Website Page With Icon I am using Icons From Font Awesome and am using the Font Awesome gem in my rails app. How can I make the icon link to my profile on another application? Can I use an ERB tag with a link_to that specific url?

A: <%= link_to(fa_icon('stack-overflow'), 'http://www.stackoverflow.com/') %>


text:
Q: Embedded screen - security We have a web application : C# + SQL 2k5
Different companies send us information, we parse, them, do different things, and come up with a simple list for each of our customers. The list will look the same, but will have different information based on the customer.
They should not have access to each other's data.
We would like to create a page which would be embedded on their own site. I was thinking about using something like an iFrame.
Basically customer ABC would embed on his own abc.com an iframe with a URL (we will give them the parameters needed) and his clients will see our data on his site.
The other customer, lets call him xyz, has an other website xyz.com, will do the same thing, but in the url I should make a difference between them.
I would like to know how is the best, safest way to proceed.
How should I start to build up this page that is going to be embedded.
How should I make a difference between the 2 customers? The only way to get info from them is the parameters they send me, and eventually, I could get the 'parent' of my embedded iFrame, so that might help me restrict xyz to embed using url parameter info to get data from abc. See my dilemma?
Probably a unique identifier for each customer (like a GUID?) will be needed, and they woul dnot know each other's ID ... Or is there a more secure way to do things like this?
Any help would be appreciated.
Thanks

A: Embed a publically visible unique id in the URL and process this to extract the client id. e.g.
<IFRAME src="http://example.com/1122334455667788aabbcc">

You could check the Request.UrlReferrer to ensure that the request see this answer
However the only safe way of doing this is to provide an authenticated API that the site uses server side to process via a services API (e.g. WCF), or at the very least an authenticated HttpWebRequest; any other way leaves your data only as secure as a publically visible unique id.

A: Take a look at how one of the credit card processing portals do this (eg WorldPay or Paypal). There are several ways.
At the very least you need provide each customer with a unique ID that they send you.


text:
Q: Android project type not supporting in visual studio i installed Xamarin Enterprise edition on my computer 9 days ago. It worked fine and i have crated some projects and tested it on Emulators. But after some times- today when i come back to work, restarted computer and tried to open Android project On visual studio. It says: The project type is not supported by this installation. What is going on. What i can do?
I use Visual Studio 2010.
I tried to open Tools-> Options-> Xamarin-> Android Settings
But it shows: An error occurred loading this property page

A: First uninstall the Xamarin.Android plugin from the Control Panel. Then, try to completely remove the extensions from the control panel.
Remove any residual files from: %LOCALAPPDATA%\Microsoft\VisualStudio\11.0\Extensions %PROGRAMFILES%\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Xamarin
Then, re-install Xamarin.Android from the following msi file:
Xamarin.Android on Windows


text:
Q: Easy Questions for Teaching Pascal to a kid I've been asked to tutor Pascal to a kid. Despite never seen Pascal before I did manage to get a tutorial and I now know enough to teach him.
I am writing you guys to see if anyone can point me out some basic exercises that involve simple algorithms, Something like: Sort this array, find the average, etc...
It can be in any language, I just need to find some exercises so he can work out.

A: Here is a list of 15 Exercises for Learning a new Programming Language from freelance that expands on basic techniques used in many languages and can give him a feel of the new lanaguage he's learning

A: I am going to address this in a (mostly) language-agnostic fashion. After teaching him print statements and flow control (if statements, for loops, etc.), my suggestion would be to start off with simple ASCII-art patterns that can be generated by for loops and such.
For example, how would you print half of a tree, like this?
*
**
***
****
*****
******

Alright, now how would you print a full tree, like this?
     *
    ***
   *****
  *******
 *********
***********

Now try drawing a rocket ship. ;)
These are great for most kids because they are visual, the results are enticing, and the exercises will impart the importance of loops and eliminating redundancy.

A: For sorting algorithms see link. It is a Wikipedia article - a little general information on sorting algorithms, but down below you have links to every type of them individually, and algorithms in pseudo code (and some languages).
As far as "find the average" goes, when you've got "n" elements:
SUM=0.
DO i=1,n
 SUM=SUM+element(i)
ENDDO
AVRG=SUM/n

Also, for learning purposes and thinking Project Euler is very nice.

Also, do take a look at this question:
Where can you find fun/educational programming challenges? I didn't want to copy paste everything, but it has a bunch of links with stuff for exactly what you're looking for (programming exercices). And this: Algorithm Questions Website, What are your programming exercises?. You'll probably find something you think he'll be interested in in there.

A: classic one:
Let the program choose a random number, the purpose of the game is to find the number through elimination. if the user guesses a lower number the program says its too low, if its higher it says its too high.

A: Tic tac toe game with "AI" (that is predefined moves) and text-graphics is a nice project.

A: Add some fun to it. A good one to start with:
Paper-Rock-Scissor Game
User enters P, R, or S
Program responds that you win, lose, or tie
More advanced features: track record, winning %, win/loss streak

A: If you know any C/C-like language it's basically the same:

*

*{ } are begin end;

*== is =

*= is :=

*a function that returns nothing is a procedure.

*a function that returns something is still a function.

*int is Integer.

The rest is almost the same. The syntax is a bit different, but not very different.
You would need to know which Pascal they're using, and what they taught them to be sure you're not wasting your/his/her time.

A: Doing basic operations on a doubly linked list is also a classic.

A: Early exercises I learned from include drawing the Mandelbrot set (computers are much faster these days so you don't immediately have to worry so much about optimization) and implementing cellular automata like the Game of Life.
Of course, if this is practice for a school course, exercises like this will only be helpful if the test is likely to test a similar domain of knowledge/skills.


text:
Q: 'This server's clock is not synchronized with the primary domain controller's clock' when accessing shared drive This is so weird I feel compelled to ask for advice.
I have a handful of workstations who are receiving time from a GPS timeclock. The PDC has the default domain policy set to use the GPS timeclock as the NTP timesource. All the workstations sync to the timeclock with precision ranging from 50ms to 1.5ms so my delta values are grossly within margins for Kerebos tickets.
Almost all the workstations access my fileserver with absolutely no problems, however a single workstation began prompting me with the message This server's clock is not synchronized with the primary domain controller's clock and unless w32tm /stripchart /computer:PDC is lying, 20ms is more than close enough to be synchronized.
Is there something I might be missing here?

A: Now that I'm convinced the problem is fixed, I'll answer my own question.
Things to Verify:

*

*Verify the modulation from the timesource If the IRIG signal is modulated, make sure your configuration is looking for a modulated time signal. If the IRIG signal is unmodulated, make sure you have the hardware configured for unmodulated signal.

*Verify the correct time If the 'Grandmaster Clock' is not receiving the correct time value from the timeclock, nothing is going to be correct. Make sure that you have the correct offset period for the correct year. Leap seconds (as of this writing) should be offset by 34 seconds.

*Verify there are no forced values, or debugging If someone is debugging a process using a frequency generator to 'fake' the time, nothing is going to be right if it overrides the Stratum time.

*Verify Time Services If your clock radio has separate software to synchronize the system time to the timesource, make sure that Windows Time Service is disabled. If you don't turn off Windows Time Service the clock will be corrected by both services.

*Verify Time Zones Timezones must be set correctly on both the time server and clients. I highly recommend setting everything to GMT without any daylight bias or UTC and creating a second time display showing the local timezone with daylight preferance.

*Verify DST is Patched If you don't have a correct implementation of DST running, you will encounter 'phantom' problems.

*Verify delta is small enough for initial synchronization If the delta time is large, the clients cannot synchronize to the time source.  You may be required to set the clock to within approximately 10 minutes for the time service to be able to synchronize.
For troubleshooting:

*

*use w32tm /tz to verify the timezones.

*use w32tm /stripchart /computer:[host to compare with] to measure differences and time drift between the 2 computers.

A: My guess is a DST patching issue on that workstation.  Last time I ran into it, I'd loaded a workstation from image, then applied XP SP3.  That's when I discovered that my image fell into a fringe case where the DST patching didn't take place when patched in that way.  If that's the issue, hopefully the MS DST page will help out.

A: This error started happening on our network on multiple workstations after the 2019 change  from daylight savings to standard time. In order to fix, I rebooted one of my two domain controllers and the network shares started working again.


text:
Q: Java - Compare 2 HTML strings and return the mismatched objects I have two 1 line innerHTML strings (fairly large) and I need to compare them and if they don't match, I need to know which objects are different. Example:
HTML 1:

MyText

HTML 2:

NotMyText

Should give the list of objects back, only 1 item in this case:
NotMyText

I'm running the script on thousands of links/pages, so the speed is very important. I tried Google Diff, which only returns the parts that do not match. It would say that MyText has been removed and NotMyText has been added or something similar, but that is not what I need.
Any idea on this?

A: I think you should not do the comparison on String Level, because from the String diff it's not easy to find out where you are, what's the enclosing element. If you work on a DOM tree representation, it should be much easier to do.
If I were you I would write a recursive DOM comparison method and do a kind of depth-first search on the complete tree like this (just pseudocode):
DomDifference compare(DOMElement a, DOMElement b) {
   if(a.isLeaf()) {
     return DomDiff(a, b)
   }
   foreach(child: a.children()) {
     otherChild = b.nextChild()
     result = compare(child, otherChild);
     if(!result.isEqual()) {
       return result;
     }
   }
   return DomDifference.nodesAreEqual;
}


text:
Q: jquery not working within the view of a asp.net mvc3? i have a problem with my asp.net mvc3 page. i have a view which has a form in it to create a item of a specific model. it looks likt this:
@model testPro.Models.AddItemModel
@{
    ViewBag.Title = "New";
}
@*
New
*@

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>New Item</legend>

                    @Html.LabelFor(model => model.UserItem.name)

                    @Html.EditorFor(model => model.UserItem.name)
                    @Html.ValidationMessageFor(model => model.UserItem.name)

            <input type="submit" value="Create" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

at the end i have my jquery stuff which should change the text-box.
the problem is, nothing is changing and i dont know why
and yes: i have jquery included in the header.

A: Try:

Things to notice:

*

*Your textbox id is UserItem_name, not UserItem_Name which obviously is not the same thing

*Use .val() to set values of form input fields instead of .html()

*The .attr() method takes 2 arguments when you want to set an attribute value: 1) the attribute name and 2) the attribute value. You are currently passing only one parameter, so you are basically reading the attribute value, not setting it.

Also if this code is inside a partial view that you have injected into your DOM after an AJAX request, you should remove the $(document).ready handler.


text:
Q: Having multiple 'sub-repositories' in one git repository? I was fortunate enough to obtain a free micro-plan Github account to use for my schoolwork through Github's EDU program. However, I am not sure how best to structure this for my CS classes. Ideally, I would have a different repository for each class -- CS101, CS102, etc. However, the micro-plan only allows up to 5 repositories, and I will be taking more than 5 classes within the next year or two. So, is there a way to structure one repository to keep commits 'separate' for each folder, i.e. have one repository with multiple 'sub'-repositories (basically a submodule).
Any advice is appreciated.
Thanks!

A: Branching
For each class, run within the repository git checkout --orphan <classname>, and you can get a new parentless branch for that class's content.
When getting local copies of your repository, run git clone --single-branch --branch <classname> <url> <localdir>, and it will only clone and later fetch that class's branch.
Bitbucket
As trauzti said, I would definitely recommend a Bitbucket account.  While the UI isn't as pretty as Github's, it has all the same functionality, and they do allow free unlimited private repositories.  I use it for my schoolwork.  If you really want to use Github though, then the above would work.

A: Maybe someone knows a way to use submodules for this: http://git-scm.com/book/en/Git-Tools-Submodules
You could use multiple branches, one branch for each class, and check out the different branches in different directories on your computer.
But if there are only 5 people or less going to be using these repositories you should check out BitBucket: https://bitbucket.org/
There you can have an infinite number of private repositories for free.


text:
Q: How do I create a Dart Server database? I know that it is possible to create a IndexedDb at client side, but I was wondering if it possible to create a key/value store server Side. In that case we could use that db as a cache server or even as an elasticSearch server, or maybe replace a SQL or NoSQL database

A: Unfortunately it is not possible to create an IndexedDb on the server in Dart. The implementation primarily leverages the APIs provided by the client-side navigator (eg. Chrome, Firefox, etc). IndexedDb is a developing web standard which will hopefully be implemented in all browsers in the future. In this way, Dart is basically using APIs to access a separate database (albeit a very simple one). It is not implemented in Dart itself.
That said, in addition to other serverside database APIs, there is also a Dart client interface for memcache which can be run on the sever to connect to a memcache instance

A: You can use any database on the server where a Dart driver is available (not so many yet, but in the future there will be support for most mainstream databases.
take a look at

*

*https://pub.dartlang.org/packages/yomp_db

*http://pub.dartlang.org/packages/mongo_dart

*http://pub.dartlang.org/packages/sqljocky


text:
Q: csv file with delimiter other than comma in php I insert data into table as bulk upload,
            $handle = fopen($_FILES['file_clg']['tmp_name'], "r");
        fgetcsv($handle);

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

        $collegename = trim(str_replace(array("'","'"),"'",$data[0]));

        $description = trim(str_replace(array("'","'"),"'",$data[1]));

        $sql1 = $db->selectquery("insert into $tbl(name,details)values('" .$collegename."','" .$description."')");

        }

        fclose($handle);

Only two fields is mentioned here: morethan 25 columns in my bulkupload csv
The problem is that the csv delimiter is the comma (',') but in some cases 'details' field contents include commas, as in this case record not inserted properly..
how to solve this case???
And a problem in insertion section,
College name : Alva's Institute of Engineering & Technology (AIET)
and its saved in table as below format :
Alva�s Institute of Engineering & Technology (AIET)
I try below code:
          $collegename = htmlentities(iconv("cp1252", "utf-8", trim(str_replace(array("'","'"),"'",$data[0]))), ENT_IGNORE, "UTF-8");

but its not working, how can i solve the issue in single quotes
And i placed : header("Content-Type: text/html; charset=ISO-8859-1");
into the header section..

A: I'd need to see some samples to say anything with confidence, but there are specs on quoting values with commas to preserve the value count.
https://stackoverflow.com/a/769675/2943403
Alternatively, you could create a new fputcsv() code block that will generate a semi-colon (or other non-conflicting character) delimited csv file.  I am not providing the actual snippet for this.  There are many available resources on SO, including:

*

*php fputcsv use semicolon separator in CSV

*Export to CSV via PHP

*PHP How to convert array into csv using fputcsv function
Then your while loop could use ; (or whatever) as a delimiter.
As for safely placing your values (which may have single quotes) into your query, use prepared statements
// I realize your query will be much larger than the sample...
// declare $collegename and $decription values
$stmt=$db->prepare("INSERT INTO `$tbl` (`name`,`details`) VALUES (?,?)");
$stmt->bind_param("ss", $collegename,$description);
if($stmt->execute()){
    echo "success";
}else{
    echo "Error: ",$db->error;
}


text:
Q: Referencing Cells within Named Range in VBA I'd like to know if its possible to use Cells(r, c) within a named range in VBA.
Ex.: I have named range "Test" to be A1:B5  and I am working on a Macro that loops through this range, however I'd like to avoid explicit declarations of ranges as much as possible, so sheet manipulation can be as easier as possible.
In case what I said wasnt possible, I basically need to be able to loop/write through cells in the named ranges, if there is another approach for this I'd be more than glad to get a suggestion.
Thanks!

A: Sure, you can simply use e. g.
Worksheets("name").Range("Test").Cells(r, c)
and
Dim c As Range
For Each c In Worksheets("Name").Range("Test").Cells
    Debug.Print c.Address
Next

A: I figured it out with a bit more of research
In case anyoone drops by wondering this:
Sub test()
    dim r1 as Range
    set r1 = Range("NamedRange")

    f = r1.row
    l = Range("NamedRange").Row + Range("NamedRange").Rows.Count - 1

    Do while (Cells(f,1) <> "" and f <= l
        'Run code
    Loop
end sub


text:
Q: What does [[:print:]] means on a directory path? What does [[:print:]] means on the following code?
echo 255 > /sys/devices/platform/[[:print:]]*/hwmon/hwmon[[:print:]]*/pwm1

What is the difference between using [[:print:]]* and only *?
echo 255 > /sys/devices/platform/*/hwmon/hwmon*/pwm1

Is there any known name of this feature, or any place I could read and understand more about?

A: [[:print:]], in either a glob-style expression or a POSIX-compliant regex, matches any printable character.
The reference for (the simplified, single-character case of) glob expressions is https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13_01; it references the regular expression portion of the standard at https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03_05 as being authoritative for square-bracket expressions, which describes [:print:] as one of the character-class expressions that all locales must provide. The details of this specific class are then provided in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01.

A: [[:print:]] is a Posix class recognized by all engines today as matching up to
144,544 or less, Unicode characters as of Unicode 14.
The raw representation of that is this UTF-8/32 regex based on UCD.
This matches up to ALL of them. Some engines match less, doesn't matter though,
it is always this or less, never more as of V14.
 [\\a-zA-Z0-9\t-\r-/:-@\[\]-`{-~\\ -¬®-ÿĀ-ͷͺ-Ϳ΄-ΊΌΎ-ΡΣ-ԯԱ-Ֆՙ-֊֍-֏֑-ׇא-תׯ-״؆-؛؝-ۜ۞-܍ܐ-݊ݍ-ޱ߀-ߺ߽-࠭࠰-࠾ࡀ-࡛࡞ࡠ-ࡪࡰ-ࢎ࢘-ࣣ࣡-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-৾ਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-੶ઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૱ૹ-૿ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍୕-ୗଡ଼ଢ଼ୟ-ୣ୦-୷ஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௺ఀ-ఌఎ-ఐఒ-నప-హ఼-ౄె-ైొ-్ౕౖౘ-ౚౝౠ-ౣ౦-౯౷-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೝೞೠ-ೣ೦-೯ೱೲഀ-ഌഎ-ഐഒ-ൄെ-ൈൊ-൏ൔ-ൣ൦-ൿඁ-ඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲ-෴ก-ฺ฿-๛ກຂຄຆ-ຊຌ-ຣລວ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ-ཇཉ-ཬཱ-ྗྙ-ྼ྾-࿌࿎-࿚က-ჅჇჍა-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፼ᎀ-᎙Ꭰ-Ᏽᏸ-ᏽ᐀-᚜ᚠ-ᛸᜀ-᜕ᜟ-᜶ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៝០-៩៰-៹᠀--᠙ᠠ-ᡸᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥀᥄-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧚᧞-ᨛ᨞-ᩞ᩠-᩿᩼-᪉᪐-᪙᪠-᪭᪰-ᫎᬀ-ᭌ᭐-᭾ᮀ-᯳᯼-᰷᰻-᱉ᱍ-ᲈᲐ-ᲺᲽ-᳇᳐-ᳺᴀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ῄῆ-ΐῖ-Ί῝-`ῲ-ῴῶ-῾ -\ ‐-\
\ -\ ⁰ⁱ⁴-₎ₐ-ₜ₠-⃀⃐-⃰℀-↋←-␦⑀-⑊①-⭳⭶-⮕⮗-ⳳ⳹-ⴥⴧⴭⴰ-ⵧⵯ⵰⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-⹝⺀-⺙⺛-⻳⼀-⿕⿰-⿻ -〿ぁ-ゖ゙-ヿㄅ-ㄯㄱ-ㆎ㆐-㇣ㇰ-㈞㈠-ꒌ꒐-꓆ꓐ-ꘫꙀ-꛷꜀-ꟊꟐꟑꟓꟕ-ꟙꟲ-꠬꠰-꠹ꡀ-꡷ꢀ-ꣅ꣎-꣙꣠-꥓꥟-ꥼꦀ-꧍ꧏ-꧙꧞-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙꩜-ꫂꫛ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-꭫ꭰ-꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-זּטּ-לּמּנּסּףּפּצּ-﯂ﯓ-ﶏﶒ-ﷇ﷏ﷰ-︙︠-﹒﹔-﹦﹨-﹫ﹰ-ﹴﹶ-ﻼ!-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ¢-₩│-○�------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------]


text:
Q: Extract part of a text file for usage in vb.net Ok. I need to store some records in a file namely data.dat.
Records in the file are sorted by date values. Each block of record starts with its date value along with a $ sign to indicate that a new block of record starts here and ends with a "#" sign to indicate end of the record block.
A sample of a record block would be:
$22/08/2013
(data)
(data)
(data)
#

The file data.dat contains several blocks like this, how can I extract each block in the file storing each in an array using vb.net?

A: Instead of an array i would use a List(Of T). You could create a custom class:
Class Record
    Public Property DateValue As DateTime
    Public Property Data As New List(Of String)
End Class

Here's a possible loop to initialize the list from your file:
Dim allData As New List(Of Record)
Dim currentRecord As Record = Nothing
Dim currentData As List(Of String) = Nothing
For Each line In File.ReadLines("data.dat")
    If line.StartsWith("$") Then
        Dim dt As DateTime
        If Date.TryParse(line.Substring(1), dt) Then
            currentRecord = New Record()
            currentRecord.DateValue = dt
            currentData = New List(Of String)
            currentRecord.Data = currentData
        End If
    ElseIf currentRecord IsNot Nothing Then
        If line.EndsWith("#") Then
            allData.Add(currentRecord)
        Else
            currentData.Add(line)
        End If
    End If
Next

A: It looks to me a Tuple quartet would be ready made for this.
Dim Record As New List(Of Tuple(Of DateTime, String, String, Integer))

Then each field can be accessed by it's item number:
Record(0).Item1


text:
Q: Unknown column 'categories1_.category' in 'field list' I have the following model.
Employee.Java
@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @Column(name="firstName")
    private String firstName;

    @Column(name="lastName")
    private String lastName;

    @Column(name = "category")
    @Enumerated(EnumType.STRING)
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name = "myobject_categories", joinColumns = @JoinColumn(name = "myobject_id"))
    private Set<Category> categories;
}

Category is an Enum as follows.
public enum Category {
CATEGORY(1), CATEGORY2(2);

private final Integer id;
Category(Integer id) { this.id=id; }
public Integer getId() { return id; }
}

My Repository is as follows,
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
    @Query("from org.arunm.Employee c WHERE :category MEMBER OF c.categories")
    List<Employee> findAll(@Param("category") Set<Category> categories);
}

The following code to retrieve the list of employees is not working.
Set<Category> categories = new HashSet<Category>();
categories.add(Category.CATEGORY);
List<Employee> list = customerRepository.findAll(categories);
customer.setCategories(categories);
customerRepository.findAll(categories);

In the logs I am seeing the query generated as
select employee0_.id as id1_1_, employee0_.first_name as first_na2_1_, employee0_.last_name as last_nam3_1_ from employee employee0_ where ? in
(select categories1_.category from myobject_categories categories1_ where employee0_.id=categories1_.myobject_id)

Following is the error that I am getting,
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'categories1_.category' in 'field list'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)

My question is what is it in my mapping that is forcing hibernate to think that there is a column called category in myobject_categories table.

A: You told hibernate to use myobject_categories as the mapping table. Such a mapping table needs to references: one back to the mapped entity (Employee in this case) and on to the entity that makes up the collection. Probably based on the enum name Hibernate assumed the name category for that field.
You might want to consider a different way of mapping Collections of enums.


text:
Q: ASPNET MVC formatting string in View I want to make an MVC View, which shows a string.
The string contains whitespaces (" ", "/t", "/n") and I want to show it in format defined in string.
My problem is, that if I return the string as ViewBag message, all of these whitespaces are lost. Is there any solution to resolve this problem?

A: A work around, replace \t with &nbsp and \n with <br/> and you could use,
@Html.Raw(ViewBag.Something)

A: Your issue is a web one where the browser ignores extraneous space.  You need to convert all space characters to   if you want to retain the number of spaces.

A: You have two options to achieve this.
use pre htnml tag
or
you have to hard code the space chars into   non-breaking white spaces.
hope it will help you to some extent.