Hurdle model results interpretation and plotting

Question: I am trying to determine the habitat of a species of dolphin. My data is highly zero-inflated, so I chose hurdle and zero-inflated negative binomial models to analyze it. I used the pscl package in R to run a suite of models with different combinations of the explanatory (environmental) variables. I have selected two models (using AIC, k-fold cross validation, likelihood ratio tests, and AUC), one that models the zero part best and one that models the count part best. These models only retained a few variables and only three ended up being significant. There are two results I'd really like to obtain, but I'm having trouble finding a method to get them. One would be a plot of the results against the original explanatory variables, just the significant ones. I'm new to statistics, so I first tried to plot the fitted responses against the original variables, but it didn't agree with the model results, so I figured that was the wrong way to go about it. The other is the "optimal" values of the significant environmental variables (e.g. dolphins are most often found in waters of x1-x2 meters depth). This is the really important metric, but I can't find anything explaining how to determine this. Does anyone have a method or a resource I can look through to try to get at these things?
Turbidity and chlorophyll a have been binned into low, medium, and high due to instrument issues. I'm not sure if there's a better way to paste in the data, so if there is, please let me know and I'll fix it so it's easier to use.
<code># zero-inflated model:
zeroinfl(formula = sightings ~ temp + salinity + turbidity + dr + calves + depth +chl,
         data = hdata1, dist = "negbin", link = "logit")

Pearson residuals:
     Min       1Q   Median       3Q      Max
-0.94465 -0.48090 -0.37887 -0.01391  9.94491

Count model coefficients (negbin with log link):
             Estimate Std. Error z value Pr(>|z|)
(Intercept) 30.947611  14.123449   2.191   0.0284 *
temp        -0.537494   0.264139  -2.035   0.0419 *
salinity    -0.488792   0.218886  -2.233   0.0255 *
turbidity    0.289667   0.204845   1.414   0.1573
dr           0.008783   0.030695   0.286   0.7748
calves       0.797886   0.266925   2.989   0.0028 **
depth       -0.018132   0.059215  -0.306   0.7595
chl         -0.197840   0.148794  -1.330   0.1836
Log(theta)   0.907219   0.420729   2.156   0.0311 *

Zero-inflation model coefficients (binomial with logit link):
              Estimate Std. Error z value Pr(>|z|)
(Intercept)   21.73311   21.43736   1.014   0.3107
temp          -0.42438    0.39871  -1.064   0.2872
salinity      -0.30755    0.33770  -0.911   0.3624
turbidity      1.00807    0.36828   2.737   0.0062 **
dr             0.05110    0.04615   1.107   0.2682
calves       -17.78058 1147.55001  -0.015   0.9876
depth         -0.20554    0.08252  -2.491   0.0127 *
chl            0.14151    0.25268   0.560   0.5755

Theta = 2.4774
Number of iterations in BFGS optimization: 36
Log-likelihood: -376.5 on 17 Df

# the hurdle model:
hurdle(formula = sightings ~ depth + temp + calves + turbidity,
       data = hdata2, dist = "negbin", link = "logit")

Pearson residuals:
    Min      1Q  Median      3Q     Max
-0.7917 -0.5273 -0.3893  0.1989  6.9482

Count model coefficients (truncated negbin with log link):
            Estimate Std. Error z value Pr(>|z|)
(Intercept) 39.33117   12.31539   3.194   0.0014 **
depth       -0.14725    0.08518  -1.729   0.0839 .
temp        -1.43828    0.45299  -3.175   0.0015 **
calves       0.47433    0.50256   0.944   0.3453
turbidity    0.62601    0.33974   1.843   0.0654 .
Log(theta)   0.53961    0.64078   0.842   0.3997

Zero hurdle model coefficients (binomial with logit link):
             Estimate Std. Error z value Pr(>|z|)
(Intercept)   -6.7758    10.1788  -0.666  0.50561
depth          0.1853     0.0605   3.063  0.00219 **
temp           0.1153     0.3718   0.310  0.75652
calves        17.2969  1474.2424   0.012  0.99064
turbidity      1.1366     0.6058   1.876  0.06063 .

Theta: count = 1.7153
Number of iterations in BFGS optimization: 41
Log-likelihood: -201.7 on 11 Df

