text:
Q: merge 4 videos and put audio in different tracks/channels I'm pretty new to ffmpeg, so I'm having a bit of a struggle.
I have found a way to merge 4 videos into one side-by-side video grid (2x2) with following code:
ffmpeg -y -i vid1.mp4 -i vid2.mp4 -i vid3.mp4 -i vid4.mp4 -filter_complex "[0:0]pad=iw*2:ih*2[a];[1:0]null[b];[2:0]null[c];[3:0]null[d];[a][b]overlay=w[x];[x][c]overlay=0:h[y];[y][d]overlay=w:h" multiple_input_grid.mp4

What I would like to do is distribute the audio of each video as follows

*

*Audio from vid1 to audiotrack 1 -> left channel

*Audio from vid2 to audiotrack 1 -> right channel

*Audio from vid3 to audiotrack 2 -> left channel

*Audio from vid4 to audiotrack 2 -> right channel

So multiple_input_grid.mp4 will have 2 audio tracks with different left/right audio
Is there a way of doing this in ffmpeg?
Thanks
The command I'm using (this should have 4 different sources, but has 4x the same):
C:\Users\Gijs\Documents\ffmpeg-20130820-git-68b63a3-win64-static\bin>ffmpeg -y -
i VIDEO0050.mp4 -i VIDEO0050.mp4 -i VIDEO0050.mp4 -i VIDEO0050.mp4 -filter_compl
ex "[0:0]pad=iw*2:ih*2[a];[1:0]null[b];[2:0]null[c];[3:0]null[d];[a][b]overlay=w
[x];[x][c]overlay=0:h[y];[y][d]overlay=w:h" multiple_input_grid.mp4

Output:
ffmpeg version N-55644-g68b63a3 Copyright (c) 2000-2013 the FFmpeg developers
  built on Aug 19 2013 20:32:00 with gcc 4.7.3 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
le-iconv --enable-libass --enable-libbluray --enable-libcaca --enable-libfreetyp
e --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --ena
ble-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-l
ibopus --enable-librtmp --enable-libschroedinger --enable-libsoxr --enable-libsp
eex --enable-libtheora --enable-libtwolame --enable-libvo-aacenc --enable-libvo-
amrwbenc --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libxavs --
enable-libxvid --enable-zlib
  libavutil      52. 42.100 / 52. 42.100
  libavcodec     55. 28.100 / 55. 28.100
  libavformat    55. 13.103 / 55. 13.103
  libavdevice    55.  3.100 / 55.  3.100
  libavfilter     3. 82.100 /  3. 82.100
  libswscale      2.  5.100 /  2.  5.100
  libswresample   0. 17.103 /  0. 17.103
  libpostproc    52.  3.100 / 52.  3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'VIDEO0050.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isom3gp4
    creation_time   : 2013-08-13 13:32:27
  Duration: 00:00:28.35, start: 0.000000, bitrate: 5298 kb/s
    Stream #0:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yu
v420p, 720x1280, 5001 kb/s, SAR 65536:65536 DAR 9:16, 29.40 fps, 30.17 tbr, 90k
tbn, 180k tbc
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : VideoHandle
    Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 95 k
b/s
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : SoundHandle
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from 'VIDEO0050.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isom3gp4
    creation_time   : 2013-08-13 13:32:27
  Duration: 00:00:28.35, start: 0.000000, bitrate: 5298 kb/s
    Stream #1:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yu
v420p, 720x1280, 5001 kb/s, SAR 65536:65536 DAR 9:16, 29.40 fps, 30.17 tbr, 90k
tbn, 180k tbc
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : VideoHandle
    Stream #1:1(eng): Audio: aac (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 95 k
b/s
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : SoundHandle
Input #2, mov,mp4,m4a,3gp,3g2,mj2, from 'VIDEO0050.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isom3gp4
    creation_time   : 2013-08-13 13:32:27
  Duration: 00:00:28.35, start: 0.000000, bitrate: 5298 kb/s
    Stream #2:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yu
v420p, 720x1280, 5001 kb/s, SAR 65536:65536 DAR 9:16, 29.40 fps, 30.17 tbr, 90k
tbn, 180k tbc
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : VideoHandle
    Stream #2:1(eng): Audio: aac (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 95 k
b/s
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : SoundHandle
Input #3, mov,mp4,m4a,3gp,3g2,mj2, from 'VIDEO0050.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isom3gp4
    creation_time   : 2013-08-13 13:32:27
  Duration: 00:00:28.35, start: 0.000000, bitrate: 5298 kb/s
    Stream #3:0(eng): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yu
v420p, 720x1280, 5001 kb/s, SAR 65536:65536 DAR 9:16, 29.40 fps, 30.17 tbr, 90k
tbn, 180k tbc
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : VideoHandle
    Stream #3:1(eng): Audio: aac (mp4a / 0x6134706D), 44100 Hz, mono, fltp, 95 k
b/s
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : SoundHandle
[libx264 @ 0000000002788fc0] using SAR=1/1
[libx264 @ 0000000002788fc0] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2
AVX
[libx264 @ 0000000002788fc0] profile High, level 5.0
[libx264 @ 0000000002788fc0] 264 - core 135 r2345 f0c1c53 - H.264/MPEG-4 AVC cod
ec - Copyleft 2003-2013 - http://www.videolan.org/x264.html - options: cabac=1 r
ef=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed
_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pski
p=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 deci
mate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_
adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=2
5 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.6
0 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'multiple_input_grid.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 0
    compatible_brands: isom3gp4
    encoder         : Lavf55.13.103
    Stream #0:0: Video: h264 (libx264) ([33][0][0][0] / 0x0021), yuv420p, 1440x2
560 [SAR 1:1 DAR 9:16], q=-1--1, 11584 tbn, 30.17 tbc
    Stream #0:1(eng): Audio: aac (libvo_aacenc) ([64][0][0][0] / 0x0040), 44100
Hz, mono, s16, 128 kb/s
    Metadata:
      creation_time   : 2013-08-13 13:32:27
      handler_name    : SoundHandle
Stream mapping:
  Stream #0:0 (h264) -> pad (graph 0)
  Stream #1:0 (h264) -> null (graph 0)
  Stream #2:0 (h264) -> null (graph 0)
  Stream #3:0 (h264) -> null (graph 0)
  overlay (graph 0) -> Stream #0:0 (libx264)
  Stream #0:1 -> #0:1 (aac -> libvo_aacenc)
