auto-attach EBS volume to a Spot instance

Question: I need some persistent storage across spot terminations.
My approach to solve the problem is

Write a startup script that attaches and mounts the persistent volume
Snapshot this state and register a private AMI
Launch Spot instances based of the private AMI

searches in this forum [1] suggests this is the correct procedure
My startup script:
#!/bin/sh

echo "executing startup script"

# attach the EBS volume to this machine
aws ec2 attach-volume --volume-id vol-7bef1d96  --instance-id  $(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id ) --device /dev/xvdg

sleep  10

# mount the attached EBS volume
echo "mounting the  attached volume"
sudo mount /dev/xvdg1 /home/ubuntu/persistent/

#run script
echo "starting the  dummy program in background"
python2 persistent/dummyProgram.py &

The script works perfectly if executed manually. However when it is executed by cron the  only the echo statement are executed
the crontab task is
@reboot /path/to/startupScript.sh

How do I solve this problem?
The corrected  crontab entry reads :
USER=username
PATH=content of $PATH
@reboot /path/to/startupScript.sh

Comment: why don't you put this into userdata instead of cron? that's why they are made for: execute some code at startup. By using cron, you expose yourself to path issues that you would probably not have with userdata
Answer: The most likely reason why commands would not be running when invoked from a crontab script is that they are not on the PATH environment variable.  Crontab entries run with a minimal set of environment variables by default.
Comment: or give the *full path* for `aws`, `sudo`, and `python2`.
Answer: While cron could definitely get the job done, the canonical way to do this is to specify a user-data script that runs when the spot instance is launched. With the AWS CLI's request-spot-instance this is specified in JSON using the --launch-specification argument.
http://docs.aws.amazon.com/cli/latest/reference/ec2/request-spot-instances.html
This section can be a small shell script and allows you to change the volume-id should that ever be necessary instead of hardcoding that into the AMI.
Comment: I tried using user-data; But for some reason I failed to make it work.
so I settled for `cron`
I didn,t notice of the hardcoded volume id but as it's not much of a issue I decided to ignore it for now


How to resume iPhone app after a Phone Call

Question: I am creating an iPhone app in which I am providing a call feature with the help of which a user can call place a call on a specified number. I am able achieve the above feature via open URL.
Now after completion of the call I want to resume the execution of app automatically. Although a user can make a fast app switch in iOS 4.0. but I want this to be done automatically.
I have seen the same behavior in "TomTom" app but I am not sure how this app has achieved it.
Thanks
Sandy
Answer: Apple does not allow you to resume an app after a phone call. What you can however try doing is using a local notification.
After calling the 'call' url handler you will need to start a background task and monitor for a call state change:
<code>CTCallCenter *c=[[CTCallCenter alloc] init];
c.callEventHandler=^(CTCall* call){
  if(call.callState == CTCallStateDisconnected) {
    // do stuff here
  }
}
</code>
When you get a call state change, create a local notification to alert the user to resume the app. If the user taps on "view" your application will then come to the foreground. Obviously if the call is longer than 10 minutes this won't work as Apple only allows 10 minutes to background tasks.


Views, add field value as class to list element

Question: I have a content field called Featured which is an list integer checkbox.
When using Views to display a list of this content, I would like to add a css class to the item wrapper when that value is 1 like so:

I suspect editing the views row template would be one option, although I do not know how to achieve this, and since this is the only change I need to make, is there an easier way?
Comment: do you need add some style to your first li element?
Answer: The question is a bit old, but i was looking for the same.
My answer is for drupal 7 / views 3.5, not sure if it works on previous versions.
You can use some field replacement patterns when specifying the classname for the row (in the view edit : Format / Settings / Row Class )
To do so, on the same settings page you may have to check the box 'force using fields'
You then have to make sure the field you want to use is added to the fields section of the view edit
To know what pattern you can use, click on the field in the fields section and go to 'rewrite results' / 'rewrite the output of this field', there is a 'replacement patterns' block that will show you the available patterns.
hope that help, I'm still stuck though by the fact that the string you will get is not class friendly and may contain spaces.
Comment: To make the string 'class-friendly', you can use field rewriting for your field of interest…
Answer: The answers here so far don't answer the question as we're specifically looking to include the value of a field within the views row within the markup of the views row wrapper element. The suggestions so far cover adding a class to the entire view's wrapper or giving a class to a field within the row, which isn't quite right.
Making a views template is a matter of clicking "Theme: Information" (Views 3) and you'll be presented with a list of candidate file template names. Create a new file in your theme with a name more specific than the currently used template (highlighted in bold) then click "rescan template files" or clear the cache.
Sample template files that you can C&P from are in the Views module (of course), look in your "sites/all/modules/views/theme" folder.
Actually creating the Views row template is not particularly hard, so finding "an easier way" might be tough :P
That said, depending on your use case you might just want to exclude all the fields from display, then create a "global: custom text" field and use a token replacement for your "featured" field in a wrapper div/span inside this custom text and drop your desired content within that to create a "row within a row" kind of effect.
Comment: I do know how to use views templates, but I do not know how to get a field value as a class based on it's value.
Comment: I think this answer applies to the *overall* list of views, but the question asker is actually looking to be able to style the items of a field list within content, not the overall list.
Answer: As developpeur 2000 suggested, one way to add a class to these rows is to edit the view and go into Format / Settings / Row Class.
In that input box, enter the token for the field you're interested in displaying, along with any prefixes you'd like to add (in my case, it was "featured-[field_featured]").
If the field you're displaying is a boolean and you want a 0 or 1 as your class, make sure that you have "Key" selected as the formatter under Fields / {Your Field} / Formatter. Otherwise nothing will show up unless you've set an "On value" and an "Off value" in the field's settings.
If you want the boolean to display as "true" or "false," for example, you'll need to set an "On value" and "Off value" for the boolean under Structure / Content Types / {Your Content Type} / Manage Fields / {Your Field}. Then you'll want to use "Default" instead of "Key" as your Formatter in views.
For your specific example, let's assume the content type you're pulling in is called News Articles and the field you're interested in adding as a class is called Featured. Here's a step-by-step that I hope should work for you:

