Interpretation of log likelihood and covariate significance in Cox regression

Question: Another newbie question here (probably piece of cake for you guys).
When I run a Cox Regression and one of my covariates come out as significant:
<code>                                                    95,0% CI for Exp(B)
        B       SE      Wald    df  Sig.    Exp(B)  Lower   Upper
risk    2,224   1,107   4,036   1   ,045    9,244   1,056   80,950
<5 covariates removed for clarity>
</code>
But my Omnibus Tests of Model Coefficients(a) isn't significant. Change from previous step: Chi-square=10,290. df=6. Sig.=0,113.
Does this mean my model is simply too bad to use for anything? Can I say anything credible about my data after running this analysis?
Thanks for any clues that'll take me closer to the beauty of applied statistics... ;)
Regards
Alex
Answer: Credibility depends on context and you've not offered any. If the other 5 degrees of freedom are in the model for good reasons but you aren't particularly interested in estimating the effects, only interested in the impact of "risk", then you may have something interesting but the really wide confidence interval prevents me from applying the label "credible". However, the likelihood ratio test for the addition of "risk" to the model would be a more solid estimate of its effect independent of the other covariates. Your Wald test is fairly borderline.
Comment: It's a bit hazy on this side of the crystal ball interface, since you are using some sort of software that has it's own particular terminology. It sounds as though there was a change in the 2*log-likelihood of 6.298 when risk was added. Given the limits of what you have offered,  it appears the evidence in favor of "risk" (whatever it might be) being associated with shorter survival time is considerably stronger than was indicated by the Wald test.
Comment: I'm not really interested in the effect of the other coravirates, I just put them in the model to control for the effect they have. If I understand you correctly, my statistic "indicates a genuine effect even though it is only borderline significant"?
Comment: Hardly. I would not accept that as a fair paraphrase of what I said. I say one would first need to do a LRT examination before doing further discussion of whether the borderline Wald test even met conventional standards for significance. And  I think the work "genuine" is a far reach in the absence of better context.
Comment: Thank you for taking your time to help me. And I'm sorry for the delayed response. I've separated the covariates in 2 blocks in the analysis. The first block contains the 5 covariates I want to control for, the second block contains only the 'risk' covariate. In Block 2 I get a 'Change from previous block'-statistic: Chi-square=6,298, df=1, sig=0,012. Doesn't this mean that the second changed the model significantly? Is this what you mean by Likelihood Ratio Test?


Enable Role as AD Certification Authority, what can go wrong?

Question: I am about to install the role Active Directory Certification Authority on a Windows Server 2012 R2 that is already our Active Directory server.
The reason is, that I want to enable LDAPS following https://docs.moodle.org/310/en/Active_Directory#MS_Active_Directory_.2B_SSL
So I wonder what can go wrong?

Will the Active Directory stop to accept unencrypted connections?
Will established certificates stop working?
Will other servers (e.g. domain controllers) that work fine without encryption try LDAPS and fail because they don't trust the certificate?
Will I be no longer able to log in and fix it, because the VPN relies on LDAP?
Comment: Don't install ADCS on a domain controller.
Comment: Actually, all I want is to be able to change passwords over ldap (for moodle), which i rumoured to be impossible without TLS.
Answer: Installing a full fledged certificate authority in order to sign a single certificate for your domain controller seems like a lot of effort for not a lot of gain. If all you need is LDAPS on a single domain controller, your time may be better spent just purchasing 3rd party certificate (there CAs that offer free certificates as well) assuming your domain name is one that you actually own and not something like corp.local. Here are a couple docs that can help:

Requirements for domain controller certificates from a third-party CA
Enable LDAP over SSL with a third-party certification authority

If you can't use a public CA for whatever reason, I'd still probably opt for something like New-SelfSignedCertificate rather than installing ADCS for a single cert.
To answer your questions.

No, AD will not stop accepting unencrypted connections after adding a certificate. The TLS encrypted services run on different ports.
I'm not sure what you mean exactly by "established certificates". But generally no, installing ADCS doesn't mess with existing cert stores other than to add the new root CA certificate as trusted.
Other servers will fail to connect if they have been configured to use TLS and have not been configured to trust the CA root certificate (unless they've also been configured to disable certificate validation which is generally a bad idea). (This is another benefit of a public certificate which is that it will already be trusted by clients)
Your VPN is unlikely to start using LDAPS for authentication unless you configure it to do so. But once you do, yes. VPN authentication will be dependent on properly functioning TLS.
Comment: Yes, it is corp.local, how did you guess? I am completely fine with a self signed certificate, as there is only one client to use it. I just need a way to make ldap listen on port 636 and present a certificate.
Comment: It's unfortunately pretty common. But for future reference, https://serverfault.com/questions/76715/windows-active-directory-naming-best-practices


How to hide edit tab on entity form

Question: I'd like to remove the ability to edit/update an entity form once it was been completed and submitted correctly.
I thought there might be a way to lock an entity form? Or remove access? or hide the edit tab.  Any suggestions on how to accomplish this?
Thanks
Answer: You could look into hiding the tab using hook_menu_alter. If you set access callback to FALSE then it will be hidden.

How to hide edit tab on entity form


Compute $ \lim_{x\to\infty}\frac{1}{x}\int_1^x\cos\frac{1}{t}\,dt $

Question: I have a limit I can't solve. I'm studying for a test in Calculus II.
I'm asked to compute the limit:
$$
\lim_{x\to\infty}\frac{1}{x}\int_1^x\cos\frac{1}{t}\,dt
$$
It's hinted that there is no need to compute the integral itself.
Can you help me compute the limit?
Comment: @yarinch AlphaGo's deleted answer was correct. You can apply l'Hôpital to forms such as $\text{anything}/\infty$; however $\lim_{x\to\infty}\cos(1/t)\,dt=\infty$, because the function is positive and has limit $1$.
Comment: Have you completed the sequences and series chapter or are you still at the chapter on methods of integration? I am gussing that a mere graph will yeild some kind of insight.
Comment: Maple gives $1$.
Comment: What's 'Maple'?
Comment: @yarinch It is a computer algebra system.
Answer: For all $t \ge 1$, we have $0 < \dfrac{1}{t} \le 1$. Then, since $\cos$ is a decreasing function on $[0,1]$, we have $\cos \dfrac{1}{t} \ge \cos 1$ for all $t \ge 1$. Thus, $\displaystyle\int_{1}^{x}\cos \dfrac{1}{t}\,dt \ge \int_{1}^{x}\cos 1\,dt = (x-1)\cos 1$.
Since $\cos 1 \approx 0.54 > 0$, $\displaystyle\lim_{x \to \infty}(x-1)\cos 1 = \infty$. Therefore, $\displaystyle\lim_{x \to \infty}\int_{1}^{x}\cos \dfrac{1}{t}\,dt = \infty$, as well.
Now that we've shown that the integral tends to infinity, we see that the limit $\displaystyle\lim_{x \to \infty}\dfrac{1}{x}\int_{1}^{x}\cos \dfrac{1}{t}\,dt$ is an indeterminate form $(\dfrac{\infty}{\infty})$. So we may use L'Hopitals Rule (as AlphaGo's deleted answer did):
$\displaystyle\lim_{x \to \infty}\dfrac{\int_{1}^{x}\cos \tfrac{1}{t}\,dt}{x} = \lim_{x \to \infty}\dfrac{\cos \tfrac{1}{x}}{1} = \lim_{x \to \infty}\cos \dfrac{1}{x} = \cos 0 = 1$.
Comment: By the way, it is not needed to show the integral has infinite limit.
Comment: Thanks! Nice and clean proof.
Answer: Notice it suffices to calculate $ \lim _{x \rightarrow \infty} \frac{\int _1^\sqrt{x}   \cos 1/t d t}{x}  $ and $ \lim _{x \rightarrow \infty} \frac{\int _\sqrt{x}^x   \cos 1/t d t}{x}  $
For the first limit we use the IVT and get
\begin{align*}
 \lim _{x \rightarrow \infty} \frac{\int _1^\sqrt{x}   \cos 1/t d t}{x} &= \lim _{x \rightarrow \infty} \frac{ (\sqrt{x}-1) \cos 1/\xi _x }{x} \rightarrow 0 \\
\end{align*}
Since $|\cos 1/\xi _x | \leq 1$
Now for the second we use again IVT and get
\begin{align*}
 \lim _{x \rightarrow \infty} \frac{\int _\sqrt{x}^x   \cos 1/t d t}{x} &= \lim _{x \rightarrow \infty} \frac{ (x-\sqrt{x}) \cos 1/\xi _x }{x}  \\
&=1
\end{align*}
Since $\xi_x  \geq \sqrt x$ which in turn means $\xi _x \rightarrow \infty$ thus $\lim _{x \rightarrow \infty} \cos 1/\xi _x =1.$
Therefore $$ \lim _{x \rightarrow \infty} \frac{\int _1^x   \cos 1/t d t}{x} =1 $$
Answer: I'm not sure what methods you are allowed to use, but as a hint:
$\lim_{x \rightarrow x_0}(fg)(x) = \left(\lim_{x \rightarrow x_0}f(x)\right)\left(\lim_{x \rightarrow x_0}g(x)\right)$
provided that the two limits on the right hand side exist.
Comment: This does not apply here. The limit of only the integral does not exist.
Comment: Ah yeah you're right.


Existence and uniqueness of $SL(n,\mathbb R)$ left-invariant Borel probability measure on $SL(n,\mathbb R)/SL(n,\mathbb Z)$.

Question: Consider the action of $SL(n,\mathbb R)$ on the homogeneous space $SL(n,\mathbb R)/SL(n,\mathbb Z)$ by left translation. Are there any good refences where I can find the proof of the existence and uniqueness of the left $SL(n,\mathbb R)$-invariant Borel probability measure on $SL(n,\mathbb R)/SL(n,\mathbb Z)$.
If there is some powerful theorem addressing this for general $G$ and $G/\Gamma$, please let me know how $SL(n,\mathbb R)$ and $SL(n,\mathbb R)/SL(n,\mathbb Z)$ satisfy the hypothesis of that theorem.
Comment: By the way, the measure in question just comes from the Haar measure on $G=SL(n,R)$, equivalently, from a left-invariant Riemannian metric on $G$.
Answer: For the $SL(n,\mathbb{R})$ case, this is the content of the fact that $SL(n,\mathbb{Z})$ is a lattice. There are two well-known approaches; one is by way of building good fundamental domains ("Siegel sets") and the other is Margulis' unipotent orbit argument.
As a starting point Witte Morris' Introduction to Arithmetic Groups is probably appropriate (available at https://arxiv.org/abs/math/0106063). See Chapter 7 there. The references there would point toward generalizations too I presume.
Answer: Generally, if $G$ is a unimodular locally compact topological group, and $\Gamma$ is a unimodular closed subgroup of $G$, there is a unique up to scalar left $G$-invariant Borel measure on the quotient space $\Gamma \backslash G$.  This measure $\mu_{G/\Gamma}$ has the property that
$$\int\limits_G f(g)dg = \int\limits_{\Gamma \backslash G} \int\limits_{\Gamma} f(\gamma g)d \gamma d\mu_{G/\Gamma}(g) \tag{$f \in L^1(G)$}$$
In your case, $G = \operatorname{SL}_2(\mathbb R)$ is unimodular, and $\Gamma = \operatorname{SL}_2(\mathbb Z)$ is a discrete and hence unimodular topological group, so the existence and uniqueness of the measure on $\Gamma \backslash G$ is no problem.  The more interesting question is why this measure space $\Gamma \backslash G$ has finite measure.
An indirect, but enlightening way of seeing this is to let $K = \operatorname{SO}_2(\mathbb R)$, and identify $G/K$ with the upper half plane $\mathbb H = \{ a+bi : b > 0\}$.  This is an identification of topological spaces and $\Gamma$-actions.  Since $K$ is compact and hence unimodular, $G/K$ has a right $K$-invariant measure, and one can check (painfully) that this measure coincides with the hyperbolic measure $\frac{dx dy}{y^2}$ on $\mathbb H$.
Let $D$ be the closure of the usual fundamental domain for $\Gamma$ acting on $\mathbb H$.  It has finite hyperbolic measure on $\mathbb H$, and for every $z \in \mathbb H$, there exists a $\gamma \in \Gamma$ such that $\gamma.z \in D$.  Identifying $D$ with a subset of $G/K$, we therefore also have $\mu_{G/K}(D) < \infty$.  Moreover,   Since $K$ is compact, the preimage $E = \{ g \in G : gK \in D\}$ has finite measure, since if $f$ is the characteristic function of $E$, we have
$$\operatorname{meas}(E) = \int\limits_G f(g)dg = \int\limits_{G/K} \int\limits_K f(gk)dkd\mu_{G/K}(k) = \operatorname{meas}(K) \mu_{G/K}(D) < \infty.$$
On the other hand, we can look at this finite number in a different way:
$$\operatorname{meas}(E) = \int\limits_G f(g)dg = \int\limits_{\Gamma \backslash G} \bigg(\sum\limits_{\gamma \in \Gamma} f(\gamma g) \bigg))d\mu_{G/\Gamma}(g).$$
Since for every $g \in G$, there is at least one $\gamma \in \Gamma$ such that $\gamma g \in E$, we have $\sum\limits_{\gamma \in \Gamma} f(\gamma g) \geq 1$ for every $g \in G$, and therefore
$$\operatorname{meas}(E) \geq \int\limits_{\Gamma \backslash G} d\mu_{G/\Gamma}(g).$$
This forces $\Gamma \backslash G$ to have finite measure, and it also implies an upper bound on each sum $\sum\limits_{\gamma \in \Gamma} f(\gamma g)$, except possibly for $g$ in a set of measure zero.


Adding content to Paragraph Date Field Drupal 8

Question: I'm programmatically creating paragraphs using the following code, but I'm unable to get the date value to store correctly within the date field. It seems to store within the database, yet on the edit page/form for the node, it remains as a blank field.
Any suggestions or insight would be appreciated.
<code>//SET THE DATE
$date = new DrupalDateTime('2017-10-24 13:30:00');

//CREATE THE NEW PARAGRAPH
$paragraph = Paragraph::create([
    'type' => 'event_venue',
    'field_tickets' => [
        ["value"  =>  'Adult Update 1|£30'],
        ["value"  =>  'Adult Update 2|£130']
        ],
    'field_date' => array($date->format('Y-m-d H:i:s')),

]);

//SAVE THE PARAGRAPH SO WE CAN ADD THE ENTITY ID TO THE NODE
$paragraph->save();

//LOAD THE NODE
$node = entity_load('node', $nid);

//ADD PARAGRAPH TO THE NODE
$node->field_dates = array(
    array(
      'target_id' => $venue_information->id(),
      'target_revision_id' => $venue_information->getRevisionId(),
    )
);

//SAVE THE NODE
$nid = $node->save();
</code>
Answer: Use the global constant DATETIME_DATETIME_STORAGE_FORMAT to format the date:
<code>// If the time is in a different timezone then adjust it to UTC before you save it
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));