Press [q] to stop, [?] for help
frame=   19 fps=0.0 q=0.0 size=       0kB time=00:00:00.94 bitrate=   0.4kbits/s
frame=   42 fps= 41 q=0.0 size=       0kB time=00:00:01.64 bitrate=   0.2kbits/s
frame=   46 fps= 23 q=0.0 size=       0kB time=00:00:01.76 bitrate=   0.2kbits/s
frame=   54 fps= 21 q=29.0 size=     179kB time=00:00:01.99 bitrate= 735.9kbits/
frame=   58 fps= 19 q=29.0 size=     338kB time=00:00:02.22 bitrate=1245.2kbits/
frame=   65 fps= 17 q=29.0 size=     546kB time=00:00:02.34 bitrate=1908.9kbits/
frame=   73 fps= 16 q=29.0 size=     778kB time=00:00:02.57 bitrate=2476.6kbits/
frame=   80 fps= 16 q=29.0 size=     927kB time=00:00:02.92 bitrate=2599.0kbits/
frame=   85 fps= 15 q=29.0 size=    1089kB time=00:00:02.92 bitrate=3053.5kbits/
frame=   91 fps= 14 q=29.0 size=    1268kB time=00:00:03.15 bitrate=3293.1kbits/
frame=   99 fps= 14 q=29.0 size=    1481kB time=00:00:03.50 bitrate=3462.3kbits/
frame=  107 fps= 14 q=29.0 size=    1666kB time=00:00:03.73 bitrate=3653.1kbits/
frame=  115 fps= 14 q=29.0 size=    1898kB time=00:00:03.96 bitrate=3919.8kbits/
frame=  123 fps= 13 q=29.0 size=    2121kB time=00:00:04.19 bitrate=4137.0kbits/
frame=  130 fps= 13 q=29.0 size=    2267kB time=00:00:04.43 bitrate=4190.3kbits/
frame=  135 fps= 13 q=29.0 size=    2428kB time=00:00:04.66 bitrate=4265.3kbits/
frame=  143 fps= 13 q=29.0 size=    2625kB time=00:00:04.89 bitrate=4392.4kbits/
frame=  149 fps= 13 q=29.0 size=    2783kB time=00:00:05.01 bitrate=4548.5kbits/
frame=  155 fps= 13 q=29.0 size=    2984kB time=00:00:05.36 bitrate=4560.0kbits/
frame=  163 fps= 13 q=29.0 size=    3195kB time=00:00:05.59 bitrate=4680.1kbits/
frame=  171 fps= 13 q=29.0 size=    3396kB time=00:00:05.82 bitrate=4776.1kbits/
frame=  179 fps= 13 q=29.0 size=    3573kB time=00:00:06.05 bitrate=4832.0kbits/
frame=  186 fps= 13 q=29.0 size=    3785kB time=00:00:06.28 bitrate=4929.5kbits/
frame=  192 fps= 13 q=29.0 size=    3949kB time=00:00:06.52 bitrate=4960.0kbits/
frame=  200 fps= 13 q=29.0 size=    4150kB time=00:00:06.75 bitrate=5033.0kbits/
frame=  206 fps= 13 q=29.0 size=    4306kB time=00:00:06.87 bitrate=5134.7kbits/
frame=  212 fps= 12 q=29.0 size=    4513kB time=00:00:07.21 bitrate=5121.3kbits/
frame=  220 fps= 12 q=29.0 size=    4707kB time=00:00:07.45 bitrate=5175.1kbits/
frame=  228 fps= 12 q=29.0 size=    4918kB time=00:00:07.68 bitrate=5244.0kbits/
frame=  235 fps= 12 q=29.0 size=    5068kB time=00:00:07.91 bitrate=5245.4kbits/
frame=  241 fps= 12 q=29.0 size=    5249kB time=00:00:08.14 bitrate=5277.5kbits/
frame=  248 fps= 12 q=29.0 size=    5444kB time=00:00:08.37 bitrate=5321.9kbits/
frame=  256 fps= 12 q=29.0 size=    5666kB time=00:00:08.61 bitrate=5390.4kbits/
frame=  264 fps= 12 q=29.0 size=    5869kB time=00:00:08.84 bitrate=5436.2kbits/
frame=  268 fps= 12 q=29.0 size=    5976kB time=00:00:09.07 bitrate=5393.6kbits/
frame=  276 fps= 12 q=29.0 size=    6201kB time=00:00:09.30 bitrate=5457.8kbits/
frame=  284 fps= 12 q=29.0 size=    6416kB time=00:00:09.54 bitrate=5509.1kbits/
frame=  292 fps= 12 q=29.0 size=    6622kB time=00:00:09.77 bitrate=5551.1kbits/
frame=  297 fps= 12 q=29.0 size=    6744kB time=00:00:10.00 bitrate=5521.7kbits/
frame=  306 fps= 12 q=29.0 size=    7125kB time=00:00:10.23 bitrate=5701.5kbits/
frame=  314 fps= 12 q=29.0 size=    7364kB time=00:00:10.46 bitrate=5762.2kbits/
frame=  321 fps= 12 q=29.0 size=    7540kB time=00:00:10.70 bitrate=5771.5kbits/
frame=  327 fps= 12 q=29.0 size=    7732kB time=00:00:11.04 bitrate=5732.3kbits/
frame=  331 fps= 12 q=29.0 size=    7834kB time=00:00:11.16 bitrate=5747.2kbits/
frame=  337 fps= 12 q=29.0 size=    8025kB time=00:00:11.28 bitrate=5827.0kbits/
frame=  342 fps= 12 q=29.0 size=    8191kB time=00:00:11.39 bitrate=5887.2kbits/
frame=  349 fps= 12 q=29.0 size=    8395kB time=00:00:11.63 bitrate=5912.9kbits/
frame=  357 fps= 12 q=29.0 size=    8648kB time=00:00:11.97 bitrate=5914.6kbits/
frame=  365 fps= 12 q=29.0 size=    8908kB time=00:00:12.21 bitrate=5976.1kbits/
frame=  372 fps= 12 q=29.0 size=    9100kB time=00:00:12.44 bitrate=5991.4kbits/
frame=  377 fps= 12 q=29.0 size=    9281kB time=00:00:12.55 bitrate=6054.1kbits/
frame=  382 fps= 12 q=29.0 size=    9435kB time=00:00:12.79 bitrate=6042.7kbits/
frame=  389 fps= 12 q=29.0 size=    9633kB time=00:00:13.02 bitrate=6059.2kbits/
frame=  397 fps= 12 q=29.0 size=    9864kB time=00:00:13.25 bitrate=6096.3kbits/
frame=  405 fps= 12 q=29.0 size=   10104kB time=00:00:13.48 bitrate=6137.0kbits/
frame=  412 fps= 12 q=29.0 size=   10289kB time=00:00:13.83 bitrate=6091.8kbits/
frame=  417 fps= 12 q=29.0 size=   10465kB time=00:00:13.95 bitrate=6144.6kbits/
frame=  424 fps= 12 q=29.0 size=   10691kB time=00:00:14.18 bitrate=6174.5kbits/
frame=  429 fps= 12 q=29.0 size=   10895kB time=00:00:14.30 bitrate=6241.0kbits/
frame=  434 fps= 12 q=29.0 size=   11068kB time=00:00:14.41 bitrate=6289.4kbits/
frame=  441 fps= 12 q=29.0 size=   11281kB time=00:00:14.76 bitrate=6258.8kbits/
frame=  448 fps= 12 q=29.0 size=   11507kB time=00:00:14.99 bitrate=6285.4kbits/
frame=  453 fps= 12 q=29.0 size=   11713kB time=00:00:15.11 bitrate=6348.8kbits/
frame=  460 fps= 12 q=29.0 size=   11936kB time=00:00:15.34 bitrate=6372.2kbits/
frame=  464 fps= 12 q=29.0 size=   12124kB time=00:00:15.57 bitrate=6375.6kbits/
frame=  471 fps= 12 q=29.0 size=   12394kB time=00:00:15.80 bitrate=6422.1kbits/
frame=  474 fps= 12 q=29.0 size=   12519kB time=00:00:15.80 bitrate=6486.8kbits/
frame=  481 fps= 12 q=29.0 size=   12790kB time=00:00:16.04 bitrate=6531.2kbits/
frame=  488 fps= 12 q=29.0 size=   13020kB time=00:00:16.27 bitrate=6553.7kbits/
frame=  493 fps= 11 q=29.0 size=   13261kB time=00:00:16.50 bitrate=6581.2kbits/
frame=  499 fps= 11 q=29.0 size=   13430kB time=00:00:16.73 bitrate=6572.9kbits/
frame=  504 fps= 11 q=29.0 size=   13643kB time=00:00:16.85 bitrate=6631.1kbits/
frame=  508 fps= 11 q=29.0 size=   13788kB time=00:00:16.97 bitrate=6655.8kbits/
frame=  514 fps= 11 q=29.0 size=   13995kB time=00:00:17.08 bitrate=6709.5kbits/
frame=  519 fps= 11 q=29.0 size=   14187kB time=00:00:17.43 bitrate=6665.6kbits/
frame=  525 fps= 11 q=29.0 size=   14402kB time=00:00:17.55 bitrate=6722.0kbits/
frame=  531 fps= 11 q=29.0 size=   14653kB time=00:00:17.78 bitrate=6750.1kbits/
frame=  537 fps= 11 q=29.0 size=   14909kB time=00:00:17.89 bitrate=6823.4kbits/
frame=  544 fps= 11 q=29.0 size=   15172kB time=00:00:18.13 bitrate=6854.6kbits/
frame=  553 fps= 11 q=29.0 size=   15667kB time=00:00:18.48 bitrate=6945.0kbits/
frame=  558 fps= 11 q=29.0 size=   15829kB time=00:00:18.59 bitrate=6972.8kbits/
frame=  564 fps= 11 q=29.0 size=   16067kB time=00:00:18.82 bitrate=6990.6kbits/
frame=  570 fps= 11 q=29.0 size=   16264kB time=00:00:18.94 bitrate=7033.1kbits/
frame=  576 fps= 11 q=29.0 size=   16530kB time=00:00:19.29 bitrate=7019.1kbits/
frame=  582 fps= 11 q=29.0 size=   16754kB time=00:00:19.40 bitrate=7071.5kbits/
frame=  588 fps= 11 q=29.0 size=   17015kB time=00:00:19.64 bitrate=7096.9kbits/
frame=  595 fps= 11 q=29.0 size=   17255kB time=00:00:19.87 bitrate=7112.8kbits/
frame=  601 fps= 11 q=29.0 size=   17491kB time=00:00:19.98 bitrate=7168.3kbits/
frame=  606 fps= 11 q=29.0 size=   17659kB time=00:00:20.22 bitrate=7153.8kbits/
frame=  611 fps= 11 q=29.0 size=   17835kB time=00:00:20.45 bitrate=7143.0kbits/
frame=  618 fps= 11 q=29.0 size=   18125kB time=00:00:20.56 bitrate=7218.1kbits/
frame=  624 fps= 11 q=29.0 size=   18306kB time=00:00:20.80 bitrate=7208.9kbits/
frame=  631 fps= 11 q=29.0 size=   18510kB time=00:00:21.15 bitrate=7169.4kbits/
frame=  638 fps= 11 q=29.0 size=   18771kB time=00:00:21.26 bitrate=7230.6kbits/
frame=  644 fps= 11 q=29.0 size=   18953kB time=00:00:21.49 bitrate=7221.9kbits/
frame=  647 fps= 11 q=29.0 size=   19065kB time=00:00:21.61 bitrate=7225.8kbits/
frame=  653 fps= 11 q=29.0 size=   19312kB time=00:00:21.73 bitrate=7280.0kbits/
frame=  660 fps= 11 q=29.0 size=   19499kB time=00:00:22.07 bitrate=7234.8kbits/
frame=  666 fps= 11 q=29.0 size=   19717kB time=00:00:22.19 bitrate=7277.2kbits/
frame=  673 fps= 11 q=29.0 size=   19897kB time=00:00:22.42 bitrate=7267.7kbits/
frame=  679 fps= 11 q=29.0 size=   20081kB time=00:00:22.54 bitrate=7297.2kbits/
frame=  685 fps= 11 q=29.0 size=   20324kB time=00:00:22.89 bitrate=7273.1kbits/
frame=  692 fps= 11 q=29.0 size=   20536kB time=00:00:23.12 bitrate=7275.0kbits/
frame=  700 fps= 11 q=29.0 size=   20776kB time=00:00:23.47 bitrate=7251.0kbits/
frame=  707 fps= 11 q=29.0 size=   20948kB time=00:00:23.58 bitrate=7275.1kbits/
frame=  711 fps= 11 q=29.0 size=   21160kB time=00:00:23.70 bitrate=7312.5kbits/
frame=  716 fps= 11 q=29.0 size=   21299kB time=00:00:23.82 bitrate=7324.8kbits/
frame=  722 fps= 11 q=29.0 size=   21472kB time=00:00:24.16 bitrate=7277.8kbits/
frame=  728 fps= 11 q=29.0 size=   21674kB time=00:00:24.28 bitrate=7311.2kbits/
frame=  736 fps= 11 q=29.0 size=   21912kB time=00:00:24.63 bitrate=7287.1kbits/
frame=  744 fps= 11 q=29.0 size=   22163kB time=00:00:24.86 bitrate=7301.6kbits/
frame=  749 fps= 11 q=29.0 size=   22354kB time=00:00:24.98 bitrate=7330.2kbits/
frame=  755 fps= 11 q=29.0 size=   22555kB time=00:00:25.09 bitrate=7362.0kbits/
frame=  761 fps= 11 q=29.0 size=   22739kB time=00:00:25.33 bitrate=7354.2kbits/
frame=  767 fps= 11 q=29.0 size=   23006kB time=00:00:25.56 bitrate=7372.7kbits/
frame=  774 fps= 11 q=29.0 size=   23232kB time=00:00:25.79 bitrate=7378.2kbits/
frame=  781 fps= 11 q=29.0 size=   23464kB time=00:00:26.02 bitrate=7385.5kbits/
frame=  788 fps= 11 q=29.0 size=   23711kB time=00:00:26.14 bitrate=7430.0kbits/
frame=  792 fps= 11 q=29.0 size=   23853kB time=00:00:26.25 bitrate=7441.6kbits/
frame=  799 fps= 11 q=29.0 size=   24083kB time=00:00:26.60 bitrate=7414.9kbits/
frame=  806 fps= 11 q=29.0 size=   24519kB time=00:00:26.83 bitrate=7483.7kbits/
frame=  813 fps= 11 q=29.0 size=   24713kB time=00:00:27.07 bitrate=7478.3kbits/
frame=  818 fps= 11 q=29.0 size=   24926kB time=00:00:27.18 bitrate=7510.7kbits/
frame=  823 fps= 11 q=29.0 size=   25074kB time=00:00:27.41 bitrate=7491.2kbits/
frame=  830 fps= 11 q=29.0 size=   25314kB time=00:00:27.65 bitrate=7499.2kbits/
frame=  836 fps= 11 q=29.0 size=   25541kB time=00:00:27.76 bitrate=7535.0kbits/
frame=  841 fps= 11 q=29.0 size=   25669kB time=00:00:28.00 bitrate=7510.0kbits/
frame=  850 fps= 11 q=29.0 size=   25971kB time=-577014:-32:-22.-77 bitrate=N/A
frame=  850 fps= 10 q=-1.0 Lsize=   27415kB time=00:00:28.37 bitrate=7915.7kbits
/s dup=21 drop=0
video:26940kB audio:444kB subtitle:0 global headers:0kB muxing overhead 0.113344
%
[libx264 @ 0000000002788fc0] frame I:4     Avg QP:20.92  size:166382
[libx264 @ 0000000002788fc0] frame P:246   Avg QP:23.11  size: 60370
[libx264 @ 0000000002788fc0] frame B:600   Avg QP:26.45  size: 20116
[libx264 @ 0000000002788fc0] consecutive B-frames:  4.2%  1.9%  9.2% 84.7%
[libx264 @ 0000000002788fc0] mb I  I16..4: 12.5% 73.1% 14.4%
[libx264 @ 0000000002788fc0] mb P  I16..4:  1.9%  3.4%  0.5%  P16..4: 55.6% 14.5
%  7.5%  0.0%  0.0%    skip:16.6%
[libx264 @ 0000000002788fc0] mb B  I16..4:  0.2%  0.3%  0.1%  B16..8: 43.8%  3.9
%  0.8%  direct: 2.9%  skip:48.0%  L0:50.7% L1:46.7% BI: 2.6%
[libx264 @ 0000000002788fc0] 8x8 transform intra:60.5% inter:79.4%
[libx264 @ 0000000002788fc0] coded y,uvDC,uvAC intra: 50.1% 56.3% 11.6% inter: 1
4.5% 16.6% 0.1%
[libx264 @ 0000000002788fc0] i16 v,h,dc,p: 35% 23% 12% 31%
[libx264 @ 0000000002788fc0] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 28% 15% 25%  6%  4%
 5%  4%  9%  5%
[libx264 @ 0000000002788fc0] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 37% 14% 13%  6%  6%
 7%  4%  8%  4%