# data for the zero-inflated model.
depth   temp    dr  salinity    turbidity   chl sightings   calves
4.7 29.36   2.011850876 28.83987925 1   3   0   0
4.7 29.13   1.900586093 28.63125671 1   2   0   0
3.3 29.01   3.010121079 28.70284166 1   3   0   0
3.9 29.07   2.861992795 28.76710579 1   2   0   0
5.2 29.2    4.583672075 28.6029197  1   2   0   0
5.5 29.6    4.379241797 28.59126789 1   2   3   0
5.6 29.68   4.511140984 28.52428319 1   1   4   0
5.2 29.22   5.302718836 28.73739597 1   2   1   0
3.1 29.9    7.430188607 28.99989079 1   2   0   0
6.8 29.63   5.893449871 28.4416111  1   2   0   0
6.6 29.83   5.987042043 28.65321564 2   2   0   0
7.3 29.61   7.391268916 28.73067284 2   2   0   0
6.6 29.64   8.64153464  28.58743846 2   2   0   0
3.5 30.2    12.07894269 29.01145684 1   2   0   0
3.5 29.49   12.47664456 28.59040281 2   2   0   0
7.6 29.51   10.09069541 28.72418516 2   1   0   0
8   29.56   9.863018878 28.75394812 2   2   6   0
8.5 29.35   9.151127294 28.81283849 2   2   2   0
8.5 29.45   9.13865022  28.7598053  2   2   2   0
8.7 29.63   10.37079927 28.67277598 2   2   0   0
9   29.72   10.35469783 28.73161687 2   2   0   0
6.7 29.87   12.45499002 28.8073637  2   1   0   0
5.1 30.02   12.59796555 28.54818389 2   2   0   0
3.6 30.29   11.83865306 28.46222804 2   2   0   0
8.1 29.82   13.25289048 28.81727466 2   3   0   0
9   29.47   13.28918743 28.90043291 2   2   0   0
8.7 29.29   13.14122345 28.96855549 3   2   0   0
9   29.06   13.0892942  29.23451699 2   1   0   0
8.3 29.16   14.10087042 29.12027592 2   1   2   0
9.5 29.4    13.85489948 29.00210782 2   2   6   1
9.5 29.4    13.55266688 29.0021078  2   2   3   0
9.8 29.4    10.94446353 29.10172937 2   2   0   0
4.6 29.54   8.789362985 28.92481034 2   1   0   0
10  29.69   10.36418006 28.90128052 2   1   0   0
9.5 29.57   11.88796421 28.93989064 2   1   2   0
8.5 29.35   14.47562218 29.0588281  2   1   0   0
10  29.72   10.31256306 28.95605919 2   1   0   0
7.3 29.9    6.742906448 28.82909105 3   1   0   0
5.3 29.89   6.224763251 28.82183531 2   1   0   0
10.5    29.55   8.119615201 28.9915907  3   2   0   0
9.5 29.28   11.04378489 29.10113712 2   2   0   0
8.3 29.28   13.14867431 29.16763054 3   2   0   0
8.5 29.02   13.37031102 29.40620646 2   2   0   0
10  29.25   9.80081831  29.29252644 2   1   4   0
11  29.81   6.219508767 29.02752455 2   1   2   0
11  29.81   5.528110919 29.0275245  2   1   2   0
11  29.81   5.000346763 29.0275245  2   1   1   0
7.8 29.66   3.969359786 28.99186977 2   1   7   1
4   30.03   2.969666548 28.69963259 1   1   0   0
4   30.03   3.04603305  28.6996326  1   1   2   0
4   30.03   3.518844779 28.6996326  1   1   2   0
10  29.7    9.389445598 29.00093723 2   1   0   0
9.5 29.68   12.35980725 29.14512854 3   1   0   0
9.2 29.68886    7.600460524 29.04483    2   1   0   0
11  29.87   5.036949007 28.99164911 2   2   0   0
5.8 29.33   0.857344694 29.15070369 2   2   0   0
11.5    29.34   5.270453212 29.2511809  2   1   0   0
10.5    29.13   7.620376215 29.41252301 2   2   0   0
11  29.11   12.43655259 29.44484927 3   1   0   0
11  29.19   8.003988425 29.34246753 3   1   0   0
11  29.66   3.194525736 29.08453485 2   1   0   0
4.7 29.85   1.07590107  28.871956   2   1   0   0
12  29.74   3.406281332 29.07606789 3   1   0   0
12.6    29.69   4.470762347 29.05327726 2   1   0   0
11.5    29.9    3.410955138 28.98043804 2   1   13  1
11  29.62   9.783137665 29.12836693 3   1   0   0
11  29.6    12.36742671 29.24636957 3   1   0   0
11.5    29.62   8.697637689 29.04891793 3   1   0   0
12.5    29.73   4.633373317 28.96325035 3   1   0   0
6.5 30.08   0.828870815 28.79464769 3   1   0   0
12.5    29.82   3.26276353  28.95562644 3   2   2   0
13  29.58   9.067819425 29.17236731 3   1   0   0
12.5    29.18   9.182096085 29.4553741  3   1   0   0
13.5    29.91351    4.868906575 28.93683    3   1   0   0
8.5 29.73477    3.404373434 29.13679    3   1   0   0
5.5 29.69   4.142661209 29.41040454 3   1   0   0
13.5    29.76791    5.239392512 29.02875    3   1   0   0
13.5    29.94902    6.982683414 28.96435    3   1   5   0
15.5    29.96003    7.400368992 28.99043    3   1   0   0
12.5    29.37   5.766773774 29.23295073 3   1   0   0
4   29.7    2.154222459 29.05385606 1   1   0   0
13.5    30.10941    7.676737927 28.85073    3   1   0   0
14  29.38   7.458393659 31.48782252 3   1   0   0
9.5 29.59   2.774917784 29.07360676 3   1   0   0
1.7 29.64   1.66547717  29.12961848 1   1   0   0
13  29.6    4.654906952 29.12056903 3   1   0   0
14.5    29.68   8.180363812 29.08565885 3   1   0   0
12.5    30.02   5.00907329  28.99431746 3   1   0   0
9.5 29.98   4.356557059 28.97213912 2   1   3   0
7.3 30.11   4.259060003 28.88830059 2   1   1   0
7.8 29.42   4.173517999 29.20261129 2   1   0   0
13  29.49   5.062757777 29.19354435 3   1   0   0
14.5    29.81   8.168807109 29.04734245 3   1   0   0
12.5    29.72   4.491526504 29.08147121 3   1   2   0
7.8 29.79   2.633742228 29.05268089 2   1   3   0
2.6 29.96   1.929356287 28.89206476 1   1   0   0
12.5    29.98   4.34165668  28.99189556 3   1   0   0
13.5    30.05   7.491453522 28.94355434 3   1   0   0
13.5    30.11   7.653779493 28.84895757 3   1   0   0
7.5 30.25   2.791320694 28.82509285 3   1   0   0
6.1 30.17   2.336981796 28.88549773 2   1   2   0
3.5 30.17   2.061542531 28.75464078 1   1   0   0
12  30.03   6.091402123 28.92262233 3   1   0   0
13  29.96   7.351647185 28.9905203  3   1   0   0
10  29.97   4.051074474 28.97152239 3   1   0   0
11.5    29.57   4.088863626 29.22473448 3   2   0   0
8   29.68   4.256975401 29.13191018 2   1   0   0
5.2 29.8    4.586146937 29.05327783 2   2   0   0
12.5    29.84   4.543197975 28.9832718  3   1   0   0
13  29.94   7.833093244 28.96307407 3   1   0   0
12.5    29.89   9.144613493 29.04554093 3   1   0   0
12  30.2    8.075421041 28.84808374 3   1   9   0
12  30.13   3.397139461 28.83056079 3   1   3   0
6   30.41   0.860964384 28.77647084 1   1   0   0
11.5    30.32   4.640321257 28.77074787 2   2   0   0
11  30.04   9.186577221 28.9954599  2   2   0   0
11  30.03   8.697804137 28.89638697 3   2   0   0
13.5    29.89   4.456552268 28.99949653 3   1   0   0
11.5    29.68   8.507109451 29.17158242 2   1   0   0
11  29.62   12.40655521 29.08202989 3   1   0   0
11  29.72   7.546991932 29.10137027 2   1   0   0
11.5    29.94   4.35468665  28.9762505  2   1   3   0
6.1 30.69   1.072825086 28.6061417  2   1   0   0
11  29.99   5.5133099   29.0318527  2   1   0   0
10.5    29.84   6.626526816 29.10181508 2   2   0   0
9.7 29.67   9.042345068 29.13790526 2   2   0   0
11  29.45   8.958467514 29.31071781 3   2   0   0
10.5    29.31   11.25229821 29.31599407 3   1   3   0
10  29.26   12.52833301 29.33979065 3   1   0   0
10  29.44   11.50836371 29.2237962  3   1   0   0
10.5    29.62   9.275779598 29.1747051  2   1   4   0
11.5    29.88   6.387971806 29.05159431 2   1   3   1
3   30.65   2.925534703 28.59700414 1   2   0   0
3   30.65   2.95143391  28.5970041  1   2   0   0
5.2 30.55   3.035058163 28.70080146 2   2   1   0
11  29.93   6.392332943 28.98879354 2   2   0   0
9.5 30.16   10.51055811 28.92416139 2   1   0   0
8.6 30.28   13.13013301 28.81390704 2   1   0   0
10  30.27   8.601104713 28.83939199 2   1   3   0
4.8 31  6.000112942 28.40077275 1   1   0   0
9.5 30.18   8.115770305 28.8729779  2   2   0   0
9.5 30.21   9.750799982 28.83561219 2   2   9   0
7.7 30.03   14.58064239 29.03429269 2   2   0   0
8.2 29.86   8.845254785 29.15575186 2   2   0   0
8.3 29.72   10.3772397  29.24006972 2   2   0   0
9.2 29.28   10.31273195 29.10769452 2   1   0   0
6.3 29.74   12.98825657 29.03644802 3   2   0   0
7.3 29.8    13.91169967 29.06648402 3   2   3   1
3.7 30.7    11.84831414 28.58734126 2   1   0   0
8.7 29.95   13.28521649 29.03606134 3   1   0   0
9   29.71   13.14053493 28.71780474 2   1   0   0
9.7 29.89   12.87993308 29.14437938 3   2   0   0
7.6 30.12   9.455180322 28.84305653 3   2   0   0
4.8 30.64   8.707607728 28.68711376 2   1   0   0
9.5 30.16   10.60603263 28.93722371 3   1   0   0
8.1 29.95   14.57068664 29.02287847 3   2   0   0
7.8 29.81   7.202404567 28.90891816 2   2   0   0
8.5 29.56   9.023794322 29.17772807 1   2   0   0
7.5 29.77   9.574542688 28.8667924  1   2   0   0
3.5 30.3    12.3168118  28.45642915 1   2   0   0
6.7 30.12   9.560253351 28.70551897 2   2   4   0
8.5 30.27   7.490584684 28.79366833 2   2   3   0
8.1 30.15   7.410217507 28.75330851 2   2   0   0
8.1 30.31   7.243489619 28.66573738 2   1   0   0
7   30.36   5.896232688 28.62990971 2   1   0   0
3   30.83   7.729748361 28.14412878 1   1   0   0
5.2 31.15   6.077294196 27.88537887 1   2   10  1
6   31.2    5.74378923  27.89556857 1   2   1   0
6.1 31.21   5.410054727 27.90270428 1   2   1   0
5   30.91   4.553877677 28.07274257 2   2   0   0
3.6 31.2    2.953496489 27.80606412 2   1   0   0
4.6 31.45   2.972738218 27.60899237 1   1   4   0
3.1 31.4    3.647301445 27.56684719 1   1   0   0
4.1 31.53   2.013234743 27.26023996 1   3   0   0
4.5 26.47   1.936861246 32.77   2   3   1   1
1.7 25.65   3.611281423 32.82   1   1   0   0
5.1 26.35   2.76293324  32.8    1   2   2   0
3.8 26.85   2.988773196 32.7    1   1   0   0
5.2 27.01   4.545916234 32.64   1   2   0   0
5.2 27.01   4.553999774 32.63   1   1   1   0
6   26.93   4.790281894 32.7    1   1   0   0
6.1 27.13   4.982764741 32.6    1   1   1   0
5.4 27.08   5.631690158 32.6    1   1   4   0
3.7 24.93   7.930438823 32.64236    1   2   0   0
6.9 27.29   6.170235535 32.58   1   2   1   0
6.8 27.39   5.98615462  32.59   1   1   0   0
7.5 27.43   7.269733065 32.69   1   2   0   0
6.2 27.61   8.869036609 32.61   1   1   0   0
3   27.45   12.3814557  32.75   1   1   0   0
3.3 26.71   12.40168154 32.79   1   2   0   0
7.1 27.14   9.554706483 32.58   1   3   0   0
8.1 26.91   9.059168735 32.62   1   3   0   0
7.4 27.22   10.4331513  32.57   1   1   0   0
8.7 27.13   10.28904374 32.61   1   3   0   0
9.1 27.15   10.45752513 32.59   1   1   2   0
9.1 27.15   10.64100531 32.59   1   1   1   1
9.1 27.24   10.84024546 32.62   1   1   2   1
5.8 27.25   13.66171736 32.64   1   1   0   0
3.4 27.24   12.27719603 32.98   1   2   0   0
2.6 26.42   11.96951493 32.73   1   1   0   0
8   26.82   13.58752573 32.58   1   3   0   0
9.3 26.74   13.25348719 32.66   1   3   4   1
9.3 26.91   13.04072258 32.73   1   3   2   0
9   26.59   13.13052031 32.75   1   3   0   0
9.5 27.05   12.98995003 32.72   1   1   0   0
6.1 27.39   9.33700795  32.76   1   2   0   0
4.7 27.68   8.860754017 32.83   1   2   0   0
9.8 27.16   10.42085676 32.74   1   1   0   0
10.6    27.05   9.0147051   32.82   1   1   0   0
5.5 26.55   6.137115111 32.78708    1   1   0   0
4.7 26.46   3.1810468   32.85   1   1   0   0
8.372993    26.33   5.366827653 32.79   1   3   0   0
8.3 26.11   8.364940423 32.89   1   3   0   0
10.4    26.18   7.576045416 32.82   1   1   0   0
2.3 26.77   0.646188602 32.81   1   1   0   0
4   26.11   2.676012951 32.87   2   1   0   0
9.7 26.06   4.517188945 32.9    1   2   5   0
10.7    26.07   5.482313705 32.89   1   1   15  0
10.9    25.86   7.288018822 32.9    1   3   2   0
8.3 25.49   13.09703714 32.87   1   2   0   0
8.7 25.54   12.54850768 32.75   1   1   5   0
10.4    25.96   8.755025322 32.75   1   1   0   0
10.7    26.14   7.939864687 32.85   1   2   3   1
4.3 26.56   6.031308177 32.77   1   1   0   0
9.4 26.22   10.42148038 32.78   1   1   0   0
8.3 25.73   14.54966766 32.69   1   3   0   0
10.1    26.27   9.066946569 32.96   1   1   0   0
11.2    25.93   12.39996638 32.7806 1   1   0   0
11  26.31   7.5398252   32.75   1   2   0   0
11.2    26.29   6.88134427  32.72   1   3   1   0
9.3 26.28   2.049234294 32.83   1   3   0   0
5   26.48   0.76436598  32.89   1   2   0   0
12.1    26.335  4.477933643 32.76207    1   2   0   0
11.1    25.63   9.643440162 32.77   1   2   0   0
10.9    25.54   12.38104264 32.84   1   2   0   0
11.4    25.78   8.632018256 32.73   1   2   0   0
11.6    25.83   9.159043774 32.86   1   2   0   0
11.9    26.16   7.214526544 32.78   1   1   4   0
10.5    26.51   1.921833117 32.75   1   1   0   0
6.3 26.34   0.826710181 32.89   1   1   0   0
12.3    26.62   5.023862758 32.72   1   2   0   0
12.9    25.91   8.08180253  32.82   1   3   1   0
12.6    26.75   9.118365869 32.8    1   2   0   0
12.6    26.59   6.1223438   32.75   1   1   2   0
12.7    26.7    5.950026524 32.87   1   1   1   0
8.8 26.78   3.522094106 32.86   1   2   0   0
5   26.56   4.305294146 32.82   1   2   0   0
12.8    26.76   4.928382663 32.75   1   2   3   1
13.4    26.72   7.33733834  32.83   1   2   0   0
13.6    25.83   7.392709162 32.87   1   3   0   0
11.8    26.05   5.916364458 32.83   1   2   0   0
2.5 26.12   1.879579704 32.9    1   2   0   0
10.5    26.13   4.004376931 32.75   1   2   5   0
13.4    26.22   7.621839315 32.75   1   2   0   0
13.9    26.3    7.470786139 32.8    1   2   0   0
9.5 26.34   2.635667496 32.89   1   2   0   0
1.5 26.58   1.886167311 33.01   1   2   0   0
7.1 26.35   4.309524603 32.72   1   2   0   0
13.1    26.45   5.832630407 32.84   1   2   0   0
14.4    26.37   8.178365664 32.84   1   2   0   0
11  26.58   3.85694089  32.84   1   1   0   0
3.2 26.54   2.213665632 32.95   1   3   0   0
7.8 25.97   4.26858637  32.81   1   3   0   0
9.5 25.92   4.196378687 32.89   1   3   3   0
12.1    25.99   4.619408132 32.85   1   3   5   0
14.4    25.95   7.92443959  32.82   1   2   0   0
14.1    26.13   8.188787243 32.79   1   2   0   0
13.7    25.99   5.817045957 32.72   2   1   3   0
13.2    26.42   4.975641002 32.82   1   1   0   0
11.3    26.09   4.158203563 32.79   2   1   2   0
11.3    26.09   3.717719323 32.79   2   1   3   0
2.7 26.22   1.926657466 32.93   1   2   0   0
11.3    26.64   3.984972891 32.83   1   2   0   0
11.3    26.64   4.302636245 32.83   1   2   2   0
12  26.26   4.868786075 32.78   1   3   1   0
13.2    26.73   7.33867965  32.81   1   2   1   0
13.3    26.45   7.505326543 32.81   1   2   0   0
13.4    26.36   7.655497249 32.85   1   2   0   0
10  26.84   4.392261535 32.84   1   2   2   0
3.3 27.14   1.635868338 32.98   1   2   0   0
12  26.97   6.059146718 32.86   1   3   0   0
13.1    26.87   7.330404224 32.86   1   2   0   0
11  25.75   2.550645674 32.92   1   3   0   0
13.8    25.62   7.359628796 32.96   1   2   0   0
13.2    25.97   4.204313203 32.87   1   1   3   0
16.1    25.98   3.931741914 33  1   3   1   0
5.5 26.24   4.419553483 32.87   1   1   0   0
11.1    26.16   3.494532097 32.81   1   1   1   0
11.3    26.08   3.625707911 32.86   1   2   3   0
13.4    26.48   6.967947604 32.8    1   1   0   0
13.2    26.55   9.14483713  32.8    1   1   0   0
12.2    26.46   4.128193493 32.94   1   1   0   0
6.2 26.7    0.839726378 33  1   1   0   0
12  26.68   4.989643532 32.98   1   2   0   0
11.2    26.55   8.084378239 32.96   1   3   1   0
12.4    26.65   8.652134914 33  1   1   0   0
10.9    26.34   9.104442941 32.96   1   3   0   0
12.9    25.94   4.473138178 32.9    1   1   0   0
11.7    26.42   9.166145778 32.67   1   1   0   0
11.8    26.51   12.37305389 32.57   1   2   0   0
11.7    26.24   7.332765348 32.92   1   1   0   0
12.2    26.35   4.396652102 32.88   1   1   5   0
12.3    26.12   3.960103363 32.91   1   1   1   0
12.3    26.12   3.525125176 32.91   1   1   1   0
4.3 26.72   0.686421186 32.91   1   1   0   0
11.8    26.51   3.999631548 32.89   1   2   2   1
12  26.56   4.29402447  32.71   3   2   1   0
10.4    27.18   8.676283115 32.84   1   1   1   0
10.2    26.62   9.416393288 32.72   1   2   2   0
9.6 27.48   12.49056063 32.52   1   2   0   0
9.3 26.96   11.37553511 32.61   1   1   1   0
10.8    26.84   6.364116525 32.94   1   2   0   0
4.6 26.97   2.928647782 33.07   1   2   0   0
3.4 26.46   2.841736021 33.03   1   3   0   0
11.5    26.21   6.528943448 32.87   1   2   0   0
9.7 26.47   11.65671968 32.76   1   2   0   0
9.1 26.81   13.13085241 32.71   1   2   0   0
8.9 26.5    10.35085054 32.97   1   1   2   0
10.3    26.24   9.428661525 32.94   1   1   5   0
10.7    26.21   8.711508391 33.05   1   2   7   0
4.5 26.9    5.998816439 33.15   1   2   0   0
10.4    26.83   9.390238203 33.07   1   2   0   0
8.6 26.32   10.99214749 33.01   1   2   2   0
8.5 26.13   14.53967166 32.93   1   2   0   0
9.4 26.91   11.97222959 33.04   1   2   2   0
9.1 26.81   10.69169582 32.99   1   2   2   0
3.9 27.9    8.712436523 33.08   1   3   0   0
6.5 27.21   9.763665166 32.97   1   2   3   0
7.1 27.38   10.13856796 33.06   3   2   7   0
8.7 27.03   13.03044331 33.04   1   2   0   0
8.6 26.71   13.1200947  33.02   1   3   0   0
8.5 26.45   13.11099202 33.16   1   2   0   0
9.8 26.49   13.93612654 33.07   1   1   1   0
9.8 26.72   13.59306787 33.23   1   1   1   0
8.4 26.99   12.59045136 32.94   1   1   2   0
5.9 26.89   11.78406859 33.05   1   2   1   0
2.7 27.92   11.73670573 33.11   1   1   0   0
7.1 27.49   13.89237165 32.97   2   2   0   0
9.2 26.64   11.54959123 33  1   2   2   0
9.5 27.46   10.75675741 33.08   1   1   1   0
8.8 27.15   10.29719857 33.05   1   3   0   0
7.1 27.3    10.36571776 33.18   1   1   0   0
7.9 26.86   9.067479051 32.98   1   3   0   0
6.9 27.35   9.929454709 33.12   1   2   0   0
2.5 28.66   12.40081634 33.1    1   1   0   0
4.2 26.68051    1.999096419 33.20698    1   1   0   0
1.4 26.62   3.658323174 33.13   2   2   0   0
3.7 26.68   2.969692048 33.21   2   2   0   0
4.9 26.54   4.541368702 33.2    1   3   0   0
5.4 26.39   5.654485707 33.34   1   1   3   0
2   27.47   8.003006041 33.14   1   1   0   0
6.9 26.88   6.043154453 33.16   1   3   2   1
6.9 26.85   5.98216496  33.14   1   3   1   0
6.6 26.94   5.985144971 33.24   1   3   0   0
7.6 26.89   7.535159504 33.2    1   1   0   0
7.4 26.72   7.235677019 33.14   1   1   0   0
7.9 27.17   7.212905221 33.21   1   3   1   0
5.5 27.38   9.404652742 33.11   1   2   0   0
3.1 26.93   12.40175438 33.15791    1   1   0   0