$paragraph = Paragraph::create([
  ...
  'field_date' => [
    'value' => $date->format(DATETIME_DATETIME_STORAGE_FORMAT),
  ],
]);
</code>
Edit
For Drupal >= 8.5: Global constants in datetime.module are deprecated and DateTimeItemInterface has been introduced.


Rolling vs Recursive vs Fixed Window Regression

Question: What precisely are the differences between rolling, recursive and fixed window regression?
As far as I understand,

recursive: we train on a period $y(0)$ to $y(n)$ then predict $\hat{y}(n+1)$. Then we train on $y(0)$ to $y(n+1)$ and predict $\hat{y}(n+2)$ and so forth. The window we train on gets bigger, and we do one-step ahead predictions.

rolling: we train on a period $y(0)$ to $y(n)$ then predict $\hat{y}(n+1)$. Then we train on $y(1)$ to $y(n+1)$ and predict $\hat{y}(n+2)$ and so forth. The size of the window we train on stays the same size, and we do one-step ahead predictions.

fixed: here is where I am confused. I was thinking that fixed was that we train on $y(0)$ to $y(n)$, then predict $\hat{y}(n+1)$ to $\hat{y}(n+m)$. But i have the feeling that this is actually multi-step forecasting. I also find some sources on the internet that claim that rolling and fixed are the same. I am confused... Is rolling different from fixed? If yes how?

Some conflicting/confusing sources:

This paper basically differentiates between fixed, rolling and recusrive, however i could not find where they explain the difference. They also mention that they focus on one-step ahead forecasting, so I am confused how they differentiate between fixed and rolling
This source (and many others) only explain rolling vs recursive, dont mention fixed..

I am relatively confused at this point and I am very happy for any answers explaining the difference or pointing me towards some relevant sources...

Update
I found a source giving some explanantion:
Source:
Regression-Based Tests of Predictive Ability, Kenneth D. West and Michael W. McCracken, https://www.jstor.org/stable/2527340?seq=3#metadata_info_tab_contents

However I'm still somewhat confused between multi-step ahead forecasting and fixed windows...
Answer: Your definitions are correct.
Economic Forecastsing - Elliot and Timmerman (2016) is a good ref for that.
See the image therein:

However I'm still somewhat confused between multi-step ahead
forecasting and fixed windows..

Recursive (expanding windows), rolling windows and fixed windows, deal with parameters estimation. Multi-step forecasting is another problem. You can make one step ahead or multi step ahead forecasts with any of the three estimation procedure you mention.
Comment: I have done even more.
Comment: I quickly looked through the book but could not find any explanation of the window types on first sight, I would appreciate the precise page numbers if possible, Thanks!


Statistical test for comparing usability of two different systems

Question: I conducted a usability test of two password systems ps1 and ps2. Same users participated in the usability of both system. Analysis of average login attempts and average login time clearly indicates that ps1 is more usable than ps2. However, I would like to know which statistical tests are more relevant for comparing the usability of ps1 vs ps2. Or are mean login attempts and login time sufficient indicators?
Also I read about t-test which is used to compare two different samples. However in my study I have used the same sample (users) to determine the usability of ps1 and ps2.
Comment: You might find useful reading about a/b testing. [This](http://research.uncc.edu/sites/research.uncc.edu/files/media/files/Designing%20Experiments2.pptx) might be an interesting piece to get the basics of design of experiments.
Comment: Thanks, but a/b testing assumes testing two variants on different samples (users). I have tested two variants on the same samples (users).
Comment: Can I use a Mann-Whitney U test?
Comment: Mann-Whitney U test still comes with strong assumptions about independence. Can those hold? How did you execute your experiment?
Answer: Whether just reporting the means (presumably with confidence intervals) is sufficient is a judgment about your intended audience.  We couldn't answer that for you.
If you want to submit these analyses to a peer-reviewed scientific journal that required a test and a p-value, you should not use t-tests.  Neither of your measures could really be normally distributed.  Your number of login attempts is a kind of count variable (specifically a negative binomial with $r=1$, cf, here), and the login time is a survival time.  There are appropriate models for both.  Also bear in mind that you need to account for the nonindependence in your data.  Probably the simplest option for you would be to use the Wilcoxon signed rank test.  My guess is that these contain the same information, and you could get away with just testing one of them.


How to reset dropdown values when an option is selected from another dropdown in React.js

Question: If the user select the number 3 from the numbers drop down, this will make the names drop down to be disabled.
I want to reset the names dropdown to "select name" when option 3 is selected.

const DropDown = ({ selectedValue, disabled, options, onChange }) => {
  return (
    <select onChange={onChange} disabled={disabled}>
      {
        options.map(o => <option value={o} selected={o == selectedValue}>{o}</option>)
      }
    </select>
  );
}

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      numbers: [1, 2, 3, 4, 5], // 3 should disable the second dropdown and reset
      names: ['john', 'jane', 'eric'],
      selectedNumber: '',
      selectedName: ''
    }

    this.onNumbersChange = this.onNumbersChange.bind(this);
    this.onNamesChange = this.onNamesChange.bind(this);
  }

  onNumbersChange(e) {
    this.setState({ selectedNumber: e.target.value });
  }

  onNamesChange(e) {
    this.setState({ selectedName: e.target.value });
  }

  render() {
    const { numbers, names, selectedNumber, selectedName } = this.state;
    return (

        <DropDown
          options={numbers}
          selectedValue={selectedNumber}
          onChange={this.onNumbersChange}

        />
        <DropDown
          options={names}
          selectedValue={selectedName}
          onChange={this.onNamesChange}
          disabled={selectedNumber == 3} // this will be disabled if selected value of the first dropdown is 3
        />

    );
  }
}

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

my dropdown is using redux form, field.
<Field name="Name"
 component={renderSelect}
 label=""
 disabled options={options}
 returnValue={"id"}
 displayText={"name"}
/>

so this is my dropdown.. I am not able to reset its value
Answer: You need to make 2 changes

in onNumbersChange function, check if e.target.value is equal to 3. if it is, updated selectedValue in the state to be 'select name'
in DropDown component, if selectedValue prop is equal to 'select name', add an extra option with the value of 'select name' and add selected attribute on it.

const DropDown = ({ selectedValue, disabled, options, onChange }) => {
  return (
    <select onChange={onChange} disabled={disabled}>
      {
         selectedValue === 'select name'
           ? <option value={selectedValue} selected>{ selectedValue }</option>
           : null
      }
      {
        options.map(o => <option value={o} selected={o == selectedValue}>{o}</option>)
      }
    </select>
  );
}

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      numbers: [1, 2, 3, 4, 5], // 3 should disable the second dropdown and reset
      names: ['john', 'jane', 'eric'],
      selectedNumber: '',
      selectedName: ''
    }

    this.onNumbersChange = this.onNumbersChange.bind(this);
    this.onNamesChange = this.onNamesChange.bind(this);
  }

  onNumbersChange(e) {
    if (e.target.value == 3) {
       this.setState({ selectedName: 'select name' });
    }
    this.setState({ selectedNumber: e.target.value });
  }

  onNamesChange(e) {
    this.setState({ selectedName: e.target.value });
  }

  render() {
    const { numbers, names, selectedNumber, selectedName } = this.state;
    return (

        <DropDown
          options={numbers}
          selectedValue={selectedNumber}
          onChange={this.onNumbersChange}

        />
        <DropDown
          options={names}
          selectedValue={selectedName}
          onChange={this.onNamesChange}
          disabled={selectedNumber == 3} // this will be disabled if selected value of the first dropdown is 3
        />

    );
  }
}

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

A better approach would be to add 'select name' in the names array in your state because after adding 'select name' in your state, you will only need to make some changes in the App component to get the required functionality.