[libx264 @ 0000000002788fc0] i8c dc,h,v,p: 61% 14% 21%  3%
[libx264 @ 0000000002788fc0] Weighted P-Frames: Y:2.8% UV:2.0%
[libx264 @ 0000000002788fc0] ref P L0: 58.0%  6.9% 26.5%  8.4%  0.1%
[libx264 @ 0000000002788fc0] ref B L0: 86.3% 10.7%  3.0%
[libx264 @ 0000000002788fc0] ref B L1: 93.4%  6.6%
[libx264 @ 0000000002788fc0] kb/s:7832.26

A:
Example of 2x2 overlay grid (vertical orientation as in Gijserman's inputs)
Create 2x2 grid overlay and combine 4 mono inputs into 1 stereo output
Example using the pad video filter to create the background, overlay video filter to place each video, amerge audio filter to merge all audio streams into one 4 channel stream, and pan audio filter to combine the resulting 4 channels into stereo (vid1.mp4 and vid3.mp4 audio into left channel, vid2.mp4 and vid4.mp4 audio into right channel):
ffmpeg -y -i vid1.mp4 -i vid2.mp4 -i vid3.mp4 -i vid4.mp4 -filter_complex \
"[0:v]pad=iw*2:ih*2[bg]; \
 [bg][1:v]overlay=w[z]; \
 [z][2:v]overlay=0:h[y]; \
 [y][3:v]overlay=w:h; \
 [0:a][1:a][2:a][3:a]amerge=inputs=4,pan=stereo:c0<c0+c2:c1<c1+c3" \
output.mp4

or you can simply use -ac 2 instead of pan:
ffmpeg -y -i vid1.mp4 -i vid2.mp4 -i vid3.mp4 -i vid4.mp4 -filter_complex \
"[0:v]pad=iw*2:ih*2[bg]; \
 [bg][1:v]overlay=w[z]; \
 [z][2:v]overlay=0:h[y]; \
 [y][3:v]overlay=w:h; \
 [0:a][1:a][2:a][3:a]amerge=inputs=4" \
-ac 2 output.mp4

The advantage of pan over -ac 2, I believe, is that pan can renormalize gain to avoid clipping noise. This is why the first example is quieter.
Note that if your inputs contain more than one audio stream then your stream specifiers must be more specific, such as [2:a:0] (first [0] audio stream [a] of the third input [2]).
Create 2x2 grid overlay and combine 4 mono inputs into 2 stereo outputs
Same as above, but vid1.mp4 (left channel) and vid2.mp4 (right channel) audio will be one stereo output stream, and vid3.mp4 (left channel) and vid4.mp4 (right channel) audio will be the second output audio stream:
ffmpeg -y -i vid1.mp4 -i vid2.mp4 -i vid3.mp4 -i vid4.mp4 -filter_complex \
"[0:v]pad=iw*2:ih*2[bg]; \
 [bg][1:v]overlay=w[z]; \
 [z][2:v]overlay=0:h[y]; \
 [y][3:v]overlay=w:h; \
 [0:a][1:a]amerge;
 [2:a][3:a]amerge" \
output.mp4

Create 2x2 grid overlay and combine 4 stereo inputs into 2 stereo outputs

*

*The stereo audio from vid1.mp4 will become the left channel of the
first output stereo stream.

*The stereo audio from vid2.mp4 will become the right channel of the
first output stereo stream.

*The stereo audio from vid3.mp4 will become the left channel of the
second output stereo stream.

*The stereo audio from vid4.mp4 will become the right channel of the
second output stereo stream.

Example:
ffmpeg -y -i vid1.mp4 -i vid2.mp4 -i vid3.mp4 -i vid4.mp4 -filter_complex \
"[0:v]pad=iw*2:ih*2[bg]; \
 [bg][1:v]overlay=w[z]; \
 [z][2:v]overlay=0:h[y]; \
 [y][3:v]overlay=w:h[vid]; \
 [0:a]pan=stereo:c0<c0+c1[left1]; \
 [1:a]pan=stereo:c1<c0+c1[right1]; \
 [left1][right1]amerge,pan=stereo:c0<c0+c2:c1<c1+c3[audio1]; \
 [2:a]pan=stereo:c0<c0+c1[left2]; \
 [3:a]pan=stereo:c1<c0+c1[right2]; \
 [left2][right2]amerge,pan=stereo:c0<c0+c2:c1<c1+c3[audio2]" \
-map "[vid]" -map "[audio1]" -map "[audio2]" output.mkv


text:
Q: Backbone view delegateevents won't work I'm having an issue with getting delegateEvents to work.
here's my View definition:
//the "." in Mustache templating simply means it will iterate through an array of JSON objects
var locationViewTemplate = '

' +
'{{#.}}' +
'
{{Name}} edit
' +
'{{/.}}' +
'{{^.}}' +
'
No Locations Defined
' +
'{{/.}}' +
'

<input type="text" id="locationName"> <input class="locationAdd" type="button" title="Add Location" id="locationAdd" value="Add">
';

//module: Location
(function(Location) {
//define Model
Location.LocationModel = Backbone.Model.extend({
    initialize: function () {
        this.entityName = 'location';
    }
});

//define collection
Location.LocationCollection = Backbone.Collection.extend({
    model: Location.LocationModel,
    initialize: function () {
        this.entityName = 'location';
    },
    getAllLocations: function () {
        this.functionName = 'GetAll';
        this.fetch();
    }
});

//define View(s)
Location.LocationListView = Backbone.View.extend({
    events: {
        'click #locationAdd': 'addClickEvent'
    },
    render: function () {
        $(this.el).html(Mustache.render(locationViewTemplate, this.collection.toJSON()));
        //this.delegateEvents();

        return this;
    },
    initialize: function() {
        this.render();
        //this.delegateEvents();
    },
    addClickEvent: function (){
        alert('this is the function');
    }

});

})(vHub.module('location'));

Here's the definition of the button that the selector '#locationAdd' should find:
<input class="locationAdd" type="button" title="Add Location" id="locationAdd" value="Add">

I also call delegateEvents from the document ready event:
//steal the JS libs that we need
steal('json2.js','mustache.js','underscore.js', 'jquery-ui-1.8.18.custom.min.js')
.then('backbone.js')
.then('./common.js')
.then('./modules/FrameTop.js', './modules/Location.js')
.then('./modules/AdminBasicsPage.js')
.then( function() {
$(function(){
initializeApp();

var Location = vHub.module('location');
var lc = new Location.LocationCollection();
lc.getAllLocations();

var lv = new Location.LocationListView({collection: lc});

$('#content').html($(lv.el).html());

});
});

I've looked at what i could find here on stackOverflow, and tried some of those suggestions.  But none have been successful yet.  Any help would be greatly appreciated.  Thanks!

A: Funny you should ask... I just solved a similar problem in an app I'm working on, and lo and behold, this was the top question under the Backbone.js tag.
Not sure that we were having the same issue, but my problem was that the button I was trying to attach to was actually outside of the scope of my view. Backbone views have an el property, and click events are only attached to children of that root element.
In my app, I had a list view which had a ul as it's root element. Both my button and the list were siblings inside of a div tag:

    <button id="save">Save</button>

My code worked initially because I set up the click handler using a raw jQuery selector in the initialize function. I was actually reaching outside of the scope of my view and attaching the click handler, which wasn't at all my intention. When I refactored to try to make it fit the Backbone convention, it failed to fire.
Try using a regular jQuery selector in your code, and if it works, you probably have a similar scoping problem. Like this:
initialize: function() {
    $('#locationAdd').click(addClickEvent);
    this.render();
}

That's not the Backbone way of doing this--you want to use the events hash like you have done in your code. But you may need to nest your collection view inside of a control-level view.

A: I took what I could from the code you posted and here is a little working example. If you want to post more code I could possibly help debug. As Elf mentioned, no need to explicitly call delegateEvents().

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I launch OCUnit test on iPhone from Command line I want to run unit test on iPhone without using Xcode. Is there any command line utility to run OCunit test on iPhone device.
I also tried fruit-strap but it only launches App not OCtests. "fruitstrap -d path_of_app" this command install app but I did not found any way to install and run octest on iPhone.

A: Look at the similar issue, I've opened recently: Is there any non-Xcode-based command line testing tool for Objective-C.
There is the answer by @MalteTancred. I am trying to adapt his answer to my project and can say that it is not a very easy task to get the stuff (that Xcode does out of box) to work when made by hands in command line.


text:
Q: Bash: How to remove 0x0A character from start of file Somewhere before the line count=~echo "$conflict" | wc -l~ (~ are used in place of back quote), the hex character 0x0A is being added. So, when the files $DA and $DB are the same (meaning the script should return a null set), 0x0A is being added. So, instead of the line count being zero in the next command, the count is 1. It is being added to the end the output for each iteration of the loop. It isn't a big deal for loops returning other content as well but is an annoyance for loops in which a null set should be returned (and accordingly, a new file should not be created). I have experimented with inserting tr -d '\r' and tr -d '\n' at the start and end of the conflict=~cat "$DA" "$DB" line but it hasn't helped.
How can I simply delete any line that contains only this character (or really any non-printable character except for \n)?
Your help is appreciated.
# Files "DA" and "DB" are titled as such:
# 10M_$i_$j_$m_OtherNonRelevantChars or 10M_$i_$k_$n_OtherNonRelevantChars
# Field one is an integer; fields 2 and 3 are alphanumeric (checksum hashes)

IFS=$'\n'

for i in {1..7}
    do for j in {P,B,R}
        do for k in {P,B,R}
            do for m in {3,9}
                do for n in {3,9}
                    do
                        DA=`ls "10M_${i}_${j}_${m}"*`
                        DB=`ls "10M_${i}_${k}_${n}"*`
                        dos2unix "$DA" "$DB"

                        conflict=`cat "$DA" "$DB" | \
                            awk  -v OFS=',' -F',' '{print $1,substr($2,0,8),substr($3,0,8)}' | \
                            sort -t',' -k1,1n | uniq -u | \
                            awk -v i=$i -v j=$j -v k=$k -v m=$m -v n=$n -v OFS=',' -F',' '{print i,j,m,k,n,$1}' | \
                            uniq -d`

                        # The unwanted character appears somewhere before here
                        count=`echo "$conflict" | wc -l`
                        if [[ "$count" -gt 0 ]]
                            then
                                echo $conflict  >> "C_${i}_${j}_${m}_${k}_${n}.txt" # output of conflicting hashes for given matching unique first field ID
                        fi
                        echo "$i $j $m $k $n"
                    done
                done
            done
        done
    done

A: $count is always greater than zero because echo adds a newline character. Each of these commands prints 1:
conflict=""; echo "$conflict" | wc -l
             echo ""          | wc -l
             echo             | wc -l

Echoing the content of a variable that contains newline character(s) can only increase the count.
This is what happens:

*

*Command substitution (conflict=…) removes all trailing newline characters.

*Therefore we can consider few cases:

*

*If there is a newline character followed by a non-newline character the the variable will contain at least one newline character.

*If the first line is non-empty and all (zero or more) following lines are empty then the variable will be non-empty but it will contain exactly zero newline characters.

*If there is only an incomplete line then the variable will be non-empty but it will contain exactly zero newline characters.

*If all the lines are empty then the variable will be empty; as such it will contain exactly zero newline characters.

*If the output is empty then the variable will be empty; as such it will contain exactly zero newline characters.

*As already stated, echo adds exactly one newline character.

*wc -l counts newline characters. When we say it counts lines, we mean formally defined lines. An incomplete line is not a line in these terms.
So after echo there is at least one newline character and [[ "$count" -gt 0 ]] is always true. Worse, using printf or echo -n to avoid adding an extra newline (xor taking it into account with -gt 1) is not a solution because "exactly one line" and "empty output" (and few other cases) generate the same number of newlines in the variable: zero.
In your case probably it's enough to test if $conflict is not empty:
[ -n "$conflict" ]

In general you may want to keep trailing newlines. It seems your second awk cannot generate empty lines though.

Note if you calculated count directly, without the intermediate conflict variable
count="$(cat … | … | wc -l)"

then there would be no problem. I notice you use $conflict later (don't you want to quote it?), so this approach is not really an option (unless you decide to obtain count and conflict independently, which is sub-optimal and in general may lead to inconsistent results when input data changes in between).

Let's get back to incomplete lines. You're using dos2unix. In the DOS/Windows world a text file may end with an incomplete line (in terms of POSIX). If this happens then after dos2unix the incomplete line will still be incomplete. You have at least two potential problems when you run cat "$DA" "$DB" | …:

*

*If the first file ends with an incomplete line then it will be concatenated with the beginning of the second file without any newline in between.

*If the second file ends with an incomplete line then the output from cat will end with it and the tools later in the pipe may "misbehave". Text processing tools expect text, lines. In general, upon encountering an incomplete line such tool may:

*

*ignore the incomplete line as if it wasn't there;

*or accept it and pass it (think about a filter like grep) to its output as an incomplete line;

*or accept it, fix (add a newline character) and pass it to its output as a complete line;

*or throw an error (example).

So pay attention to your input files.


text:
Q: Is it possible to create my own system of math with a new set of axioms that may or may not be observable in "the real world"? If the axioms that we know about are true statements that can not be proven and are the foundation of "standard mathematics", would it still be considered mathematics if I create my own set of axioms then derive theorems from those axioms? Despite that the axioms probably wouldn't be observable in the real world just like how 2 apples + 2 apples =/ 3 apples (and thus wouldn't be applicable to anything) but would that still be a valid system you would consider as mathematics?

A: So, if I understand your question correctly, then the answer is definitely "yes", without doubt.
There are already existing axiomatic systems which are independently studied but mutually inconsistent. Based on your question, I have no information about your current level of familiarity with mathematical structures. So I will use the easiest examples I can think of:
EXAMPLE A: The additive group of integers, denoted by $(\mathbb{Z},+)$, consisting of the numbers $\cdots, -3, -2, -1, 0, 1, 2, 3, \cdots$:

*

*AXIOM G1: There is an integer $0$ such that $a+0=a$ for any integer $a$.

*AXIOM G2: For any integer $x$ there is an "opposite" integer, denoted by $(-x)$, such that $x+(-x)=0$.

*AXIOM G3: For any integers $a$, $b$, $c$, we have $(a+b)+c=a+(b+c)$.

*AXIOM AB: For any integers $a$ and $b$, we have $a+b=b+a$.

*AXIOM Z1: There is an integer $1\neq0$.

*AXIOM Z2: The integer $1+1+\cdots+1$ is never equal to $0$.

*AXIOM Z3: Every nonzero integer can be written as either $1+1+\cdots+1$ (if it is a positive integer), or $(-1)+(-1)+\cdots+(-1)$ (if it is a negative integer).

EXAMPLE B: The additive group of integers mod 2, denoted by $(\mathbb{Z}_2,+)$, consisting of the numbers $0$ and $1$:

*

*AXIOM G1: There is an integer $0$ such that $a+0=a$ for any integer $a$.

*AXIOM G2: For any integer $x$ there is an "opposite" integer, denoted by $(-x)$, such that $x+(-x)=0$.

*AXIOM G3: For any integers $a$, $b$, $c$, we have $(a+b)+c=a+(b+c)$.

*AXIOM AB: For any integers $a$ and $b$, we have $a+b=b+a$.

*AXIOM Z1: There is an integer $1\neq0$.

*AXIOM Z4: $1+1=0$

*AXIOM Z5: Every integer is equal to either $0$ or $1$.

These two axiomatic systems are clearly inconsistent with each other, especially axioms Z2 from example A and Z4 from example B. However, both $\mathbb{Z}$ and $\mathbb{Z}_2$ have immeasurable importance in not just math but also computer science and statistics.
Now, it is possible that you meant more by your question. However, I am answering your question as I understand it. I hope this helps!
EDIT: If you are interested in the study of consistency and what can be concluded from sets of axioms (known as "theories"), then I highly recommend researching the continuum hypothesis. Basically, the following are all true in standard ZFC set theory:

*

*The size of the set of natural numbers is denoted $\aleph_0$.

*The size of the set of real numbers is denoted $2^{\aleph_0}$.

*It is possible that there exists an infinite set $B$ of size $\beta$ such that $\aleph_0 < \beta < 2^{\aleph_0}$. This is denoted $\neg CH$. "There is a size between countable and continuum."

*It is ALSO possible that there does not exist such a set $B$. This is denoted $CH$. "There is no size between countable and continuum."

In other words, even the axioms you select do not completely determine which statements will be true and false.


text:
Q: Java heap out of space : after -XmX1G I am trying to read a lot of data(10k-20k records) from files (10 threads running for 10 mins). I get an exception:
Exception in thread "main" Exception in thread "Thread-26" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Unknown Source)
    at java.lang.String.<init>(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)

