Are interaction terms commutative?

Question: Im trying to understand interaction effects a little better. My question is, if I have a model that's described by:
$y = \beta_{0} + \beta_{0}x_{1} + \beta_{0}x_{2} + \beta_{0}x_{1}x_{2} + \epsilon$
where, $\mathit{x_i\sim N(0,1)}$ and $\epsilon\sim N(0,1)$.
Is the interaction between $x_1$ and $x_2$ commutative?
As in, if I change the order of the variables to the following, does it make a difference... and if so, why?
$y = \beta_{0} + \beta_{0}x_{1} + \beta_{0}x_{2} + \beta_{0}x_{2}x_{1} + \epsilon$
Comment: Is it really the intention that all the $\beta$'s shall have the same subscipt $_0$, so be identical?
Comment: yes, that's intentional. In the toy model I'm experimenting with I've set all the $\beta$'s to have the same value. However, it's not a necessity that they are all equal.
Answer: If $x_1$ and $x_2$ are real numbers, then their multiplication commutes.
You could rewrite your equation like this:
$$y = \beta_0 + \beta_0x_1 + \beta_0 x_2 + \beta_0x_3 +\epsilon$$
$$x_3 = x_1x_2$$
I think this makes it clear that the interaction commutes.
Answer: Yes, under the commutativity law for multiplication, $\beta_{0}x_{2}x_{1}$ and $\beta_{0}x_{1}x_{2}$ are the same.
Comment: @Electrino Yes: $x_1x_2$ and $x_2x_1$ are literally the exact same numbers.
Comment: @Electrino I wonder if it's because of some numerical issue when you switch the multiplication order. When you multiply the $x_1$ and $x_2$ columns to produce $x_3$, are the numbers slightly different than when you reverse the multiplication order?
Comment: Follow up question, if $\beta_{0}x_{1}x_{2}$ and $\beta_{0}x_{2}x_{1}$ are commutative, then am I correct in saying that if I measure the interactions $x_{1}:x_{2}$ and $x_{2}:x_{1}$, then I should get the same value (i.e., the interactions are symmetrical?)
Comment: thanks for the clarification. The main reason I'm being explicitly clear is because, for some reason, in my model, the interactions aren't exactly symmetrical. I'll post a different question to try get to the bottom of this.
Answer: Conventionally speaking, there is no interaction terms in the model. Rewritten as $y=\beta_0(x_1 + x_2 + x_1x_2) + \epsilon$, we see this is simple linear regression of $y$ on $z=x_1+x_2+x_1x_2$ with forcing the intercept term to be zero.
Given that $z$ is symmetric in $x_1$ and $x_2$, it seems clear that the "interaction" is "symmetric" in $x_1$ and $x_2$ in any sense of the word.

Are interaction terms commutative?


Efficient ways to octave down notes that exceed range?

Question: Often, I'll come across music with notes that exceed my range. Typically, I will just octave the phrase down, and that usually sounds fine. Recently, I've come across a run, in which if I were to octave it down so I could play it properly, the lower end would go below trumpet range (below a concert e). Short of improving my range (which I am working on), what is the best way to octave down so that it is playable and still sounds good? The highest I can consistently play is the A just above the staff.
An example I have found in sheet music is an f minor blues scale going down two octaves to middle f.
I couldnt manage to upload a picture of the sheet music so I did my best to recreate the run I want to be able to play
Comment: As a clarification, you're dealing with an f minor blues scale that starts on the f above the staff and descends to the f on the first space in the staff? Also, what is currently the comfortable top of your range?
Comment: If we're dealing with the run, what's its highest note? If we're dealing with the f minor blues scale, you _could_ transpose it down an octave: it would then be within your range. But it would sound brighter and more like the original if you were to transpose it down a minor 6th, so that the highest note would be your top A (just above the staff) and the lowest the A below the staff.
Comment: Having the notation for the written run will get you the best answers, otherwise it's a guessing game as there are different ways of handling something like this.
Comment: Yes. Currently the top of my consistent range is the A just above the staff.
Comment: Is it just an exercise, or part of an actual composition you want to play?
Comment: @user1079505 This is part of a composition I would like to play (a written solo for a jazz piece)
Comment: Alright, I added it
Answer: My short and obviously subjective suggestion is to move the first measure octave down. The pause at the beginning of the second measure makes a decent break point. Then both first and the second measure start on the same note (F), which legitimizes the whole structure.
An alternative could be to compose a different version of this (or another) measure which follows the rhythm and shape of the original melody, outlines the same harmony, but moves in appropriately reduced range. In an improvised genre like blues changing some notes of the melody can be acceptable.
Speaking more generally, if the notes fall outside of the range of the soloist, a common solution is to change the key. Vocalists do it routinely. Also jazz/blues musicians often transpose music fluently.
Answer: In general if you are taking something down (or up) an octave because it's out of your range, you'll want to switch to the the correct octave as soon as practical after the notes go into your range. You need to consider musical aspects to choose the exact point. Good places to jump are:

at a bar line
at a new phrase, or a break within a phrase
after a rest
where the line jumps downwards (to minimise the jump up)

If your range goes to A, then, for this example, a couple of obvious places to jump are:

after the second quarter of measure 1
after the fourth quarter of M1

There are several places after that, that make musical sense (e.g after the second quarter of M3), but they put you in your lower range for too long.
In the end it's your decision. Do whatever you think works best for you.
Answer: I think the best move is to play only the first 4 notes down the octave. The C up to Ab is a good place to jump up and is the most musical way to play that phrase IMO. Frankly I think the line has a better shape overall that way. It also puts the descending line from the Ab to the C in the staff in a logical place. Try it and see what you think.
Answer: Keep the shape of each phrase or sub-phrase as far as possible.   In your example I think it would be effective to break the octave-down transposition at any of the first three rests.  My preference would be for the second one.


Factorise $x^4+y^4+(x+y)^4$

Question: I think this problem involves making use of symmetry in some way but I don't know how. I expanded the $(x+y)^4$ term but it din't help in the factorization. I am very bad at factorizing, so I didn't work too long on this problem. Any help would be appreciated, I want hints rather than a full solution. But even a full solution is okay.
Answer: Note
\begin{align}
&x^4+y^4+(x+y)^4\\
=&(x^2+y^2)^2 -2x^2y^2 + (x^2+y^2+2xy)^2\\
=&2(x^2+y^2)^2 +4xy(x^2+y^2)+ 2x^2y^2\\
=&2(x^2+y^2+xy)^2
\end{align}
Comment: I think it should be $4xy(x^2+y^2)$ in the third line.
Comment: @SujalMotagi right thanks
Comment: How did you come up with this? Could you tell me about some of the motivation behind it.
Comment: and the final result should be $2 \left(x^2+x y+y^2\right)^2$
Comment: @Lozenges you're correct
Comment: @SujalMotagi for symmetric quartic polynomials, you often look for factors in the form $x^2+axy +y^2$
Answer: If $a+b+c=0$
$$a^4+b^4+c^4$$
$$=(a^2+b^2)^2-2a^2b^2+c^4$$
$$=((a+b)^2-2ab)^2-2a^2b^2+c^4$$
$$=((-c)^2-2ab)^2-2a^2b^2+c^4$$
$$=2(c^2-ab)^2$$
Here $a=-x,b=-y,c=?$
Answer: Let $s={x+y\over 2}$ so $x,s,y$ make an arithmetic progression with difference name it $d$. So $x=s-d$ and $y=s+d$.
Now \begin{align}E&= (s-d)^4+(s+d)^4+16s^4\\
&= 2s^4+12s^2d^2+2d^4+16s^4\\
&= 18s^4+12s^2d^2+2d^4\\
&=2(9s^4+6s^2d^2+d^4)\\
&=2(3s^2+d^2)^2
\end{align}
Answer: $x^4+y^4+(x+y)^4=2x^4+6x^2y^2+4x^3y+2y^4+4y^3x=2(\color{green}{x^4}+3\color{green}{x^2y^2}+2x^3y+\color{green}{y^4}+2y^3x)$
You can see by expanding that $3$ terms are perfect squares, so you can attempt $(x^2+a.xy+y^2)^2$ and see what's left, with a coefficient for $xy$ since this is unsure how much $xy$ there is.
It is not guaranteed to works, but if the expression is indeed a square, your chances are high.
Answer: $$x^4+y^4+(x+y)^4$$
$$=2x^4+4x^3y+6x^2y^2+4xy^3+2y^4$$
$$=2(x^4+2x^3y+3x^2y^2+2xy^3+y^4)$$
$$=2(x^2+xy+y^2)^2$$
The last bit I guessed from $111^2=12321$.
Comment: This way is not as elegant as @Quanto's way of doing it but this way is more obvious and that's what I usually prefer while solving math.

Factorise $x^4+y^4+(x+y)^4$


Why Does My CSS Grid when I add  to an image?

Question: When I add an anchor to an image, the grid breaks.
with anchor tag](https://i.stack.imgur.com/ykr64.jpg)
without acnchor tag](https://i.stack.imgur.com/6HPE4.png)
I quadrouple checked my code, I searched overstack, and google, and nothing addresses this directly.  I also noticed someone asked this question 2 years ago, but he didn't get a clear answer.  Please help me. Thanks in advance.

FEATURED MENUS

BRUNCH

LUNCH

DINNER

.food-box {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: auto;
    row-gap: 0em;
    color: #262626;
    background-color: #fdfdfd;
    font-family: 'Roboto', sans-serif;
}

#food-title {
    grid-column-start: 2;
    position: relative;
    justify-self: center;
    }

#dish1 {
    grid-column-start: 1;
    padding-left: 1em;
    grid-row-start: 2;
    max-width: 20em;
    }

#dish-title1 {
    position: relative;
    left: 7em;
    grid-column-start: 1;
    padding-left: 1em;
    }

#dish2 {
    grid-column-start: 2;
    grid-row-start: 2;
    max-width: 20em;
    }

#dish-title2 {
    position: relative;
    left: 7em;
    grid-column-start: 2;
    grid-row-start: 3;

    }

#dish3 {
    grid-column-start: 3;
    grid-row-start:2;
    max-width: 20em;
    }

#dish-title3 {
    position: relative;
    grid-column-start: 3;
    grid-row-start: 3;
    left: 7em;
    }