const DropDown = ({ selectedValue, disabled, options, onChange }) => {
  return (
    <select onChange={onChange} disabled={disabled}>
      {
        options.map(o => <option value={o} selected={o == selectedValue}>{o}</option>)
      }
    </select>
  );
}

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      numbers: [1, 2, 3, 4, 5], // 3 should disable the second dropdown and reset
      names: ['select name', 'john', 'jane', 'eric'],
      selectedNumber: '',
      selectedName: ''
    }

    this.onNumbersChange = this.onNumbersChange.bind(this);
    this.onNamesChange = this.onNamesChange.bind(this);
  }

  onNumbersChange(e) {
    if (e.target.value == 3) {
       this.setState({ selectedName: this.state.names[0] });
    }
    this.setState({ selectedNumber: e.target.value });
  }

  onNamesChange(e) {
    this.setState({ selectedName: e.target.value });
  }

  render() {
    const { numbers, names, selectedNumber, selectedName } = this.state;
    return (

        <DropDown
          options={numbers}
          selectedValue={selectedNumber}
          onChange={this.onNumbersChange}

        />
        <DropDown
          options={names}
          selectedValue={selectedName}
          onChange={this.onNamesChange}
          disabled={selectedNumber == 3} // this will be disabled if selected value of the first dropdown is 3
        />

    );
  }
}

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

Comment: Here numbers is coming from state..so in theonNumbersChange function, it is written this.state.names[0], how do i write it of numbers was coming from render funtion.. In a diff code my numbers option value is coming from an api, and I have defined it first in render...so how to make write that
Comment: when you get the numbers from the api, save them in the state. No need to define them in render function
Comment: my dropdown is using redux form, field.      so this is my dropdown.. I am not able to reset its value
Comment: i have edited it in the question...I dont know why i am not able to reset for this method


Flex Web App automated testing

Question: I want to test my web App developed on Flex 3.
I have used selenium, but working with it is a pain since it has problem deceting some custom components. It has problems working with pop up window, etc.
Can you suggest to me a new tool to work with?
Comment: Are you looking to spend lots of money or get it for free? (or somewhere in between)?
Comment: Other than QTP mentioned in an answer; you can also look for "Flex Monkey" which was renamed but I forget what the new name is.  And RIATest which is a commercial tool for this.  There is also unit test tools such as FlexUnit.  This question most likely got closed b/c it is not a specific programming question; and many would say "StackOverflow is not a recommendation engine"
Answer: In my former company, we used Mercury QTP (part of the Mercury Test Director suite, now a property of HP). It was working fine with Flex 1.5, 2 and 3 as long as you put ids on all your application components, widgets ... and that you embed some SWC files while compiling (automation.swc mainly).
But I assume you're looking for a "free" test utility. You should have a look here:
Automated testing of FLEX based applications
There are some UI testing software listed.
Comment: Note that Test Director is a "whole enchilada" tool; you really mean QTP (QuickTest Pro).
Comment: Yes, sorry, I meant QTP

Flex Web App automated testing


Deployment failed because no Windows Phone 8 phone was detected. Make sure a phone is connected and powered on

Question: I wrote first app using VS2012, Its giving error although I did attach my phone.

Error 1 Deployment failed because no Windows Phone 8 phone was
  detected. Make sure a phone is connected and powered on
Answer: I disconnected the Phone from the USB. Then went to 'Control Panel->Hardware and Sound->Devices' and Removed Device. Then connected the Phone to the USB.
I was the able to Register the Phone and Run the app.


Erro em consulta ao webservice CADSUS em PHP

Question: Olá, pessoal.
Estou tentando consumir a função "pesquisar" do barramento CADSUS, porém recebo como resposta o erro
"Forced circuit exception";

O código utilizado segue abaixo, usando Laravel 5.6 e PHP 7.1:
Route::get('/ws/teste', function () {
    try {
        $opts = array(
            'http' => array(
                'user_agent' => 'PHPSoapClient'
            )
        );
        $context = stream_context_create($opts);
        $wsdlUrl = 'https://servicoshm.saude.gov.br/cadsus/CadsusService/v5r0?wsdl';
        $soapClientOptions = array(
            'trace' => 1,
            'stream_context' => $context,
            'cache_wsdl' => WSDL_CACHE_NONE,
            'Username' => 'CADSUS.CNS.PDQ.PUBLICO',
            'Password' => 'kUXNmiiii#RDdlOELdoe00966'
        );
        $client = new SoapClient($wsdlUrl, $soapClientOptions);
        $parameters = array(
            'CNESUsuario' => array(
                'CNES' => '6963447',
                'Usuario' => 'LEONARDO',
                'Senha' => ''
            ),
            'FiltroPesquisa' => array(
                'nomeCompleto' => 'SERGIO ARAUJO CORREIA LIMA',
                'tipoPesquisa' => 'IDENTICA'
            ),
            'higienizar' => 0
        );
        $result = $client->pesquisar($parameters);
        print_r($result);
    }
    catch(\Exception $e) {
        echo $e->getMessage();
    } });

Se alguém souber o que pode estar acontecendo, por favor, me ajude!
Answer: Boa noite,
Tive um problema parecido e tive que alterar bastante seu codigo,
- a unica maneira que consegui autenticar foi enviando no header com os namespaces definidos no exemplo

passa os dados com array da muito problema 'Encoding: object has no ', melhor passar por classe, segue abaixo codigo que funcionou pra mim.

<?php
try {
    $wsdlUrl = 'https://servicoshm.saude.gov.br/cadsus/CadsusService/v5r0?wsdl';
    $wsUser = 'CADSUS.CNS.PDQ.PUBLICO';
    $passWs = 'kUXNmiiii#RDdlOELdoe00966';
    $soapClientOptions = array(
 'trace' => 1,
 'cache_wsdl' => WSDL_CACHE_NONE
    );
    $client = new SoapClient($wsdlUrl, $soapClientOptions);
    $xmlheader = '
<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:UsernameToken wsu:Id="UsernameToken-F6C95C679D248B6E3F143032021465917">
        <wsse:Username>' . $wsUser . '</wsse:Username>
        <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">' . $passWs . '</wsse:Password>
    </wsse:UsernameToken>
</wsse:Security>
';
    $header = new SoapHeader('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', new \SoapVar($xmlheader, XSD_ANYXML), false);
    $client->__setSoapHeaders($header);

    $requestPesquisar = new stdClass();
    $requestPesquisar->CNESUsuario = new stdClass();
    $requestPesquisar->CNESUsuario->CNES = '6963447';
    $requestPesquisar->CNESUsuario->Usuario = 'LEONARDO';
    $requestPesquisar->CNESUsuario->Senha = '?';
    $requestPesquisar->FiltroPesquisa = new stdClass();
    $requestPesquisar->FiltroPesquisa->nomeCompleto = new stdClass();
    $requestPesquisar->FiltroPesquisa->nomeCompleto->Nome = 'SERGIO ARAUJO CORREIA LIMA';
    $requestPesquisar->FiltroPesquisa->tipoPesquisa = 'IDENTICA';
    $requestPesquisar->higienizar = '0';
    $result = $client->pesquisar($requestPesquisar);
    if ($result) {
 echo '
', print_r($result), '
';
    } else {
 echo '
Request:
';
 echo '
', print_r($client->__getLastRequest()), '
';
 echo '
Header:
';
 echo '
', print_r($client->__getLastRequestHeaders()), '
';
 echo '
Response:
';
 echo '
', print_r($client->__getLastResponse()), '
';
    }
} catch (Exception $e) {
    echo '
', print_r($e), '
';
}
?>

Busca Por CNS (Unica que retorna dados completos) Exemplo XML

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cad="http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice" xmlns:cnes="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/cnesusuario" xmlns:cns="http://servicos.saude.gov.br/schema/cadsus/v5r0/cns">
   <soap:Header>
   <wsse:Security soap:mustUnderstand="1"
   xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
   xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <wsse:UsernameToken wsu:Id="UsernameToken-F6C95C679D248B6E3F143032021465917">
   <wsse:Username>CADSUS.CNS.PDQ.PUBLICO</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">kUXNmiiii#RDdlOELdoe00966</wsse:Password>
   </wsse:UsernameToken>
   </wsse:Security>
   </soap:Header>
   <soap:Body>
      <cad:requestConsultar>
         <cnes:CNESUsuario>
            <cnes:CNES>?</cnes:CNES>
            <cnes:Usuario>?</cnes:Usuario>

            <cnes:Senha>?</cnes:Senha>
         </cnes:CNESUsuario>
         <cns:CNS>
            <cns:numeroCNS>AQUI_NUMERO_CNS</cns:numeroCNS>
         </cns:CNS>
      </cad:requestConsultar>
   </soap:Body>
</soap:Envelope>
Comment: poderia colocar o codigo dentro da resposta, pois nao podemos confiar em links, uma vez  que possam ser cancelados no futuro
Comment: @UmProgramador ja inseri o codigo na resposta.
Comment: Funcionou perfeitamente! Muito obrigado! Só surgiu uma dúvida: mandar os dados de usuário e senha pelo xml header não sei uma falha de segurança? Se alguém estiver snifando a rede, não conseguiria capturar o pacote e visualizar?
Comment: Lucas Maia, não sei dizer se há problema de segurança mas acredito que não. e na especificação técnica pede para enviar assim, no exemplo da página 13 http://datasus.saude.gov.br/images/Interoperabilidade/Especificao%20Tecnica%20para%20Integracao%20CADSUS%20V5.pdf
Comment: Opa, @AndreRicardoAlvesDosSantos, muito obrigado mais uma vez!
Comment: complementando: descobri que para retornar os dados completos utilize a operação consultar do webservice informando somente o cartao sus. mas a estrutura tem que ser exata vou colocar na resposta inicial.


Automorphisms of free groups

Question: Suppose $U$ is a subgroup of finite index in the free group on $k$ generators $F_k$.
Suppose $\sigma$ is an automorphism of $F_k$ such that $\sigma|_U = \text{id}$, then must $\sigma = \text{id}$?
Comment: Ah good point..
Answer: So...it turns out this is one of the situations where you read a sentence in a paper, and only after you spend forever thinking about why its true, that you notice the sentence ends in a colon, and the very next sentence has the proof. Basically, the proof is this:
Let $g_1,\ldots,g_k$ be the free generators of $F_k$. Then for any $i$ we can build a surjective homomorphism $F_k\rightarrow\mathbb{Z}$ sending any word in $F_k$ to the number of $g_i$'s appearing in that word. If no power of $g_i$ is in $U$, then $U$ is contained in the kernel of this homomorphism, and hence must be infinite index. Therefore, for every $i$, there is an $n$ such that $g_i^n\in U$. But that means $\sigma(g_i)^n = \sigma(g_i^n) = g_i^n$, and since $F_k$ is free, that means $\sigma(g_i) = g_i$. Since the $g_i$'s generate $F_k$, $\sigma = \text{id}$.
Comment: A little simplification (without $F_k\rightarrow\mathbb{Z}$): Since the index is finite, $g^m,g^n$ are in a same coset for some $m\ne n$. Hence $g^{m-n}\in U$.
Comment: It counts inverses as negative, so $a_1^{-1}a_2a_1 \mapsto -1 + 1 = 0$.
Comment: Which paper is it? Just curious :)
Comment: Yes, I also may need this result. Could you tell where it is published already?
Comment: @mathreader I think it's simple enough that you don't really need to cite it. If you need to use it I would just include it as a lemma.

Automorphisms of free groups


remove link tags in head