I get the above error message for the code snippet below.
I have been trying to debug this : and the closest I have come is to use CharSequence. But I still get the heap exception. (At this point - can anyone help me understand why CharSequence would be better? => It seems it'll load smaller amount of data in main memory, but eventually all the data needs to be in the main memory).
I am able to run the code if for 1 min. But anything near 10 mins explodes. Is there an efficient way to read the files?
**This code is part of a research and I am still re-factoring it, so a lot of inefficient code does exist.
    try{
        for(int i=0; i<threadCount; i++){
            fstream = new FileInputStream(dir+"//read"+machineid+"-"+i + ".txt");
            // Use DataInputStream to read binary NOT text.
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String line;
            // Read File Line By Line
            String[] tokens;

            while ((line = br.readLine()) != null) {
                tokens = line.split(",");
                logObject record = new logObject(tokens[0], tokens[1], tokens[2],tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], "", tokens[8]);
                toBeProcessed[toBeProcessedArraySz] = record;
                toBeProcessedArraySz++;
                if(readToValidate == toBeProcessedArraySz){

                    try {
                        semaphore.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace(System.out);
                    }
                    //create thread to process the read records
                    ValidationThread newVThread = new ValidationThread(props,toBeProcessed, updateStats, initCnt, semaphore, finalResults, staleSeqSemaphore, staleSeqTracker, seqTracker, seenSeqSemaphore, toBeProcessedArraySz, freshnessBuckets,bucketDuration);
                    vThreads.add(newVThread);
                    toBeProcessedArraySz = 0;
                    toBeProcessed = new logObject[readToValidate];
                    semaphore.release();
                    newVThread.start();
                }
            }
            br.close();//remove to test
            fstream.close();
        }

    }catch(Exception e){
        e.printStackTrace(System.out);
    }

A: Try starting the JVM with a larger heap space; that is call java -Xmx=1G yourProgram. It is hard to tell only by a code snippet why is the program running out of memory. You can also user a profiler tool such as Eclipse MAT to see exactly what objects cause the memory to be full.

A: Do not simply increase the heapsize if you do not understand the problem. Increasing the heapsize does not solve your problem. It only postpones it till it's worse (taking longer to occur).
The problem is that your program does not wait with reading in data when the heap is full. This is a simple problem. There is nothing in your algorithm which stops the reading thread from filling the heap further and further. If the processing threads can not keep up with the reading speed, the OOME must occur at some point. You have to change this: For the data reading thread, add some way that it pauses reading if a maximum number of processing threads are active, and to resume reading data when the number of processing threads goes below this threshold again.
Moreover:
Maybe one of your files is corrupted and contains a very long line, e.g. > 500MB at one line. Find out if the OOME always occurs in the same line (this is very likely the case) and then check the line. What line delimeter does it have at the end, \n or \r\n? Or \r?


text:
Q: Chrome scrolls too much when there is a fixed division at the top of the viewport I'm back.
When there is a fixed division at the top of the viewport, Chrome scrolls too much.
I have created a page which will allow you to text how your browser scrolls and if you have Chrome you can see how Chrome falls on its face.
THE DEMO IS AT http://thetesting.site/fixednav/scrolling.html
There are instructions as to how to use the page and how to reproduce the Chrome problem on the page itself.
I've  been faulted for not providing the code of the page - here is all of it - there is no particular part of the HTML and CSS that I want help on. You have to look at the entire page.
I don't know if the  snippet can be run - have never posted snippets before. Just go to the page and use it.

function resize() {
 // Get the height of the fixed-header. parseInt used to strip off the px in the value
 fixedHeight = parseInt(document.getElementById("topfixed").offsetHeight, 10);

 // Set the height of the fixed, scrolling, instructions division to the viewport height minus the
 // height of the fixed-header and 20px "slop space"
 document.getElementById('instructions').style.height = (parseInt(window.innerHeight, 10)
  - fixedHeight - 20) + "px";
}

gblLastButtonClicked = 0;   // Yes, I'm using a global variable - did so because this is down and dirty.

function buttonclick(button) {
 // Set the height of the fixed-header from the value of the button just clicked. Values are 0px,
 // 10px, 20px....80px
 document.getElementById("topfixed").style.height = button.value;

 // Display the height in the button bar
 document.getElementById("heighttext").innerHTML = "Height is " + button.value + " ";

 // Set the body margin-top to the height of the fixed-header (as gotten from value of the clicked button)
 document.getElementById("body").style.marginTop = button.value;

 // Set the top of the Instructions division to the height of the fixed-header (from button.value)
 document.getElementById("instructions").style.marginTop = button.value;

 // Set the top of the buttonbar division to the height of the fixed-header (from button.value)
 document.getElementById("buttonBar").style.marginTop = button.value;

 // Set the previously clicked button's text to blank
 document.getElementById("button" + gblLastButtonClicked).style.color = "black";

 // Set the previously clicked button's font-weight to normal
 document.getElementById("button" + gblLastButtonClicked).style.fontWeight = "normal";

 // Set the last button clicked global variable.
 gblLastButtonClicked = parseInt(button.value, 10);

 // Set the text color of the button just clicked to red
 button.style.color = "red";

 // Set the font-weight of the button just clicked to bod
 button.style.fontWeight = "bold";

 // Call the resize function (defined above) to resize the fixed instuctions division
 resize();

 // Set the focus to the body of the page. It will be on the button just clicked and setting it to the
 // body allows the use of the pagedown key without clicking on a part of the body - I've seen
 // some browsers which keep the focus on the button and, as a result, pagedown does not scrol the page
 document.getElementById("content").focus();

 // Scroll the page to the top. We do this so the testing always starts at the same point and to save
 // the user from having to do so.
 window.scrollTo(0, 0);

}