Answer: You have specific grid styling for your images (e.g. #dish1 { grid-column-start: 1; }).
When you wrap the images in links, the images are no longer grid children. The links are the grid children instead. You're styling the wrong elements.
Comment: Ahhhh woW!  Ok thank you! I didn't know the  counts as a container... Now I know, Lesson learned!


How to create a Solr search with partial matches and autocomplete?

Question: I configured a search box for a drupal site and am a bit confused on how to get a search working with partial matches and a sensible autocomplete.
Some basic details:

Drupal: 9.3.9
Modules: Search API, Search API Autocomplete, Search API Solr
Solr: 8.11.1

The search searches through different fields from several types of content. At first I set the field types to "Fulltext". Then I noticed that only complete words are matched. So searching for "idea" would not find pages containing "ideas". That worked when I changed all field types to "Fulltext ngram". But: Now the autocomplete suggests all the partials as well. So entering "super" would suggest "superh", "superhe" and "superhero". That's not really useful for the site's visitors.
What I already tried: The autocomplete uses the suggester "Retrieve from server". I tried to enable the additional module "search_api_solr_autocomplete". That adds three more suggesters, "Solr Spellcheck", "Solr Suggester" and "Solr Terms". The spellcheck suggester did not yield any autocomplete suggestions. Neither did the Solr Suggester. Solr Terms does the same as "Retrieve from server", it suggests all intermediate steps between the search word and the finished term, letter for letter.
What I am looking for is a clue how to configure this so that the search matches tokens with partial searches, but that only complete tokens are used for the autocomplete feature. Maybe a configuration step is missing?
Comment: Is your search block created using views with an exposed filter using "Fulltext search" field?
Comment: Yes, I use a view with a fulltext search filter.
Comment: You may have to create two indexes and then use this https://www.drupal.org/project/fac on your search input field. This would search the index without ngram for the autocomplete but when you press search/submit it uses the view.
Comment: Sorry for the lack of feedback. I spent so much frustrating time on this issue, that I needed some time away from it. My current solution is that I have a new field which is a concatenation of all the other fields' contents. This field is the source for the autocomplete. This seems like the right approach, but is not working in practice. I think, I struggle with selecting the right field type for the new field.
Answer: I couldn't get this to work previously, but after upgrading to Drupal 9.4 it now works. What I did was this:

I added a new field "autocomplete_tokens" as an "aggregated_field". I put all the text fields in there that were part of the search, especially the rendered HTML and the file contents.
As a field type I chose "Fulltext Tokens", which is defined as "Full text field without any processing like stemming or stop word filters, just unmodified tokens from the text separated by white spaces". This way, all the words in the input stay exactly as they are. No stemming, no breaking up ito ngrams.
In the "autocomplete" tab of my index, I clicked on "Edit" and chose the suggester "Retrieve from server". Under "Configure suggester Retrieve from server > Override used fields" I chose the new field "autocomplete_tokens". This way, the autocomplete feature got its suggestions only from my new field, not from all the other stemmed and ngrammed fields.

And that's it, this time it worked like a charm. Reindex all contents (since a new field was added and needs to be present in the index), and the autocomplete now behaves as expected. I can only guess that I did something stupidly wrong or that something changed with Drupal 9.4.
This solution has some caveats, of course. First, when I add a new field to be part of the search (e.g. for a new content type), I have to remember to add it to the autocomplete token concatenation field as well. This can easily be forgotten. On the other hand, I also have to add the new field to the view and maybe other places, so this needs to be tested anyway.
I also found that this datatype does not remove punctuation from the tokens. So if my content contains e.g. "unbowed, unbent, unbroken", the autocomplete suggestion for "unb" is "unbowed," and "unbent," along with "unbroken" (or "unbroken.", if it ends as a sentence). This can maybe dealed with using a different field type or adding a special field type to the schema.xml. Since I wanted to close this issue fast, I added a filter instead to my local search module:
<code>function my_module_search_api_autocomplete_suggestions_alter(array &$suggestions, array $alter_params) {
  $allNewSuggestions = [];
  foreach ($suggestions as $index => $suggestion) {
    // Remove punctuation from the end of autocomplete suggestions.
    $newSuggestionSuffix = rtrim($suggestion->getSuggestionSuffix(), ".!?,-'\"");
    $suggestion->setSuggestionSuffix($newSuggestionSuffix);

    // Now remove duplicates that occur if two different input suggestions are
    // reduced to the same token when removing the punctuation.
    $newSuggestion = $suggestion->getSuggestionPrefix() . $newSuggestionSuffix;
    if (in_array($newSuggestion, $allNewSuggestions)) {
      unset($suggestions[$index]);
      continue;
    }
    $allNewSuggestions[] = $newSuggestion;
  }
}
</code>
This removes all punctuation from the end of the suggestions and removes duplicates (if a word was suggested one with a trailing comma and once with a trailing full stop, for example). Now we might have fewer than the configured number of sugestions, but I can live with that.
I also notice that all the suggestions are in lower-case, which looks a bit strange for German nouns. But for now I can also live with that.


Sample size calculation with multiple conditions

Question: I am interested in computing the required sample size for bioreactor yields. The mean yield should be 60% or more with no yield being less than 25% and at-least 60% of runs should have more that 60% yield. the alpha will be 0.05. I plan to use a t-test for the purpose. any suggestions?
Comment: Can you provide more details of the experiment you are performing? Guidance on improving your question is here: https://stats.stackexchange.com/help/how-to-ask
Comment: In order to calculate a required sample size you need to state the size of the difference of yields that you want to detect.
Answer: The first question is what is the appropriate analysis. This is an analysis of change from baseline, specifically whether a proportion change under one experimental condition is greater than the same change under a different experimental condition, presumably performed in separate units.
The most valid analysis is an ANCOVA where the response is log transformed, the baseline is adjusted as a covariate in the model, and the experimental condition is adjusted as a binary covariate. This will reduce false positive findings when certain assumptions aren't met. However, those assumptions are unexpected and difficult to quantify, so for the purposes of the power calculation, the simplified t-test can be used as the basis for a sample size calculation. The response here is the log of the ratio of post/pre. The one correction we might make is to add one to the final sample size to account for the additional degree-of-freedom for estimating the baseline effect.
To identify the meaningful parameters for a t-test sample size calculation, you've identified the effect, but you must specify the variance of the log-pre-post response. In other words, we don't know what the $\pm$ is for the effect size you've proposed... for experimental condition A, will the 95% CI be 60% (50-70%) or 60% (20-100%)?
Comment: A randomized sampling should increase the yield by at least 20% and a mean increase of 60%. The CI being 95% .
Comment: Thanks a lot I assume I can do it with anova with main and special effect and defining effect size from data :)