Go into Structure / Content Types / News Articles / Manage Fields / Featured and set the "On value" to featured. Leave the "Off value" blank. Save settings.
Edit your view and click on Format / Settings. Under row class, enter [field_featured]. Apply.
Still in your view edit area, click on Fields / Featured. Make sure the formatter is set to Default. (I also use "Exclude from display" since I don't want this appearing anywhere else in my markup.)
Inspect your list to make sure you've got the "featured" class on items you want featured, then save.

This method avoids editing the views row template, which is nice because it's theme independent this way. You can load up a different theme and you'll still be adding the "featured" class to the same place.
Answer: If I understand well your question, I think that your view have a class to achieve this. You can use your current featured class to style the first element. for example:
li.featured:first-child
{
color:red;
}

regarding add a class according the value of your first LI item, I do not know how to make this from a Drupal way, I just can offer a jquery way:
if your view already have a featured class you can try this, just putting this code in the head of your page.tpl.php

I hope information be useful.
Comment: I am not looking to manually add a class, I need the class to be created based on the value of a field.
Answer: Adding details to the good  answer from  to "developpeur 2000", if the  field type you rely on is "Text List", be sure the output format is "Key".
This will produce safe class names as
views-row-{{ field-Featured }}

"Exclude from output" in field setting is probable necessary also.


Will correlated features reduce the accuracy of a classifier?

Question: Will correlated features reduce the accuracy of a classifier?
Most of the posts related to correlated features talk about using PCA to remove the correlation. My problem is not specific to any algorithms. Or is the question algorithm specific? I understand that correlation may cause numerical troubles in regression but what if we are talking about neural networks, etc.?
Comment: `cause numerical troubles`. After all, are you talking about correlatedness or about multicollinearity? These are different things.
Comment: Reduce the accuracy compared to what?
Comment: @PeterFlom to removing the correlated features
Answer: What you are referring to is called Multicollinearity. There is a lot of views on its impact on your model.
Correlation between your input variables usually cause issues as far as interpreting model coefficients.
As far as predictive accuracy is concerned it should not affect you, but where it causes the most heartache in the the interpretation of your model.
Coefficients can switch signs and be very sensitive to the data it is trained on. If interpretation is of less importance, multicollinearity is less of an issue to you.
Answer: What with some used methods independence of errors is required. This is a much weaker condition than statistical independence of features. For nonlinear models this is rarely a concern though and engineering dependent features might in many cases even improve your precision.


How to select div including a span with specific id via beautifulsoup?

Question: I want to scrape a text of some div that includes a span with specific id or class.
for example:

      text to scrape

      text to scrape

      text to scrape

      text to scrape

I want to get the text in the div (class1) but specifically only the one witch include span (span1)
thanks

Thank you I have solved my problem using this code below:
soup = BeautifulSoup(html, "html.parser")
for x in soup.find_all(class_='class1'):
    x_span = x.find('span',class_='span1')
    print(x_span.parent.text.strip())

Comment: I think at first you should change **** to  ****
Answer: this should do
soup.select_one('.class1:has(#span1)').text

Answer: As Beso mentioned there is an typo in your html that should be fixed.
How to select?
Simplest approache in my opinion is to use a css selector to select all
 that have a  with class named "span1" (cause there is more than one in your example html)
soup.select('div:has(> #span1)')

or even more specific as mentioned by diggusbickus:
soup.select('.class1:has(> #span1)')

To get the text of all of them you have to iterate the result set:
[x.get_text(strip=True) for x in soup.select('div:has(> #span1)')]

That will give you a list of texts:
['text to scrape', 'text to scrape']

Example
from bs4 import BeautifulSoup

html='''

  text to scrape

  text to scrape

  text to scrape

  text to scrape

'''
soup = BeautifulSoup(html, "html.parser")

[x.get_text(strip=True) for x in soup.select('div:has(> #span1)')]


Putting music theme A onto theme B background

Question: A friend has shown me 2 piano books she has where a classical piece is used as the background theme and another non-classical piece is overlaid at intervals.  For example, a piece begins with Liebestraum, and after a few bars it becomes Great Is Thy Faithfulness with a slight adjustment but keeping the Liebestraum harmonic and rhythmic style.  GITF drops out and returns, but Liebestraum finishes the piece.  The only term I can find is "Mashup", which isn't quite right for this.  Is there a name for when one piece is "dropped into" another piece in this manner?
Comment: And the right answer is... "Music". Seriously tho, it's literally "Chord substitution" but that name's already taken, so what is it?
Answer: A technique I liked to practice in my compositions without ever asking for an expression for it.
Now I've found the term "blend":
In the following video a comment says: the tunes have been blended into the music.

Searching for blend two songs I came to the term you mention: mash-up
and this here:
https://www.wikihow.com/Blend-Two-Songs-Together
Well,  I think merging, mixing, mash-up are all terms derived from the music technic scene:

A mash-up is similar to a DJ mix in that the DJ provides few, if any, significant new sounds to the music, other than those required to blend already-existing music. A mash-up differs from a DJ mix in that two or more songs are playing simultaneously, rather than one after the other. In general, in a mash-up, each original source will contribute more-or-less equally to the final work. There is no requirement, however, that the entire mix of each source be used; a common mash-up technique is to use the vocals from one song mixed with the music of another. Songs involved in a mash-up can be indicated with Mash-up Relationship Type.

https://musicbrainz.org/doc/Terminology
But the idea to mix two or more themes together in a composition is much older: already in Baroque era there was a practice to sing several songs together like canons or a quodlibet.
In my view this technic could be simply called a counterpoint (using another existing song as c.p.
One of my favorite examples: Let the sunshine in and  Manchester England from the musical HAIR.
P.S.
Another idea: How about assembling? (related with Ensemble for a group of musicians playing together ...
Edit:
When listening today the Asian sketches by Borodin I reminded your question:

He did exactly what you're asking and "merged" two tunes together . He calls it(double) counterpoint.

The composer told a very surprised and impressed friend about the excellent processing of the themes: "Before I composed this piece, I had already thought up the two themes - the Russian and the Oriental, which were then both brought together in double counterpoint; and only later did I develop the entire accessory for this orchestra picture."

https://en.wikipedia.org/wiki/In_the_Steppes_of_Central_Asia


Piecewise continuous power law distribution sampling

Question: I am trying to sample a piecewise power law distribution:
$$
\
f(x) =
\begin{cases}
  a_1x^{-\alpha_1} & \text{if } x_1 \leq x \leq \tilde{x} \newline
  a_2x^{-\alpha_2} & \text{if } \tilde{x} \leq x \leq x_2 \newline
\end{cases}
\
$$
I want to make this distribution continuous in $\tilde{x}$ so I obtain $a_1 = a_2 \tilde{x}^{ \alpha_1 - \alpha_2} $. Thus I have:
$$
\
f(x) =
\begin{cases}
  a_2 \tilde{x}^{ \alpha_1 - \alpha_2} x^{-\alpha_1} & \text{if } x_1 \leq x \leq \tilde{x} \newline
  a_2x^{-\alpha_2} & \text{if } \tilde{x} \leq x \leq x_2 \newline
\end{cases}
\
$$
To fix $a_2$, I use the normalization of $F(x) = \int_{x_1}^{x_2} f(x) \,dx = 1$.
For the simple case (not piecewise) I just pick a random number $u \in [0,  1]$ and then plug in the inverse of $F(x)$. In this case, I don't know how to continue since I cannot figure out which function to use when I pick a $u$. Furthermore, if I pick some $u$ such that the corresponding $x$ is $x > \tilde{x}$, I need to use only the $F(x)$ corresponding to $x > \tilde{x} $ or I need to use the $F(x)$ for $x < \tilde{x} $ summed with $F(x)$ for $x > \tilde{x} $.
Answer: You can see this distribution as a mixture of two power law distributions,
$$f(x)=\alpha f_1(x) + (1-\alpha) f_2(x)$$
with
$$f_1(x)=\frac{^{−a_1}\mathbb I_{x_1\le x\le \tilde x}}
{\underbrace{\int_{x_1}^{\tilde x} y^{−a_1}\,\text dy}_{\frac{1}{a_1-1}[x_1^{1-a_1}-\tilde x^{1-a_1}]}}
\qquad
f_2(x)=\dfrac{^{−_2}\mathbb I_{x_2\ge x\ge \tilde x}}{\underbrace{\int^{x_2}_{\tilde x} y^{−a_2}\,\text dy}_{\frac{1}{a_2-1}[\tilde x^{1-a_2}-x_2^{1-a_2}]}}$$
and
\begin{align}\alpha&=\tilde x^{a_1−a_2}\frac{1}{a_1-1}[x_1^{1-a_1}-\tilde x^{1-a_1}]\Big/\\
&\quad\left\{\tilde x^{a_1−a_2}\frac{1}{a_1-1}[x_1^{1-a_1}-\tilde x^{1-a_1}]+\frac{1}{a_2-1}[\tilde x^{1-a_2}-x_2^{1-a_2}]\right\}\end{align}
Simulating from $f$ can thus be done by

selecting between $f_1$ and $f_2$ with probabilities $\alpha$ and $1-\alpha$
simulating from the resulting (truncated) power law


XSD: Allowing different elements inside an element only after the first appearance of that element

Question: I have an question about XSD. Is it possible to allow different elements inside an element, if the element already appeared?
Lets say I have this structure:
<entry>
    <col>

    </col>
    <col>

    </col>
</entry>

  <xs:element name="col">
    <xs:complexType mixed="true">
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element ref="a" />
        <xs:element ref="b" />
      </xs:choice>
    </xs:complexType>
  </xs:element>

At the moment the  element can be set every time. But I only want to allow an  element to be set, if the <col> element appeared atleast once before.
Answer: This might help:
Create a variable for counting number of <col>
<xsl:variable name="colCount" select="count(/entry/col)" />

or
<xsl:variable name="colCount" select="count(//col)" />

Then check if number of <col> is at least 1. If yes,  will be added.
<xs:choice minOccurs="0" maxOccurs="unbounded">
    <xsl:if test="$colCount > 0">
        <xs:element ref="a" />
    </xsl:if>
    ...


Como pegar valor de RadioButtonFor através de FormCollection e salvar em BD SQL Server

Question: Possuo um model com vários booleanos, preciso pegar os valores deles através de um FormCollection e salvar no banco de dados SQL (não aceita boolean, por isso o campo esta como bit).
Minha View:

            @Html.RadioButtonFor(model => model.Sex,"false", false)F
            @Html.RadioButtonFor(model => model.Sex,"true", true)M

Action:
public ActionResult Create(FormCollection form)
        {
            var pSimpleUser = new SimpleUserr()
            {
                IdSimpleUser = 0,
                Sex = Convert.ToBoolean (form["sex"]),
            };
            if (ModelState.IsValid)
            {
                using (SimpleUserDAO dao = new SimpleUserDAO())
                    if (dao.SaveSimpleUser(pSimpleUser))
                    {
                        ViewBag.AlertMessage = "Salvo Com Sucesso";
                        return View();
                    }
            }
            ViewBag.AlertMessage = "Ocorreu um problema ao salver";
            return View(pSimpleUser);
        }

    }
}

Função com a montagem do comando para a Procedure:
    public bool SaveSimpleUser(SimpleUserr pSimpleUser)
            {
                if (pSimpleUser !=null)
                {
                    using (_context)
                    {
                        SqlCommand cmd = new SqlCommand("SaveSimpleUser");
                        cmd.Parameters.AddWithValue("@idSimpleUser", pSimpleUser.IdSimpleUser);
                        cmd.Parameters.AddWithValue("@sex", pSimpleUser.Sex);
pSimpleUser.IsPaceMaker);
                        cmd.CommandType = CommandType.StoredProcedure;
                        this._context.ExecuteProcedure(cmd);
                        return true;
                    }
                }
                return false;
            }

Comment: Cara, você devia pensar seriamente em abandonar o uso do `FormCollection` em prol de usar um objeto tipado.
Answer: A conversão de Boolean para bit é transparente. Não sei como está sua procedure, mas se o parâmetro @sex é um bit, esta declaração:
cmd.Parameters.AddWithValue("@sex", pSimpleUser.Sex);

Funciona sem problemas.
Essa abordagem não está de todo correta. No seu lugar, eu definiria um Enum para Sex:
public enum Sex {
    Male,
    Female
}

O Model teria uma coluna com o tipo Sex:
public Sex Sex { get; set; }

A View então ficaria assim:

        @Html.RadioButtonFor(model => model.Sex, Enums.Sex.Female) Female
        @Html.RadioButtonFor(model => model.Sex, Enums.Sex.Male) Male

E a parametrização da procedure ficaria:
cmd.Parameters.AddWithValue("@sex", (int)pSimpleUser.Sex);


VMWare ESXi 4.1.0 - Checking SMART info

Question: I'd like to know if there's a way to check the SMART info for hard drives on VMWare ESXi 4.1.0? Thank you.
Comment: why are you on such an old version?
Answer: Access to SMART info  was not introduced until 5.1.
See KB article here:http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2040405

VMWare ESXi 4.1.0 - Checking SMART info


SUM with a pivot to calculate overall score

Question: From another question I got this query to get my scores summed up properly:
SELECT callSign,event, SUM(score)
  FROM scores LEFT JOIN candidates
ON scores.candidateID=candidates.id
  WHERE candidateID IN
    (SELECT id
      FROM candidates
    WHERE assessmentID='1321')
  GROUP BY event, callSign
  ORDER BY candidateID,event

I get data that looks like:
callSign    event           TotalScore
Y209    Bridge                  45
Y209    PSA                     3
Y209    Team Analyst Exam       40
X125    PSA                     1
X125    Team Analyst Exam       38
V023    Amazing Race Planning   37

What I need is data like:
callSign      Bridge   PSA   Amazing Race Planning     Team Analyst Exam
V023                                37
Y209           45       3                                   40
X125                    1                                   38

TABLE STRUCTURE
`events`
id  event
1   PSA
2   Bridge
30  Stress Board
25  Amazing Race Planning
26  Amazing Race Execution

`scores`
id  candidateID     event            rubric            category                         score   comment
1   18       Team Analyst Exam  Team Leader Rubric  Organizes and Tasks Team Members    3
2   18       Team Analyst Exam  Team Leader Rubric  Roles and Responsibilities          5
3   18       Team Analyst Exam  Team Leader Rubric  Backward Planning                   5
4   18       Team Analyst Exam  Team Leader Rubric  Time Management

`candidates`
id  firstName   middleInitial   lastName    callSign    service     rank    sex     height  weight  assessmentID    currentlyAssessing  hired

callSign is where X125 would go
Comment: looks like @bluefeet beat me to it.
Comment: Your subquery is unnecessary
Answer: Since you are using MySQL, in order to pivot the data into columns, you will need to use an aggregate function with a CASE expression:
SELECT callSign,
    SUM(case when event = 'Bridge' then score else 0 end) as Bridge,
    SUM(case when event = 'PSA' then score else 0 end) as PSA,
    SUM(case when event = 'Amazing Race Planning' then score else 0 end) As AmazingRacePlanning,
    SUM(case when event = 'Team Analyst Exam' then score else 0 end) as TeamAnalystExam
FROM scores
LEFT JOIN candidates
    ON scores.candidateID=candidates.id
WHERE candidateID IN (SELECT id
                      FROM candidates
                      WHERE assessmentID='1321')
GROUP BY callSign

If you have an unknown number of events, then you will have to use a prepared statement to generate dynamic SQL:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(CASE WHEN event = ''',
      event,
      ''' THEN score END) AS `',
      event, '`'
    )
  ) INTO @sql
FROM scores
LEFT JOIN candidates
    ON scores.candidateID=candidates.id;