Question: I am working on a project involving migrating a site with many static pages to Drupal 8. Since a number of the pages are old blog posts, there's often broken links, broken images, etc.
For quality assurance, we are using the httrack command line tool to traverse the new Drupal 8 site and report broken links and images.
It turns out that Drupal 8 is putting some extra <link> tags in the page head (the  section of the html, not the header region or anything like that).
First, when there is a page with a taxonomy term in it, there are links to the term's admin pages in the head, like so:
<link rel="devel-definition" href="/devel/taxonomy_term/226/definition" />
<link rel="clone-form" href="/entity_clone/taxonomy_term/226" />
<link rel="token-devel" href="/taxonomy/term/226/devel/token" />
<link rel="display" href="/taxonomy/term/226/manage-display" />

These links are on the page even for anonymous users.
Second, we have media images in our pages, and they are getting weird head link tags, also. For instance, if we have the image inside-a-classroom.jpg, we'll have this: <link rel="image_src" href="Inside A Classroom" />.
The problem is, httrack is finding these links in head, trying to download them, and returning a 404. And of course it would, because when it spiders, it's not logged on and can't access admin menus. In the case of images, they're not even proper links to the image.
Is there any way we can turn these off? They are false negatives in our scraping, and make it difficult to quality check our work.
Comment: For me this looks like a Drupal permission issue or a server caching issue. Maybe anonymous user role has too many permissions granted? Also why enable Devel on live at all? And do you use something like Varnish, Akamai etc.?
Comment: @leymannx It's not live, but our development/migration target server. We don't have any caching or in-betweens. I don't understand how they would know Drupal-specific paths anyway.
Comment: Well, what happens when you disable the Devel module?
Comment: @leymannx I tried this, and I'm still getting the link tags in the head : /
Answer: Links like this are handled as attachments to the page.  They are inserted where the Drupal placeholder tags (like head-placeholder) are in the twig file.
To modify these, you need to use hook_page_attachments_alter().  Here's example code that fixes a problem with canonical URLs containing query string not getting generated properly by core (converts & to &).
/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  if ( isset($attachments['#attached']['html_head'])) {
    foreach ($attachments['#attached']['html_head'] as $key => $item) {
      if (in_array("canonical_url", $item)) {
        $href = $item[0]['#attributes']['href'];
        $attachments['#attached']['html_head'][$key][0] = [
          '#type' => 'inline_template',
          // Formatted to include a newline in page source.
          '#template' => "{{ href|raw }}
",
          '#context' => [
            'href' => '<link rel="canonical" href="' . $href . '"/>',
          ]
        ];
      }
    }
  }
}

In the case of these entity links, these are in the 'html_head_link' area of the attachments.
FYI - This is also related to this core issue.
Comment: I've used this hook to look at the contents of the `attachments` array, and I don't see the various extra page links. I do see elements such as `head`, `shortlink`, and `canonical_url`, so there must be something adding them later.
Comment: These are in the 'html_head_link' key of the attached array.  Updated answer.
Comment: Yes, under that key I have elements such as `head`, `shortlink`, etc. as I mentioned above, but it does not contain elements that have `taxonomy/term/212/devel/token`, `devel/taxonomy_term/213/render `, etc.
Comment: Hmm, I see them via a ksm dump if I'm logged in.  They are not there for the anonymous user.  These are basically the links defined in the entity definitions.  So they also vary by what is being displayed.  My test was displaying a taxonomy term page.  They do have a odd structure like $attachments['html_head_link'][14][ ['rel'=>..., 'href'=> ..], TRUE]
Comment: Thanks for taking the time to look into this to help me with my problem. In my theme, I just added a `die(print_r(...` in the page_alter hook. I don't have any of the image or taxonomy information in the key, either logged in or not. Just the ones I referenced above, and a few others.

remove link tags in head


C# conversão de um private void para public void

Question: Olá a todos eu percisava de saber como posso converter este codigo para public void. O Visual Studio acusa erro na variável e.
Mensagem de erro: "The name 'e' does not exist in the current context"
Eu limitei-me a fazer ctrl+c e ctrl+v de:
private void TextDisplay_KeyPress(object sender, KeyPressEventArgs e)

Para:
public void Detect()

Abaixo o corpo do meu método:
if (e.KeyChar == 49 || e.KeyChar == 50 || e.KeyChar == 51 || e.KeyChar == 52 || e.KeyChar == 53 || e.KeyChar == 54 || e.KeyChar == 55 || e.KeyChar == 56 || e.KeyChar == 57 || e.KeyChar == 58)
        {
            TextDisplay.Text = TextDisplay.Text + e.KeyChar.ToString();
        }

        //Detetor da tecla Equal
        if (e.KeyChar == 61)
        {
            Equal();
        }

        //Detetor da tecla Multi
        if (e.KeyChar == 42)
        {
            Multi();
        }

        //Detetor da tecla Plus
        if (e.KeyChar == 43)
        {
            Plus();
        }

        //Detetor da tecla Divisão
        if (e.KeyChar == 47)
        {
            Divisão();
        }

        //Detetor da tecla  less
        if (e.KeyChar == 45)
        {
            Less();
        }

        //DetetoR da tecla backspace
        if (e.KeyChar == 8)
        {
            if (TextDisplay.Text == "")
            {
                System.Media.SystemSounds.Beep.Play();
            }
            else
            {
                if (TextDisplay.Text.Length == 1)
                {
                    TextDisplay.Text = "";
                }
                else
                {
                    TextDisplay.Text = TextDisplay.Text.Substring(0, TextDisplay.Text.Length - 1);
                }
            }
        }

        //Detetor da tecla enter
        if (e.KeyChar == 13)
        {
            Equal();
        }

        //Detetor da tecla Esc
        if (e.KeyChar == 27)
        {
            Clear();
        }

Comment: A mudança que está informando na pergunta não deve causar nenhum problema. De qualquer forma só com esse trecho não é possível identificar o que ocorre. Coloque mais detalhes sobre o erro (mensagem, linha) e outros trechos relevantes.
Comment: @bigown eu limitaime a fazer ctrl c ctrl v do codigo acima de `private void TextDisplay_KeyPress(object sender, KeyPressEventArgs e)` para `public void Detect()` fiz ctrl s e apareceu o erro acima
Comment: coloque public void Detect(object sender, KeyPressEventArgs e)
Comment: @PabloVargas Obrigado podes por isso como resposta
Answer: ao trocar a visibilidade e nome do método, você deve manter os parâmetros também.
Ficando da seguinte forma
public void Detect(object sender, KeyPressEventArgs e)

Answer: Primeiro você precisa entender o problema: O corpo do seu método com a assinatura private void TextDisplay_KeyPress(object sender, KeyPressEventArgs e) usa a variável "e" para detectar as teclas selecionadas e fazer algumas comparações dentro desse método.
Quando você mudou a assinatura no método para public void Detect() essa variável deixou de existir, por esse motivo ocorreu o erro "The name 'e' does not exist in the current context".
Para solucionar esse erro você precisa declarar os mesmos parâmetros:
public void Detect(object sender, KeyPressEventArgs e)
{
   ...
}


redirecting to another page through php if error is Occurred?

Question: i have to check weather the page is having error,if error is there i have to redirect to one default page like error.php
I have tried with the following link but i cannot get the result
changes in my .htaccess
ErrorDocument 400 /errors.php
ErrorDocument 403 /errors.php
ErrorDocument 404 /errors.php
ErrorDocument 405 /errors.php
ErrorDocument 408 /errors.php
ErrorDocument 500 /errors.php
ErrorDocument 502 /errors.php
ErrorDocument 504 /errors.php

my errors.php code
<?php
$urPath= $_SERVER['PHP_SELF'];
$fle =basename($urPath);
$finstr =str_replace("$fle","","$urPath");
$status = $_SERVER['REDIRECT_STATUS'];
$codes = array(
       400 => array('400 Bad Request', 'The request cannot be fulfilled due to bad syntax.'),
       403 => array('403 Forbidden', 'The server has refused to fulfil your request.'),
       404 => array('404 Not Found', 'The page you requested was not found on this server.'),
       405 => array('405 Method Not Allowed', 'The method specified in the request is not allowed for the specified resource.'),
       408 => array('408 Request Timeout', 'Your browser failed to send a request in the time allowed by the server.'),
       500 => array('500 Internal Server Error', 'The request was unsuccessful due to an unexpected condition encountered by the server.'),
       502 => array('502 Bad Gateway', 'The server received an invalid response while trying to carry out the request.'),
       504 => array('504 Gateway Timeout', 'The upstream server failed to send a request in the time allowed by the server.'),
);

$title = $codes[$status][0];
$message = $codes[$status][1];
if ($title == false || strlen($status) != 3) {
       $message = 'Please supply a valid HTTP status code.';
}

echo '
Hold up! '.$title.' detected

'.$message.'
';
?>
<!DOCTYPE html>

    <title>Error</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="<?php echo $finstr;?>css/token-input.css" rel="stylesheet" />
    <link rel="stylesheet" href="<?php echo $finstr;?>css/jquery.mobile-1.2.0.min.css" />
    <link rel="stylesheet" href="<?php echo $finstr;?>css/app-reset.css" />
    <link rel="stylesheet" href="<?php echo $finstr;?>css/jquerymobilecrm.min.css" />
    <link rel="stylesheet" href="<?php echo $finstr;?>css/jqm-datebox.css" />
    <link rel="stylesheet" href="<?php echo $finstr;?>css/dcr_css.css" />
    <link rel="stylesheet" href="<?php echo $finstr;?>css/jQueryValidationEngine.css" />

    <?php //require_once"header.php";?>

Error Page

        Home

Error Occurred !!!

suggest me any idea,Thanks in advance..
Comment: What exactly is happening when you run the code?
Comment: it showing default error page...
Comment: Did you spell the `.htaccess` file incorrectly on disk as well as in your question?
Comment: no in disk is ok.....
Answer: Are you working on a local server/localhost?
/errors.php will refer to your base url, e.g. http://localhost/errors.php. If you are working with a project directory (e.g. http://localhost/project_dir/), the path to the errors.php-file should be /project_dir/errors.php.
With this change, the code works fine on my system.
Comment: my path is like CRM/mobile/
Comment: So /CRM/mobile/errors.php as ErrorDocument path in your .htaccess-files is not working?
Comment: i changed it like the above but it is not coming.


Virtual Attribute Rails Model

Question: I wanted to create an attribute on my model that took in a symbol for ascending or descending.  However, RoR does not allow enumerated types in the database, so I created a boolean property and then added an attribute on my model.  This works great for everything except validations, which I can't seem to get to work.  container.valid? always returns true, even when order hasn't been set.Any ideas?
class Container < ActiveRecord::Base
  attr_accessible :score_order
  validates :order, :presence => true

  def order
    return order_ascends ? :ascending : :descending
  end

  def order=(order)
    case order
    when :ascending
        self.order_ascends = true
    when :descending
        self.order_ascends = false
    else
        throw :unexpected_argument
    end
  end
end

Answer: You want to validate order_ascends:
1: it is present
2: it is a boolean

The order method is just what you're using to interface to order_ascends.
Comment: Hmm, that make sense but `valid?` is still returning true.
Comment: Whoops, I was just being stupid and looking at the wrong test.  Thanks for the help.

Virtual Attribute Rails Model


VBA - works in debug but sometimes get runtime error

Question: I have a pivot table and I am "dummy proofing" it for co-workers. I've created 7 buttons, one for each day of the week. I've attached macro's to them so that the pivot table changes the layout to display data for the day when the button is clicked. It works sometimes, but I often get "Run-Time error '1004':  Unable to set the Orientation property of the PivotField class" error. I select debug and run it in VBA and it works fine. I close VBA and then the macro works... sometimes. Then repeats the process all over.
This is code for one of the days (They are all the same except when setting the visible field, I use the specific day):
   Sub Sun()