Reuse subquery results in multiple SELECT in Oracle (Can't create table)

Question: I have multiple SELECT queries using same subset of data. I  would like to reuse it so no repeated subqueries or WITH clause.  However, I can't CREATE TABLE or VIEW because of insufficient privileges. So is there a workaround?
I'm using TOAD Oracle.
For example,
WITH LOCAL_RESULTS
    AS (SELECT a, b, c, d...
          FROM SURVEY )
SELECT A, B
FROM LOCAL_RESULTS
where condition=1

WITH LOCAL_RESULTS
    AS (SELECT a, b, c, d...
          FROM SURVEY )
SELECT A, C
FROM LOCAL_RESULTS
where condition=2

WITH LOCAL_RESULTS
    AS (SELECT a, b, c, d...
          FROM SURVEY )
SELECT B, D, A...
FROM LOCAL_RESULTS
where condition=3

Thanks for any help.
Answer: A union query might work.
with local_results as
(subquery goes here)

select a, b, c, 1 condition
from local_results
where whatever
union
select a, b, null c, 2 condition
from local_results
etc

Comment: Thanks Dan but I would like to avoid using UNION because the 3 results pattern is very different. The select statements here are very simplified.


sda1 (?) raid failed on debian - what to do now?

Question: ispconfig says that my server has raid problems. The server is not mine, it is rented from a hosting company. The OS installation was not my business: the hosting firm did it.
cat /proc/mdstat

Personalities : [raid1]
md0 : active raid1 sda1[2](F) sdb1[1]
      312568576 blocks [2/1] [_U]

I'm really not familiar with this problem, I never met problem like this.
I guess sda1 is dead. Can you help me what to do now (apart from that I should call the hosting firm)? I have everything important backed up.
Answer: Don't panic, this is a common and recoverable error. Your hosting company set up a two-disk redundant array to protect the data in case one of the disks fails. This failure has now occurred. The output indicates that sda1 has failed, and that the RAID1 array is working, but degraded.
Right now you're on borrowed time, though. If the second disk fails, that data is gone and you'll have to restore from backup. Ask your hosting company to replace the failed disk immediately and get back to you when it's done!
Comment: @aseq: Disks are cheap, your data probably isn't.  Unless you know that a transient error happened and probably won't happen again, once a drive is marked bad, why not replace it?
Comment: Sure if this is a server with critical data go ahead and replace it. Though it's useful to try and bring the disk back to life until you got a replacement. But if the server is lowly QA machine or dev test box that's being abused anyways I see little point replacing a disk unless it is really broken.
Comment: thanks a lot. will the hosting company need to log in to my server and do anyting via the console, or they 'only' have to physically replace the disk and thats all? will i have to do anyting after the disk was replaced?
Comment: That depends on your service agreement with the hosting company. If they're a "full service" shop, then they'll do everything that's required and you can put your feet up on the table. If they ONLY physically swap the disk, you need to get your feet wet with mdadm. You don't sound comfortable with this option. If at ALL possible, give them access and have them do the entire job. Expect them to bill at a hefty rate (100-200 USD per hour). It's worth the peace of mind (and having someone to yell at).
Comment: ok, my last question before calling them (its almost midnigt here): if they will *not* do anyting except replacing the drive, do i need to do anyting *before* the disk replacement?
Comment: Depends on the storage controller, and the way that booting is configured. Pulling the disk hot (while it's on) could cause a kernel panic. Furthermore, that failed disk may have other things (like the files and settings required for Linux to boot). These are questions that your hosting company should be able to answer.
Comment: The disk does not necessarily have to be dead. I have brought disks back to life and made them an active part of the mdadm array again (and running for years) after having shown a similar failure. You may have good luck failing/removing and re-adding the disk with the proper mdam commands. Of course you need to know what you're doing, so if you feel uncomfortable with it, don't try it.
Answer: Also, making sure the backups are fine before messing or having someone mess with a degraded raid is a good idea. Cascade failures sadly happen, and so do mistakes by host staff (triple check that you and the hands at the hosting company are on the same page as to what is to be done to which disk).
AFAIK, if the device is called /dev/mdX, it is always linux softraid, so no hardware storage controller apart from a straight SATA or SAS host adapter is involved.
There are ways in linux to tell it that a disk is to be logically removed or has been added, however these should ever only be necessary if hotplugging directly attached PATA or parallel SCSI devices (which should be considered verboten anyway on hardware that does not explicitly support it anyway).
smartctl (from the smartmontools package; do not run it if there is an ssd involved AND the provider did not set up a smartmontools daemon or cron script on the server; there are versions of smart utilities known to damage certain ssds) can tell you a lot about WHAT is wrong with a drive, especially if directly attached as is the case here, so can calling dmesg. The spinup_count and power_on_hours values you get on the replacement disks you get sometimes make for interesting discussion topics with hosters ;)


Ruby on Rails - Submitting Form Data Directly to a Session Variable

Question: I have spent hours trying to find a resource that explains the process of submitting form data directly to a session variable, but I have had no luck finding anything!
Essentially I am not wanting to store the data in the database when the user submits in this particular form, I just want it to be assigned to the session[:member_pin] variable when the user submits the form, so I can then check if the pin they entered matches the pin on the members database record.
Please let me know if you need anymore clarification for what I am trying to do, and thank you so much for your help!
Comment: `session[:verified] = User.find_by_pin(params[:pin]).present?`
Comment: Why do you need to store anything in the session at all? Just verify the pin when it is submitted…
Comment: Oh! I didn't even know you could do that... what would that action look like?
Comment: This isn't checking the submitted pin against the current User's pin... this is just checking whether or not that pin exists in the database under any user... Any idea how to specify this same snippet to the current user?
Answer: You don't have to save the data to database every time a form is submitted. In your controller 's action, get the params you want and store them in the session. Eg.,
def some_action
  session[:user_id] = User.find_by_pin(params[:pin]) if params[:pin]
end

Then in your application controller, make a helper method like this. Then you should be able to access "current_user" method in your views. (It will be nil if you haven't got any user verified with pins.
def current_user
  User.find(session[:user_id]) if session[:user_id].present?
end

Comment: How would my `form_for` be set up?
Comment: Just updated the answer. Please check again. The form just has to submit the "pin" in a text field, I guess.
Answer: maybe something like this in your controller method:
session[:member_pin] = params[:member_pin_input_name]


Search numpy array inside numpy array

Question: I need to find if a numpy array is inside other numpy array, but it seems to work different to python lists.
I tried to search this question in numpy documentation and internet, but not answer.
This is an example:

    import numpy as np
m1=np.array([[1,2,3],[5,3,4]])
m2=np.array([5,4,3])
m2 in m1
True
m3=[[1,2,3],[5,3,4]]
m4=[5,4,3]
m4 in m3
False

In numpy I obtain True but with Python lists I obtain False. Is there any numpy function to make this work?
Thanks.
Comment: Is there a typo in m3? Did you mean `m3 = [[1, 2, 3], [5, 4, 3]]` in place of `m3 = [[1, 2, 3], [5, 3, 4]]`.
Answer: To get the same behavior as in for lists, you could do something like this:
any(np.all(row == m2) for row in m1)

That does the loop over rows in python, which isn't ideal, but it should work.
To understand what's going on with the numpy in, here's a description of the semantics of in from Robert Kern on the numpy mailing list:

It dates back to Numeric's semantics for bool(some_array), which would
  be True if any of the elements were nonzero. Just like any other
  iterable container in Python, x in y will essentially do
for row in y:
   if x == row:
       return True
return False

Iterate along the first axis of y and compare by boolean equality. In
  Numeric/numpy's case, this comparison is broadcasted. So that's why
  [3,6,4] works, because there is one row where 3 is in the first
  column. [4,2,345] doesn't work because the 4 and the 2 are not in
  those columns.
Probably, this should be considered a mistake during the transition to
  numpy's semantics of having bool(some_array) raise an exception.
  scalar in array should probably work as-is for an ND array, but
  there are several different possible semantics for array in array
  that should be explicitly spelled out, much like bool(some_array).

Search numpy array inside numpy array


Como escapar caracteres no Batch do Windows?

Question: Tenho o seguinte script:
start "" "https://site.com.br/app/index.jsf?username=nomecabuloso&token=tokenzera"

Porém, quando eu executo, ele não passa do index.jsf, ele abre o seguinte url:
https://site.com.br/app/index.jsf

Já tentei utilizar a tecla de escape \, para o ?, mas não funciona.
Minha dúvida é, como fazer ele executar o link inteiro?
Comment: Era pras aspas já escaparem os caracteres.
Answer: Para escpar caracteres use o acento circunflexo ^
Comment: @Francisco o `&` é um caracter especial então precisa de um `^` nele também.
Comment: Percebi. Consegui fazer funcionar, vlw.
Answer: Não precisa de nada disso,basta fazer assim:
@echo off
start chrome "https://site.com.br/app/index.jsf?username=nomecabuloso&token=tokenzera"

Obs: troque o nome do navegador pelo navegador que você irá abrir.
Answer:

Para usar passando argumento/parâmetro e não necessitando de prévias edições nos caracteres especiais presentes no link.

Basicamente, o bat vai jogar o argumento/parâmetro (%1) no loop for e já adicionado aspas (usebackq)

Q236618.cmd "%1"

Q236618.cmd "https://site.com.br/app/index.jsf?username=nomecabuloso&token=tokenzera"

Código Q236618.cmd com argumento '%1' no for usando usebackq...

@echo off & for /f usebackq %%i in ('%1')do start "" /b %%i

Código Q236618.cmd com '%1' ou 'link' direto no for usando usebackq filtrado num if...

@echo off
if not ".%~1" == "." (for /f usebackq %%i in ('%1')do start "" /b %%i) else (
for /f usebackq %%i in ('"https://site.com.br/app/index.jsf?username=nomecabuloso&token=tokenzera"')do start "" /b %%i)


Dynamic change of style from combobox value qml

Question: Everyone, I have made my own style and add this to qml.qrc then I calling it in main.cpp:
engine.addImportPath("qrc:/Styles");
QQuickStyle::setStyle(Modern style);

Everything is working, but I've to make it dynamically changing from C++ code, and taking value from combobox

I've tried to add:
char str1[] = "Basic";
engine.rootContext()->setContextProperty("styling", *str1);
QQuickStyle::setStyle(str1);

Like this it doesn't change in real-time, maybe someone helps me, thank you.
P.S.: I need dynamically change style of app, which depends on the value of selected value in comboBox).
Comment: Make `str1` a `QString` instead.
Comment: QString str1 = "Basic";
engine.rootContext()->setContextProperty("styling", str1);
QQuickStyle::setStyle(str1);

Also I've writed to combobox.qml
onActivated : {
            styling = _comboBox.currentText;
            console.log("FINE");
        }
But it's doesn't change style dynamicly
Comment: @Zond please provide a [mre]
Answer: i've founded solution:
It is not possible to change the style on the fly, because QQC2 styling is based on QML type registration time file selection, but it is possible to:
unload all QML,
destroy any existing QQmlEngine instance(s),
call qmlClearTypeRegistrations(),
call QQuickStyle::setStyle(),
and then re-load the QML content so that QQC2 types are re-registered with the new style.
This process should be clearly documented in QQuickStyle. Preferably, an example should be provided that uses QML Settings to retain the state of the UI, for example.
It is important to emphasize the warning in the qmlClearTypeRegistrations() docs:
Do not call this function while a QQmlEngine exists or behavior will be undefined. Any existing QQmlEngines must be deleted before calling this function. This function only affects the application global cache. Delete the QQmlEngine to clear all cached data relating to that engine.


Get date in php in 2 weeks

Question: $addhr = time() + (1 * 13 * 60 * 60);
$curDateTimeMil= date("Y-m-d G:i:s",$addhr);
echo $curDateTimeMil;

This will echo 2010-08-27 16:21:31.
How can I get the date after 2 weeks? (sept 10)
Comment: Out of curiosity, what did you expect `1 * 13 * 60 * 60` does?
Comment: There is also a example in the [PHP date() documentation](http://php.net/manual/en/function.date.php) how to achieve this. Read Example #3. But strtotime would be a solid solution (@jensgram).
Answer: $dateInTwoWeeks = strtotime('+2 weeks');

See strtotime().

Update #1: Yes, this is the lazy way to do it. However, I do believe that the possible negative performance impact is countered by the positive effect on readability / understanding of the code. Should performance be an issue, one could switch to native (integer-based) time manipulation (and add comments).

Update #2: The optional second argument is the reference date. E.g.:
strtotime('+2 weeks', mktime(0, 0, 0, 2, 8, 1984)); // 8th Feb. 1984 + 2 weeks

Comment: By accepting answers to some of your previous questions :-)
Or reading the documentation. Or using `time()`.
Comment: how can i specify the start date before obtaining the date in 2 weeks?
Answer: You can specify the starting time (from where to calculate) using mktime().
Example: Two week after September 10, 2010 (i.e. +14 days):
 $date = date("Y-m-d", mktime(0, 0, 0, 9, 10 + 14, 2010);

To get just the DATE (not time) of two weeks later (+14 days) from today:
 $date = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d")+14, date("Y")));

And this gives with TIME of two weeks later (+14 days) from now:
 $date = date("Y-m-d G:i:s", mktime(date("G"), date("i"), date("s"), date("m"), date("d")+14, date("Y")));

Answer: You could simply add the number seconds of two weeks:
2 weeks = 2 · 7 days = 14 days
        = 14 · 24 hours = 336 hours
        = 336 · 60 minutes = 20160 minutes
        = 20160 · 60 seconds = 1209600 seconds

So:
$curDateTimeMil += 1209600;
// or
$curDateTimeMil += 2 * 7 * 24 * 60 * 60;

Comment: @deceze: That's not an issue with the time but with the representation of the time.
Comment: With the tiny caveat that you may miss the right day if you're unlucky enough to fall into a daylight savings switchover or leap second... :)

Get date in php in 2 weeks


Cardano's Method Application

Question: Please forgive me for any mistake in the proposal of this problem
Problem

The first step of Cardano's Method states:-Remove the term containing $x^2$ by taking $y=x-\dfrac{b}{3a}$. However if we are not able to remove the $x^2$ in a equation then how will we solve it.

Any help is welcome. Thanks in advance
Comment: Why shouldn't you be able to remove the quadratic term?
Comment: Isn't it a contradiction in the problems description? Think about it again!
Comment: Go here $\longrightarrow$ https://www.math.ucdavis.edu/~kkreith/tutorials/sample.lesson/cardano.html
Answer: Your question doesn't make sense. If, in $ax^3+bx^2+cx+d$ (with $a\neq0$), $x$ gets replaced by $y-\frac b{3a}$ and then you expand it, you always get a cubic without a monomial with degree $2$, namely$$ay^3+\left(c-\frac{b^2}{3a}\right)y+\frac{2 b^3}{27 a^2}-\frac{c b}{3 a}+d.$$

Cardano's Method Application


creating an animated responsive popup pulling content from another page

Question: I am trying to create a responsive animated popup that pulls content from another page. This would be so that variable values can be passed from java-script (in parent page) to a PHP variable via URL query string (in popup content page).
Thanks
Answer: You can do it like this:
<code>$('#popup').css("display","hidden");
var href = "http://yoursite/anotherpage.php?var1=value1";
$.ajax({
   url:href,
   type:'GET',
   success: function(data){
       $('#content').html($(data).find('#popup').html());
       $('#popup').css("display","block");
   }
});
</code>


iOS trouble parsing large JSON message

Question: I've got an app that receives JSON messages over TCP. This works perfectly for smaller messages, however sometimes when the messages are large they get cut off in the middle, and the app is unable to parse them.
My iOS code:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {

    collectedData = [NSMutableData data];

    switch (streamEvent) {

        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");

            break;
        case NSStreamEventHasBytesAvailable:

            if (theStream == inputStream) {

                NSData *nl = [@"\n" dataUsingEncoding:NSUTF8StringEncoding];

                uint8_t bufferz[1024];
                int lenz;
                while ([inputStream hasBytesAvailable]) {
                    lenz = [inputStream read:bufferz maxLength:sizeof(bufferz)];
                    [collectedData appendBytes: (const void *)bufferz length:lenz];
                }
                NSRange nlRange =[collectedData rangeOfData:nl options:0 range:NSMakeRange(0, [collectedData length])];
                while (nlRange.location != NSNotFound) {
                    // Extract data from the beginning up to (but not including) the newline character:
                    NSData *jsonData = [collectedData subdataWithRange:NSMakeRange(0, nlRange.location)];
                    // Remove data from the beginning up to and including the newline character:
                    [collectedData replaceBytesInRange:NSMakeRange(0, nlRange.location + nlRange.length) withBytes:NULL length:0];

                    // Process jsonData ...
                    NSError *error;
                    NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                    // ...

                    NSString* type = [jsonDict objectForKey:@"type"];

                    //NSLog(@"NEW NEW NEW --> %@\n", jsonDict);
                    NSString *outputData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

                    if(error) {
                        NSLog(@"THE STRING ------------>>>>> %@\n", outputData);
                        NSLog(@"PARSE ERROR ------------->>>>> : %@\n", error);
                    }

                    //NSLog(@"TYPEN ----------------------------------------------> %@", type);

                    if([type isEqualToString:@"message"]) {
                        //NSLog(@"New chat message: %@", output);

                        [self messageReceived:outputData];

                    } else if([type isEqualToString:@"offlineMessages"]) {
                        NSLog(@"New offline messages: %@", outputData);
                        NSLog(@"NEW OFFLINE MESSAGES!!");
                        [self offlineMessagesReceived:outputData];

                    }

                    // Check for another newline character:
                    nlRange =[collectedData rangeOfData:nl options:0 range:NSMakeRange(0, [collectedData length])];
                }
            }
            break;

        case NSStreamEventErrorOccurred:

            [self closeNetworkCommunication];
            isConnected = 0;

            NSLog(@"STREAM ERROR");
            //theStream = nil;

            break;

        case NSStreamEventEndEncountered:

            [self closeNetworkCommunication];
            isConnected = 0;

            NSLog(@"STREAM END");
            //theStream = nil;

            break;
    }
}

This is an example string that the server is sending the app:

{"id":"1", "type":"offlineMessages", "msg":
  "{\"agentsArray\":[{\"id\":281102,\"msgFrom\":\"V281570150514504\",\"msgDate\":\"2014-04-10T11:09:49.000Z\",\"msgBody\":\"Pellentesque
  habitant morbi tristique senectus et netus et malesuada fames ac
  turpis egestas. Donec odio tellus, dictum eu congue id, malesuada non
  risus. Mauris dapibus velit massa, non laoreet lectus lacinia nec.
  Morbi sagittis molestie eros, nec blandit sem accumsan eget. Aliquam
  eu sem egestas, malesuada urna sit amet, gravida velit. Curabitur
  auctor sit amet turpis vitae feugiat. Nam id velit viverra eros
  blandit consectetur vel eu tortor. Nullam at augue eros. Praesent
  dolor libero, venenatis in adipiscing vitae, dignissim nec nisi. In
  lobortis sem a neque ultrices, a vestibulum urna ullamcorper.
  Pellentesque eu suscipit est, quis dignissim orci. Aenean condimentum
  vitae dolor ac cursus. Aenean eu pulvinar nunc, et mollis erat.
  Vestibulum commodo malesuada nunc et iaculis. In mattis cursus mi
  vitae gravida. Etiam et iaculis tellus, non iaculis
  nulla.\",\"channelID\":\"V281570150514504\",\"recipient\":\"email@example.com\"}]}",
  "name": "281", "time": "12:09", "channel": "V281570150514504"}\n

Sometimes the app will parse the message like this:

auctor sit amet turpis vitae feugiat. Nam id velit viverra eros
  blandit consectetur vel eu tortor. Nullam at augue eros. Praesent
  dolor libero, venenatis in adipiscing vitae, dignissim nec nisi. In
  lobortis sem a neque ultrices, a vestibulum urna ullamcorper.
  Pellentesque eu suscipit est, quis dignissim orci. Aenean condimentum
  vitae dolor ac cursus. Aenean eu pulvinar nunc, et mollis erat.
  Vestibulum commodo malesuada nunc et iaculis. In mattis cursus mi
  vitae gravida. Etiam et iaculis tellus, non iaculis
  nulla.\",\"channelID\":\"V281570150514504\",\"recipient\":\"firstname.lastname@example.com\"}]}",
  "name": "281", "time": "12:09", "channel": "V281570150514504"}\n

I should add that this does not happend all the time, its around 50% off the times.
Any ideas what I'm doing wrong?
Comment: You might give `JSONObjectWithStream:options:error:` a try. I've never tested this myself where the input are multiple JSON documents, though.
Comment: Try to append the data until you receive the end of the message and try to parse it only then.
Comment: @Jenox How would i accomplish that?
Comment: What exactly are you trying to accomplish with the newline stuff?
Comment: Im using the newline to separate messages
Comment: I would not use newlines for that. Why don't you send a JSON array if you have multiple messages to send? I think the issue has something to do with your newline code.
Comment: I cant change the way the server is sending the messages :/ Have to somehow solve this within the app
Comment: Sorry, I'm afraid I cannot help you then. Your code looks fine to me.
Answer: It sounds like you're probably running into issues around TCP packet sizes. So when a message is large, it's split up and not received all at once.
From the way it looks, you would need to build in checks to make sure you have all of the bytes you are expecting before attempting to process the JSON.
Here is the Apple documentation for something kind of "similar", https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html#//apple_ref/doc/uid/20002273-BCIJHAGD.
You will see from that it can handle multiple runs of handleEvent and appends the data to the buffer as it goes.
Hope that helps.
Answer: Use following for getting JSON data from server
 NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:myUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", json);
}];
[dataTask resume];

