Can an iPhone have entitlements to get decrypted wifi password info, e.g. to send by bluetooth?

Question: I am looking to design a way to configure wifi setup for a non-apple device, by pairing it via bluetooth with an app on an iPhone.
The iPhone would be one already connected to the target wifi network.  The app would support its own bluetooth connection with the non-apple device
I understand that there are entitlements, like CNCopyCurrentNetworkInfo, but from research it doesn't look like that is enough.  Maybe there are others?  Or is this only possible by being approved to implement HomeKit on the 'target non-apple device'?
The presume path of data is

credential stored in iOS
some entitlement that permits access to unencrypted data
app with entitlement
app security handles data
valid bluetooth pairing of the app
unencrypted password sent via bluetooth
non-apple device uses the network SSID + credential to make its own connection

Thanks for your help or corrections. These existing Q&A do not answer it: 1, 2
Answer: CNCopyCurrentNetworkInfo does not give you the password, even if you jump through all the hoops including users location permission. Theoretically you can only get SSID of the connected network (with location permission from the user)
Best humane way to approach this (as of today) is by asking the user to enter their WiFi SSID/password in a popup and send it to the Bluetooth device. I was not able to find a better way.
If you use something like Blufi, you can :

have BT device scan for available hotspots
display the list of hotspots for the user
have them select the network + enter the password manually
send the credentials to the Bluetooth device

PS. it would be quite spooky if there was a way to read system keychain passwords from an app.
Comment: it did seem a bit creepy, but was thinking that there would be the need to enter info for one's AppleID, which would be a more 'root permission' that enabled others.   Anyway, sounds like there's no real option — unless there is a way for HomeKit to .... do something to support it?


How to override menu Item?

Question: I am using entity_translation module for translating node titles. And with this Translate tab appears on node view like in screenshot.

I am trying to override titles and access permissions for this menu tab and found that its coded in /sites/all/modules/entity_translation/entity_translation.node.inc like below:
/**
 * Node-specific menu alterations.
 */
function entity_translation_node_menu_alter(&$items, $backup) {
  if (isset($backup['node'])) {
    $item = $backup['node'];
    // Preserve the menu router item defined by other modules.
    $callback['page callback'] = $item['page callback'];
    $callback['file'] = $item['file'];
    $callback['module'] = $item['module'];
    $access_arguments = array_merge(array(1, $item['access callback']), $item['access arguments']);
  }
  else {
    $callback = FALSE;
    $access_arguments = array(1);
  }

  $items['node/%node/translate']['page callback'] = 'entity_translation_overview';
  $items['node/%node/translate']['page arguments'] = array('node', 1, $callback);
  $items['node/%node/translate']['access arguments'] = $access_arguments;
  $items['node/%node/translate']['access callback'] = 'entity_translation_node_tab_access';
  $items['node/%node/translate']['file'] = 'entity_translation.admin.inc';
  $items['node/%node/translate']['module'] = 'entity_translation';
}

In my custom module I tried overriding like this:
function my_module_node_menu_alter(&$items, $backup) {
  $items['node/%node/translate']['title'] = "My New Title";
  $items['node/%node/translate']['access callback'] = 'my_module_transaltion_access';

}

function my_module_transaltion_access(){
   // code for my permissions according to user roles.
}

But I am not able to alter this menu item. Please suggest what is right way to do this ?
UPDATE:
function my_module_menu_alter(&$menu,&$items) {

   $items['node/%node/translate']['access callback'] = "my_module_transaltion_access";
}

function my_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {
    case 'menu_alter':

      // Move some of our hook implementations to the end of the list.
      $group = $implementations['my_module'];
      unset($implementations['my_module']);
      $implementations['my_module'] = $group;
      break;
  }
}

Thanks!
Answer: Try hook_menu_alter() to alter the menu,  https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7.
Moreover, entity_translation_node_menu_alter() is not a hook and it is a function called from entity_translation_menu_alter().
Comment: Thanks for your answer, please see updated question. I did with menu_alter as well and entity_translation was having high priority but I made priority of my module high and weight of my module is 1000 but it still does not work.
Answer: function my_module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  global $user;

  foreach ($router_item['page_arguments'] as $key => $argument) {
    if (is_object($argument) && in_array($router_item['page_arguments'][$key]->type, array('link'))) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == 'node/%/translate') {
          if (add condition according to requirement) {
            unset($data['tabs'][0]['output'][$key]);
          }
        }
      }
    }
  }
}

With this code I am able to unset Translate tab according to user roles.
NOTE: "link" is my content type.

How to override menu Item?


How to generalize standard deviation for n-dimensional arrays?

Question: Here is the application: I have a spectrometer and I need to test different lighting setups for it. Each time, I illuminate a fixed set of 9 color references, and I measure them. The spectrometer is sensible to 8 wavelengths. Here are the plots with two different configurations:

Configuration #1

Configuration #2

As you can see, configuration #1 gives less scattered data than configuration #2.
My goal is to choose the configuration where the data are the most scattered, so that it will be easier for me to differentiate the colors.
Thus I need to have a metrics to compare the configuration between them. Something like standard deviation would do, but I do not know how to generalize it to arrays. Is there a better solution?
Thank you for your advices. :)
Comment: Hello, could you simply compute the covariance matrix (whose elements are the covariance of each pair of coordinates) and take a (matrix) square root ?
Comment: "Need metrics to choose the configurations which is the less scattered" is so general and abstract that it invites many possible potentially conflicting answers.  Could you perhaps explain what you mean by "scattered"?
Comment: I have updated my question to be more specific. Is it more clear now? Thanks
Answer: I think you should consider

Normalizing the spectrum vectors so that their 7-entry light intensity vectors are all unit vectors in $L_2$ sense.

Use the angle between each vector pair as a measure of their distance.


Magento Vs Magneto

Question: Lately, i am seeing in Magento stack exchange that, Some question's descriptions are having the following commands with the spelling of Magento and Magneto.

bin/magento
bin/magneto
Comment: There is nothing wrong ... ;)
Answer: This is quite a good question.
Maybe the user does not intentionally do this mistake.
So, we should correct this spelling mistake. Let do it.
Comment: Ok, ill edit that questions, thank you. I just checked this. Now the results are not appearing with bin/magneto. What a fast response dear. Good
Answer: @Teja bhagavan Kollepara its not only about commands ... you fix nearly every "magneto" typo. So keep on ... :P
(I only disagree with some of your removals of "thank you" lines ... it doesnt hurt and saying THX isnt normal today anymore ... so pls keep them.)
Comment: Yes. Thanks for update. Yeah i have understand the way of editing bro. Thanks

Magento Vs Magneto


Lower bounds on the norm of the gradient of a dot product on an $n$-sphere