# data for the hurdle model.
depth   temp    dr  salinity    turbidity   chl pH  sightings   calves
4.5 26.47   1.936861246 32.77   2   3   7.88    0   0
1.7 25.65   3.611281423 32.82   1   1   7.85    0   0
5.1 26.35   2.76293324  32.8    1   2   7.91    2   0
3.8 26.85   2.988773196 32.7    1   1   7.92    0   0
5.2 27.01   4.545916234 32.64   1   2   7.95    0   0
5.2 27.01   4.553999774 32.63   1   1   8   1   0
6   26.93   4.790281894 32.7    1   1   8.09    0   0
6.1 27.13   4.982764741 32.6    1   1   8.02    1   0
5.4 27.08   5.631690158 32.6    1   1   8.02    4   0
3.7 24.93   7.930438823 32.64236    1   2   7.56    0   0
6.9 27.29   6.170235535 32.58   1   2   8.01    1   0
6.8 27.39   5.98615462  32.59   1   1   8.01    0   0
7.5 27.43   7.269733065 32.69   1   2   8.06    0   0
6.2 27.61   8.869036609 32.61   1   1   8.08    0   0
3   27.45   12.3814557  32.75   1   1   8.12    0   0
3.3 26.71   12.40168154 32.79   1   2   8.15    0   0
7.1 27.14   9.554706483 32.58   1   3   7.96    0   0
8.1 26.91   9.059168735 32.62   1   3   8.04    0   0
7.4 27.22   10.4331513  32.57   1   1   8.14    0   0
8.7 27.13   10.28904374 32.61   1   3   8.08    0   0
9.1 27.15   10.45752513 32.59   1   1   8.04    2   0
9.1 27.15   10.64100531 32.59   1   1   8.04    1   1
9.1 27.24   10.84024546 32.62   1   1   8.08    2   1
5.8 27.25   13.66171736 32.64   1   1   8.13    0   0
3.4 27.24   12.27719603 32.98   1   2   8.08    0   0
2.6 26.42   11.96951493 32.73   1   1   8   0   0
8   26.82   13.58752573 32.58   1   3   8.02    0   0
9.3 26.74   13.25348719 32.66   1   3   7.99    4   1
9.3 26.91   13.04072258 32.73   1   3   8.01    2   0
9   26.59   13.13052031 32.75   1   3   8.02    0   0
9.5 27.05   12.98995003 32.72   1   1   8.11    0   0
6.1 27.39   9.33700795  32.76   1   2   8.1 0   0
4.7 27.68   8.860754017 32.83   1   2   8.06    0   0
9.8 27.16   10.42085676 32.74   1   1   8.02    0   0
10.6    27.05   9.0147051   32.82   1   1   8.09    0   0
5.5 26.55   6.137115111 32.78708    1   1   7.69    0   0
4.7 26.46   3.1810468   32.85   1   1   7.91    0   0
8.372993    26.33   5.366827653 32.79   1   3   7.91    0   0
8.3 26.11   8.364940423 32.89   1   3   7.99    0   0
10.4    26.18   7.576045416 32.82   1   1   8.06    0   0
2.3 26.77   0.646188602 32.81   1   1   8.21    0   0
4   26.11   2.676012951 32.87   2   1   7.09    0   0
9.7 26.06   4.517188945 32.9    1   2   7.53    5   0
10.7    26.07   5.482313705 32.89   1   1   7.59    15  0
10.9    25.86   7.288018822 32.9    1   3   7.7 2   0
8.3 25.49   13.09703714 32.87   1   2   7.58    0   0
8.7 25.54   12.54850768 32.75   1   1   7.77    5   0
10.4    25.96   8.755025322 32.75   1   1   7.72    0   0
10.7    26.14   7.939864687 32.85   1   2   7.92    3   1
4.3 26.56   6.031308177 32.77   1   1   7.86    0   0
9.4 26.22   10.42148038 32.78   1   1   7.93    0   0
8.3 25.73   14.54966766 32.69   1   3   7.71    0   0
10.1    26.27   9.066946569 32.96   1   1   8.14    0   0
11.2    25.93   12.39996638 32.7806 1   1   8.1 0   0
11  26.31   7.5398252   32.75   1   2   8.05    0   0
11.2    26.29   6.88134427  32.72   1   3   8.02    1   0
9.3 26.28   2.049234294 32.83   1   3   8.05    0   0
5   26.48   0.76436598  32.89   1   2   8.04    0   0
12.1    26.335  4.477933643 32.76207    1   2   7.15    0   0
11.1    25.63   9.643440162 32.77   1   2   7.76    0   0
10.9    25.54   12.38104264 32.84   1   2   7.71    0   0
11.4    25.78   8.632018256 32.73   1   2   8.16    0   0
11.6    25.83   9.159043774 32.86   1   2   8.04    0   0
11.9    26.16   7.214526544 32.78   1   1   8.18    4   0
10.5    26.51   1.921833117 32.75   1   1   8.07    0   0
6.3 26.34   0.826710181 32.89   1   1   8.16    0   0
12.3    26.62   5.023862758 32.72   1   2   7.9 0   0
12.9    25.91   8.08180253  32.82   1   3   7.91    1   0
12.6    26.75   9.118365869 32.8    1   2   7.94    0   0
12.6    26.59   6.1223438   32.75   1   1   8.04    2   0
12.7    26.7    5.950026524 32.87   1   1   7.96    1   0
8.8 26.78   3.522094106 32.86   1   2   8.07    0   0
5   26.56   4.305294146 32.82   1   2   8.05    0   0
12.8    26.76   4.928382663 32.75   1   2   8.03    3   1
13.4    26.72   7.33733834  32.83   1   2   8.04    0   0
13.6    25.83   7.392709162 32.87   1   3   7.73    0   0
11.8    26.05   5.916364458 32.83   1   2   8.05    0   0
2.5 26.12   1.879579704 32.9    1   2   7.88    0   0
10.5    26.13   4.004376931 32.75   1   2   7.87    5   0
13.4    26.22   7.621839315 32.75   1   2   7.94    0   0
13.9    26.3    7.470786139 32.8    1   2   8.1 0   0
9.5 26.34   2.635667496 32.89   1   2   8.13    0   0
1.5 26.58   1.886167311 33.01   1   2   8.24    0   0
7.1 26.35   4.309524603 32.72   1   2   8.01    0   0
13.1    26.45   5.832630407 32.84   1   2   7.98    0   0
14.4    26.37   8.178365664 32.84   1   2   8.03    0   0
11  26.58   3.85694089  32.84   1   1   8.1 0   0
3.2 26.54   2.213665632 32.95   1   3   8.1 0   0
7.8 25.97   4.26858637  32.81   1   3   7.94    0   0
9.5 25.92   4.196378687 32.89   1   3   7.98    3   0
12.1    25.99   4.619408132 32.85   1   3   7.93    5   0
14.4    25.95   7.92443959  32.82   1   2   7.99    0   0
14.1    26.13   8.188787243 32.79   1   2   7.88    0   0
13.7    25.99   5.817045957 32.72   2   1   8.03    3   0
13.2    26.42   4.975641002 32.82   1   1   8.16    0   0
11.3    26.09   4.158203563 32.79   2   1   8.03    2   0
11.3    26.09   3.717719323 32.79   2   1   8.03    3   0
2.7 26.22   1.926657466 32.93   1   2   8.04    0   0
11.3    26.64   3.984972891 32.83   1   2   8.02    0   0
11.3    26.64   4.302636245 32.83   1   2   8.02    2   0
12  26.26   4.868786075 32.78   1   3   8.03    1   0
13.2    26.73   7.33867965  32.81   1   2   8.03    1   0
13.3    26.45   7.505326543 32.81   1   2   8.05    0   0
13.4    26.36   7.655497249 32.85   1   2   8.07    0   0
10  26.84   4.392261535 32.84   1   2   8.09    2   0
3.3 27.14   1.635868338 32.98   1   2   8.06    0   0
12  26.97   6.059146718 32.86   1   3   8.07    0   0
13.1    26.87   7.330404224 32.86   1   2   8.05    0   0
11  25.75   2.550645674 32.92   1   3   7.9 0   0
13.8    25.62   7.359628796 32.96   1   2   7.94    0   0
13.2    25.97   4.204313203 32.87   1   1   7.98    3   0
16.1    25.98   3.931741914 33  1   3   8.07    1   0
5.5 26.24   4.419553483 32.87   1   1   7.95    0   0
11.1    26.16   3.494532097 32.81   1   1   7.98    1   0
11.3    26.08   3.625707911 32.86   1   2   8.06    3   0
13.4    26.48   6.967947604 32.8    1   1   8.01    0   0
13.2    26.55   9.14483713  32.8    1   1   8.05    0   0
12.2    26.46   4.128193493 32.94   1   1   8.17    0   0
6.2 26.7    0.839726378 33  1   1   8.18    0   0
12  26.68   4.989643532 32.98   1   2   8.15    0   0
11.2    26.55   8.084378239 32.96   1   3   8.1 1   0
12.4    26.65   8.652134914 33  1   1   8.16    0   0
10.9    26.34   9.104442941 32.96   1   3   8.13    0   0
12.9    25.94   4.473138178 32.9    1   1   7.9 0   0
11.7    26.42   9.166145778 32.67   1   1   7.92    0   0
11.8    26.51   12.37305389 32.57   1   2   7.97    0   0
11.7    26.24   7.332765348 32.92   1   1   8.02    0   0
12.2    26.35   4.396652102 32.88   1   1   8.07    5   0
12.3    26.12   3.960103363 32.91   1   1   8.1 1   0
12.3    26.12   3.525125176 32.91   1   1   8.1 1   0
4.3 26.72   0.686421186 32.91   1   1   8.02    0   0
11.8    26.51   3.999631548 32.89   1   2   8.01    2   1
12  26.56   4.29402447  32.71   3   2   7.91    1   0
10.4    27.18   8.676283115 32.84   1   1   8.04    1   0
10.2    26.62   9.416393288 32.72   1   2   8.01    2   0
9.6 27.48   12.49056063 32.52   1   2   8.05    0   0
9.3 26.96   11.37553511 32.61   1   1   8.14    1   0
10.8    26.84   6.364116525 32.94   1   2   8.14    0   0
4.6 26.97   2.928647782 33.07   1   2   8.09    0   0
3.4 26.46   2.841736021 33.03   1   3   7.72    0   0
11.5    26.21   6.528943448 32.87   1   2   6.71    0   0
9.7 26.47   11.65671968 32.76   1   2   7.65    0   0
9.1 26.81   13.13085241 32.71   1   2   7.73    0   0
8.9 26.5    10.35085054 32.97   1   1   8.01    2   0
10.3    26.24   9.428661525 32.94   1   1   7.86    5   0
10.7    26.21   8.711508391 33.05   1   2   7.88    7   0
4.5 26.9    5.998816439 33.15   1   2   8   0   0
10.4    26.83   9.390238203 33.07   1   2   7.72    0   0
8.6 26.32   10.99214749 33.01   1   2   7.85    2   0
8.5 26.13   14.53967166 32.93   1   2   7.85    0   0
9.4 26.91   11.97222959 33.04   1   2   7.88    2   0
9.1 26.81   10.69169582 32.99   1   2   7.9 2   0
3.9 27.9    8.712436523 33.08   1   3   7.9 0   0
6.5 27.21   9.763665166 32.97   1   2   7.88    3   0
7.1 27.38   10.13856796 33.06   3   2   7.8 7   0
8.7 27.03   13.03044331 33.04   1   2   7.86    0   0
8.6 26.71   13.1200947  33.02   1   3   7.75    0   0
8.5 26.45   13.11099202 33.16   1   2   7.37    0   0
9.8 26.49   13.93612654 33.07   1   1   7.74    1   0
9.8 26.72   13.59306787 33.23   1   1   7.7 1   0
8.4 26.99   12.59045136 32.94   1   1   7.62    2   0
5.9 26.89   11.78406859 33.05   1   2   7.91    1   0
2.7 27.92   11.73670573 33.11   1   1   7.7 0   0
7.1 27.49   13.89237165 32.97   2   2   7.44    0   0
9.2 26.64   11.54959123 33  1   2   6.81    2   0
9.5 27.46   10.75675741 33.08   1   1   7.43    1   0
8.8 27.15   10.29719857 33.05   1   3   7.48    0   0
7.1 27.3    10.36571776 33.18   1   1   7.64    0   0
7.9 26.86   9.067479051 32.98   1   3   7.50461 0   0
6.9 27.35   9.929454709 33.12   1   2   7.55    0   0
2.5 28.66   12.40081634 33.1    1   1   7.56    0   0
4.2 26.68051    1.999096419 33.20698    1   1   7.408918    0   0
1.4 26.62   3.658323174 33.13   2   2   6.98    0   0
3.7 26.68   2.969692048 33.21   2   2   7.42    0   0
4.9 26.54   4.541368702 33.2    1   3   7.56    0   0
5.4 26.39   5.654485707 33.34   1   1   7.72    3   0
2   27.47   8.003006041 33.14   1   1   7.58    0   0
6.9 26.88   6.043154453 33.16   1   3   7.26    2   1
6.9 26.85   5.98216496  33.14   1   3   7.04    1   0
6.6 26.94   5.985144971 33.24   1   3   7.83    0   0
7.6 26.89   7.535159504 33.2    1   1   7.46    0   0
7.4 26.72   7.235677019 33.14   1   1   7.33    0   0
7.9 27.17   7.212905221 33.21   1   3   6.93    1   0
5.5 27.38   9.404652742 33.11   1   2   7.55188 0   0
3.1 26.93   12.40175438 33.15791    1   1   7.554546    0   0
</code>
Comment: This is going to be difficult to answer as posted. Can you paste in tour data and your model output?
Comment: I just added in the data and output.
Comment: Why do you have 2 different datasets for the models?
Comment: @Justine Your questions are not clear. What do you mean by "plot of the results against the original explanatory variables"? And what exactly is  "the "optimal" values of the significant environmental variables"? Define "optimal".
Comment: Data collection was performed over several years by different people and there were equipment problems, so I made different datasets depending on data availability for the different years of the study. I then modeled all combinations of variables for each dataset and the resulting best models ended up being from the analyses of different datasets.
Comment: I want to be able to visualize the modeled relationship between dolphins and environmental variables. I would like a plot that has probability of presence on one axis and depth on the other, for example. And as far as "optimal" goes, I would just like to be able to say that, based on this model, dolphins can be more often found in certain depths or if there's a certain temperature range over which we can expect to find more of them. I'd like these results to be applicable beyond my study system. This is a threatened species and we need a way to predict where they may occur in other locations.
Answer: I have several comments. I'm not sure whether they qualify for an answer but they might help you get a few steps further.
For exploratory displays you can simply use the hurdle idea and generate plots of (a) the binarized response (=0 vs. >0) against the regressors and (b) the truncated subset positive (log-)count response against the regressors. For your <code>hdata1</code> and the regressor <code>depth</code> this yields:
<code>plot(factor(sightings == 0) ~ depth, data = hdata1, main = "Zero")
plot(log(sightings) ~ depth, data = hdata1, subset = sightings > 0,
  main = "Count")