Comment: Not quite sure that I follow, what should i replace in my code? =)

iOS trouble parsing large JSON message


Contextual link in Product Display type to allow me to edit the referenced Product?

Question: I have a Product Display node and it has the following contextual links: Edit, Delete and Manage Display.
The Edit link allows to edit the Product Display node.  I need to add another contextual link to allow me to edit the product referenced by the product display.
Please take a look a this image:
Comment: What happens if the product display contains more than one referenced node?
Comment: good question. But in my case it only references one product. Anyway which other options do I have to add this capability.
Answer: This is a year old question, but worth answering I think.
You can use this hook (hook_menu_contextual_links_alter). The sample does exactly what you want. (I mean altering node's contextual links)
Here's an actual code I did. And it works for multiple products too.
<code>    // Add a link to all contextual links for nodes of type product_display.
    if ($root_path == 'node/%' && $router_item['page_arguments'][0]->type == 'product_display') {

      // Loop through all products
      foreach ($router_item['page_arguments'][0]->field_product[LANGUAGE_NONE] as $element) {
        $product = commerce_product_load($element['product_id']);

        // Add your contextual link
        $links['edit_prod_'.$element['product_id']] = array(
          'title' => t('Edit @sku', array('@sku' => $product->sku)),
          'href' => 'admin/commerce/products/'.$element['product_id'].'/edit',
          'localized_options' => array(
            'query' => array(
            'destination' => current_path(),
          ),
        ),
      );
    }
  }
</code>
This will add contextual links like 'Edit HMWPB' or 'Edit POHPB'


Como fazer um sistema de movimentação utilizando touch no unity?

Question: Ao deslizar o dedo para cima tela executa o comando e ao deslizar o dedo para baixo executa o comando, um exemplo de comando seria um movimento para cima e uma movimento para baixo com o touch me retornar um tipo bool true ou false.
Answer: Você pode testar as posições:
        //Variáveis de controle
        bool up    = false;
        bool down  = false;
        bool left  = false;
        bool right = false;

        if (touch.y < Screen.height / 4) {
            Debug.Log ("Para Baixo"); //Aqui você seta a variável para TRUE
            transform.Rotate (Vector3.right, 2);
        }  else if (touch.x < Screen.width / 2 && touch.y > Screen.height / 4 && touch.y < (Screen.height - (Screen.height / 4))) {
            Debug.Log ("Para Esquerda"); //Aqui você seta a variável para TRUE
            transform.Rotate (Vector3.up, 2);
        }  else if (touch.y > Screen.height - (Screen.height / 4)) {
            Debug.Log ("Para cima"); //Aqui você seta a variável para TRUE
            transform.Rotate (Vector3.left, 2);
        }  else {
            Debug.Log ("Para Direita"); //Aqui você seta a variável para TRUE
            transform.Rotate (Vector3.down, 2);
        }

Ao mover para qualquer direção você tem a variável True, é possível ainda implementar para saber se esta movimentando para as diagonais, basta testar os 2 deslocamentos simultaneamente!
Editado conforme sua edição da pergunta
Script básico para facilitar o entendimento:
using UnityEngine;
using System.Collections;

public class MoveTouch : MonoBehaviour
{
    private float speed = 1.5f;

    //Controle de Zoon
    private Vector2 v2_current_Distance;
    private Vector2 v2_previous_Distance;
    private float f_comfort_zone;
    private float mScaleFactor = 1;
    private GameObject go;

    //Controle de Rotaçao
    private Vector2 firstPressPos;
    private Vector2 secondPressPos;
    private Vector2 currentSwipe;

    void Start ()
    {
        go = GameObject.Find ("target");
    }

    void Update ()
    {
        if (Input.touchCount == 2 && Input.GetTouch (0).phase == TouchPhase.Moved && Input.GetTouch (1).phase == TouchPhase.Moved) {
            v2_current_Distance = Input.GetTouch (0).position - Input.GetTouch (1).position;
            v2_previous_Distance = ((Input.GetTouch (0).position - Input.GetTouch (0).deltaPosition) - (Input.GetTouch (1).position - Input.GetTouch (1).deltaPosition));

            //Funçao Zoon
            float touchDelta = v2_current_Distance.magnitude - v2_previous_Distance.magnitude;

            if (touchDelta <= 1) {
                mScaleFactor = transform.localScale.x;
                mScaleFactor *= 0.9f;
                transform.localScale = new Vector3 (mScaleFactor, mScaleFactor, mScaleFactor);
            }

            if (touchDelta > 1) {
                mScaleFactor = transform.localScale.x;
                mScaleFactor *= 1.1f;
                transform.localScale = new Vector3 (mScaleFactor, mScaleFactor, mScaleFactor);
            }
        } else if (Input.touchCount == 1 && Input.GetTouch (0).phase == TouchPhase.Moved) {
            Vector2 touchDeltaPosition = Input.GetTouch (0).deltaPosition;
            go.transform.Translate (touchDeltaPosition.x * speed * Time.deltaTime, touchDeltaPosition.y * speed * Time.deltaTime, touchDeltaPosition.y * speed * Time.deltaTime);

        } else if (Input.touchCount == 1 && Input.GetTouch (0).phase == TouchPhase.Stationary) {
            Vector2 touch = Input.GetTouch (0).position;

            if (touch.y < Screen.height / 4) {
                Debug.Log ("Para Baixo");
                transform.Rotate (Vector3.right, 2);
            }  else if (touch.x < Screen.width / 2 && touch.y > Screen.height / 4 && touch.y < (Screen.height - (Screen.height / 4))) {
                Debug.Log ("Para Esquerda");
                transform.Rotate (Vector3.up, 2);
            }  else if (touch.y > Screen.height - (Screen.height / 4)) {
                Debug.Log ("Para cima");
                transform.Rotate (Vector3.left, 2);
            }  else {
                Debug.Log ("Para Direita");
                transform.Rotate (Vector3.down, 2);
            }
        }
    }
}

Anexando esse Script em qualquer GameObject você o controlara para todas as direções, detalhe, você precisa gerar o APK, pois, observe que não possui nenhum controle de mouse ou teclado!
Faça os teste, e é de fácil implementação da primeira parte da resposta que postei!
Comment: Não precisava abrir outra pergunta amigo, bastava editar esta!
Comment: eu testei, e não funcionou no caso teria que passar um parâmetro para reconhecer esse movimento na tela.
Comment: Na verdade amigo, esse teste é para exatamente o que você descreveu na pergunta, e não um controle de movimento. Serve de você já tem um sistema de movimento, que deu a entender na sua pergunta.
Comment: acho que me expressei mal, queria implementar o touch no unity pois eu não tenho um sistema de movimentação, se você achar melhor eu abro outra pergunta e deixo essa como teste de movimentação.
Comment: ok vou editar essa valeu
Answer: Se preferir usar como o input do direcional com suavidade, a intensidade você pode mudar de acordo com o tamanho da tela assim quando chegar ao y = -1 ou 1 atribuiria o valor para top e down e semelhante para x left e right,
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Usatouch : MonoBehaviour
    {
        private Vector2 StartPos ;
        private Vector2 TouchDir ;
        public int intensidade = 200;
        void Update()
        {
            touchupdate();
            horizontal = Mathf.Clamp(TouchDir.x/intensidade,-1,1);
            vertical = Mathf.Clamp(TouchDir.y/intensidade,-1,1);

        }
        void touchupdate()
        {
            if (Input.touchCount > 0)
            {
                Touch touch = Input.GetTouch(0);
                switch(touch.phase)
                {
                case TouchPhase.Began:
                    StartPos = touch.position;
                    break;
                case TouchPhase.Moved:
                    TouchDir = touch.position - StartPos;
                    break;
                case TouchPhase.Ended:
                    break;
                }
            }
        }

}


Exibir conteúdo somente após carregamento total da página

Question: Olá, eu tenho o seguinte trecho de código abaixo:
Código

div#container{
 position:absolute;
 width: 100%;
 height: 100%;
 top: 0px;
 left:0px;
 background-color: #eee;
 display: block;
}