Question: I'm working with an integral that involves terms of the form $\nabla (x\cdot \omega)$, where $x, \omega \in \mathbb{R}^n$, and $\omega$ is a point on $\mathbb{S}^{n-1}$. That is to say $$ \omega = (\omega_1(\phi_0, \ldots, \phi_{n-2}), \ldots, \omega_n(\phi_0, \ldots, \phi_{n-2})),$$ where $\phi_0 \in [0,2\pi]$ and $\phi_1, \ldots,\phi_{n-2} \in [0,\pi]$ are the usual $n$-dimensional spherical coordinates (i.e. assuming $r = 1$ is fixed). So, for example, in $\mathbb{R}^3$ on $\mathbb{S}^2$ we have $\omega = (\cos\theta \sin\phi, \sin\theta \sin\phi, \cos\phi)$, whereas $\mathbf{x} = (x,y,z)$, meaning
$$\mathbf{x}\cdot \omega = x\cos\theta \sin\phi + y\sin\theta \sin\phi + z\cos\phi.$$
In particular, I have shown that $\nabla_{\phi}(x\cdot \omega) \cdot \nabla_{\phi} e^{(x\cdot \omega)} = \left| \nabla_{\phi}(x\cdot \omega) \right|^2 e^{(x\cdot \omega)}$ from standard multivariable calculus identities, which leads me to (hopefully) conclude the following identity:
$$e^{(x\cdot \omega)} = \left( \frac{\nabla_{\phi} (x\cdot \omega)}{\left| \nabla_{\phi}(x\cdot \omega) \right|^2}  \cdot \nabla_{\phi} \right) e^{(x\cdot \omega)}.$$
However in order to do that I would need to conclude that $\left| \nabla_{\phi}(x\cdot \omega) \right| > 0$, which is where I'm struggling.
I have that $x \neq 0$, and that it is constant with respect to the $\phi_k$ variables. Shouldn't I be able to relate the norm of the gradient to the norm of $x$ somehow? I feel like I'm getting lost in the weeds here, so any help is much appreciated.
Answer: I'm not sure I understand entirely.
In the 3-space case, we have  $\omega_1(\theta, \phi) = \cos \theta \sin \phi$, is that right?
In other words, $\omega_i( \ldots )$ is the $i$th rectangular coordinate of the point whose spherical coordinates are the arguments. So the $\omega_i$ are known functions, and predetermined, right? In particular, you've written out the three of them for $S^2$.
And your hope is that for any fixed vector $x$, and any location $\phi_0$, we have
$$
| \nabla_\phi (x \cdot \omega(\phi)|(\phi_0) > 0,
$$
is that right?
If that's right, then you're having a hard time proving it because it's not true. :(
Look at $x = (0,0,1)$, and $(\theta_0, \phi_0) = (0, 0)$, so that $x$ is a vector pointing to the north pole, and $\omega(\theta_0, \phi_0)$ happens to point in the same direction as $x$. As it happens, in this case $x \cdot \omega(\theta, \phi)$ is easy to compute -- it's just $\omega_3 (\theta, \phi) = \cos \phi$. The gradient of this with respect to $\theta, \phi$ is $(0, \sin \phi)$. Evaluated at $(\theta_0, \phi_0) = (0,0)$, this gives the vector $(0,0)$, whose norm is not, in fact, positive.


T-distribution problem

Question: I am working through the exercises of Martin Sternstein's Statistics (Barron's College Review Series) ... struggling with Exercise 4 in Chapter 14.
Given are the weight lifting strengths of 9 people before/after 8 weeks of weight lifting exercises: Before: 3,3.5,4,6,7,8,8.5,12.5,15. After: 7,17,19,12,19,22,28,20,28.
Asked is to construct the 95% CI a) before training strength, b) after training strength and c) strength gain.
The answers are given at the back of the book as follows: a) 7.5 +- 2.262(4.085/sqrt(9)) b) 19.11 +- 2.262(6.791/sqrt(9)) and c) 11.61 +- 2.262(4.891/sqrt(9)).
My struggles:
a) given n=9, I thought df=8 and looked up 2.5% (due to two-sided) and got critical value of 2.306, but the book's answer uses 2.262 which corresponds to df=9. Anyone know why?
b) I understand both 4.085/sqrt(9) and 6.791/sqrt(9) for a) and b) but not the 4.891/sqrt(9). I had sqrt(4.085^2/9 + 6.79^2/9). Any ideas?
Comment: Please add the [tag:self-study] tag & read its
[wiki](https://stats.stackexchange.com/tags/self-study/info). Then tell us what you understand thus far, what
you've tried & where you're stuck. We'll provide hints to
help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you
is grounds for closing.
Comment: Thank you for the feedback. I have added the self-study tag and read the wiki. And this is not homework. I am 50 year old engineer working in Lean Six Sigma and using the mentioned book to refresh my college knowledge from 25+ years ago.
Comment: Not sure what more I can add to explain what I have done and where I'm stuck. The calculations of the means are fine but the look-up of the critical value is one problem where I was using a different value from the book's answer.
Comment: Second ... calculating the CI of the difference (gain) between after and before, I get the correct central value, but here I also used the df=8 critical value instead of the df=9 which the book uses and for the stdev i was using what i wrote in the last line of the original post whereas the book uses 4.891 which I dont know how they got to.
Comment: 95% CI before: $(4.36, 10.64),$ rounded to two places. After: $( 13.89, 24.33).$ Gain: $( 7.85, 15.37).$ See if you can get similar answers from formulas in your text. // It seems you're right about DF. If the answer book has a mistake, it would certainly not be the first time for such a thing to happen. My answers from R. // If you have trouble, post the specifics of what you tried.// For Gain you have to use a **one-sample** t interval for the nine differences. (Not a 2-sample procedure.) // Quantiles .025 & .075  of T(8) from R are 'qt(c(.025, .975), 8)': $-2.306004  ,  2.306004,$ resp.
Comment: I got standard deviations 4.085034, 6.790516, and 4.891177.
Comment: Thanks Bruce for the replies. Your idea of using R prompted me to use Minitab (silly me ... I not think of it before). And that indeed confirms the df should be 8 and the answer in the book is incorrect.
Comment: The other mistake I made is to interpret the "95% CI for the gain" as a paired t-test, which for the purpose of the 95%CI is not needed. Like you said, the exercise was basically to create 3 one-sample t-tests. Thanks again for your help and response.
Answer: It seems you may still be puzzled by the CI for gain.
You have paired data. You need to start by getting the nine gains, and then
do a one-sample CI using those nine values.
Here is a bit of R code that computes the CI directly
and then again as part of the t.test procedure in R.
g = a-b
g
[1]  4.0 13.5 15.0  6.0 12.0 14.0 19.5  7.5 13.0

mean(g); sd(g)
[1] 11.61111
[1] 4.891177
qt(c(.025,.975),8)
[1] -2.306004  2.306004

CI = mean(d) + qt(c(.025,.975), 8)* sd(g)/3;  CI
[1]  7.85142 15.37080

t.test(g)$conf.int
[1]  7.85142 15.37080
attr(,"conf.level")
[1] 0.95

T-distribution problem


How can I assign a session key with Javascript?

Question: I have a PHP program, called login.
When the user passes something, like email and password, login.php will return a session key to the user, if the login succeeds.
And I have JavaScript code to call this function to do the login.
How can I store this session key to identify whether the user is logged in?
Comment: you cant set a session using javascript... you can do cookie instead but cookies are not secure... but if you want to access the session value you can print $_SESSION['key'] in your js code(if the js code exist in .php file)....
Answer: The session is stored in a cookie by the server.
You don't need to do anything on the client.
Answer: a session is serverside.. not clientside.. so you cant set it through js
Answer: Sessions are declared manually like this:
$_SESSION['user'] = $_POST['username']; // or any other variable

You can then check on the other pages with PHP like this:
if(isset($_SESSION['user'])){

    //do this if true

}


Let $m, n ∈ \mathbb{N}$ such that $2m^{2} + m = 2n^{2} + n$ , then prove that $m-n$ is a perfect square .

Question: After simply factorizing the equation given in the question I got $\mathbf{m + n = -0.5}$
. But the question mentioned $m, n ∈ \mathbb{N}$ . Then how $m + n = -0.5$ ?
Did I do some mistake or is the question wrong?
Comment: There's the second factor. What happens if that is $0$?
Comment: You wrote "factorizing". I suppose you got more than one factor doing that.
Comment: What do u mean by "There's the second factor"
Comment: Oh thanks that second factor gives m = n and solves the question ;)
Comment: How can i end my question ?
Comment: You could write and accept your own answer
Comment: Ok ............
Answer: Yes. $m-n$ is a perfect square.
Just observe that your condition implies that
$$ (m-n)(2m+2n+1)=0$$
Since $m$ and $n$ are natural numbers, we must have $m-n = 0$ which is a perfect square
Comment: Not clear precisely which way you deduced $\,m=n,\,$ but if it is from  $\,m\neq n\Rightarrow\, -2(m+n) = 1\,$ then this proof by parity (divisibility) contradiction generalizes widely - see my answer where I shows how to extend it from the divisor $2$ to $d.\ \ $
Comment: @Bill Dubuque product of two integers is 0 implies that atleast one of them is 0. Since $m$ and $n$ are naturals, $2m+2n+1$ cannot be $0$.
Comment: Yes, that's essentially the proof by parity that I surmised you used.
Answer: As you conclude in the comments, the point is that we must have $m = n$.
Here's an alternative proof: suppose for contradiction that $m \neq n$; in particular take $m > n$. Let $k = 2m^2 + m$. We see that $m$ and $n$ are two solutions to the quadratic equation
$$
2x^2 + x - k = 0.
$$
The sum of the roots of $ax^2 + bx + c = 0$ is given by $-\frac{b}{a} = - \frac 12$, which is to say that $m + n$ is not an integer. This is impossible since $m,n \in \Bbb Z$.
Comment: Nice method but u just complicated it ,if x is not equal to y then x + y = -0.5 which is not true
Comment: @AdhirajSinghBrar You're right. When I first wrote it I was trying to figure out why $m-n$ would be a perfect square...
Comment: @AdhirajSinghBrar I made the proof more succinct now
Comment: @Adhiraj I added an answers which emphasizes the underlying *number theory* (per your tag).
Comment: Thanks @BenGrossmann
Comment: Thanks @BillDubuque
Answer: An alternative way to approach the same result: For nonnegative values of $x$, the function $f(x)=2x^2+x$ is strictly increasing, so the only way to have $f(m)=f(n)$ is if $m=n$.  And then of course $m-n=0$ is a perfect square.
Answer: Special case of that below, namely $\, d=2,\ f = 2x^2\!+\!x$.
Theorem $\ $ If $\,f(x)\in\Bbb Z[x]\,$ and $\!\bmod d\!:\ f\equiv bx\!+\!c,\, \color{#c00}{b\not\equiv 0}\,$ then $\,f(m)=f(n)\Rightarrow m = n$
Proof $\,\ 0 = f(m)\!-\!f(n) = (m\!-\!n)\:\!k,\,$ for $\,k = \dfrac{f(m)-f(n)}{m-n}\in\Bbb Z,\,$ thus if $\,m\neq n\,$ then $\,k = 0\,$ thus $\bmod d\!:\,\ \color{#c00}0 = k \equiv \dfrac{bm\!+\!c-(bn\!+\!c)}{m-n}\equiv \color{#c00}b,\,$ contra hypothesis.


Geometry Math 8th (Area of a Trapezoid)

Question: The windshield in a truck is in the shape of a trapezoid. The lengths of the bases of the trapezoid are 70 inches and 79 inches. The height is 35 inches. Find the area of the glass in the windshield.
Comment: Can you show your effort and point the issue where you have trouble?
Answer: The formula for the area of a trapezoid is $\dfrac {a+b}2\times h$, so that becomes $\dfrac {149}2\times35 = 2,607.5$inches$^2$
Answer: The average of the two bases is 74.5, and I multiply that by the height which is 35 to get 2607.5 inches.
Comment: not quite, $2607.5$ inch squared
Comment: Oops, I accidentally got the place value wrong, thanks

Geometry Math 8th (Area of a Trapezoid)


length of $\sqrt{x} + \sqrt{y} = 1$ ? on $[0,1]$

Question: how to calcuate length of $\sqrt{x} + \sqrt{y} = 1$ ?
I put $x = \cos^4{t} , \ y = \sin^4{t}$ but failed.
Do you have Any good idea form here?
Comment: Are you comfortable with an answer involving the gamma function?
Answer: $$
\sqrt{x}+\sqrt{y}=1\implies y'=-\frac{\sqrt{y}}{\sqrt{x}}
$$
Substituting $x\mapsto u^2$ and $2u-1\mapsto\tan(\phi)$ gives
$$
\begin{align}
\int_0^1\sqrt{1+y'^2}\,\mathrm{d}x
&=\int_0^1\sqrt{1+\frac yx}\,\mathrm{d}x\\
&=\int_0^1\sqrt{1+\frac{1+x-2\sqrt{x}}x}\,\mathrm{d}x\\
&=2\int_0^1\sqrt{2u^2-2u+1}\,\mathrm{d}u\\
&=\sqrt2\int_0^1\sqrt{\left(2u-1\right)^2+1}\,\mathrm{d}u\\
&=\frac1{\sqrt2}\int_{-\pi/4}^{\pi/4}\sec^3(\phi)\,\mathrm{d}\phi\\
&=\frac1{\sqrt2}\int_{-\pi/4}^{\pi/4}\frac{\mathrm{d}\sin(\phi)}{\left(1-\sin^2(\phi)\right)^2}\\
&=\frac1{4\sqrt2}\int_{-\pi/4}^{\pi/4}\left(\frac{\mathrm{d}\sin(\phi)}{(1-\sin(\phi))^2}+\frac{\mathrm{d}\sin(\phi)}{1-\sin(\phi)}+\frac{\mathrm{d}\sin(\phi)}{(1+\sin(\phi))^2}+\frac{\mathrm{d}\sin(\phi)}{1+\sin(\phi)}\right)\\
&=\frac1{4\sqrt2}\left[\frac{2\sin(\phi)}{\cos^2(\phi)}+2\log\left(\frac{1+\sin(\phi)}{\cos(\phi)}\right)\right]_{-\pi/4}^{\pi/4}\\
&=\frac1{2\sqrt2}\left[\tan(\phi)\sec(\phi)+\log(\tan(\phi)+\sec(\phi))\vphantom{\frac12}\right]_{-\pi/4}^{\pi/4}\\
&=\frac1{2\sqrt2}\left[2\sqrt2+2\log(\sqrt2+1)\right]\\
&=1+\frac{\log(\sqrt2+1)}{\sqrt2}
\end{align}
$$
Comment: I really appreciate your answer. I knew that $2u-1 = tanx$ was the key. I will check calculus has no mistake(maybe it is right :D ). Thx again bro.
Comment: You can start with $x=\cos^4(t)$ and $y=\sin^4(t)$, but you just end up with the integral above with $u=\sin^2(t)$.


Failing to call REST endpoint in vbox

Question: I have my spring boot services running in vbox with the ports exposed. I've confirmed this.
When attempting do a post from my flutter app I am receiving the following:
Error: XMLHttpRequest error.
    C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 908:28                get current
packages/http/src/browser_client.dart 71:22                                                                                <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1687:54                                              runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 160:18                                        handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 767:44                                        handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 796:13                                        _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 593:7                                         [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11                                         _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1232:7                                             <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14  _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39  dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37332:58                              <fn>

    at Object.createErrorWithStack (http://localhost:63034/dart_sdk.js:5074:12)
    at Object._rethrow (http://localhost:63034/dart_sdk.js:38925:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:63034/dart_sdk.js:38921:13)
    at Object._microtaskLoop (http://localhost:63034/dart_sdk.js:38778:13)
    at _startMicrotaskLoop (http://localhost:63034/dart_sdk.js:38784:13)
    at http://localhost:63034/dart_sdk.js:34519:9

The code where I make the request is as follows:
void _registerBuild() async {
    Map<String, String> headers = {
      'Content-Type' : 'application/json',
      'Accept' : 'application/json'
    };
    Map data = {
      'buildingName': buildingName,
      'erf': erf,
      'addressRoad': addressRoad,
      'addressSuburb': addressSuburb,
      'addressCity': addressCity,
      'addressProvince': addressProvince,
      'addressCountry': addressCountry,
      'addressPostalCode': addressPostalCode
    };

    var response = await http.post(Uri.http('192.168.1.102:9081', '/trusteeman/building/register'),
        headers: headers,
        body: jsonEncode(data));

    if (response.statusCode == 200) {
      print("**************************************\n");
      print(response.body);
    }
  }

I've tried using the IP address of: 10.0.2.2 but receive the same error.
Any help appreciated
EDIT 1 - I've built the backend with WSL and started them up but still having the same issue
Comment: Does it has `CORS` enabled?
Comment: I don't believe so. It's this s setting or configuration I need to add?
Comment: @PrinceSanjivy you're correct. Added debug logging to the service and I can see the 403 error now. Many thanks
Answer: Was a CORS issue. debug logging showed it on the server side.

Failing to call REST endpoint in vbox


The question about the char code of C/C++ AND Java

Question: I try to enter the code for the emoji with Unicode code \U+1F431 like this:

This is done on VS Studio 2019. The file encoding of CPP is UTF8-BOM.
C/C++ language in the char occupies only a byte, need two bytes 2 ^ 16 = 65536 to say Chinese characters. In Java, Unicode is used as the internal code, and char is encoded in UTF-16, one char are two bytes, you need to use two char (4 bytes) to represents a single emoji, why emoji just use two bytes in the C language can be said?
In addition, in this online C++ runtime environment(https://c.runoob.com/compile/12), run the same code, output is 4, the character encoding of the http request from the page is UTF-8, the results I understand should be the number of bytes in this emoji encode by UTF-8, but why is not the same as the result of the execution? Will the results of C++ programs still be affected by file encoding? It is always same whatever file encoding in Java

#include <iostream>
#include <cstring>

int main()
{
    char str[] = "";
    printf("%d", strlen(str));
    // output is 2 in VS Studio and 4 in the online C++ runtime environment

    char str1[] = "哈";
    printf("%d", strlen(str1));
    // output is 2 in VS Studio and 3 in the online C++ runtime environment
}

Comment: A good starting point: https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/
Comment: As is, this is a very confusing question. Please edit your question and provide some code examples.
Comment: C/C++ doesn't know about unicode.  In Visual Studio you have to select Unicode support in your project settings and use the appropriate (wide character) functions and data types.
Comment: @Gyro Gearless I didn't know how to upload pictures the first time I asked, but it's been added. I hope I can get your help
Comment: No, @user15129239, *do not* upload pictures.  We always want code as text.  Likewise console input and output.  Use images only when text cannot serve.
Comment: I konw this. so your meaning is that char can not express emoji correctly. the output: 2 in img1 or 4 in img2 is error? but what if I set like this: char str[] = "哈", the output is 2 in vs studio and 3 in the online c++ runtime environment, that is my question
Comment: @John Bollinger OK. I've added the code, it's not long
Answer:
The file encoding of CPP is UTF8-BOM.

I assume that you are talking about the encoding of your particular source file, as opposed to asserting something about the C++ language.  In fact, however, the encoding of your source file is not relevant as long as you and your compiler agree about it and the compiler supports it.  C and C++ distinguish between the encoding of source files (the source character set) and the encoding of character data in runtime memory (the execution character set).  They do not require these to be the same.  The strlen() function, being executed at runtime, will evaluate the number of bytes in the runtime encoding of your C string literal.

C/C++ language in the char occupies only a byte, need two bytes 2 ^ 16 = 65536 to say Chinese characters.

How many bytes are required to encode Chinese characters depends on the character and the encoding.  For example, with Unicode encoded in UCS-4, all characters require four bytes.
With Unicode encoded according to UCS-2, all characters require two bytes, but fewer than 65536 characters can be represented at all -- the Unicode "basic multilingual plane".  All Chinese characters that can be represented at all occupy two bytes in this encoding, just like every other character.
With UTF-16, some characters require two bytes and others require four.  Unicode maps many Chinese characters that it considers less commonly used to code points outside the BMP, and these require four bytes in UTF-16.
With UTF-8, all characters outside the BMP require four bytes.  Most BMP characters require three bytes, but some require fewer.
This is by no means an exhaustive list of alternatives.

In Java, Unicode is used as the internal code, and char is encoded in UTF-16, one char are two bytes, you need to use two char (4 bytes) to represents a single emoji, why emoji just use two bytes in the C language can be said?

Unicode encodes all emoji outside the BMP.  Two bytes is not sufficient to convey their Unicode codes, no matter what encoding is chosen.  For example, your particular emoji is U+1F431, "cat face".  Its Unicode code point has 17 significant bits.  It cannot be represented in UCS-2, its representation in UTF-16 has four bytes, and its representation in UTF-8 also has four bytes.
Therefore, the output of your program probably shows that either the source is buggy or that it has not been built correctly by VS.  You can probably view it either way, as the most likely problem is that VS is assuming a different source character set than the one with which your source file is actually encoded.  It might be instructive to print the strings, too, as opposed to just their lengths, or to examine them at runtime with VS's debugger.
Your Chinese character example is Unicode character U+54C8.  Its representation in UCS-2 and UTF-16 has two bytes, and the one in UTF-8 has three bytes.  VS is again doing something strange here (see below), probably again because of a disagreement between you and it about the source character set.

In addition, in this online C++ runtime environment(https://c.runoob.com/compile/12), run the same code, output is 4, the character encoding of the http request from the page is UTF-8, the results I understand should be the number of bytes in this emoji encode by UTF-8, but why is not the same as the result of the execution?

Yes and no.  It is very unlikely (but not impossible) that the online environment you are using takes the encoding of your HTTP requests into account for determining the C++ implementation's execution character set, which is what matters for strlen().  But if it is any good then it does take the request encoding into account with respect to the source character set, either by transcoding to a chosen standard encoding or by telling the compiler which source encoding to use on a case-by-case basis.  Thus, it is reasonable to believe that the online environment does not suffer from any source-encoding disagreement such as I have raised as the likely issue in VS.
UCS4, UCS-2, and UTF-16 are not viable execution character sets for C and C++ because the encodings of many non-null characters contain null bytes.  C and C++ implementations will not use those.  (Wide strings are a different consideration.)  Implementations may have options for a variety of execution character sets, but UTF-8 is a common default.  That's because it's a pretty good choice, not because of the encoding of any particular external data.
The output of your program in the online environment is consistent with UTF-8 being that environment's choice of execution character set.

Will the results of C++ programs still be affected by file encoding? It is always same whatever file encoding in Java

The results of C++ programs can be affected by the implementation's execution character set.  When I/O is involved, you also have to consider the encoding of the external data. As you observe, Java is different -- the internal representation of character data in terms of its char data type and java.lang.String class is not permitted to vary across implementations.  However, you may still run into trouble with Java if there is a disagreement over source file encoding, and with Java you still have to take character encoding into account when you perform I/O.
Comment: Thank you for your detailed answer. I think I have found the reason for the exception of vs output. The default execution character set of vs studio 2019 is encoded as GBK. You need to use the following code to make the output normal.
`code`
char str1[] = u8"哈";
`code`
Comment: But I still have some questions, char can support UTF-8 coding, why C + + will also introduce wide character wchar_t ? Under UTF-8 coding, some people say that the reason for using wide characters is that a character can represent a Chinese character, but for Emoji expressions, a wide character can't represent a single emoji. In addition, there is a conversion between ASCII and Unicode in windows, that is char and wchar_t conversion, maybe not right, what does this code conversion mean?
Comment: @user15129239, wide characters and wide strings were introduced before UTF-8 strings.  `wchar_t` and wide strings support *implementation-specific* character representations with *fixed-size* units.  This is amenable to a whole set of analogues of the original string functions.  At the time these were designed, it was not yet evident that they would prove too limited in practice, and UTF-8 had not yet achieved the ubiquity it now has.
Comment: As for conversions between wide and narrow strings, that would be the subject of a different question.
Comment: OK. Thank you very much for your answer. It's very helpful.
Comment: You are welcome, @user15129239.  If your original question has been answered to your satsifaction, then it is customary to "accept" one of the answers by clicking on the check mark icon next to it.


i am having trouble renaming objects in my code but when i do it manually it works fine. what am i doing wrong?

Question: curl -# -O https://media.wix.com/ugd/d49749_7b2f263007bf4717ba5e6550a251f0d9.doc?dn=database.doc ; echo now uncrupting info... ; mv d49749_7b2f263007bf4717ba5e6550a251f0d9.doc?dn=database database.zip ; echo installing cart ; unzip database.zip ; say -i ok i finished it, thanks for waiting frend

i am trying to change d49749_7b2f263007bf4717ba5e6550a251f0d9.doc?dn=database to database.zip then unzip it but it keeps on saying
mv: rename database.zip to d49749_7b2f263007bf4717ba5e6550a251f0d9.doc?dn=database: No such file or directory

what am i doing wrong?
and i am sorry but i am still new to bash so i have no idea what i am doing.
Answer: You have too see the name that it get's when it is downloaded I really think the name is database.doc and not d49749_7b2f263007bf4717ba5e6550a251f0d9.doc?dn=database
Or tell curl what name it should have once downloaded
Comment: how do i tell curl to do that?


Check if a taxonomy term synonym exists

Question: I have a $category variable containing country names separated by comma. So I use the following code to save them as taxonomy terms:
$tids = array(); $ctids = array();
$category = explode(',',$category);
foreach($category as $cat) {
  insert_term_if_not_exists($cat, 'countries');
  $term_country = taxonomy_get_term_by_name($cat);
  $tid_country = key($term_country);
  $lang_country = field_language('node', $node, 'field_country');
  array_push($ctids, $tid_country);
}
foreach ($ctids as $index => $ctid) {
 $node->field_country[$lang_country][$index]['tid'] = $ctid;
}

As you see the above code uses the insert_term_if_not_exists() function which works perfectly well to check if a taxonomy term exists and to create it programmatically if it doesn't:
function insert_term_if_not_exists($term_name, $vocabulary_name) {
   $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
   $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
  if(empty($matched_terms)) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $term_name;
    taxonomy_term_save($term);
  } else {
    $term = array_shift($matched_terms);
  }
return $term;
}

However, I also need to check and avoid creating a new taxonomy term if it is a synonym of already existing another taxonomy term. So I modified the above code in the following way:
function insert_term_if_not_exists($term_name, $vocabulary_name) {
   $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
   $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);

    if(empty($matched_terms)) {
      $matched_synonym = synonyms_get_term_by_synonym($term_name, $vocabulary);
      if (empty($matched_synonym)) {
        $term = new stdClass();
        $term->vid = $vocabulary->vid;
        $term->name = $term_name;
        taxonomy_term_save($term);
      } else {
        /*
        * Here I need to do something, but don't know what exactly. Using
        * $term = taxonomy_term_load($matched_synonym);
        * here doesn't work.
        */
        }
    } else {
        $term = array_shift($matched_terms);
    }
  return $term;
}

Having troubles to make it work properly.
Comment: `synonyms_get_term_by_synonym()` expects its `$vocabulary` parameter to be a fully loaded vocabulary object, so make sure you're passing a valid vocabulary object. If it isn't, that could be the cause of the the error you get on line 356.
Comment: But what is a "valid vocabulary object"? Both $term_name and $vocabulary->machine_name are just strings which work perfectly well with the insert_term_if_not_exists function given above. So what exactly I need to feed synonyms_get_term_by_synonym() with, what is the difference?
Comment: I pretty much meant to make sure you're giving it $vocabulary and not $vocabulary->machine_name or $vocabulary_name. Internally that function is using $vocabulary->vid so if $vocabulary is a valid vocabulary object, it'll presumably have a vid.
Answer: Edited my answer since my original answer referred to dev code.
The following simple module works with Drupal 7.34 and the current stable version of synonyms (7.x-1.2) and successfully matches a synonym to a taxonomy term.
synonyms_test.module:
function synonyms_test_menu() {
  $menu['test-synonyms'] = array(
    'page callback' => 'synonyms_test_page',
    'access callback' => TRUE,
  );

  return $menu;
}

function synonyms_test_page() {
  $vocabulary_name = 'tags';
  $output = '
Assuming you have a taxonomy with machine name "tags" and that '
            . 'taxonomy has a term named "first term" and that term has a '
            . 'synonym "syn one", this test will produce these results:
';
  $test_terms = array('first term', 'bogus term', 'syn one');
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  foreach($test_terms as $test_term) {
    $output .= 'Testing "' . $test_term . '"
';
    $matched_terms = taxonomy_get_term_by_name($test_term, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $output .= 'Not an existing taxonomy term.';
    } else {
      $output .= 'Is an existing taxonomy term.';
    }
    $output .= '

';
    $matched_synonym = synonyms_get_term_by_synonym($test_term, $vocabulary);
    if(empty($matched_synonym)) {
      $output .= 'Not an existing synonym.';
    }
    else {
      $output .= 'Is an existing synonym, for tid ' . $matched_synonym;
    }
    $output .= '
=========

';
  }
  return $output;
}

* Original answer below *
This is the function you're looking for (from synonyms.module):
/**
 * Returns the term objects that have the given string as a synonym.
 *
 * @param $synonym
 *  A string containing the synonym to search for.
 * @param $vocabulary
 *  (optional) The machine name of the vocabulary in which to search for.

 * @return
 *  An array of term objects containing that synonym.
 */
function synonyms_root_terms_get($synonym, $vocabulary = NULL) {
  $tids = synonyms_root_tids_get($synonym, $vocabulary);

  return taxonomy_term_load_multiple($tids);
}

So if your $matched_terms is empty, try something like:
$matched_synonyms = synonyms_root_terms_get($term_name, $vocabulary->machine_name);
if(empty($matched_synonyms)) {
  // ...now create your new term
}
else {
  $term = array_shift($matched_synonyms);
}

Comment: Thanks @dblue, but I tried that before and, unfortunately, it is giving: `Fatal error: Call to undefined function synonyms_root_terms_get()`
Comment: I also tried the `function synonyms_get_term_by_synonym()` with no much success, please see the updated post above.
Comment: Oh, my mistake, `synonyms_root_terms_get()` is in the master branch of the module's code, but not in the 7.x-1.x branch, that's why you get the undefined function error.
Comment: I'll give a try to master branch if it works.
Comment: Since it's dev code, I hope it's stable enough to work, if you can't get synonyms_get_term_by_synonym() in the current release to work. Let us know how it goes.
Comment: Still it gives: Fatal error: Call to undefined function synonyms_root_terms_get()
Comment: Did you check out the master branch from the git repository (http://cgit.drupalcode.org/synonyms)? That said, I'm sorry I pointed you down this road; in looking more closely at the repo, the master branch seems pretty separate from the release branches, and hasn't been updated in 3 years. If that code hasn't been put into a release or had any attention in all that time I wouldn't trust it to be stable. You're probably better off turning your attention back to the cause of your error when you try to use `synonyms_get_term_by_synonym()`.
Comment: Can you please test this on a clean Drupal install? The function simply doesn't hook in. Both modules - synonyms and my custom module - are enabled. Is it enough to enable two Drupal modules to make them interact with each other? Or do I have to somehow make additional call (declare or smth) to synonyms in my custom module?
Comment: @Sasha, it should be enough just to enable both modules. See my edit; it provides a working example that uses the stable version of synonyms and its `synonyms_get_term_by_synonym()` function.
Comment: I accepted your answer as with little bit modification I've got it working. Thanks!
Comment: You're welcome. Good to know you got it working. And sorry I led you down the detour.

Check if a taxonomy term synonym exists


setting a property that has only a getter js error

Question: i have the following div structure with respective ids :

but when i click on the parent div an error is encountered which says :
setting a property that has only a getter
i have written listener for keyboard press events(direction keys)
the following function is called when i hit enter from keyboard :
function jsfunc() {
    var elem = document.getElementByID(currpos_html);
    for(var i=0;i<elem.childNodes.length;i++){
        if(elem.childNodes[i].id == "_img") elem.childNodes[i].style="block";
        if(elem.childNodes[i].id == "border") {
            elem.childNodes[i].style.display="block";
        }
}

Comment: the following function is called when i hit enter from keyboard :

function jsfunc() {
 var elem = document.getElementByID(currpos_html);
 for(var i=0;i<elem.childNodes.length;i++){
  if(elem.childNodes[i].id == "_img") elem.childNodes[i].style="block";
  if(elem.childNodes[i].id == "border") {
   elem.childNodes[i].style.display="block";
  }
}
Answer: Unless this :
elem.childNodes[i].style="block";

is a transcription typo it may be your problem, you cannot set style to a string AFAIK.
In the next line you have
elem.childNodes[i].style.display="block"

which is more reasonable


C#: Async Task: Cancel

Question: I have an function that does some work for a few seconds. I'm trying to cancel that task after a certain time period and am unable to do so. My objective is to do the asyncFunction for 5 seconds and then, move onto to a different task. For some reason, I can't seem to await _t1.
private async Task asyncFunction(string line_1, string line_2, string line_3, string line_4, int _time, System.Threading.CancellationTokenSource _cts)
    {
        _cts.Token.ThrowIfCancellationRequested();

        await Task.Run(async () => {
            someFunction_01(line_1, line_2, line_3, line_4);
            someFunction_01("HELLO WORLD");
            await Task.Delay(_time, _cts.Token);
        });
    }

The way I'm calling my funcion is:
TimeSpan _timeout = TimeSpan.FromSeconds(5);
            var timeoutCancellationTokenSource = new System.Threading.CancellationTokenSource(_timeout);

            Task _t1 = asyncFunction("LINE 01", " ", " ", " ", 6000, timeoutCancellationTokenSource);
if (await Task.WhenAny(_t1, Task.Delay(_timeout, timeoutCancellationTokenSource.Token)) == _t1)
            {
                await _t1;
            }
            else
            {
                // timeout/cancellation logic
                timeoutCancellationTokenSource.Cancel();
            }

I can't seem to cancel the Task.Delay inside of the asyncFunction. Any code help is appreciated.
Answer: I don't quite understand the purpose of the code. Particulary the if-statement:
if (await Task.WhenAny(_t1, Task.Delay(_timeout, timeoutCancellationTokenSource.Token)) == _t1)

Why pass in a _timeout to Task.Delay which is the same timeout as you created the timeoutCancellationTokenSource with?
If we ignore the first parameter you give Task.Delay it also means you have two calls to Task.Delay with the same CancellationToken and now you have a race-condition where it's impossible to predict which Task.Delay will be cancelled first.

To show an example of how you can get the cancellation to work, you can do like this:
TimeSpan _timeout = TimeSpan.FromSeconds(1);
var timeoutCancellationTokenSource = new System.Threading.CancellationTokenSource(_timeout);

Task _t1 = asyncFunction("LINE 01", " ", " ", " ", 2000, timeoutCancellationTokenSource);
try
{
    await _t1;
}
catch (OperationCanceledException)
{
    Console.WriteLine("Operation was cancelled");
}

// Output: Operation was cancelled

If _timeout is longer than the 2000 milliseconds passed into asyncFunction the task completes after 2 seconds without being cancelled.
See this fiddle for a test run.
Comment: instead of asyncFunction can you use a simple method which prints hello world and await Delay(2000);
Comment: @user1735921 Yea, definitely. Although, it's not clear to me what the purpose of the `Task.Delay` is.

C#: Async Task: Cancel


Gram matrices in the Rayleigh-Ritz algorithm

Question: I want to get the math behind of the Rayleigh-Ritz Procedure (that minimize Rayleigh quotient)
But when I look at the code (*), I cannot understand:
Why are Gram matrices in the Rayleigh-Ritz procedure constructed this way? And why we should solve the eigenproblem with Gram matrices?
Can someone explain why we use Gram matrices or advice a paper that covers this? I googled but didn't find any description of the Gram matrix into Rayleigh-Ritz

the pseudocode I mentioned before is a part of LOBPCG algorithm (page 5)
https://arxiv.org/pdf/0705.2626.pdf

Thank you in advance
Answer: I think I was very tired when asked this...hmmm. I don't delete the question, cause somebody would ask himself the same question someday
The answer in the definitions
If we have an eigenproblem $Ax = \lambda Bx$ and a subspace defined by basis vectors in a matrix $S$, then the projections of eigenvectors on $S$ are the solutions of $S^TASx_i = \lambda S^TBSx_i$. (definition of the Rayleigh-Ritz procedure)
If $S$ defined as a set of vectors $X_i$ = ($v_{i1} ... v_{in}$) that has some senses, we can write the matrix multiplication in the block form - the form gives a Gram matrix.


PA Mixer Setup for band

Question: I have a PA Mixer (Yamaha emx512) that has channels 1-4 with XLR or mono 1/4 Line. Channels 5/6 and 7/8 are in pairs where the controls of 5/6 are shared and 7/8 shared where the inputs are 1 XLR and 1 set of stereo 1/4 lines each. Channels 9/10 and 11/12 share controls operate the same way as 5/6 and 7/8 except the inputs are 1 XLR or stereo RCA jacks.
The band I'm in has 2 guitars, 1 bass, 1 keyboard, drums and 3 vocalists. I can isolate my powered monitors from the PA speakers so it would be awesome if I could run everything into the PA Mixer.
1 guitar amp has to be mic'd, and all other instruments have DI options. How would you guys approach things in order to maximize the number of mics I can put on the drum kit? Thanks!
Edit: Small venues around 100 - 150 people and we do a variety of high energy rock. Wattage of the PA speakers I have is enough to hold PA at max levels (don't have details). I'm mainly looking for the best way to optimize my inputs and which channels to put them on.
I was intending on the guitar amps holding their own and leveraging the PA Mixer just to include guitars in the monitors. So assume no headroom needed for guitars. We use powered monitors so that also doesn't require anything from the PA, just the mixer.
Bass player has their own speaker and power amp, but sometimes the space of the stage just forces us to DI into the PA.
Keyboard player doesn't have their own amp so she is DI.
Currently we have two Samson R15s which are 225 watts at 8 ohms.
Likely for drums we'd shoot for bass drum, snare, and maybe an overhead for the cymbals. Sort of trying to figure out what is economical
Edit 2: Thanks this is incredibly helpful and am tracking on the drums.
So when you were talking about the guitars taking up some of the wattage, does that apply even if we are adding them just for the purpose of monitors? Each player has a 40-50 watt high end combo amp so volume of guitars is not an issue. We just wanted to have them in the monitors as the placement of the amps isn't always good for hearing ourselves. Fully intend on zeroing the guitars out in the PA when we play the smaller rooms.
Thanks again, I'm a complete newby when it comes to this.
Comment: One more comment about guitars in monitors: it's really a luxury that your band should probably learn to live without. I've mixed over 100 small venue shows and played guitar in maybe half as many, including many gigs with another guitarist on the other side of the stage. My amp was my monitor and for most shows I couldn't always hear the other guitar but I only needed to keep time with drums, lock in with the bass, and not step on the vocals, so you just trust the other guitarist to do their job. The show is for the audience, so if not hearing the other guitar makes a better show, I'm ok.
Comment: Assuming you have multiple mics for drums and cymbals, it's worth getting a mixer just for the drumkit - if drummers need amplifying! That way, you need only take up one (or two for stereo) inputs on the Yamaha. Price of a small mixer is hardly worth talking about in comparison to the rest of or gear.
Comment: My answer focuses on the front of house mix, so if want guitars in the monitors and the don't drown out the vocals or keys in the monitors, then there's no reason not to do it. But the monitors are kinda like another PA just for the band, so all the same rules apply. Like FOH, vocals are usually the most important thing in monitors because most singers really can't hit notes if they can't hear themselves. You may very well find that squeezing the keys into the monitors while keeping the singers happy is hard enough without putting guitars in.
Comment: @ToddWilcox - I agree about the other guitar , but it's often not difficult to turn both amps inwards so both can hear. Sometimes it's a luxury to have another guitarist, sometimes, what's the opposite of luxury?
Answer: For a venue and audience that size, the most important thing will be making the vocals audible. You should run mono. If you don't have even small subs then bass and kick drum might not make sense to run through the PA at all.

Vocal mikes up on channels 1-3
Channel 4 mono keyboards channel (a passive DI with ground lift would be ideal for this)
Kick drum mic on channel 5/6
bass DI (ideally a DI out from a bass amp) on 7/8
guitar 1 miked on channels 9/10,
guitar 2 miked on channels 11/12

How I would mix it:
Being the vocals up to unity on their channels, maybe drop BG vox a little - 3-6 dB. Bring the main fader up until the vox are clearly audible over the band. If you can't get them audible you PA is too small or you have something configured wrong with the front of house rig.
Once that's done, you have the minimum requirements for a show met. Likely the keyboards might be hard to hear. If so, bring them up, starting about halfway up until they sit under the vocals and maybe just slightly quieter than the stage sound from the bass amp. EQ the keys to sit as best you can.
Once that's done, you might want to do something similar with the guitars. Their stage sound will probably be louder than the key stage sound so they need less in the PA. I'd bring them up slowly from nothing until I can just barely tell they are in the PA. Cut the lows pretty hard on these channels and maybe roll the highs off a little since a mic right on a speaker cone can be harsh.
Now, if you have subs for FOH, I'd bring the kick drum in just a little and boost the low EQ on that channel just a little. This is another case of bring it up until you can just barely tell. Kick drum similar but only if it sounds quieter than the snare and just bring it up to match the snare and give it thump.
If you have no subs at FOH, then the most you can add for kick and bass is some articulation. Without subs if you try to boost lows on kick and bass into the PA you will easily take up all the power bandwidth for vocals and the singers will be lost. Unless you have some mixing experience - enough so that you probably wouldn't need to ask this question, I would resist the urge to put any kick or bass in the PA if you have no subs. Having the bass DI in the PA is good if there's a problem with the bass amp but again you gotta be very careful not to bury everything else and make the PA into a huge bass amp.
Overall, if the keyboard and bass players have decent amps, you often don't need a PA for anything but vocals under 200 audience members. I suggest keeping that in mind as you do this. The PA is for the vocals because they have no other way to get heard. If if you have a lot of watts and headroom out front (maybe 1500 - 2000+), then you have more leeway to augment the other instruments. Otherwise, whatever you do with non-vox is going to take some away from the vox, so only if you need it and as little as necessary.

Regarding your continued desire to put drums besides kick in the PA:
A) You don't need to. Unless you're outdoors in an open field and even then you probably don't need to.
B) At 225 Watts per, for a total of 450 Watts, you're definitely in "vocals only" territory.
Aside from maybe the kick drum, indoors in front of <200 people you do not need drums in the PA. If people can't hear the drums either you have accidentally gotten a jazz drummer in your high energy rock band or your guitar and/or bass amps are way too loud. And if those amps are too loud, people are going to more likely complain about not hearing the vocals.
Let's look at your actual biggest problem, which has nothing to do with drums:
Suppose you have two guitar amps that are rated at 30-50 Watts and a bass amp rated at 100 watts (those are conservative numbers). The guitar amps will probably have distortion for at least some parts of the show and otherwise do not need or use headroom so when comparing with a PA and vocals they kind of "count" for double, so that's effectively 100 watts for each guitar. The bass might play compressed and/or with a little distortion so they are maybe comparable at 1.5 times the rated output so lets call that 150 Watts.
So you're looking at a phantom "350 Watt PA" for guitars and bass and only a real 450 Watt PA for three singers and keyboards. Add in the acoustic Watts of the drum kit and you're in for a rough ride.
Ideally the keyboard player would get an amp and leave you maximum wattage for vocals, because you're going to need them.
If you're doing band practices you should set some of this up at band practice. If you can get the monitors working for vocals and keys at band practice and hear them over drums, guitars, and bass, then you'll have clues about how to do FOH also.
If you try to put overheads through the PA, crash cymbals and open high hat will make everything completely inaudible unless you have a huge stage, a huge venue, and a professional mix engineer. Keep in mind that all of your vocal mikes are also mid-field drum room mikes. Making the snare and cymbals audible is absolutely your lowest, lowest concern here. With three open vocal mikes on stage and some stages being so small there's no room for a bass amp, you're already miking the drum kit more than anything else.
Comment: @user1079505 First, I recommend the asker not even mike the kick in this situation. Second, the kick is definitely the quietest part of the drum kit, except possibly the floor toms, but the kick is about 20 times more important than toms. The snare is potentially the loudest part of the kit but it has no sustain, so when mixing the cymbals are a bigger problem. But the snare generally doesn't need a mike until the show gets bigger. One reason to mike a snare on a mid size show is to add reverb without even putting any direct snare through the mains, but asker isn't in that situation.
Comment: Could you justify why do you propose to mike the kick drum only, especially given OP says they play energetic rock, and this is a style where the snare drum is probably more important than the kick drum. Why do you believe it's the lowest concern?
Answer: The objective of a p.a. is to give the audience a good mix of the music being played. An audience of <200 means a fairly small venue, so even a rock band doesn't have to be deafening - particularly for those closest to the p.a. speakers, often at the front of the stage, either side. And certainly not for the players on stage. My loss of hearing in my 70s is testament to that!
Drums will generally find their own way through the sound, which is good, as the rest of the band needs the, to keep in time. The usual drum that's put through the p.a. is the kick, to give a better sound for the audience. So one mic there.
Guitarists seem to often have a battle of volume with each other, a shame really, as that fills the stage with noise. It can be solved using D.I., as then their amps should work as monitors, given they're angled up and not blowing through the players' legs. Mics will capture a better sound, which obviously then goes through that p.a.
Bass is usually better self-contained (I find it so, as the speaker can be close to the drummer, making a tighter rhythm section), and leaving it out of the p.a. means the vocals aren't muddied in any way.
Vox. They're the weak link as they must rely on the p.a. for enough volume to be heard by the audience - and by themselves. So paramount is the mics get preference, and if at all possible, foldback in such a small venue can be provided by judicious placing of the p.a.speakers. At least that way, everyone gets to hear pretty well what the audience is hearing. So long as feedback isn't a problem. Some rooms/stages make that almost impossible.
Keys can go quite happily in p.a. (although I prefer to have my own mini p.a. when I'm out on keys) but in the absence of an amp, reliance on hearing the p.a., or using monitors, will help a lot. Main reason being when I change from, say, pno to organ to vibes to strings to e.p., etc., the resulting volume fluctuates quite a bit. Being able to hear better what I'm producing (volume wise) means I can balance keys better that way. If it's all out front, it's difficult, and depending what else is sent through foldback, not easy either.
Monitors. Ah, used properly these do a great job, especially for vox, and those at the back of the stage. But often they're abused, and just add to the sound pressure on stage. And with only one mix, and maybe several monitor speakers, things are less than ideal. Everyone wants more me.
Then there's the setting up and breaking down of all the gear. The more, not the merrier. And controlling it during the gig. Those on stage, unless very experienced, won't be able to hear properly what's going out f.o.h. And micing as many up as possible probably exacerbates this. And vocal mics left open while no-one is singing through them produces a different mix.
So, in summary. Obviously 3 vox mics have priority. next (in your case) are keys. Kick drum might come next - not necessarily to amplify it, more to give the audience a good sound from it. And if the snare is mic'd it may encourage the drummer to not hit it so hard! For smaller gigs, guitars should be fine on their own, provided the amps are well placed. Bass on its own, as its sound isn't directional, but it needs to be heard on stage, too.
I don't think there is one ideal set-up. Stage (or lack of) and proportions of room as well as acoustics therein will affect set up too, and lack of a good sound guy (preferably a muso) will jeopardise settings. Which, if done in a sound check in an empty room won't do much either.
I was hoping to cover this in a couple of paragraphs, but it seems that isn't possible! The only other alternative would be to have everything going through the p.a., with monitors for everyone, but that would necessitate electronic drums instead of an acoustic set.
Comment: I go to a lot of trouble providing answers. Please go to a little bit of trouble explaining the dv. Thank you.  In fact, I consider it rude not to.

PA Mixer Setup for band


C# AssemblyVersion 3 digits for use with NuGet's PreRelease versioning

Question: In AssemblyInfo.cs:
[assembly: AssemblyVersion("1.0.*")]

Will generates a 1.0.x.x four digits version number.
Which, if I use this nuspec metadata:
<version>$version$-test</version>

generates an error when packing:
The version « 1.0.5431.31092-test » does not follow semantic version control instructions

Is there a simple way around this?
Comment: What do you mean "three digits one"? Clearly `Assembly.GetName().Version` has 4 parts (due to being `System.Version`)... so you probably mean something different, but unclear what.
Comment: Ok I get this now. The class has a three digits constructor but its properties are not nullable. That makes sens.
Answer: Not possible, an assembly's version is stored in the System.Version class, that consists of Major, Minor, Build and Revision.
EDIT: I was a bit to hasty to answer. When you use the AssemblyVersionAttribute's constructor with a string containing an asterix, all four properties of a version will be generated. The only way to cause a version with lesser numbers is to specify the exact version number, without asterix, i.e "1.0.1". See: http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute(v=vs.110).aspx
What you could do, if you want lesser numbers in the version and also generated version numbers, is to use an external tool altering version numbers in the pre-build step.
Comment: Even if I set "1.0.1", NuGet sees "22.214.171.124" which makes sens since Version is an object with non nullable int members, so "126.96.36.199-test" still generate an error beacue of the extra digit.
Comment: @Jerther Why did you mark this as an answer to your question? It does not solve the problem at all, and is in fact incorrect: nuget will still get 4 digits even if a 3 digit version is specified in the `AssemblyVersion`. I created a [new question about the number of digits issue](http://stackoverflow.com/questions/28194498/nuget-pack-does-not-honor-number-of-digits-on-assembly-version) which I feel is the core problem that would also solve your issue here if fixed.
Comment: `What you could do, if you want lesser numbers in the version and also generated version numbers, is to use an external tool altering version numbers in the pre-build step.` This would not help at all. Even if the attribute has only 3 explicit digits, the nuget parsing process seem to always use all 4 digits.
Comment: the class has a three digits constructor, and the ToString() method even returns a three digits version: http://msdn.microsoft.com/en-us/library/00dkw4kk(v=vs.110).aspx
Comment: You're correct, I was mixing up System.Version and the behaviour of AssemblyVersionAttribute. If you use "1.0.x" in AssemblyVersionAttribute's constructor, both Build and Revision will be generated. I've edited my answer.
Comment: Still, your answer helped me understand. It's an object not a string
Comment: An external tool works. I made one that reads the assembly version which always has four digits and only take the first three and put it in the nuspec.
Answer: No post processing is necessary, NuGet is using [assembly: AssemblyInformationalVersion("")] as a package version, set it to whatever number of componets you please and be done with it.
P.S I strongly encourage you to also set AssemblyVersion as this is the one .NET actually uses, at least set it to auto increment
Some reading available here
Full example
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyInformationalVersion("1.0")]

Will generate a package Lib.1.0.nupkg containing assembly with 1.0.x.x version, version you will be dealing with is 1.0
Whenever you want to change nuget version, just change AssemblyInformationalVersion, not touch AssemblyVersion at all
Comment: You can add the -test postfix :

[assembly: AssemblyInformationalVersion("1.0-test")]


Apache Solr server URI problem

Question: I rebulding solr server after VPS crash, so I'm not completely newbie, but this time something went wrong and I can't manage the problem:
I configuring Apache Solr to use with Drupal. Acoording to may manuals Solr server URI should look like
xx.xx.xx.xx:8983/solr/corename
but my Solr ULR looks like
xx.xx.xx.xx:8983/solr/#/~cores/corename
However, Drupal reports "The Solr server could be reached", but when indexing I get errors:

SearchApiException while deleting items from server New SOLR server:
"400" Status: Bad Request HTTP Status 400 - HTTP method POST is not
supported by this URL The request sent by the client was syntactically incorrect.
SearchApiException: Could not index items since important pending
server tasks could not be perfor

med.
System info: Ubuntu 14, solr 4.7.2, tomcat 7
Comment: You did not say which Solr module for Drupal you are using.
Comment: I wonder why it has been accepted an answer given a year later than another one, and that essentially says the same thing as the older one.
Answer: The URL that the Drupal modules need is different than the one on which you browse the Solr server as an admin. Thus, for you, assuming 8983 is server port, it should be:
xx.xx.xx.xx:8983/solr/corename
Comment: Thank you, this helped me to solve my problem.
Answer: The solution is to put "/solr/corename" in Solr path field ignoring "#/~cores/" part of URL on the Drupal Searh API server configuration page. Then you should press "Clear all indexed data" button on index page, then reindex.
Answer: For Solr 4.x the server's path should also contain the Solr core name.
E.g. when using default example application, set the path to
/solr/collection1 instead of /solr, then it should work.
Related: Upgrade - The Solr server could not be reached at d.o.

Apache Solr server URI problem


Are magerun questions out of scope?

Question: Someone just posted this question : Set default role permissions during Magento installation (magerun ?)
I was just wondering as you guys did some times ago with Magmi. Do we allow magerun questions on Magento SE ?
To me, it sounds off topic but I reckon it's on the edge for some people.
Answer: I stand by my opinion. Off topic. It's a third party module that should be maintained and supported its developers.
Comment: Agreed. You can use the magento community forums for these types of questions.
Comment: Agreed as well - their GitHub issues register is very active and should be used instead.

Are magerun questions out of scope?


Numerically Solve for Parameters Characterizing Lognormal RV that's Truncated from Above

Question: I am trying to numerically solve for parameters characterizing a lognormal distribution truncated from above with first moment = mean, second moment = moment_2, and upper = 99th percentile of the untruncated distibution. This involves solving a constrained non-linear system of 2 equations and 2 unknowns. Currently I am having issues solving these equations numerically, and would appreciate any suggestions on the best solving technique to use.
I am trying to do this in R, and hence have expressed the equations as R functions. The desired parameters logmean and logstd can be recovered by solving the following system of 2 equations and 2 unknowns, which relate the first and second moments of the truncated distribution to the parameters logmean and logstd. Note that these equations have the PDF and CDF for a standard normal random variable in them written as dnorm and pnorm respectively.
mean_fun <-function(mean, logmean, logstd, upper = .99){

    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    return(mean - exp(logmean+logstd^2/2)*pnorm(-logstd+b_0)/pnorm(b_0))
}

second_moment_fun <-function(moment_2, logmean, logstd, upper = .99){
     upper_lim <- qlnorm(upper, logmean, logstd)
     b_0 <- (log(upper_lim) - logmean)/logstd
     return(moment_2 -exp(2*logmean+2*logstd^2)*pnorm(-2*logstd+b_0)/pnorm(b_0))
}

UPDATE: This can be consistently solved using R's nleqslv and by providing the jacobian. These equations and their derivation can also be found at this paper by searching for Example 21.75.
Answer: Here is code that uses nleqslv to solve this problem. It requires defining the jacobian, which is why the code is somewhat lengthy. Here is the code in full, which includes a test example at the bottom.
library("nleqslv")

mean_fun <-function(mean, logmean, logstd, upper = .99){

    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    return(mean - exp(logmean+logstd^2/2)*pnorm(-logstd+b_0)/pnorm(b_0))
}

moment2_fun <-function(moment_2, logmean, logstd, upper = .99){
    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    return(moment_2 -exp(2*logmean+2*logstd^2)*pnorm(-2*logstd+b_0)/pnorm(b_0))
}

d_mean_du <- function(mean, logmean, logstd, upper = .99){
    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    -exp(logmean+logstd^2/2)*(pnorm(-logstd+b_0)/pnorm(b_0)+
                           -dnorm(-logstd+b_0)/(logstd*pnorm(b_0))+
                           pnorm(-logstd+b_0)*dnorm(b_0)/(logstd*pnorm(b_0)^2)
    )
}

d_mean_dstd <- function(mean, logmean, logstd, upper = .99){
    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    -exp(logmean+logstd^2/2)*(pnorm(-logstd+b_0)*logstd/pnorm(b_0)+
                           dnorm(-logstd+b_0)*(-1-b_0/logstd)/pnorm(b_0)+
                           pnorm(-logstd+b_0)*dnorm(b_0)*b_0/(logstd*pnorm(b_0)^2))
}

d_moment2_du <- function(moment2, logmean, logstd, upper = .99){
    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    -exp(2*logmean+2*logstd^2)*(pnorm(-2*logstd+b_0)*2/pnorm(b_0)+
                             -dnorm(-2*logstd+b_0)/(logstd*pnorm(b_0))+
                             pnorm(-2*logstd+b_0)*dnorm(b_0)/(logstd*pnorm(b_0)^2)
    )
}

d_moment2_dstd <- function(moment2, logmean, logstd, upper = .99){
    upper_lim <- qlnorm(upper, logmean, logstd)
    b_0 <- (log(upper_lim) - logmean)/logstd
    -exp(2*logmean+2*logstd^2)*(pnorm(-2*logstd+b_0)*4*logstd/pnorm(b_0)+
                             -dnorm(-2*logstd+b_0)*(-2-b_0/logstd)/pnorm(b_0)+
                             pnorm(-2*logstd+b_0)*dnorm(b_0)*b_0/(logstd*pnorm(b_0)^2)
    )
}

trunc_log_norm_mean_moment2 <-function(x, mean, moment2, upper){
    c(mean_fun(mean, x[1], x[2], upper), moment2_fun(moment2, x[1], x[2], upper))
}

trunc_log_norm_jacob <- function(x, mean, moment2, upper){
    matrix(c(d_mean_du(mean, x[1], x[2], upper),
             d_moment2_du(moment2, x[1], x[2], upper),
             d_mean_dstd(mean, x[1], x[2], upper),
             d_moment2_dstd(moment2, x[1], x[2], upper)),2)

}

mean1 <- 10
moment21 <- 20+10^2
log_normal_m_upper_param_gen <-function(mean, std){
    # takes vector of means and stds and returns inputs needed
    # to enter into R's plnorm and dlnorm functions so that
    # these have the desired means. Returns data.frame with named columns
    # as output
    logstd <- sqrt(log((std/mean)^2+1))
    logmean <- log(mean)-.5*logstd^2
    c(logmean, logstd)
}

initial_guess <- log_normal_m_upper_param_gen(mean1, moment21-mean1^2)
upper <- .99

w <- nleqslv(x=initial_guess, fn=trunc_log_norm_mean_moment2, jac =trunc_log_norm_jacob,
        mean = mean1, moment2 = moment21, upper = upper)

p <- c(qlnorm(.99,w$x[1], w$x[2] ), w$x[1], w$x[2])
mean <- integrate(function(m) m*dlnorm(m, p[2], p[3]/plnorm(p[1], p[2], p[3])), 0, p[1])
moment2 <- integrate(function(m) m^2*dlnorm(m, p[2], p[3]/plnorm(p[1], p[2], p[3])), 0, p[1])


Maximum distance an arm can be extended with a trigonometrical question

Question: This is a past paper multiple choice question that I am attempting and all of the answer sheets says that its $13$ while my answer is $17$. The question is as follows:
"The distance, d meters, of an arm of a shaping machine from its starting position can be modelled by the equation $d=12\cos\theta+5\sin\theta$. The MAXIMUM distance, in metres, from the starting point is: $5, 12, 13,17$."
Isn't the maximum values $\sin\theta$ and  $\cos\theta$ can go up to both $1$ so shouldn't $12*1+5*1=17 $ ? Thank you for your help.
Comment: For some fixed angle $\theta$, $\sin \theta$ and $\cos \theta$ cannot be equal to $1$ at the same time.
Comment: Waw yes that's true! So then the answer is actually $5$ ?
Comment: Can't be $5$, set $\theta = 0$ and you get $\cos(0) = 1$, $\sin(0) = 0$, so have $d=12$. But a larger value can still be produced.
Answer: We have the distance $d$ of the arm as a function of the angle $\theta$, that is:
$$d(\theta) = 12\cos \theta + 5\sin \theta$$
A standard optimization problem. We search for $d'(\theta) = 0$ to find extreme points:
$$d'(\theta) = -12\sin \theta + 5\cos \theta$$
We search for the zeroes, that is:
$$0 = -12\sin \theta + 5\cos \theta$$
$$12\sin \theta = 5\cos \theta$$
$$12\frac{\sin \theta}{\cos \theta} = 5$$
$$12\tan \theta = 5$$
$$\tan \theta = \frac{5}{12}$$
We solve this by using the $\arctan$ function in our calculator and get
$$\theta = \arctan\left(\frac{5}{12}\right) = 0.39479..$$
We plug this value of $\theta$ into $d(\theta)$ and get
$$d(\arctan(5/12)) =13$$
Thus, the answer is $13$, which is in the given choices.
Answer: Or, more quickly:
$d=12cos(\theta)+5sin(\theta)=Acos(\alpha)cos(\theta)+Asin(\alpha)sin(\theta)$
$$A=\sqrt{(12^2+5^2)}=13 $$ $$  \alpha=\arctan{(5/12)}$$
$$d=13cos(\theta-\alpha)$$


Parse loading Image into UIImageView iOS

Question: Here is the code for the data I am passing on to the scene with the image:
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    rowNo = indexPath.row;
    PFUser *currentUser = [PFUser currentUser];
    PFQuery *query = [PFQuery queryWithClassName:@"Photo"];
    [query whereKey:@"username" equalTo:currentUser.username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        _photo = [objects objectAtIndex:rowNo];
    }];

    [self performSegueWithIdentifier:@"showImageCloseup" sender:self];

}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    ImageCloseupViewController *destination = [segue destinationViewController];
    destination.photoObject = _photo;
}
</code>
And here is the code which loads the image:
<code>- (void)viewDidLoad
{
    [super viewDidLoad];
    PFFile *p = [_photoObject objectForKey:@"photo"];
   [p getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
       if(!error){
           UIImage *image = [UIImage imageWithData:data];
           [_imageView setImage:image];
       }
   }];
</code>
For some reason, the image is not loading, why is this is so? How can I fix it?
Answer: This:
<code>[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    _photo = [objects objectAtIndex:rowNo];
}];

[self performSegueWithIdentifier:@"showImageCloseup" sender:self];
</code>
Needs to be:
<code>[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    _photo = [objects objectAtIndex:rowNo];
    [self performSegueWithIdentifier:@"showImageCloseup" sender:self];
}];
</code>
Because:
<code>// Runs 1st - executes in background thread stores block, then runs block once it's done
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    // Runs 3rd - already segued at this point
    _photo = [objects objectAtIndex:rowNo];
}];

// Runs 2nd - starts segue
[self performSegueWithIdentifier:@"showImageCloseup" sender:self];
</code>
However, this seems like there's an overall problem with your design pattern.  If you already have access to objects, you shouldn't have to requery the entire database each time. Do you have a reference to the array populating the tableView?  If so, something like this:
<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    rowNo = indexPath.row;
    _photo = yourDataArray[indexPath.row];
    [self performSegueWithIdentifier:@"showImageCloseup" sender:self];

}
</code>
Comment: cool, this works. I'm trying to accept your answer, but it keeps saying "accept in one minute" lol
Comment: No problem @user3140562  - I made an update at the bottom that you should look at that I think will help you in the long run.  Good luck with the rest of your project!


How much do starting-blocks affect the 60m sprint?

Question: My previous PB in the 60m was 7.21, with blocks. That was about 18 months ago, the other day I ran 60m in 7.47. I've read the blocks can effect the 100m anywhere from .2 - .4, how much will my time change with blocks to you think?
Answer: I don't know, but I know/assume the gain depends on how strong your quads are. The stronger the quads, the faster start and more benefit from blocks or if you start from a lower position with a more flexed knee, without blocks.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to change the constructor initialization value in c++ and explain the reason?

Question: using namespace std;

class Gparent{
    public:
    int house;
        Gparent(){
            house = 1;
            cout<<house<<endl;
        }
    ~Gparent(){
        cout<<"Gparent got killed"<<endl;
    }
};

class Parent: private Gparent{
    public:
        Parent(){
            Gparent::house=2;
            cout<<Gparent::house<<endl;
        }
    ~Parent(){
        cout<<"Parent got kiled"<<endl;
    }
};

int main(){
    Gparent g;
    g.house=100;
}

output:
1
Gparent got killed
why the output is not 100?
I can understand the object creation but bit confused with the initialization part.Could someone help me to understand the concept?
Comment: Not directly related, but nonetheless interesting for beginners: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/430766)
Answer: When you wrote  Gparent g; this means

you are defining an object of type Gparent using the default constructor.

Now you have already provided a default constructor as :
Gparent(){
            house = 1;
            cout<<house<<endl;
        }

So the data member house is assigned a value of 1 and then you print that value using cout. Which is why you get the output 1 since house = 1 at this point.
Next when the object g is destroyed, the destructor is ran/executed and  you get the output Gparent got killed.
So you didn't get the output 100 because the variable house had a value of 1 at the time of using cout.
Note if you use cout after the statement g.house = 100; you will see that its value is changed to 100 and hence 100 is printed on the console.
    Gparent g;
    g.house=100;
    cout << g.house<<endl;//THIS PRINTS 100 now because house = 100 at this point

Answer: See what your code compiles to here. In the main(), this is what it roughly gets compiled to
call    Gparent::Gparent() [base object constructor]
:
mov     dword ptr [rbp - 8], 100
:
call    Gparent::~Gparent() [base object destructor]

It's basically just calling the constructor, so that'll print 1 since that's what house is initialized to and only after that the value of g.house is changed. And then the destructor is called so that'll print Gparent got killed. To see the changed value, you could perhaps change your code to
class Gparent{
    public:
    int house;
        Gparent(){
            house = 1;
            cout<<house<<endl;
        }
    ~Gparent(){
        cout<<house<<" Gparent got killed"<<endl;
    }
};

so that now the updated house member variable is printed during the destruction and you should get
1
100 Gparent got killed


Visual Studio and OpenCV fails to link cv.lib

Question: I downloaded the latest OpenCV-2.4.2.exe and unpacked it. Then I opened a project in visual studio 2010 and pointed it to the include and lib folders that it needs to build.
In my case, the lib folder is in \opencv\build\x64\vc10\lib which is different than the instructions online. This folder seems to contain a compiled version of everything. However, when I build my project, I get
LINK : fatal error LNK1104: cannot open file 'cv.lib'
cv.lib is nowhere to be found.
Is there something else that needs to be compiled?
Comment: Except for pointing to the lib folder, do you actually include the libs? Also, have you included OpenCV in your PATH?
Answer: Well, I solved the issue.
In stdafx.h I had to comment out:
<code>//#pragma comment(lib, "cv")
//#pragma comment(lib, "cxcore")
//#pragma comment(lib, "highgui")
</code>
which were trying to load cv.lib, etc. My guess is this was correct for previous openCV version but isn't valid for 2.4.2. Then I had to add
<code>D:\opencv\build\x86\vc10\lib\opencv_core242d.lib;D:\opencv\build\x86\vc10
\lib\opencv_imgproc242d.lib;D:\opencv\build\x86\vc10\lib\opencv_highgui242d.lib;
D:\opencv \build\x86\vc10\lib\opencv_objdetect242d.lib;
</code>
to my project in the Linker->Input->Additional dependencies part.
I tried the staticlib folder and x64 but this is what worked for me on Windows 7 64-bit.
Hope this helps someone else (I've seen similar issues other people had).


Django - null value in column "author_id" violates not-null constraint (Image uploading)

Question: I am trying to get my head around how to upload and post an image through my Django form. I have sussed out how to post content, but not Images.
At the moment, when I try to upload an image with my Post, the following error is returned:
null value in column "author_id" violates not-null constraint

Views.py
class CreatePostView(LoginRequiredMixin, CreateView):

    model = Post
    fields = ['content', 'image']
    template_name = 'core/post_new.html'
    success_url = '/'

    @login_required
    def post_image(request):

        form=upl()

        if request.method == 'POST':
              form = upl(request.POST, request.FILES)

            upl.save()

        return render(request, 'core/post_new.html', {'form': form})

    def form_valid(self, form):
        form.instance.author_id = self.request.user
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        data['tag_line'] = 'Create new post'
        return data

Models.py

class Post(models.Model):
    content = models.TextField(max_length=1000)
    date_posted = models.DateTimeField(default=timezone.now)
    image = models.ImageField(default='default.png', upload_to='core_media')
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.content[:5]

        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

UPDATED Views.py
class CreatePostView(LoginRequiredMixin, CreateView):

    model = Post
    fields = ['content', 'image']
    template_name = 'core/post_new.html'
    success_url = '/'

@login_required
    def post_image(request):
    form=upl()

    if request.method == 'POST':
          form = upl(request.POST, request.FILES)

    upl.save()

    return render(request, 'core/post_new.html', {'form': form})

    def form_valid(self, form):
        form.instance.author_id = self.request.user
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        data['tag_line'] = 'Create new post'
        return data

Any assistance/direction would be most appreciated. Thank you :)
Comment: indent the `@login_required` properly as a *method* of the class, right now the `form_valid` is a function *inside* the `post_image` function.
Comment: Ah thank you! Sorry everything is a little scattered at the moment, I'm just trying to reference as many tutorials as I can, but I have a habit of putting certain bits of code in the wrong places. I'll try your suggestion now! :)
Answer: The form_valid and get_context_data are here no members of your CreatePostView, but inner functions of the post_image function.
You should implement this as:
class CreatePostView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['content', 'image']
    template_name = 'core/post_new.html'
    success_url = '/'

    #   ↓        ↓ method of the CreatePostView
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    #   ↓              ↓ method of the CreatePostView
    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        data['tag_line'] = 'Create new post'
        return data
Comment: Hello Willem! Thank you for your response! I have updated my original question with an updated Views.py file (based on the code you provided me with) does the format of my code look a little better now? :-) I'll have to buy a you a few coffees if you accept donations :)
Comment: @Jarjar95: exactly what is `post_image(request):` doing here? It looks like a different view.
Comment: Basically, I'm trying to achieve a form which allows you to write text in to the "content" field and at the same time, I want to be able to upload an image which displays together with the post content (within the same form). The "post_image" bit there, is my attempt at trying to get my uploaded image to save. But I think i've got it a little wrong!
Comment: What if you remove the `post_image` method (and the code in that method, and the `@login_required` decorator)?
Comment: So I've just removed the method and the code within (and have also removed the `@login_required` - And my form appears, (The form displays my Content field and Image field) but after I write in some content, upload an image and hit the submit button, I receive this error - IntegrityError -  null value in column "author_id" violates not-null constraint
Comment: @Jarjar95: but the `def form_valid(self, form):` method is still in your `CreatePostView` class? What if you use `form.instance.author = self.request.user` (so *without the `_id` part)?
Comment: That's correct, the `def form_valid(self, form):` method still exists within my CreatePostView class. I've tried removing the `_id` but still get the same error. Here's the exact error: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains (26, sdhsdhdshdsh, 2021-05-25 15:58:01.053625+00, 0, 0, null, default.png)`    (The scrambled bit of writing after where it says 26, is just some dummy content I entered in to the text box)
Comment: @Jarjar95: can you edit the question with the current state of the (entire) view?
Comment: Hey Willem! I finally got it working!!! :-D I noticed that in my forms.py file, I hadn't added `enctype="multipart/form-data"`and I also had a redundant name tag on my form which I removed and the error has gone! Photos are uploading and I've added the relevant template tags for where I want my photos to appear. All is working great, but a huge thanks goes out to you! If i can send any donations your way, please let me know! I will be happy to do so! :-)