</code>

These show that for the binary zero hurdle a quadratic <code>ploy(depth, 2)</code> would probably fit much better. And for the positive counts no particular relationship pops out. In short, the dolphins have been sighted at medium depths but given that there were sightings the depth does not seem to lead to more or less frequent sightings. (Of course, this is just a marginal plot but the formal models seem to support this.)
You can also try to add fitted regression lines into these plots, e.g., by fixing all regressors at their means (or other typical values) and then varying only the current regressor of interest. But I'm not sure whether this is what you're after.
As for the two data sets and two models, I'm still not convinced how you got to your solution. For you <code>hdata1</code> the <code>zeroinfl()</code> and <code>hurdle()</code> models seem more or less equivalent with the latter being slightly better.
<code>m1 <- zeroinfl(sightings ~ temp + salinity + turbidity + dr + calves +
  depth + chl, data = hdata1, dist = "negbin")
m2 <- hurdle(sightings ~ temp + salinity + turbidity + dr + calves +
  depth + chl, data = hdata1, dist = "negbin")
AIC(m1, m2)
##    df      AIC
## m1 17 786.9758
## m2 17 784.9835
</code>
Note also that there is quasi-separation in the data with respect to the <code>calves</code> variable - hence the large coefficient and the even larger standard error. (For the 14 observations with <code>calves > 0</code> there are no observations with <code>sightings == 0</code>.)
Finally, the two parts of the models may have different regressors. It seems worth exploring this because in your current version many variables are still non-significant. Thus, something like:
<code>m3 <- hurdle(sightings ~ temp + salinity + turbidity + calves |
  poly(depth, 2) + turbidity + calves, data = hdata1, dist = "negbin")
AIC(m3)
## [1] 765.3405
</code>
yields an even better AIC. I didn't check a cross-validation, AUC, etc., though.
Comment: Thanks so much! To get to the two different models, I used AIC, CV, and LR to compare within types of models (zeroinfl, hurdle), then used AUC to compare between types of models. I had thought that AIC wasn't always comparable for different model types, so chose to use a combination of different tests to choose the best one. So, within the set of hurdle models run, those using hdata2 had a better AIC than m2, but CV and LR test favored the zeroinfl run with hdata1. Using only AIC, models run with hdata2 are quite a bit better. Would you suggest giving more weight to AIC than the other two?
Comment: Well, the usual caveats about model selection apply. LR tests can only be applied to nested models and you can create multiple testing problems. AIC and BIC are alternatives then for model selection. CV is particularly useful if the focus is prediction etc. So you need to decide what is most important in your case: significance testing, model selection for explanation, or prediction.
Comment: Thanks for the insight! And thanks again for the answer!


Effective storing of SQL queries in C# Visual Studio projects

Question: I have about 20 (relatively) big queries hardcoded in my C# code that I would like to move somewhere else, as they are now making my code look unmanageable. These SQL queries have in common that they receive a fixed set of parameters (2 parameters to be precise).
I am looking at ways of where to place them in my project and how to manage them, and so I was thinking of creating separate sql files for each query in a folder in which the code would look into, somehow passing these two parameters before actually executing the query.
The question is the following. Are there any standard/efficient ways of performing the above in C#? I really do not like these SQL queries hard-coded in my projects, but I am also mindful that these would be parametrised queries and so I might not be able to achieve the above.
Any guidance or help would be most welcome. In case it helps, I do not have access rights to write stored procedures to solve this situation.
Comment: Keeping them embedded in C# is fine. Or you can keep them in resources, or in external files which get deployed alongside your program. Please just be careful about SQL injection and use bound parameters - do **not** rely on simple string replacement (like Vishnu proposed).
Comment: See this SO question: http://stackoverflow.com/q/576571/5077042
Comment: You can have placeholders for your parameters. After retrieving queryjust use `queryString.Replace("placeholder","yourValue")` for each of your parameters. Make sure your placeholders are unique and will not collide with actual SQL command. Something like `myParameterPlaceholder`
Comment: Thanks, I had already seen this post. Unfortunately, it does not contemplate the possibility of having parametrised SQL queries. Only towards the end it mentions that tweaks could be made at run time when creating a database table, but I am looking at introducing those "tweaks" at compile time.
Answer: Too bad that it has to be a query not stored procedure
If it is not possible to execute stored procedures then you can put the queries in text files and all those text files can be loaded in a resource file. You can access them with "resourceFileName.TextFileName" and please keep the parameters with @ and their names.
you can load the query with
    using System.Resources;
    var resourceManager = new ResourceManager("resourceFileName", Assembly.UnsafeLoadFrom("resourceDll"));
    string myQuery= resourceManager.GetString("TextFileName");


How to delete records from multiple tables in sequelize?

Question: I am trying like :-
In sequelize
sequelize.query("Delete from table1 where id=1;Delete from table2 where id=124;",{
    replacements: {},
    type: sequelizeObj.QueryTypes.DELETE
  })

It throws error like:-
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
But the same syntax is working for selecting the records.
Comment: You're using a delete command to select records? And it works?
Comment: @Jaybird for select there is QueryTypes.SELECT instead of QueryTypes.DELETE.
Answer: If you want to run multiple queries you need to pass multipleStatements: true :
Like this :
sequelize.query("Delete from table1 where id=1;Delete from table2 where id=124;",{
    replacements: {},
    type: sequelizeObj.QueryTypes.DELETE ,

    dialectOptions: {
        multipleStatements: true // <---- HERE
    }
})

Comment: I tried the same adding dialectOptions. now getting error:--

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM user_educations WHERE user_id=3840;DELETE from user_families WHERE u' at line 1


Return JSON instead of XML from web service using Ajax while 'contentType' is 'false'

Question: I made an AJAX call to send an image file to one of my web service (.asmx) methods. Everything's okay, but the problem is that the web service returns XML instead of JSON because I HAVE TO set 'contentType' to 'false', otherwise file can't be sent. (If I set contentType to application/json; charset=utf-8, it returns JSON but I can't do that because I'm sending a file.)
This is my JavaScript:
function setAvatar(imageFile, successCallback) {
var formData = new FormData();
formData.append("UploadedAvatar", imageFile);
$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});

And the web service method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Result SetAvatar()
{
    HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
    Image avatar = Image.FromStream(postedFile.InputStream, true, true);
    avatar = new Bitmap(avatar, new Size(150, 150));
    avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

    return new Result(true, Messages.AvatarSavedSuccessfully);
}