div#loader{
 border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
 position: fixed;
 top: 0px;
 left:0px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
<!DOCTYPE html>

 <meta charset="utf-8">
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <title>PÁGINA LOAD</title>
 <link rel="stylesheet" href="css/style.css" media="screen"/>

Exibir meu código PHP aqui após o carregamento total da página

Objetivo
Eu gostaria que o meu conteúdo PHP fosse exibido na tela somente após carregar 100% pois esse trecho PHP é um select no banco de dados que demora um bom tempo para exibir dando aspecto que a página não está respondendo.
Problema
O loader sempre é exibido junto ao conteúdo PHP, sendo assim ele só é exibido após a requisição finalizar. Tentei diversas formas antes de postar no fórum, se alguém puder mostrar um método que funcione será de grande ajuda!
Comment: O loader deve desaparecer somente quando o código PHP estiver inserido no HTML?
Comment: Creio que vc deverá usar Ajax para carregar apenas o conteúdo da div #content.
Comment: Exatamente @VictorCarnaval
Comment: Como posso fazer isto @Sam? Poderia me dar um exemplo por favor!
Answer: Use Ajax para carregar o conteúdo da div #content. Por ser assíncrono, o loader ficará visível até que o conteúdo seja carregado na div.
Faça o seguinte:
Esconda a div #content no seu CSS:
#content{
   display: none;
}

Crie um arquivo .php que irá retornar o HTML que será inserido na div. Esse arquivo .php será requisitado pelo Ajax. O mesmo código PHP que você colocou na div #content será o que você irá colocar no arquivo .php.
Então você chama o Ajax quando a página for carregada:

Após o Ajax retornar os dados para a div, o loader será ocultado no callback do Ajax.
A pagina.php é de onde virão os dados. Aí você coloca o nome que quiser (ex., content.php etc...). Nessa página é onde será processado o código PHP que será retornado.

Talvez nem seja preciso ocultar a div #content, já que ela estará
  vazia inicialmente. Se não quiser esconder, pode dispensar o CSS que coloquei acima
  e apagar a linha $("#content").show();.
Comment: Excelente resposta @Sam, indica algum material para leitura sobre AJAX?
Comment: Tem vários no Google. Pesquise por "javascript ajax" que os primeiros resultados da busca terão bons materiais para ler.
Comment: beleza, obrigado pela força!


adding a jQuery event in the initialize but getting an error

Question: I'm migrating some things to backbone and have a question about this error
Uncaught TypeError: Object loadPrevious has no method 'apply'

for this code:
el: $('#mig-container'),
events: {'click .next-btn' : 'loadNext' },
 template:_.template($('#mig-image-tmp').text()),
initialize: function() {
     $('#mig-container').on('click','.prev-btn',this.loadPrevious());
},....
loadPrevious: function(){
  console.log('i want to load Previous');
}

How would I make this on click event handler work properly?
thx
Answer: it should be
$('#mig-container').on('click','.prev-btn',this.loadPrevious);

you should not invoke the event handler in event registration by appending () to the end of loadPrevious, you need to pass the function reference to .on()


Adjust for covariates in small sample size (IPTW, PS match, etc.)

Question: I have a dataset of patients with a grouping variable (groups A (control) and group B (treatment)). The two groups have sample sizes of 170 vs. 30. I would like to compare outcomes between the two treatment groups but they differ in baseline covariates. I tried propensity score matching and inverse probability treatment weights (IPTW) but both don't seem to achieve good covariate balance between the groups (as of SMD <0.1).
My guess is the sample size of the treatment group is too small. Does anybody have a recommendation how I can adjust for baseline covariates in such a small sample size?
Comment: Can you please expain (as an edit) the abbrevs IPTW, PS, etc?
Comment: Did you do the most basic versions of propensity score matching and IPTW, or did you do advanced versions that target balance like overlap weighting, cardinality matching, genetic matching, and entropy balancing? Is there a reason you don't want to adjust for covariates using regression?
Comment: Yes, I did the most basic versions of PS match and IPTW. And there is no big reason why not to do regression.
Answer: Differences in baseline covariates are not intrinsically a bad thing. Given the small sample size, and the possible number of "covariates" compared, it's almost a certainty one or more will show "imbalance" - but that's just an artifact of an uncontrolled familywise error rate - and hey, what's the primary endpoint anyway?
It's most useful to think of the randomization assumption not as balancing a possibly infinite list of covariates, but balancing their "average effect" on each group; exactly the rationale for propensity matching. Stephen Senn has written extensively on this issue as one of the major "myths" of clinical trials - and we must infer by the convention of "treated" and "control" that this is a randomized study. https://onlinelibrary.wiley.com/doi/abs/10.1002/sim.5713
Dr. Senn goes on the explain that imbalance is much different from confounding, since even if the variable is associated with the outcome, it is theoretically unrelated to randomization, unless there is some kind of conditional analysis such as in the "per protocol" population. In spite of all this, adjustment prevails as the superior way to handle imbalance because, given the variable conditioned upon is prognostic - i.e. it actually predicts the outcome - the tendency is to increase power. Variables that are not strongly predictive of the response tend to attenuate the power of the test when adjusted willy nilly.
But all of this goes in the bin if it's not actually a prespecified analysis. This is because you can't choose the analysis that you finally do based upon what you see in the data. Do the analysis you planned, it's probably the right one.
Answer: Look to see if any of these imbalanced covariates is associated with the outcome variable through regression on the available data or via a literature review.  If there is little evidence to suggest they are associated, then you would feel that much more confident there is no harm in having the imbalance.  You may end up choosing to balance only one or two of the covariates that indeed show evidence of an association with the endpoint.  Ultimately you sill still need the "no unmeasured confounders" preface if you are going to make causal inference.  See this thread.
You could perform several sensitivity analyses to see the effect of balancing each covariate separately and in combination, sample size permitting.
Also look at this thread regarding imbalance in patient characteristics due to post-baseline events.
Comment: It is not a good idea to do variable selection and effect estimation in the same dataset, and OP clearly doesn't have enough data to properly split their sample, so they really should just rely on theory to determine confounders to adjust for. This still does not get at their question of *how* to adjust for the confounders.
Comment: So you are saying that I should not check on my dataset, if covariates are relatd to my endpoint (survival) and instead rely on what the literature says?


Violin vibrato without shoulder rest

Question: I've been playing violin exclusively with a shoulder rest for several years of playing thus far, but I recently found out some benefits of playing without one (better sound, more mobility, convenience) and I've since wanted to learn how to do it.
As of right now, I can comfortably play in and across positions 1 and 5 with a little difficulty in adjusting my hand in upper positions without a shoulder rest, but the difficulty is manageable.
Doing vibrato, however, is the one thing I'm having trouble with. I first learned vibrato the traditional "loose wrist" way: with all but the thumb and vibrating finger moving entirely without contact to the violin. This obviously works well in conjunction with a shoulder rest, wherein no upward force from the left hand is required. The way I hold the violin without a shoulder rest, though, involves actually partially lifting it up using the bottom-most index finger and thumb joints. As such, holding the violin in this way doesn't allow for the regular wrist vibrato I'm used to.
How might one vibrate using this type of left hand grip?
Answer: Wrist vibrato without a shoulder rest can be accomplished by

twisting the left elbow to the right, thereby flattening the thumb somewhat
simply resting the violin neck on the horizontal thumb

This not only releases the index finger from holding the violin in place (thus allowing for freely moving vibrato), but also allows for what I find to be a left shoulder far less susceptible to cramps or soreness.
It is important to note that the neck of the violin should generally rest above the thumb's bottom knuckle; otherwise, wrist vibrato yields a very peculiar motion.
This horizontal thumb position also has other useful applications: without the need to jump between positions, holding the violin on the lower thumb makes it much easier to shift.
Answer: If wrist vibrato isn't working, then how about trying finger vibrato?  In the long run, this might work better.  It would probably be more subtle than wrist vibrato, but that's not necessarily a bad thing.

Violin vibrato without shoulder rest


How can I make a node like template for a vocabulary?