SET @sql
  = CONCAT('SELECT callSign, ', @sql, '
           FROM scores
            LEFT JOIN candidates
                ON scores.candidateID=candidates.id
            WHERE candidateID IN (SELECT id
                                  FROM candidates
                                  WHERE assessmentID=''1321'')
            GROUP BY callSign');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Edit #1, if your events are stored in a separate table, then you can use the following to generate the dynamic result:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(CASE WHEN event = ''',
      event,
      ''' THEN score END) AS `',
      event, '`'
    )
  ) INTO @sql
FROM events;

SET @sql
  = CONCAT('SELECT callSign, ', @sql, '
           FROM scores
            LEFT JOIN candidates
                ON scores.candidateID=candidates.id
            WHERE candidateID IN (SELECT id
                                  FROM candidates
                                  WHERE assessmentID=''1321'')
            GROUP BY callSign');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See SQL Fiddle with Demo
Comment: @h3rrmiller See my edit. If you are going to have an unknown number of `events` then you will need to use dynamic sql to generate the sql string.  If you would update your OP with your table structures, sample data, then I could show you exactly how this will work.
Comment: thanks, now what if i have a table called `events` that has a list of the events i need to aggregate? `SELECT event FROM events ORDER BY id`. Could I work that in to the query so I dont have to statically add events as they come and go?
Comment: @h3rrmiller I see you edited your post with the `scores` and `events` table but you did not include the `candidates` table, can you add that?
Comment: done, i left out examples because they are names but i think the column names are pretty obvious
Comment: @h3rrmiller See my edit, I included a dynamic version that will pull the `events` from the separate table.
Comment: that is awesome... thank you so much.  Is this something that will work with php?  Ive never used a prepared statement with php.


Webform POST handler, add API/header creds?

Question: Using the Remote POST handler in Webform 5, is there a way to add basic auth / API key to the request leveraging tokens or referencing a const? I'd like to find a way not to hardcode actual values.
Comment: Sounds like you are going to want to define a custom webform handler. You can add settings to the settings form on the handler for your api keys. Try making a new one that extends the remote post handler to give you a head start. This way your keys end up in config
Answer: Just adding an answer in addition to @Ryan Hartman's comment. Extend the RemotePostWebformHandler class and its ::buildConfigurationForm() method:
/**
 * Custom Webform submission remote post handler.
 *
 * @WebformHandler(
 *   id = "custom_remote_post",
 *   ...
 * )
 */
class CustomRemotePostWebformHandler extends RemotePostWebformHandler {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['api_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Key'),
      '#description' => $this->t('The API key for basic auth.'),
      '#default_value' => $this->configuration['api_key'] ?? NULL,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    $this->configuration['api_key'] = $form_state->getValue('api_key') ?: NULL;
  }

  ...

Alternatively implement the form element provided by the Key module so you can securely store sensitive secret keys.


Use of "without loss of generality"

Question: Why do we use "without loss of generality" when writing proofs?
Is it necessary or convention? What "synonym" can be used?
Comment: Who introduced WLOG? Was it Koosis?
Answer: I think this is great question, as the mathematical use of "without loss of generality" often varies from its literal meaning.  The literal meaning is when you rephrase a general statement

$P(x)$ is true for all $x \in S$,

using another set (which is easier to work with)

$P(z)$ is true for all $z \in T$,

where $P$ is some property of elements in $S$ and $T$, and it can be shown (or is known) that $S=T$.
For example:

We want to show that $P(x)$ is true for all $x \in \mathbb{Z}$.  Without loss of generality, we can assume that $x=z+1$ for some $z \in \mathbb{Z}$.  [In this case, $S=\mathbb{Z}$ and $T=\{z+1:z \in \mathbb{Z}\}$.]

We want to show that $P(x)$ is true for all $x \in \mathbb{Z}$.  Without loss of generality, we can assume that $x=5q+r$ where $q,r \in \mathbb{Z}$ and $0 \leq r < q$.  [In this case, $S=\mathbb{Z}$ and $T=\{5q+r:q \in \mathbb{Z} \text{ and } r \in \mathbb{Z} \text{ and } 0 \leq r < q\}$.]

In the above instances, indeed no generality has been lost, since in each case we can prove $S=T$ (or, more likely, it would be assumed that the reader can deduce that $S=T$).  I.e., proving that $P(z)$ holds for $z \in T$ is the same as proving that $P(x)$ holds for $x \in S$.
The above cases are examples of clear-cut legitimate usage of "without loss of generality", but there is a widespread second use.  Wikipedia writes:

The term is used before an assumption in a proof which narrows the premise to some special case; it is implied that the proof for that case can be easily applied to all others (or that all other cases are equivalent). Thus, given a proof of the conclusion in the special case, it is trivial to adapt it to prove the conclusion in all other cases.

[emphasis mine.]
So, paradoxically, "without loss of generality" is often used to highlight when the author has deliberately lost generality in order to simplify the proof.  Thus, we are rephrasing a general statement:

$P(x)$ is true for all $x \in S$,

as

$P(z)$ is true for all $z \in T$, and
if $x \in S$, then there exists $z \in T$ for which $P(x)$ is true if $P(z)$ is true.

For example:

Let $S$ be a set of groups of order $n$.  We want to show $P(G)$ is true for all $G \in S$.  Without loss of generality, assume the underlying set of $G$ is $\{0,1,\ldots n-1\}$ for some $n \geq 1$.  [Here, $T$ is a set of groups with underlying set $\{0,1,\ldots n-1\}$ that are isomorphic to groups in $S$, and the reader is assumed to be able to deduce that property $P$ is preserved by isomorphism.]

My personal preference is to replace the second case with:

"It is sufficient to prove $P(z)$ for $z \in T$, since [[for some reason]] it follows that $P(x)$ is true for all $x \in S$."
Comment: Good answer, but there is not "set" of groups of size $n$. This collection is a proper class.
Comment: Ah yes, I suppose $\{e \in G:G \text{ is a group and } e \text{ is the identity of } G\}$ is the set of everything.  Hmm...
Answer: It means that no generality is lost by making a particular simplifying assumption, that is, it is trivial to see that if the proposition to be proved is true in that simple case then it is true in all cases.
Comment: "it is trivial to see that". It does not have to be. The reduction to the particular case may in itself be a significant part fo the argument.
Comment: @AndresCaicedo : If the reduction is a significant part of the argument, then I wouldn't write "without loss of generality".  Instead I'd probably write something like: "First we show how to reduce the problem for that of......" etc.
Comment: I've certainly seen things like: "That we can do this without loss of generality follows from  Lemma 2.2 and an application of Ghengis Khan's theorem."
Comment: @MichaelGreinecker : Assuming those theorems are already proved, it may be trivial to see that the conclusion follows from them.
Comment: @MichaelHardy: Sure, it is trivial given the additional information. It might not be without.
Answer: Consider the proof of the triangle inequality for the real line:
 Thm:  $\forall x, y \in \mathbb{R}, |x + y| \leq |x| + |y|$.
One popular approach to a proof is to consider cases. We may, for example, consider the case that exactly one of $x \text{ or } y$ is positive. Indeed, it is irrelevant if we pick $x$ to be positive rather than $y$ (or vice-versa). The proof, if our reasoning is valid, works out the same regardless. So, we simply state, "Without loss of generality, assume $x > 0$. " This is the essence of the phrase "without loss of generality" and its usage.
Is it necessary? Not as far as I can see. Simply stating, "Assume $x > 0$," is made possible by the fact that it is irrelevant which variable we pick to be positive.  Otherwise, we would state, "Since ..., $x > 0$." So, in a way, if our choice is arbitrary (and correctly so), the phrase "without loss of generality" is implied, and, we may opt to omit it as a "synonym."
Answer: I often times just do a case "Assume _" and then say "and the other cases follow similarly" which, at least for me, replaces WLOG most of the time.
Answer: It means we're going to save time by appealing to symmetry. For instance, if $p$ is an irreducible element of a ring and $ab=p$, then precisely one of $a$, $b$ are units. Instead of considering these two cases separately, we might say: "Without loss of generality, assume $a$ is a unit." This is the same as saying: "We will consider the case where $a$ is a unit; the case where $b$ is a unit is similar."

Use of "without loss of generality"


Visual Studio Community showing 30 day evaluation trial

Question:
if visual studio community free So why does this message appear to me?
Comment: I've removed your irrelevant tags, since this question isn't related to C#, C++, or Python.
Comment: https://visualstudio.microsoft.com/vs/support/community-edition-expired-buy-license/
Comment: I'm voting to close this question as off-topic because it is based on a false premise (free commercial software does not have restrictions).
Answer: You don't need to buy a license to use the Community edition of Visual Studio.
You might just need to sign in with your Microsoft account to register your edition, but no payment is needed.
Source: https://visualstudio.microsoft.com/vs/support/community-edition-expired-buy-license/
Comment: I was already signed in but my licence showed that it was expiring. All I had to do was click "Check for an updated licence" and once again all is good with the world.


Statically linking a library in Android Studio 3.x and CMake

Question: First of all, this is my error.
Build command failed.
Error while executing process /Users/{user}/Library/Android/sdk/cmake/3.6.4111459/bin/cmake with arguments {--build /Users/{user}/Desktop/android/app/.externalNativeBuild/cmake/debug/arm64-v8a --target native-lib}
ninja: error: 'src/main/jniLibs/zlib/arm64-v8a/lib/libz.a', needed by '../../../../build/intermediates/cmake/debug/obj/arm64-v8a/libnative-lib.so', missing and no known rule to make it

I have a statically linked prebuilt zlib.a library for every ARCHs (armeabi, armeabi-v7a, arm64-v8a, x86, x86_64) and placed the library like this.
app/src/main/jniLibs/zlib/${ANDROID_ABI}/include/zlib.h
app/src/main/jniLibs/zlib/${ANDROID_ABI}/lib/libz.a

Here is my CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1)

add_library(native-lib SHARED src/main/cpp/native-lib.cpp)

add_library(libz STATIC IMPORTED)

set_target_properties(libz PROPERTIES IMPORTED_LOCATION src/main/jniLibs/zlib/${ANDROID_ABI}/lib/libz.a)

include_directories(src/main/jniLibs/zlib/${ANDROID_ABI}/include)

find_library(log-lib log)

target_link_libraries(native-lib libz ${log-lib})

in a Java file,
static {
    System.loadLibrary("libz");
    System.loadLibrary("native-lib");
}

I don't have no idea about this issue. It seems okay. I don't touch build.gradle, should I? What am I missing? What is problem?
Answer: Property IMPORTED_LOCATION should be an absolute path.
Use ${CMAKE_CURRENT_SOURCE_DIR} for refer to the directory with currently processed CMakeLists.txt:
set_target_properties(libz PROPERTIES
  IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/zlib/${ANDROID_ABI}/lib/libz.a)


How do you find the number of combinations of 3 elements chosen from multiple sets when you can't take more than element from each set?

Question: So, for example, I have groups {1,2}, {3}, {4, 5}, {6,7,8,9}.
Now, I want to find the number of ways to choose N elements(specifically 3 in my case), from these sets, when I can only choose one element from each set.
Thanks.
Answer: I used the generating functions approach
<code>For the 1st set - (1 + 2x) [Choose none or one of the {1,2}]
For the 2nd set - (1 + x)  [Choose none or only {3}]
For the 3rd set - (1 + 2x) [Choose none or one of the {4,5}]
For the 4th set - (1 + 4x) [Choose none or one of the {6,7,8,9}]
</code>
The solution is the coefficient of $x^3$ in the expansion of
$$(1 + 2x)(1 + x)(1 + 2x)(1 + 4x) = (1 + 9 x + 28 x^2 + 36 x^3 + 16 x^4)$$
Therefore 36 is the required solution
Answer: If you have $s$ sets and the number of elements in each are $n_1,n_2,\ldots,n_s$, and if no specific element occurs in more than one of the sets, then the number of choices will be the sum of all products of $N$ different numbers $n_k$, that is,
$$\sum_{1\le k_1<\cdots<k_N\le s}n_{k_1}\cdots n_{k_N}\ .$$
If you have some specific information about the numbers $n_k$ (for example, they are all equal) then this could be simplified.  The answer for the case you propose is
$$(2\times1\times2)+(2\times1\times4)+(2\times2\times4)+(1\times2\times4)=36\ .$$
Comment: Is there no faster way to do this? Although for 4 sets it's manageable, finding the answer would seem to get out of hand fairly quickly when the sets increase.
Comment: If the numbers of elements in the various sets are "random" then I rather doubt that there would be anything faster than this.  But maybe somebody will have some ideas. . .
Comment: @DavidWell I can guarantee they're all distinct. But I think I do have a solution for choosing 3. It would be the total permutations of all the elements of the set(N*(N-1)*(N-2)), minus the sum of each set(|S|) multiplied by (|S|-1)*(|S|-2)*(Total elements-|S|)*3 (which is the way to choose 2 elements in the same set, and one element outside that set), minus |S|*|S-1|*|S-2|(which is the way to choose 3 elements from the same set). Sorry if that was a bit confusing, kinda hard to write things clearly without latex. :(


How can I scrape HTML button data?

Question: I am working on this project where the information I need is included in the button on the website. I am trying to scrape the number where the 97,800 is right now using python. This number changes every time the page refreshes. I have not tried anything yet because I am new to HTML with python. How would I go about this? Thank You.
Forgot to mention this but the number changes every second and I need to find a way where it pulls html from the url and not hardcoding the html ahead of time.

    <button name="button" type="submit" data-disable-with="Please wait..." data-
    confirm="Are you sure?" class="title-button">
        "Sell Now at "

        "  97,800 "
    </button>

Answer: One possible solution is to select the <button> tag and use the .contents property:
from bs4 import BeautifulSoup

html_doc = """

    <button name="button" type="submit" data-disable-with="Please wait..." data-
    confirm="Are you sure?" class="title-button">
        "Sell Now at "

        "  97,800 "
    </button>

"""

soup = BeautifulSoup(html_doc, "html.parser")
value = soup.select_one("button").contents[-1].strip(' "\n')
print(value)

Prints:
97,800

Comment: I appreciate the response but the only issue is that the number changes every second. I need to find a solution where I don't hardcode the html ahead of time where it instead scrapes the webpage real time.
Comment: @MatthewPatience Most probably the price is loaded with JavaScript from external source. You can use `selenium` for example or use their API (if they have one).
Answer: Try this:
import requests
from bs4 import BeautifulSoup

#input your url
url=" "
r1=requests.get(url)
c1=r1.content
soup1=BeautifulSoup(c1,"html.parser")

# Finding the location of button....Using find_all gives a list. You can
# reference the exact button by filling the "NuM" below with the index
# of the particular element
btn = soup1.find_all("button", {"class": "title-button"})[NuM].text
btn_text = btn.replace("Sell Now at ","")

Comment: Thanks for the comment. This works in the sense that it finds a button with that class but the issue is there are many buttons with the same class name and this code finds the wrong one. Is there a way to specify which button to be found if they all have the same class name?
Comment: I have modified the answer. Instead of using "find", you can use "find_all", then reference the index of the element

How can I scrape HTML button data?


C code not working properly

Question: I'm just learning how to code in C, It's my first non-web language and it's not off to a good start.
I have the following code:
//
//  main.c
//  Greeting
//
//  Created by Austen on 2013-06-27.
//  Copyright (c) 2013 Austen. All rights reserved.
//

#include <stdio.h>

int main()
{
    int confirm[100];
    char name[100];
    char mood[100];

    printf( "Please enter your name: " );
    scanf("%s", name);
    printf( "Hey there, %s . How are you? ", name);
    scanf("%s", mood);
    printf("Oh, you are %s?. Enter 1 or 0: ", mood);
    scanf("%i", confirm);
    if (confirm == 1) {
        printf("Oh good!");
    }
    else {
        printf("Make up your mind");
    }
    getchar();
    return(0);

}

For some reason I just can't get it to work, I've had to change a few things in order for Xcode to stop moaning at me for so many reasons.
It's giving me a
warning: Comparison between pointer and integer int* and int

When I run it, even if I enter 1, it tells me to make up my mind.
Any help would be great, just so I know better next time. It's probably something really simple.
Comment: get integer from `scanf`, give it argument "%d".
Comment: `confirm` should not be an array. Just `int confirm;`
Comment: For future reference, it's useful if you can provide the full warning message copied and pasted from the output. C is fiddly, and often the act of reading/formating a warning makes you realize something you've been ignoring. Welcome to SO :-)
Comment: `int confirm[100];` --  you don't need 100 confirmations; one will do.
Comment: @MYMNeo `%i` is fine ... it allows numbers in octal or hex form.
Answer: No need to create an array to hold an answer for confirm, a normal int will do:
int confirm;

But as scanf expects a pointer you need to pass its address like so:
scanf("%d", &confirm);

Finally, this - scanf("%i", confirm); should actually be this - scanf("%d", &confirm);.
%d is the standard formatting character for integer variables.
After that, everything compiled fine.
C is always pass by value, so there's no way for scanf to store the value you enter in the variable provided, unless it reaches inside memory where it resides and writes it to memory directly.
That's why it asks for the memory address of the variable, rather than the variable itself (you provide the address of something by prepending & to it).
Arrays are already treated as addresses (pointers to be more precise and pointers store the address of something) when passed as arguments to a function which is why you don't do it for them.
Some information on pointers and arrays here.
Comment: That's because you need to pass a pointer to the memory address of `confirm`, and that's what the `&` operator does.
Comment: @Austen Patterson C is always pass by value, so there's no way for `scanf` to store the value you enter in the variable provided, **unless** it reaches inside memory where it resides and writes it to memory directly. That's why it asks for the memory address of the variable, rather than the variable itself (you provide the address of something by appending `&` to it, arrays are already treated as addresses which is why you don't do it for them).
Read up on pointers for more information :)
Comment: But can you explain why I need to add the &?
Comment: @Nobilis You missed the & in the scanf statement
Comment: @Austen Patterson I've added it in the answer body.
Answer: The reason you get that warning is because you're comparing an array of 100 integers to 1 integer. The correct code would be something like this
if (confirm[0] == 1)

or even easier
int confirm;
scanf("%d", &confirm);
if (confirm == 1)

Answer: Use %d for integers (for confirm)
Confirm is declared as an array, but you just want a plain integer. Remove the [100] after confirm in the declaration. It should just be;
int confirm;

The warning you got was because confirm was an array and it tried to compare the array's base address(confirm) to an integer value (1).
Whenever you declare an array, the base address of that array is available in the array name.(Eg. confirm here)
Replace the scanf line which takes confirm with
scanf("%d",&confirm);

it should work fine then
Comment: Still getting the same problem =/
Comment: There was one more error.... confirm was declared as an array .... see the answer again

C code not working properly


TextView posicionar texto exibido sempre no final

Question: Como fazer no TextView para que ao ir inserindo texto ele ficar como uma linha só e a caixa de texto ir acompanhado à medida que vai escrevendo?
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />

Quando você vai inserindo texto no TextView, quando chega no fim da caixa texto ele vai inserindo e você não vê, eu quero fazer com que se veja o que vai sendo digitado, a parte inicial vai se escondendo e não ajustar.
Comment: Possível duplicata de [Como que faço para acessar o tamanho do texto(TexView) e comprimneto da caixa de texto (TextView) via código?](http://pt.stackoverflow.com/questions/107957/como-que-fa%c3%a7o-para-acessar-o-tamanho-do-textotexview-e-comprimneto-da-caixa-de)
Comment: @DiegoFelipe essa é outra pergunta, pois quando você vai inserindo texto no `TextView`, quando chega no fim da caixa texto ele vai inserindo e você não vê, eu quero fazer que veja o que sendo digitado a outra parte vai se escondendo e não ajustar na tela referente a outra pergunta
Comment: Por favor, edite a pergunta para acrescentar detalhes...
Answer: Troque por EditText
Conforme insere o texto você implementa o código abaixo junto
//posiciona o cursor no final do EditText
etReplicar.setSelection(etReplicar.getText().length());

No seu xml seu edit text deve ficar da seguinte forma para se comportar como um TextView
     <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:focusable="false"
            android:id="@+id/et_replicar" />

Comment: deu certo era isso queria, só um pergunta tem como voltar atrás só para visualizar o digitei.
Comment: arrastar com o dedo no touch n da?
Comment: você fez um pergunta, com o dedo no touch não deu,  mas não teria outro jeito?, tentei o  `horizontalScrollView`  mas sem sucesso.
Comment: Qual versão do android vc ta testando, eu fiz o teste aqui e consegui mover o conteudo para fazer a leitura? (eu testei na versão 4.1.1)
Comment: testei na versão 4.1.2 aparelho físico e no emulador 4.4, mas o que você fez ?,  só tocou com o dedo.
Comment: testei novamente deu certo mas ele vai travando, e não pega de primeira e tive que fazer um movimento aleatório puxando para horizontal depois para vertical  para o ver conteúdo.Tem uma maneira de melhorar isso ?


Change of variables from complex variables to real ones

Question: I´m trying to prove a result shown on many physics books:
$\int {dz^* \over (2\pi i)^{1/2}} {dz \over (2\pi i)^{1/2}} e^{-z^* b z} = {1\over b}$,
$z$ and $z^*$ complex.
It is usually obtained by making $z = x + i y$,  $z^* = x + i y$ and $dx dy = -{1\over 2} i dz^* dz$.
It is this last part I don't understand. The Jacobian determinant of the change from $dz^* dz$ to $dx dy$, can be $2 i$ or $-2 i$ depending on the ordering of $dz^* dz$ and $dx dy$, and if we take the absolute value the complex $i$ goes away. In other words, why is the following wrong:
$dx dy = {1\over 2} dz^* dz$ ?
I know this probably a very basic question of complex analysis, but I can't find a single reference that treats it in a simple way (without going into differential forms and such)
Answer: Well, if you write $z(x, y) = x+iy$, then by "cal 3 chain rule" we have that
\begin{align}
dz = \frac{\partial z}{\partial x} dx + \frac{\partial z}{\partial y}dy = dx+idy
\end{align}
and likewise
\begin{align}
dz^\ast = dx-idy.
\end{align}
Hence it follows
\begin{align}
-i\frac{1}{2}dzdz^\ast = \frac{1}{2i}[dx^2+dy^2] \neq dxdy .
\end{align}
Note, I have used the fact $[dx, dy] = 0$. So, regardless whether you use $\frac{1}{2}$ or $\frac{1}{2i}$, you will  not get what you want. What the expression should actually read is as follows
\begin{align}
\frac{1}{2i}dz\wedge dz^\ast =&\ \frac{1}{2i}(dx+idy)\wedge (dx-idy)\\
 =&\ \frac{1}{2i}[dx\wedge dx +idy\wedge dx-idx\wedge dy +dy \wedge dy]\\
 =&\ \frac{1}{2i}[idy\wedge dx-idx\wedge dy]\\
=&\ \frac{1}{2i}[-idx\wedge dy-idx\wedge dy]= -dx\wedge dy = -dxdy
\end{align}
which means
\begin{align}
\frac{1}{2i}dz^\ast \wedge dz = dx\wedge dy =dxdy.
\end{align}
Hence order matters and the $1/i$ matters. (Note: $\wedge$ is the wedge product).
Comment: I see. But why are we defining $dz dz^*$ as $dz \wedge dz^*$? Does that mean $[dz,dz^*]\ne 0$ and $[dx,dy] \ne 0$?
Comment: What I'm say is that $dzdz^\ast$ and $dz\wedge dz^\ast$ are different objects.  Also, $[dz, dz^\ast ] $ is still zero.


Creating a link to an id that refreshes the page

Question: I am working on a project that uses javascript to make tabs.  It has 3 tabs.
Tab three has an id of tab3, what I need is a refresh button that will be on tab3 that will refresh the page. Problem I'm having is if you click on tab3 it will display tab3 data, but it does not change the url.  So the refresh button isn't working.
I tried an onclick javascript that reloads the page using location.reload() which reloads the page but not to the tab3.  So I put that on a link,
<a href="<?php echo $_SERVER['REQUEST_URI']; ?>#tab3" onclick="reloadPage();" >Refresh

This will link to the correct location, the URL then has #tab3 at the end, then the Javascript runs and it reloads back to the url without the #tab3.
So I then tried this that I saw somewhere.
<a href="javascript:;" onclick="window.location = '<?php echo $_SERVER['REQUEST_URI']; ?>#tab3;'">Go

Which links, but doesn't reload.
What is the best way to do this?
Comment: URL with hash `#` on the current page tells to the browser to scroll to an HTML-element, not to reload.
Answer: Try this-
Refresh

Comment: This relaods the page.  So if you are on http://www.example.com/index.php/ you can click on tab3 which would load the content for tab3, but the URL stays at http://www.example.com/index.php/, if you click this link it will move the widnow to the tab3 id, so the url would then look like http://www.example.com/index.php/#tab3, then I guess the Javascript kicks in and the page reloads, but it doesn't use the new #tab3 url it reloads back to the index.php page.
Answer: In head put,

and do this to your button
<a onclick=goto("<?php echo $_SERVER['REQUEST_URI'] . '#tab3'; ?>"); >GO

if you want to refresh the page and aslo goto same place this code will work
<form method=post action="">
<input type=hidden name=value value="#tab3" />
<input type=submit value=GO />
</form>
<?php
if (isset($_POST['value']))
{
header('Location: http://'. $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI] . $_POST["value"]);
}

?>

Comment: This doesn't work.  When you go to say example.com/index.php which uses javascript to have tabs.  So when index.php loads it is on tab1.  Now you would click on tab3, which keeps the url the same but would switch to tab3.   Now on tab3 I need to put in a refresh button to refresh the page but stay on tab3.  With the above, it does link to the correct tab but it does not refresh the content.
Answer: Using window.location is the solution, however if the current location is already the same as the new url that is assigned, then browser will not re-load the page.
The only trick would be to make the new url look "new". This can be done by adding a random identifier as querystring parameter.
In the form:
http://hostname?<dynamic/random>#tab3

Example:
<a href="javascript:;" onclick="window.location = '<?php echo $_SERVER['REQUEST_URI']; ?>' + Date.now() + '#tab3;'">Go

Comment: This does add the data at the end of the link but it doesn't link to the #tab3, I was thinking maybe using php to check the $_GET for the tab3, but I think this is adding an extra step that I don't need.
Comment: Clarification: 1.)moving from one tab to another is handled in JS. 2.) After moving to tab3 by means of javascript, if a button is pressed the content of tab3 needs to be refreshed.  If this is true, then in the page loading sequence there should be JS code that is acting on enabling the correct tab as the browser will only try to move the focus to the given #id. But the whole statemachine of the UI is owned by the JS part of the app, and it needs handle the incoming hash link.  Doing this in PHP is like duplicating the logic in two different places.  My answer covered only request initiation.
Comment: If you were to use any if the modem JS MVC frameworks,  handling of the hash id would be done via the concept of "routes" (E.g. backbone, ember, ...).


Distance between point and linear Space

Question: Suppose $E$ is a normed vector space. Let $f$ be a continuous linear functional on $E$ and denote by $M$ the Kernel of $f$. Let $x\in E$. How to show that $$\operatorname{dist}(x,M)=\displaystyle\inf_{y\in M}\|y-x\|=\frac{|f(x)|}{\|f\|}\, ? $$
Answer: We assume that $f$ doesn't vanish identically. First, if $y\in \ker f$, then
$$|f(x-y)|=|f(x)|\leqslant \lVert x-y\rVert\cdot\lVert f\rVert,$$
hence
$$\operatorname{dist}(x,\ker f)\geqslant \frac{|f(x)|}{\lVert f\rVert}.$$
Let $\{y_n\}\subset E$ such that $f(y_n)/\lVert y_n\rVert\to \lVert f\rVert$. As $x-\frac{f(x)}{f(y_n)}y_n\in \ker f$, we have
$$\operatorname{dist}(x,\ker f)\leqslant\inf_n\left\lVert x-\frac{f(x)}{f(y_n)}y_n-x\right\rVert=|f(x)|\inf_n\left|\frac 1{f(y_n)}y_n\right|\leqslant \frac{|f(x)|}{\lVert f\rVert}.$$

Distance between point and linear Space


How can I view what causes a page to load slow?

Question: i currently have the devel module on and i'm trying to figure out why my site is slow. I get the following info line:
Page execution time was 4661.1 ms. Memory used at: devel_boot()=3.27 MB, devel_shutdown()=65.39 MB, PHP peak=70 MB.
Is there a way to view why my page is taking 4661 ms to load? Here's a view of what the page is loading:
Answer: Yes you can figure out which function(s) spends more time in the execution by using a profiling module, then you can optimize that particular function(s)
Below are the available profiling modules in Drupal 7(AFAIK),

XHProf
Profiling

Personally I used XHProf and it helped us lot to improve the performance.

XHProf is a hierarchical profiler for PHP. It reports function-level
  call counts and inclusive and exclusive metrics such as wall (elapsed)
  time, CPU time and memory usage. A function's profile can be broken
  down by callers or callees. The raw data collection component is
  implemented in C as a PHP Zend extension called xhprof. XHProf has a
  simple HTML based user interface (written in PHP). The browser based
  UI for viewing profiler results makes it easy to view results or to
  share results with peers. A callgraph image view is also supported.

In addition to this you can also look into Performance Logging and Monitoring module which was removed from Devel.
Answer: You could turn on the devel mysql log to see which queries are taking too long to execute. You can also turn on the mysql slow query log in your mysql my.cnf file.
I suspect you are using views for this page. If that's the case, check the views filters. Try to add proper filtering on index columns from the node table. Or any other index column. In addition to that, check to see you have mysql cache enabled.
Answer: While Drupal supports a number of awesome profiling tools, such as XHProf –which is being used by the Twig team to insure the new theme system is performant– there are also some online graphing tools you use to instantly see what your page load waterfall looks like.
Pingdom is one that gives you a visual display of all loaded assets and how long they took to render.
For example, here's Pingdom's waterfall graph of the page you are reading now:
http://tools.pingdom.com/fpt/#!/hmCRv/https://drupal.stackexchange.com/questions/76227/how-can-i-view-what-causes-a-page-to-load-slow
--
Also, after I posted this answer I couldn't help noticing you are in New York. Come to NYC Camp next month and learn how to performance tune Drupal: http://nyccamp.org
Comment: hello forest... ;) gotta get xhprof installed.


Address field "Same as above"

Question: I have 2 address fields : Res. addr and Permanant addr.
On clicking another field : same as above
I want to copy all the values entered in Res. addr to Permanant addr.
Please let me know how to do it?
Thanks,
ronforever
Comment: http://api.drupalcommerce.org/api/Drupal%20Commerce/sites!all!modules!commerce_shipping!plugins!format!copy_billing_address.inc/DC
Comment: Are these fields in a node? User profile? Commerce checkout? Form API? There is one universal form api method but I bet that you would prefer something easier.
Answer: There is no simple solution, and therefore I'm not sure this question is good for the Drupal Stack Exchange. It's going to be a matter of custom JavaScript or AJAX Form API code, and it will be dependent on how you're using Address Field and what sort of form you're integrating it into.
Based on the comments below, though, I'd add that there's nothing particularly challenging about this. If both sets of form elements are on the same page, it's a simple matter to use JavaScript (especially with jQuery) to copy the data from one form field to the next. There just isn't a simple property to toggle within the form API code itself.
Comment: This is a realistic problem that could be of use to a wide audience.  An answer that outlines why something isn't possible, or summarizes the difficulties, is perfectly acceptable.
Comment: If I understand StackExchange correctly, that's just not how the tool is supposed to be used. I'm all for that sort of documentation happening, but there's really nothing for it than to use regular ol' JavaScript to copy fields from one part of the DOM to another. So, it's possible, there are no real difficulties... not sure what else needs to be said. : )
Comment: I get what you are saying, but if you just look at the question itself from a non-developer's point of view, they may not know that there isn't a simple solution.  My approach as mod is to try to judge on-topic / off-topic solely on the question, and then let the answers come.  This is the reason for leaving it open.  Other mods or the community may disagree and close this out.  BTW, thanks for stopping by to answer UC and Commerce questions.
Comment: No worries, happy to help. : )
Answer: I had the same problem and my solution was to use RULES. I have to address fields on my node, one is the registration address of a particular company a the other address field is the standard shipping address.
So in my case I have made the shipping address field not mandatory and if its empty a RULE i triggered which copies the address from the other field.
Comment: Would you mind adding an export of that rule to your answer?

Address field "Same as above"


Como uma tag em um elemento de uma table com jQuery?

Question: Tenho uma tabela simples:

table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}

      R$ 92.4
      R$ 137.48
      R$ 108.27
      R$ 129.25

Como eu faço para inserir a tag  no  que tem o menor valor com jQuery?
Assim:
R$ 92.4

Comment: Você poderia editar o título da pergunta @usuario, está confuso.
Comment: Primeiro, identifique a célula com o menor valor. Já conseguiu isso? Se sim, poste o código. Se não, descreva como você acha que é feito.
Comment: Não consegui. Eu pensei em listar todos os `` que estão dentro da `` com o id `#precos` utilizando o `$.each` do jQuery depois pegar a que tiver o menor valor utilizando o `Math.min.apply(Math, variavel)`. Depois adicionar a tag e substituir as ``. Mas não consegui
Comment: A ideia parece correta. Tem como postar mesmo assim este código que tentou fazer? Ajudará a identificar exatamente qual foi seu erro.
Comment: So consegui achar o menor valor: https://jsfiddle.net/newtech/gr9xn8as/
Comment: Certo. Agora você percorre todos os elementos `td`, verifica qual possui o valor igual ao mínimo e adiciona a tag `mark`.
Comment: Pergunta: e se houverem dois preços iguais, ambos deverão ser marcados ou qual seria, então, o critério de seleção?
Comment: Nunca vai ter dois preços iguais.Eu agrupo os valores iguais antes de listar na tabela
Answer: A idéia aqui é:

Usar recursos do ES6 como spread operator e arrow function para retornar um array
Usar o Array#map para retornar somente o conteúdo dos tds
Aplicar a expressão regular /[0-9.]/g para capturar somente o valor numérico
Por fim encontrar o menor e usar o wrapInner do jQuery para criar a marcação

const tds = [...document.getElementsByTagName('td')].map(item => Number(item.innerHTML.match(/[0-9.]/g).join('')));
const menor = Math.min.apply(Math, tds);

$('td').each(function() {
  if ($(this).html().indexOf(menor) > -1) {
    const aux = $(this).html();
    $(this).html('').wrapInner('' + aux + '');
  }
});
table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}

      R$ 92.4
      R$ 137.48
      R$ 108.27
      R$ 129.25

Comment: Muitos dos recursos já são suportados pelos novos browsers sem precisar usar um transpiler @RafaelAcioly. Podemos olhar [aqui](http://caniuse.com/#search=es6)  e [aqui](http://kangax.github.io/compat-table/es6/) para ver a compatibilidade.
Comment: Como posso saber quais `features` do ES6 já posso utilizar em produção?
Answer: Segue abaixo código comentado com cada etapa para marcar o menor valor com o mark.

$(function() {

  function markMinValue() {
    var pricesTd = $('td', 'table #qtdPrecos #precos'),
      pricesValue = [],
      minValue,
      indexMinValue;

    // Percorre as linhas da tabela com preços
    $.each(pricesTd, function(indice, element) {
      // Armazena o valor de cada uma em uma variável temporária
      var value = $(element).text().replace('R$ ', '') * 1;
      // Adiciona no array o valor
      pricesValue.push(value);
    });

    // Busca o menor valor
    minValue = Math.min.apply(null, pricesValue);

    // Encontra o indice do menor valor
    indexMinValue = pricesValue.indexOf(minValue);

    // Marca o item com menor valor pelo indice encontrado
    $(pricesTd[indexMinValue]).wrapInner('');

  }

  // Executa a função para marcar o item de menor valor
  markMinValue();

});
table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}

      R$ 92.4
      R$ 137.48
      R$ 108.27
      R$ 129.25

Answer: Vi que já responderam a pergunta, mas estou contribuindo com mais uma solução do problema, minha resposta foi baseada em soluções encontradas aqui: Find the smallest value of a table row using javascript
.

//Percorre as TDS da table e monta um ARRAY
var valoresNaTd = $('#qtdPrecos tr td').map(function() {
  var valor = $(this).text().substr(2);
  return valor;
}).get();

//Localiza o valor mínimo no array
var valorMinimo = Math.min.apply(Math, valoresNaTd);

//Coloca o mark na TD de menor valor
$('#qtdPrecos tr td').filter(function() {
  return $(this).text().substr(2) == valorMinimo;
}).wrapInner('');
table {
  border-collapse: collapse;
}

table tr td {
  border: 1px solid #000;
}

mark {
  background: yellow;
}

      R$ 92.4
      R$ 137.48
      R$ 108.27
      R$ 129.25

Answer: Vamos separar por passos o que deve ser feito:

Pegar todos os valores dentro de cada td.
Coloca-los em ordem de menor para maior.
Pegar o element com menor valor e inserir a tag  nele.

Passo 1:
Pegando todos os elementos:
$('#precos td.pointer');

Passo 2:
Colocar os elementos em ordem de acordo com o valor dentro do HTML, para isso podemos utilizar a função sort() que realiza um loop pegando de 2 em 2 elementos e comparando entre eles:
var values = $('#precos td.pointer').sort(function(current, next) {
    // Substitui a string R$ por "vazio" e pega apenas os
    // valore dentro do HTML e transforma em números.
    var one = parseFloat(current.innerHTML.replace('R$', ''));
    var two = parseFloat(next.innerHTML.replace('R$', ''));

    // Verifica se o valor atual é maior ou menor que o próximo
    if (one < two) return -1;
    return 1;
});

Agora a variável values possui todos os elementos em ordem decrescente (menor para o maior), e assim podemos simplesmente pegar o primeiro elemento de values que sempre sera o maior e alterar o HTML
$(values[0]).html(''+values[0].innerHTML+'');

Veja abaixo o código funcionando:

var values = $('#precos td.pointer').sort(function(current, next) {
    // Pega apenas os valore dentro do HTML e transforma em números.
    var one = parseFloat(current.innerHTML.replace('R$', ''));
    var two = parseFloat(next.innerHTML.replace('R$', ''));

    // Verifica se o valor atual é maior ou menor que o próximo
    if (one < two) return -1;
    return 1;
});

$(values[0]).html(''+values[0].innerHTML+'');

         R$ 92.4
         R$ 137.48
         R$ 108.27
         R$ 129.25

Comment: Faltou só editar a explicação ali _"ordem crescente (maior para o menor)"_, no caso o `values` ficou do menor para o maior agora.


Dotted 8th note in a triplet swing rhythm

Question: I'm looking at isn't she lovely by Stevie Wonder and as I've only been reading music for about a year I've not really come across this type of notation - I'm fine with the first two beats as they're just crotchets, but on the 3rd beat, the notation shows an 8th note rest, followed by the notes B, E, G* (an E chord), followed by another 8th note rest, which make up the whole triplet - but the B note is a dotted 8th note which in a typical straight 4/4 rhythm would mean the dotted 8th note is played as 3/4 of a beat (an 8th note + a 16th note). So how would this dotted eigth note be played in an 8th note triplet? Or swung 4/4 rhythm? It won't let me upload a pic as it's too big but I that makes sense, Cheers!
Comment: Upload the picture here: https://imgur.com/upload or something similar and I'll fix it for you. Just give me the link when you're done.
Comment: I have a feeling this question was downvoted because the OP didn't provide a picture, but please keep in mind that new users can't add pictures to their posts (as the OP noted). The question itself seems fine to me.
Answer: It's almost a shuffle, sort of swing time.
Imagine it written not in 4/4, but in 12/8. So you count 123 223 323 423.
That problematic bit is on beat 3, except the E chord comes in after 3, just on the '23' after it
To explain another way - imagine counting 1 - 12 in that bar. 123 and 456 are the first two chords, miss 7, play 89 using that E chord, and E again on 10 11 12.
Answer:
Study the classic Morecambe and Wise song 'Boom Oo Yata-Ta-Ta'.    That's the rhythm, split between treble and bass. (Ignoring two extra 8ths in the bass.)


How to compare multiple columns, on multiple rows - comparison only applicable within rows who hold common ID

Question: Every record in table has a course_id (auto incremented), a study_id (refers to a patient, each patient can have multiple records in this table), and each record contains a start_date and a stop_date.
I am looking to compare within each patient's records, to see if any of these date ranges overlap. However, I want to do this for all the patients in this table.
For example:
course_id  study_id  start_date  stop_date

1234123    12222     01/09/2019  01/12/2019
1444233    12222     01/10/2019  01/01/2020

Desired result of query:
study_id

12222

etc etc for all study_ids with similar overlaps in the start/stop dates.
Hoping someone could lead me in the right direction at least. Thanks!
Comment: Please provide sample data and expected results as tabular text.
Comment: @GMB - Thank you for the tips - new here!
Comment: For your reference, [this](https://stackoverflow.com/questions/60078622/merge-two-tables-in-one-sql-query-and-make-the-date-values-unique) is what a fully constructed question looks like. For tips and tools to use to improve your question, here is a good reference article. [How to post a SQL question on a public forum](https://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/)
Answer: I think that this does what you want:
select distinct study_id
from mytable t
where exists (
    select 1
    from mytable t1
    where
        t1.course_id <> t.course_id
        and t1.study_id = t.study_id
        and t1.start_date <= t.end_date
        and t1.end_date   >= t.start_date
)

This works by using a correlated subquery with an exists condition that filters on record for which another record exists with the same study_id and an overlaping date range. Then, the outer query uses distinct to remove duplicate study_id.
Answer: Using selfjoin
select distinct t.study_id
from yourtable t
join yourtable t2 on t.study_id = t2.study_id
  and t.course_id > t2.course_id
  and t.start_date <= t2.stop_date
  and t2.start_date <= t.stop_date


Clarification of output of metabin and metareg

Question: I used the metabin and metareg commands in the meta package of R.
There were 21 trials and I initially looked at the safety outcome.  The output of metabin is below.
Test of heterogeneity:

      Q    d.f.  p-value
  35.72      20   0.0166

Details on meta-analytical method:
- Mantel-Haenszel method
- DerSimonian-Laird estimator for tau^2

Below is the output of  metareg with vaiables "TypeRCT" which takes a value of a 1 or a zero, "Per" which goes from 30-100, and "Rec" ranging in values from 250 to 422.  Output of metareg below
Mixed-Effects Model (k = 21; tau^2 estimator: DL)

tau^2 (estimated amount of residual heterogeneity):     0.0168 (SE = 0.0722)
tau (square root of estimated tau^2 value):             0.1294
I^2 (residual heterogeneity / unaccounted variability): 7.97%
H^2 (unaccounted variability / sampling variability):   1.09
R^2 (amount of heterogeneity accounted for):            86.59%

Test for Residual Heterogeneity:
QE(df = 17) = 18.4732, p-val = 0.3596

Test of Moderators (coefficient(s) 2,3,4):
QM(df = 3) = 13.7827, p-val = 0.0032

Model Results:

         estimate      se     zval    pval    ci.lb   ci.ub
intrcpt   -0.5573  0.8053  -0.6920  0.4889  -2.1358  1.0211
TypeRCT    0.1144  0.2415   0.4737  0.6357  -0.3590  0.5878
Per       -0.0115  0.0062  -1.8497  0.0644  -0.0237  0.0007  .
Rec        0.0032  0.0018   1.7514  0.0799  -0.0004  0.0068  .

My question is does the QM  of 13.7827 and p-val of 0.0032 mean that the variables together account for significant portion of heterogeneity.  Second question: Do the p-values of 0.06 and 0.08 mean that the estimates of coefficients are not quite significant.
Answer: Regarding the first question: Correct. The test is an omnibus test of the null hypothesis that the true coefficients for TypeRCT, Per, and Rec are all jointly equal to 0 (in which case your model does not explain any heterogeneity). Clearly, you can reject that null hypothesis.
Regarding the second question: Correct. It may be somewhat surprising that the omnibus test is significant, but none of the individual coefficients reach significance (at $\alpha = .05$). This usually indicates that the predictor variables are correlated (i.e., there is some degree of multicollinearity).


Meu vídeo não roda no background css em tablets ou ipads. Apenas em PC

Question: Olá pessoal tenho um vídeo que roda normalmente em background css no PC. Mas quando acesso o site por tablets ou ipads ele não roda.
Veja o código:
<video autoplay loop poster="torre.jpg" class="bg_video">
            <source src="bg.webm" type="video/webm">
            <source src="bg.mp4" type="video/mp4">
</video>

CSS:
.bg_video{
            position: fixed;
            right: 0;
            bottom: 0;
            min-width: 100%;
            min-height: 100%;
            width: auto;
            height: auto;
            z-index: -1000;
            background: url(torre.jpg) no-repeat;
            background-size: cover;
        }

Já coloquei ele no formato conforme pedem MP4 e WEBM, mas nada resolve.
Comment: Já verificou se o navegador aceita tal recurso?
Comment: @Mike é o mesmo do pc
Comment: Mas ele já rodou em outros navegadores no teu PC?
Comment: @Mike sim, normalmente. Só não roda em dispositivos móveis.
Comment: O que você quer dizer com rodar em background?
Comment: @Pablo Rodar em background eu consegui. Só que ele só está rodando em PC. Em tablets e ipads ele não roda.
Comment: Não estou entendendo o que você quer dizer com rodar em background. Você quer dizer rodar enquanto o navegador está minimizado?
Comment: @Pablo Quando digo rodar quer dizer que o vídeo não executa em tablets ou ipads. Apenas em PC
Answer: Em uma situação similar eu consegui com que o vídeo fosse exibido tanto em dispositivos iOS mobile quanto em desktops com duas ações:
1 - Privilegiando a versão .mp4 (colocando-a em primeiro lugar)
<video autoplay loop poster="torre.jpg" class="bg_video">
    <source src="bg.mp4" type="video/mp4">
    <source src="bg.webm" type="video/webm">
</video>

2 - Fazendo com que os vídeos fossem renderizados com o parâmetro Field Order: None (progressive). Você precisará realizar o re-encoding dos vídeos, caso o Field Order seja diferente.
O suporte a Codecs ainda não é padronizado em todos os browsers.
Comment: Como faço esta implementação?
Comment: @GladisonNeuzaPerosini Eu alterei a resposta para torná-la mais clara.


Should I take logarithm of weights in WLS regressions

Question: I am new here.
I have a question regarding the anlaytical weights used in ivreghdfe or reghdfe regressions. People usually take aweights in STATA, my question is how we deal with the weight if the weight itself is highly skewed?
Should we take the logarithm over that or should we drop those outlier observations simply?
Comment: Most weights are arranged to sum to unity.  Their logarithms would all be negative, making nonsense of any attempt to use them as weights.
Answer: No, you should not take the logarithm of analytical weights or drop observations with high weights.
When you use weights in a model, you are telling stata how many people in your population had certain characteristics. If you are using frequency weights, for example, you might have counted 10 people who exercised 1 hour a week, smoked, and had heart disease, and then 40 people who exercised 3 hours a week, smoked, and had heart disease.
When a weight is high, that just means that lots of people in your population had a given pattern of data. If you were to drop "outlier" weights because they were too large, you would be discarding a lot of people from your dataset just because their experience was really common. This forces your model to make inferences on uncommon people, and it tells people that the most common covariate patterns never happened.
If you were to take the logarithm of weights, you would misrepresent how common a given pattern of characteristics was in your population. The model would weight patterns of observations from a group of 200 only a little bit higher than patterns of observations from a group of 100 (because log(200) / log(100) = 1.15) while for correct inference, it needs to weight the pattern of observations from the group of 200 twice as heavy as the group of 100.
Analytic weights as you reference don't work exactly as described above, but the same principle applies. You should not take the log of weights or drop "outlier" weights.
For a summary of weighting methods in stata, see this page
Comment: Stata supports *four* concepts of weighting, of which "analytic" weights are a catch-all for anything the user wants to do.  Not all weights are frequency weights of the type you describe.  Probability weights, for instance, describe the chances with which individual observations are included in a sample and might have nothing to do with population frequencies.


Mockito mock Java @Value with spring boot

Question: Hi I have this simple code for my Spring Boot Project:
@Component
public class UserRowMapper implements RowMapper<User> {
    @Value("${bug.value}")
    private String id;
    @Value("${wrong.value}")
    private String userName;

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return User.builder()
                .id(rs.getInt(id))
                .userName(rs.getString(userName)).build();
    }
}

what I want is to create a simple Mockito Test that will check @Value strings like so:

@ExtendWith(MockitoExtension.class)
class UserRowMapperTest {
    @Mock
    Environment environment;
    @Mock
    ResultSet resultSet;
    @InjectMocks
    UserRowMapper userRowMapper;

    @Test
    void testMapRow() {
        when(environment.getProperty("user.id")).thenReturn("id");
        when(environment.getProperty("user.userName")).thenReturn("userName");
        try {
            final User user = userRowMapper.mapRow(resultSet, anyInt());

            // check if its ok
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

But I can't find a simple way to check if the value I injected is what I expect.
any ideas?
Answer: Unfortunately, there is no mocking mechanism for Spring's @Value. However, you can use a simple workaround using ReflectionUtils that serves for this purpose according to the JavaDoc:

ReflectionTestUtils is a collection of reflection-based utility methods for use in unit and integration testing scenarios.
There are often times when it would be beneficial to be able to set a non-public field, invoke a non-public setter method, or invoke a non-public configuration or lifecycle callback method when testing code involving

ReflectionTestUtils.setField(userRowMapper, "id", "my-id-value");
ReflectionTestUtils.setField(userRowMapper, "userName", "my-userName-value");

JavaDoc for ReflectionTestUtils#setField(Object, String, Object).
Comment: Reflection and OOP principles are not friends, I know. Using `ReflectionTestUtils` is a common practice for setting `@Value` properties. Alternatively, you might want to create a full-args constructor to pass the mocks and String properties through.
Comment: Hi Nikolas, as I understand that using ReflectionTestUtils is a bad practice.
Answer: Add getter methods for id and userName fields instead of mocking Environment class.
@Component
public class UserRowMapper implements RowMapper<User> {
    @Value("${bug.value}")
    private String id;

    @Value("${wrong.value}")
    private String userName;

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return User.builder()
                .id(rs.getInt(getId()))
                .userName(rs.getString(getUserName())).build();
    }

    public String getId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }
}

While mocking:
Mockito.when(userRowMapper.getId()).thenReturn("id");
Mockito.when(userRowMapper.getUserName()).thenReturn("userName");

Also, you can use TestPropertySource annotation to provide altogether different properties file:
@SpringBootTest
@TestPropertySource(locations = "/application2.properties")
public class TestClassTest {

    @Autowired
    TestClass testClass;

    @Test
    public void test() {
        assertEquals("id", testClass.getId());
    }
}

Comment: `userRowMapper` is under test, it's not a mock, exception will be thrown due to `Mockito.when(userRowMapper.getId()).thenReturn("id");`
Comment: the problem with your approach is that it's not a unit test anymore when you use @SpringBootTest annotation.
Answer: I would rather suggest to you to do not use inline @Value annotation on the consumer class. As you have seen, the class testability decreases.
You can solve your problem simply creating a @Configuration bean and injecting it to the UserRowMapper class. In this way, using DI you can easily mock the configuration in your tests.
See below a naïve implementation.
@Configuration
public class UserRowMapperConfiguration {
    @Value("${bug.value}")
    private String id;

    @Value("${wrong.value}")
    private String userName;

    public String getId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }
}

@Component
public class UserRowMapper implements RowMapper<User> {

    private UserRowMapperConfiguration configuration;

    public UserRowMapper (UserRowMapperConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return User.builder()
                .id(rs.getInt(this.configuration.getId()))
                .userName(rs.getString(this.configuration.getUserName())).build();
    }
}

@ExtendWith(MockitoExtension.class)
class UserRowMapperTest {
    @Mock
    UserRowMapperConfiguration configuration;
    @Mock
    ResultSet resultSet;
    @InjectMocks
    UserRowMapper userRowMapper;

    @Test
    void testMapRow() {
        when(configuration.getId()).thenReturn("id");
        when(configuration.getUserName()).thenReturn("userName");
        try {
            final User user = userRowMapper.mapRow(resultSet, anyInt());

            // check if its ok
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

Comment: I like this idea, the problem is that when you add a configuration class, it becomes really hard to understand what properties can be used in `UserRowMapper` without changing classes but maybe its the best cource of action but it doesn't solve the problem with checking if user written a Value parameter by mistake
Comment: @AndreyKishtov I did not catch your point :-)
Comment: i meant that when you move the code from UserRowMapper to UserMapperConfiguration it will be harder to spot a mistake, my main goal was to see if someone made a mistake in     @Value("${bug.value}")
and now the mistake can't even be seen
Comment: Actually, the UserRowMapperConfiguration class I wrote does not contain any logic, it is just a container for all the configuration values that could be used by the UserRowMapper class.
Answer: As thepaoloboi suggested use a configuration class to hold all your configs.
Now to test that your config is pointing to the right @Value key, you create an integration test by simply loading that object using spring without loading the whole context. That way it'll be as fast as a unit test.
Here's an example:
@ExtendWith(SpringExtension.class)
@Import(UserRowMapperConfiguration.class)
@TestPropertySource(properties = { "user.id=id" , "user.userName=userName"})
class UserRowMapperConfigurationTest {

    @Autowired
    UserRowMapperConfiguration userRowMapperConfiguration;

    @Test
    void test() {
        assertEquals("id",userRowMapperConfiguration.getId());
        assertEquals("userName",userRowMapperConfiguration.getUserName());
    }
}

and Configuration class:
@Configuration
public class UserRowMapperConfiguration {
    @Value("${bug.value}")
    private String id;

    @Value("${wrong.value}")
    private String userName;

    public String getId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }
}

Answer: Mockito cannot inject primitives, wrappers (Integer, Long, ...) or Strings, so @InjectMocks is not an option unless you refactor those fields to a different object and mock that object as @thepaoloboi suggested.
In any case, field injection provides really bad testability so the best option would be to use constructor injection as seen below:
@Component
public class UserRowMapper implements RowMapper<User> {

    private final String id;
    private final String userName;

    public UserRowMapper(@Value("${bug.value}") String id, @Value("${wrong.value}") String userName) {
        this.id = id;
        this.userName = userName;
    }

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
        return User.builder()
                .id(rs.getInt(id))
                .userName(rs.getString(userName)).build();
    }
}

@ExtendWith(MockitoExtension.class)
class UserRowMapperTest {

    private final String mockId = "id";
    private final String mockUserName = "userName";

    @Mock
    private ResultSet resultSet;
    private UserRowMapper userRowMapper;

    @BeforeEach
    void beforeEach() {
        userRowMapper = new UserRowMapper(mockId, mockUserName);
    }

    @Test
    void testMapRow() {
        ...
    }
}

Answer: @Service
public class PreComputeService {

    @Autowired
    LoadData loadData;

    @Autowired
    PreComputeHelper preComputeHelper;
    @Autowired
    CalculationService calculationService;
    @Autowired
    DataPointRepository dataPointRepository;

    @Value("${hds.email.host}")
    String environment;  // property we are using from application.properties

  // do some stuff

}

@ExtendWith(MockitoExtension.class)
    class PreComputeServiceTest {
        @Spy
        @InjectMocks
        PreComputeService preComputeService;

        @BeforeEach
        void setUp() {
            MockitoAnnotations.openMocks(this);
            preComputeService.environment ="Dev";
        }
       // some test cases

    }


Store and fetch CSV columns from DB using implode and magic __get()

Question: I have PHP code to select categories from tbl_categorie, Now I have a multiple select in a form where an article can have more than one categorie. While inserting the values in database, I want to store multiple categories values in one column/attribute. Where ID_CAT attribute would only store categories ids of the tbl_categorie separated by comma(,).
I have two tables in one DB,
 tbl_blog:
  ID_BLOG    ID_CAT               TITLE          ARTICL        DATE
  1          1,3                  title1         article1      2013-03-04
  2          4,10                 title2         article2      2013-03-04
  3          3,6                  title3         article3      2013-03-04

 tbl_categorie:
  ID_CAT    NOM_CAT
  1          HTML
  2          CSS
  3          DESIGN
  4          PHP
  5 ..

I have problem in first place to add tow ID_CAT for one article although I used the implode() statment but she works when i change the type of ID_CAT from int to varchar , and this is the process to add article :
Article::creatArticle(0,$_POST['title'],implode(', ', $_POST['id_categorie']),$_POST['article']);

and this is the function to add article from class_article :
/**
 * function créeArticle
 */
public static function creatArticle($id_article,$title,$id_categorie,$article)
{
    global $db;
    $req = $db->prepare("INSERT INTO blog (ID_BLOG,TITLE,ID_CAT, ARTICLE,DATE) VALUES ('',:title,:id_categorie,:article,'".date('Y-m-d')."')");
    $ok = $req->execute(Array('title' =>$title,'id_categorie' => $id_categorie,'article' => $article));
     return $db->lastInsertId();
    //$erreur = $req->errorInfo();
}

now i have probleme to fetch all categories for which in each article shall have , and this is how i fetch in my back-office the table of articles using the magic method get() which she returne only the first value in th column :
 <?php
    foreach(Article::getAllArticle()as $blog ){
        $article= new Article($blog->ID_BLOG);
        $categorie = new Categorie($article->getIDCategorie());

        echo'

';
                            echo '<input type="checkbox" />	';
                            echo ''.$article->getTitlearticle().'	';
                            echo ''.$categorie->getNomCategorie().'	';
                            echo ''.$article->getDatearticle().'	';
                            echo '35	';
                            echo ' ';
                            echo 'getIDarticle().');" title="Edit this content">';
                            echo ' getIDarticle().');" title="Delete this content">	';
                            echo '
';

                        } ..

i know that i have to use the explode() statment or making a loop but i can't figure it out how :( ,and i have a doubt about the type of ID_CAT should be varchar make the problem ? thanx !
Answer: It is difficult to understand what you are doing and what you want to do. I'm not sure if you are getting the results from a CSV file or from a database?
If it is from a database, from what I can see you need to normalise your database tables. Create a linking table between the blog and categories, this would make it a lot easier to bring back the results. A simple join sql will get all articles in an category or the get all categories that the article is associated with.
tbl_blog:
  ID_BLOG                TITLE          ARTICL        DATE
  1                      title1         article1      2013-03-04
  2                      title2         article2      2013-03-04
  3                      title3         article3      2013-03-04

 tbl_categorie:
  ID_CAT    NOM_CAT
  1          HTML

tbl_blogcat
 ID_BLOG    ID_CAT
 1           1
 1           3
 2           4
 2           10

It might be a little extra work now but it will be worth it in the future. Storing your categories as a comma delimited string makes it difficult to search.
Answer: This problem can be solve easy way, You can create a new table which will store the information of tbl_blog and tbl_catagory's primary id. The benefit is when you choose one more categories of a blog it will store your information of every category of a blog. the table is look like.....

tbl_combine:

ID_COMB    ID_Blog    ID_Cat
1          1          2
2          1          1
3          1          3
4          2          3
5          2          2
6          3          1
7          3          2
8          3          3

Above  we just let 3 blog and 3 categories. the tbl_combine  can store each blog category's primary id of its chosen blog in each row. So we can insert unlimited categories of a blog. there's no need explode or implode function.
Then we can retrieve any blog categories. The query look like.

SELECT
      (SELECT category_name FROM tbl_catagory
       WHERE id_cat=A.id_cat)
       AS catagory_name
FROM tbl_combine
AS A
WHERE id_blog=$blog_id

Note we just store id of tbl_blog and tbl_catagory tables is tbl_combine it will not slow


Image processing general questions and terms

Question: ) In digital image processing, an image is a matrix of rows (m) and columns (n) denoted by [m,n]. When showing as an image output would the rows become the Y axis and and column the X axis? Just wanted to confirm this as sometime it is confusing. In Matlab and in textbook what is the convention?

Do we call a gray-scale image as a matrix or a 2D array? What is the difference between these two?

What is a tensor image?
Comment: you can easily google the first one. The second one is yes, a 2D array is a matrix. A tensor image is an image that has multiple values per pixel.
Answer: • The rows would extend from left-to-right. The columns would extend from top-to-bottom. Below each square represents a pixel within the image. To count the number of rows you would go along the y-axis to get dimension (m). To count the number of columns you would go along the x-axis to get dimension (n).
In the below "Test Image" m = 2 and n = 4.

• As the comment above stated a 2D-array is a matrix. A greyscale image only has a single channel causing it to be a 2D-array. An RGB-image can have 3 channels leading to a matrix with the third dimension of 3.

• A tensor image provides more than one data sample per pixel. A tensor image is a multi-dimensional array. I can imagine various types that may take advantage of RGB, HSV, LUV colour spaces along with other more sophisticated data.
Here is an example that might shed some light:

<code>Image = imread("Image.png");
%Grabbing the size of the image%
[m,n,h] = size(Image);

Number_Of_Rows = m;
Number_Of_Columns = n;
Number_Of_Colour_Channels = h;

fprintf("Number of rows (m): %d pixels\n",Number_Of_Rows);
fprintf("Number of columns (n): %d pixels\n",Number_Of_Columns);
fprintf("Number of colour channels: %d channels\n",Number_Of_Colour_Channels);

%Plotting the image%
Figure = figure(1);
imshow(Image);
truesize(Figure);

title('RGB Image');
xlabel(["Number of Columns" num2str(Number_Of_Columns)]);
ylabel(["Number of Rows" num2str(Number_Of_Rows)]);
</code>
Comment: Yes, that's right. In academia, it is common to denote in the (x,y) format. This causes the convention to be reversed. Typically I work in rows (m) and columns (n) to avoid any confusion since most programming languages abide by this. I'll create a small script that you can play with to experiment.
Comment: Here's the script I came up with to clarify. It uses a small grid and set of pixels that you can play with to test around. https://github.com/MichaelTr7/StackOverflow/tree/master/Sample_Image_Test
Comment: thank you for your answer. In the image the row, `m` is represented by the Y axis and column, `n` by X axis. But in the explanation you mentioned that rows `m` extends from left to right --> this to me means traversing the Y axis OR did you do a typo where the rows means top to bottom? Is the horizontal & vertical axis reversed? I mean, the X and Y axis in the explanation and the picture do not match Can you please clarify?
Comment: I added a diagram to clarify.  Hopefully, this clears up any misconceptions. Image processing best described with images right.
Comment: Thank you for the clarifications. So just to confirm if I understood you correctly, (1) rows --> correspond to Y axis and columns -->X axis? (2) Why in textbooks (http://www.ece.northwestern.edu/local-apps/matlabhelp/toolbox/images/intro28.html) it is mentioned that the coordinate is reversed? What is the reversal coordinate or is it the one that you have explained in your answer? In maths, we write x c-oordinate first followed by y coordinate (x,y) so `x` means accessing the horizontal axis and `y` means `vertical axis`. In image, it seems reversed?
Comment: So if I want to access element at (2,3) coordinate position, I should go to row 2 and column 3 in image, similar to the access scheme in Maths array ?
Comment: Yes, accessing element (2,3) will give you the element in row 2 and column 3.
Comment: But in graph, the first element 2 represents the x axis and second element = 3 represents the y axis. But in image, this is reversed to me. Or did I misunderstand.
Comment: Oh, I see the conventions you are going by in the article. If I have this right  if (x = 2, y = 3) → (row = 3, column = 2). In MATLAB you would call this by using Image(3,2).
Comment: Yes, this is my confusion which one is correct? Translating the image to a graph shows that the coordinates are reversed. But your answer makes more sense. In general, if x is the horizontal axis and y is the vertical axis then in an image representation x = columns and y = rows like you shows with the tiger image?
Comment: I see, so the (x,y) in images does not mean that the first element refers to the horizontal axis (rows) and the second element in y is the y axis (colm)?  thank you for the script and explanation
Comment: Yeah, it, unfortunately, doesn't. Not sure why the conventions are like that. It even states in the article/textbook that was linked.


Drake Visualizer : Unknown file extension in readPolyData when using .dae file

Question: I am trying to add a custom mesh (a torus) .dae file for collision and visual to my .sdf model.
When I run my program, drake visualizer gives the following error
  File "/opt/drake/lib/python2.7/site-packages/director/lcmUtils.py", line 119, in handleMessage
    callback(msg)
  File "/opt/drake/lib/python2.7/site-packages/director/drakevisualizer.py", line 352, in onViewerLoadRobot
    self.addLinksFromLCM(msg)
  File "/opt/drake/lib/python2.7/site-packages/director/drakevisualizer.py", line 376, in addLinksFromLCM
    self.addLink(Link(link), link.robot_num, link.name)
  File "/opt/drake/lib/python2.7/site-packages/director/drakevisualizer.py", line 299, in __init__
    self.geometry.extend(Geometry.createGeometry(link.name + ' geometry data', g))
  File "/opt/drake/lib/python2.7/site-packages/director/drakevisualizer.py", line 272, in createGeometry
    polyDataList, visInfo = Geometry.createPolyDataFromFiles(geom)
  File "/opt/drake/lib/python2.7/site-packages/director/drakevisualizer.py", line 231, in createPolyDataFromFiles
    polyDataList = [ioUtils.readPolyData(filename)]
  File "/opt/drake/lib/python2.7/site-packages/director/ioUtils.py", line 25, in readPolyData
    raise Exception('Unknown file extension in readPolyData: %s' % filename)
Exception: Unknown file extension in readPolyData: /my_path/model.dae

Since prius.sdf also uses prius.dae, I assume this is possible.  What am I doing wrong?
Answer: tl;dr drake_visualizer doesn't load dae files. If you put a similarly named .obj file in the same folder it will load that (and you can leave your sdf file still referencing the dae file).
Long answer:
drake_visualizer has a very specific, arbitrary protocol for loading files. Given an arbitrary file name (e.g., my_geometry.dae) it will

Strip off the extension.
Try the following files (in order), loading the first one it finds:

my_geometry.vtm
my_geometry.vtp
my_geometry.obj
original extension.

It can load: vtm, vtp, ply, obj, and stl files.
The worst thing is if you have both a vtp and an obj file in the same folder with the same name and you specify the obj, it'll still favor the vtp file.