'Sunday Macro

ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
    ActiveSheet.PivotTables("PivotTable1").PivotFields("1 Sun").Orientation = _
        xlHidden
    ActiveSheet.PivotTables("PivotTable1").PivotFields("2 Mon").Orientation = _
        xlHidden
    ActiveSheet.PivotTables("PivotTable1").PivotFields("3 Tue").Orientation = _
        xlHidden
    ActiveSheet.PivotTables("PivotTable1").PivotFields("4 Wed").Orientation = _
        xlHidden
    ActiveSheet.PivotTables("PivotTable1").PivotFields("5 Thu").Orientation = _
        xlHidden
    ActiveSheet.PivotTables("PivotTable1").PivotFields("6 Fri").Orientation = _
        xlHidden
    ActiveSheet.PivotTables("PivotTable1").PivotFields("7 Sat").Orientation = _
        xlHidden
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("1 Sun")
        .Orientation = xlRowField
        .Position = 8
    End With
    ActiveWorkbook.SlicerCaches("Slicer_1_Sun").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_2_Mon").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_3_Tue").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_4_Wed").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_5_Thu").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_6_Fri").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_7_Sat").ClearManualFilter
    With ActiveWorkbook.SlicerCaches("Slicer_1_Sun")
        .SlicerItems("6am").Selected = True
        .SlicerItems("x").Selected = True
        .SlicerItems("off").Selected = False
        .SlicerItems("(blank)").Selected = False
        .SlicerItems("5th").Selected = True
        .SlicerItems("6th").Selected = True
        .SlicerItems("PTO").Selected = True
    End With
End Sub

When I open the debug, the first activesheet command is highlighted hinting that I should start my fixing here.
The button to run the macro is on the sheet that it needs to run on, so there is no reason to specify the sheet but I've tried it both ways and still same problem.
Thoughts?
Updated code still gets same error.
Here is the updated version with sheet specified:
    Sub Tue()
'Tuesday Macro

Sheets("CrewSheets").PivotTables("PivotTable1").PivotCache.Refresh
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("1 Sun").Orientation = _
        xlHidden
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("2 Mon").Orientation = _
        xlHidden
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("3 Tue").Orientation = _
        xlHidden
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("4 Wed").Orientation = _
        xlHidden
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("5 Thu").Orientation = _
        xlHidden
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("6 Fri").Orientation = _
        xlHidden
    Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("7 Sat").Orientation = _
        xlHidden
    With Sheets("CrewSheets").PivotTables("PivotTable1").PivotFields("3 Tue")
        .Orientation = xlRowField
        .Position = 8
    End With
    ActiveWorkbook.SlicerCaches("Slicer_1_Sun").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_2_Mon").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_3_Tue").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_4_Wed").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_5_Thu").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_6_Fri").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_7_Sat").ClearManualFilter
    With ActiveWorkbook.SlicerCaches("Slicer_3_Tue")
        .SlicerItems("off").Selected = False
        .SlicerItems("x").Selected = True
        .SlicerItems("(blank)").Selected = False
        .SlicerItems("5th").Selected = True
        .SlicerItems("6th").Selected = True
        .SlicerItems("PTO").Selected = True
    End With

End Sub

Comment: specify the sheet: `Worksheet("Sheet1")` instead of using `ActiveSheet`
Comment: What is the error message?
Comment: Through some testing, I've learned that when I first open the workbook, the first time I click on a day, the code works but does not on a second click of a different day (which day does not seem to be relevant). If I am already selected on any other day aside from sunday, when I click sunday, it will allow me to click Monday on my second try. Only seems to work with sunday selected first then Monday. No other day combination seemed to allow me to select other days beyond the first try.
Comment: I've tried it with the sheet specified before but did as you suggested. Performed multiple tests again, same error.
Comment: "Run-Time error '1004': Unable to set the Orientation property of the PivotField class"
Comment: Maybe try looking at: https://stackoverflow.com/questions/1388244/excel-vba-error-hiding-calculated-field-in-pivot-table
Answer: It is highly unadvised to use ActiveSheet in a macro, especially if the worksheets of your workbook look differently (which is most probably the case here).
If your code is relevant for different sheets, then you might start your macro with something like:
if ActiveSheet.Name <> "This is the correct one"
then Exit sub
else ... (here you have the rest of your original macro)
end if

Good luck
As the problem seems not to be related to the sheet itself, I've been looking for another solution and I found this URL.
Does this answer your question?
Comment: I've ran it with active sheet and specified sheet and both give me the same error. As suggested though, I've specified the sheet to avoid any future possible errors.
Comment: @Jason: I've been looking on the site and found a question with a similar error message. Can you check this out?
Comment: I tried to read through that discussion and I think that there was a solution but I'm not sure how to get it to work with my code. I tried a more recent solution that was posted (the one with pivotitems.visible=false but no feedback if it was an actual solution) but I couldn't get that one to work for me either.
Answer: Don't repeat same code over and over. Instead use procedures and functions with parameters like shown below.
The Sub Sun(), Sub Mon() and so on are only needed if you want to link them to a button or something. Otherwise you can omit them and directly run PreparePivot "1 Sun" form other procedures if needed.
Option Explicit

Public Sub Sun()
    PreparePivot "1 Sun"
End Sub

Public Sub Mon()
    PreparePivot "2 Mon"
End Sub

'and so on for other days

Private Sub PreparePivot(ByVal DayName As String)
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("SheetThatHasYourPivot") 'adjust

    With ws
        .PivotTables("PivotTable1").PivotCache.Refresh
        .PivotTables("PivotTable1").PivotFields("1 Sun").Orientation = xlHidden
        .PivotTables("PivotTable1").PivotFields("2 Mon").Orientation = xlHidden
        .PivotTables("PivotTable1").PivotFields("3 Tue").Orientation = xlHidden
        .PivotTables("PivotTable1").PivotFields("4 Wed").Orientation = xlHidden
        .PivotTables("PivotTable1").PivotFields("5 Thu").Orientation = xlHidden
        .PivotTables("PivotTable1").PivotFields("6 Fri").Orientation = xlHidden
        .PivotTables("PivotTable1").PivotFields("7 Sat").Orientation = xlHidden

        With .PivotTables("PivotTable1").PivotFields(DayName) 'here it uses the parameter DayName that was submitted
            .Orientation = xlRowField
            .Position = 8
        End With
    End With

    With ThisWorkbook
        .SlicerCaches("Slicer_1_Sun").ClearManualFilter
        .SlicerCaches("Slicer_2_Mon").ClearManualFilter
        .SlicerCaches("Slicer_3_Tue").ClearManualFilter
        .SlicerCaches("Slicer_4_Wed").ClearManualFilter
        .SlicerCaches("Slicer_5_Thu").ClearManualFilter
        .SlicerCaches("Slicer_6_Fri").ClearManualFilter
        .SlicerCaches("Slicer_7_Sat").ClearManualFilter

        With .SlicerCaches("Slicer_" & Replace$(DayName, " ", "_")) 'here it replaces the space in the parameter eg "1 Sun" with an underscore "1_Sun"
            .SlicerItems("6am").Selected = True
            .SlicerItems("x").Selected = True
            .SlicerItems("off").Selected = False
            .SlicerItems("(blank)").Selected = False
            .SlicerItems("5th").Selected = True
            .SlicerItems("6th").Selected = True
            .SlicerItems("PTO").Selected = True
        End With
    End With
End Sub

This way the long code is only written once and you just need the short subs to link them to a button. This way the code is much easier to maintain and easier to make consistant for all days.
Comment: So far, my experience with VBA is making changes to recorded macros which is limited. I tried your method and it works great! ….  except that I still get the same error.   Run-Time error '1004': Unable to set the Orientation property of the PivotField class. I also need to point out that it generally only happens on the second time I click a day (except Sunday to Monday). After I've clicked a day, if I want to change days again, I have to close it out, reopen, and then I can click a different day.
Comment: Not sure if VBA can do this, but I was thinking that if VBA can check to see what field is located in position 8 (for example), then insert that field into the x1Hidden command, it would reduce the likelihood of an error. I think the error is happening because I am asking the code to hide fields that are already hidden... maybe?


Eclipse Code Formatter Profile within IntelliJ: Javadoc formatting

Question: as all the other collegues are working with eclipse for an project I have imported the Eclipse Formatter profile xml file and imported it within IntelliJ so far everything seems to be ok, but there is a difference with the javadoc formatting and I could not find the place where to adjust this value.
Eclipse: 12 spaces indent for parameter description
<code> * @param first
 *            The first parameter. For an optimum result, this should be an
 *            odd number between 0 and 100.
</code>
IntelliJ: 10 spaces indent
<code> * @param i
 *         short named parameter description
</code>
The simplest solution would be to turn off formatting javadoc within IntelliJ but maybe there is a better one?
I have tried spotless maven plugin with the xml profile and the import order but it was also messing around with the javadoc.
Since java is quite grown-up programming language and is widely used I am wondering how this can be. Google code format is not an option so far. But an code formatter which you can customize to that level would be great. Any suggestions?
Thanks and Best Regards
Matt
Comment: It's a known limitation of IntelliJ not covering all Eclipse formatting settings.
Answer: The indent size for parameter descriptions is defined by the "Continuation indent" value (Settings/Preferences -> Editor -> Code Style -> Java -> Tabs and Indents)
That will affect more than just parameter descriptions, though, so I'm not sure if that would work for you.
Another option for you might be configuring Adapter for Eclipse Code Formatter
One more thing I can think of is EditorConfig, but it will require some configuring on both Eclipse and IDEA ends.
Comment: Thanks for the answer, I installes the adapter for eclipse code formatter in IntelliJ but there are still differences in line breaks and the way long expressions with chained function calls etc. are splitted. I miss something like black that I used for my python and django projects.


DUVIDA SELECT COM INNER JOIN E COUNT

Question: Ola,sou relativamente novo quando o assunto e banco de dados e preciso gerar um relatório com as seguintes informações,mas não estou conseguindo alguém poderia me dar uma luz por favor:
Nome do cliente
Qtd de compras realizadas por cada cliente
Total em R$ das compras de cada cliente
Qtd de compras realizadas no ano atual de cada cliente
Total em R$ das compras no ano atual de cada cliente
Foto do perfil (foto com ordem_foto = 1)
considerando apenas compras com o status (sel_status_compra) concluido
com as seguintes tabelas
tabela clientes_fotos:

tabela compras acima

tabela itenscompra acima

tabela clientes acima
Comment: Passe o esquema das tabelas como texto.
Answer: Não vi nenhum campo do tipo data para filtrar a data das compras pelo ano, mas tentei deixar a query mais próxima possível. Tenta aí no seu computador e ajuste o que for necessário.
<code>select
    cli.nome_cliente,
    count(c.id_compra),
    sum(ic.valor_itemc),
    count(sra.id),
    sum(sra.valor),
    cf.url_foto
from cliente cli
    inner join compras c on cli.id_cliente = c.fk_id_cliente_clientes
    inner join itenscompra ic on ic.fk_id_compra = c.id_compra
    left join (select * from clientes_fotos where ordem_foto = 1) cf on cf.fk_id_cliente_clientes = cli.id_cliente
    left join (select compras.fk_id_clientes_clientes, compras.id_compra, sum(itenscompra.valor_itemc) as valor
                from compras
                    inner join itenscompra on itenscompra.fk_id_compra = compras.id_compra
                where year(compras.**ALGUM CAMPO DATA NA TABELA COMPRAS**)=2019 and compras.sel_status_compra = "Concluido"
                group by compras.id_compra) sra on cli.id_cliente = sra.fk_id_cliente_clientes