Question: I have a taxonomy where I want to theme the term pages.
I only want to theme the terms pages in this taxonomy.
No matter what I do I can't see to get it to show a template file that I can then further customise.
I have a node page at /name
then I have the terms of the taxonomy using the path pattern /name/term_name
Can anyone help me figure this out, it seems strangely difficult. To the point where I am begining to wonder if some module might be derailing me.
From what I understand I should be about to make a template named something "taxonomy-term--myTaxonomy_name.tpl.php" but I can't seem to dislodge the default term view. Even with many cache clearings.
Comment: Should be able to do it in Views template rewrite or custom them suggestion. Have you tried them?
Answer: Enable the Taxonomy term Views if you haven't already, and look into theme suggestions there.
It seems you have views-view--taxonomy-term--page.tpl.php available where you can add some logic that would apply to only a certain Vocabulary.
You can also Clone the Taxonomy term Views twice, Filter to only certain Vocabulary in one Views, and to all the rest in the other Views, then use the template in the first Views for special styles.
You can use the Taxonomy Views Integrator module to assign different Views to output different term pages.
Answer: The templat naming should be taxonomy-term--vocabulary-machine-name.tpl.php, as /admin/structure/taxonomy/[vocabulary-machine-name]
Also, you could use a preprocess function in your template.php file to be sure:
/**
 * Implements hook_preprocess_taxonomy_term()
 *
 * @param $vars
 */
function YOUTHEME_preprocess_taxonomy_term(&$vars) {
  $vars['theme_hook_suggestions'][] = 'taxonomy_term__' . $vars['view_mode'];
  $vars['theme_hook_suggestions'][] = 'taxonomy_term__' . $vars['vocabulary_machine_name'] . '__' . $vars['view_mode'];
}

And then name your templates:

taxonomy-term--vocabularyname.tpl.php,
taxonomy-term--vocabularyname-full.tpl.php,
taxonomy-term--vocabularyname-teaser.tpl.php,
etc.


derivative of normalized associated Legendre function at the limits of x = +/-1

Question: I'm trying to compute the derivative of the normalized associated Legendre function of $x=\cos \theta$ and I'm having issues when $\cos \theta =\pm 1$ which causes the denominator to go to $0$.  I've seen an answer on the forum about the derivative of the associated Legendre polynomial at the boundary of $x=\pm 1$ but I'm looking for the derivative of the normalized associated Legendre function.  The answer is $0$ for all $m$ except for $m=1$ so I was hoping to find a closed form expression in a textbook showing the expression for the special case but I have not found much about the derivative of the normalized associated Legendre function.  Thanks.
Answer: I was able to get this worked out.  Below is the answer for anyone else that needs it.
Expression for theta = 0
Expression for theta = pi


Can't remote access to mysql in Ubutnu

Question: I have two virtual machine in VirtualBox with clean installation Ubuntu server.
I need to mysql connect from one to another VM. I allow access from my second VM with ip 192.168.1.80. In first VM in mysql config I write down:
bind-address = 192.168.1.80

Also tried 0.0.0.0, 192.168.1.118 (ip first VM), comment out line.
I connect from second VM via user = root, therefore I changed host to % in user table in first VM. Then I allowed connect in ufw by different ways:

First VM successfully pings from second. When I try to connect:
mysql -h 192.168.1.118 -u root -p

I see:
ERROR 2003 (HY000): Can't connect to MySQL server on '192.168.1.118' (111)

I open ports, allow connect in mysql config. What else should I do?
Comment: You need to start the MySQL server first.
Comment: Set `bind-address = 0.0.0.0`. If you have `mysql` on both VMs set it on both. Restart `mysql`s. Try to connect. `bind-address` is an IP mysql used to listen on, not the allowed client's IP.
Comment: After restarting mysql, run `netstat -patn | grep mysq` to see on which interface mysql is listening on.
Comment: @Kondybas I set in both VM bind-address = 0.0.0.0 nothing changes.
Comment: @ThoriumBR It show: tcp   0   0   127.0.0.1:3306   0.0.0.0:*   LISTEN   1607/mysqld
Comment: @Michael Hampton Mysql is running.
Answer: I had this same issue this morning - but I'm new to VM Servers + DBs so I didn't try the bind-address = 0.0.0.0, I added a new user within mysql with
CREATE USER 'name'@'address' IDENTIFIED BY 'password';

where the address was the IP address of the the client and it worked.
Comment: Answer is correct. You also have to have users configured to specify where they are coming from. Whether that is local host, or 192.168.x.x or % for anywhere

Can't remote access to mysql in Ubutnu


Otherwise com redirectTo para outra url que não faça parte do Single page application

Question: Por exemplo, nas rotas abaixo:
app.config(function($routeProvider){
    $routeProvider.when('/dashboard', {
        templateUrl: "../views/dashboard.html",
        controller : "dashboardCtrl"
    }).when('/cadastro', {
        templateUrl: "../views/signin.html",
        controller : "signInCtrl"
    }).otherwise({
        redirectTo : '/login'
    });
})

Eu uso o otherwise para /login, o que tem como consequência a rota:
http://www.myapp.com/rotaAtual/#/login

Já que é a rota padrão da sigle page application, mas caso eu queira mudar para uma rota como:
http://www.myapp.com/login

é possível?
Obrigado.
Answer: Olá,
Você terá que criar um controller, quer por javascript faça redirect para a url externa, algo assim:
.otherwise({
    controller : function(){
       window.location.replace('http://www.myapp.com/login');
    },
    template : "

"
});

Comment: Obrigado, funcionou bem como eu queria. Mas, uma coisa, ele só funciona com a declaração do template?
Comment: Cara, faço a mesma pergunta acima, por que você utilizou o ``template``?  O que ele significa nessa situação? Links?


Why DividerItemDecoration get a null object reference in recyclerView fragment?

Question: So i try to show my data from local database in recyclerView in HomeFragment, but when I start my app this getting error like this : Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.addItemDecoration(androidx.recyclerview.widget.RecyclerView$ItemDecoration)' on a null object reference
at org.d3ifcool.tasksreminder.ui.home.HomeFragment.onCreateView(HomeFragment.kt:50)
this is my AddTaskAdapter
AddTaskViewModel
HomeFragment
Comment: Check this answer https://stackoverflow.com/questions/57886100/how-to-add-item-divider-for-recyclerview-in-kotlin
Answer: Your recyclerView object is null. Since you have implemented binding you should use your binding object. Also, move your code to onViewCreated(View, Bundle?) as you will want your view to have been created when you reference a view object
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    ...
    binding.recyclerView.addItemDecoration(...)
}


find the limit in distributions(space of generalized functions)

Question: How to find limit in $ \mathcal{D}^{'}$
$$
\exp(itx)(x+i0)^{-1}, t \rightarrow \infty
$$
I try to use Sokhotsky's formula $(x+i0)^{-1} = -i\pi\delta(x) + \rho\frac{1}{x} $  , but did not come to a meaningful answer.
Comment: That thing you're calling Sokhotsky's formula is absurd. What's correct is that $\lim_{\epsilon\to0^+}(x+i\epsilon)^{-1}$ equals the RHS.
Comment: @DavidC.Ullrich. I can accept $(x+i0^+)^{-1}$ as a shorthand, but just $0$ is not very meaningful since the limit depends on whether we go from the positive or negative side of $0.$
Comment: Recall that the FT of distributions is continuous and show that $\lim_{t \to \infty} \mathcal F[x \mapsto e^{i t x} (x + i0)^{-1}](w) = 0$.
Comment: @DavidC.Ullrich $f(x + i0)$ and $f(x - i0)$ are notations for the limits from above/below in the complex plane (distributional limits in this case), similar to $f(x + 0)$ and $f(x - 0)$.
Answer: By Sokhotsky's formula, what we want to calculate is
$$
e^{itx} \left( -i\pi\delta(x) + \operatorname{pv}\frac{1}{x} \right)
= -i\pi \left( e^{itx} \delta(x) + e^{itx} \operatorname{pv}\frac{1}{x} \right)
.
$$
The first term is easy, using $f\delta=f(0)\delta$:
$$
e^{itx} \delta(x) = e^{it0} \delta(x) = \delta(x)
.
$$
For the second term we first use a couple of definitions:
$$
\langle e^{itx} \operatorname{pv}\frac{1}{x}, \phi(x) \rangle
= \langle \operatorname{pv}\frac{1}{x}, e^{itx} \phi(x) \rangle
= \lim_{\epsilon\to 0} \int_{|x|>\epsilon} \frac{1}{x} e^{itx} \phi(x) \, dx
.
$$
Then we note that because of symmetry only the odd part of $e^{itx}\phi(x)$ matters. The odd part equals
$$
\cos tx\ \phi_{\text{odd}}(x) + i \sin tx\ \phi_{\text{even}}(x)
.
$$
For the first of these terms we use the fact that there exists $\psi\in C_c^\infty(\mathbb R)$ such that $\phi_{\text{odd}}(x) = x\psi(x).$ This gives
$$
\lim_{\epsilon\to 0} \int_{|x|>\epsilon} \frac{1}{x} \cos tx\ \phi_{\text{odd}}(x) \, dx
= \lim_{\epsilon\to 0} \int_{|x|>\epsilon} \frac{1}{x} \cos tx\ x\psi(x) \, dx
= \lim_{\epsilon\to 0} \int_{|x|>\epsilon} \cos tx\ \psi(x) \, dx
\\= \int \cos tx\ \psi(x) \, dx
\to 0 \text{ as }t\to\infty.
$$
For the second term we have
$$
\lim_{\epsilon\to 0} \int_{|x|>\epsilon} \frac{1}{x} \sin tx\ \phi_{\text{even}}(x) \, dx
= \lim_{\epsilon\to 0} \int_{|x|>\epsilon} \frac{\sin tx}{x} \ \phi_{\text{even}}(x) \, dx
= \int_{|x|>\epsilon} \frac{\sin tx}{x} \ \phi_{\text{even}}(x) \, dx
\\
\to \pi\phi_{\text{even}}(0) \text{ as } t\to\infty.
$$
But $\phi_{\text{even}}(0) = \phi(0)$ so this just becomes $\pi\phi(0).$
I leave it to you to summarize the result.


Laravel sanctum 401 Unauthorized

Question: I'm trying to set-up Laravel authentication using sanctum. I'm able to create a successful login function, which returns a token (bearer), but once that bearer is added to a next request using postman, a 401 unauthorized is received, and I cannot figure out why. I'm running the setup using XAMPP (127.0.0.1:8000).
Config/auth contains the following guards
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users'
    ]
],

The config/sanctum guard is set to api.
I've added (and tested with) the following variables in the .env file;
SESSION_DOMAIN='localhost'
SANCTUM_STATEFUL_DOMAINS='localhost:8000'

Lastly, routes are set as follows;
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('friends', FriendsController::class);
});

I'm now unsure what the issue could possibly be.
Comment: you need to add bearer token to access the routes protected by scantum middle ware ....
request from frontend should be like this reffer this answer https://stackoverflow.com/a/72231664/15177375
Comment: Yes, I'm aware and already do so. So unfortunatly that's not the issue.
Answer: if you are using axios make sure to set it to send the cookies
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;

also make sure to see the config/cors.php
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

finally add the domains to your .env file , SPA location in app url , backend in sanctum stateful domains
APP_URL=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8000