function fillPage() {    // this function writes 150 lines of text into the body
 for (i = 1; i < 151; i++) {
  document.writeln("********************** Line #"  + i + "
");
 }
}
 .button {
  width: 50px;
  font-size: 12px;
 }
 .instructions {
  position: fixed ;
  z-index: 10;
  width: 40%;
  overflow: auto;
  font-size: 15px;
  height:500px;
  left: 57%;
  background-color: lightblue;
  color: black;
  padding: 5px;
  border: 2px black solid;
  top: 0px;
 }
 .topfixed {
  background-color: yellow;
  opacity: .8;
  z-index: 1;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 0px;
  color: red;
  font-weight: bold;
 }
 .buttonBar {
  position: fixed;
  left: 0px;
  padding-bottom: 10px;
  background-color: green;
  width: 100px;
  text-align: center;
  z-index: 10;
  top: 0px;
 }
 .content {
  width: 80%;
  margin: 25px auto;
  margin-top: 0px;
 }
function resize() {
 // Get the height of the fixed-header. parseInt used to strip off the px in the value
 fixedHeight = parseInt(document.getElementById("topfixed").offsetHeight, 10);

 // Set the height of the fixed, scrolling, instructions division to the viewport height minus the
 // height of the fixed-header and 20px "slop space"
 document.getElementById('instructions').style.height = (parseInt(window.innerHeight, 10)
  - fixedHeight - 20) + "px";
}

gblLastButtonClicked = 0;   // Yes, I'm using a global variable - did so because this is down and dirty.

function buttonclick(button) {
 // Set the height of the fixed-header from the value of the button just clicked. Values are 0px,
 // 10px, 20px....80px
 document.getElementById("topfixed").style.height = button.value;

 // Display the height in the button bar
 document.getElementById("heighttext").innerHTML = "Height is " + button.value + " ";

 // Set the body margin-top to the height of the fixed-header (as gotten from value of the clicked button)
 document.getElementById("body").style.marginTop = button.value;

 // Set the top of the Instructions division to the height of the fixed-header (from button.value)
 document.getElementById("instructions").style.marginTop = button.value;

 // Set the top of the buttonbar division to the height of the fixed-header (from button.value)
 document.getElementById("buttonBar").style.marginTop = button.value;

 // Set the previously clicked button's text to blank
 document.getElementById("button" + gblLastButtonClicked).style.color = "black";

 // Set the previously clicked button's font-weight to normal
 document.getElementById("button" + gblLastButtonClicked).style.fontWeight = "normal";

 // Set the last button clicked global variable.
 gblLastButtonClicked = parseInt(button.value, 10);

 // Set the text color of the button just clicked to red
 button.style.color = "red";

 // Set the font-weight of the button just clicked to bod
 button.style.fontWeight = "bold";

 // Call the resize function (defined above) to resize the fixed instuctions division
 resize();

 // Set the focus to the body of the page. It will be on the button just clicked and setting it to the
 // body allows the use of the pagedown key without clicking on a part of the body - I've seen
 // some browsers which keep the focus on the button and, as a result, pagedown does not scrol the page
 document.getElementById("content").focus();

 // Scroll the page to the top. We do this so the testing always starts at the same point and to save
 // the user from having to do so.
 window.scrollTo(0, 0);

}

function fillPage() {    // this function writes 150 lines of text into the body
 for (i = 1; i < 151; i++) {
  document.writeln("********************** Line #"  + i + "
");
 }
}

Well, take look at it and see what you think
I've only tested with Chrome and Firefox. If you have other browsers install, please try the page with the and let me know the results.
There are full instructions on the page.
EDIT - here is a page with screen captures of the demo page
EDIT - I have created a version of the demo page which has a work around for Chrome - for Chrome I unfix that fixed-header. I cannot post another link - I'm limited to two - but there is a link to the modified page on the original demo page.
EDIT - It has been seven hours since I posted the URL of the page with screen captures showing how it works and how I expect it to work and 23 hours since I posted the question.
Should I assume that this has everyone stumped?
Has anyone tried this with browsers other than Firefox and Chrome? If so, what were the results - what browser did you try and did it work like Firefox or Chrome?
I'd want to open a bug report with  I'd like to first find out if it behaves the same way with Chrome with higher screen resolution than 1024 x 600.
Has anyone tried this on a screen with resolution higher than 1024 x 600 with Chrome? If so, what were the results? Does it work the same with Chrome with a higher resolution as with 1024 x 600 or does it work differently?
Should I post a step by little step at a time script for testing this? Should I spell it out step by step for Chrome and Firefox using the different height buttons?
EDIT - the last one.
Okay - I'll assume that either no one has any ideas to make it work with Chrome or no one wants to even read the question - most the "views" are probably my checking to see there has been activity.
I've reported this as a Chrome bug and will wait to see what comes of that. Has anyone actually gone to the demo page and tried it out with IE or other browser other than Chrome or Firefox?
I'll assume that this one has everyone is stumped. So much for even hearing from someone who tried a different browser of screen resolution....

A: I'm closing this out - my "answer" is that there is a problem which needs to be addressed. I've submitted a bug report to the folks at Chrome and I am pulling together a lot more documentation to aid them in evaluating the issue.
Since no one took the time to test this and get back to me, I still have not determined the extent of the matter. I have, however, had someone try it out on a screen of much higher resolution and they got the same results as I did.
As I have said, I'm using a standby system with a relatively low resolutions screen, and the issue could be related to some combination of things specific to this system - but, again, I don't have any detailed feedback from any one as to the results of any testing they did.
The issue, simply stated, is that if there is a fixed division at the top of the viewport, depending on the height of the fixed division, Chrome will scroll one or more of the next lines on the next "page" underneath the fixed division when you "page down" The reverse happens when you :page up" except the lines are scroll "off" the bottom of the viewport. I call this "losing lines."
One person said that it is not important, that the fixed divisions get over used, in short - you shouldn't do it and this is not really a bug. They said it is something you can "fix" with code; that it was no big deal and sort of like the chicken and egg thing - I don't quite get that one.
The comments were more in the vein of defending the problem rather than discussing it or sharing testing results.
I've encounter this bug on Yahoo pages and while no one is perfect  - even myself - Yahoo has a good reputation for web design and function and, yet, they are using fixed divisions - are they commenting an error in having that fixed division on their pages? Are they sinning?
If the thought is that a fixed division takes up valuable screen space, well, given the physical size and resolution of new screens, that is hardly a consideration. Sure, you can over do it but there are times, if not a lot of times, when you'd like to keep controls available at the top of the viewport.
I've seen a trend, not away from fixed divisions but towards them, most especially fixed divisions which scroll with the page - for awhile. They don't go to the top and get "fixed" until you scroll down to the point that the information in the division would scroll off the top of the viewport.
Many pages now do this and people are wanting to duplicate it. I've seen a lot of questions as how to do "float the bar and then fix it when needed" here on StackOverFlow.
The first time I encountered such a bar, I thought - Oh, that's cute, but what is the point other than to show "hey, look what I can do?"
As with any tool or facility, you can over use fixed divisions or use them poorly. Whether or not the occurs is what separates computing professionals from the "unwashed masses. :-)
Just to stir things up - remember frames? How they are considered inherently evil? They are not evil, they simply have a couple of issues that caused problems. The most cited one being that when you bookmarked a "page" you really got a bookmark to the frameset, not the content. There is a very simple way to fix that - very simple - and that need not stop anyone from using frames.
You pick the what you think is the best tool for the job and if it has limitations, you either work around them or you reach for a different tool.
One last thing and I'll close this out.
I was discussing computers with a non-technical person and I was searching for a way to explain that computer programming entails far - FAR - more than just learning a programing language and I came up with the best analogy I've thought of so far.
You have three people. One is Spanish, one is Russian, and one is American and they are all three fluent in their native languages. Each of these people aspire to being an author.
Being fluent in a language does not mean you know how to write. Writing, good writing, is about far more than being able to put words together to make grammatically correct sentences. Writing is an art you must learn and constantly refine.
So it is which computer programming and all the ancillary processes which it entails.


text:
Q: How to implement find text mechanism in JTextPane? I want to implement Find mechanism (like text editors or word) in my JTextPane.
I want it to have next / previous options (up/down arrows) and highlighting to all the words it found.
Is there a simple way to do so?

A: There's a JFindReplace tool. You can disable replace and just have find. Apart from that I don't know how good it is.
Link: http://www.javalobby.org/java/forums/t19015.html

A: I am not an expert, I found the following code working:-
    public static void GetTextToFindAndFind(String textToFind, int ignorecase, int findCounter){
    // findCounter = 0 or 1. 0 represents find and 1 represents findCounter.
    String Current2 = textPane.getText();
    if(findCounter ==0){

        if(textToFind == null){
            optionPane.showMessageDialog(null, "Please Enter Text.", "Error", 0);
        }
        else if(textToFind.isEmpty()){
            optionPane.showMessageDialog(null, "Please Enter Text.", "Error", 0);
        }
        else{
            // Use any Character. But I a suggest to use a character from an Encrypted file.
            Replacer = "¥";
            CurrentText = textPane.getText();
            if(ignorecase==1){
                CurrentText = CurrentText.toLowerCase();
                textToFind = TextToFind.toLowerCase();
            }
            int counter = 0;
            readtext = new StringReader(CurrentText);
            readBuffer = new BufferedReader(readtext);
            try {
                String Line = readBuffer.readLine();
                int found = 0;
                while(Line!=null || found != 1){
                    if(Line.contains(TextToFind)){
                        Line = null;
                        found = 1;
                    }
                    if(Line!=null){
                        Line = readBuffer.readLine();
                        counter = counter + 1;
                    }
                }
                if(found == 1){
                    textPane.setSelectionStart(CurrentText.indexOf(textToFind) - counter);
                    textPane.setSelectionEnd(CurrentText.indexOf(textToFind) + textToFind.length() - counter);
                    int counter2 = 1;
                    while(counter2!=textToFind.length()){
                        Replacer = Replacer + "¥";
                        counter2 = counter2 + 1;
                    }
                    CurrentText = CurrentText.replaceFirst(textToFind, Replacer);
                    findCounter = 1;
                            }
                else{
                    optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
                    }

                }
                catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  catch(NullPointerException e){
                optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
            }
            }
        }

    else{
        int counter = 0;
        readtext = new StringReader(CurrentText);
        readBuffer = new BufferedReader(readtext);
        try {
            String Line = readBuffer.readLine();
            int found = 0;
            while(Line!=null || found != 1){
                if(Line.contains(textToFind)){
                    Line = null;
                    found = 1;
                }
                if(Line!=null){
                    Line = readBuffer.readLine();
                    counter = counter + 1;
                }
            }
            if(found == 1){
                textPane.setSelectionStart(CurrentText.indexOf(textToFind) - counter);
                textPane.setSelectionEnd(CurrentText.indexOf(textToFind) + textToFind.length() - counter);
                CurrentText = CurrentText.replaceFirst(textToFind, Replacer);
                        }
            else{
                optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
                }
            }
             catch(IOException e){
                e.printStackTrace();
            } catch(NullPointerException e){
                optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
                }
            }
    }


text:
Q: Artificial intelligence application development in PHP I am new to AI development and looking for some guide line to start. I'm a php developer and if any one have experience AI developing in PHP, please help. Prefers AI related libraries and etc...

A: To develop AI applications, PHP seems not to be the best choice. It is a script language intended to create websites etc., not to, e.g., steer a robot. Of course you can use PHP to learn some concepts, but it makes sense to switch as soon as you want to create "serious" applications related to this topic.
To get into the topic, I recommend the Udacity course "Intro to Articial Intelligence", see https://www.udacity.com/course/cs271 - it is absolutly free to take this courses.
AI is not a simple topic, but it is very interesting. Good luck and have fun!


text:
Q: How to implement a State Pattern for Blazor pages using multiple components to build a page? I have a Blazor page that utilizes multiple components within it - how can I implement a State pattern (ideally per-page) that would be able to handle the current state of a page?
Currently I have all of the state and state-manipulation being done on the page (and via injected Services), but I imagine it would be cleaner to implement a state pattern where each page has some kind of State object which then allows you to manipulate the page and its components in a strict manner.
Ideally the State object would implement INotifyPropertyChanged and be able to dynamically have its State updated, but I also don't hate the idea of having the State object relegate State-manipulation to methods on the object to make sure state isn't just 1-off updated on the Blazor page.
I've already tried to implement some kind of MVVM pattern, but that turned into more questions than answers.
I started to create a State object for the current page being worked on, but I'm not sure if I should basically just be putting most of the logic that was on the Blazor page in the State object, or if I should still have some data, but delegating the heavy lifting to the State.
eg: I have some code that used to be in the "OnAfterRenderAsync" function on the Blazor page, but I'm in the process of moving basically everything in there to a "LoadMatterDetails()" function in the State object that is handling that. Does this make sense, or should I only really have object State in the state object, and writing to & reading from the State object when particular pieces of information are available?
public class MatterDetailsState : IMatterDetailsState
{
    private readonly IMatterDetailsService matterDetailsService;
    private readonly NavigationManager navigationManager;

    public bool EditMode { get; private set; } = false;
    public int EditMatterId { get; private set; } = 0;
    public Matter Matter { get; set; } = new();
    public MatterPaymentOptionDetails PaymentDetails { get; set; } = new();

    public List<MatterStatus> MatterStatuses { get; private set; } = new();

    public MatterDetailsState(
        IAppState appState,
        IMatterDetailsService matterDetailsService,
        NavigationManager navigationManager)
    {
        this.matterDetailsService = matterDetailsService;
        this.navigationManager = navigationManager;
    }

    public async Task LoadMatterDetails()
    {
        // Query Params handling
        var uri = navigationManager.ToAbsoluteUri(navigationManager.Uri);
        var decryptedUri = HelperFunctions.Decrypt(uri.Query);
        var queryParamFound = QueryHelpers.ParseQuery(decryptedUri).TryGetValue("MatterID", out StringValues uriMatterID);

        if (queryParamFound)
        {
            EditMatterId = Convert.ToInt32(uriMatterID);
            EditMode = !String.IsNullOrEmpty(uriMatterID) && EditMatterId > 0;
        }

        await LoadMatterStatuses();

        if (EditMode)
        {
            Matter = await matterDetailsService.GetMatterByIdAsync(EditMatterId);
            PaymentDetails = await matterDetailsService.GetMatterPaymentInfoByMatterId(EditMatterId);
        }
    }

    private async Task LoadMatterStatuses()
    {
        MatterStatuses = await matterDetailsService.GetAvailableMatterStatusesAsync();
    }
}

Basically, should I instead of having more or less the entire function in the State object, or only make the calls like setting Matter & PaymentDetails go through functions in the State object? Not sure what the standard for this is.

A: I've used Fluxor, which is a Flux/Redux library for Blazor, and have liked it. It holds all your state in an object which you can inject into your component for read access. You then manage state by dispatching actions from your components which are processed by effects or reducers which are essentially methods that process the action and make changes to state. It keeps everything neat, separated and very testable in my experience.
https://github.com/mrpmorris/Fluxor

A: There isn't a "standard", but applying good coding practices such as the "Single Responsivity Principle" and Clean Design principles drives you in a certain direction.
I divide the presentation and UI code into three:

*

*UI - components and UI logic

*State - data that you want to track state on.

*Data Management - getting, saving,....

Each represented by one or more objects (Data Management is the ViewModel in MVVM).
You can see an example of this in this answer - https://stackoverflow.com/a/75157903/13065781
The problem is then how do you create a ViewModel instance that is scoped the same as the Form component.  You either:

*

*Scope the VM as transient - you can cascade it in the form if sub components need direct access to it.  This is the approach in the referenced example.

*Create an instance from the IServiceProvider using ActivatorUtilities and deal with the disposal in the form component.
If the VM implements IDisposable/IAsycDisposable the you have to do the second.
The following extension class adds two methods to the IServiceProvider that wrap up this functionality.
public static class ServiceUtilities
{
    public static bool TryGetComponentService<TService>(this IServiceProvider serviceProvider,[NotNullWhen(true)] out TService? service) where TService : class
    {
        service = serviceProvider.GetComponentService<TService>();
        return service != null;
    }

    public static TService? GetComponentService<TService>(this IServiceProvider serviceProvider) where TService : class
    {
        var serviceType = serviceProvider.GetService<TService>()?.GetType();

        if (serviceType is null)
            return ActivatorUtilities.CreateInstance<TService>(serviceProvider);

        return ActivatorUtilities.CreateInstance(serviceProvider, serviceType) as TService;
    }
}

Your form then can look something like this:
public partial class UIForm: UIWrapperBase, IAsyncDisposable
{
    [Inject] protected IServiceProvider ServiceProvider { get; set; } = default!;

    public MyEditorPresenter Presenter { get; set; } = default!;

    private IDisposable? _disposable;

    public override Task SetParametersAsync(ParameterView parameters)
    {
        // overries the base as we need to make sure we set up the Presenter Service before any rendering takes place
        parameters.SetParameterProperties(this);

        if (!initialized)
        {
            // Gets an instance of the Presenter from the Service Provider
            this.Presenter = ServiceProvider.GetComponentService<MyEditorPresenter>() ?? default!;

            if (this.Presenter is null)
                throw new NullReferenceException($"No Presenter could be created.");

            _disposable = this.Presenter as IDisposable;
        }

        return base.SetParametersAsync(ParameterView.Empty);
    }

//....
    public async ValueTask DisposeAsync()
    {
        _disposable?.Dispose();

        if (this.Presenter is IAsyncDisposable asyncDisposable)
            await asyncDisposable.DisposeAsync();
    }
}


text:
Q: How to make polymer serve be accessible on the internet or Lan, instead localhost? I have a Polymer 2 component that I serve locally running
polymer serve

I get the following back:
Files in this directory are available under the following URLs
applications: http://127.0.0.1:8081
reusable components: http://127.0.0.1:8081/components/component-name/

That works very well; as expected I am able to open a local URL and view the component on Chrome.
I need to test this component on an Android Device, the best way it would be (please correct me if I´m wrong) to make this polymer component available on the internet or my local network.
Any suggestion is appreciated. thanks.

A: When you use the serve command you have some additional parameters. With one of them (-H) you can set the IP you want to be used. So instead of launching the server for your loopback (localhost) IP (the default), you can use your LAN IP (I guess most likely something like 192.169.x.x), or even:
polymer serve -H 0.0.0.0

"0.0.0.0" basically meaning "all IPv4 addresses on the local machine". So now you only need to know your IP in the network you are and that Android device is connected also. So if both of them are connected to the same router you should be able to open in your phone an URL like http://192.168.x.x:8081


text:
Q: Select triggers mouseout/mouseleave event I hide the following div -

        <select>
            <option>OptionA</option>
            <option>OptionB</option>
        </select>

with this code -
$("#testDIV").mouseleave(function () {
            $(this).animate({ 'opacity': 0 }, 500, function () { $(this).remove(); });
        });

If user select an option the mouseleave also triggers...
How can I disable the mouseout/mouseleave events when user select an option.

A: Is this what you need?

var $div = $("#testDIV");

function mLeave(e){
  $div.animate({ 'opacity': 0 }, 500, function () { $div.remove(); });
}
$div.on('mouseleave', mLeave );

$("#testDIV select").click(function () {
  $div.off('mouseleave', mLeave );
})

        <select>
            <option>OptionA</option>
            <option>OptionB</option>
        </select>

A: So it should only remove the html when the user has selected the option A or B?
Maybe add an default "Please select" and check the value first. If nothing has been chosen than don't remove the html.
HTML

<select>
  <option value="default">Please select</option>
  <option value="A">Option A</option>
  <option value="B">Option B</option>
</select>

jQuery
   var optionVal;

    $("#testDIV").mouseleave(function () {
      if(optionVal != "default"){
        $(this).animate({ 'opacity': 0 }, 500, function () { $(this).remove(); });
      }
    });
    $("#testDIV select").on('click change', function () {
      optionVal = $(this).val();
    });

A: I've put your code in a jsfiddle to test, and on MacOs X, I don't have the issue your having.
I'm specifying the OS, because styling is different on Windows and Mac Os X.
Could it be that your options are going out of your div when the select is open ?
This would explain the behaviour. The mouse would be out of the div when it's selected.
If it's the case, the solution would be to set a height big enough so that the options wouldn't go out of the div.
Hope it helps you.
EDIT:
You can test the target of the event with "this" which is the element attach to the event. If the are different, then you don't trigger the hide function.
$("#testDIV").mouseleave(function (event) {
    if (event.target !== this) return;

    event.stopImmediatePropagation();
    $(this).animate({ 'opacity': 0 }, 500, function () {
    $(this).remove();
  });
});


text:
Q: Exclude column in `dplyr` `mutate_at` while using data in this column I want to rescale all variables (but year and gender) in a df by one specific year, grouped by gender:
set.seed(1)
df <- data.frame(gender = c(rep("m", 5), rep("f", 5)), year = rep(1:5, 2), var_a = 1:10, var_b = 0:9)
df

   gender year var_a var_b
1       m    1     1     0
2       m    2     2     1
3       m    3     3     2
4       m    4     4     3
5       m    5     5     4
6       f    1     6     5
7       f    2     7     6
8       f    3     8     7
9       f    4     9     8
10      f    5    10     9

I can generate what I expect using:
df %>% group_by(gender) %>% mutate(var_a = ifelse(year == 3, 0, var_a - var_a[year == 3])) %>%
  mutate(var_b = ifelse(year == 3, 0, var_b - var_b[year == 3]))

   gender  year var_a var_b
   <fct>  <int> <dbl> <dbl>
 1 m          1    -2    -2
 2 m          2    -1    -1
 3 m          3     0     0
 4 m          4     1     1
 5 m          5     2     2
 6 f          1    -2    -2
 7 f          2    -1    -1
 8 f          3     0     0
 9 f          4     1     1
10 f          5     2     2

However, this is not an option since I have too many columns.
So I tried (with no success):
df %>% group_by(gender) %>% mutate_at(vars(-gender, -year), ifelse(year == 3, 0, var_a - var_a[year == 3]))

Error in ifelse(year == 3, 0, var_a - var_a[year == 3]) :    object
  'year' not found

How can I exclude column names in mutate_at (or an alternative) using vars(-col_name) while still reading the data in those columns?
This is related to this one

A: Use position in mutate_at
library(dplyr)

df %>%
  group_by(gender) %>%
  mutate_at(-c(1, 2), ~ifelse(year == 3, 0, . - .[year == 3]))

#  gender  year var_a var_b
#   <fct>  <int> <dbl> <dbl>
# 1 m          1    -2    -2
# 2 m          2    -1    -1
# 3 m          3     0     0
# 4 m          4     1     1
# 5 m          5     2     2
# 6 f          1    -2    -2
# 7 f          2    -1    -1
# 8 f          3     0     0
# 9 f          4     1     1
#10 f          5     2     2

In case, if you do not know the position of columns beforehand you can first find it
cols <- which(names(df) %in% c("gender", "year"))

df %>%
  group_by(gender) %>%
  mutate_at(-cols, ~ifelse(year == 3, 0, . - .[year == 3]))

Or select columns which starts_with
df %>%
  group_by(gender) %>%
  mutate_at(vars(starts_with("var")), ~ifelse(year == 3, 0, . - .[year == 3]))

A: If you add a ~ before the function you should get the wanted output.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
set.seed(1)
df <- data.frame(gender = c(rep("m", 5),
                            rep("f", 5)),
                 year = rep(1:5, 2), var_a = 1:10, var_b = 0:9)
df
#>    gender year var_a var_b
#> 1       m    1     1     0
#> 2       m    2     2     1
#> 3       m    3     3     2
#> 4       m    4     4     3
#> 5       m    5     5     4
#> 6       f    1     6     5
#> 7       f    2     7     6
#> 8       f    3     8     7
#> 9       f    4     9     8
#> 10      f    5    10     9

df %>%
  group_by(gender) %>%
  mutate_at(vars(-gender, -year),
            ~ifelse(year == 3, 0, . - .[year == 3]))
#> # A tibble: 10 x 4
#> # Groups:   gender [2]
#>    gender  year var_a var_b
#>    <fct>  <int> <dbl> <dbl>
#>  1 m          1    -2    -2
#>  2 m          2    -1    -1
#>  3 m          3     0     0
#>  4 m          4     1     1
#>  5 m          5     2     2
#>  6 f          1    -2    -2
#>  7 f          2    -1    -1
#>  8 f          3     0     0
#>  9 f          4     1     1
#> 10 f          5     2     2

Created on 2019-04-29 by the reprex package (v0.2.1)
EDIT:
In older versions of dplyr you would use funs(), but it is soft deprecated as of dplyr 0.8.0
df %>%
  group_by(gender) %>%
  mutate_at(vars(-gender, -year),
            funs(ifelse(year == 3, 0, . - .[year == 3])))


text:
Q: Binary Tree; Print in increasing order of frequency; C language I'm supposed to use what I know, this is a assignment for class and I'm only up to chapter 7 in the K&R book
what I am trying to do is traverse a already created binary tree (put in lexicographical order) and print the structures in increasing order of their frequency here is my recursive treeprint. my idea to traversing the treeprint recursively is to check the pcount against the treenode count, if they are the same print the node, set its count to -4 so its out of the printing (numcount is out of use right now) so when it gets to either a null pointer or that the p->count equals -4, that should mean the tree has been fully traversed and that we should start over again and increment pcount to check for that frequency. I know something is wrong but I can't figure it out. I'm using a text file called gettysburg, I've included the text as is at the end
 /* treeprint: in-order print of tree p */
  void treeprint(struct tnode *p)
  {

      if(p != NULL) {
          treeprint(p->left);
          if(p->count == -4 || p == NULL){
              pcount++;
              treeprint(pt);
          }
          if(pcount == p->count) {
          printf("%4d %s\n", p->count, p->word);
          p->count = -4;
          numcount++;
      //  treeprint(p->right);
          }
          treeprint(p->right);
      }
  }

here is the declarations and main body:
  #include <stdio.h>
  #include <ctype.h>
  #include <string.h>
  #include <stdlib.h>
  #include "getch.h"
  #define MAXWORD 100

  int numcount = 1;
  int pcount = 1;
  struct tnode * pt;

  typedef struct tnode{
      char *word;
      int count;
      struct tnode *left;
      struct tnode *right;
  }treenode;

  int getword(char *, int);
  struct tnode *addtree(struct tnode *, char *);
  void treeprint(struct tnode *);
  int getch(void);
  void ungetch(int);
  main()
  {
      struct tnode *root;
      struct tnode *sortedtree;
      char word[MAXWORD];

      root = NULL;
      while(getword(word, MAXWORD) != EOF)
          if(isalpha(word[0])){
              root = addtree(root, word);
              pt = root;
          }
  //  sortedtree = treesort(sortedtree, root);
      treeprint(root);
  //  printf("so far so good \n\n");
  //  treeprint(sortedtree);
      printf("numcount = %d\n", numcount);
      return 0;
  }

my addtree function which builds the tree:
  /* addtree: add a node with w, at or below p*/
  struct tnode *addtree(struct tnode *p, char *w)
  {
      int cond;

      if(p == NULL) {
          p = (struct tnode *) malloc(sizeof(struct tnode));
          p->word = strdup(w);
          p->count = 1;
          p->left = p->right = NULL;
      } else if ((cond = strcmp(w, p->word)) == 0)
          p->count++;
      else if (p->count < 0)
          p->left = addtree(p->left, w);
      else
          p->right = addtree(p->right, w);
      return p;
  }

gettysburg text:

Four score and seven years ago our fathers brought forth on this
  continents a new nation, conceived in Liberty, and dedicated to the
  proposition that all men are created equal.  Now we are engaged in a
  great civil war, testing whether that nation or any nation so
  conceived and so dedicated, can long endure. We are met on a great
  battle field of that war. We have come to dedicate a portion of that
  field, as a final resting place for those who here gave their lives
  that that nation might live. It is altogether fitting and proper that
  we should do this.  But, in a larger sense, we can not dedicate we can
  not consecrate  we can not hallow this ground. The brave men, living
  and dead, who struggled here, have consecrated it, far above our poor
  power to add or detract. The world will little note, nor long remember
  what we say here, but it can never forget what they did here. It is
  for us the living, rather, to be dedicated here to the unfinished work
  which they who fought here have thus far so nobly advanced.  It is
  rather for us to be here dedicated to the great task remaining before
  us that from these honored dead we take increased devotion to that
  cause for which they gave the last full measure of devotion that we
  here highly resolve that these dead shall not have died in vain that
  this nation, under God, shall have a new birth of freedom and that
  government of the people, by the people, for the people, shall not
  perish from the earth.

A: part of what's wrong is that you don't mention your approach for ordering them into frequency order.
It would be a lot easier to write a heap structure, traverse the words tree and insert each word:count into the heap, then remove and print the values from the heap.
A heap is a partially ordered tree with the largest value always at the root.  On insert and delete the tree is rebalanced to maintain this property.  There is a really efficient implementation that maps the heap into an array, s.t. root is at offset 1, the left child is at offset 2*root and right child at 2*root + 1.  A heap is a fun structure to write.


text:
Q: TextKit and VoiceOver I've been following the iOS7 Day-by-Day multi-page TextKit tutorial, and ran into an issue with accessibility. The code for the tutorial is here: iOS7 Day-by-Day
The problem is that each of the text views (one per column, two per "page") seems to contain the entire string, and with VoiceOver enabled, every time a column gets the focus, the text is read from the very beginning of the string to the very end, instead of reading the text that is actually visible in a column.
The textviews/columns are created using the new iOS7 method
UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame
                                           textContainer:textContainer];
How can I get VoiceOver to read only the visible text in each column?

A: Sounds like you simply need to determine what text is visible and then pass that to VoiceOver.
To do that, you can use the two possible methods found in this related question and with the range of the visible text, you can then create a substring via something like:
NSString *textToPassToVoiceOver = [[textView.text] rangeOfSubstring:visibleTextRange];

Makes sense?


text:
Q: Displaying shared mailbox calendar from outlook on modern Sharepoint site/page Is there a way to sync/display a Shared mailbox calendar in outlook onto a Sharepoint page?

A: According to my research, there is currently no OOTB web part to display Shared mailbox calendar from Exchange/Outlook on the SharePoint Online page.
Here is a similar post for your reference:

*

*Displaying an Exchange Shared Mailbox Calendar on SharePoint
Online


text:
Q: Uninitialized Constant Error from Ruby EventMachine Chat Server I'm trying to build a chat server in ruby using EventManager. Needless to day, I'm new to Ruby and feeling a little over my head with the current error I am getting, as I have no clue what it means and a search doesn't return anything valuable. Here's some of the logistics-
(ive only implemented LOGIN and REGISTER so I'll only include those..)
user can enter-
REGISTER username password - registers user
LOGIN username password    - logins user
I'm taking in the string of data the user sends, splitting it into an array called msg, and then acting on the data based on msg[0] (as its the command, like REGISTER, LOGIN, etc)
Here is my code, all contained in a single file- chatserver.rb (explanation follows):
require 'rubygems'
require 'eventmachine'

class Server
  attr_accessor :clients, :channels, :userCreds, :userChannels

  def initialize
    @clients     = [] #list of clients connected e.g. [192.168.1.2, 192.168.1.3]
    @users       = {} #list of users 'logged in' e.g. [tom, sam, jerry]
    @channels    = [] #list of channels          e.g. [a, b, c]
    @userCreds   = {} #user credentials hash     e.g. { tom: password1, sam: password2, etc }
    @userChanels = {} #users and their channels  e.g. { tom: a, sam: a, jerry: b }
  end

  def start
    @signature = EventMachine.start_server("127.0.0.1", 3200, Client) do |con|
      con.server = self
    end
  end

  def stop
    EventMachine.stop_server(@signature)

    unless wait_for_connections_and_stop
      EventMachine.add_periodic.timer(1) { wait_for_connections_and_stop }
    end
  end

  # Does the username already exist?
  def has_username?(name)
    @userCreds.has_key?(name)
  end

  # Is the user already logged in?
  def logged_in?(name)
    if @users[name] == 1
      true
    else
      false
    end
  end

  # Did the user enter the correct pwd?
  def correct_pass?(pass)
    if @userCreds[name] == pass
      true
    else
      false
    end
  end

  private

    def wait_for_connections_and_stop
      if @clients.empty?
        EventMachine.stop
        true
      else
        puts "Waiting for #{@clients.size} client(s) to stop"
        false
      end
    end
end

class Connection < EventMachine::Connection
  attr_accessor :server, :name, :msg

  def initialize
    @name = nil
    @msg = []
  end

  # First thing the user sees when they connect to the server.
  def post_init
    send_data("Welcome to the lobby.\nRegister or Login with REGISTER/LOGIN username password\nOr try HELP if you get stuck!")
  end

  # Start parsing incoming data
  def receive_data(data)
    data.strip!
    msg = data.split("") #split data by spaces and throw it in array msg[]
    if data.empty? #the user entered nothing?
      send_data("You didn't type anything! Try HELP.")
      return
    elsif msg[0] == "REGISTER"
      handle_register(msg) #send msg to handle_register method
    else
      hanlde_login(msg)    #send msg to handle_login method
    end
  end

  def unbind
    @server.clients.each { |client| client.send_data("#{@name} has just left") }
    puts("#{@name} has just left")
    @server.clients.delete(self)
  end

  private

    def handle_register(msg)
      if @server.has_username? msg[1] #user trying to register with a name that already exists?
        send_data("That username is already taken! Choose another or login.")
        return
      else
        @name = msg[1] #set name to username
        @userCreds[name] = msg[2] #add username and password to user credentials hash
        send_data("OK")  #send user OK message
      end
    end

end

EventMachine::run do
  s = Server.new
  s.start  #start server
  puts "Server listening"
end

Whew, okay, it's only the beginning, so not that complicated. Since I'm new to Ruby I have a feeling I'm just not declaring variable or using scope correctly. Here's the error output:

chatserver.rb:16:in start': uninitialized constant Server::Client
  (NameError)   from chatserver.rb:110:inblock in '     from
  /Users/meth/.rvm/gems/ruby-1.9.3-p392@rails3tutorial2ndEd/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in
  call'    from
  /Users/meth/.rvm/gems/ruby-1.9.3-p392@rails3tutorial2ndEd/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in
  run_machine'     from
  /Users/meth/.rvm/gems/ruby-1.9.3-p392@rails3tutorial2ndEd/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in
  run'     from chatserver.rb:108:in<\main>'

ignore the slash in main in that last line.
line 108 is the last function- EventMachine::run do etc.
Any help would be appreciated, if I didn't provide enough info just let me know.

A: I would think that when you call EventMachine::start_server you need to give it your Connection class as the handler. Client is not defined anywhere.


text:
Q: Where is the connectionstring stored in an MSAccess app? adp and/or accdb I have an Access 2013 app that has linked tables. During development I have pointed to a dev DB. Now I would like to point the Access app to a production db. Where is the connection information stored and what is the correct way to change it?
If it were a .Net app or web app I would change it in the App.Config or Web.Config. Is there an equivalent in Access?


text:
Q: Access Terrain data more efficiently I'm developing an editor tool for terrains. I want to do some calculation every time the terrain is modified by user.
Currently I get heightmap with these:
TerrainData tData = SketchTerrain.terrainData;
int resolution = tData.heightmapResolution - 1;
float[,] heights = tData.GetHeights(0, 0, resolution, resolution);

And then I have to check every float in the array to see if there are any changes. This works but it's slow and creates garbage and I have to do it in a fraction of a second (like 4 times per second). I also have to do it for splats too. This puts too much pressure on the CPU and results in frame rate drop.
So is there an alternative?


text:
Q: Java development for the web I'm looking to start developing for the web using Java - I have some basic Java knowledge, so that's not a problem, but I'm at a loss when it comes to deciphering the various technologies for use in web applications.
What options are available to me? How do they work? Are there any frameworks similar to Django/Ruby on Rails which I could use to simplify things?
Any links which could help with understanding what's available would be much appreciated.

A: Start with JSP backed by logic in Java classes. Or use servlets.
The advantage of using JSP and Servlets is that you gain knowledge of what all the frameworks do under the hood. And that understanding is crucial to figure out how to do X in that particular framework.
Furthermore, JSP is very easy. You can easily see what you're doing and very easily see it when you mess up the view with business logic.
And quite a lot of frameworks (Struts, Spring MVC) use JSP as their view technology. It's a natural first step in web development using Java.

A: I don't know if there's anything quite as nice as Django for Java, but Spring has a light-weight web framework built on J2EE
http://www.springframework.org/about

A flexible MVC web application
  framework, built on core Spring
  functionality. This framework is
  highly configurable via strategy
  interfaces, and accommodates multiple
  view technologies like JSP, Velocity,
  Tiles, iText, and POI. Note that a
  Spring middle tier can easily be
  combined with a web tier based on any
  other web MVC framework, like Struts,
  WebWork, or Tapestry.

A: Java frameworks come in two basic flavors. One is called the "Action" Framework, the other the "Component" Framework.
Action frameworks specialize on mapping HTTP requests to Java code (actions), and binding HTTP Requests to Java objects. Servlets is the most basic of the Action Frameworks, and is the basic upon all of the others are built.
Struts is the most popular Action framework, but I can't in good conscience recommend it to anyone. Struts 2 and Stripes are more modern, and very similar to each other. Both are light on the configuration and easy to use out of the box, providing very good binding functionality.
Component Frameworks focus on the UI and tend to promote a more event driven architecture based on high level UI components (buttons, list boxes, etc.). The frameworks tend to hide that actual HTTP request from the coder under several layers. They make developing the more advanced UIs much easier. .NET is a component framework for Windows. On Java, the popular component frameworks are JSF (a standard) and Wicket.
As a rule, if you're creating a "web site". that is something more akin to presenting information (like a blog, or a community site), the Action frameworks work better. These sites tend to be simpler, get bookmarked often, require "pretty URLs" etc. This is generally easier to do with an Action framework.
Component frameworks are much better for things like back office applications with lots of UI elements and complicated workflows. You'll find, particularly with tooling, that these style of apps will go together faster using a component framework. But component frameworks have more complicated request workflow, sometimes relying on hidden state, lots of POST actions, etc. Many have "horrible" URLs, and sometimes create pages that are difficult to bookmark.
Both frameworks can be used for both tasks, just some are more suited to the task than others.
None of these frameworks directly address persistence, but many have extension modules or idioms that work tightly with JPA/EJB3 or Hibernate.

A: something like grails ?
there is also the projects from spring

A: You'll need to start with servlets and JSP.  There are many web frameworks in Java and all of them are based on these two technologies.

A: You could try Jboss Seam : http://www.seamframework.org/Documentation/GettingStarted
If you are using Eclipe as your IDE there is good integration via Jboss Tools or you can use the Seam-Gen tool that comes with Seam. This allows you to define a database table (or tables) and with a few easy commands, build an entire runnable web project from it. It's a nice way to get the ball rolling.

A: Your basic java web technology is servlets. Servlets let you write Java code that responds to various HTTP events (doGet, doPost, doPut, etc). They're generally used for controllers in the MVC architecture.
Link: http://java.sun.com/products/servlet/
JSP lets you write HTML with embedded Java instead of the other way around (in servlets). JSP has been extended via JSF to incorporate more recent architectural advances. This is in the same line as PHP and ASP. This is the view portion of the MVC architecture.
Link: http://java.sun.com/developer/technicalArticles/GUI/JavaServerFaces/
A lot of more complex applications utilize Enterprise Java Beans (EJB) for session management, clustering, etc. This isn't a web technology, per se, but you see it go hand-in-hand when dealing with more complex webapps. Alternatives include frameworks such as Spring.
EJB: http://docs.jboss.org/ejb3/app-server/tutorial/
Spring: http://www.springframework.org/
Also, you'll want to familiarize yourself with ORM technology (after servlets and JSP/JSF). The leading ORM framework is currently Hibernate. This lets you map SQL tables to java objects and interact with them accordingly. This is more advanced stuff so save it for when you're trying to get your head around EJB/Spring, etc.
Link: http://www.hibernate.org/
edit: I forgot to define ORM. It stands for Object Relational Mapping/Mapper (whatever version of "Map" you feel like using :)

A: Also Java Server Faces
http://en.wikipedia.org/wiki/Java_Server_Faces

A: This is a very open-ended question.  The short answer is "yes" there are frameworks, libraries and standards to do everything from writing things at the HTTP request level up to content management systems in Java.
You can also use other languages (e.g. Python, Ruby, etc) on the JVM for that matter.
For some of the Java-only technologies, investigate JSP/Servlets, Struts, Struts2 (which is the updated version of Webwork), Spring MVC, Tapestry, web4j, Wicket.
There are other frameworks built on the JVM but use languages other than Java such as Grails.
To get started I would download Eclipse (latest version) and Tomcat.  Create a new web application in Eclipse.    There are guides that can get you started.
Start with learning how JSPs and Servlets work, these are a bit low level and aren't really a framework, but will let you get up and running quickly.  From there investigate and choose your framework.
Spring MVC is pretty easy to get set up and going.  I'm certain there are others.

A: If you already know Ruby On Rails, you can use it with JRuby and deploy to a Java server (like Tomcat) with Warbler.
In pure Java, Wicket has a good approach and is getting quite popular.

A: Before studying those frameworks, why not study first where it all started? Try programming with servlets first, so you could a peek at the core of most of those java web frameworks. It would help you understand J2EE better.

A: J2EE is the standard. You can use this to build apps with Java Server Pages, Servlets and EJBs.
Struts is also a very popular framework that uses JSPs and Servlets. Its a bit tricky to get setup but it is a very good option for mid size sites.
http://en.wikipedia.org/wiki/Struts

A: In general Java is more component-based, i.e. you don't have frameworks that do it all for you (you'll probably have to pick a database access framework yourself, for example). For Data Access I'd recommend Hibernate or iBATIS.
For the front-end there are literally hundreds of frameworks around. Investigate JSF, Wicket, Struts 2, Stripes - whichever one you use depends on your specific needs as they all have different strengths.
And for a business layer I'd recommend the Spring Framework, which is very comprehensive and has a great reference guide / tutorial :)

A: I learned Java in college back when it was in version 1.1.5.  I recently started trying to program for the web, but it didn't make sense until I read Head First Servlets and JSP.  There are way more things involved in web development with Java than I ever realized, and without this book, I would have quit and just used PHP.


text:
Q: Start Jboss with Ant. Command exec doesn't work I try to start JBoss with ant.
When i execute this script :
<target name="start-jboss" >
         <exec executable="${jboss.bin.dir}\run.bat" >
                       <arg line="--configuration=Myserver -b localhost" />
         </exec>

</target>

JBoss is blocking at this step :
 [exec] 15:52:55,373 INFO  [AjpProtocol] Initializing Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009

But when i run the run.bat it works... Its the same when i add spawn="true" in exec.
I think that the problem comes from eclipse...
Thanks

A: To run a batchfile use cmd as executable, something like :
<exec dir"yourworkingdir" executable="cmd" failonerror="true">
<arg line="/c ${jboss.bin.dir}\run.bat --configuration=Myserver -b localhost"/>
</exec>

if arg line=... doesn't work, use arg value=... for every parameter.
EDIT : if you have trouble using the batchfile, why not get rid of using that addtional batchfile and use the java task straightforward as explained here ?


text:
Q: React - make input appear with text selected I have a functional component, that uses hooks.
const [editMode, setEditMode] = useState(false);
...
return (
      ...
     {editMode && <input value="Some value">}
}

When editMode is changed to true  - the input field is appearing and I want it to appear with already selected text inside of it. How can I do this?

A: You can use the useRef hook to create a ref and put it on your input element, and use the useEffect hook to run a function every time editMode changes. If editMode is true, you can invoke the select method on the ref.current element.
Example

const { useState, useRef, useEffect } = React;

function App() {
  const [value, setValue] = useState("Some value");
  const [editMode, setEditMode] = useState(false);
  const ref = useRef();

  useEffect(() => {
    if (editMode) {
      ref.current.select();
    }
  }, [editMode]);

  return (

      <button onClick={() => setEditMode(!editMode)}>Toggle edit</button>

        {editMode && (
          <input
            ref={ref}
            value={value}
            onChange={e => setValue(e.target.value)}
          />
        )}

  );
}

ReactDOM.render(<App />, document.getElementById("root"));


text:
Q: Функция для создания вложенных HTML-блоков Хотелось сделать красивую функцию, чтобы можно было одной "цепочкой" вызовов создать и вернуть вложенные HTML-элементы.
 Вызовы функций получились (и вставки работают как надо), а вот как, в самом конце вызовов, сразу вернуть самый первый созданный элемент - вопрос.
 Получается такой ужОс:

let html = nestHTML('div', 111)('div', 222)('div', 333, 'moo')('div', 444);

test.appendChild( html.bubu.parentNode.parentNode.parentNode );

function nestHTML(tag, textContent, className) {
  let elem = document.createElement(tag);

  elem.textContent = textContent || "";
  elem.className = className || "";

  if( nestHTML.bubu ){
    nestHTML.bubu.appendChild(elem);
    nestHTML.bubu = elem;
  } else {
    nestHTML.bubu = elem;
  }

  return nestHTML;
}
section div {
  border: 2px solid orange;
  padding: 5px;
}

.moo {
  border-color: red;
}

А хотелось бы в главный appendChild передать что-то покороче.
(можно было сделать одну функцию с аргументом-массивом, но тут в том числе и спортивный интерес).

A: Самый простой вариант – сохранить самый первый созданный элемент, например в свойство root:

let html = nestHTML('div', 111)('div', 222)('div', 333, 'moo')('div', 444);
test.appendChild(html.root);

function nestHTML(tag, textContent, className) {
  function nested(tag, textContent, className) {
    let elem = document.createElement(tag);

    elem.textContent = textContent || "";
    elem.className = className || "";

    if (nested.parent) {
      nested.parent.appendChild(elem);
      nested.parent = elem;
    } else {
      nested.parent = elem;
    }

    return nested;
  }
  nested.root = nested(tag, textContent, className).parent;
  return nested;
}
section div {
  border: 2px solid orange;
  padding: 5px;
}

.moo {
  border-color: red;
}


text:
Q: DC/DC split rail converter with coupled inductor I'm trying to build a DC-DC split-rail converter using circuit from this article. My goal is to split 12..14V input voltage into +2.4V and -2.4V. To do that, I choosed LM1501AGR-ADJ IC, calculated the needed inductance value (15 uH) and made the coupled inductor, then built the following circuit:

It works OK, but only when I apply a certain load. When the load is 1K or more, Vout- is about -11V, and Vout+ is -0.2V (input voltage is 12V). Load resistance of 220R or less makes Vout- equal to -2.39V, and Vout+ to 2.36V, which is just fine for my purposes.
I don't like the fact that circuit needs some "dummy" load to work correctly, because it means aditional power consumption. I'm gonna use battery as the power supply, so I whant it to consume as less power as possible. Besides, it looks like a very quick'n'dirty solution. Are there better ways to solve this problem?
To provide some additional information about the circuit, I tried to obtain the inductor's currents waveforms. To do that, I removed C2 and C3 and applied the load resistors 10R, than measured the voltage waveform on them. Here is what I got:

Primary coil

Primary coil - large scale

Secondary coil
By primary coil I mean the coil which is connected directly to IC.

A: This answer is just to summarise up the John D's explanations. The "primary coil" (which is connected directly to IC) must reserve enough energy for the "secondary coil". Since the inductor current is discontinious, it is possible only when the load consuming enough current is applied. Without it the circuit will not work correctly - in my case the output voltages without load were completey different from expected values. So, dummy load in my case is necessary. The other way is to use the circuit with continious current mode.