where
    c.sel_status_compra = "Concluido"
group by cli.nome_cliente, cf.url_foto
</code>
Comment: muti obrigado irmão,fiz os ajustes e funcionou aqui.

DUVIDA SELECT COM INNER JOIN E COUNT


Puck going out of bounds 'directly' off faceoff

Question: "When the puck goes outside the playing area directly off the face-
off, regardless as to which player may have last contacted the puck,
the face-off shall remain in the same spot and no penalty will be
assessed to either team for delaying the game."
Seems fairly straightforward, but I have a question about interpretation. Does this simply mean cases where the puck is pulled out of play by one of the two centers participating in the faceoff, and the puck goes out of play without touching or deflecting off a winger or defenseman, or can the language be interpreted to include situations where the puck is drawn back by either of the centers and it immediately glances off another player on either team as a direct result of the won faceoff being drawn to them?
In other words, does "directly" refer to timing and include immediate subsequent deflections as a result of a faceoff, or does it only refer to the centers taking the draw and either of them propelling the puck out of play (non-deflected) off the faceoff? The added part about delay of game seems to support the non-deflected case. Is that Right?
Answer: Yes Rule 85 "Puck out of Bounds" seems up to interpretation by the officials on the ice at the time of play.  "Directly off of the face off" leads me to believe it could deflect off of a tertiary player to the face off or an official themselves and the face off would be repeated in the same position but it is one of the grey areas of the game that change depending on who is making the call and their point of view.
Comment: Perhaps my supposition should have been a comment rather than an answer.  As I stated "it seems" and "leads me to believe" which were not backed up by sources rather my personal experience with the game for decades. I agree with Matt in that interpretation varies and it could be called either way. It seems it would be a case by case basis called by on ice officials so there wouldn't be more clarification.
Comment: Do you have a reliable source that shows this to be the (majority/only) interpretation in use? One or two example incidents are not enough - officials do make mistakes and that doesn't mean the rule changes.


Ordem de plotagem scatterplot ggplot2

Question: Eu estou fazendo um scatterplot e mapeando os pontos por cor (duas categorias) e tamanho (uma variável discreta).
Os pontos devem se sobrepor, pois são medidas de um mesmo lugar, em épocas diferentes
O problema é: o ponto de maior tamanho é plotado 'na frente' do menor, aí sobrepõe.
Mesmo usando alpha pra deixar 'transparente' tá ficando muito feio.
Existe algum jeito de eu inverter a ordem que o ggplot plota as variáveis?
Aqui tá um print do gráfico. Idealmente, os pontos pretos deveriam ser plotados atrás dos pontos vermelhos.

Edit:
LIGHT <-
 structure(list(Sensor = c("Sensor 01", "Sensor 02",
 "Sensor 03", "Sensor 04", "Sensor 05", "Sensor 06",
 "Sensor 07", "Sensor 08", "Sensor 09", "Sensor 10",
 "Sensor 11", "Sensor 12", "Sensor 13", "Sensor 14",
 "Sensor 15", "Sensor 01", "Sensor 02", "Sensor 03",
 "Sensor 04", "Sensor 05"), Light = c(29.2326025,
 19.1888217741935, 20.2879273387097, 22.6006463709677,
 29.4652291129032, 31.4922126612903, 18.0189039516129,
 44.2132503225806, 19.6836093548387, 29.6778536290323,
 23.7034666935484, 37.4008766935484, 32.4513981451613,
 57.5753566129032, 41.8583696774194, 64.6308373214286,
 44.2330882142857, 45.8567069642857, 61.8264760714286,
 57.66113125), Dif_PAR.sensor = c(136.820568709677,
 146.864349435484, 145.765243870968, 143.45252483871,
 136.587942096774, 134.560958548387, 148.034267258065,
 121.839920887097, 146.369561854839, 136.375317580645,
 142.349704516129, 128.652294516129, 133.601773064516,
 108.477814596774, 124.194801532258, 81.3658292857143,
 101.763578392857, 100.139959642857, 84.1701905357143,
 88.3355353571429), Percent_of_PAR = c(19.0689480982097,
 14.2716407995484, 15.1293532713629, 15.8380714606935,
 17.456968456871, 18.0777406968065, 13.7234488349113,
 72.7551326408065, 11.6857118804435, 21.3044665453226,
 16.434219278871, 25.781927983129, 23.9310200270565,
 42.2960034949194, 32.4126078909758, 39.0122370998214,
 26.402147205, 30.3298732019643, 36.2347200010714,
 31.7127142146429), Height = c(11.3, 11.65, 12.8, 13.1,
 13.1, 13.45, 13.5, 15.05, 16.15, 16.5, 17.7, 18.45, 18.5,
 19, 20.1, 11.3, 11.65, 12.8, 13.1, 13.1), North = c(0, 0,
 0, 1.5, 3, 0, 0, 0, 1.9, 2.3, 0.4, 0, 4.2, 0, 1, 0, 0, 0,
 1.5, 3), South = c(0, 0, 0, 0, 0, 0.1, 1.5, 0.7, 0, 0, 0,
 0, 0, 0.2, 0, 0, 0, 0, 0, 0), East = c(0.3, 0, 1.9, 0, 0.7,
 0, 0, 0.3, 0, 0.6, 1, 0, 0, 0, 0.2, 0.3, 0, 1.9, 0, 0.7),
 West = c(0, 0, 0, 0, 0, 2.5, 0.1, 0, 1.9, 0, 0, 2, 0, 0,
 0, 0, 0, 0, 0, 0 ), Northeast = c(0, 0, 2.45, 1.95, 3.55,
 0, 0, 0, 0, 2.9, 1.6, 0, 0, 0, 1.5, 0, 0, 2.45, 1.95, 3.55),
 Northwest = c(0, 0, 0, 0, 0, 0, 0, 0, 3.25, 0, 0, 0, 4.6,
 0, 0, 0, 0, 0, 0, 0), Southeast = c(0.85, 0, 0, 0, 0, 0, 0,
 1.3, 0, 0, 0, 0, 0, 0, 0, 0.85, 0, 0, 0, 0), Southwest = c(0,
 0, 0, 0, 0, 2.95, 1.95, 0, 0, 0, 0, 2.5, 0, 0.8, 0, 0, 0, 0,
 0, 0), Dist_to_tree_center = c(0.85, 0, 2.45, 1.95, 3.55,
 2.95, 1.95, 1.3, 3.25, 2.9, 1.6, 2.5, 4.6, 0.8, 1.5, 0.85,
 0, 2.45, 1.95, 3.55), N_S = c(-0.5, 0, 0.5, 1.9, 3.4, -0.5,
 -1.9, -1.1, 2.3, 2.7, 0.8, -0.5, 4.6, -0.6, 1.4, -0.5, 0, 0.5,
 1.9, 3.4), E_W = c(0.7, 0, 2.4, 0.5, 1.1, -2.9, -0.5, 0.7,
 -2.3, 1, 1.4, -2.4, -0.5, -0.5, 0.6, 0.7, 0, 2.4, 0.5, 1.1),
 Aspect = c("Southeast", "On the bole", "Northeast",
 "Northeast", "Northeast", "Southwest", "Southwest",
 "Southeast", "Northwest", "Northeast", "Northeast",
 "Southwest", "Northwest", "Southwest", "Northeast",
 "Southeast", "On the bole", "Northeast", "Northeast",
 "Northeast"), Leaf_set = c("With", "With", "With",
 "With", "With", "With", "With", "With", "With", "With",
 "With", "With", "With", "With", "With", "Without",
 "Without", "Without", "Without", "Without")),
 row.names = c(NA, 20L), class = "data.frame")

O código que eu usei foi esse:
ggplight <- ggplot(LIGHT, aes(x=Dist_to_tree_center, y=Height, size = Percent_of_PAR, color=Leaf_set))+
  scale_color_manual(values=colors, labels=c("With leaves", "Without leaves"))+
  geom_point(alpha=.4) +
  scale_size(range = c(3, 15), name="Light")+

  labs(x = 'Distance to tree centre (m)', y = 'Height (m)', color='', title = '(b)', subtitle = '')+

  theme_classic(base_size = 30)+
  theme(panel.background = element_blank())+
  theme(panel.grid.major = element_blank())+
  theme(panel.grid.minor = element_blank())+
  theme(plot.background = element_blank())+
  guides(color = FALSE)+
  theme(legend.position=c(1,0.1), legend.justification=c(1,-0.1))+
  theme(legend.background = element_rect(fill="transparent"))

Comment: Pode, por favor, **editar a pergunta** com a saída de `dput(LIGHT)` ou, se a base for muito grande, de `dput(head(LIGHT, 20))`?
Comment: Vê se era isso, por favor.
Comment: Sim era isso mesmo, obrigado.
Comment: No entanto, com os dados da pergunta, não há pontos de cores diferentes sobrepostos.
Comment: Desculpa se tá confuso. O que eu fiz foi: usei "Height" no eixo y e "Dist_to_tree_center" no eixo x. os valores plotados mapeados com size são os de "Percent_of_PAR" e usei cor pra mapear "Leaf_set".
Answer: Uma maneira de plotar os pontos mais pequenos por cima dos maiores é reparar que os pontos mais pequenos correspondem ao Leaf_set == "With" e usar duas geom_point, filtrando o Leaf_set correspondente a cada um dos valores. Primeiro a "Without" e de seguida a "With".
library(ggplot2)

ggplight <- ggplot(LIGHT, aes(Dist_to_tree_center, Height, size = Percent_of_PAR, color = Leaf_set))+
  geom_point(
    data = subset(LIGHT, Leaf_set == "Without"),
    alpha = 0.6
  ) +
  geom_point(
    data = subset(LIGHT, Leaf_set == "With"),
    alpha = 0.6
  ) +
  scale_color_manual(breaks = c("With", "Without"), values = colors) +
  scale_size(range = c(3, 15), name="Light")+
  labs(x = 'Distance to tree centre (m)', y = 'Height (m)', color='', title = '(b)', subtitle = '') +
  guides(color = "none") +
  theme_Mariana()

ggplight

theme do gráfico
theme_Mariana <- function(){
    theme_classic() +
    theme(
        title = element_text(face = "bold"),
        axis.title = element_text(face = "bold"),
        panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.background = element_blank(),
        legend.title = element_text(face = "bold"),
        legend.text = element_text(face = "bold"),
        legend.position = c(1, 0.05),
        legend.justification = c("right", "bottom"),
        legend.background = element_rect(fill = "transparent")
    )
}