and most importantly don't forget to run this to load the new .env
php artisan config:cache

Laravel sanctum 401 Unauthorized


How to set value programmatically for mobile number module's field using entity wrappers?

Question: how do I set value for the mobile_number field using entity wrappers?
Currently, this field is attached to an entity and I'm trying as below.
$entity_type = 'mp_customer';
$entity = entity_create($entity_type, array('type' => 'mp_customer'));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->field_phone = "0777123456";
This gives an PDO Exception .... field_phone_value cannot be null....
Adding more
This field needs more data to store in field_data_field_phone,
those are:
{field_phone_value}
{field_phone_country}
{field_phone_local_number}
{field_phone_verified}
{field_phone_tfa}
This field was created using this module : https://www.drupal.org/project/mobile_number
Comment: Hi @Mahinda, Please do not leave your question with no answer accepted if you want others keep helping you. Alternatively, you can provide and accept your own solution. Whatever you do, just do not abandon your questions as next time less people want to react when you ask help.
Comment: Hi there,
Inserting values as an array didn't work. It throws an error as invalid data.
So, I'm still looking for a solution save values using entity wrappers. Because using entity_save() is not actual solution.
Answer: To store a value with entity wrapper set() should be used. Please read https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
So your code $wrapper->field_phone = "0777123456"; would be $wrapper->field_phone->set('0777123456'); if the field structure required just a simple string.
However, according to the error message, it is not a string as it requires additional values for {field_phone_value} {field_phone_country} {field_phone_local_number} {field_phone_verified} {field_phone_tfa}.
So to make sure I would first figure out its structure. You could do so, for example, saving any value via UI and then outputting the value of respecting variable using dpm(). However, most probably its an array and you could give a try to:
$phone = array(
  'field_phone_value' => '0777123456',
  'field_phone_country' => 'US',
  'field_phone_local_number' => 'some value',
  'field_phone_verified' => 'some value',
  'field_phone_tfa' => 'some value'
);
$wrapper->field_phone->set($phone);

Comment: It's not working,
PDO Exception error throw with
INSET INTO {field_data_field_phone}
{entity_type}{entity_id}{revision_id}{bundle}{delta}{field_phone_value}{field_phone_country}{field_phone_local_number}{field_phone_verified}{field_phone_tfa}
VALUES();

field_phone_value
field_phone_country
field_phone_local_number
field_phone_verified
field_phone_tfa

saying these values are NULL
Comment: Check the edited answer.
Comment: Finally, I figured out save this using entity_save()...
But entity wrappers are not working..invalid data format.
Comment: Because as I tried explain above, your are feeding just a string instead of array. Read the edited answer.


How to prove that every left-invariant differential form on a Lie group is smooth

Question: Let $G$ be a Lie group. Recall that a differential $k$-form $\omega
\in \Omega^k(G)$ is called left-invariant if its pullback by left multiplication maps is itself:
$$L_g^*\omega=\omega$$
for all $g\in G$. Such forms are determined by its value at the identity $e\in G$, because for any $g\in G$, we have that
\begin{equation}\omega_g=(L_{g^{-1}}^*\omega)_g.\end{equation}
I believe that such differential forms are always smooth. I tried searching for this result from Google but could not get satisfactory answers. So I thought maybe the proof was too easy and tried proving it. My idea is to use take any smooth vector fields $X_1,\ldots, X_k$ and show that $\omega(X_1,\ldots, X_k): G\to \mathbb{R}$ is a smooth function. Now by definition, the function $\omega(X_1,\ldots,X_k)$ is defined by
$$\omega(X_1,\ldots,X_k)(g)=\omega_g(X_1|_g,\ldots,X_k|_g),$$
using the above expression for $\omega_g$ we get that
$$\omega(X_1,\ldots,X_k)(g)=\omega_e(dL_{g^{-1}}(X_1|_g), \ldots, dL_{g^{-1}}(X_k|_g)).$$
This shows that $\omega(X_1,\ldots,X_k)$ is equal to the composition:
$$\require{AMScd}
\begin{CD}G @>dL_{g^{-1}}(X_1|_g)\times \cdots \times dL_{g^{-1}}(X_1|_g)>> T_eG\times\cdots\times T_eG @>\omega_e>> \mathbb{R}. \end{CD}
$$
Since $\omega_e$ is multilinear, so it is smooth. Therefore showing that $\omega$ is smooth boils down to showing that the map $G\to T_eG: g\mapsto dL_{g^{-1}}(X_i|_g) (i=1,\ldots, k)$ is smooth. This is where I get stuck. I don't have any idea how to show that this map is smooth.
Answer: Your line of argument is correct, although there are simpler ways to see this. To complete your argument, you can use the (standard) result that the so-called left trivialization, which sends a tangent vector $\xi$ at $g\in G$ to $(g,T_gL_{g^{-1}}(\xi))$ defines a diffeomorphism $\Phi:TG\to G\times T_eG$. A vector field then is a smooth map $X_i:G\to TG$, so $\Phi\circ X_i$ is smooth and its second component is the $i$th component of the map $G\to T_eG\times\dots\times T_eG$ that you consider.
The simpler way to get the result is to observe that smoothness of $\omega$ follows if for each $g\in G$ you find a local frame for $TG$ defined on an open neighborhood of $g$ such that inserting any frame elements into $\omega$ one gets a smooth function on the domain of definition of the frame. Now you can take a global frame formed by the left invariant vector fields corresponding to a basis of $T_eG$. Inserting frame elements into $\omega$ you always get functions that are constant and hence smooth.
Comment: What does the notation $T_g((L_{g^{-1}})(\xi)$ means. I have never seen this type of notationd.
Comment: @Uncool $T_gL_{g^{-1}}$ is the differential of $L_{g^{-1}}$ at $g$. Using your notation, $T_gL_{g^{-1}}(\xi)$ would be $dL_{g^{-1}}(\xi)$.
Comment: Oh.. yes this silly me, I forgot to use the left-invariant frame. The use of a left-invariant frame is indeed much easier.


Testing 400 status code axios throws error

Question: I'm creating an api test framework for a project I am working on and I'm looking to validate required fields in JSON objects being sent to an endpoint.
I'm trying to send a JSON object with a missing field and expecting a 400 response from my application with a validation message. But when making this call with axios it (somewhat rightly) throws an error as it received the 400.
I want to be able to assert that 400 is expected and to assert on the validation message.
All the examples I've come across are all regarding dealing with the 400 response in the correct way you would if you are not expecting the 400 response, but i am expecting it.
I couldn't seem to find anyone else trying this.
async function createReminder(reminderObject) {
  const response = await axios.post(`${config.get('baseUrl')}/reminder`, {
    ...reminderObject
  });

  return response;
}

module.exports.createReminder = createReminder;

Here is my working code as it stands. This will make a valid 200 when being used with a valid call.
I need to have the 400 response / validation message be returned in teh response object to be handled in the function that calls this function.
Answer: In effect, you want to intercept the response and transform it as you wish. There's a section in the axios docs dedicated to interceptors. As an example of what you can do with it, here is what I've used in a recent project with a Laravel back-end:
axios.interceptors.response.use(
  res => Promise.resolve(res.data),
  error => {
    let message = null;
    if (error.response) {
      // if error has a data.error property, it's an error formatted by server
      if (error.response.data.error) message = error.response.data.error;
      else if (error.response.status === 500) message = 'Oops! Something went wrong.';
    } else {
      // if error has a code property, it's an error defined by axios
      if (error.code === 'ECONNABORTED') message = 'Timeout exceeded';
      else message = 'Oops! Something went wrong.';
    }
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject({ error: message });
  }
);

The code above allows me to make axios calls as follows, and always expect the same format:
axios.post('/url', { data: { ... }})
  .then(({ jsonProp1 }) => console.log(jsonProp1))
  .catch(({ error }) => console.log(error);

Note: if you do create a new axios instance, you need to reinject the response interceptor for this instance too.
Comment: Thank you. I did see that in the docs but don't really understand how to implement it.

Where do I place the code for the interceptor?
Comment: @Kpizzle right after importing axios so you can be sure that all subsequent AJAX calls will use it. E.g. I usually create an api.js file and put this code there
Comment: So adding after the require statement means the interceptors will be called before any API calls are made.

But how do I then call that code if I have it in another file as you suggest, which looks like the correct way to go?
Comment: You dont need to call it explicitly. You just import axios anywhere you want (it exports a default instance, and you've registered an interceptor on it, so it will automatically be executed for every request response). If you're not familiar, search for the term middleware, axios interceptors work just similar to Express js or really any kind of **middleware**
Comment: Ahh, that make a lot of sense, yes, I understand middleware. Thank you very much. Let me go an attempt to add this now.


change a file at a time located in different location

Question: Iam very new to linux.
suppose i have two file with same name fstab one file is located in /etc and the other is located in /root/
If i make a change in /etc/fstab file the changes has to reflect in /root/fstab .
Is there any command to do this?
Kindly help me...
Mythili
Answer: Given your comment to @ewwhite, a symbolic link won't solve your problem.  The symbolic link will be replicated, but not the file contents.  You have several options.  The simple one:

Periodically copy /etc/fstab to /root/fstab using a cron job.

More work but exactly what you want:

Use something like incron to arrange for a script to run whenever /etc/fstab changes.  This can then copy the file to wherever the file needs to go.
Comment: But based on the comment to @ewwhite, cron is probably also not a good option.  There are procedures and tools specifically for doing this in a DRBD environment, including /etc/fstab and other files/directories.  See my response for more details.
Answer: You could use a symbolic link to the original file in /etc/fstab.
ln -s /etc/fstab /root/fstab

That creates a link at /root/fstab that points to the file at /etc/fstab.
May I ask why you need to see that file in multiple locations? Why not just use /etc/fstab?
Comment: Iam using HA drbd for replication.My replicated device is in one partion(sda3) and /etc is in one partion.After failover only the file in sda3 are replicating.In my case files are replicating but the fstab file of (/etc/) also has to change at a time.
Comment: Yes, the DRBD scenario changes this a bit... I'd go with one of the purpose-built utilities or some thing like a scheduled synchronization.
Answer: For /etc/fstab on Linux-HA, you typically would not change /etc/fstab as part of the resource start.  Normally what you would do is list all the mount-points you may have, but ones that are not always mounted list with "noauto".  For example:
/dev/drbd0           /shared              ext3       defaults,noauto,noatime 0 0
/dev/drbd1           /var/lib/pgsql       ext3 defaults,noauto,noatime 0 0

At boot time those file-systems will not be mounted.  Then, to bring those file-systems up you would list a resource like:
Filesystem::/dev/drbd0::/shared::ext3 \
Filesystem::/dev/drbd1::/var/lib/pgsql/::ext3 \

Additionally, you may wish to look at drbdlinks (probably available in your distro) which manages links to DRBD file-systems.  However, I don't think you want to make /etc/fstab a drbdlink...


Minimization of two variables

Question:
(General) How can I find $$\min\limits_{\phi\leq x\leq \alpha , \ \beta \leq y \leq \delta}\{a+bx,c+dy\}$$ given values of $a,b,c,d,\phi, \alpha, \beta, \delta \in \mathbb{R}?$
(Specific) How can I find $$\min\limits_{0 \leq x , \ y \ \leq 1}\{.4664048+(2147.0588450)x,0.0313096+(91.2500009)y\}?$$

Thanks.
Answer: Each of the two terms is linear, so will be minimized at an endpoint, so there are at most four items to check.
For the specific question, since $b,d$ are each positive, they will be minimized when $x=y=0$, so the minimum is $$\min\{.4664048,0.0313096\}=0.0313096$$

Minimization of two variables


Optimizing travel time

Question: A woman is on a boat 4 miles north of shore.  There is a restaurant 6 miles east of her current position.  Her boat can move at 3 miles per hour, and she can walk at 2 miles per hour.  Find the distance from the restaurant that she will land on shore so that her time is minimized.
My attempt: (Incorrect, the answer is $\frac{8}{\sqrt{5}}$ miles)
I drew a right angle triangle with horizontal component $x$ and vertical component $4$.
The distance she then has to travel from shore to the restaurant is $6 - x$
The distance she travels from the water to the shore is then (right angle triangle) $\sqrt{4^2 + x^2}$
So, I figured the time she has to travel is given by $t(x)=\frac{\sqrt{4^2 + x^2}}{3} + \frac{6-x}{2} \implies t'(x)= \frac{2x-3 \sqrt{x^2+16}}{6 \sqrt(x^2+16)}$
There are no real solutions for  $t'(x)=0$ or $t'(x)$ D.N.E.  I am unable to solve this problem and have been stuck on it for several hours.
EDIT: I also checked both endpoints, with $x=0$ or $x=6$ and I still don't get the right answer of $x=\frac{8}{\sqrt{5}}$
Comment: There's no minimum because the boat is both *faster* and *can go straight* (no trade-off needed, it's just better). So just take the entire path by boat, therefore $x=6$.
Comment: There is likely a typo in the question. Intuitively, the shortest path between two points is a straight line. Given that she travels faster by boat then by foot, there is no incentive for her to walk at all, yielding $x = 6$.
Answer: You are doing fine.  Your range of $x$ is restricted to $[0,6]$ as if she lands farther than the restaurant the walking time becomes $\dfrac {x-6}3$  The fact that there is no zero of the derivative says the minimum comes at one end of the interval, here at $x=6$ as shown by this Alpha plot.  She should travel on the water directly to the restaurant, so the distance is zero. I don't get $\dfrac{8}{\sqrt 5}$ even if I reverse the speeds.

Optimizing travel time


equivalency of weak and strong convergence

Question: Why are weak convergence and strong convergence equivalent in finite dimensional spaces?  Please tell me, Where can I find a proof for this?
Thanks.
Answer: Take a basis $\{v_1,...,v_k \} $ of $V$, and define projection $\pi_i \in V^* $ as $$ \pi_i(\sum_j c_j v_j) = c_i $$ Then $\{\pi_1,...,\pi_k \} $ is also a
 basis of $V^*$ . Now introduce the $l^1$ norm as $ \|v\| = \sum_i |\pi_i(v)| $ for all $ v \in V $. Now if $v^n \rightharpoonup v  \in V $ then $ \pi_i(v^n) \rightarrow \pi_i(v) $ for all $i$, hence $ \|v^n -v\| \rightarrow 0 $. But in finite dimensional space, all norms are equivalent, hence the convergence is strong.
Answer: I think most functional analysis or topology textbooks will answer your question. But in any case, the key for a finite dimensional space $E$ is that every point $x \in E$ can be written as $x = \sum_{i=1}^k x_i e_i$, where $e_1, e_2, \ldots, e_k$ form a basis in $E$ such that $||e_i|| = 1$ for all $i$. This allows you to choose a particular radius for neighborhoods in the weak topology based on neighborhoods in the strong topology.
We only need to check that an open set in the strong topology is open in the weak topology. Consider a neighborhood of $y$ with radius $r$, denoted by $B(y, r)$. The map $f_i(x) = x_i$ is continuous and linear. Hence
$$
||x - x_0|| \leq \sum_{i=1}^k |\langle f_i, x - y \rangle |.
$$
Let $V$ be the neighborhood
$$
V = \{ x \in E : | \langle f_i, x - y \rangle | < \frac{r}{k}, i = 1, \ldots, k \}.
$$
Then clearly $||x - y|| < r$ for every $x \in V$, hence $V \subset B(y, r)$. We see here that $E$ being finite dimensional allowed us to choose $\frac{r}{k}$ as our radius in our neighborhood $V$ so that $V \subset B(y, r)$.


WPF: Condition Binding versus Property, XamlParseException using either

Question: I'm having trouble with a Condition for a MultiTrigger.  If I do the following:
<Condition Binding="{Binding RelativeSource={RelativeSource
    AncestorType={x:Type ListView}}}" Property="IsEnabled" Value="True"/>