Comment: See my answer [here](https://stackoverflow.com/questions/49961146/webmethod-in-my-webservice-should-return-a-dataset-and-yet-returns-an-array/49961604#49961604). You're trying to return an object but it must be serialized first. You will probably be able to remove contentType after that and go with the default setting.
Comment: @wazz That didn't help me
Comment: See this https://stackoverflow.com/questions/42360139/asp-net-core-return-json-with-status-code, make sure you have `options.RespectBrowserAcceptHeader = true;`, so that the return type is based on the `Accept` header
Answer: Set the Accept header when making the request to expect JSON
$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    headers: { //SET ACCEPT HEADER
        Accept : "application/json; charset=utf-8",
    },
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});

On the server side, using Json.Net you can serialize the result
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SetAvatar() {
    HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
    Image avatar = Image.FromStream(postedFile.InputStream, true, true);
    avatar = new Bitmap(avatar, new Size(150, 150));
    avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);

    var result = new Result(true, Messages.AvatarSavedSuccessfully);
    return JsonConvert.SerializeObject(result);
}

This should allow the response to be in the desired type
Comment: When I add this code, I get ajax error because the result of service method is not JSON
Comment: @AmirHosseinAhmadi what does the result currently look like
Comment: the result is still an XML Document :(
Comment: @AmirHosseinAhmadi even with the latest suggestion on server? Show a snippet of the result. is it XML wrapping JSON?
Comment: The second suggestion returns XML too. :( I'll put an instance in question today
Answer: After beating my head against the wall for many days, I finally figured out the solution which belongs to Ajay, here.
While nothing else has helped me, I used this and it worked perfectly:

Change the return type of your method to void.
And then instead of writing the return statement in your method, you need to do this to return a value:
Context.Response.ContentType = "application/json; charset=utf-8";
Context.Response.Write(new JavaScriptSerializer().Serialize(new YourData()));

After that you can easily get the result using the success event of the Ajax call:
success: function (result) {
    alert(result.Property); // Note: Don't use result.d here
}

Answer: You need to update your .NET code and add options.RespectBrowserAcceptHeader = true
services
    .AddMvc(options => {
        options.RespectBrowserAcceptHeader = true;
    })
    //support application/xml
    .AddXmlDataContractSerializerFormatters()
    //support application/json
    .AddJsonOptions(options => {
        // Force Camel Case to JSON
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });

The dataType: 'json' will automatically add the Accept header as below
"accept":"application/json, text/javascript, */*; q=0.01"

If you specifically want just application/json, then you need to add below to your ajax options
headers: {
  Accept : "application/json; charset=utf-8"
}

Comment: Where should I put that code? In other words, what is 'services' variable?
Comment: See this thread https://learn.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-2.1
Comment: Any feedback on this?


Prove that $f(x) = x^3 -x $ is NOT Injective

Question: Okay, so I know there are plenty of injective/surjective (and thus, bijective) questions out there but I'm still not happy with the rigor of what I have done. So I'd really appreciate some help!
So the question actually asks me to do two things:
(a) give an example of a cubic function that is bijective. Explain why it is bijective.
(b) give an example of a cubic function that is not bijective. Explain why it is not bijective.
So for (a) I'm fairly happy with what I've done (I think):
$$ f: \mathbb R \rightarrow \mathbb R , f(x) = x^3$$
So we know that to prove if a function is bijective, we must prove it is both injective and surjective.
Proof: $f$ is injective
Let: $$x,y \in \mathbb R : f(x) = f(y)$$
$$x^3 = y^3$$            (take cube root of both sides)
$$x=y$$
Proof: $f$ is surjective
Let: $$y \in \mathbb R$$
$$x = \sqrt[3]{y}$$
$$f(x) = (\sqrt[3]{y})^3 = y$$
So I believe that is enough to prove bijectivity for $f(x) = x^3$. Keep in mind I have cut out some of the formalities i.e. invoking definitions and sentences explaining steps to save readers time. This is just 'bare essentials'.
So for (b)
$$f: \mathbb R \rightarrow \mathbb R , f(x) = x^3 - x$$
Now I'm just going to try and prove it is NOT injective, as that should be sufficient to prove it is NOT bijective.
Let:
$$x,y \in \mathbb R : f(x) = f(y)$$
$$x^3 - x = y^3 - y$$
This is about as far as I get. Send help. Thanks everyone.
Comment: @Carl you mean two numbers $x,y$ such that $x\neq y$ but $f(x)=f(y)$
Comment: What happens if $x=0$ or $x=1$?
Comment: To prove that a function $f$ is not injective, you just need to find two different numbers $x$ and $y$ such that $f(x)\not=f(y)$.
Comment: @CarlHeckman as JMoravitz said, you may confuse op...
Comment: Thanks for the help guys, +1's given.
Comment: @JMoravitz : Yes, you're both right! I meant $f(x)=f(y)$.
Answer: Injectivity:
A function $f$ from $X\to Y$ is said to be injective iff the following statement holds true:

for every $x_1,x_2\in X$ if $x_1\neq x_2$ then $f(x_1)\neq f(x_2)$

The negation of this then yields:
A function $f$ from $X\to Y$ is not injective iff there exists $x_1,x_2\in X$ such that $x_1\neq x_2$ but $f(x_1)=f(x_2)$
In the case of the cubic in question, it is an easily factorable polynomial and we can find multiple distinct roots.  $f(x)=x^3-x=x(x^2-1)=x(x+1)(x-1)$
We know that a root of a polynomial is a number $\alpha$ such that $f(\alpha)=0$

 So, $f(1)=f(0)=f(-1)=0$ despite $1,0,-1$ all being distinct unequal numbers in the domain.  This shows that it is not injective, and thus not bijective.

As an aside, one can prove that any odd degree polynomial from $\Bbb R\to \Bbb R$ must be surjective by the fact that polynomials are continuous and the intermediate value theorem.
Comment: This is great. I think it has helped my understanding significantly. So what you're sort of saying is because f(1) and f(-1)  equal 0, there is more than one-to-one mapping to the elements in the co-domain (hence not injective)? So in this case the set might even look like this: {(1,0) , (-1,0)} (just as a way to visualise it)?
Answer: Regarding (a), when you say "take cube root of both sides" you are (at least implicitly) assuming that the function is injective -- if it were not, the cube root would not be a well-defined operation.  Depending on what you are / are not allowed to assume, that could be regarded as a circular argument.
However, there is another approach.  Beginning with the assumption that $x^3=y^3$, you can manipulate the expression as follows:
$$x^3-y^3=0$$
$$(x-y)(x^2+xy+y^2)=0$$
Now if you can find a convincing argument that the second factor, $x^2+xy+y^2$, is always positive for any choice of $x$ and $y$, then it follows that the only way $x^3=y^3$ can be true is if $x=y$.
The factorization $x^3-y^3=(x-y)(x^2+xy+y^2)$, by the way, could also give you some insight into how to handle (b).
Comment: $$x^2+xy+y^2 = {x^2+y^2\over 2} + {1\over 2}(x^2 + 2xy+y^2) = {x^2+y^2\over 2} + {1\over2}(x+y)^2 \ge 0.$$ The only way to get equality is to have $x=0$ and $y=0$, but then $x=y$ in that case as well.
Comment: @CarlHeckman  Yes, I know.  Also $x^2+xy+y^2 = (x + \frac{1}{2}y)^2 + \frac{3}{4}y^2$.  I was intentionally leaving that out to leave the OP something to finish.


How can I "replace" the interface for an object returned from COM to managed code?

Question: I face some weird performance issues and I suspect that they may arise from having a dynamic specified as return type of a COM interface method. Specifically this is how IHTMLDOMChildrenCollection interface ends up in the interop:
[DefaultMember("item")]
[Guid("3050F5AB-98B5-11CF-BB82-00AA00BDCE0B")]
[TypeLibType(4160)]
public interface IHTMLDOMChildrenCollection : IEnumerable
{
    [DispId(-4)]
    [TypeLibFunc(65)]
    IEnumerator GetEnumerator();
    [DispId(0)]
    dynamic item(int index); // HERE is the dynamic

    [DispId(1500)]
    int length { get; }
}

and I suspect that once my code calls item() method then some extra wiring is created which reduces performance in the other code.
The code is organized like this:
var document = (IHTMLDocument)documentBrowser.Document;
var selector = (IDocumentSelector)document;
IHTMLDOMChildrenCollection allElements = selector.querySelectorAll("*");
int length = allElements.length;
for (int index = 0; index < length; index++)
{
    var item = allElements.item(index);
}

This answer states that performance maybe would improve if IHTMLDOMChildrenCollection interface was declared such that item() returned object, not dynamic.
Would it be possible to declare a new interface and somehow convince the CLR to give me an RCW implementing that interface?
I tried the following:
[DefaultMember("item")]
[Guid("3050F5AB-98B5-11CF-BB82-00AA00BDCE0B")]
[TypeLibType(4160)]
public interface IHTMLDOMChildrenCollectionCopy : IEnumerable
{
    [DispId(-4)]
    [TypeLibFunc(65)]
    IEnumerator GetEnumerator();
    [DispId(0)]
    [return: MarshalAs(UnmanagedType.IDispatch)]
    object item(int index); // HERE it's object, not dynamic

    [DispId(1500)]
    int length { get; }
}

and in the code:
IHTMLDOMChildrenCollection allElementsOriginal = selector.querySelectorAll("*");
var unknown = Marshal.GetIUnknownForObject(allElements);
var newElements = (IHTMLDOMChildrenCollectionCopy)Marshal.GetTypedObjectForIUnknown(
   unknown , typeof(IHTMLDOMChildrenCollectionCopy));
int length = newElements.length; // this fails

and it works until the line reading .length is executed. The latter fails with

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

Should this work? What am I doing wrong?
Comment: `dynamic` can certainly impact performance as it creates lots of wrappers on C# side. Try this instead: `[PreserveSig] int Item(int index, [MarshalAs(UnmanagedType.IDispatch)] out object ppItem);`
Comment: `[PreserveSig]` doesn't work for some reasons. However I did "replace" the interface - it had to be declared with `[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]`
Comment: I thought the interface was fully generated (TypeLibType, TypeLibFunc, DefautlMember are rarely used), so I didn't take a closer look at it's definition. It should be InterfaceIsIDual, not pure dispatch, otherwise you will again suffer perf issues (.NET will always use Invoke instead of calling methods directly). [PreserveSig] should work.
Comment: Using InterfaceIsIDual causes AccessViolationException as it was without attribute.
Comment: In this case, .NET calls the methods directly (which is what you want for perf) instead, so it means the definition is incorrect. In fact, it is, the interface binary layout is `get_length` first, then `get__newEnum` and `item` like this: https://pastebin.com/raw/4cnbrCrQ
Comment: Yes, dual works both with and without `PreserveSig` when members are reordered this way: length -> GetEnumerator() -> item()
Comment: This doesn't improve performance at all however.
Answer: Yes, this should work. The missing part was the interface was not decorated with [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
This is complete declaration:
[DefaultMember("item")]
[Guid("3050F5AB-98B5-11CF-BB82-00AA00BDCE0B")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(4160)]
public interface IHTMLDOMChildrenCollectionCopy : IEnumerable
{
   // same members as in the question
}


In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Question: TensorFlow has two ways to evaluate part of graph: Session.run on a list of variables and Tensor.eval.  Is there a difference between these two?
Comment: full namespace `tf.Tensor.eval()` and `tf.Session.run()`, but connected are `tf.Operation.run()` and `tf.Tensor.eval()` as explained in [here](https://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-eval/54296807#54296807)
Answer: If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).
You can make a session the default as follows:
t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:
t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.
Comment: what is the different in the second example? Is it just that you can evaluate to separate operations (or graphs? not sure what the difference is)?
Comment: wait, does your example actually run? I tried: `a = tf.constant(2.0)
b = tf.constant(3.0)
ab = tf.matmul(a, b)`  and I just got complaints from tensorflow that the shapes don't match, i guess more precisely, that the rank must be at least 2.
Comment: @Pinocchio I think the API changed as the original answer is posted 4 years ago. I used `tf.multiply(t, u)` and it worked fine.
Answer: The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:

If t is a Tensor object, t.eval() is shorthand for sess.run(t) (where sess is the current default session. The two following snippets of code are equivalent:
sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)

c = tf.constant(5.0)
with tf.Session():
  print c.eval()

In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run().
I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.
Answer: eval() can not handle the list object
tf.reset_default_graph()

a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
    z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

but Session.run() can
print("grad", sess.run(grad))

correct me if I am wrong
Answer: The most important thing to remember:

The only way to get a constant, variable (any result) from TenorFlow is the session.

Knowing this everything else is easy:

Both tf.Session.run() and tf.Tensor.eval() get results from the session where tf.Tensor.eval() is a shortcut for calling tf.get_default_session().run(t)

I would also outline the method tf.Operation.run() as in here:

After the graph has been launched in a session, an Operation can be executed by passing it to tf.Session.run(). op.run() is a shortcut for calling tf.get_default_session().run(op).
Answer: Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.
!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Answer: In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph.
Now When you pass values to the graph then first you need to create a tensorflow session.
tf.Session()

Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.
Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is
tf.get_default_session().run(values)

You can check that yourself.
At the place of values.eval() run tf.get_default_session().run(values). You must get the same behavior.
what eval is doing is using the default session and then executing run().


Separable ordinary differential equation -- where was my mistake?

Question: I'm attempting to find the general solution of the following:
$$\frac{dy}{dx} =-5\left(\frac{y}{x}\right)$$
The answer is supposed to be (according to an online calculator):
$$y = \frac{e^{5c}}{x^5}$$
Where $c$ is some constant. Here's my work:
$$\frac{dy}{dx} =-5\left(\frac{y}{x}\right)$$
$$-\frac{1}{5y} dy= \frac{1}{x} dx $$
Integrating both sides gets one to:
$$\frac{-\ln(y)}{5} + c_1 = \ln x + c_2$$
$$\frac{-\ln(y)}{5}  = \ln x + c_3$$
$$\ln(y) = -5\ln x - 5c_3$$
$$y = e^{-5\ln x - 5c_3}$$
$$y = \frac{x^{-5}}{e^{5c_3}}$$
$$y = \frac{x^{-5}}{e^{5c}}$$
I seem to have the answer for $\frac{1}{y}$ rather than $y$. Where was my mistake?
Answer: The answers are the same (look at the power of $x$), but with different integration constants.
Comment: @MyGlasses If this was put as a comment, this would pretty much answer the question, which is discouraged: *"Avoid answering questions in comments"*
Comment: This is a comment rather answer. For a person with 5 gold and 43k reps, not suit to have a such answer.
Answer: You have the same answer, you just don't realize it.
$C$ is a generalized constant.  You can do a lot to it, and it is still just a constant --  $C, 2C, C+D, \ln C$ still just a constant.  There is no need to show these operations.  You can just carry the constant along and keep calling it $C.$
$e^{5c} = \frac 1{e^{5c}} = C$
next.
$x^{-5} = \frac 1{x^5}$
Update:
When you have intial conditions...
$\frac {y'}{y} = -\frac {5}{x}\\
\ln y = -5\ln x + C$
Now you could choose to apply the intial conditions and solve for $C$ and sometimes this is the best time to do so.
$y(2) = 1\\
0 = -5\ln 2 + C\\
C = 5\ln 2$
and then carry that along
$\ln y = \ln (x^{-5}) + 5\ln 2\\
y = e^{\ln (x^{-5}) + 5\ln 2}\\
y = e^{\ln (x^{-5})} e^{5\ln 2}\\
y = 32x^{-5}$
Alternatively, you can wait until a later time (the end).
$\ln y = -5\ln x + C\\
y = Cx^{-5}\\
1 = C 2^{-5}\\
C = 2^5$
I usually wait until the end, but sometimes it is easier to do it earlier.
Comment: So does is it not matter if the constant is $C$ or $C^{-1}$ in that case? Because the constant in the solution is in the numerator.
Comment: Correct.  Once you solve for $C$ based on the initial conditions, you will need to keep track.  But, until that time, you can be really lazy.
Comment: In that case, what if $y(2) =1$? My arrangement with the constants won't change the particular solution?
Comment: @sangstar I have added some discussion on initial conditions.
Answer: $$y=\frac{x^{-5}}{e^{5c}}=\frac{e^{-5c}}{x^5}=\frac{e^{5d}}{x^5}$$
where $d=-c$. The solutions are equivalent.


Database error when execute drush migrate:status

Question: I'm trying to do a 'file to media' migration on a d8 installation. Following the readme on the module I have created a custom module and created the two yaml files. After enabling the module and drush ms i get the following error:
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed

The error appears on my local (DDEV) and my production environment. Drush works otherwise. drush sql-cli works.
I think i'm missing something. Do i have to set a database reference somewhere?
Happy to provide additional information when needed, as i'm clueless atm.
Thanks for pointing me in the right direction.
Edit:
output of drush ms -v
Exception trace:
  at myproject/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php:416
 PDO->__construct() at myproject/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php:416
 Drupal\Core\Database\Driver\mysql\Connection::open() at myproject/docroot/core/lib/Drupal/Core/Database/Database.php:374
 Drupal\Core\Database\Database::openConnection() at myproject/docroot/core/lib/Drupal/Core/Database/Database.php:169
 Drupal\Core\Database\Database::getConnection() at myproject/docroot/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php:201
 Drupal\migrate\Plugin\migrate\source\SqlBase->setUpDatabase() at myproject/docroot/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php:154
 Drupal\migrate\Plugin\migrate\source\SqlBase->getDatabase() at myproject/docroot/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php:221
 Drupal\migrate\Plugin\migrate\source\SqlBase->checkRequirements() at myproject/docroot/core/modules/migrate_drupal/src/Plugin/migrate/source/DrupalSqlBase.php:112
 Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase->checkRequirements() at myproject/docroot/modules/contrib/metatag/src/Plugin/migrate/source/d7/MetatagFieldInstanceDeriver.php:69
 Drupal\metatag\Plugin\migrate\source\d7\MetatagFieldInstanceDeriver->getDerivativeDefinitions() at myproject/docroot/core/lib/Drupal/Component/Plugin/Discovery/DerivativeDiscoveryDecorator.php:101
 Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDerivatives() at myproject/docroot/core/lib/Drupal/Component/Plugin/Discovery/DerivativeDiscoveryDecorator.php:87
 Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() at myproject/docroot/core/modules/migrate/src/Plugin/MigrationPluginManager.php:262
 Drupal\migrate\Plugin\MigrationPluginManager->findDefinitions() at myproject/docroot/core/lib/Drupal/Core/Plugin/DefaultPluginManager.php:175
 Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() at myproject/docroot/core/modules/migrate/src/Plugin/MigrationPluginManager.php:109
 Drupal\migrate\Plugin\MigrationPluginManager->createInstances() at myproject/docroot/modules/contrib/migrate_tools/src/Commands/MigrateToolsCommands.php:697
 Drupal\migrate_tools\Commands\MigrateToolsCommands->migrationsList() at myproject/docroot/modules/contrib/migrate_tools/src/Commands/MigrateToolsCommands.php:135
 Drupal\migrate_tools\Commands\MigrateToolsCommands->status() at n/a:n/a
 call_user_func_array() at myproject/vendor/consolidation/annotated-command/src/CommandProcessor.php:257
 Consolidation\AnnotatedCommand\CommandProcessor->runCommandCallback() at myproject/vendor/consolidation/annotated-command/src/CommandProcessor.php:212
 Consolidation\AnnotatedCommand\CommandProcessor->validateRunAndAlter() at myproject/vendor/consolidation/annotated-command/src/CommandProcessor.php:176
 Consolidation\AnnotatedCommand\CommandProcessor->process() at myproject/vendor/consolidation/annotated-command/src/AnnotatedCommand.php:302
 Consolidation\AnnotatedCommand\AnnotatedCommand->execute() at myproject/vendor/symfony/console/Command/Command.php:255
 Symfony\Component\Console\Command\Command->run() at myproject/vendor/symfony/console/Application.php:1005
 Symfony\Component\Console\Application->doRunCommand() at myproject/vendor/symfony/console/Application.php:255
 Symfony\Component\Console\Application->doRun() at myproject/vendor/symfony/console/Application.php:148
 Symfony\Component\Console\Application->run() at myproject/vendor/drush/drush/src/Runtime/Runtime.php:118
 Drush\Runtime\Runtime->doRun() at myproject/vendor/drush/drush/src/Runtime/Runtime.php:49
 Drush\Runtime\Runtime->run() at myproject/vendor/drush/drush/drush.php:72
 require() at myproject/vendor/drush/drush/includes/preflight.inc:18
 drush_main() at phar:///usr/local/bin/drush/bin/drush.php:143
 require() at /usr/local/bin/drush:10

Update2:
I have tried the whole process with a vanilla drupal 8.9.11, some manually created nodes with managed files (image) and all worked like a charm. So there must be something in my project going wrong.
Comment: That indicates a networking/DNS issue on your server. A common cause would be not defining 'localhost' properly ...
Comment: If you uninstall the file to media module and your custom module, does the error still occur?
Comment: I thought so too, but as i tested the migrate module also on the production server (with the same error result) and the fact that drush works otherwise lead me to the assumption it could be something related to the migrate process...
Comment: Try the --uri option to drush to specify the site URL. Check your settings.php and /etc/hosts to make sure your database host name is properly declared.
Comment: @NoSssweat, i have uninstalled file to media and the custom module and the error still appears with the same message.
Comment: Can you show the two YAML files that have been created?
Comment: @StefanKorn Sorry. I missed your "Silvester"-question. I'm updating the post right now, got it finally working.
Answer: This is because it cannot connect to the old database. If you use ddev you have two options:

Create a new instance for the old database.
Import the old database on current instance as a second database.

See more on https://stackoverflow.com/q/49785023/1365264
Answer: I have (finally!) resolved the problem:

Starting from scratch
I had setup a new Thunder distribution with Drupal 9.1.0 (Thunder 6.1.1)
Instead of using the UI-version of migrate-update i did the migration from the d7 source with drush. For this the source database was additionally imported into the ddev-environment.
After this was done, the file to media migration worked without database errors.


Gini Index Formula

Question: I've read many related articles and posts. The more I read, the more I got confused about 'Gini index' and 'Gini Impurity'. I understood the concept but it seems to me that these things are used differently by different people.
ISLR book* (page 326) defines Gini Index as $\sum p_i(1– p_i)$ or $1 - \sum p_i^2$.

However, this (and many other articles) [the Same question has been asked in comments too by Shanu_not answered though] compute Gini by $ p^2+q^2$ formula for Binary classifier.
So, their Gini Impurity [ 1 $-$ Gini Index] is exactly the same as the Gini Index computed as per ISLR  book.
Please let me know what am I missing. I realize that reading concepts after a long break is painful.
*Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani. (2013). An introduction to statistical learning : with applications in R. New York :Springer,
Comment: Apart from looking at the formulas, the words _purity_ and _impurity_ are indicative (so long as they are used carefully). $\sum p_i^2$ is maximal (purity is highest) when there is just one category present and so the sum is the sum of $1^2$ and any number of $0^2$ and so just $1$. $1 - \sum p_i^2$ is minimal in the same case (impurity is lowest).
Comment: $p^2 + q^2$ is clearly not a general recipe, but applies only when there are two categories in play.
Comment: The Gini index formula is the $G$ you defined above. That $p^2 + q^2$ computes somehow purity, it is specific to two classes, and the $1$ from $G$ got removed because it is constant when you compare two nodes in a decision tree. Usually splitting criteria in decision trees use impurity measures: eg Gini index or entropy. An example here: https://stats.stackexchange.com/questions/44382/mathematics-behind-classification-and-regression-trees/44404#44404
Comment: ISLR won't be recognisable by all readers, so please give references in good academic style (authors, date, book title, publishers, place).
Comment: Thanks Nick, done that.
Comment: "the words PURITY and IMPURITY are indicative". I understood this concept. And Obviously, the decision rule is the same both ways [Even for other data sets]. However, as per the book referred 'Gini-Index' is a measure of impurity and as per the article, I mentioned above, ' 1 - Gini-Index' is a measure of impurity [Called Gini Impurity]
Comment: Yeah, I should mention it that p^2 + q ^2 applies only for binary classification.
Answer: Usually, the terms Gini Index and Gini Impurity are used as synonyms. Indeed, when defined as $1-\sum p_i^2 $ it measures impurity - in the sense that it increases with impurity.
To me it looks like the link you gave uses an alternative, rather confusing definition, where they use Gini Index as a measure of purity, and Gini Impurity as 1-Index. This is something I had never seen in the literature, and it does not seem to recur anywhere else (I took a quick tour of links and definitions, and I could not find it anywhere else).
Therefore, I would rather use the definition you can find in Hastie/Tibshirani's book, as it is the most common. Indeed, we can trace that definition it back to Classification And Regression Trees (Breiman, 1984):

4.3.3 The Gini Criterion
  [...]
  In later work the Gini diversity index was adopted. This has the form:
  $$i(t) = \sum_{i\neq j}p(i|t)p(j|t)$$
  and can also be written as $$i(t) = [...] =1-\sum_jp(j|t)^2$$

The original name is therefore Gini (diversity) index, but since it is a measure of impurity you may also call it Gini impurity.
Comment: Thanks for confirming.

Gini Index Formula


Install needed to connect to RabbitMQ from PHP

Question: I have an Ubuntu 12 server running and I need to run some PHP code on it to connect to RabbitMQ(running on another server - Windows) What is required? If I go to the Ubuntu terminal and run: "which amqp" it returns nothing but if I do: "pecl install amqp" I get:"pecl/amqp is already installed and is the same as the released version 1.0.9"
What did I do wrong? How do I install amqp and subsequently the librabbitmq client library?
Thanks
Jack
Answer: From the first page of google search results:
http://blog.webgen.hu/rabbitmq-for-php-on-ubuntu/
They install the full server on ubuntu, but you don't have to use it after the install, and you can always work on streamlining once you get stuff working.
Answer: Amqp is not a command line program, it's a library to access RabbitMQ so which amqp won't give you anything.
If you installed the pecl/amqp extension, then you need to use it in your PHP code.
See http://php.net/manual/en/book.amqp.php
Comment: Thanks for the tip on the "which" - I am new to Linux and PHP so I make mistakes. Ok, is there a way to get all installed extensions so that I can confirm that it installed correctly?

If it is actually installed, can I use "$cnn = new AMQPConnection();" (from http://php.net/manual/en/amqp.examples.php) in my php files?
Answer: There is an AMQP native PHP and a C Library + PHP Module implementation which can be use for connection to RabbitMQ.
The Problem they are both really slow compared to python and C# because they do not use connection pooling.
The PHP implementation is of course the worst.
I worked around the performance issue using Unix Sockets to sent the message to python process(es) writing them to the rabbitmq. Works perfect - approved by load tests
Cheers


What was the first team sport ever invented?

Question: What was the first team sport ever invented?
By team sport I mean:

group of two or more players playing against another group of two or more players
athletic competition involving an agreed upon set of rules and objectives
Comment: war doesn't count?
Answer: Team sport: "Most likely Tsu Chu , which was played in China as early as 3000 BC" - It was similar to soccer.
First sport ever invented
Answer: The Mesoamerican ballgame and its descendants have been played since 1400BCE.
While they may not count directly as team sports, these may also have been competed in by teams:
Ancient Egyptian records indicate organised competition in such things as swimming, wrestling and javelin.
Ancient Chinese records indicate organised competition in gymnastics.
Ancient Persian records indicate organised competition in wrestling and jousting.
Sources to follow


Suppose $f$ analytic in the closed unit disk. Assume $\Re(f) \geq 0$ for all $|z| \leq 1$. Show the Taylor coefficients are $\Re(a_n) \leq 2$.

Question:
Suppose $f$ analytic in the closed unit disk. Assume $\Re(f) \geq 0$ for all $|z| \leq 1$. If the Taylor expansion about the origin is
  $$
f(z) = 1 + a_1 z + a_2 z^2 + \cdots
$$
  then show the Taylor coefficients are $\Re(a_n) \leq 2$.

I've tried directly examining
$$
 2 - a_n
$$
using the fact that
$$
a_n = \frac{1}{2 \pi i} \int_{|s| = 1} \frac{f(s)ds}{s^{n+1}}
$$
and looking at the modulus.
I can also see that the Taylor expansion implies that $f(0)=1$ so there should exists points on the unit circle that contain real parts above and below $1$.
What other factors am I missing?
Comment: Observe that $\frac{f(z)-1}{f(z)+1}$ maps the closed unit disk to itself, and fixes $0$. Schwarz' Lemma immediately gives $|a_{1}|\leq2$
Answer: Note first that \begin{align}
a_n=\frac{1}{2\pi i}\int_{|z|=1} \frac{f(z)}{z^{n+1}}dz=\frac{1}{2\pi}\int_0^{2\pi}f(e^{i\theta })e^{-in\theta }d\theta .\tag{1}
\end{align}
Especially
$$
2=2a_0=\frac{1}{\pi}\int_0^{2\pi} f(e^{i\theta })d\theta $$
and hence we have \begin{align}
2=\frac{1}{\pi}\int_0^{2\pi} \Re (f(e^{i\theta }))d\theta .\tag{2}\end{align}
On the other hand, for $n\ge 1$ we have \begin{align}
0=\frac{1}{2\pi i } \int_{|z|=1}f(z)z^{n-1}dz=\frac{1}{2\pi}\int_0^{2\pi} f(e^{i\theta })e^{in\theta }d\theta .\tag{3}\end{align}
Therefore $(1)+(3)$ yields that $$
a_n=\frac{1}{2\pi}\int_0^{2\pi} f(e^{i\theta })\left(e^{-in\theta }+e^{in\theta }\right)d\theta
=\frac{1}{\pi}\int_0^{2\pi} f(e^{i\theta })\cos n\theta d\theta
$$
and hence \begin{align}
\Re (a_n)=\frac{1}{\pi}\int_0^{2\pi} \Re (f(e^{i\theta }))\cdot \cos n\theta d\theta \tag{4}
\end{align}
Thus we see from (2) and (4) that $$
2-\Re (a_n)=\frac{1}{\pi}\int_0^{2\pi} \Re (f(e^{i\theta }))(1-\cos n\theta) d\theta\ge 0,
$$
since $\Re f\ge 0$.


Most general expression for adjoint operators on C2 vector space

Question: We know the Pauli spin matrices (along with identity matrix) are a basis for the C2 vector space. All of them are self adjoint.
However, since they are a basis for the entire C2 operator space, linear combinations can give rise to operators that are not self adjoint.
What are the conditions on the coefficients of this basis, such that I get the most general self adjoint operator space on C2?
Answer: It is a simple solution that I missed.
On taking a,b,c and d as coefficients, and equating the general operator to its adjoint, one gets the condition that all coefficients must be real.
Hence, any linear combination of the Pauli matrices and the identity with real coefficients is an operator.


Angular 9 - Quando colo o link absoluto de um link interno do meu site ele dá erro

Question: Por exemplo:
Link do Portfólio:  http://www.impactodesigner.com.br/portfolio/
Se eu colar no browser já com um link interno ele dá erro, por exemplo:
http://www.impactodesigner.com.br/portfolio/curriculum
Não sei se na hora do build tenho que fazer algo, estou especificando assim:
ng build --base-href http://www.impactodesigner.com.br/portfolio/
E na metatag no "dist/index.html" ele coloca isso (lembrando que é um subdominio):

<base href="http://www.impactodesigner.com.br/portfolio/">
Answer: As rotas do angular não são reconhecida pelo servidor.
Você precisa configurar corretamente o web.config do servidor, abaixo um exemplo para o IIS.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Angular Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="./index.html" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Comment: vc. quis dizer IIS ou ISS, minha hospedagem é Linux.
Answer: Resolvi o problema com .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on

    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # Rewrite everything else to index.html
    # to allow html5 state links
    RewriteRule ^ index.html [L]
</IfModule>


ArduinoUploader NuGet package

Question: I have downloaded the NuGet package Arduino Uploader (https://www.nuget.org/packages/ArduinoUploader/), and receive the following error when trying to run it using the example on the github page (https://github.com/twinearthsoftware/ArduinoSketchUploader) under the .Net package.
The code is as follows
var upload = new ArduinoSketchUploader(
new ArduinoSketchUploaderOptions()
{
    FileName = @"location of the file",
    PortName = "COM7",
    ArduinoModel = ArduinoModel.Micro
});

upload.UploadSketch();

The error of Exception unhandled occurs on the upload.UploadSketch(); line giving off
ArduinoUploader.ArduinoUploaderException: 'Exception during close of the programmer: 'Object reference not set to an instance of an object.'.'`.

The details copied from Visual Studio are `ArduinoUploader.ArduinoUploaderException
  HResult=0x80131500
  Message=Exception during close of the programmer: 'Object reference not set to an instance of an object.'.
  Source=ArduinoUploader
  StackTrace:
   at ArduinoUploader.BootloaderProgrammers.Protocols.AVR109.Avr109BootloaderProgrammer.Close()
   at ArduinoUploader.ArduinoSketchUploader.UploadSketch(IEnumerable`1 hexFileContents)
   at ArduinoUploader.ArduinoSketchUploader.UploadSketch()
   at arduino_sending_code.Program.Main(String[] args) in C:\Users\User\source\repos\arduino sending code\arduino sending code\Program.cs:line 39

  This exception was originally thrown at this call stack:
    [External Code]
    arduino_sending_code.Program.Main(string[]) in Program.cs

Are there any suggestions to overcome this error?
Answer: The error you recieved is due to a dodgy hex file. You need to find the hex file from temp folder on your computer where the computer places them. Thats the only file which works. Also later on you might face an issue with another error, make sure you have the right programmer on the arduino, the details are avilable under the bootloader column on the ArduinoUploader github page.

ArduinoUploader NuGet package


Rails way to detect mobile or web device

Question: I want to send an email to user to confirm their account. My app have only mobile version so I want to detect case when user will open email and click confirmation button using web browser. In such case I need to display instruction to go to the mobile app. But in case when it's opened by mobile the confirmation button should redirect to the app and confirmed whole account.
Is there any rails way to distinguish between these two cases? I'm using devise for all email mechanism.
Answer: In your controller you can access the request method.
You can create a helper method like this to get the user_agent :
def mobile_device?
  request.user_agent =~ /Mobile|webOS/
end


Where is the Authoritative Name Server Information storing?

Question: Short Version:
Where does host -t ns github.com getting the answers?
Long Version:
In slide 7 of this google slides, for the last two stops: If "x.root-servers.net" do not know the domain, It will ask the "Authoritative Name Server" for it. The problem is Who tell the "Authoritative Name Server" (info, aka IP) back to root servers?
I did read an article related, but I still do not know the answer.
I know the whois lookup will fetch information (including the name servers) for the domain name, is this the way routers get the "Authoritative Name Server" info?
Which server is storing the information of the Authoritative Name Server? A server from the domain name registrar?
Edited:
I don't understand why you (expert) guys vote this as off-topic. I've read (and read it just again) the FAQ of Serverfault and don't think this is off topic. It did say you can ask questions about "Network routing, switches, and firewalls".
I'm not requesting all the education things about the whole dns-loopup routes but only not understand one step - Where the Authoritative server info is saved. If this is not place to ask this, where should I? SO.com?
Edit 2:

Updated the title
Have got the answer from oo: the gTLD Servers hold the data.
Comment: The root servers store the name servers of the TLD zones. The TLD zones store the name servers of the second level zones. And so on. It's a hierarchy.
Comment: I think that it's worth explicitly noting that whois is an entirely separate protocol from dns and plays no part at all in dns lookups. Whois only serves as a means of providing domain name registration metadata (in the context of domain names, it's also used in some other contexts). The data provided by whois is primarily for human consumption as the data is a free-form blob of text.
Answer: Hopefully, this will be a little clearer for you, even though it's a bit wordy.
That part of the slide is slightly incorrect -- the root servers don't ask any other servers for records on your behalf. In that example, all of the heavy lifting is done by Google's 126.96.36.199 server
To better explain this, you first need to know the difference between an authoritative DNS server, and a recursive DNS server.
Authoritative vs. Recursive DNS
An authoritative DNS server will only respond with answers for records which it hosts. If you try to ask an authoritative server for a record which it's not responsible for, it will tell you either "No." (REFUSED) or tell you where to look (NOERROR, and a list of servers in the AUTHORITY section of the DNS packet).
A recursive DNS server (e.g. your Linksys, your ISP, Google's 126.96.36.199, etc), will try to the best of its ability to follow the chain of DNS server referrals until it can get to an authoritative server to get an answer. This is also known as "DNS recursion".
Root Servers and Referrals
The root servers (x.root-servers.net) act as authoritative DNS servers at the top of the DNS tree (.), which tell the requester what is the next DNS server they should look for.
Typically, the root servers will refer you to a gTLD server for the TLD in question (.com, .net, .org, etc).
Domain Registrars and gTLD Servers
When you register a domain, you're required to enter a set of DNS servers (or use your registrar's own).
At the time of domain registration (or an update), your domain registrar sends an update to the respective generic top-level domain servers (or gTLD servers), which are responsible for handing out referrals for the TLD in question (.com, .net, .org, .uk, etc).
The update basically says "Hey, in the future, whenever someone asks about github.com, refer them to ns1.p16.dynect.net, ns2.p16.dynect.net, ns3.p16.dynect.net, and ns4.p16.dynect.net".
The gTLD server holds onto this information until it's changed by the registrar.
The Query: From Root, to gTLD, to Github
When you ask a.root-servers.net for "www.github.com" ("dig www.github.com @a.root-servers.net"), its response is:
"I don't know about github.com specifically, but I can tell you that any of these DNS servers for .com can give you a better answer".
$ dig www.github.com @a.root-servers.net

; <<>> DiG 9.8.3-P1 <<>> www.github.com @a.root-servers.net
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52400
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 13, ADDITIONAL: 14
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;www.github.com.            IN  A

;; AUTHORITY SECTION:
com.            172800  IN  NS  m.gtld-servers.net.
com.            172800  IN  NS  l.gtld-servers.net.
com.            172800  IN  NS  k.gtld-servers.net.
com.            172800  IN  NS  j.gtld-servers.net.
com.            172800  IN  NS  i.gtld-servers.net.
com.            172800  IN  NS  h.gtld-servers.net.
com.            172800  IN  NS  g.gtld-servers.net.
com.            172800  IN  NS  f.gtld-servers.net.
com.            172800  IN  NS  e.gtld-servers.net.
com.            172800  IN  NS  d.gtld-servers.net.
com.            172800  IN  NS  c.gtld-servers.net.
com.            172800  IN  NS  b.gtld-servers.net.
com.            172800  IN  NS  a.gtld-servers.net.

;; ADDITIONAL SECTION:
m.gtld-servers.net. 172800  IN  A   18.104.22.168
l.gtld-servers.net. 172800  IN  A   126.96.36.199
k.gtld-servers.net. 172800  IN  A   184.108.40.206
j.gtld-servers.net. 172800  IN  A   188.8.131.52
i.gtld-servers.net. 172800  IN  A   220.127.116.11
h.gtld-servers.net. 172800  IN  A   126.96.36.199
g.gtld-servers.net. 172800  IN  A   22.214.171.124
f.gtld-servers.net. 172800  IN  A   220.127.116.11
e.gtld-servers.net. 172800  IN  A   188.8.131.52
d.gtld-servers.net. 172800  IN  A   188.8.131.52
c.gtld-servers.net. 172800  IN  A   188.8.131.52
b.gtld-servers.net. 172800  IN  A   22.214.171.124
b.gtld-servers.net. 172800  IN  AAAA    2001:503:231d::2:30
a.gtld-servers.net. 172800  IN  A   188.8.131.52

;; Query time: 17 msec
;; SERVER: 126.96.36.199#53(22.214.171.124)
;; WHEN: Sun Sep 28 05:38:56 2014
;; MSG SIZE  rcvd: 492

So, now you have a list of servers that can tell you about .com domains. Next when you ask one of the gTLD servers you were referred to ("dig www.github.com @a.gtld-servers.net"), its response is:
"I don't know about www.github.com specifically, but I can tell you that any of these servers for github.com can give you a better answer".
$ dig www.github.com @a.gtld-servers.net

; <<>> DiG 9.8.3-P1 <<>> www.github.com @a.gtld-servers.net
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9895
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 4, ADDITIONAL: 4
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;www.github.com.            IN  A

;; AUTHORITY SECTION:
github.com.     172800  IN  NS  ns1.p16.dynect.net.
github.com.     172800  IN  NS  ns3.p16.dynect.net.
github.com.     172800  IN  NS  ns2.p16.dynect.net.
github.com.     172800  IN  NS  ns4.p16.dynect.net.

;; ADDITIONAL SECTION:
ns1.p16.dynect.net. 172800  IN  A   126.96.36.199
ns3.p16.dynect.net. 172800  IN  A   18.104.22.168
ns2.p16.dynect.net. 172800  IN  A   18.104.22.168
ns4.p16.dynect.net. 172800  IN  A   220.127.116.11

;; Query time: 43 msec
;; SERVER: 188.8.131.52#53(18.104.22.168)
;; WHEN: Sun Sep 28 05:40:14 2014
;; MSG SIZE  rcvd: 182

And finally, when you ask one of the designated servers you were referred to ("dig www.github.com @ns1.p20.dynect.net"), its response is:
"Ah yes! I know this one, www.github.com is a nickname for github.com, and github.com has an IP address of 220.127.116.11".
dig www.github.com @ns1.p16.dynect.net

; <<>> DiG 9.8.3-P1 <<>> www.github.com @ns1.p16.dynect.net
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 35620
;; flags: qr aa rd; QUERY: 1, ANSWER: 2, AUTHORITY: 4, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;www.github.com.            IN  A

;; ANSWER SECTION:
www.github.com.     3600    IN  CNAME   github.com.
github.com.     30  IN  A   220.127.116.11

;; AUTHORITY SECTION:
github.com.     86400   IN  NS  ns3.p16.dynect.net.
github.com.     86400   IN  NS  ns1.p16.dynect.net.
github.com.     86400   IN  NS  ns4.p16.dynect.net.
github.com.     86400   IN  NS  ns2.p16.dynect.net.

;; Query time: 25 msec
;; SERVER: 220.127.116.11#53(188.8.131.52)
;; WHEN: Sun Sep 28 05:57:19 2014
;; MSG SIZE  rcvd: 148

Recursive DNS servers are responsible for traversing this chain of referrals until they get an answer to give back to you. This is typically what your ISP's DNS servers do on your behalf.
Your browser (or whatever application you're using), waits until your recursive DNS server does all the heavy lifting and returns a single answer to you. All of this tends to happen in a brief amount of time, measured in milliseconds -- even faster if the recursive DNS server already has the answer in its cache.
Comment: `dig +trace +add example.com` maybe helpful as a single command that shows the chain of delegations.
Comment: Thank you oo, I'm very appreciate for your detailed answer, though I'm not asking the whole steps (I already knew them). So the answer is "The x.gtld-servers.net." is storing the Authoritative Namer Server Info", right? So for a domain like "good.im", the servers "hoppy.iom.com., etc" (got by `dig +trace good.im`) hold the Authoritative Namer Server Information for ever until the Registrar server (the user) send a change request, right?
Comment: @mitnk Yes, that is correct.


u-substitution of indefinite integrals without algebraically manipulating differentials

Question: Take for example $$\int 2x \cos(x^2)dx$$ Its easy to see that this is the result of chain rule. If we take $u=x^2$ then $dx = du/2x$ and then we get $$\int \cos(u)du$$ and it is simple from there.
But this method requires algebraically manipulating the differentials, which I am aware is rigorously proven in nonstandard analysis, but how else would we arrive to this simpler form? That is when we are treating $dx$ just as notation.
My main confusion is how to justify the change of variable of integration when we are not just substituting something in place of $dx$
Answer: There really are no differentials involved here!
I will use a slightly non standard notation: If $f:[a,b]\to\mathbb{R}$ is integrable i simply write $\int_a^b f$ for the Riemann integral of $f$ over $[a,b]$ instead of the more usual "$\int_a^b f(x) dx$". In what follows there will be not a single differential.
The chain rule (for the Riemann integral) says (i.e. here):

Theorem: Let $a,b,c,d \in \mathbb{R}$ with $a<b, c<d$, $g: [a,b] \to [c,d]$ be continuously differentiable (with onesided derivative at the end points) and $f : [c,d] \to \mathbb{R}$ continuous.
Then $$\int_a^b  g^\prime   \cdot (f \circ g) = \int_{g(a)}^{g(b)}f,$$
where $g^\prime$ is the derivative of $g$.

Example: Say we want to calculate the following integral $I$ defined by:
$$ I:= \int_0^{\sqrt{\pi/2}} x \mapsto 2x \cos (x^2).$$
Define $g:[0,\sqrt{\pi/2}]\to [0,\pi/2]$ by $g(x) := x^2$.
Then $g$ is continuously differentiable with derivative $g^\prime :[0,\sqrt{\pi/2}]\to \mathbb{R}$ given by $g^\prime(x) = 2 x$.
Now define $f: [0, \pi/2]\to \mathbb{R}$ by $f(y) := \cos(y)$. Clearly $f$ is continuous.
By definition
$$I = \int_0^{\sqrt{\pi/2}} g^\prime \cdot f \circ g$$
and so using the above theorem and the well known anti-derivative of $y \mapsto \cos(y)$:
$$
I = \int_{g(0)}^{g(\sqrt{\pi/2})}f = \int_{0}^{\pi /2} f = \int_{0}^{\pi /2} y \mapsto \cos (y) = \sin (\pi/2) - \sin (0) = \sin (\pi/2) =1.
$$
Answer: Formally, $u$-substitution is just an integral equivalent of the chain rule:
$$\begin{align*}
\int f(g(x))g'(x) \, \mathrm{d}x &= \int f(u) \, \mathrm{d}u \\
\int_a^b f(g(x))g'(x) \, \mathrm{d}x &= \int_{g(a)}^{g(b)} f(u) \, \mathrm{d}u
\end{align*}$$
provided

$f : [c,d] \to \mathbb{R}$ is continuous
$g : [a,b] \to [c,d]$ is differentiable
$g'$ is Riemann integrable on $[a,b]$

(One can loosen this some, especially in the context of Lebesgue integration, e.g. to $f \in L^1[c,d]$ and $g$ absolutely continuous on $[a,b]$ and strictly increasing being one in my notes, but this is not the main focus here.)
This is a result you can prove, and is typical in analysis classes (where one gets keener on the mild abuse of convention in the indefinite case), but is essentially just application of the chain rule. (Further discussion on these matters here.) The technique of substitution essentially leverages replacing $g(x)$ and $u$.
Answer: You already have answers formally justifying the integration.  But I want to point out that you don't need nonstandard analysis (or anything beyond calculus) to justify manipulating first-order differentials like $ \mathrm d x $ and $ \mathrm d u $.  (Higher-order differentials like $ \mathrm d ^ 2 x $ or $ \mathrm d x \, \mathrm d y $ are a little trickier, but still standard.)
Formally, all that is necessary is that every variable quantity is a differentiable function of a single independent variable, which in this case could be $ x $ (since $ u = x ^ 2 $); but you don't need to specify this, so I'll generically write the independent variable as $ q $.  So $ x = \chi ( q ) $, and $ u = \upsilon ( q ) $, where $ \chi $ and $ \upsilon $ are differentiable functions, but we don't care which functions.  (If $ q $ is $ x $, then they're $ \chi ( q ) = q $ and $ \upsilon ( q ) = q ^ 2 $, but the details don't matter.)  Then $ \mathrm d x $ and $ \mathrm d u $ can be formally defined as the derivatives of these functions.
Now because $ u = x ^ 2 $, we have $ \mathrm d u = 2 x \, \mathrm d x $, which can be formally calculated as $$ \mathrm d u = \upsilon ' ( q ) = ( \chi ^ 2 ) ' ( q ) = 2 \chi ( q ) \chi ' ( q ) = 2 x \, \mathrm d x \text , $$ which is true no matter what the functions $ \chi $ and $ \upsilon $ are (as long as they're differentiable and $ \upsilon = \chi ^ 2 $).  But you really don't want to think about $ \chi $ and $ \upsilon $ (much less $ q $) when doing the calculation; you just know that the differentials are secretly derivatives and so all of the rules for differentiation apply to them.
So knowing that these functions are there behind the scenes, you can manipulate differentials in confidence that your calculations are valid.  This works for integration by substitution, implicit differentiation, solving first-order differential equations, etc.