Comment: Vou rodar aqui meu script e confirmar os dados, só um instante, por favor.
Comment: Ah, acho que entendi o que houve. Quando eu enviei o output de "dput(head(LIGHT, 20))" não pegou todo o conjunto de dados, então ficaram faltando os dados referentes a algumas sobreposições. Mas algumas saíram (os 5 pontos da parte inferior). É exatamente isso que acontece no meu gráfico. Queria um jeito de plotar o círculo maior por baixo, invertendo a ordem com que eles se sobrepõem.
Comment: @Mariana O códiog anterior estava errado, troquei as cores e não consegui ver nada de errado. Veja agora.
Comment: É isso sim! O que você trocou? \o/
Comment: AAAhh, achei agora o que você escreveu!! Desculpa, primeira vez usando aqui. Obrigada, Rui!! Um ótimo domingo!
Comment: @Mariana O que fazer quando [alguém responde](https://stackoverflow.com/help/someone-answers) às suas perguntas.
Comment: Ahhh, entendi! Acho que eu fiz certo, mas se estiver errado, me diz que eu mudo.
Pôxa, de novo, muito obrigada!

Ordem de plotagem scatterplot ggplot2


Running Deep Learning model using Kubernetes

Question: I am in stage of deploying a deep learning model using Kubernetes. My questions are  as follows:
1: Does kubernetes supports parallel processing?. After preprocessing the data, need to run deep learning model with different set of hyper parameters. Is it possible to run it parallely on different pods and whats the python code for it.?

If a particular pod fails or breaks while running, will it enable another pod (copy of the original pod) to run automatically?
Also, if a particular pod reaches certain percentage of GPU (threshold), will it make another pod to run automatically?.

I need your help on this. I am finding much tutorial on this. Also, looking for  python code to perform all these actions.
Thanks
Answer: This seems like no prior research has been put into this question, and you are not a new member - so for the future please try to ask concrete questions on what problems did you meet as it shows that you have put an effort before asking question. I will try to answer from Kubernetes perspective as I had no opportunity to use deep learning on Kubernetes, yet.

Kubernetes does support parallel processing. The cluster is a set of "independent" nodes each with its own memory and CPU but they are connected through a network and can be used all together to solve a common task. You can have multiple pods/jobs running what you need. More about it in context of ML here and an example of Deep Learning on Kubernetes here.
Pod as a basic building block in Kubernetes is also a representation of a running process on your cluster. They are what we could call cattle. We consider them ephemeral entities that can be replaced or discarded at will. Common practice is to not create Pod itself but for example Deployments which will make sure you always have a specified number of Pods running (when one dies, another is created on it's place to keep the specified number). You can find more about controllers here:

They can be responsible for replication and roll-out and providing self-healing
  capabilities at cluster scope.

Not sure about GPU as I did not use it too much, but Kubernetes definitely can scale based on CPU and Memory, you can also set Resources and Limits to control this. I believe Cluster Autoscaler can scale based on GPU as there is a specific metric for GPU:

Minimum and maximum number of different GPUs in cluster, in the format
  ::. Cluster autoscaler will not scale the cluster beyond
  these numbers. Can be passed multiple times. CURRENTLY THIS FLAG ONLY
  WORKS ON GKE.


Creating module with autocomplete and accepting multiple values in textfield

Question: I am creating my own form in my module using the Form API.
How do I enter multiple values in the below textfield and have it autocompleted, and suggested (separated by commas, for example)?
Right now it takes whatever is in the textfield box as one single big string.
$form['keywords'] = array(
  '#type' => 'textfield',
  '#title' => t('Keywords'),
  '#size' => '40',
  '#multiple' => TRUE,
  '#autocomplete_path' => 'papers_pub_search/keywords_autocomplete'
);

function _autosearch($string) {
  $query = "SELECT name FROM users WHERE name LIKE :name";
  $result = db_query($query, array(':name'=> '%' . db_like($string) . '%'));
  foreach($result as $row) {
    $match[$row->name] = check_plain($row->name);
  }
  drupal_json_output($match);
}

Answer: You can use the following code.
function _autosearch($string) {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
      $matches[$value] = check_plain($value);
    }
  }

  drupal_json_output($matches);
}

This is the result.

If you want to avoid a username can be used more than once, then you can use the following code.
function _autosearch($string = '') {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      if (!in_array($user->name, $items)) {
        $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
        $matches[$value] = check_plain($value);
      }
    }
  }

  drupal_json_output($matches);
}

Comment: Also, instead of array_map(), I used drupal_explode_tags().  It seems to give more flexibility on how keywords are separated.  http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_explode_tags/7
Comment: Thumbs up for the answer, Is there any module/solution for Drupal 8?
Comment: This is a perfect example!  Worked well.  The one difference was that I used db_query() instead of your db_select().  Seems to make no difference.
Comment: Here is d6 module which uses similar code provided by kiamlaluno https://www.drupal.org/project/multiple_users_autocomplete


Rules activates but not firing in JESS

Question: I am new to JESS and I know a little of its functionality. I have a program that asks for a students id-number and the program goes and gets the student's subjects.
The thing is by the end of procedure the program asks the user if he/she wants to get another student's subjects.
If the user wants to input another student, It will go back to the first rule that fired but when I tried that, the rule only activated and did not fire.
What could be the problem? I made sure there was (run) of course.
Here's my code.
<code>(defrule check-subject
    ?a <- (phase check-back)
    ?stud <- (lookupID (id ?id))
    (student-information (id-number ?id)
                         (course ?course)
                         (subjects-taken $?taken)
                         (year ?year)
                         (semester ?sem))
    (prospectus-information (curriculum-name ?course)
                            (1st-year-1st-sem-subjects $?subjects1))
    =>
     (printout t "Student took: " (intersection$ $?taken $?subjects1) crlf)
     (printout t "Student flunked: " (complement$ $?taken $?subjects1) crlf)
     (assert (back-subject (complement$ $?taken $?subjects1)))
     (retract ?a ?stud)
     (ask))
</code>
And I have the function ask
<code>(deffunction ask ()
  (printout t "Consult another? (y/n) ")
  (if (eq (read) y)
  then (assert (phase choose-student))))
</code>
And my defrule when phase choose-student is asserted
<code>(defrule student-select
    (phase choose-student)
    =>
    (printout t "Input Student ID: ")
    (assert (lookupID (id (read)))))
</code>
The rule student-select, activates but never fires. My program stops there.
Comment: The problem is a mistake in the Jess code. This can be discovered and fixed by people being able to look at the relevant code.
Comment: I have edited my post. Please do help me. Thank you.
Comment: Make sure to *accept* answers if they are of any use. It's not necessary to write "Thank you"-comments.
Answer: It's better to write the control part of an application separate from the rules.
<code>(deffunction ask ()
  (printout t "Consult another? (y/n) ")
  (if (eq (read) y) then
    (printout t "Input Student ID: ")
    (assert (lookupID (id (read))))
    (return TRUE)
  else
    (return FALSE)))
</code>
Use this in a while function:
<code>(while (ask) do (run))
</code>
And you won't need the <code>(phase choose-student)</code> any more.
Comment: I based my codes from jess' sample program the sticks.clp whereas it asks for the user if he/she wants to restart again. My problem really is that my rules just activates and never fires. It stops there.
Comment: I tried using your suggested code but when I input the student ID it wont let me check if it exists in my database but your code enlightened me. I placed a (run) inside the ask-function and the student-select rule fired. Thank you!
Comment: It would "let you check" if you would follow my suggestions precisely. I suspect you didn't omit `(phase check-back)` from the rule.
Comment: I did mam. My check-student-id rule just activated but did not fire.
Comment: Not really sure what you mean by "activated", but if you use it in the usual sense, i.e., that it is ready to fire because there's (at least) on set of matching facts, then only a failure to call `(run)` will keep it from being fired.

Rules activates but not firing in JESS


Orthogonal projection matrix onto a plane

Question: To find, for example, the orthogonal projection matrix onto the plane:
$$x-y-z = 0$$
... we would choose two independent vectors that lie on the plane, use them as columns of a matrix A, and use the following equation:

As I understand it, this works because this matrix essentially projects onto the column space of A, but given how we have created matrix A, the column space of the matrix is exactly equal to the plane of interest.
However, does this method still apply for planes not passing through the origin?
Because as far as I know, column space (when it is a 2D subspace of $R^3$) is a plane through the origin. So, if you take two independent vectors on a plane not passing through the origin, and come up with an orthogonal projection matrix as I have described, surely that matrix would project onto a plane that is through the origin (the column space of A), and not the intended plane (albeit the two planes would have the same basis/direction vectors)?
Am I missing something here?
Comment: Projections onto affine spaces (e.g. planes not containing the origin) are not linear transformations (e.g. note that $0$ is not mapped to $0$) and cannot be expressed as $f(v) = Pv$ for some matrix $P$.
Comment: A common way of dealing with this non-linearity is to conjugate by a translation map. Pick some individual point $\vec{x}_0$ in the plane, and two linearly independent direction vectors parallel to the plane (i.e. vectors between two points in the plane). Compute the matrix $P$ with these two direction vectors. Then, the projection onto the plane (not through the origin) of a vector $\vec{x}$ is given by $P(\vec{x} - \vec{x}_0) + \vec{x}_0$.
Answer: If the plane equation is
$ n^T (r - r_0) = 0 $
Then let
$ A = [u_1, u_2] $
where $n \cdot u_1 = n \cdot u_2 = 0 $ and $u_1 $ and $u_2$ are linearly independent.
Then the projection of a point $P$ onto the plane is
$ \text{Proj}(P) = r_0 + A (A^T A)^{-1} A^T (P - r_0) $
To derive this formula, note that
$ r = r_0 + A u $
where $ u \in \mathbb{R}^2 $.  Since we want $r$ to be the projection of $P$ onto the plane, then
$ P - r $ is perpendicular to the plane, i.e. perpendicular to $u_1$ and $u_2$, therefore,
$ A^T (P - r_0 - A u) = 0 $
From which
$ u = (A^T A)^{-1} A^T (P - r_0)$
Hence,
$ \text{Proj}(P) = r = r_0 + A u = r_0 + A (A^T A)^{-1} A^T ( P - r_0) $


Mathematical demonstration of the distance concentration in high dimensions

Question: I know that in high-dimensional space, the distance between almost all pairs of points has almost the same value ("Distance Concentration"). See Aggarwal et al. 2001, On the Surprising Behavior of Distance Metrics in High Dimensional Space.
Is there a mathematical way to observe this phenomenon?
Answer: There is a simple mathematical thought experiment that sheds light on this phenomenon, although it might not seem immediately applicable.  I will therefore describe this experiment briefly and follow that, in a separate section, by a computer analysis of a concrete situation.

A Thought Experiment
An old cartographic chestnut is that most of the area of a map lies near its edges.  Similarly, much of a pizza--more than you might think--consists of its crust.  Even more so is the fact that a great deal of the volume of a thick-skinned fruit, like a grapefruit or watermelon, is in its skin.

More than half this pizza lies near its edge, outside the shaded area.  However, the width of this "crust" is only $18\%$ of the diameter of the pie.
Maps and pizzas and grapefruits don't have a common shape, but there is a common underlying explanation.  We may model the border of a map, the crust of a pizza, or the skin of a fruit by supposing its basic shape -- a rectangle, circle, sphere, or whatever -- has been shrunk uniformly by some factor $\alpha$ and that the "crust" or "rind" consists of what lies between these two concentric similar shapes.
In $n$ dimensions (the examples involve $n=2$ or $n=3$), the $n$-dimensional volume of the interior will therefore be $\alpha^n$ times the volume of the original shape.  (This volume scaling law is sometimes used to define the number of dimensions of a space.)  The volume of the rind relative to the original volume therefore is
$$1 - \alpha^n.$$
As a function of $\alpha$ its rate of growth is
$$\mathrm{d}(1 - \alpha^n) = -n\,\alpha^{n-1}\,\mathrm{d}\alpha.$$
Beginning with no shrinking ($\alpha=1$) and noting $\alpha$ is decreasing ($\mathrm{d}\alpha$ is negative), we find the initial rate of growth of the rind equals $n.$
This shows that the volume of the rind initially grows much faster -- $n$ times faster -- than the rate at which the object is being shrunk.  The factor of $n$ implies

in higher dimensions, relatively tiny changes in distance translate to much larger changes in volume.