Then I get this exception:

Condition cannot use both Property and Binding.  Error at object 'System.Windows.Condition' in markup file

However, when I do the following:
<Condition Binding="{Binding RelativeSource={RelativeSource
    AncestorType={x:Type ListView}}, Path=IsEnabled}" Value="True"/>

Then I get this exception:

Must specify both Property and Value for Trigger.  Error at object 'System.Windows.Condition' in markup file

What gives?  If it matters, here's the entire trigger:
<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Binding="{Binding Path=IsSelected}" Value="True"/>
        <Condition Binding="{Binding Path=ItemsControl.AlternationIndex}"
                   Value="0"/>
        <Condition Binding="{Binding RelativeSource={RelativeSource
            AncestorType={x:Type ListView}}, Path=IsEnabled}"
                   Value="True"/>
    </MultiTrigger.Conditions>
    <Setter Property="Background"
            Value="{StaticResource evenSelected}" />
    <Setter Property="BorderBrush"
            Value="{StaticResource evenSelectedBorder}" />
</MultiTrigger>

Answer: The API in this case is confusing.  Condition is used for two different types of multi-triggers, and the properties used are different. When using MultiTrigger, you will use the Property and Value properties. When using MultiDataTrigger (which is what you need), you specify a Binding and a Value.  So, if you just switch your code to use a MultiDataTrigger, you'll be good to go:
<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Path=IsSelected}" Value="True"/>
        <Condition Binding="{Binding Path=ItemsControl.AlternationIndex}"
                   Value="0"/>
        <Condition Binding="{Binding RelativeSource={RelativeSource
            AncestorType={x:Type ListView}}, Path=IsEnabled}"
                   Value="True"/>
    </MultiDataTrigger.Conditions>
    <Setter Property="Background"
            Value="{StaticResource evenSelected}" />
    <Setter Property="BorderBrush"
            Value="{StaticResource evenSelectedBorder}" />
</MultiDataTrigger>

Comment: Great, thanks!  I no longer get the `XamlParseException`, though I must not have the last `Condition` right yet, because my setters don't work anymore on enabled `ListView` items.


Problema com acentuação - R

Question: Tento resolver o problema dos acentos com esse script:
Mapa@data$NAME_2 <- Mapa@data$NAME_2 %>%
      as.character() %>%
      stri_trans_general("Latin-ASCII") %>%
      toupper()

Mas, quando abro a coluna NAME_2, o nome dos municípios fica, por exemplo:
MACEIA³ ao invés de MACEIÓ ou MACEIO.
Mapa@data$NAME_2 é uma coluna com o nome dos municípios do Brasil.
Comment: Qual comando está utilizando para ler os dados? Você precisa setar o encoding para "utf-8".
Answer:
# Instalar o pacote abjutils, se ainda não tiver instalado:
# install.packages("abjutils")

library(abjutils)
x <- c("maceió", "acentuação")
rm_accent(x)
#> [1] "maceio"     "acentuacao"

Created on 2018-06-27 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0).

Ou, neste tópico tem outras respostas: Remover acentos
Answer: Teste isso:
#Ajustando codificação de caracters do dataset
df = apply(Mapa@data, 2, as.character)
Encoding(df) = "UTF-8"
Mapa@data = as.data.frame(df)

Comment: Eu já havia tentado isso, infelizmente não funcionou. :(
Comment: Verifique o banco de dados, pode ser que o erro não esteja na leitura pelo R, e sim no arquivo de dados.

Problema com acentuação - R


Is it possible to create Custom Error Log in Apache 2 for 404 hits?

Question: Is it possible to create a log file (for example not_found.log) with only 404 HTTP Status Code with Apache2?
Just like this: http://www.helicontech.com/articles/mod_log_config-capabilities/  (Per status code differentiation)
The main problem with this solution is that when status doesn't match, each log will contain a non-informative record like this (--,- -- -):
cat /var/log/apache2/not_found.log
[28/Aug/2013:16:45:42 +0200] 192.168.1.0.,Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 Version/12.15 /index.php/LogApache/titi 404
[28/Aug/2013:16:45:43 +0200] 18.104.22.168,Opera/9.80 (X11; Linux x86_64) Presto/2.12.388 Version/12.15 /favicon.ico 404
- -,- -- -
- -,- -- -
My goal is to count 404 hits and it takes too many time to parse an access_log with more than 1 000 000 lines, that's why I just want to run a wc -l on not_found.log.
Thank you in advance for your help,
Best regards,
Answer:
My goal is to count 404 hits and it takes too many time to parse an
  access_log with more than 1 000 000 lines, that's why I just want to
  run a wc -l on not_found.log.

<code>graeme@server:~$ wc -l access_log
10219670 access_log
graeme@server:~$ time awk '$9 == 404' access_log |wc -l
11060

real    0m23.791s
user    0m14.440s
sys     0m2.450s
</code>
That's 23 seconds to count 404s in a file with 10,000,000 lines. Not fast enough?
Comment: To be more precise, the file can reach 90 000 000 lines, time awk '$9 == 404' access_log |wc -l  90.40s user 14.28s system 83%. It is also based on your configuration. My main problem is that I have to run my script in less than 1 minute.
Comment: You would do well to include that sort of information upfront. Saying "more than 1 000 000" when you mean "up to 90 000 000" is far from useful. You also don't mention the time constraint at all in your question.


proof that $1/2 \ln x = \ln(\sqrt x)$ where $x>0$

Question: What is a proof that $1/2 \ln x = \ln(\sqrt x)$ where $x>0$?
Thank you.
Answer: $a\ln(x)=\ln(x^a)$ why ?
if $\ln(x)=b$ and $\ln(x^a)=c,x^a=e^c,x=e^b$ so $e^c=e^{ab}$so $c=ab$
$$\ln(x^a)=ba=a\ln(x)$$
Comment: You of course also need that $\sqrt x$ is the same as $(x)^{1/2}$
Answer: $$
ln x = \int_1^x  \frac{dt}{t}
$$
(set $t=q^2$)
$$
= \int_1^{\sqrt{x}} \frac{2qdq}{q^2} = 2 \int_1^{\sqrt{x}} \frac{dq}{q} = 2 ln \sqrt{x}
$$