How do I set the default value of an exposed filter to a value that is not "-Any-"?

Question: I have a view with exposed filters, in Drupal 8. I need to set the default value of a filter to its title or custom text. I also need to unset/remove the - Any - option from the select list.
How can I achieve this?
Here is my code:
<code>    function bootstrap_barrio_subtheme_form_alter(&$form, FormStateInterface
    $form_state, $form_id) {
        if ($form_state['view'] == 'office_locations_doctor_detail') {
            $form['field_doctor_reference_target_id_1']['#default_value'] =
            'Select Doctor';
        }
     }
</code>
Cleared the cache and reload the page but nothing changed.
Comment: Welcome to Drupal Answers!  You can do that by implementing hook_form_alter in a custom module or theme. And then I think you simply have to set the `'#default_value'` of this element. Have you tried that already?
Answer: Try this:
<code>/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function bootstrap_barrio_subtheme_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ( $form_state->get('view')->id() == 'office_locations_doctor_detail'){
     // Set the default value as tid not the name of term.
     // Change 'Select Doctor' by the tid of it.
    $form['field_doctor_reference_target_id_1']['#default_value'] = '1';
    // Remove - Any - option.
    unset($form['field_doctor_reference_target_id_1']['#options']['All']);
  }
}
</code>
Comment: I've achieved this by using Better Exposed Filter module.
Comment: Nothing is changed. Cleared the cache also.
Comment: if nothing changed, make sure that your theme name is `bootstrap_barrio_subtheme` and change the view name from àrticles` to your view name `office_locations_doctor_detail` for example, and make sure also the your field machine name is `field_doctor_reference_target_id_1`
Comment: check my update
Comment: Checked, but no effect.


Given a field $K$, the two ideals $(x^2 ,xy,y^2)$ and $(x,y)^2$ in $K[x,y]$ are the same.

Question: I want to prove that given a field $K$, the two ideals $(x^2,xy,y^2)$ and $(x,y)^2$ in $K[x,y]$ are the same. For the inclusion $(\subseteq)$, it is obvious that $x^2,y^2 \in (x,y)^2$, but how do I have to show that $xy \in (x,y)^2$? If char$K \neq 2$, then I can use that $2xy=(x+y)^2-x^2-y^2$, but I cannot handle the case char$K=2$.
Comment: Note that for an ideal $I$, the ideal $I^2$ is the ideal generated by $\{ a\cdot b : a,b \in I\}$. Clearly $x,y \in (x,y)$.
Comment: @C.Brendel You cannot say about $x^{-1}$ since $K[x,y]$ is a polynomial ring, not a field of rationals.
Comment: Sorry, for no reason whatsoever I thought about adjoining $x,y$ to $K$ when reading $K[x,y]$ and writing my comment. That's a tad embarassing
Answer: You even don't need $K$ to be a field. Any commutative ring would work. First of all, as Daniel recalled, $(x,y)^2$ is the ideal generated by $\{a\cdot b\mid a,b\in (x,y)\}$, which, in particular, means that $(x,y)^2\supsetneq \{a^2\mid a\in(x,y)\}$ and that elements in $(x,y)^2$ are of the form
$$\sum_{i=1}^t (a_ix + b_iy)(c_ix+ d_iy)$$
for some $t\geq1$, $a_i,b_i,c_i,d_i \in K[x,y]$. Therefore, clearly, $x^2,y^2,x y\in(x,y)^2$ and hence $(x^2,x y,y^2)\subseteq (x,y)^2$. Conversely,
$$\sum_{i=1}^t (a_ix + b_iy)(c_ix+ d_iy) = \sum_{i=1}^t a_ic_ix^2 + (b_ic_i + a_id_i)xy + b_id_i y^2\in (x^2,x y,y^2).$$


indiscrete topology

Question: Let X be an infinite set and let $\mathcal T $ be a topology on X.
2) prove that if $\mathcal T $ contains every infinite subset of X, then it is the indiscrete topology.
i think this is untrue, consider $X= \Bbb N $ the indiscrete topology has two sets $\{\emptyset ,\Bbb N\}$  but we have for example $2\Bbb N $ and $\Bbb P $ which are not in the indiscrete topology?
Comment: while indiscreet is a real word, the correct word here is indiscrete   http://www.imdb.com/title/tt0051773/
Comment: spellchecks a ***** but it has nothing to do with math, i had it spelt right it just flagged it.
Comment: The correct conclusion we can actually draw is that $\mathcal T$ is the discrete topology, for which see [this question](https://math.stackexchange.com/questions/60269/if-a-topology-contains-all-infinite-subsets-then-it-is-the-discrete-topology?rq=1).
Comment: thats must be the intended question, thank you i was sure this didnt work!
Answer: If every infinite subset of $X$ is declared open, then this topology is the discrete topology, not the indiscrete one.
To see this, take an arbitrary countably infinite subset $Y$ of $X$. Enumerate the elements of $Y$ as $\{y_1,y_2,\ldots\}$ in such a way that all these elements are distinct (that is, $y_n\neq y_m$ whenever $n,m\in\mathbb N$ and $n\neq m$). Now define
\begin{align*}
Y_{\text{o}}\equiv&\;\{y_n\,|\,n\in\mathbb N\text{ is odd}\}=\{y_1,y_3,y_5,\ldots\},\\
Y_{\text{e}}\equiv&\;\{y_n\,|\,n\in\mathbb N\text{ is even}\}=\{y_2,y_4,y_6,\ldots\}.
\end{align*}
Then $Y_{\text{o}}$ and $Y_{\text{e}}$ are both infinite and they are disjoint.
Take any arbitrary $x\in X$. Then, the sets $Y_{\text{o}}\cup\{x\}$ and $Y_{\text{e}}\cup\{x\}$ are both infinite and thus open, and the only common element in them is $x$. The intersection of these two sets, which is $\{x\}$, is therefore open.
It follows that every singleton is an open set, so that the topology must be the discrete one.
Comment: I mean i would of taken a simple yes the question is incorrect but proving its discrete is enough to shows its not indiscrete so i will give it to you.
Comment: @Faust Actually, the discrete and the indiscrete topology are one and the same if $X$ consists of only one element. Thank you for the accept! :-)

indiscrete topology


Extract gpg fingerprint

Question: I'm trying to extract the fingerprint from a key in my keyring and I can't figure out how to parse the output.
Running
gpg --fingerprint 'Identifier'

Outputs
pub   rsa3072 2021-12-14 [SC]
      ABCD EFGH 1234 5678 ABCD  ABCD EFGH 1234 5678 ABCD
uid           [ unknown] First Last (Identifier) <email@example.com>
sub   rsa3072 2021-12-14 [E]

I want to extract the short or long fingerprint ABCD EFGH 1234 5678 ABCD  ABCD EFGH 1234 5678 ABCD
Adding a --with-colons to the call ends up printing multiple fingerprints
...
fpr:::::::::ABCDEFGH12345678ABCDABCDEFGH12345678ABCD:
...
fpr:::::::::1234123412341234123412341234123412341234:

What is the best method for extracting the fingerprint for a public and secret key in my key ring?
gpg --version
gpg (GnuPG) 2.2.27

Answer: Using sed
$ gpg --fingerprint | sed -n '/^\s/s/\s*//p'
ABCD EFGH 1234 5678 ABCD  ABCD EFGH 1234 5678 ABCD

-n - Silence the output
/^\s/ - Match lines that begin with a space
s/\s*//p - Remove the leading spaces. Print.

Extract gpg fingerprint


Is there an easy expression for multiplicative inverses in $\mathbb Z_p$?

Question: I know that in arbitrary division rings, one can go about finding inverses Euclidean division. But take $\mathbb Z_{11}$ as a simple example. Is there a "nice" expression which yields the inverses in general? i.e. an expression $e(n)$ such that
$$
e(1) = 1, \quad
e(2) = 6, \quad
e(3) = 4, \quad
e(4) = 3, \quad
e(5) = 9, \quad
e(6) = 2, \quad
e(7) = 8, \quad
e(8) = 7, \quad
e(9) = 5, \quad
e(10) = 10,
$$
all up to mod 11.
I tried polynomial interpolation, but ended up with this ugly thing:
$$-\frac{7 x^9}{2160}+\frac{77
   x^8}{480}-\frac{4279
   x^7}{1260}+\frac{28919
   x^6}{720}-\frac{4653
   x^5}{16}+\frac{1911679
   x^4}{1440}-\frac{4091593
   x^3}{1080}+\frac{2321143
   x^2}{360}-\frac{1229503
   x}{210}+2123,$$
which isn't surprising, given the points it should pass through:

Naturally this does not account for modulo 11, so probably one can get something better if polynomial interpolation can be adapted up to mod 11. Or maybe the expression isn't a polynomial at all, maybe it can include a factorial term? I'm mentioning this because I tried to play around with Wilson's theorem but this didn't yield anything immediately useful.
Comment: To find inverses, you need the extended Euclidean algorithm in general. Only in special cases, they can be found easier.
Comment: For small $a$ we can give an explicit formula (closed form)  for $\,a^{-1}\bmod n\,$ using Inverse Reciprocity, e.g. I do that [here](https://math.stackexchange.com/a/191201/242) for $\,a = 5.\,$ But generally this involves about $\ a/2\,$ cases so it is not practical for large $\,a.$ $\ \ $
Answer: Yes, there is a nice and simple polynomial (over the field $\mathbb F_p$): namely,
  $$ x \mapsto x^{p-2}. $$
If you want to map the integers $[0,p-1]$ to themselves, combine this with the fractional part function:
  $$ x\mapsto p\left\{\frac{x^{p-2}}{p}\right\}. $$
Comment: Yes that is indeed a simple formula ! More generally, the inverse of $a$ mod $m$ when $\gcd(a,m)=1$ is $a^{\phi(m)-1}$. But, for large $p$, it is slower than the Euclidean Algorithm as a means of calculating $a^{-1}$.
Comment: @DerekHolt, if we use square-and-multiply as an algorithm for computing the power mod $p$, it only takes $O(\log p)$ steps, I think.
Comment: @paulgarrett That's true, but according to the discussion [here](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) it is still slower than using the extended euclidean  algorithm.
Comment: Of course, because $\mathbb F_p\setminus \{0\}$ is a group! I can't believe I missed this. Thank you.


How to fetch data from a JSON file?

Question: In work on a project I use Next.js. How can I get data from a JSON file (mainMenu) and display it on the screen? What am I doing wrong?

function MyApp({ Component, pageProps, props }) {
  const newProps = Object.entries(props)
  console.log(props)
  return (
    <>

              {newProps.map((item) =>
                item.map((elem) => (

                    <Link href={`/${elem.url}`}>
                      {elem.label}
                    </Link>

                ))
              )}

            <Input />

      <Component {...pageProps} />
    </>
  )
}

MyApp.getInitialProps = async (ctx) => {
  const res = await axios.get(`${url}/global`)
  console.group(res)
  return { props: res.data }
}

export default MyApp

Comment: Thank you for getting the res.data.mainMenu do I need to fix it? I am trying to get mainMen.label, mainMenu.url
Answer:
Pass res.data.mainMenu instead of res.data in getInitialProps.
Object.entries and nested maps are not required as mainMenu is an array.

Final Code:
const MyApp = ({ Component, pageProps, mainMenu }) => (
  <>

            {mainMenu.map(elem => (

                <Link href={`/${elem.url}`}>
                  {elem.label}
                </Link>

            ))}

          <Input />

    <Component {...pageProps} />
  </>
)

MyApp.getInitialProps = async () => {
  const res = await axios.get(`${url}/global`)
  return { mainMenu: res.data.mainMenu }
}

export default MyApp

Comment: @Cracker please accept the answer by pressing the grey tick if it helped you.

How to fetch data from a JSON file?


Sliderbar with 3 word choices

Question: Aloha, so I got this idea of adding a slide bar with 3 choices and save it as post, but I don't know how to make both of them, please help me.
I've included a picture of what I'm trying to achieve.:)

Thanks a lot:)
Comment: do you have any code to show?
Comment: no if I had I would have done so mate...
Answer: You can use html5's input type="range" for the slider and add some positioned strings on top of it. Then you only need to get the value and save it.
Demo: http://jsfiddle.net/uh4x4wcv/
Comment: Hi k-nut, I have made this code:

 bad
 ok
 best
Comment: Yes this is because the values that the slider has are actually 1,2 and 3. You will have to map those to your ratings on the server.

Sliderbar with 3 word choices


Difference in log base for cross entropy calcuation

Question: I have started going through the TensorFlow tutorials here and I have a small question about the cross entropy calculations. Most places I have seen cross entropy calculated using base 2 log, but the tf.log is base e. Under what conditions would using one log base be preferred over the other?
Comment: Makes no difference if used consistently.
Answer: log base e and log base 2 are only a constant factor off from each other:
$$\frac{\log_e{n}}{\log_2{n}} = \frac{\log_e{2}}{\log_e e} = \log_e 2$$
Therefore using one over the other scales the entropy by a constant factor. When using log base 2, the unit of entropy is bits, where as with natural log, the unit is nats.
One isn't better than the other. It's kind of like the difference between using km/hour and m/s.
It is possible that log base 2 is faster to compute than the logarithm. However, in practice, computing cross-entropy is pretty much never the most costly part of the algorithm, so it's not something to be overly concerned with.


How to handle count type features in survival regression?

Question: I want to understand how to model 'count' or 'customer behaviour' type features in survival analysis.
For example, assume that Netflix wants to predict time to churn after a customer upgrades to a Premier subscription by using a Cox Proportional Hazards survival regression.
Say the training data looks like this as at an observation date of 2022-08-23, with customers 2 and 3 right-censored.

ID
Premier upgrade date
Churn date
Movies watched per week prior to Premier
Movies watched per week since Premier

1
2022-03-01
2022-05-01
10
1

2
2022-08-22
NULL
0
6

3
2022-07-01
NULL
1
20

4
2022-07-01
2022-08-01
20
1

The number of movies a customer has watched per week since upgrading to Premier is likely to be a good indicator of whether they will churn.

Can I just plug this covariate in to the model the same way I would plug in a covariate such as gender? Does it need to be treated a special way / treated as a time-varying covariate?

Am I allowed to use customer behaviour data before they upgraded to Premier in the model? For example, can I use the ratio of number of movies after Premier upgrade / number of movies before Premier upgrade as an input to predict churn duration after upgrading to Premier?
Answer: So long as you respect causality with respect to covariates (that is, you can't use future values of covariates to explain current survival) and you provide corresponding covariate values for all those at risk at any event time,* then you are allowed to try any covariate that makes sense based on your understanding of the subject matter.
The trick in this context is the second part of that restriction: "provide corresponding covariate values for all those at risk at any event time." With this type of data that necessarily means time-varying covariate values that are updated for all at-risk individuals at each event time (whether their own event times or someone else's).
To summarize: for question 1, yes, you need to use a model that allows for time-varying covariate values; for question 2, if the covariate value is in place no later than the time of the churn event then you can consider it.

*Be careful in using the word "event" in survival analysis contexts. That's usually taken to mean the event of interest, the churn event in this context. You're using "number of events" to mean something else, like how many movies were watched. That confused me a bit at first in reading this question. It's better to use some more generic term like "count variable" for candidate predictors. In this answer I use "event time" to mean the time at which the churn occurs.


Direction of a one sample Wilcoxon signed rank test

Question: I am comparing a selection of values which come from a non-normal distribution to 0. I've done a wilcoxon in python:
result = scipy.stats.wilcoxon(values)

my W is positive and huge (> 10000) and my p value is < .001.
My question is how do I tell which of my two tails the data is in? Is it sufficient to just check their means/medians or?
Answer: The reference for the function can be found here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.wilcoxon.html
They recommend using the function a second time for a one-sided test as in
from scipy.stats import wilcoxon
d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75]

w, p = wilcoxon(d, alternative='greater')

The possible values for alternative are {"two-sided", "greater", "less"}
Comment: The return value `statistics` is `the sum of the ranks of the differences above or below zero, whichever is smaller`. "Whichever is smaller" erases the information you seek. Writing your own function to compute the ranks of values above or below zero should be doable, if you can find no better function in scipy. `scipy.stats.rankdata` can produce the ranks, which you will then have to filter and sum.
Comment: Working in an environment where I'm not allowed to be past scipy 1.2.1 at work. This isn't an option in the old scipy and I was wondering if there's any way to just interpret it from the result?


Prove that $AD\cdot BD \cdot CD \leq \dfrac{32}{27}$ where $ABC$ is a triangle of circumradius 1 and $D\in (BC)$.

Question:
Let triangle $ABC$ of circumradius $1$ and $D$ a point on side $(BC)$.
  Prove that $$AD\cdot BD\cdot CD\leq \dfrac{32}{27}.$$

My idea. By letting $\alpha = \dfrac{BD}{BC}$ (of course $0<\alpha <1$) we get $BD=BC\cdot \alpha
, \enspace CD=BC\cdot(1-\alpha)\tag{1}$ and also
$$\overrightarrow{AD}=(1-\alpha)\cdot\overrightarrow{AB}+\alpha\cdot \overrightarrow{AC}.$$
By squaring this relation we have that $$AD^2=AB^2(1-\alpha)+AC^2\alpha+BC^2(\alpha^2-\alpha). \tag{$2$}$$
By law of sines we also have $AB=2\sin C$, $AC=2\sin B$ and $BC=2\sin A$.
Now combining with $(1)$ and $(2)$ we may rewrite the desired inequality as follows:
$$((1-\alpha)\sin^2C+\alpha\sin^2B+(\alpha^2-\alpha)\sin^2A)\cdot\alpha^2(1-\alpha)^2\sin^4A\leq \dfrac{2^4}{27^2}.$$
This is where I got stuck. Maybe we could also use the fact that $\sin A=\sin (\pi -B-C)=-\sin(B+C)=-(\sin B\cos C+\sin C\cos B)$ to get rid of $\sin A$?
Thank you in advance!
Comment: I'm not sure about (2).
Comment: Maybe I got some computations wrong. It happens pretty often. Sorry.
Comment: See also here: https://math.stackexchange.com/questions/1380999
Answer:
It is a really bad practice to ask a geometry problem without a picture.
Let $OD = x.$ Then $BD\cdot CD = 1 - x^2.$ If $\angle AOD = \alpha,$ then:
$$AD^2 = 1+x^2-2x\cos\alpha.$$
So you need to prove:
$$(1-x^2)\sqrt{1+x^2-2x\cos\alpha}\leq\dfrac{32}{27}.$$
But this is just AM-GM:
$$(1-x^2)(1+x^2-2x\cos\alpha)^{\frac 12}\leq(1-x^2)(1+x)=4(1-x)\cdot\dfrac{1+x}{2}\cdot\dfrac{1+x}{2}\leq 4\cdot \left(\dfrac{2}{3}\right)^3 = \dfrac{32}{27}.$$
Comment: Btw, what software did you use for this picture? Thanks.
Comment: @AlexeyBurdin it's just geogebra.
Answer:
Just some work, that was too big for a comment.

Well, when we have a $\triangle\text{ABC}$:

We know that:
$$
\begin{cases}
\angle\alpha+\angle\beta+\angle\gamma=\pi\\
\\
\frac{\text{a}}{\sin\left(\angle\alpha\right)}=\frac{\text{b}}{\sin\left(\angle\beta\right)}=\frac{\text{c}}{\sin\left(\angle\gamma\right)}\\
\\
\text{a}^2=\text{b}^2+\text{c}^2-2\text{b}\text{c}\cos\left(\angle\alpha\right)\\
\\
\text{b}^2=\text{a}^2+\text{c}^2-2\text{a}\text{c}\cos\left(\angle\beta\right)\\
\\
\text{c}^2=\text{a}^2+\text{b}^2-2\text{a}\text{b}\cos\left(\angle\gamma\right)
\end{cases}\tag1
$$
We also know that the circumradius of that triangle is given by:
$$\text{R}=\frac{\text{a}\text{b}\text{c}}{\sqrt{\left(\text{a}+\text{b}+\text{c}\right)\left(\text{b}+\text{c}-\text{a}\right)\left(\text{a}+\text{b}-\text{c}\right)}}\tag2$$

So, when $\text{R}=1$ we know that:
$$\text{a}\text{b}\text{c}=\sqrt{\left(\text{a}+\text{b}+\text{c}\right)\left(\text{b}+\text{c}-\text{a}\right)\left(\text{a}+\text{b}-\text{c}\right)}\tag3$$
Which is the same as:
$$\text{a}^2\cdot\text{b}^2\cdot\text{c}^2=\left(\text{a}+\text{b}+\text{c}\right)\left(\text{b}+\text{c}-\text{a}\right)\left(\text{a}+\text{b}-\text{c}\right)\tag4$$
Comment: You missed one factor
Answer:
Let $M$ the second intersection of $AD$ and the circumcircle of triangle $ABC$. By power of a point, $BD \cdot DC=AD\cdot DM$. Let $x=AD$ and $y=DM$. The inequality can be rewritten as $$x^2y\leq \dfrac{32}{27}.$$
It is clear that $$(x-2y)^2(4x+y)\geq 0$$ which is equivalent to $$x^2y\leq (x+y)^3\cdot \dfrac{4}{27}$$ and combining with $x+y\leq 2$ (which is true as $x+y=AM$ is not greater than the diameter of the circle) we get the conclusion.


How to create a custom resource with Services-3.x

Question: Drupal 7.9
I have installed Services 3.x module and can successfully access nodes etc using the rest server e.g. http://api.domain.com/api/rest/node/6.xml. I now wish to create a custom resource and am having difficulty understanding how to do that correctly. I have followed the much-quoted tutorials on this which all seem to be based on the same example: http://drupal.org/node/783460 and am struggling to understand hook_services_resources. For example:
<code>   'note' => array(
     'retrieve' => array(
       'help' => 'Retrieves a note',
       'file' => array('file' => 'inc', 'module' => 'noteresource'),
       'callback' => '_noteresource_retrieve',
       'access callback' => '_noteresource_access',
       'access arguments' => array('view'),
       'access arguments append' => TRUE,
       'args' => array(
         array(
           'name' => 'id',
           'type' => 'int',
           'description' => 'The id of the note to get',
           'source' => array('path' => '0'),
           'optional' => FALSE,
         ),
       ),
     ),
</code>
Where are the available values for these arrays? For example what are the valid options for source in the args array? I've seen the following: array('path' => '0'), 'data', array('param' => 'page'), 'param'. Where can I find a reference for how this needs to be defined?
To give a bit more information about what I want to achieve, we have a custom form that accepts a series of parameters and returns a set of html-formatted data. The form calls this function:
  return account_manager_search_accounts($billing_party, $other_party, $date_from, $date_to, $billing_id);
}
My idea is to allow users to retrieve the appropriately formatted data (e.g. json, xml) RESTfully and it seemed Services was the right way to do that.
Something like:
<code>function account_manager_services_resources() {
  return array(
   'records' => array(
     'retrieve' => array(
       'help' => 'Retrieves records',
       'file' => array('file' => 'inc', 'module' => 'account_manager'),
       'callback' => '_account_manager_records_retrieve',
       'access callback' => 'user_access',
       'access arguments' => array('view records'),
       'access arguments append' => TRUE,
       'args' => array(
         array(
           'name' => 'billing_party',
           'type' => 'varchar',
           'description' => 'The billing party',
           'source' => what should go here,
           'optional' => FALSE,
         ),
         array(
           'name' => 'other_party',
           'type' => 'int',
           'description' => 'The other party',
           'source' => what should go here,
           'optional' => FALSE,
         ),
       ),
     ),
   ),
  );
}
</code>
Then I'm not even sure what the URL would be for this. Would it be something like: ./api/rest/account_manager/records
Any suggestions or advice appreciated.
Answer: All the documentation for the hook is in the services.services.api.php file included with the module. The args array is:

an array describing the arguments which should be passed to this resource when it is called. Each element in the array is an associative array containing the following keys:

name: The name of this argument.
type: The data type of this argument (int, string, array)
description: Text describing this argument's usage.
optional: A boolean indicating whether or not this argument is optional.
source: Where this argument should be retrieved from. This can be 'data' (indicating the POST data), 'param' (indicating the query string) or 'path' (indicating the url path). In the case of path, an additional parameter must be passed indicating the index to be used.
default value: this is a value that will be passed to the method for this particular argument if no argument value is passed

There are a fair few examples in that file it might be worth giving them a read through, although the API documentation does actually specifically refer to the link you posted above as a detailed example of creating a new resource.
Comment: Thanks that's useful. Are you able to point me in the direction of information about debugging? Debugging is turned on here: ./admin/structure/services/list/rest_api
Answer: If you look at services.services.api.php
It looks like this.
https://gist.github.com/1b4a1bdef433cad8b142


Criar componentes html CodeIgniter

Question: Estou usando CodeIgniter e não sei como criar componentes para embutir nas minhas views. Acho que devo criar meus componentes usando templates, correto? Tenho muitos códigos repetidos nas views mas vi que, usando parser, o consumo de recursos no servidor aumenta muito. O que posso fazer para aumentar a reutilização de código no meu projeto?
Answer: Sim, usar templates é bom, e há uma resposta excelente aqui. Mas o uso de templates pras views não implementa propriamente componentes HTML. Siga a orientação na indicação e adicione o mecanismo de templates. Vai ajudar a incrementar a reutilização de código, principalmente se vc tem seções diferentes dentro do sistema.
Componentes criados com helpers
Para implementar componentes, sugiro usar um helper. Particularmente, o HTML Helper. Carregue-o na aplicação usando o Autoload.
Dentro de application/config/autoload.php, procure por $autoload['helper'] e acrescente o helper html na lista:
$autoload['helper'] = array('html');

Crie/extenda application/helpers/MY_html_helper.php e insira o seguinte:
if( ! function_exists('bootstrap_alert')){

    function bootstrap_alert($class=null, $msg=null){
        $ci = & get_instance();
        echo '
';
        echo '<button type="button" class="close" data-dismiss="alert"';
        echo 'aria-label="Close">×</button>';
        echo $msg;
        echo '
';
    }

}

Pronto. Com a function bootstrap_alert() eu criei um componente Alert da biblioteca CSS Bootstrap v3.3.7. Agora é só chamar bootstrap_alert() em qualquer view passando a $msg e a $class CSS desejada que essa estrutura será mostrada.
Isso vale para, literalmente, qualquer tipo de componente HTML que vc precisar criar.
Componentes a partir de arquivos físicos
Pode ser necessário carregar componentes a partir de modelos gravados no servidor. Modais, por exemplo, podem ser carregados para o documento HTML e manipulados com JavaScript para criar interações com o usuário. Segue a função:
if( ! function_exists('load_modal')){

    /**
     * Carrega conteudo de arquivos no corpo do documento HTML;
     * @return void
     */
    function load_modal() {
        $path = APPPATH . "views/modal/";
        if (file_exists($path)) {
            $iteractor = new DirectoryIterator($path);
            foreach ($iteractor as $entry) {
                if ($entry->isFile()) {
                    $exts = ['php'];
                    if (in_array($entry->getExtension(), $exts)) {
                        include_once($path.$entry->getFilename());
                    }
                }
            }
        }
    }
}

Basicamente, todos os arquivos .php que vc salvar dentro do diretório $path serão carregados para o HTML no local em que a function load_modal() for chamada (o que pode ser imediatamente após , por exemplo). Sabendo disso, dentro de $path, salve o arquivo modal.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$ci = & get_instance();
?>

    <form class="form-horizontal" method="post" action="<?= base_url('users/modal_alert') ?>">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                        Aviso

                    <button type="button" data-dismiss="modal" class="btn btn-default" id="modal_alert_cancel_button">
                        Fechar
                    </button>

    </form>

Escolhi salvar como .php por que posso precisar/querer que esse modal imprima algum item de configuração, algum dado do banco, ou qualquer outra coisa (no caso, usei base_url('users/modal_alert') na action do formulário). Mas isso não é obrigatório, como você pôde ver na função acima.
Isso vale para, literalmente, qualquer tipo de componente HTML que vc precisar criar a partir de arquivos pré-formatados.
Comment: Excelente, muito obrigado, irei fazer um teste.
Comment: Perfeito!, funcionou!, obrigado...

Criar componentes html CodeIgniter


Quickfix Socket Error: Connection reset by peer c++

Question: I'm getting a "Socket Error: Connection reset by peer" message using the tradeclient c++ demo code from the quickfix download.
another user commented that it was related to network issues. if anyone has the solution it would be appreciated.
QuickFix C++ Socket Error Connection Reset By Peer?
<20141221-17:32:11.049, FIX.4.4:myusername->hostusername, event>
      (Created session)
    <20141221-17:32:11.056, FIX.4.4:myusername-> hostusername, event>
      (Connecting to fix.hostusername.com on port 5001)
    <20141221-17:32:11.221, FIX.4.4:myusername-> hostusername, outgoing>
      (8=FIX.4.49=10735=A34=149=myusername =20141221-17:32:11.21856= hostusername    98=0108=30141=Y10=000)
    <20141221-17:32:11.221, FIX.4.4:myusername-> hostusername, event>
      (Initiated logon request)
    <20141221-17:32:11.253, FIX.4.4:myusername-> hostusername, event>
      (Socket Error: Connection reset by peer.)
    <20141221-17:32:11.253, FIX.4.4:myusername-> hostusername, event>
      (Disconnecting)

think i found the reason. the host I'm trying to connect with is using quickfix java which supports SSL. the quickfix c++ client doesn't seem to support the SSL enable tag in the session settings. finally had to resort to wireshark to determine this. i searched all over the web and many people were reporting this similar error. i hope this post saves them any anyone in the future from debugging endlessly to solve this "Socket Error: Connection reset by peer" error.
Comment: There is no one solution. Better is debug and figure out, which is the easiest and quickest way, rather than asking people to guess your issue.
Answer: Two reasons I am aware of for "Socket Error: Connection reset by peer" are:-
1) Your SenderCompId/TargetCompId does not match with that of other side. In that case just make sure you are using correct one.
2) Other one is that sequence number expected by server is something different what you are sending. In that case just try with ResetOnLogon field ( in your registry file )to No and check if that resolves the issue.
There can be many reasons for this error. However, I doubt it that network is responsible for this error as connection request has been sent to server properly. You could search through the internet for wider range of answers.
Answer: Could well be firewall, have you the right IP and port, and permission to get there?
Answer: think i found the reason. the host I'm trying to connect with is using quickfix java which supports SSL. the quickfix c++ client doesn't seem to support the SSL enable tag in the session settings. finally had to resort to wireshark to determine this. i searched all over the web and many people were reporting this similar error. i hope this post saves them any anyone in the future from debugging endlessly to solve this "Socket Error: Connection reset by peer" error. – geiger zaehler
Answer: We got this error message when we had not correctly imported the security certificate.


hyper-v pass-thru disks fail after migration or host reboot

Question: I'm running a Hyper-V 2008R2 cluster with iSCSI backed storage. I'm using a mix of Cluster Shared Volumes for most VM's, but I use a couple pass-thru disks to iSCSI volumes for some larger data volumes.
The pass-thru volumes are frequently being mounted on the host and assigned a drive letter. This causes the volume to become unavailable in the guest. Sometimes I can manually remove the drive letter from the host and add it to the guest and the volume works again, but this doesn't always work. I can reliably reproduce this problem by live migrating the guest to a different host or rebooting the host.
Answer: The problem is the way the pass-thru disk was configured. If you add the disk to the cluster resource that represents the guest manually, the host server will mount the volumes on the disk before bringing the guest online. This renders the disk unavailable inside the guest.
You can verify that you have this problem by looking at "Services and Applications" in the Failover Cluster Manager. Looks at the VM guest and find the list of "Disk Drives". If the "File System" is listed as NTFS, then the host has the volume open. If the "File System" is <unknown> then the volume is already configured correctly.
The correct sequence for adding a pass-thru disk to a highly available VM (i.e., guest running on a clustered Hyper-V host) is a follows:

Present the storage to the cluster. (Configure the iSCSI session, etc.)
Open Disk Management.

If this is a blank disk, right-click the disk and pick Initialize. Right-click again and take it Offline.
If this disk already has data on it that you want to preserve, right-click the disk and bring it Online, then right-click again and take it Offline.

Open the Failover Cluster Manager and navigate to Storage.
Click "Add a Disk" and select the disk.
Right-click the disk and pick Properties. Name the disk something useful. Also note the disk name above the volume list. You'll need this name later. (In this example, the disk is named Disk5.)

Go to "Services and Applications" in the Failover Cluster Manager console and find your VM. Alternatively, open the Hyper-V management console.
Right-click the VM and pick Settings.
If the VM doesn't already have one, add a SCSI controller.
Add a new disk to the SCSI controller. Select the "Physical hard disk" option. Choose the disk name your found in step 5. Click OK.
Complete the disk configuration inside your guest.

If you already have a volume configured incorrectly and you want to fix it:

Shut down the guest.
Remove the pass-thru disk from the VM configuration.
Remove the disk resource from the VM in the "Services and Applications" screen of the Failover Cluster Manager console.
Open the VM configuration and add the pass-thru disk back. (See steps 5-10 above.)


Adding vector fields

Question: Consider two vector fields:
$$ \vec F_1=(\sin(x),\sin(y)) $$
$$ \vec F_2=(\sin(1-x),\sin(y)), $$
where $x,y \in(0,\pi).$
Does adding the two superimposed vector fields produce a net vertical flow, $\vec F_3$?
$$ \vec F_1+\vec F_2=\vec F_3 $$
What does $\vec F_4=\vec F_1 \times \vec F_2$ look like?
Can I see a picture of all four vector fields?
Thanks.
Answer: Wolfram|Alpha can answer all of your questions, I think.
Picture of $\vec F_1$
vector plot (sin(x),sin(y)) for x from 0 to pi and y from 0 to pi

Picture of $\vec F_2$
vector plot (sin(1-x),sin(y)) for x from 0 to pi and y from 0 to pi

(Are you sure you didn't want $\sin(\pi-x)$ instead of $\sin(1-x)$?)
Picture of $\vec F_3=\vec F_1+\vec F_2$
vectorplot (sin(x),sin(y))+(sin(1-x),sin(y)) for x from 0 to pi and y from 0 to pi

Picture of $\vec F_4=\vec F_1\times\vec F_2$
For this we have to be careful. The main definition of cross product does not apply to 2D vectors like these. However, if we treat $\vec F_1$ and $\vec F_2$ as 3D vectors with third component $0$, then we can take their cross product as normal, and it's somewhat common to do so. We'd get $\left(0,0,\sin(x)\sin(y)-\sin(1-x)\sin(y)\right)$. Since all of the values of the cross product are multiples of $(0,0,1)$, we may as well just take the number in the third component, which is occasionally called the "scalar cross product" of 2D vectors. This is Wolfram|Alpha's default interpretation, as in their vector algebra examples.
With this in mind, the plot will just be of that scalar function (you could pretend there are "up" and down arrows from the $xy$ plane to the plot, if you prefer), and we get:
vectorplot cross((sin(x),sin(y)),(sin(1-x),sin(y))) for x from 0 to pi and y from 0 to pi
Comment: Thanks, yes I actually did want $\sin(\pi-x)$ but didn't realize until now. That would make $\vec F_3$ vertical right
Comment: @Ultradark While it would be good practice for you to get Wolfram|Alpha to show you the answer, it's also good to review your basic trig. How does $\sin(\pi-x)$ relate to $\sin(x)$? What does that do to the $x$ components of $\vec F_1+\vec F_2$?

Adding vector fields


Is holding the wall or bouncing up off the bottom legal in water polo?

Question: Is it okay to hold the edge of the pool or touch the bottom of the pool during a game of water polo?
The pool I will play in is 2 metres deep and I'm 1.89 metres tall so that's why I thought of the bottom.
I read that it's illegal to push off the wall, which is fine because that gives you an advantage. Is it okay to hold on to it if you're just tired?
This isn't really a very high level of competition either, if that makes a difference.
Answer: From FINA WATER POLO RULES:

WP 20 ORDINARY FOULS

WP 20.1 It shall be an ordinary foul to commit any of the following offences (WP 20.2 to WP 20.17), which shall be punished by awarding of a free throw to the opposing team.
WP 20.4 To hold or push off from the goal posts or their fixtures, to hold or push off from the sides or ends of the pool during actual play or at the start of a period.
WP 20.5 To take any active part in the game when standing on the floor of the pool, to walk when play is in progress or to jump from the floor of the pool to play the ball or tackle an opponent. This Rule shall not apply to the goalkeeper while within the goalkeeper's 5 metre area.

WP 21 EXCLUSION FOULS

WP 21.1 It shall be an exclusion foul to commit any of the following offences (WP 21.4 to WP 21.18) which shall be punished (except as otherwise provided by the Rules) by the award of a free throw to the opposing team and the exclusion of the player who committed the foul.
WP 21.4 For a player to leave the water or sit or stand on the steps or side of the pool during play, except in the case of accident, injury, illness or with the permission of a referee.

Read WP 24 PERSONAL FOULS
WP 25 ACCIDENT, INJURY AND ILLNESS

WP 25.1 A player shall only be allowed to leave the water, or sit or stand on the steps or side of the pool during play in the case of accident, injury, illness or with the permission of a referee. A player who has left the water legitimately may re-enter from the re-entry area nearest his own goal line at an appropriate stoppage, with the permission of a referee.

Is it ok to hold the edge of the pool during a game of Water polo?

No, it is not ok to hold the edge of the pool except in the case of accident, injury, illness or with the permission of a referee. (see WP 21.4)

Is it ok to touch the bottom of the pool during a game of Water polo?

No, it is not ok to take any active part in the game when standing on the floor of the pool, to walk when play is in progress or to jump from the floor of the pool to play the ball or tackle an opponent. (see WP 20.5)


Redirecionamento de página jsp usando SpringFramework

Question: Olá!
Estou com seguinte problema em fazer um redirecionamento da página index.jsp para página de login.jsp, no tomcat só aparece que essa página não foi encontrada, ERRO 404. Se alguém puder ajudar, estou usando  e estudando Spring, talvez tenha algo diferente das páginas jsf.
Index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

    <title>Index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Aguarde...

    <c:redirect url="login/login.jsp"/>

login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Tela de Login</title>

Testando....

application-context.xml
<context:component-scan base-package="com.gervasios.sgr" />

    <mvc:annotation-driven/>

    <mvc:view-controller path="/" view-name="index"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="true" version="3.0">
    <display-name>sgr-application</display-name>

    <servlet>
        <servlet-name>Spring-Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/application-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Spring-Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Usando o spring eu tenho que usar somente páginas jsp ?
Comment: Você já tentou fazer  `` ou ``
Comment: Obrigado pela resposta MiguelCPJava, respondi minha pergunta com a solução.
Answer: Tive que apagar todo código jsp da minha página de index e deixar somente esse trecho.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="/login"/>


Combine two content types in one using search api views

Question: I am using search api views for site search.
I have 4 content types A, B, C and D.
In the views filter when I expose a content type filter, it display as following on the search page
All
A
B
C
D

I want to combine the C and D content types.
All
A
B
Combined

Where Combined will be a custom text and when click , it should filter the content with Content type C and D.
Is it possible with search api or is there any workaround?
Answer: You have to:
1) allow multiselect for the field;
2) implements hook_form_views_exposed_form_alter and edit the filter - replace 2 values on new value and in validate function to replace back.
Example for the simple field:
/**
 * implements hook_form_views_exposed_form_alter
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){

        $form['#validate'][] = 'MYMODULE_form_views_exposed_form_validate';

        $form['field_your_field_value']['#multiple'] = false;
        $form['field_your_field_value']['#size'] = 1;
        $options = $form['field_your_field_value']['#options'];
        unset($options[3]);
        unset($options[4]);
        $options['3+4'] = 'name of combine value';
        array_unshift($options, '- ALL -');
        $form['field_your_field_value']['#options'] = $options;
    }
}

/**
 * our validate for  form views-exposed-form-list-your-views
 */
function MYMODULE_form_views_exposed_form_validate($form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-list-your-views'){
        if(in_array('3+4', $form_state['input']['field_your_field_value'])){
            form_set_value($form['field_your_field_value'], array(3,4), $form_state);
        }
    }

}

Comment: Can you change this line `if($form_state['input']['field_your_field_value'] == '3 + 4'){` to `if(in_array('3+4', $form_state['input']['field_your_field_value']))`? Then your answer is accepted answer.
Comment: @Ahmad I've done it.


Burnside Lemma Necklace Problem

Question: I am trying to solve the following problem:

How many necklaces can we make that use $4$ red stones, $5$ blue stones and $3$ green stones, such that the necklaces are in the shape of a regular dodecagon.

I know I need to use the Cauchy-Frobenius (or Burnside) Lemma to count the "Fixes" of all the rotations and flips of $D_{12}$, which we can describe as:
$$D_{12}=\langle x,y\text{ }\Big|\text{ }x^2=e,y^{12}=e, xyxy=e\rangle$$
I have already calculated the fixes for $e$ (which is $\frac{12!}{5!4!3!}$), and for powers of $y^i$, where $i=1,5,7,11$. For $i=1$, I noted that we would eventually reach the conclusion that all of the stones must be the same, which is obviously false. For $i=5,7,11$, I said that since their $gcd(i,12)=1$, we could eventually find $n$ such that $(y^i)^n=y$, which we have shown has a Fix of 0.
These solutions have been rather intuitive, and not super mathematically rigorous. I have an intuition that the remaining powers of $y$ will also have fixes of $0$ (after some testing with specific examples), but I'm not entirely certain how to prove it. I was thinking of using the fact that we can describe $D_{12}$ as the permutations of the numbers $1,2,...,12$, and that the orbits of these remaining $y^i$ do not have size $5$ or $3$, and thus we cannot have a fix for these $y^i$. However, I'm not certain if the correlation between these two things is as strong as I'm hoping it is.
If it is the case that the orbits formed by a permutation of $D_{12}$ do tell us about the Fix in this way, then I feel confident that I can figure out the Fixes for $xy^i$. However, if this is not the case, then a suggestion as to where to start would be sincerely appreciated. Cheers.
Answer: Yes, it is a very good idea to label the vertices of the dodecagon from $1$ to $12$ and then to study the permutations induced on the set $\{1,\ldots,12\}$ by the symmetries in $D_{12}$ - these are extremely related.
More specifically, you want to think about the orbits of these points under the symmetry. Presumably, to see that a pattern symmetric with the rotation $y$ would only have one color, you first reason that vertices $1$ and $2$ must be the same color because $1$ is moved to $2$ by $y$. Then $2$ and $3$ must have the same color too - and so on.
If you write the permutation induced by $y$ in disjoint cycle notation, you get
$$y \rightarrow (1\,2\,3\,4\,5\,6\,7\,8\,9\,10\,11\,12)$$
where, in case this notation is unfamiliar, each number maps to the one to the right of it and the last term maps to the first. Everything in a cycle must be the same color. If we want to study the fix of $y^2$, we can write that in permutation notation:
$$y^2\rightarrow (1\,3\,5\,7\,9\,11)(2\,4\,6\,8\,10\,12)$$
where we have two orbits - each of which must be the same color. However, there is still clearly no way to assign colors to orbits to satisfy the counts desired. In general, you can find that, as you suspect, the elements $y^n$ for $n\neq 0$ will not have a fix because it will not be possible to color the orbits in any way to get the desired numbers - you can prove, for instance, that $y^n$ has $\gcd(n,12)$ orbits of equal size. This serves as a generalization of what you already have.
Then, for the flips, you will find two possible configurations of orbits: six flips consist of $6$ orbits of size $2$ and the other six consist of $5$ orbits of size $2$ and $2$ orbits of size $1$. For instance, two possible flips are the flip along the $1$ to $7$ axis given as
$$(1)(2\,12)(3\,11)(4\,10)(5\,9)(6\,8)(7)$$
and the one which is along the perpendicular bisector of the edge from $1$ to $2$ given as
$$(1\,2)(3\,12)(4\,11)(5\,10)(6\,9)(7\,8).$$
You can note that, in the latter case, there is no way to color the orbits appropriately, since the orbits all have even size. In the former case, however, you will find that you can color the orbits - which means that there is some fix of these symmetries.
To find the size of that fix, you can just note that you must first color one of the orbits of size $1$ blue and the other green (giving $2$ choices) and then, of the remaining orbits of size $2$, color $2$ red, $2$ blue, and $1$ green. This lets you extend your reasoning to find all the fixes for this problem and thus to compute the number of necklaces possible.
Comment: Thanks for your response! I have of course seen the disjoint cycle notation (this is what I was getting at in my question; it was rather hastily written, so it might not have come across). Your explanation for how to approach the flip cases makes a lot of sense. Thanks once again.
Answer: Given that  we have dihedral symmetry  we suppose we are  working with
bracelets (naming convention by OEIS).   This requires the cycle index
$Z(D_{12})$ of  the dihedral  group $D_{12}.$ We  have for  the cyclic
group that
$$Z(C_{12}) = \sum_{d|12} \varphi(d) a_d^{12/d}
= \frac{1}{12}
(a_1^{12} + a_2^6 + 2 a_3^4 + 2 a_4^3 + 2 a_6^2 + 4  a_{12}).$$
We get twelve  more permutations corresponding to flips  about an axis
passing through opposite slots or opposite edges, for a result of
$$Z(D_{12}) = \frac{1}{24}
(a_1^{12} + a_2^6 + 2 a_3^4 + 2 a_4^3 + 2 a_6^2 + 4  a_{12})
+ \frac{1}{24} ( 6 a_1^2 a_2^5 + 6 a_2^6).$$
By  the Polya  Enumeration  Theorem  (PET) we  are  interested in  the
quantity
$$[R^4 G^3 B^5] Z(D_{12}; R+G+B).$$
Working through the rotational terms we find

 $[R^4 G^3 B^5] (R+G+B)^{12} = {12\choose 4,3,5}.$

The terms  other than the  first produce second, third,  fourth, sixth
and twelfth powers of $R,G$ and $B$ simultaneously and hence can never
yield $R^4 G^3 B^5$, making for a zero contribution.
We get from the reflections

 $[R^4 G^3 B^5] 6 (R+G+B)^2 (R^2+G^2+B^2)^5
\\ = [R^4 G^2 B^4] 12 (R^2+G^2+B^2)^5
= [R^2 G^1 B^2] 12 (R+G+B)^5
\\ = 12 \times {5\choose 2,1,2},$
 $[R^4 G^3 B^5] 6 (R^2+G^2+B^2)^{6} = 0.$

Collecting everything we find for our result that it is
$$\frac{1}{24} \left({12\choose 4,3,5}+
12 {5\choose 2,1,2}\right).$$
which yields
$$\bbox[5px,border:2px solid #00A000]{1170.}$$

Burnside Lemma Necklace Problem


Soccer game outcome, are chances equal between win/loss/tie?

Question: In soccer (or any discipline with similar scoring rules), is there statistically equal chance for win, loss and tie?
So, there are 3 possible outcomes, but are all 3 outcomes equally possible?
This does not take into account better/worse teams, so teams are equal for the chances... So ranking, player setup or physique, etc, should not be taken into account. Also, neither should any external condition (quality of playing field, weather, ...).
The reason I thinks so, is because a win is everything where scoreA > scoreB, which seems (intuitively) more likely to happen than scoreA = scoreB.
If scoreB is 1, then a tie is only possible when scoreA is also 1. However when scoreB is 1, a win for A is any possible combination where scoreA > scoreB. Which is much more than the 1 single option for a tie...
Comment: I see no reason to think so.
Comment: A good assumption would probably be a Poisson distribution underlying the number of goals for each team. Equally good teams can then have the same rate parameter $\lambda$. Depending on $\lambda$, the odds between draws and non-draws changes. There is presumably (at least one) lambda, where a draw is equally likely as one of the two teams winning.
Comment: For some intuition, consider two extreme scenarios. In the first, two equally-matched teams both have terrible offenses and great defenses, and so most of their games end scoreless. The chance of a tie when these teams meet will be very high. In the second, both teams have terrible defenses and typically score extraordinary numbers of goals. Since that number is subject to random variation, the chance that the game ends with both teams scoring the same is low--that is, the chance of a tie becomes small.
Comment: It may be miscommunication. I responded to this "there are 3 possible outcomes, but are all 3 outcomes equally possible?". I see no reason - even from a situation of ignorance of which team might be better - to regard the tie option as being as probable as the other two.
Comment: Do you mean for two teams that are equally good?
Comment: @Glen_b the reason I thinks so, is because a win is everything where scoreA > scoreB, which seems (intuitively) more likely to happen than scoreA = scoreB. If scoreB is 1, then a tie is only possible when scoreA is also 1. However when scoreB is 1, a win for A is any possible combination where scoreA > scoreB. Which is much more than the 1 single option for a tie...
Comment: Indeed miscommunication, sorry
Answer: First of all, it only makes sense to consider a situation in which both teams are equally good. Then, losses and victories are equally probable, so consider the comparison between winning and drawing for illustrative purposes. Then outcomes for which the two teams draw are for instance 0-0, 1-1, 2-2, ..., whereas outcomes for which team 1 wins are for instance 1-0, 2-0, 3-0, 4-0,..., 2-1, 3-1, 4-1,... As you can see, the number of outcomes for draws and the number of winning outcomes is not equal (and hence the probabilities are also unequal). You could formalize this idea by assuming that team $X$ and team $Y$ both score a number of goals in a time period of for instance 90 minutes that is Poisson distributed with a certain parameter $p$. Then you could compute the probabilities that $X-Y>1$ (so that team one wins) and that $X=Y$, so that the teams draw.
Answer: This is not a question that can resolved using statistics or stochastics. First off, it obviously depends on the player of each team, of the conditions on the field, etc.
Let's make an easy scenario: We have two duplicates of exactly the same team playing against each other, with sides of the field determined by random choice. In this case, it would follow by symmetry that each team is equally likely to win.
These assumptions do not suffice to determine the likelihood of a draw - there are psychological factors at play. For example, depending on the team they might become especially motivated or demotivated if they are behind.
Sure, as @rbm could you might model the number of goals as Poisson-Distributed, but this would assume that the performance of the teams would be unaffected by the current score and the time remaining. That wouldn't be soccer anymore. If you would go that route, it would depend on the lambda parameter (which roughly described the rate of goals per team). Depending on lambda a tie become more or less likely. My intuition is that the higher lambda is the less likely a win becomes - if both team tends to score many goals it becomes unlikely that they end up at the exact same number. If both tend to not score any goal at all it is likely the game will end 0:0.
I then tested my intuition with some simulation code in R:
<code>lambda <- seq(0, 30, by = 0.1)
draws <- rep(0, length(lambda))

for (i in 1:length(lambda)) {
lamb <- lambda[i]
team1 <- rpois(1e6, lamb)
team2 <- rpois(1e6, lamb)
draws <- team1 == team2
draw.likelihood[i] <- sum(draws)/length(draws)
}

plot(draw.likelihood ~ lambda, type = "l", lwd = 2)
grid()
</code>
You can interpret lambda as average goals per side per game. The results look like this and matches my intuition:

Since even good teams seldom score more than three goals per game you get a substantial draw rate. At least it matches real observations so far. For reference for lambda = 0, 1, 2, 3 the draw rates are 100%, 31%, 21% and 17% respectively.


How do I create a custom cycling status in discord.py?

Question: I have a discord bot that I'm using to learn how to use the API and to practise my python knowledge. I'm trying to create a system that randomly chooses a status and applies it then waits a short time, currently 10 minutes, then continue like that infinitely until the bot is shutdown. Currently, I have the loop in my on_ready() function but the bot shuts down after a short time (less than 10 minutes, around 2-3) and I can't figure out why. The current code is this:
@client.event
async def on_ready():
  print("We have logged in as {0.user}".format(client))
  infiniteTime = 1
  while infiniteTime != 20:
    statusType = random.randint(0, 1)
    if statusType == 0:
      statusNum = random.randint(0, 10)
      await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.playing, name=playingStatus[statusNum]))
    else:
      statusNum = random.randint(0, 10)
      await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=watchingStatus[statusNum]))
    time.sleep(600)

watchingStatus and listeningStatus are 1D arrays with 11 strings in. Any assistance/feedback is appreciated as I'm new to the API. Cheers!
ETA: Should probably clarify that I've realised that having the code in the on_ready() function means that it never ends and so can't do anything else. I'm asking because I don't know why the bot shuts-down on Discord's end without me stopping the code and I don't know where else I should put this loop as I'm new to this async/await system and the way the API functions.
Comment: You should prob utilize task loops for this: https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html
Answer: The place where you are trying to change the status of the bot is correct, the problem is the way of trying to create this loop is stopping your bot from working, as time.sleep is not suitable for an asynchronous library such as discord.py. Instead you can use asyncio.sleep().
You could do something like this:
import asyncio

@client.event
async def on_ready():
  # ...
  # Here goes your code for on_ready()
  # ...
  while True:
    statusType = random.randint(0, 1)
    if statusType == 0:
      statusNum = random.randint(0, 10)
      await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.playing, name=playingStatus[statusNum]))
    else:
      statusNum = random.randint(0, 10)
      await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=watchingStatus[statusNum]))
    asyncio.sleep(600)

Another way of doing this would be using discord.ext.tasks, which are functions defined to be running background tasks like the one you want to achieve.
from discord.ext import commands, tasks
import asyncio

# Your code here

@loop(seconds=600)
async def status_change():
    # ...
    # Some code to define playingStatus and watchingStatus arrays
    # ...
    statusType = random.randint(0, 1)
    if statusType == 0:
      statusNum = random.randint(0, 10)
      await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.playing, name=playingStatus[statusNum]))
    else:
      statusNum = random.randint(0, 10)
      await client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=watchingStatus[statusNum]))

status_change.before_loop(client.wait_until_ready())
status_change.start()
client.run("TOKEN")

References:

asyncio
asyncio.sleep()
discord.ext.tasks
Comment: Both methods come out with errors. The first boots and logs in properly but then says that 'sleep' was never awaited and to enable tracemalloc to get a traceback ([screenshot](https://gyazo.com/48c5df9d22f42db8faa2c144b845ecd0)). The second says that name 'loop' was not defined ([screenshot](https://gyazo.com/93876005dd6b064a60eee04bd10b95ef)). Any ideas?
Comment: My bad, as your code is hard to reproduce I could not test that it was fully working. For the first one you need to await the sleep: `await asyncio.sleep(600)`. For the second method you might need to explicitely import loop with `from tasks import loop`.
Comment: That's working thank you! Sorry it was so hard to reproduce, it's pretty janky so was a little difficult to pin down!


criar intro page em site multilingual

Question: Não consigo criar uma intro page no meu site e acredito que o problema seja relacionado ao multilanguage ativado. Alguém  sabe como resolver isto? estou usando o Framework Vertex.
Comment: Sua pergunta é vaga, confusa, não esclarece. Qual a sua dúvida exatamente? Você já tem alguma coisa pronta?
Answer: Penso que este vídeo poderá ser uma possível ajuda para o seu problema:
http://www.shape5.com/documentation/Joomla/Getting-Started/How-To-Setup-Multilanguage-Support-In-Joomla
Comment: Sua resposta não atende os requisitos. Imagine se esse link ficar off line, sua resposta não tem sentido. Tente criar uma resposta com conteúdo.

criar intro page em site multilingual


Diferença na tela Windows Forms C#

Question: Estou com um problema no Visual Studio > Windows Forms. Quando habilito o tema clássico do Windows e crio um projeto em C# a tela fica dentro do que eu quero, porém, ao habilitar o modo Aero, o lado direito da tela fico desalinhada.
Logo abaixo está um print da diferença (distância do lado esquerdo difere do lado direito).
Comment: Esclareça seu problema específico ou acrescente outros detalhes para destacar exatamente o que precisa. Do modo como está escrito aqui, é difícil saber exatamente o que você está perguntando. Consulte a página [Como perguntar](http://pt.stackoverflow.com/help/how-to-ask) para obter ajuda no esclarecimento desta pergunta.
Comment: parece-me que tem a ver com o tamanho do border do form
Answer: Isso é comum. Existem diversos fatores que alteram o "tamanho real" do form. Como, por exemplo, as bordas ou até mesmo aquela sombra que fica "atrás" da janela no Windows 10.
O que você pode fazer é trabalhar com funções do sistema operacional para tentar lidar com isso.
Talvez esta resposta do SO possa te ajudar. Como não sei qual seu objetivo, não posso indicar nada mais do que isso.
Comment: Então, precisa fazer algo para manter o mesmo padrão para todos os visuais.
Comment: Não tem como manter padrão magicamente. Você teria que calcular as dimensões o tempo inteiro ou então usar painéis e âncoras.
Answer: Normalmente você colocando painéis com 6-8 de largura nas bordas evita esse tipo de problema.
Answer: Consegui resolver, o problema estava no tamanho mínimo e tamanho máximo do Forms.

Diferença na tela Windows Forms C#


How to find circle radius from cyclic trapezium

Question: I'm solving some of my countries olympiad problems, and after manipulating all of the data I was able to get the title of the question. I have an isosceles trapezium $ABCD$ which has all of its vertices inscribed in a circumference, and I need to find the circle's radius. The side lengths are  $AB=4$, $AD=BC=2$, and $CD=6$. The angles are $\angle ADC = \angle DCB = 60$ and $\angle BAD = \angle CBA = 120$.
I know there is a ridiculous formula which uses diagonals and semi perimeters, but I don't think that is the intended answer. In fact, I suspect the answer is half 3, half of $CD$, but I haven't been able to prove it.
I'm not sure if this matters anymore, as I used it to get to this part of the problem, but $AD$ and $BC$ intersect at $E$, and form an angle of $60$ (all numbers on degrees).
Can't provide a sketch, but it should be easy to draw.
Comment: Hello, why can't you provide a sketch? Also every time you post a question on the site, you should share your attempt.
Comment: [Software for drawing geometry diagrams](https://math.stackexchange.com/q/1985/947379), Actually we welcome even a diagram drawn by hand. The only purpose is to understand your question better.
Comment: Are you sure you have the side lengths correct?  AB,AC,AD,CD don't form sides of a trapezium.  Anyway, the answer cannot be half 3 (i.e. 3/2), or half CD (i.e. 3).
Comment: Also I think you should have written $AD = BC = 2$?
Comment: Sorry, just read all of this. I did indeed right stuff wrong, will correct. Cant provide a sketch cause I frankly don't know how to. And I didn't include my attempt, as this isn't the full problem. It involved using the fact that $\angle AED$ was 60 to find that  $DC$ was 6. Afterwards I got stuck, and tried to, unsuccessfully, prove arc $CD=180$
Comment: @DollarStoreRichard it still does not justify you posting a question without showing your efforts. Here is a hint - the center of the circle $O$ is on perpendicular bisector of $AB$ and $CD$ (parallel sides of trapezium) and as $\angle D = 60^\circ$, what angle does diagonal $AC$ subtend at center $O$? So if you find $AC$, you are done.
Comment: I'm too bad at this to conclude anything. Sorry. I have no idea the angle $AC$ subtends at $O$ (or what that even means).
Answer: Let O is center of circumference, E is middle of AB, F is middle of CD, OA=$R$, OE=$x$. Then OF=$|\sqrt{3}-x|$.
Then $R^2=OA^2=AE^2+OE^2=4+x^2$, $R^2=OD^2=DF^2+OF^2=9+3-2\sqrt{3}x+x^2$.
Then $4+x^2=9+3-2\sqrt{3}x+x^2 \Rightarrow$ $2\sqrt{3}x=8 \Rightarrow$ $x=\frac{4}{\sqrt{3}} \Rightarrow$ $R^2=4+\frac{16}{3}=\frac{28}{3} \Rightarrow$ $R=2\sqrt{\frac{7}{3}}$.
Comment: Thank you for your answer.


Python3: Telling a context manager to execute the code block more than once?

Question: I'm wondering whether something is possible under python3. I would like to write a context manager which would execute its code block more than once. This doesn't seem to fit into the standard python3 context manger semantics, but I'm wondering whether I'm missing something. I want something like the following:
CtxMgr(repeat_count=N, ... other args ...):
    # This is the code block.
    # This code block does whatever it needs to do,
    # and this context manager makes sure that it
    # runs `repeat_count` times.

I'm guessing that if such a thing is possible, it might be implementable somehow under a structure similar to this:
class CtxMgr(contextlib.AbstractContextManager):
    def __init__(self, repeat_count=1, *args, **kwargs):
        self.repeat_count = repeat_count
        ## etc.
    def __enter__(self):
        ## etc.
    def __exit__(self, *args):
        ## etc.
    ## What other method(s) would need to be implemented here?

I know that I can do the following, but I don't want to do it this way. I'm looking for a way to do this solely as a context manager.
# What I don't want to do ...

def func(... ...):
    # whatever

CtxMgr(repeat_count=3) as f:
    for _ in range(0, f.repeat_count):
        func(... ...)

In other words, I'm wondering whether this could somehow be accomplished in python3 without the auxiliary function func, and for whatever code block follows the context manager instantiation, that code block would be automatically executed repeat_count times.
Thank you in advance.
Comment: I also have tried doing this at some point, but it is not (currently) possible.  In my case I decided to use a decorator instead.
Comment: Thank you. Could you post an example of how you used a decorator for this purpose?
Answer: As I mentioned in my comment, this is not currently possible with a context manager.  However, you can use a decorator:
import functools
import time
from typing import Collection, Type, Union

def retry_n_times(n: int, *, sleep_secs: float = 0.0, retry_on: Union[Type[Exception], Collection[Type[Exception]]] = Exception):
    """
    Retry the decorated function up to `n` times.  Raise a RuntimeError if all attempts fail.
    If `sleep_secs` is specified, sleep that long after each attempt.
    If `retry_on` is specified, only retry on these exception types - other exceptions will escape as normal.
      By default, retry on any exception.
    """
    if n <= 0:
        raise ValueError("'n' must be >= 1")

    if not isinstance(retry_on, Collection):
        retry_on = [retry_on]
    retry_on = tuple(retry_on)

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_exception = None
            for _ in range(n):
                try:
                    return func(*args, **kwargs)
                except retry_on as exc:
                    last_exception = exc  # prevents "local variable 'exc' referenced before assignment"
                    if sleep_secs:
                        time.sleep(sleep_secs)
            else:
                raise RuntimeError(f'{func.__name__} failed {n} times') from last_exception

        return wrapper
    return decorator

Example usage:
count = 0

@retry_n_times(3)
def succeed_on_second_try():
    count += 1
    if count == 1:
        raise ValueError('Intentional failure')

succeed_on_second_try()
assert count == 2

Comment: This is close enough to what I want. I'm more interesed in the functionality itself, rather than specifically using a context manager. Thank you very much!


What on my PHP Curl call do I need to add to read a response's custom headers?

Question: I tried a few several ways to read the responses custom header but have not been able to. I know the response I get is served by nginx and the custom header names start with X-......
<code>$endpoint =  'url here';
$ch = curl_init( $endpoint );

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'cbFunc');

$result = curl_exec($ch);

print_r( curl_getinfo($ch ) );
</code>
Comment: Show what you tried (in your question) along with describing the actual result vs the expected result.
Comment: ok @PatrickQ I updated w/ my code sample above
Comment: Have you read the documentation for these things? Are you aware of what `CURLOPT_HEADERFUNCTION` does?
Comment: Possible duplicate of [Can PHP cURL retrieve response headers AND body in a single request?](https://stackoverflow.com/questions/9183178/can-php-curl-retrieve-response-headers-and-body-in-a-single-request)
Comment: @miken32 what should the callback function I write  do?  do you have sample code
Answer: The PHP manual is an excellent reference guide an a good starting point when you run into problems like this.

CURLOPT_HEADERFUNCTION [Set value to] A callback accepting five parameters.

hence
<code>log_headers('init');
$endpoint =  'url here';
$ch = curl_init( $endpoint );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'log_headers');
$result = curl_exec($ch);
$headers=log_headers();
print_r($headers);

function log_headers($ch=false, $headers=false)
{
    static $hdrs;
    if (is_array($hrs) && $ch===$headers===false) {
        return $hdrs[];
    } elseif ($ch==='init') {
        $hdrs=array();
        return 0;
    }
    $hdrs[]=$headers;
    return strlen($headers);
}
</code>
Comment: Whoops - copied/pasted the wrong description, should be 2  - Thanks miken32
Comment: PHP Parse error:  syntax error, unexpected '===' (T_IS_IDENTICAL) in /app/catalog-sunbutter-feed.php on line 22  is code right


Who authenticates baseball paraphernalia?

Question: There is always a person at major league baseball games who authenticates certain items. A player's 1st hit or home run ball, a home run caught by a fan, a pitcher's 2,000th strike out, things like that.
Who determines which items are authenticated, and is that person hired by MLB, the ballpark, or whom?
Answer: Off-duty law enforcement officers working as independent contractors are assigned by Authenticators, Inc. for Major League Baseball Properties to authenticate autographs and game-used memorabilia at every Major League Baseball game. Only those items that an authenticator actually witnesses being signed or used in a game may be eligible for authentication under the MLB Authentication Program.
Other Sources: tokens-icons.com, sportscollectorsdigest.


Como tirar a borda azul do tabpane?

Question: Não consigo tirar a borda azul padrão que é mostrada no evento <code>:focused</code>.
Estou tentando resolver esse problema pelo CSS, mas não consigo.
Meu código CSS:
<code>.tab-pane .tab-header-area .tab-header-background {
    -fx-background-color: #333333;
}

.tab-pane {
    -fx-tab-min-width:90px;
}

.tab{
    -fx-background-insets: 0 1 0 1,0,0;
    -fx-padding: 10 20;
}

.tab-pane .tab{
    -fx-background-color: #333333;
}

.tab-pane .tab:selected
{
    -fx-background-color: #FAFAFA;
}

.tab .tab-label {
    -fx-alignment: CENTER;
    -fx-text-fill: #CCCCCC;
    -fx-font-size: 13px;
    -fx-font-weight: bold;
}

.tab:selected .tab-label {
    -fx-alignment: CENTER;
    -fx-text-fill: #555555;
}
</code>
Resultado:
Comment: Tenta algo como: **outline: 0;** no seu css
Ele vai retirar a borda azul, quando o elemento está em :focused
Answer: Como já falaram, você pode usar o outline: 0;, porém cabe ressaltar que ao retirá-lo, você reduz a acessibilidade da sua página. Soluções alternativas: estilizar o outline para ficar mais estético, ou retirá-lo, mas criar um estilo para quando o elemento estiver :focus, que pode ser o mesmo do :hover.
Vale a pena conferir esses links sobre outline e acessibilidade:
http://ux.sapo.pt/acessibilidade/web-acessibilidade/navegacao-4/#toc-no-remover-o-outline-dos-elementos-clicveis
http://www.outlinenone.com/

Como tirar a borda azul do tabpane?


How is One-Hot Encoding interpreted by an Algorithm?

Question: I'm new to machine learning, and just learned about the use of one-hot encoding as a method of passing a categorical variable as an input into a machine learning algorithm. As I understand it, one of the advantages of one-hot encoding is that it allows the algorithm to learn separate weights for each possible value of the categorical variable.
My questions are the following: If the model is made to learn a separate weight for each input feature, how can it learn N weights when it comes to a one-hot encoded feature of N possible values, and then only apply the relevant one? Isn't this the same as turning the categorical variable into N individual boolean features?
Thanks in advance!
Answer: Yes, you are absolutely right. One-hot-encoding is the same as "turning the categorical variable into N individual boolean features" and is called "creating dummy variables" in statistics. The main purpose of doing this is that you can easily manipulate a model/neural network/whatever else you are using by using matrix algebra.
E.g. if you have a class that is either "cat", "dog" or "bird", then it's hard to see how to apply linear algebra. So, instead we represent this as $x=(1,0,0)^T$, $(0,1,0)^T$ or $(0,0,1)^T$, where $^T$ denotes transposing. Then it becomes easy to have a second vector of weights or coefficients $\beta = (\beta_1, \beta_2, \beta_3)^T$, and to write that the mean outcome is $\mu = x^T\beta$. That is a more convenient notation that saying that the mean outcome for cats is $\beta_1$, for dogs $\beta_2$ and $\beta_3$ for birds, but more importantly computers can easily handle this using linear algebra in the same way as for continuous predictors.


Python legend attribute error

Question: Why am I getting an error here that relates to the plt.plot label?
fig = plt.figure()
ax = plt.gca()
barplt = plt.bar(bins,frq,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm');
ax.set_xlim([min(bins)-1, max(bins)+1])
ax.set_ylim([0, max(frq)])
plt.xlabel('Dgr')
plt.ylabel('Frequency')
plt.show()
plt.legend(handles=[barplt,normplt])

This is the error that I get:
'list' object has no attribute 'get_label'
Comment: You question would have been improved by posting the *full traceback*.  That would have pinpointed the line that caused the issue and helped people answer the question.  It also would have helped you solve your own issue.  Had your question been written more carefully, it may have received an upvote.
Answer: Because plt.plot can plot more than one line at once, it returns a list of line2D objects, even if you only plot one line (i.e. in your case, a list of length 1). When you grab its handle for the legend, you want to only use the first item of this list (the actual line2D object).
There are (at least) two ways you can resolve this:
1) add a comma after normplt when you call plt.plot, to only store the first item from the list in normplt
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt, = plt.plot(bins_n,frq_n,'--r', label='Norm')   # note the comma after normplt

print normplt
# Line2D(Norm)    <-- This is the line2D object, not a list, so we can use it in legend
...
plt.legend(handles=[barplt,normplt])

2) Use only the first item in the list when you call plt.legend (normplt[0]):
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm')

print normplt
# [<matplotlib.lines.Line2D object at 0x112076710>]
# Note, this is a list containing the Line2D object. We just want the object,
# so we can use normplt[0] in legend
...
plt.legend(handles=[barplt,normplt[0]])

Answer: In new matplotlib version (3.1.0) was added new method
for creating legends for scatter plots.

Now, PathCollection provides a method legend_elements() to obtain the handles and labels for a scatter plot in an automated way. This makes creating a legend for a scatter plot as easy as

So, you can also use automated legend creation:
N = 45
x, y = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)

fig, ax = plt.subplots()

scatter = ax.scatter(x, y, c=c, s=s)

# produce a legend with the unique colors from the scatter
legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes")

plt.show()

Comment: Thanks for letting us know it was just added -- I came here wondering why I was getting `'PathCollection' object has no attribute 'legend_elements'` in an older version.

Python legend attribute error


writing appending text file from databricks to azure adls gen1

Question: I want to write kind of a log file back to azure adls gen1
I can write (not append) using
dbutils.fs.put(filename,"random text")

but i cant append it using
with open("/dbfs/mnt/filename.txt","a"):
f.write("random text")

it give me error
1 with  open("/dbfs/mnt/filename.txt", "a") as f:
----> 2   f.write("append values")

OSError: [Errno 95] Operation not supported

alternatively, i tried using logger.basicconfig(logging.basicConfig(filename='dbfs:/mnt/filename.txt', filemode='w')
but looks like its not writing into the path.
can anyone help please
Answer:
Append Only ('a') : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.

file = open("myfile.txt","a")#append mode
file.write("Today \n")

Output of append file:
Comment: @iratelilkid Please find the screenshot of the file content.
Comment: If it is useful for you, could you please [accept it as an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)? It may help more people who have similar issue.
Comment: Can you show a screenshot of the file's contents? I think that would confirm if it has gotten appended or not?
Comment: This is not helping, in Databricks you will still have the error OSError: [Errno 95] Operation not supported if trying to append a new line to an existing file.
Answer: You can do that to a DBFS file.
https://kb.databricks.com/en_US/dbfs/errno95-operation-not-supported
You may need to figure out a logic to read a file from datalake using python CLI and write to it.
Answer: I had the same issue. Turns out you can't use standard python file operations on databricks because of the file system (DBFS). You end up getting the error [Errno 95] Operation not supported. You have to use dbutils to do it and I've found that you can't append. The below code is how I've gotten around it. Note that you need to use dbfs:/ file path when using dbutils.fs operations.
dbfs_path_home = "dbfs:/mnt/directory
dbfs_path_log = f"{dbfs_path_home}/logfile.log"

Then when you want to log something, you will need to read in the entire contents of the log file and add the new message. E.g.
def logging(message):
    logmsg = dbutils.fs.head(dbfs_path_log)
    logmsg += message + '\n'
    dbutils.fs.put(dbfs_path_log, logmsg, overwrite=True)


Why is the slope function not differentiable?

Question: I encountered this (complex) function in my textbook:
$$
g(z)=
\left\{
\begin{split}
&\frac{f(z)-f(a)}{z-a}&, \space z \neq a\\
&f'(a)&, z=a
\end{split}
\right.
$$
The book says that $g(z)$ is continuous everywhere. However, $g$ is not differentiable at $z=a$. I understand the continuity part, but I am not sure the reason for $g$ not differentiable at $z=a$.
Below is my attempt:
$$
\lim_{h \to 0} \left. \frac {g(z+h)-g(z)}{h} \right |_{z=a}=\lim_{h \to 0} \frac {g(a+h)-g(a)}{h} = \lim_{h \to 0} \frac { \frac{f(a+h)-f(a)}{h}-f'(a)}{h}\\
$$
Now how do I show that the limit doesn't exist? It looks like there is an indetermitane form in this limit, though I am not sure.
Comment: Just take a function whose second derivative $f''(a)$ does not exist - this'll provide you the desired counter-example.
Comment: Unless $f$ has some smoothness, $g$ doesn't need to: after all, $g'$ would be more akin to a *second* derivative of $f$.
Comment: @IvoTerek Could you elaborate a bit more?
Comment: Can anybody show me how to proceed with this problem? I have tried myself but still couldn't figure it out.
Comment: Take $f(z)=z$ and $g$ is perfectly differentiable.
Comment: Not *necessarily* differentiable. *Can* be differentiable.
Answer: If $f$ happens to be analytic in some neighborhood $U$ of $a$ then the function $g$ is not only continuous on $U$ but even analytic as well, in particular differentiable at $a$. There is no question about that.
On the other hand, if $f$ is any old continuous function which is, by coincidence, complex differentiable at $a$, but maybe nowhere else, then $g$ is indeed continuous, but maybe not differentiable at $a$. Consider the  example $f(z):=z\bar z$. For this $f$ we have
$$\lim_{z\to0}{f(z)-f(0)\over z}=\lim_{z\to0}\bar z=0\ ,$$
hence $f$ is complex differentiable at $0$. Furthermore
$g(z)=\bar z$ is continuous on all of ${\mathbb C}$, but not complex differentiable anywhere.
Answer: Use $f(x) = x|x|$ and $a = 0$. Then $f'(0) = 0$, $f(0) =0$, so that for all $x \neq 0$ $g(x) = \frac{f(x)}{x}= \frac{x|x|}{x} = |x|$ and $g(0) = f'(0) = 0.$
Thus:
$ \lim_{h \rightarrow 0^+}  \frac{g(h)-g(0)}{h} = \lim_{h \rightarrow 0^+}  \frac{|h|}{h}= 1 \neq \lim_{h \rightarrow 0^-}  \frac{g(h)-g(0)}{h} = \lim_{h \rightarrow 0^-}  \frac{|h|}{h}= -1$ , so $g$ is not differentiable at $0$.


should the destructor be called with placement new even on the same type

Question: #include <new>

struct X
{
    ~X() { std::cout << "destroyed" << std::endl; }
    int x;
};

int main(int argc, const char * const * const argv)
{
    X x{1};

    new (&x) X{2};

    std::cout << x.x << std::endl;

    return 0;
}

Output
2
destroyed

What I know is that the destructor should always be called when placement new is used. However in this sample code, the destructor is implicitly called in the end of the main so calling it again is undefined behaviour I suppose.
so now I want to know if the destructor should always be called when placement new is used or are there certain conditions under which the destructor should not be called?
Answer: It's specified explicitly in the C++ standard

[basic.life]
5 A program may end the lifetime of any object by reusing the
  storage which the object occupies or by explicitly calling the
  destructor for an object of a class type with a non-trivial
  destructor. For an object of a class type with a non-trivial
  destructor, the program is not required to call the destructor
  explicitly before the storage which the object occupies is reused or
  released; however, if there is no explicit call to the destructor or
  if a delete-expression is not used to release the storage, the
  destructor shall not be implicitly called and any program that depends
  on the side effects produced by the destructor has undefined behavior.

The last sentence leaves a little bit of wriggle room regarding the possibility of undefined behavior1. But ultimately, the only types for which this is well-defined are those for which the destructor is truly trivial.

1 - As of writing this, anyway.
Comment: that implies that one should preferably always call the dtor before reusing storage of a type with a non trivial dtor in order to guarantee the side effects of that dtor. However, upon scope exit is there still one implicit dtor call guaranteed, is an explicit call a UB then?
Comment: The part about UB will probably be removed. See https://github.com/cplusplus/draft/pull/2342
Comment: so this means that one should **not** make the explicit call upon scope exit at the moment right? it is guaranteed to be called then.
Comment: @mkmostafa - One object declared, one object destroyed at scope exit.
Answer:
What I know is that the destructor should always be called when placement new is used.

Yes, except when the type is trivially destructible.
In this case, you must destroy the previously constructed object before placement new:
X x{1};
x.~X();
try {
    new (&x) X{2};
} catch(...) {
    std::abort(); // no way to recover
}

An automatic variable of non-trivially destructible type must not go out of scope in a destroyed state. If the constructor throws, the behaviour will be undefined. Reusing memory of a non-trivial object is not recommended.
It is safer to reuse memory of a trivial object:
alignas(alignof(X)) std::byte arr[sizeof(X)];
new (arr) X{2};
x.~X();

Comment: Note that we have [`std::aligned_storage`](https://en.cppreference.com/w/cpp/types/aligned_storage) for this purpose. Or, I prefer [`std::aligned_union`](https://en.cppreference.com/w/cpp/types/aligned_union), since then you don't need to write all those `sizeof` and `alignof` operators. (It would be nice to simply write `std::aligned_storage_t buf;`, wouldn't it? ;-)


Flush CPU caches in C++ by iterating an array and disable compiler optimizations

Question: For benchmarking reasons, I need to run the same algorithm over the same data multiple times. Now, I want to explore the case where all the runs over the same data are on cold caches.
I was thinking of adding a for loop reading every element of an array (LOAD/MOV instruction on every element) so the cache fill with the array elements. Eg.
vector<size_t> vec(CACHE_SIZE/sizeof(size_t));
//...
//...
size_t element;
for (size_t i = 0; i < vec.size(); ++i) {
    element = vec[i];
}

But when compiled with optimization, all of this will probably be removed.
So how do I do this, possibly with minimal overhead.
Answer: Declare element to be volatile. Accesses and assignments to a volatile variable are not allowed to be optimized away.
volatile size_t element;

Comment: This makes sense. It should probably generate additional LOAD/MOV to memory instruction but that seems fine. I'll check it out.
Comment: `vector vec` might be better, but I'm not sure if this is allowed.


Evaluating $\lim_{c\to\infty}\sqrt{\frac{a}{b}}\left[\frac{1+c\sqrt{ab}}{c+\sqrt{ab}}\right]$

Question: The equality
$$k_a=\sqrt{\frac{a}{b}}\left[\frac{1+\sqrt{ab}(c)}{\sqrt{ab}+c}\right]$$
is equal to $a$ when $c=\infty$. The condition $\sqrt{ab}=\sqrt{a}\sqrt{b}$ holds.
Can you explain how this works? When substituting $c=\infty$, we have:
$$k_a=\sqrt{\frac{a}{b}}\left[\frac{1+\sqrt{ab}(\infty)}{\sqrt{ab}+\infty}\right]$$
what are the steps, rules, logic to go from there to  showing that $k_a=a$?
Comment: $\frac{1+c\sqrt{ab}}{c+\sqrt{ab}}=\frac{\frac1c+\sqrt{ab}}{1+\frac1c\sqrt{ab}}\to\frac{\frac1\infty+\sqrt{ab}}{1+\frac1\infty\sqrt{ab}}$ and $\frac1\infty=0.$
Comment: Make the substitution $c=1/d$, simplify, and then take $d=0$.
Answer: Note that:
$$\frac{1+c\sqrt{ab}}{c+\sqrt{ab}}=\frac{\frac1c+\sqrt{ab}}{1+\frac1c\sqrt{ab}}
$$
And therfore :
$$\lim_{c\to\infty}\sqrt{\frac{a}{b}}\left[\frac{1+c\sqrt{ab}}{c+\sqrt{ab}}\right]=\lim_{c\to\infty}\sqrt{\frac{a}{b}}\left[\frac{\frac1c+\sqrt{ab}}{1+\frac1c\sqrt{ab}}\right]=a
$$


How can I prevent memory size exhaustion when dumping variables in Twig?

Question: hello everyone i have a problem with kint , in my twig page i want to listing all variables contains int 'content' variable to make some logic on it , but the page can't loaded because the big pip memory , can any one tell me how to solve this problem to dump the 'content' variable?

this is the msg

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 29994336 bytes) in /var/www/html/core/modules/big_pipe/src/Render/BigPipe.php on line 336

Answer: There are several options to prevent this:

The most obvious one, increase memory
Create a new node or entity or whatever with only a single field you want to output in kint(), so the server doesn't have to run it for multiple fields
Make your kint() more specific, don't do kint(content) but kint(content['field_name']) for example

If none of these work, figure out how to set up xdebug, which is probably a much cleaner way of debugging.
Answer: Variable content is pretty large to print, but you can try to lower your printing depth in modules/contrib/devel/kint/kint/config.default.php
by setting $_kintSettings['maxLevels'] to lower number than 7.
Comment: Hey Patrick please try to find possible duplicates first and the flag the question accordingly to prevent duplicate answers. Many thanks
Comment: so i have just reduce the number but it shows me this error , Cannot save /var/www/html/project/web/modules/contrib/devel/kint/kint/config.default.php.
Unable to create a backup file (config.default.php~).
The file left unchanged.


Minimizing cache clearing during development

Question: I'm suffering from very long (several second) load times when developing locally with Drupal 8 when developing/debugging twig templates or in general having ALL caching disabled.  Rebuilding cache makes my admin pages needlessly require a rebuild for example.  When I'm not actually working on them I'd like them to remain cached.
I'd like to be more specific in my cache clearing so that I can clear only the parts I'm actively working on - ex a view or block - instead of constantly invalidating the entire site cache which is rather expensive.
I've found that cache tags may work, but I can't find documentation or the location where I might find a listing of available cache tags or really much else on clearing specific caches.  So if tags are effective, where can I find all registered cache tags on my site?
Is there more information I'm missing on how targeted caching is implemented in Drupal 8?  Are there alternatives to tags that might work better?
Edit:  I should mention my environment, in case there is an alternative solution.
I'm running Drupal using docker, with Nginx/PHP-FPM and MySQL containers , on Docker for Mac which has known issues with file mounts so I'm only mounting my custom modules as volumes into any containers.  I profiled the difference between mounting everything and am now spending negligible time doing file operations whereas previously it was very expensive.
Now it appears that my bottleneck is calling the Database many times per pageload, I imagine this is because I'm rebuilding the entire cache meaning I'm adding/removing it from the DB over and over.  I may try memcached or redis and see if that helps.
My ideal solution here is to just invalidate portions of the cache I actually want to invalidate instead of the entire thing though.  Cached pages are ofc incredibly fast in this environment.  My staging environment which is using native Docker does not have the FS issues but still suffers when caches are turned entirely off.
Comment: You could try using [aquia clould](https://www.acquia.com/free), it's free. Local dev is so slow & unproductive.
Answer: Define all caches disabled, how do you do that?
The recommended approach is to only disable the render cache (as per the example local settings.php), but if you have a complex site and a slow, especially virtualized environmment, that can still take some seconds on every request.
Make sure you don't have xdebug or so constantly enabled. Use PHP7 if possible, that's basically 50% faster. It doesn't make mysql faster obviously, but unless you have very slow/bad queries, that is likely a smaller part of the whole response than you think. And if you have slow queries, then you need to find ways to optimize them, since it will get much morse when you have more parallel page requests.
If you clear cache manually, make sure you use drush cc render and not drush cr unless you actually change something that requires a full cache clear.
Cache tag invalidation doesn't really help that much, you could of course find out the cache tag of your specific block/view and invalidate just that, but there is no drush command for that yet). You could write your own cache backend that extends from the default and allows to ignore cache writes of cache IDs that match a certain pattern. But invalidation will require you to figure out the cache id of the thing, unless you work on the same thing for quite some time, that won't be worth the effort.
For more specific things, you'd need to profile the site to find out what is actually slow.


Where is the lower limit for a (baseball) strike?

Question: Yesterday, watching the Pirates-Mets game, I saw the Pirates' Andrew McCutchen called out on a third strike. The pitched ball was clearly over the plate, but "low." IMHO, it should, or at least could, have been called a ball.
In addition to being over the plate, the pitched ball must fall between the players' shoulders and knees. It was the "knees" part that confused me.
I was taught that "at the knees" meant at the level of kneeCAPS. Is that too high; that is, is there a definition of "knees" that is lower than the kneecaps?
Is it true that umpires have been informally expanding the strike zone, so that almost anything that is "over the plate" is called a strike as long as it is not in the dirt, even though it's technically "below the knees" (basically at the shin, as opposed to ankle, level)?
Could camera angles have caused a difference of opinion? That is, I saw a "flat" pitch "below the knees" through a TV camera, while an umpire, standing behind the plate, saw a "sinker," part of which was "barely" at knee level?
Answer: This page shows that the pitch caught the very bottom of the zone per PitchFx. The zone is technically from the letters to the knees. Granted, it's not always called that way, but this is how PitchFx is calibrated. This isn't an expanded zone, it's actually exactly the zone they are supposed to call.
Note that the zone is measured from the front of home plate, not where the catcher catches the ball. This pitch was very flat though, I don't have replay of it, but it doesn't look like it broke much from the pitchFx data.
As far as the true lower limit, Page 22 of the MLB rules indicates that the zone is below the kneecaps, not above them.
Comment: OK, the definition of "knees" appears to be where the shin bone joins the thigh bone, not the "kneecap." By that definition, the pitch was (barely) "at the knees."
Comment: @TomAu yeah, it's definitely *barely* a strike, a good pitch, and a good call IMO.