This operation requires IIS integrated pipeline mode. when publishing to host

Question: For school we have to publish our sites on a specific hosting they provide.
but when I publish my site to that host. I get the following error:
This operation requires IIS integrated pipeline mode.
I can't change much from my account on the hosting. So is there a way to fix this in the project?
I tried changing it from integrated to classic. but that doesn't change much
It's with MVC version: 22.214.171.124
Comment: On which page are you getting this ?
Comment: All of them. or I didn't found any that doesn't have the error
Comment: So have you changed mode to integrated ?
Comment: Yep, now it's on Integrated. as default when creating a new project
Comment: This needs to be changed on IIS.
Comment: But what makes the project needing this? I have this problem even with a freshly created one
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67665/discussion-between-mairaj-ahmad-and-kiwi).
Answer: You need to change your application pool mode to integrated from IIS.

Open IIS.
Click your server name on top left.
Click on application pools.
Select pool of your website.
Click on Basic settings on right side and change mode to integrated.


How to quit band

Question: So, I have been in this band for 2 years, we have done many rehearsals no live gigs, not a single one, only live Facebook shows, I don't do music full time, but I like it. However, things have changed since the corona virus thing, my country is under lockdown and I am not getting paid by my regular job, because I can't work due to the lockdown. One member of this band is a pop artist and she has big plans, I can't tell if something will come of it or not since there are no gigs. The problem I have is that every time we rehearse to do one of these live shows, she asks me to contribute a large amount of money so that we can party after the show or she wants us to rehearse over a weekend and stay over so that the money can be said to cover our living expenses for the weekend, the thing is at the moment I can't do this because I don't have money, furthermore, I don't get a say in how songs should be done, I am basically just doing it because I love music. I am thinking of quitting should I quit?
Comment: Two years of rehearsals that you helped pay for? Sounds like you should have left a long time ago! There are many 'rehearsal' bands around, that see it as a social occasion rather than 'let's get out and gig'.
Comment: Sounds like you have one member who thinks that in order to become a pop star, you first have to live like one. They are so self-centred that they expect others to pay for this.. This is, to put it bluntly, arse about face. Leave, leave now. Run. Don't look back. Don't apologise, just go, now.
Comment: With Tetsujin all the way. Been there, done it, got the scars. If she ever did make big, she'd most probably ditch the band without a thought (or a thank you).
Comment: If you want or need to quit is up to you. Being in a band is like being in a complicated relationship with multiple people but also like a job. Like any good relationship you must do what is best for you but also talk to your band mates so it is all out in the open. Talk to her, tell her your concerns and try to work things out. If she must have money and you don't have it walk away. But you may come up with a compromise.
Comment: https://interpersonal.stackexchange.com/ This is not exactly about Music. We may be able to give you answers but the whole thing wouldn't fit into MusSE.
Comment: it is generally accepted that the easiest way to kill a band is for someone to get a girlfriend. Tragic kingdom was the exception that proved the rule..
Answer: I'm going to add this an an answer because I think you deserve it in letters bold & large.
Someone is taking you for a ride. They're extracting everything they can from you & offering absolutely nothing in return.
This isn't a band, this is one person's perceived free ride to fame - which they are about 0.1% likely to ever achieve even if they're actually very good.
You have one member who thinks that in order to become a pop star, you first have to live like one. They are so self-centred that they expect others to pay for this…
This is, to put it bluntly, arse about face.
This is not behaviour that a quick band chat after rehearsal is ever going to fix, this is simply delusional behaviour.
Leave, leave now.
Run.
Don't look back.
Don't apologise, just go, now.
Comment: Shouting out the reasons to everyone else as you go!
Comment: @RishiNandha_M - could be (almost) plagiarising I Will Survive?
Comment: And then write Heavy Metal with Tetsujin's Lyrics, Get published before your current band. (Dont take this srsly pls)