Let's call this the "edge-of-map principle."
Consider, now, a tabular dataset consisting of observations of $n$ numerical features.  We may view each observation as a point in $\mathbb{R}^n$ and (at least in our imagination) might also suppose this collection of points is contained within some kind of compact region $\mathcal D$ with relatively simple boundary.
If we choose to use Euclidean distances to compare these points to each other (and to other points in $\mathcal D$) and consider an arbitrary observation $x,$ the edge-of-map principle implies that most of the room in $\mathcal D$ is nearly as far as possible from $x.$  (The fudge term "nearly" is needed to account for what goes on around the boundary of $\mathcal D.$)
Another implication that goes to the heart of the question is the generalization of the cartographer's quandary: if our observations are somewhat "spread out" over $\mathcal D,$ then the cartographer's question is "what proportion of this dataset is near the boundary?"  To express this in a quantitative fashion, let's invert it: we ask, by how much should we shrink $\mathcal D$ to make it, say, only half its original volume?  Let's call this the "half-length" of $\mathcal D,$ analogously to the half-life of a radioactive decay.
If the half-length is $\alpha,$ we need only solve the equation
$$\alpha^n = \frac{1}{2};\quad \alpha = 2^{-1/n} = e^{-(\log 2)/n} \approx 1 - \frac{\log 2}{n} \approx 1 - \frac{0.7}{n}.$$
In two dimensions the half-length is $1 - 0.35.$  Since half of the shrinking occurs on one side of the map or pizza and the other half on the other side (refer to the preceding figure), half of the area of a map ($n=2$) lies within (approximately) $35/2=18\%$ of its diameter from the boundary.
In three dimensions the half-length is $1 - 0.23:$ now, half the volume of a fruit lies within $12\%$ of its diameter from its boundary. A fruit whose skin is just one-eighth the width of the entire fruit is more than half skin.

Despite appearances, approximately half the volume of this grapefruit is rind.  (Source: FreeDigitalPhotos.net.)
In very large dimensions the half-length is very close to $1.$  In $n=350$ dimensions it is greater than $98\%,$ within two percent of $1.$  Thus, expect half of any $350$-dimensional dataset to lie within $1\%$ of its diameter from its boundary.  Unless the data are strongly clustered, this generalization will be accurate.
Another way to express these results is:

Absent strong clustering, in higher dimensions $n$ we can expect most Euclidean distances between observations in a dataset to be very nearly the same and to be very close to the diameter of the region in which they are enclosed.  "Very close" means on the order of $1/n.$

Several parts of this analysis are really just hand-waving and approximations, due to the vagueness of $\mathcal D$ and the very general assumptions about the dataset.  How is $\mathcal D$ defined, anyway?  In some applications it is determined by inherent limits; for instance, when all features are proportions.  In many applications the features are arbitrarily scaled to lie within a fixed interval ("normalized") and we often take $\mathcal D$ to be the corresponding hypercube.  But that's only an artifice and it is exquisitely sensitive to any outlying data values.  The rest of this post explores an alternative in which the boundary plays a less important role in the results.  It comes to similar conclusions.

Analysis of distances in a closed Euclidean space
I find the paper's setting rather arbitrary, because it is exploring distances within unit cubes.  The distance distributions depend strongly on the shapes of the boundaries of those cubes.
There's a way to avoid boundary effects.  In one dimension, the "cube" is just the unit interval, $[0,1].$

Because this interval has two ends, some of the points are far from the rest; others (near the middle) tend to be close to all the points.   This is asymmetric.  To remove the asymmetry, roll the interval around into a loop where the beginning point $0$ meets the end point $1:$

Geometrically, all its points are equivalent.
We can do the same in higher dimensions by rolling up each coordinate separately into a loop.  The result in dimension $d$ is the $d$-torus.  It has no boundaries and all points are geometrically equivalent.  It's not perfectly symmetrical like a sphere, though: unlike the (Euclidean) sphere, whose geometry no longer is Euclidean due to its curvature, these $d$-tori are flat, without curvature.  They can give us insight into Euclidean distances without the complication of dealing with boundaries.
Analytical study of the distances in a torus is complicated, at least for dimensions greater than $1.$  Let's study these distances by generating random points from the uniform distribution on a $d$-torus and computing all their mutual distances (apart from the necessarily zero distances between each point and itself).  For the following figures I generated 500 points in each of eight separate dimensions, resulting in over 100,000 distances in each dataset.  How are these distances distributed and how do those distributions vary with the dimension $d$?
Here is an array of histograms of these distances, one per dimension.

It's not hard to prove mathematically what the eye already sees: the distributions tend to a Gaussian, or "Normal," shape, as the dimension increases.
There is another remarkable regularity: the spreads of these histograms are nearly constant.  Beneath each I have printed the standard deviation (SD) of the distances.  It hardly changes from $1$ through $128$ dimensions.  In this sense, there is no "concentration" of distances in high dimensions at all!
Here are the same figures shown on a common plot for easier comparison:

The colors mean the same as before, showing that the average distances increase with dimension.  They do so roughly with a square-root law: the average distance is about one-quarter the square root of the dimension.  (Those familiar with the Pythagorean Theorem in higher dimensions will at once understand why.)  The greatest possible distance in the $d$-torus is achieved by pairs of points whose coordinates all differ by $1/2$ (because you cannot get any further apart than that along a loop); that distance obviously is $\sqrt{d}/2.$
Thus, it makes sense to compare the relative distances in each dimension.  Here we go with one more plot of the same datasets, now with the distances all divided by $\sqrt{d}/2:$

This normalization has centered the histograms near $0.58,$ regardless of dimension.  Here we are looking at the clearest manifestation of a "concentration of distance:" although the relative distances are typically the same in each dimension, as the dimension increases the distances concentrate more closely around a central value.  As you can tell from the posted standard deviations, they too enjoy an inverse square-root law: the spread of the relative distances is approximately $1/(4\sqrt{d}).$
In other words, around any given point on a high-dimensional torus (and all points are geometrically the same, so it doesn't matter which point), nearly all other points on the torus are nearly the same distance away!  If you were an inhabitant of a high-dimensional flat Euclidean space, albeit one with no boundaries, most of that space would seem to lie close to a spherical shell surrounding you.  In $d$ = a million dimensions, for instance, the maximum possible distance is $500,$ the average distance would be around $288.7,$ and virtually all distances would be within $0.5$ of that value.

All these general conclusions about the shape, typical value, and spread of Euclidean distances hold in other domain shapes, but the details vary.  The general result, though, is that randomly selected points within reasonably compact high-dimensional domains tend not to cluster appreciably.  This has obvious implications for statistical (and machine-learning) methods based on clustering and nearest neighbor analyses.
Comment: +1 Great answer, I really like the idea of using tori for this demonstration.
Comment: Sorry again, if you do not mind sharing the source code for easy replicability. Many thanks.
Comment: @Maximilian Since every part of generating random points on the torus, computing their mutual distances, and plotting the results is straightforward, all you need is the toroidal distance function.  Here is its square: `function(x, y) {
  z <- abs(x - y);
  z <- pmin(z, 1-z);
  sum(z^2)
}` Its arguments are two $d$-vectors with components in the interval $[0,1].$
Comment: @whuber this is really great. I'm trying to wrap my head around this: when you roll a unit interval into a circle to avoid boundary effect, shouldn't you look at geodetic distance instead of L2?
Comment: @Alex That *is* the geodetic distance.  These tori are not curved: their Riemannian curvature is everywhere zero.  It's hard to visualize, though: if you try to represent the 2D torus $S^1\times S^1$ as a surface in $\mathbb{R}^3,$ you do have to curve it-which distorts its metric.  But in $\mathbb{R}^4$ it can be exhibited as a perfectly flat surface.  (In $(x,y,z,w)$ coordinates it is isometric to the intersection of the hypersurfaces $x^2+y^2=1$ and $z^2+w^2=1,$ for instance.)
Comment: I still don't quite understand where does the $\sqrt{d}$ comes from, could you please elaborate more? Thank you
Comment: @FantasticAI It's the Pythagorean Theorem.  When a typical coordinate difference is $x$ and there are $d$ orthogonal coordinates, the typical *squared* distance will be $d$ times $x^2.$  The typical distance is its square root, $\sqrt{d}$ times $x.$
Comment: @whuber thank you for the quick reply. Yes, $\sqrt{d}$ times $x$ is easy to verified. How this property relates to the distance to the origin in high dimensional space?
Answer: Note that this depends on a) the distance measure (you are probably referring to the Euclidean distance) and b) the underlying measure/probability distribution, according to which you specify what "almost all" means. Surely all kinds of values and distributions for the distances are possible if you don't specify these.
That said, for a derivation of required conditions see:
Hall, P., Marron, J.S., Neeman, A.: Geometric Representation of High Dimension Low Sample Size Data. J. Roy. Stat. Soc. B67, 427–444 (2005),
https://www.jstor.org/stable/3647669?seq=1
Ahn, J., Marron, J.S., Muller, K.M., Chi, Y.-Y.: The High Dimension, Low Sample Size Geometric Representation Holds Under Mild Conditions. Biometrika94, 760–766 (2007)
https://www.jstor.org/stable/20441411?seq=1


How to get replacement pattern for Search API's fulltext search in global text area header

Question: In Drupal 7, I'm currently using the default core search, and a view for node search results. I have a global text to pull in the replacement pattern for the term that were searched for. I get the token by adding the contextual filter Search: Search Terms I am using the replacement pattern %1 as seen in the picture:

Then I put You searched for:  %1  in my global text to display the keywords that were searched for:

This all works great for Drupal core search, but I am not finding a way to do this with the view in Search API? I am using Database Service, and a view built from the database index I created. I have tried to find a field such as keywords for the full text search, but since the view is based off of indexed content, I am not able to get those type of fields added, to make them available for tokens, even via relationships. Maybe there is a better way to build the view?
Answer: The problem I was having here is my view that I was trying to build for search API was using a full text search exposed filter rather than a contextual filter. The contextual filter provides the search term title and search term input tokens that are pictured above. The exposed filter will not produce them. Live and learn.
EDIT: There is a bit of a workaround I found but it was an implementation I would not recommend. I was using Drupal core search blocks with Search API view's contextual filters together. I was able to add the contextual filter, get the token, then remove the contextual filter. That somehow allowed the token to work in that context.


elasticsearch null_value replacement not working for integers

Question: i have the following in my mapping. The id can be null sometimes so i am using null_value : 1.
 "Id" : {
        "type" : "integer",
        "store" : true,
        "doc_values" : true,
        "null_value" : 1,
        "index":"not_analyzed"
},

when I try to add documents to the index, I am still getting parse error. How can I fix this?
[2017-12-24 10:42:42,601][DEBUG][action.bulk              ][test-2017-12-24]
[7] failed to execute bulk item (index) index {[test-2017-12-24][test]
org.elasticsearch.index.mapper.MapperParsingException: failed to parse [Id]
    at

Caused by: java.lang.NumberFormatException: For input string: "null"
    at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)

Comment: Only string data types can have "NULL" not integers.
Comment: Which ES version?
Comment: From [here](https://www.elastic.co/guide/en/elasticsearch/reference/current/null-value.html) it looks like you need something like `"null_value": "NULL"` in mapping. Why do you set null value to 1?
Answer: From the error you can see that you try to index the string "null" in the Id field, which it cannot parse into a (nullable) integer. Try putting in null (without quotes)
Comment: This should be marked as the correct answer. Such a simple thing , but very difficult to pinpoint answer.