How to quit band


python and assigning variable values in if statements

Question: I'm somewhat of a beginner in python and I swear I got a very similar program to what I'm doing right now to work. But, for some reason, I can't make it work. I was able to pinpoint my problem and created a fake program to play around with it. Here is what the program:
global heading
global heading2
global a

heading=2
a=2
heading2=4

def function ():
    if a==2:
        heading=heading2
        print 'yes'
        print heading

function()
print heading

This is what appears:
yes
4
2

Why doesn't the heading variable heading keep the value 4? I tried putting return heading all over. Didn't work. I tried putting the variables in the parentheses of the function. Didn't work either... Do you know what I'm doing wrong?
Answer: global statement is meaningless outside of a function. If you want to modify the global variable, instead of introducing a local one, you need to put global inside the function
def foo():
    global x
    x = x2

Also, don't use globals.
Answer: The line:
    heading=heading2

Creates a new local variable called heading, which is different to the other varaible called heading that you passed into the function.
You can make the function assign to external variables by adding:
global heading

before you assign to heading:
def function():
    global heading
    if a==2:
        heading=heading2
        print 'yes'
        print heading

Answer: Inside function, you are creating a local variable called heading. This isn't the same heading declared outside of the function.


Views 2 - Don't display results if user DOES NOT have a specific permission

Question: I am trying to hide the results of a view from users who have a specific permission. For instance, Let's assume that a user has the permission "create page content". I would like for the view to show NO results to this user.
I can't restrict on roles because the user can have overlapping roles. Basically, I need the "Access" portion of views to work opposite of how it normally does.
I suspect I should be able to do this with the Global:Null argument validator, but I am having no luck. However I am assuming that has more to do with me weak php chops.
Thanks in advance.
Answer: Hook_perm to the rescue! I would suggest thinking the other way around: Grant access to the view's results if the user HAS a permission. Create a new permission and assign it only to the roles that may view the results.
In your custom module, add a new permission like so:
function mymodule_perm() {
    return array('can view results of my view');
}

Then in your view, change the 'Access' setting to your new permission.
You may run into problems if the roles that you're trying to exclude have the 'Access all views' permission (or a similar administrative views permission). If that is the case, you'll need to use a views hook to remove the results.
function mymodule_views_pre_render(&$view) {
  switch($view->name) {
    case 'the_view_name':
      if(!user_access('can view results of my view')) {
        $view->result = array();
      }
    break;
  }
}

I would flush caches in order to have this hook picked up by views.