Having issues with my first python web scraper

Question: I am trying to scrape information on a website called supremecommunity for a personal project. They have an archive of items from different seasons and I am trying to put that information into a csv. My code includes a loop that I got from this github page https://github.com/CharlieAIO/Supreme-Community-Scraper/blob/master/sup.py
below is the code that I am working with, it will run without error but the csv remains empty save for the headers that I set. Am I doing something wrong here? Is the website denying my request? Any help or direction appreciated.
import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.text,"html.parser")
    cards = soup.find_all('div',{'class':'card card-2'})

    for card in cards:
        item = card.find("div",{"class":"card-details"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        price = card.find("span",{"class":"label-price"}).text
        price = price.replace(" ","")
        price = price.replace("\n","")
        upvotes = card.find("p",{"class":"upvotes hidden"}).text
        downvotes = card.find("p",{"class":"downvotes hidden"}).text

        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()

Comment: Pretty much all the information you are trying to scrape isn't originally baked into the HTML that the server serves to you. All these elements are populated later asynchronously using JavaScript on the client-side. BeautifulSoup is not able to see any `div`s with class `card card-2` because they aren't in the DOM by the time you scrape for them, so the `for card in cards` loop never executes. Even if you could find the cards, all the other elements are populated in the same way using JavaScript. You're better off using Selenium for this.
Answer: this code save the csv file with some detail of product.
import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.content,"html.parser")
    #print(soup)
    cards = soup.find_all('div',{'class':'card-2'})
    #print(cards)
    #print(len(cards))
    for card in cards:
        item = card.find("div",{"class":"card__top"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        try :
            price = card.find("span",{"class":"label-price"}).text
            price = price.replace(" ","")
            price = price.replace("\n","")
        except :
            price = 'Not Available'
        try :
            upvotes = card.find("p",{"class":"upvotes hidden"}).text
            downvotes = card.find("p",{"class":"downvotes hidden"}).text
        except:
            upvotes = 'Not Found'
            downvotes = 'Not Found'
        print((item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n"))
        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()

Answer: This is one of the ways you can fetch all the aforementioned fields from that webpage other than the prices as they are not available in there yet. To check it, you can click on each image and toggle the price tab. I've used .select() instead of .find_all() to make it concise. Once you execute the script, you should get a data-ridden csv file containing the required fields accordingly.
import csv
import requests
from bs4 import BeautifulSoup

base = 'https://www.supremecommunity.com{}'
link = 'https://www.supremecommunity.com/season/fall-winter2011/overview/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"lxml")

with open("supremecommunity.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerow(['item_name','item_image','upvote','downvote'])

    for card in soup.select('[class$="d-card"]'):
        item_name = card.select_one('.card__top')['data-itemname']
        item_image = base.format(card.select_one('img.prefill-img').get('data-src'))
        upvote = card.select_one('.progress-bar-success > span').get_text(strip=True)
        downvote = card.select_one('.progress-bar-danger > span').get_text(strip=True)
        writer.writerow([item_name,item_image,upvote,downvote])
        print(item_name,item_image,upvote,downvote)


amazons3-7-x-2.0, Multiple upload to S3, #upload_location wrong URI

Question: I installed the brand new amazons3-7.x-2.0 published last week, and the process is not straightforward.
I finally managed to have it works, and I have the CCK file field, with a typical remote #upload location URI : s3://[bucketname]/[subdirectory].
On the node form, the first file I upload works fine. It monitored the file_managed_file_save_upload($element) function, which is called with the proper argument (remote URI):  $element['#upload_location']=s3://[bucketname]/[subdirectory] .
But when I click on "add new file" and select another file, the file_managed_file_save_upload function is called with a wrong #upload_location :
$element[#upload_location']= s3://[subdirectory]
The upload then failed with the following message : "The file could not be uploaded.".
In order to get amazons3 module to work with this long awaited new release, I had to patch a lot of files with contributed patches fixing the exact same issue of bucketname in the URI.
Is somebody facing the same problem and found a solution ? I will try the plupload module see if it fixes the issue.
Answer: ok, after spending a few hours debugging the code, I have finally identified  the problem and come out with a solution :
Amazons3 implements a amazons3_field_widget_form_alter that fixes the $element['#upload_location'] :

function amazons3_field_widget_form_alter(&$element, &$form_state, $context) {
$field = $context['field'];
    $instance = $context['instance'];
    $delta = $context['delta'];
if (in_array($field['type'], amazons3_file_like_field())) {
      $element[$delta]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
    }
  }

The problem is that this function is only called once, on $delta=0. Thus, it only fixes the first delta instance of the field, correcting the first upload. But the second upload fails because the bucketname is not in the remote URI.
In order to fix this, I propose the wrote following function in my module :

function mymodule_field_widget_form_alter(&$element, &$form_state, $context){
      // On essaie de corriger les settings upload_location
      if (!function_exists('amazons3_file_like_field')) {
          return;
      }
      $field = $context['field'];
      $instance = $context['instance'];
      $delta = $context['delta'];
<code>if (in_array($field['type'], amazons3_file_like_field())) {
    foreach (array_keys($element) as $count => $key) {
        if (is_numeric($key) && isset($element[$key]['#upload_location']) && !(strpos($element[$key]['#upload_location'],'s3://')===FALSE)) {
            $element[$key]['#upload_location'] = amazons3_field_widget_uri($field, $instance);
        }
    }
}
return;
</code>
}

It works well, allowing multiple uploads in S3 with the new release of the library.
Next step would be to post a patch to the amazons3 module. Which I will do now.


Transformation of probability of occurrence to prob of first occurrence

Question: I have a series of probabilities that event $E$ occurs at iteration $i$ with $i=1,2,....$. These are denoted $p_1,p_2,....$. These probabilities are that $E$ occurs on iteration $i$, but do not consider whether $E$ occurred before $i$.
I want to transform these $p$s into a new series such that $\hat{p}^i$ = probability of first occurrence of $E$ on $i$. My thought is that this is:
$$\hat{p}^i = (1-p_1)(1-p_2)....(1-p_{i-1})p_i$$
Assuming $p_i$ is independent of $p_j$ for $i>j$.
But how do I transform if they are not independent?
In my problem, the probability $E$ occurs over time approaches a stationary distribution and is increasing up to that point. E.g, after some iteration $T$ $p_{t} = X \forall t>T$. "An event waiting to happen"
Comment: +1 agree with your answer, and yes, it certainly assumes independence
Comment: @MikeP I edited my question with new information asking about that.
Comment: You would normally speak of independent *events*, rather than probabilities. What do you mean by "agnostic"? If the probability of an event at $j$ is the same whether or not an event occured at $i$, then the events are independent.
Answer: They could still be independent.  I can come up with an example, although very contrived.
Suppose that p-primes are 0.1, 0.2, 0.3, 0.4 (have to sum to 1)
We can work backwards and come up with ps assuming independence to match using:
$$p'(i)=\prod_{j=1}^{i-1}(1-p(j))\cdot p(i)$$
$$p(i)=\frac{p(i)}{\prod_{j=1}^{i-1}(1-p(j))}$$
Using Matlab ps are 0.1000, 0.2222, 0.4286, 1.0000
Comment: from summing my $p$s I have learned that I must not have independence. Thus I've edited my question to ask how to transform it not independent.
Answer: You would normally talk about independent events rather than probabilities.
To be more precise, let $E_i$ be a binary indicator such that
$$E_i=\begin{cases}
1 & \text{an event occurs at iteration }i \\
0 & \text{otherwise}
\end{cases}$$
Then the marginal probability of $E_i=1$, with respect to an event at some other iteration $j$, will be
\begin{align}\Pr\big[E_i=1\big] &= \Pr\big[E_i=1\mid E_j=1\big]\times\Pr\big[E_j=1\big] \\ &+\Pr\big[E_i=1\mid E_j=0\big]\times\Pr\big[E_j=0\big]\end{align}
If the event $E_i$ is independent of the event $E_j$, then you will have
$$\Pr\big[E_i=1\mid E_j=1\big] = \Pr\big[E_i=1\mid E_j=0\big] = p_i$$
This intuitively would seem to correspond to your statement about "agnostic".
Mathematically, since you are specifying the probabilities $p_i$ without reference to the sequence of values $E_{j<i}$, your model is assuming independent events. (Otherwise you would need to marginalize over possible "prefix sequences" to determine the $p_i$.)
Comment: this answer helps. because my $p$s do not seem to add to 1, so I guess I am violating independence somewhere.
Comment: can I re-ask, how to transorm if they are not independent? I edited my question
Comment: Where do your $p_i$ values come from? My understanding was that multiple events can occur, so the sum of the $p$'s would not sum to $1$. (As distinguished from the $\hat{p}$'s; e.g. you have a variable-$p$ version of [this](https://en.wikipedia.org/wiki/Geometric_distribution).)
Comment: more information: 1) only one event can occur. 2) i've updated the question with information about $p$s approaching a stationary distribution.
Comment: yes it looks like a variable p version of that; is there a straitforward answer to that?


R control jitter function - avoid overplotting / non-random jitter

Question: My problems seems simple, I am using ggplot2 with geom_jitter() to plot a variable. (take my picture as an example)
Jitter now adds some random noise to the variable (the variable is just called "1" in this example) to prevent overplotting. So I have now random noise in the y-direction and clearly what otherwise would be completely overplotted is now better visible.
But here is my question:
As you can see, there are still some points, that overplot each other. In my example here, this could be easily prevented, if it wouldn't be random noise in y-direction... but somehow more strategically placed offsets.
Can I somehow alter the geom_jitter() behavior or is there a similar function in ggplot2 that does exactly this?

Not really a minimal example, but also not too long:
library("imputeTS")
library("ggplot2")

data <- tsAirgap

# 2.1 Create required data

# Get all indices of the data that comes directly before and after an NA

na_indx_after <- which(is.na(data[1:(length(data) - 1)])) + 1
# starting from index 2 moves all indexes one in front, so no -1 needed for before
na_indx_before <- which(is.na(data[2:length(data)]))

# Get the actual values to the indices and put them in a data frame with a label
before <- data.frame(id = "1", type = "before", input = na_remove(data[na_indx_before]))
after <- data.frame(id = "1", type = "after", input = na_remove(data[na_indx_after]))
all <- data.frame(id = "1", type = "source", input = na_remove(data))

# Get n values for the plot labels
n_before <- length(before$input)
n_all <- length(all$input)
n_after <- length(after$input)

# 2.4 Create dataframe for ggplot2

# join the data together in one dataframe
df <- rbind(before, after, all)

# Create the plot

gg <- ggplot(data = df) +
  geom_jitter(mapping = aes(x = id, y = input, color = type, alpha = type), width = 0.5 , height = 0.5)

gg <- gg + ggplot2::scale_color_manual(
  values = c("before" = "skyblue1", "after" = "yellowgreen","source" = "gray66"),
)

gg <- gg + ggplot2::scale_alpha_manual(
  values = c("before" = 1, "after" = 1,"source" = 0.3),
)

gg + ggplot2::theme_linedraw() + theme(aspect.ratio = 0.5) + ggplot2::coord_flip()

So many good suggestions...here is what Bens suggestion would look like for my example:
I changed parts of my code to:
gg <- ggplot(data = df, aes(x = input,  color = type, fill = type, alpha = type)) +
  geom_dotplot(binwidth = 15)

Would basically also work as intended for me. ggbeeplot as suggested by Jon also worked great for my purpose.
Comment: I don't know anything built into ggplot2 to do this. You might look at the `ggbeeswarm` package for a few options on this. But it might not be what you want since it packs all the points together toward the centerline.  You might alternately define a quasirandom function to do this, e.g. using `poissoned` or `poissondisc` packages. Or if you want to go overkill you could create a simulation using `particles` to repel any overlapping points.
Comment: Can we have a [mcve] please? I thought that `ggplot(df, aes(x, y, color = col, fill=col)) + geom_dotplot(stackdir="center",binwidth=0.1, alpha=0.5) ` would work (using @JonSpring's example but I don't think it works for variable `y`.
Comment: You guys are such a great help! I clearly had difficulties finding the right terms to google. Ben's solution also works great for my purpose (see my edited answer). You might also add this as answer, Ben. Nice thing here is it doesn't need an additional package beyond ggplot2. But I also quite like all the possibilities that come with the ggbeeswarm package. Perfect, I have gone from no satisfying solution to choosing from multiple nice solutions in 1 day. Thanks so much.
Answer: I thought of a hack I really like, using ggrepel. It's normally used for labels, but nothing preventing you from making the label into a point.
df <- data.frame(x = rnorm(200),
                 col = sample(LETTERS[1:3], 200, replace = TRUE),
                 y = 1)

ggplot(df, aes(x, y, label = "●", color = col)) + # using unicode black circle
  ggrepel::geom_text_repel(segment.color = NA,
                           box.padding = 0.01, key_glyph = "point")

A downside of this method is that ggrepel can take a lot time for a large number of points, and will recalculate differently each time you change the plot size. A faster alternative would be to use ggbeeswarm::geom_quasirandom, which uses a deterministic process to define jitter that looks random.
ggplot(df, aes(x,y, color = col)) +
  ggbeeswarm::geom_quasirandom(groupOnX = FALSE)

Comment: Nice, but only seems to work if there are not too many points. Otherwise I get "ggrepel: 95 unlabeled data points (too many overlaps). Consider increasing max.overlaps" and it just doesn't print all the points. Also don't know what is actually does behind the scenes (what is added into the plot) but the plot takes really long to load (when switching plots). Your ggbeeswarm suggestion though works perfectly (maybe you also want to add this to the answer or as additional answer, that I can accept it). Thanks a lot for your help, Jon!


Symfony 1.4 setter type double precision

Question: I want to save a number with 14 decimal places, but symfony only saves 6. How can I control this:
$loc->setSinRadLon(0.73946213661883);

In the schema the column looks like:
sin_rad_lon: { type: double(), scale: 14, notnull: true }

The DB stetting is:
sin_rad_lon     double(18,14)

In the DB the column value is: 0.73946200000000 (8 numbers are cut).
(I just tried ini_set("precision", "14") but it does not solve all problems.)
Thx for your help.
Answer: try to change at your schema the "length" of the datatype for example type: double(X), scale: Y


How to make a variable stored on the server

Question: How do you make a variable that is stored on the server of your script? So the value stays on it even when you go out. And it has to be worldwide. So if somebody increases the variable by one, somebody else on the other side of the world could see that change. This might have already been asked before, but I didn't see anything. Or else I didn't word the question differently. Anyway, could you give me a solution, or direct me to another variation of the question? Thanks!
Comment: Akshey Bhat, Manish - How is caveman life?
Comment: Javascript runs on client side not on server side. So variable will be on client side only
Comment: Javascript is client side scripting language. So what ever you do on client side you need to send that those updates to the server. And Storing data on server side requires server side programming. So answer to your question is Using javascript alone its not possible to store server side variables. But yes you can use a server side technology such as PHP or ASP.NET etc. Which can help you to achieve what you need.
Comment: Move that to Database :/
Answer: Why didnt use database? If you love JavaScript so much, and won't to learn other language, you can use nodejs.
check this to get start using nodejs:
https://google/MkVg6Q
Answer: Normally when you increment a variable in your browser, the scope and life of that variable unfortunately is just the browser. To make it persist, you need to store it in a database on the server so that it persists across requests to your page. So your answer is, a database. They come in all flavours and sizes and complexities but you might be better off starting with something like MySql.


How to prove boundary of a subset is closed in $X$?

Question: Suppose $A\subseteq X$. Prove that the boundary $\partial A$ of $A$ is closed in $X$.
My knowledge:

$A^{\circ}$ is the interior
$A^{\circ}\subseteq A \subseteq \overline{A}\subseteq X$

My proof was as follows:
To show $\partial A = \overline{A} \setminus A^{\circ}$ is closed, we have to show that the complement $( \partial A) ^C = X\setminus{}\partial A =X \setminus (\overline{A} \setminus A^{\circ})$ is open in $X$. This is the set $A^{\circ}\cup X \setminus(\overline{A})$
Then I claim that $A^{\circ}$ is open by definion ($a\in A^{\circ} \implies  \exists \epsilon>0: B_\epsilon(a)\subseteq A$. As this is true for all $a$, by definition of open sets, $A^{\circ}$ is open.
My next claim is that $X \setminus \overline{A}$ is open. This is true because the complement is $\overline{A}$ is closed in $X$, hence $X \setminus \overline{A}$ is open in $X$.
My concluding claims are: We have a union of two open sets in $X$, By a proposition in my textbook, this set is open in $X$. Therefore the complement of that set is closed, which is we had to show.
What about this ?
Answer: From your definition, directly,
$$
\partial A=\overline{A}\setminus \mathring{A}=\overline{A}\cap (X\setminus \mathring{A})
$$
is the intersection of two closed sets. Hence it is closed.
No need to prove that the complement is open, it just makes it longer and more complicated.
Also, keep in mind that a set $S$ is open in $X$ if and only if its complement $X\setminus S$ is closed in $X$. This should be pavlovian.
Comment: thank you for your reply.But is my proof correct ?
Comment: @JoyeuseSaintValentin Yes, it is correct. But aggain, it does not add anything interesting to consider the complement. Except for a little complication, i.e. determining this complement. So it is instructive for study purposes, but you should favor the direct way.
Comment: I agree. This was during an exam and I was not completely clear in my mind. Of course your proof is much 'cleaner' :)
Comment: @JoyeuseSaintValentin I've written crazy things during exams...And even at home without any pressure.
Comment: haha ok, good to hear that others struggle too sometimes
Answer: Your proof looks correct to me. The interior is indeed open by definition (and the closure is closed by definition). And the fact that a union of open sets is open is one of the axioms for a topology. You may wish to note that $\partial A$ is often defined as $\overline{A} \cap \overline{X - A}$. Since finite intersections of closed sets are closed, it follows that $\partial A$ is closed in $X$.


Find the probability of a device failure

Question: A device ceases to work if at least $5$ first type of light bulbs burn out or at least $2$ second type light bulbs burn out. Find the probability of the device ceasing to work, knowing that $5$ bulbs burned out (but not which type). The probability of the first type of light bulbs to burn out is $0.7$ and the probability of the second type of light bulbs to burn out is $0.3$
Comment: You should edit your question to include what you've tried and where you're stuck.
Comment: Do you know about the binomial distribution? One way to think about the problem is call each bulb failure a *sucess* if it is a type 1 bulb failure. Then the two failure modes can be thought of in terms of the number of successes out of $5$ independent trials.
Comment: The point is that I'm stuck exactly at the start, because of it having 2 separate failure factors. I tried getting the probability of 5 failing in first type bulbs, adding to it 3 first type fail & 2 second type fails but that isn't right.
Answer: Call a bulb failure a sucess if it is a type one bulb failure. Then, the probability of success is $0.7$. Let $N$ be the number of successes, then noting that we have $5$ trials, it is clear that $N$ is distributed binomially, i.e., $\text{Bin}(5,0.7)$.
Now, there are two ways for the device to fail. Either $N=5$ meaning all the bulbs were type 1, or $N\leq 3$ meaning at least 2 of the failures were from type 2 bulbs. Since we know how $N$ is distributed, we can compute this directly.
In particular, the probability of getting exactly $k$ sucesses is $$P(N=k)={{5}\choose{k}} 0.7^k(1-0.7)^{5-k}.$$
Comment: As a matter of fact, about 15 minutes ago I tried going the binomial way as well and had success! Thank you David, this is the correct answer.


Missing (replaced) polish characters after serving via IIS

Question: I have a page in ASP.net (VB) that I'm serving via IIS.
The page is basically a translation of the uk site.
I have:
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

at the top of the code, and all the characters show ok in the code.
however in (all) browsers many of the special polish characters, such as 'Ł' are missing, replaced directly with 'L'.
Is this an IIS thing? or could it be something else?
ETA: I just noticed that the polish text portion drawn out of the SQL database is being displayed correctly within the same page..! Odd!

Further edit:
I have found the basic source of the issue, I think, but not a solution:
The areas that are not showing properly are headers and footers, which are imported into the page via Server Side Include.
It seams some sort of encoding is being lost in this import / injection.
Should the imported file have some sort of encoding header?
Answer: This sounds like a problem with encoding in your static content files. The content-type <meta> has no bearing on the actual physical encoding of the file. I have a suspicion the file is saved in Codepage 1252 instead of UTF-8.
I suggest you open your *.aspx files (where I assume you're storing the problematic Polish text) in a text editor that supports different encodings (such as VS or Notepad2. Not WordPad or Windows Notepad). Force-save the file with UTF-8 encoding (in VS, go File > Advanced Save Options and ensure "Unicode (UTF-8 with signature)" is selected). Then access your site again.
Also ensure that the Content-Type HTTP header is also correctly set to UTF-8.
Comment: It seems that you were very close there David, as it turns out, the header and footer were .shtml files imported vis SSI in IIS on request.
These files were (I imagine) originally created in Notepad and saves as ANSI type. While this worked fine for the English site, it wont for the polish characters.
So I have re-saved them as UNC-8 and all is rosy.


Comparison in twig templates

Question: I have a list field for a custom content type that looks like this:
Field Machine name is: field_app_os
key|label
Win|Windows
Android|Android

I can access the key in Twig template by using content.field_app_os or Twig Field Value and the output of both is Android:

Twig Field Value allows Drupal 8 themers to get partial data from
  field render arrays. It gives them more control over the output
  without drilling deep into the render array or using preprocess
  functions.
  Filters:
  - field_label : Returns the field label value.
  - field_value : Returns the render array of the field value(s) without the field wrappers.

/* with use of Twig Field Value module */
{{ content.field_app_os|field_value }}  {# outputs 'Android' #}

 /* without use of Twig Field Value module */
{{ content.field_app_os }}  {# outputs 'Android' #}

However, if I do a simple comparison, the output of both is False.
{% set app_os = content.field_app_os|field_value %}
{{ kint(app_os == 'Android') }} {# outputs 'bool FALSE' #}

Or When I use:
{% set app_os = content.field_app_os %}
{{ kint(app_os == 'Android') }} {# outputs 'bool FALSE' #}

What's wrong in my code?
Comment: For those who are attempting to resolve the issue: As a test
{{ content.field_app_os }} produced 'Android' but {% if content.field_app_os == 'Android' %} True {% endif %} didn't work.
Comment: @4k4: Thanks for your help and attention, When I use `node.field_app_os.value` then all things work correctly, But can you explain a little more about the cause of this issue, Please.
Comment: What is the output when you do {% set app_os = content.field_app_os|field_value %} {% if app_os == 'Android' %} app_os is Android{% endif %} ?
Comment: Hmm weird. I wonder if 'content.field_app_os|field_value' is slightly different. Like maybe there's white space or something. As a test what happens if you just straight do {% set app_os = 'Android' %} does it work then?
Comment: Okay well At least we got it down to 'content.field_app_os|field_value' being the issue. And you are completely positive it's producing just that string with nothing else? And it doesn't produce that string inside an array or anything like that?
Comment: Here's a chat room we can discuss this in https://chat.stackexchange.com/rooms/66357/mojtaba-reyhani-and-matt-chat
Comment: The question is, when using a key/label pair, why not use the key for logic, which you get in `node.field_app_os.value`? Otherwise your logic breaks if you translate the label. And the fields in content contain render arrays, so you can't compare it to a string.
Answer: {{ content }} is a render array, where you find the label of the key/label pair probably here:
{{ content.field_app_os[0]['#markup'] }}

But this is not ideal for logic:

The position in the render array can change, for example if you
install a layout module.
The content of #markup depends on how the
field formatter is configured in the view mode.
The label is translatable, so the
logic breaks on a multilingual site.

So it's better to use the database value in:
{{ node.field_app_os.value }}

This is the first part of the key/label pair, which is untranslatable and you can access the value independent on how the field is configured in the view mode.
Comment: I don't know this module, but this is probably to extract the part of the render array which renders the value without the field div's and not to extract a string value you can use in a logic expression. In general use `content.` for rendering and `node.` for logic.
Comment: Thank you so much, But for what when I use [Twig Field Value](https://www.drupal.org/project/twig_field_value), The `{{ content.field_app_os|field_value }}` not work correctly?

Comparison in twig templates


How can I set a single proxy for a requests session object?

Question: I'm using the Python requests package to send http requests. I want to add a single proxy to the requests session object. eg.
session = requests.Session()
session.proxies = {...} # Here I want to add a single proxy

Currently I am looping through a bunch of proxies, and at each iteration a new session is made. I only want to set a single proxy for each iteration.
The only example I see in the documentation is:
proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

I've tried to follow this, but to no avail. Here is my code from the script:
# eg. line = 184.108.40.206:80
r = s.get('http://icanhazip.com', proxies={'http': 'http://' + line})

But I get an error:
requests.packages.urllib3.exceptions.LocationParseError: Failed to parse 188.8.131.52:80

How is it possible to set a single proxy on a session object?
Answer: In addition to @neowu' answer, if you would like to set a proxy for the lifetime of a session object, you can also do the following -
import requests
proxies = {'http': 'http://10.11.4.254:3128'}
s = requests.session()
s.proxies.update(proxies)
s.get("http://www.example.com")   # Here the proxies will also be automatically used because we have attached those to the session object, so no need to pass separately in each call

Comment: Strangely, when I set the proxies for the session like that, it fails for me (with `ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',))`), but if I pass the exact same dict to the `get` method, it works fine.
Comment: Ah, just found the issue - if you have other proxies defined in the environment, use `session.trust_env=False` to make sure your proxies defined for the session are not overridden by the environment (in my case, we use different proxies for different tasks).
Comment: This is a much better way to do it.
Comment: if you're doing this chances are you're using a self signed certificate that will throw **[SSL: CERTIFICATE_VERIFY_FAILED]** to surpass that use **s.verify = False**
Comment: Thanks @BugHunterUK
Comment: Many thanks! It's the better response for me. Use the proxies in ALL next requests
Answer: In fact, you are right, but you must ensure your defination of 'line', I have tried this , it's ok:
>>> import requests
>>> s = requests.Session()
>>> s.get("http://www.baidu.com", proxies={'http': 'http://10.11.4.254:3128'})
<Response [200]>

Did you define the line like line = ' 22.214.171.124:80', there is a space at the front of address.
Comment: There was a space at the beginning of each line. It's always the simplest things that trick me out the most lol. Thanks :)
Comment: Note: If you're using a proxy server e.g. squid, this isn't going to keep you using the same IP address. i.e. the subsequent `s.get` will use the original proxy/actual ip.
Answer: There are other ways you can set proxies, apart from the solutions you have got so far:
import requests

with requests.Session() as s:
    # either like this
    s.proxies = {'https': 'http://22.214.171.124:8888', 'http': 'http://126.96.36.199:8000'}
    # or like this
    s.proxies['https'] = 'http://22.214.171.124:8888'
    r = s.get(link)

Comment: hows this differ from `s.proxies.update(proxies)` in the answer above?
Answer: Hopefully this may lead to an answer:

urllib3.util.url.parse_url(url)
  Given a url, return a parsed Url namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None.

retrived from https://urllib3.readthedocs.org/en/latest/helpers.html


Finding Matrix invertion by multiplication

Question: Given a  matrix $[A, B]$ where $A$ and $B$ are $n\times n$ invertible matrices. Is it possible to find a matrix $\begin{bmatrix}C \\D \end{bmatrix}$ such that $\begin{bmatrix}C \\D \end{bmatrix}$ $[A, B]$ is invertible?
Answer: Notably, you haven't said what the sizes of $C$ and $D$ are.
In any case, there is no matrix $M$ such that $M [A \ \ B]$ is invertible.  To see that this is the case, note that if we fix a non-zero vector $b$, then we find that
$$
x = \pmatrix{A^{-1}b\\ -B^{-1}b} \implies
\pmatrix{A & B} x = 0
$$
So, $[A\ \ B]$ has a non-trivial kernel.   We see that for any matrix $M$, $(M [A \ \ B])x = 0$, which means that $M [A \ \ B]$ will have a non-trivial kernel, which means that it will not be invertible.
For another perspective: $M [A \ \ B]$ will have rank at most $n$, but if it's square, it has to be of size $2n \times 2n$.


How to "statistically adjust" for variables?

Question: I've been trying to understand what means "statistically adjusted" when comparing two variables.  For example, when computing the odds ratio for a death after surgery in two hospitals, we compute the odds of death in one hospital, to the odds of death in the other hospital.
But, then let's say we want to "statistically adjust" (as the literature likes to call it)  for other variables.  For each variable we "statistically adjust" for, we will multiply the number of odds ratios by 2.
For example, we "statistically adjust" for whether or not the patients are healthy.  This would mean that we would have two odds ratios:

odds ratio for the patients in good health
odds ratio for patients of poor health

Then lets say we adjust for patients of age >50 and patients of age < 50.  Then, we have a total of 4 odds ratios, which is the cartesian product of age, and health.
How do I end up with one odds ratio comparing death rates in the two hospitals?
A resource that attempts to explain this is here:  https://www.iwh.on.ca/wrmb/statistically-adjusted.  It says that a statistician "will tell you that the odds ratio has been statistically adjusted to incorporate the effect of patient condition at the time of surgery, and is now 1.14".  I do not understand how one value, 1.14, is able to summarize everything about multiple odds ratios.  Thanks for helping me.
Comment: Here's a very closely related question: [How exactly does one "control for other variables"?](http://stats.stackexchange.com/q/17336/22228). It's debatable whether it is a duplicate or not, but it seems pretty close.
Comment: I believe "(statistically) adjusting variables" is yet another *Americanized* way of English. I prefer saying **holding all other variables constant** which is more clearer.
Answer: When you "statistically adjust" something, what you are really doing is removing the effect of whatever you are adjusting for. Formally, the things you are adjusting for are called "covariates", which is just the set of variables that (a) you did not experimentally control and (b) have in impact on the outcome.
Not surprisingly, these things pop up a lot in observational studies, where you want to measure X (say, spending on beer) as a function of Y (say, age), but cannot set up a formal experiment. A naive approach to my example of studying age and beer expenditures would simply select a random sample of the population and regress beer spending on age.
However: what other things affect beer purchase patterns? Is it the only factor influencing beer expenditures? Off the top of my head, I'd expect that some other factors that would be influencing the outcome would be:

College student or not
Race/ethnicity
Religion (e.g. Mormons don't drink)
Income (positively correlated with age, until about 65)

So, let's say your naive regression shows a strong, positive effect of age on beer expenditures. However, what if your random sample contains a large number of young frat boys (who never pay for the copious beer they drink) while also having a large number of rich, elderly persons.
A critic of your study would say that age has no intrinsic effect, it's all income and the availability of alternative beer sources. To counter, you would adjust for the effect of these "covariates" on beer expenditures by including these variables as explanatory variables in your regression model. After you do that, the coefficient/weight applied to the age factor better represents the differential impact of age (ceteris paribus).
It may turn out that after including income and availability, the residual variability left for age to explain is minuscule, in which case your thesis is in trouble.
So, the bottom line is that statistically "adjusting" doesn't mean applying some fudge factor, it means that you've included explanatory variables in your model that are in some sense "ancillary" to your study's purpose (but nonetheless are important for accurately measuring your target effect). Fitting a statistical model with extra variables will spread the observed variability among these variables.
Answer: There are a few ways that adjustments can be done but one of the most common ways when there are multiple variables to adjust for is to simply include, as independent variables into a model, the variables for which you want to adjust.
So for example, let's say you wanted to compare the odds of death for hospital A and hospital B, adjusting for patient age (in years) and severity of illness measured (for simplification) as "minor" or "extreme."  Then you could simply fit the following logistic regression model:
$log[p/(1-p)]=\beta_0+\beta_1X_1+\beta_2X_2+\beta_3X_3$
where $p=P(Y=1|X_1, X_2, X_3)$,
$y= 0, 1$ is the indicator variable for death and $X_1=1$ for hospital A or 0 for hospital B, $X_2$ is the patient's age in years, and $X_3=1$ for minor severity of illness, 0 otherwise.  With this model you can calculate the odds of death in hospital A compared to hospital B, adjusted for the other variables included in the model by simply exponentiating the the estimated coefficient corresponding to the hospital indicator variable you obtain from your logistic regression model, in this case, $exp(\hat{\beta}_1)$.
Edited to Address your follow-up question
If you didn't want to use logistic regression for this, you can still use a tabular approach.  The method for obtaining the adjusted odds ratio is called the Mantel-Haenszel adjusted odds ratio.  This is simply a weighted average of the individual odds ratios obtained in each of the tables obtained by stratifying on the confounder (in your linked example the odds ratios formed from the individual odds ratio from the good health table and poor health table).  The weight for each table is equal to the inverse of the estimated variance of the odds ratio for the table.  The general formula is given by:
$\sum_i a_id_i/n_i\over{\sum_i b_ic_i/n_i}$
for each table $i$, where, in this example, $a_i$ is the number of deaths in hospital B, $d_i$ is the number of living in hospital A, $b_i$ is the number of deaths in hospital A and $c_i$ is the number living in hospital B.  Taking the numbers from this example we have, letting table $i=1$ for those in good health and $i=2$ for poor health:
$\sum_i^2 a_id_i/n_i\over{\sum_i^2 b_ic_i/n_i}$=$(8)(594)/1200+(8)(1433)/1700\over{(6)(592)/1200+(57)(192)/1700}$=$1.138958\approx1.14$
Comment: @Sother, I edited my answer to include the answer to your follow-up question.
Comment: @Sother, If you found this acceptable, please click the green checkmark.  Thanks.
Comment: Okay, I understand.  so, the hospital becomes an indicator variable.  Now, perhaps you understand my confusion in this [example](https://www.iwh.on.ca/wrmb/statistically-adjusted), where they claim to compute an odds ratio without fitting a model: "will tell you that the odds ratio has been statistically adjusted to incorporate the effect of patient condition at the time of surgery, and is now 1.14".
Comment: OK, thanks a lot for your explanation.  I understand that we have to compute some kind of weighted average, but the formula you use somehow doesn't make complete sense to me.  I would have thought a representative value would be a weighted average of the odds ratios, weighted by the number of people:  The odds ratios for good and poor health, respectively, are `1.3/1` and `4/3.8`, so  `OR = ((1.3*1200)+(4/3.8)*1700)/(1200+1700)`.  Is there anything wrong with this formulation?
Comment: @Sother, the weights are chosen so to be the inverse of the variance of the odds ratio.  That way tables with smaller variances are given more weight compared to those with larger variances.  Simply weighting by the number of people in the table isn't providing you with better estimates if the variance in higher in those tables with more people.  See the original paper for a derivation of the MH statistic:  (see here under Articles (methods):  http://www.medicine.mcgill.ca/epidemiology/hanley/c634/stratified/


Ignorar tecla enter em modal aberto

Question: No meu sistema, criei um modal que vai servir de alerta sempre que o usuário fizer alguma operação inválida.
Mas para obrigar o usuário a sempre fechar o modal pelo botão close, eu queria evitar que ele feche o modal ao apertar a tecla ENTER. Tem alguma coisa que faz isso?

// Get the modal
var modal = document.getElementById('mensagem');

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}
.modal {
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

<input type="hidden" autofocus="true">

    ×

<?=$mensagem;?>

Comment: O seu modal só fecha se clicar no botão X.
Comment: Desculpe, mas não entendi. Você quer que não feche ao apertar enter? Mas, ele já não está fazendo isso? Ao meu ver, seria mais racional, possibilitar fechar com a tecla....
Comment: Meu modal está fechando quando aperto Enter mas quero que isso não aconteça. Porque o usuário está viciado em apertar o enter em qualquer mensagem e não ler. Quero seja uma "desculpa a mais" pro usuário observar a mensagem antes de fechar. Além de que tenho que usar essa validação em inputs de código de barra no qual o enter é automático.
Comment: No teste daqui quando aperta o Enter nada acontece. O que faz a modal fechar quando aperta o Enter?
Comment: Desculpe a demora pra responder. Realmente o modal não deveria fechar. Mas então reparei o seguinte. O campo que faz a validações está com autofocus e ele é utilizado para informar um código de barras. Então eu redireciono pra outra pagina para uma série de operações  e depois usando um header eu volto pra mesma página e mostro o erro se existir uma S_SESSION. Ao voltar pra página o campo está com o focus e ao dar enter ele fecha o modal de erro e abre outro.
Answer: Voce poderia tentar, se não me engano, aplicar ao 'span' o evento de teclado 'onkeypress' e defini-lo para que quando houver um evento de teclado, nada aconteça. Exemplo:
 span.onkeypress = function() {
  modal.style.display = "none";
 }

Ai um evento de teclado aciona a ação sobre o modal. Para evitar isso, você pode passar 'none' para o evento. Ficaria assim:
span.onkeypress = none;

evitando assim qualquer evento de teclado sobre o 'span'.
Answer: Uma opação:

document.querySelector('.modal').addEventListener('keypress', function(evt) {
    if (evt.key) {
        evt.preventDefault();
    }
});

Mas pensando em acessibilidade isso é bem ruim porque uma pessoa que depende do leitor de tela pode não conseguir interagir com sua aplicação. Na verdade o ideal seria deixar a interação com teclado e pensar em usar um tabindex para ajudar o leitor de tela e usar um svg com title.

Ignorar tecla enter em modal aberto


A question of Hirzebruch surface $ \mathbb{P}(\mathcal{O}(1) \bigoplus \mathcal{O})$

Question: My question comes from my professor. I try my best to understand what the question means, but  it doesn't work! I even cannot understand the question meaning!   I think I need some hints to answer the question.
We can find the definition of Hirzebruch surface  in [Fulton " Introduction Toric varieties" page 8].
Which introduce the construction of  Hirzebruch surface $ \mathbb{F}_a $ with $ a \in \mathbb{N}$. And we know that, in fact, $ \mathbb{F}_a $ is a projective bundle $ \pi:  \mathbb{P}(\mathcal{O}_{\mathbb{P}^1}(a) \bigoplus \mathcal{O}_{\mathbb{P}^1}) \to \mathbb{P}^1$.
Now, let us consider the case of $a = 1. \  i.e. \ \mathbb{P}(\mathcal{O}_{\mathbb{P}^1}(1) \bigoplus \mathcal{O}_{\mathbb{P}^1})$.
In [Fulton], we construct $ \mathbb{F}_1 $ from the toric variety point of view.
My main Question:

But if we just regard $ \mathbb{F}_1$ $\cong$
  $\mathbb{P}(\mathcal{O}_{\mathbb{P}^1}(1) \bigoplus$
  $\mathcal{O}_{\mathbb{P}^1})$ as a scheme, how do I write down all
  affine open pieces and identifications between any two affine open
  piece which is "compatible" with the toric construction )

What is the meaning of "Compatible"? I have no sense about this important key word.
I follow the definition of $\mathbb{P} (\mathcal{E})$ in [Hartshorne]:
Let $\mathcal{E} = \mathcal{O}_{\mathbb{P}^1}(1) \bigoplus \mathcal{O}_{\mathbb{P}^1}$ be a locally free sheaf on $\mathbb{P}^1$.Recall that in  $\mathbb{P}^1$, there are two standard affine open subsets $D_{+}(x_0) \cong  Spec \ \mathbb{C}[x_0,x_1]_{(x_0)}$ and $D_{+}(x_1) \cong  Spec\ \mathbb{C}[x_0,x_1]_{(x_1)}$
So we have   $\mathcal{E} | _ {D_{+}(x_0)}$   =  $(\mathcal{O}_{\mathbb{P}^1}(1) \bigoplus \mathcal{O}_{\mathbb{P}^1})|_{D_{+}(x_0)}$  $\cong$ $\widetilde{S(1)_{(x_0)}}\bigoplus \widetilde{S_{(x_0)}}$, where $S =  \mathbb{C}[x_0,x_1]$.
We have $\mathcal{E} | _ {D_{+}(x_0)}( D_{+}(x_0)) = x_0 \mathbb{C}[x_0,x_1]_{(x_0)} \bigoplus  \mathbb{C}[x_0,x_1]_{(x_0)}$
Let $ M := x_0 \mathbb{C}[x_0,x_1]_{(x_0)} \bigoplus  \mathbb{C}[x_0,x_1]_{(x_0)}$, then $ M $ is a free $\mathbb{C}[x_0,x_1]_{(x_0)}-module$ of rank 2.
Consider the symmetric algebra of $M$, $Sym(M) \cong   \mathbb{C}[x_0,x_1]_{(x_0)}[y_0,y_1] $, which is clearly an graded ring over $\mathbb{C}[x_0,x_1]_{(x_0)}$. Therefore, we can consider the projective scheme $Proj(\mathbb{C}[x_0,x_1]_{(x_0)}[y_0,y_1])$.
$\implies

$ $Proj(\mathbb{C}[x_0,x_1]_{(x_0)}[y_0,y_1])$
$ \ \ \ \cong Spec\ \mathbb{C}[x_0,x_1]_{(x_0)}\ \times_{Spec\ \mathbb{C}} Proj(\mathbb{C}[ y_0,y_1])$
$ \\\\\\\\\\\\\\\  \ \   = Spec\ \mathbb{C}[x_0,x_1]_{(x_0)}\ \times Proj(\mathbb{C}[ y_0,y_1]) $
$ \\\\\\\\\\\\\\\  \ \   = Spec\ \mathbb{C}[x_0,x_1]_{(x_0)}\ \times \mathbb{P}^1$
So, we also have four affine open pieces of the scheme of $\mathbb{P} (\mathcal{E})$.
Now, we need to gluing such four affine pieces "compatible" with the structure in [Fulton,page8].(the meaning of "compatible" really confuses me ).
Recall that

$D_{+}(x_0) \bigcap D_{+}(x_1)$  $\cong  D_{+}(x_0x_1)$ $\cong  Spec \ \mathbb{C}[x_0,x_1]_{(x_0x_1)}$
$ Spec\ \mathbb{C}[x_0,x_1]_{(x_0)}\ \times_{Spec\ \mathbb{C}} D_{+}(y_0) $ $\cong$ $ Spec\ (\mathbb{C}[x_0,x_1]_{(x_0)} \bigotimes_{\mathbb{C}}\mathbb{C}[y_0,y_1]_{(y_0)})$

What shall I do ?  Should I need to construct ring isomorphisms between rings?
For example, an isomorphism $\mathbb{C}[x_0,x_1]_{(x_0x_1)}$  $\cong$  $\mathbb{C}[x_0,x_1]_{(x_0x_1)}$, obviously, we can find a trivial isomorphism, but is such isomorphism satisfies the "compatibility" requirement?
Thank you very much!!!
Answer: The best  description of $\mathbb F_1$ is that it is just the blow-up of $\mathbb P^2$ at a point $P\in \mathbb P^2$, i.e $ \mathbb F_1=\tilde {\mathbb P^2}$.
The exceptional curve $E\subset \tilde {\mathbb P^2}$ of the blow-up is the basis of the fibration $\pi:\mathbb F_1\to E=\mathbb P^1$ and the fibres $\tilde L$ of $\pi$ are the strict transforms of the lines $L\subset \mathbb P^2$  through $P$.
The exceptional curve $E$ corresponds to the quotient line bundle $\mathcal O$ in $\mathbb P(\mathcal O\oplus \mathcal O (1))$
If you make the blow-up explicit you will find  $\mathbb F_1$  embedded in $\mathbb P^2_{x:y:z}\times \mathbb P^1_{u:v}$ as the surface with equation $uy-vz=0 $ ( $\mathbb P^2_{x:y:z}$ has been blown up at $P=(1:0:0))$ .
The morphism $\pi_1$ sends the point of $((x:y:z), (u:v))\in \mathbb F_1$ to $(u:v)\in \mathbb P^1$ .


How to add custom submit logic to search_block_form?

Question: I want to alter the input typed into the default search block in a way that when users search for "möp" (with a German umlaut) the search should be broadened to "möp OR moep" automatically.
So I simply tried to append a custom form submit to the search_block_form and simply expand the string by a certain logic. But then I found out that the search_block_form seems to be a little bit special. In core/modules/search/src/Form/SearchBlockForm.php I found the following comment.

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // This form submits to the search page, so processing happens there.
  }

My question now is: Where do I actually add the logic exactly if not in the form submit? I don't find any redirect or controller that would help here. Could you please point me in the right direction? Or maybe, you even have a better idea than appending the logic this way?

I removed the D8 tag as I guess the logic behind this is pretty equal amongst all common Drupal versions.
Comment: Submit handler is in  core/modules/search/src/Form/SearchPageForm.php.

Also Plugins with additional search parameters will need to provide their
 own form submit handler to replace this.
Comment: @sarika - I see it and can change it when I hack the code in the search module. Can you give me a rough outline on how to override this from a custom module?
Answer: You can do this in hook_search_preprocess():

Preprocess text for search.
This hook is called to preprocess both the text added to the search
  index and the keywords users have submitted for searching. The same
  processing needs to be applied to both so that searches will find
  matches.

This is not part of the preprocess in theming. This hook is called directly from the search module. Btw. German umlauts are already replaced by default.
Comment: Brilliant! Yeah, German Umlauts are already replaced by their equivalent letters without the dots. But the equivalent with the e appended to it is missing, as far as I observed it.
Comment: Hm, this function doesn't seem to do what it's supposed to do. Even the sample code on the function's page doesn't return the proposed output. Filed an issue for now https://www.drupal.org/node/2863687
Answer: I am not certain if this will help, but I found from the module documentation the following

search_invoke_preprocess() is deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Use a custom implementation of SearchTextProcessorInterface instead. See https://www.drupal.org/node/3078162

According to which preprocessing is moved to an internal method https://www.drupal.org/project/drupal/issues/3075703
I guess the last resort I found was creating a preprocess plugin as described in
https://www.drupal.org/docs/8/modules/search-api/getting-started/processors
Answer: As hook_preprocess_search() currently is not preprocessing (issue here) I found a workaround for now. In the end I had to have the logic in two places.
First, I created a custom block that contains a custom form that roughly mimics the search block form by sending/redirecting the search string (after my desired preprocessing) to the search page. That's how my submit function looks like.
public function submitForm(array &$form, FormStateInterface $form_state) {

  $input = $form_state->getValue('MYTEXTFIELD');

  // Trim whitespaces.
  $input = trim($input);
  $input = preg_replace('/\s+/', ' ', $input);

  // Rewrite search string to match my logic.
  // Searching for 'Müller' rewrites to 'Müller OR Mueller'
  $processed = _rewrite_search_string($input);

  // The rest now is routine as Drupal replaces spaces with plus
  // signs between two words in a multiple word string.
  // Let's do the same.
  $keys         = explode(' ', $processed);
  $max          = sizeof($keys);
  $search_query = '';

  if ($max == 1) {
    $search_query = $keys[0];
  }

  else {
    for ($i = 0; $i < $max - 1; $i++) {
      $search_query .= $keys[$i] . '+';
    }
    $search_query .= $keys[$max - 1];
  }

  // Finally, redirect to the search page with the expected
  // query pattern. For example 'Müller+OR+Mueller'.
  $url = Url::fromUserInput('/search/content?keys=' .
    $search_query);
  $form_state->setRedirectUrl($url);

}

Second, the same logic but in a different way needed to get appended to the real 'search_form' on the search page. So I added a custom submit function that looks the same as the original search form submit function except for the little addition that adds the desired logic.
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'search_form') {

    $form['#submit'][] = 'MYCUSTOMSUBMIT';
  }
}

function MYCUSTOMSUBMIT(&$form, FormStateInterface $form_state) {

  $input = $form_state->getValue('keys');

  // Here the same as above. 'Müller' gets rewritten to 'Müller OR Mueller'.
  $processed = _rewrite_search_string($input);

  $query['keys'] = $processed;

  // Rest is just c/p.
  $route = 'search.view_' . $form_state->get('search_page_id');
  $form_state->setRedirect(
    $route,
    [],
    ['query' => $query]
  );
}

As soon as hook_search_preprocess() gets fixed I mark @4k4's answer as the correct one.


Erro 242 ao consumir NfeDownloadNF

Question: Estou tentando consumir o serviço de download de NFE na fazenda:
https://www.sefazvirtual.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx
mas tenho obtido o seguinte erro:

ERRO: 242
  Motivo: Rejeicao: Elemento nfeCabecMsg inexistente no SOAP Header

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
    <soap:Body>
        <nfeDownloadNFResult xmlns=\"http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF\">
            <retDownloadNFe versao=\"1.00\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">
                <tpAmb>1</tpAmb>
                <verAplic>SVAN_2.1.1</verAplic>
                <cStat>242</cStat>
                <xMotivo>Rejeicao: Elemento nfeCabecMsg inexistente no SOAP Header</xMotivo>
                <dhResp>2015-11-03T12:18:06</dhResp>
            </retDownloadNFe>
        </nfeDownloadNFResult>
    </soap:Body>
</soap:Envelope>

O erro é peculiar porque conforme é possível observar na mensagem abaixo a estrutura do cabeçalho está na mensagem.
A mensagem que tenho enviado é :
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>
        <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/nfeDownloadNF">
            <cUF>31</cUF>
            <versaoDados>3.10</versaoDados>
        </nfeCabecMsg>
    </soap:Header>
    <soap:Body>
        <nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">
            <downloadNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="3.10">
                <tpAmb>1</tpAmb>
                <xServ>DOWNLOAD NFE</xServ>
                <CNPJ>[NUMERO DO CNPJ]</CNPJ>
                <chNFe>[CHAVE DA NOTA FISCAL]</chNFe>
            </downloadNFe>
        </nfeDadosMsg>
    </soap:Body>
</soap:Envelope>

Removi todos os espaços conforme é solicitado (já consumo alguns outros serviços com sucesso)
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = byteData.Length;

O certificado tenho certeza que está correto também.
Ressalto que consigo consumir outros serviços.
WSDL do serviço
<wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">
    <wsdl:types>
        <s:schema elementFormDefault="qualified" targetNamespace="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">
            <s:element name="nfeDadosMsg">
                <s:complexType mixed="true">
                    <s:sequence>
                        <s:any/>
                    </s:sequence>
                </s:complexType>
            </s:element>
            <s:element name="nfeDownloadNFResult">
                <s:complexType mixed="true">
                    <s:sequence>
                        <s:any/>
                    </s:sequence>
                </s:complexType>
            </s:element>
            <s:element name="nfeCabecMsg" type="tns:nfeCabecMsg"/>
            <s:complexType name="nfeCabecMsg">
                <s:sequence>
                    <s:element minOccurs="0" maxOccurs="1" name="versaoDados" type="s:string"/>
                    <s:element minOccurs="0" maxOccurs="1" name="cUF" type="s:string"/>
                </s:sequence>
                <s:anyAttribute/>
            </s:complexType>
        </s:schema>
    </wsdl:types>
    <wsdl:message name="nfeDownloadNFSoapIn">
        <wsdl:part name="nfeDadosMsg" element="tns:nfeDadosMsg"/>
    </wsdl:message>
    <wsdl:message name="nfeDownloadNFSoapOut">
        <wsdl:part name="nfeDownloadNFResult" element="tns:nfeDownloadNFResult"/>
    </wsdl:message>
    <wsdl:message name="nfeDownloadNFnfeCabecMsg">
        <wsdl:part name="nfeCabecMsg" element="tns:nfeCabecMsg"/>
    </wsdl:message>
    <wsdl:portType name="NfeDownloadNFSoap">
        <wsdl:operation name="nfeDownloadNF">
            <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
                Serviço destinado ao atendimento de solicitações de download de Notas Fiscais Eletrônicas por seus destinatários.
            </wsdl:documentation>
            <wsdl:input message="tns:nfeDownloadNFSoapIn"/>
            <wsdl:output message="tns:nfeDownloadNFSoapOut"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="NfeDownloadNFSoap" type="tns:NfeDownloadNFSoap">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="nfeDownloadNF">
            <soap:operation soapAction="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF/nfeDownloadNF" style="document"/>
            <wsdl:input>
                <soap:body use="literal"/>
                <soap:header message="tns:nfeDownloadNFnfeCabecMsg" part="nfeCabecMsg" use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:binding name="NfeDownloadNFSoap12" type="tns:NfeDownloadNFSoap">
        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="nfeDownloadNF">
            <soap12:operation soapAction="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF/nfeDownloadNF" style="document"/>
            <wsdl:input>
                <soap12:body use="literal"/>
                <soap12:header message="tns:nfeDownloadNFnfeCabecMsg" part="nfeCabecMsg" use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap12:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="NfeDownloadNF">
        <wsdl:port name="NfeDownloadNFSoap" binding="tns:NfeDownloadNFSoap">
            <soap:address location="https://www.sefazvirtual.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx"/>
        </wsdl:port>
        <wsdl:port name="NfeDownloadNFSoap12" binding="tns:NfeDownloadNFSoap12">
            <soap12:address location="https://www.sefazvirtual.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

INFORMAÇÃO NA DOCUMENTAÇÃO DO SERVIÇO
POST /NfeDownloadNF/NfeDownloadNF.asmx HTTP/1.1
Host: www.sefazvirtual.fazenda.gov.br
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF/nfeDownloadNF"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">
      <versaoDados>string</versaoDados>
      <cUF>string</cUF>
    </nfeCabecMsg>
  </soap:Header>
  <soap:Body>
    <nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">xml</nfeDadosMsg>
  </soap:Body>
</soap:Envelope>

Alguém poderia me indicar o erro?
Comment: Olhando, sem testar, a única coisa que vejo de diferente no *header* da SOAP *message* é o *namespace*, que está `http://www.portalfiscal.inf.br/nfe/wsdl/nfeDownloadNF` enquanto deveria ser `http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF`.
Comment: Esse web service é de onde, especificamente? [Procure aqui e não achei](http://www.nfe.fazenda.gov.br/portal/webservices.aspx).
Comment: Este é um dos Webservices do SPED, especificamente o serviço responsável por baixar uma nota fiscal especifica pela chave.
Comment: Então, tentei conseguir o WSDL pra conferir se sua mensagem está correta, mas não consegui. De qual site você pegou esse link?
Comment: Muito obrigado pelo ajuda. O link eu peguei em alguns exemplos pela web, mas o WSDL pode ser obtido no endereço :
https://www.sefazvirtual.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx?wsdl

Todavia se você não conseguir acessar, pode ser alguma restrição quanto a certificados que devem estar instalados no browser

Vou copiar abaixo o conteúdo
Comment: Foi isso que tentei. Deu erro 403. Não faz sentido exigir um certificado para conseguir a WSDL.
Comment: Realmente não faz nenhum sentido, mas parece que é isso que eles fazem.... :( todavia copiei o conteúdo da pagina com o WSDL para minha pergunta.
Comment: Bruno César realmente, o problema não foi resolvido, mas o namespace estava errado. O erro mudou estou tratando.
Answer: Consegui fazer funcionar, vou relatar aqui todos os problemas que tive para ajudar alguém que esteja na mesma situação.
Nota é melhor usar a URL:
https://www.nfe.fazenda.gov.br/NfeDownloadNF/NfeDownloadNF.asmx
A Mensagem deveria ser a seguinte:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>
        <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">
            <cUF>31</cUF>
            <versaoDados>1.00</versaoDados>
        </nfeCabecMsg>
    </soap:Header>
    <soap:Body>
        <nfeDadosMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF">
            <downloadNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.00">
                <tpAmb>1</tpAmb>
                <xServ>DOWNLOAD NFE</xServ>
                <CNPJ>[CNPJ]</CNPJ>
                <chNFe>[CHAVE]</chNFe>
            </downloadNFe>
        </nfeDadosMsg>
    </soap:Body>
</soap:Envelope>

As principais pontos são:

Hoje dia 04/11/2015 o serviço está na versão 1.00, diferente do que é indicado no site da fazenda
O namespace deveria ser http://www.portalfiscal.inf.br/nfe/wsdl/NfeDownloadNF e não http://www.portalfiscal.inf.br/nfe/wsdl/nfeDownloadNF
Não se esqueça de remover os caracteres em branco, a mensagem não pode ter caracteres de formatação.
Você só vai conseguir fazer download de notas que tenham manifestação do usuário.

Erro 242 ao consumir NfeDownloadNF


How do i find the order of a permutation in the group $S_n$

Question: How can i define the order of a permutation without doing the permutation again and again? Example: say $σ=(1-->2,2-->3,3-->5,4-->1,5-->4)$ in $S_5$.
Comment: Some friendly advice: do not ask a second question when you should ask a *new*@ question (new post). It makes the answers you received seem incomplete. If you have questions about how to find the inverse of a permutation, you need to first search the site to find one of the many duplicate questions on that, or, if you cannot find a duplicate, post it as a new question.
Comment: Im really sorry for the re editing.
Comment: No problem, Manolis. As I said, I was offering some friendly advice.
Comment: Advice is taken.I will do that.
Answer: Write the permutation in cycle notation (and expressed as the product of disjoint cycles).
For each cycle in the permutation determine its length. (If there is only one cycle of length greater than $1$, then the order of the permutation is the length of that cycle. If all cycles in a permutation are of length one, it is necessarily the identity permutation, and has order $1$.
Calculate the least common multiple of all cycle lengths.
The result is the order of the permutation.
Example: Let $\tau =\begin{pmatrix} 1& 2& 3& 4& 5\\ 2& 4 & 5 & 1& 3\end{pmatrix}$
Written as the product of disjoint cycles gives us $\tau = (1, 2, 4)(3, 5) \in S_5$.
Then the lengths of the cycles, from left to right, are $3, 2$.
$\operatorname{lcm}(3, 2) = 6$.
The order of $\tau$ is equal to $6$.
Answer: The order is the least common multiplier of the length of all circles in the
 circle notation of the permutation.
Comment: you mean lcm of the lengths of all the "cycles" in the "disjoint cycle" representation of the permutation.
Comment: Can you o an example pease. Say $S5$ $$σ=(1-->2,2-->3,3,-->5,4-->1,5-->4)$$
Comment: @manolis that has one cycle of length 5, so the order is 5.
Comment: The cycle notation is (12354) in this case.
Answer: The element that you have listed isn't  permutation because it sends both $4$ and $5$ to $1$. If, however, you had $\sigma = (1235) \in S_5$, then you can find the order by simply multiplying the permutation by itself:
$$\begin{align}
\sigma^1 &= (1235) \\
\sigma^2 &= (13)(25) \\
\sigma^3 &= (1532) \\
\sigma^4 &= (1).
\end{align}
$$
So the order of $\sigma$ is $4$.
This, obviously, only works when the group is relatively small.

If you wanted to ask about the order of $\sigma = (12354)$, then just star
$$\begin{align}
\sigma^1 &= (12354) \\
\sigma^2 &= (13425) \\
\sigma^3 &= \dots.
\end{align}
$$

In case you are not familiar with the notation, $(1235)$ is the permutation that
$$\begin{align}
1 &\longrightarrow 2 \\
2 &\longrightarrow 3 \\
3 &\longrightarrow 5 \\
5 &\longrightarrow 1\\
4 &\longrightarrow 4.
\end{align}
$$
Comment: sorry i meant 5-->3
Comment: @ManolisLyviakis: It still doesn't work.
Comment: ******5--->4 sorry


Error: cannot find symbol class Builder (using Retrofit)

Question: Been following this Retrofit tutorial, but I am completely stuck on this issue:

Error:(12, 46) error: cannot find symbol class Builder

Here's my file, RestAdapter.java:
package com.myapp.jobapp;

import retrofit.RestAdapter.Builder;
import retrofit.RestAdapter;

public class RestAdapter {
   public static final String BASE_URL = "http://api.myservice.com";
   RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(BASE_URL)
        .build();
}

Here's what's in my build.gradle:
dependencies {
    compile 'com.squareup.retrofit:retrofit:1.9.0'
}

Here's the stacktrace:
Executing tasks: [:app:compileDebugSources, :app:compileDebugAndroidTestSources]

Configuration on demand is an incubating feature.
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72200Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42200Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:compileDebugJava

/app/src/main/java/com/myapp/jobapp/RestAdapter.java:12: error: cannot find symbol
    RestAdapter restAdapter = new RestAdapter.Builder()
                                             ^
  symbol:   class Builder
  location: class RestAdapter
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugJava'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:305)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.BuildModelAction.run(BuildModelAction.java:43)
    at org.gradle.tooling.internal.provider.BuildModelAction.run(BuildModelAction.java:30)
    at org.gradle.tooling.internal.provider.ConfiguringBuildAction.run(ConfiguringBuildAction.java:119)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:47)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:35)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:24)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.StartStopIfBuildAndStop.execute(StartStopIfBuildAndStop.java:33)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:71)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:69)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:69)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:70)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.DaemonHygieneAction.execute(DaemonHygieneAction.java:39)
    at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:46)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
    at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details.
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:44)
    at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:97)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:50)
    at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:36)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:34)
    at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25)
    at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:158)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:138)
    at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:92)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:235)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:222)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 55 more

BUILD FAILED

Total time: 1.351 secs

Would appreciate any help on this
Comment: Do you have the import of the RestAdapter in your class? That is: import retrofit.RestAdapter;
Comment: I tried `import retrofit.RestAdapter;` and that did not solve it
Comment: When you put this import in your code, the IDE recognizes it? For example, you can hit CTRL and click on this import?
Comment: Yup, it is grayed out and is an unused import statement
Comment: Strange! Does your project run properly if you don't use anything of the retrofit?
Comment: Yup, everything else works -- just this `Builder` that is giving the 1 error
Comment: have you tried the answer?
Answer: I've tried your code, and the Buider is not recognized this way you are doing.
Try this:
public static final String BASE_URL = "http://api.myservice.com";

public RestAdapter providesRestAdapter(Gson gson) {
    return new RestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .build();
}

Of course, this method goes inside some class. Think this class as a Module/RestClient where you configure your api. So, you can name this class AppModule, RestClient or another name you prefer.
Below, some tutorials that can be useful:

A smart way to use Retrofit
Durable Android REST Clients
REST Interfaces and Android
Implementing an Android REST Client using Retrofit
Comment: Thanks -- this solution works! I would upvote you, but unfortunately I do not have enough reputation


jsmin+ causes high server load in drupal 6

Question: I have the JavaScript aggregator module on my site. Whenever I check the jsmin+ checkbox (so it uses jsmin+ instead on jsmin), the server becomes really slow. I have to use jsmin+, instead of jsmin, because jsmin doesn't group JavaScript files correctly, and I get JavaScript errors (Ckeditor and Vertical Tab are breaking).

Drupal 6.20
JavaScript aggregator 1.6
jsmin+ 1.4
Answer: Give AdvAgg a try. It works around the limitations of jsmin+
Comment: I'm using drupal 6 and I installed the JSMIN+ in my hosting and don't know how to use in my site, because Pagespeed suggest me to minify the javascript file after enabling AdvAgg. Please help me! my issue is same like this https://drupal.org/node/1842454


Dynamic Livewire Listeners : Listener does not listen for triggered event

Question: I'm having trouble with dynamic Livewire listeners. I'm trying to use two components on the same page, where one component has an input field and the other is a modal that is supposed to fire an event on the second input component when a button is clicked.
Here is my first component, Input:
class Input extends Component {
 public $name; public $type; public $multiple; public $selectedMedias; public $previewFiles;
public $listeners = [];

public function mount($name, $type, $multiple, $selectedMedias = '')
{
    $this->name = $name;
    $this->type = $type;
    $this->multiple = $multiple;

    if ($selectedMedias) {
        $this->selectedMedias = explode(',', $selectedMedias);
        $this->previewFiles = $this->getFileData($this->selectedMedias);
    }

    $this->listeners = ['updateSelectedMedias:'.$this->name => 'updateSelectedMedias'];
}

public function render()
{
    return view('livewire.dashboard.medias.input');
}

public function updateSelectedMedias($selectedMedias)
{
    $this->selectedMedias = $selectedMedias;
    $this->previewFiles = $this->getFileData($this->selectedMedias);
    $this->emit('hideModal');
}

private function getFileData($ids)
{
    $medias = Media::whereIn('id', $ids)->get();

    $data = $medias->map(function ($item) {
        return [
            'id' => $item->id,
            'url' =>  $item->getUrl(),
            'name' => $item->file_name,
        ];
    });

    return $data->toArray();
}}

Here is my second component, the modal, which is supposed to fire an event on the second input component:
class Modal extends Component { public $name; public $selectedMedias;
public function mount($name)
{
    $this->name = $name;
}

public function addMedias()
{
    $this->emitUp('updateSelectedMedias:'.$this->name, $this->selectedMedias);
}

public function render()
{
    return view('livewire.dashboard.medias.modal');
}

The event is fired on the first input component but not on the second input component on the same page. Here is the Livewire Blade template code:
`<livewire:dashboard.medias.input name="images" type="image" multiple="true" selected-medias="1,2" />

<livewire:dashboard.medias.input name="images2" type="image" multiple="true" selected-medias="5" />`

even if i'm getting the correct response from the second component !
response: { event: "updateSelectedMedias:images2", params: [["5"]], ancestorsOnly: true }
Answer: Possible solution :
Instead of using dynamic listeners, I just add an extra parameter to the emit function to pass the name and check it in the other component. In the modal component, modify the addMedias function like this:
public function addMedias()
{
    $this->emit('updateSelectedMedias', $this->name, $this->selectedMedias);
}

in the Input component :
protected $listeners = ['updateSelectedMedias'];

public function updateSelectedMedias($inputname, $selectedMedias)
{
    if ($inputname == $this->name) {
        $this->selectedMedias = $selectedMedias;
        $this->previewFiles = $this->getFileData($this->selectedMedias);
        $this->emit('hideModal');
    }
}


Question about approaching a delta epsilon argument for continuity

Question: So I was working on a question in Folland's Advanced Calculus (specifically section 1.3 Q5) and I know that I have to show that this function is continuous everywhere except at the origin

5. Let $f(x, y) = \frac{y(y - x^2)}{x^4}$ if $0 < y < x^2$, $f(x, y) = 0$ otherwise. At which point(s) is $f$ discontinuous?

I was able to do this problem by the limit definition of continuity and the fact that it was composed of continuous functions (for when $x \neq 0$) and I was able to show that this function is discontinuous at the origin as well, but I wanted to try to approach this problem using a delta epsilon argument for the two endpoints ($y = 0, y = x^2$). I have not been able to get a good idea of how to go about getting a $\delta$ for this problem. I have thought of bounding it (specifically $\frac{y-x^2}{x^4}$) but that didn't yield anything helpful nor have I been able to reduce it to the Euclidean norm. Any help would be greatly appreciated.
Comment: I'm not sure I follow exactly what you're trying to do. Could you perhaps clarify this? I might be able to help you then
Comment: I want to specifically use the delta epsilon definition of continuity to show that $\frac{y(y-x^2)}{x^4}$ is continuous for $y = x^2$ and $y = 0$. So, $|x - a| < \delta \rightarrow |\frac{y(y-x^2)}{x^4}| < \varepsilon$ (for the case when $y = 0$).
Answer: Case $(1)$
Since $f(x_0,0)=0$ for $x \neq 0$, to prove continuity of $f(x,y)$ at $(x_0,0)$, we need to show that
For any $\varepsilon \gt 0$, there exists $\delta \gt 0$ s.t.
$$\sqrt {(x-x_0)^2+y^2} \lt \delta \implies \left\lvert \frac{y(y-x^2)}{x^4}\right\rvert \lt \varepsilon.$$
Notice that if $\color{red}{\delta =\min \left( \frac{\left\lvert x_0 \right\rvert}{2},  \frac{\left\lvert x_0 \right\rvert^2}{4}, \frac{\left\lvert x_0 \right\rvert^2\varepsilon}{40} \right)}$, then
$$\sqrt {(x-x_0)^2+y^2} \lt \delta $$
$$\implies \sqrt {(x-x_0)^2+y^2} \lt \frac{\left\lvert x_0 \right\rvert}{2} $$
$$\implies \left\lvert x-x_0 \right\rvert \lt  \frac{\left\lvert x_0 \right\rvert}{2} $$
$$\implies \frac{\left\lvert x_0 \right\rvert}{2} \lt x \lt  \frac{3\left\lvert x_0 \right\rvert}{2}$$
We also have
$$\sqrt {(x-x_0)^2+y^2} \lt \delta $$
$$\implies \sqrt {(x-x_0)^2+y^2} \lt \frac{\left\lvert x_0 \right\rvert^2}{4}$$
$$ \implies \lvert y\rvert  \lt \frac{\left\lvert x_0 \right\rvert^2}{4}$$
Also
$$\sqrt {(x-x_0)^2+y^2} \lt \delta $$
$$\implies \sqrt {(x-x_0)^2+y^2} \lt \frac{\left\lvert x_0 \right\rvert^2\varepsilon}{40}$$
$$  \implies \lvert y\rvert  \lt \frac{\left\lvert x_0 \right\rvert^2 \varepsilon}{40}$$
Therefore
\begin{align}
 \left\lvert f(x,y)-f(x_0,0) \right\rvert
& = \left\lvert \frac{y(y-x^2)}{x^4}\right\rvert \\
& \leq \frac{\left\lvert y \right\rvert (\left\lvert y \right\rvert + \left\lvert x \right\rvert^2)}{\left\lvert x \right\rvert^4} \\
& \leq \frac{ \left(\frac{\left\lvert x_0 \right\rvert^2 \varepsilon}{40} \right) ( \frac{\left\lvert x_0 \right\rvert^2}{4} + \frac{\left\lvert 9x_0 \right\rvert^2}{4})}{\frac{\left\lvert x_0 \right\rvert^4}{16}} \\
& = \varepsilon
\end{align}
$\therefore f(x,y)$ is continuous at $(x_0, 0)$ where $x_0 \neq 0.$
$$$$
Case $(2)$
For any point $(x_0, y_0)$ where $y_0=x_0^2$ and $x_0 \neq 0$
Case $(i)$ $x_0 \gt 0$
For any $\varepsilon \gt 0$,
take $$\color{red}{\delta = \min \left(\frac{x_0}{2}, \frac{y_0}{2}, \varepsilon' \right)}$$ where $$\color{red}{\varepsilon' = \min \left(1, \frac{x_0}{2}, \frac{y_0}{2}, \frac{x_0^4 \varepsilon}{48(1+x_0)y_0} \right)}$$
Then similar to case $(1)$, when $\sqrt {(x-x_0)^2+y^2} \lt \delta \leq \varepsilon'$, we have
$$x_0-\varepsilon' \lt x \lt x_0+\varepsilon'$$
$$x_0^2-2x_0\varepsilon'+\varepsilon'^2 \lt x^2 \lt x_0^2+2x_0\varepsilon'+\varepsilon'^2   \tag{1}$$
Similarly we have
$$y_0-\varepsilon' \lt y \lt y_0+\varepsilon'  \tag{2}$$
From $(1), (2)$,  we have
$$y_0-x_0^2-\varepsilon'\left(1+2x_0+ \varepsilon'\right) \lt y-x^2 \lt y_0-x_0^2+\varepsilon'\left(1+2x_0- \varepsilon'\right)$$
$$-\varepsilon'\left(1+2x_0+ \varepsilon'\right) \lt y-x^2 \lt \varepsilon'\left(1+2x_0- \varepsilon'\right)$$
Since $\varepsilon' \leq 1,$
$$\lvert y-x^2\rvert \lt \varepsilon'\left(2+2x_0 \right) $$
Also note that
$$\sqrt {(x-x_0)^2+y^2} \lt \delta \leq \frac{x_0}{2} \implies \frac{x_0}{2} \lt x \lt \frac{3x_0}{2}$$
and
$$\sqrt {(x-x_0)^2+y^2} \lt \delta \leq \frac{y_0}{2} \implies \frac{y_0}{2} \lt y \lt \frac{3y_0}{2}$$
Therefore
\begin{align}
 \left\lvert f(x,y)-f(x_0,y_0) \right\rvert
& = \left\lvert \frac{y(y-x^2)}{x^4}\right\rvert \\
& = \frac{\left\lvert y \right\rvert \left\lvert y - x^2 \right\rvert}{\left\lvert x \right\rvert^4} \\
& \leq \frac{ \left(\frac{3 y_0  }{2} \right) \left( 2+2 x_0 \right)\varepsilon' }{\frac{ x_0^4 }{16}} \\
& \leq \frac{48(1+x_0)y_0}{x_0^4} \cdot \frac{x_0^4 \cdot \varepsilon}{48(1+x_0)y_0} \\
& = \varepsilon
\end{align}
Therefore $f(x,y)$ is continuous at $(x_0, y_0)$ where $x_0 \gt 0$ and $y_0=x_0^2.$
The case $x_0 \lt 0$ and $y_0=x_0^2$ can be dealt with similarly.
Comment: Thank you so much!


Why do frequencies that follow a base two logarithmic relationship sound the "same"?

Question: We know that frequencies that follow a base two logarithmic relationship sound as the same tone. This seems to be one of the fundamental principles that underlies music theory. For example, frequencies of 220, 440, 880, 1760, ... all sound as the same tone: 'A'.
<code>f_n = f_0 • 2^n
</code>
After searching through several different music theory sources, I have not found a convincing physical or mathematical explanation for this phenomenon. Many sources say that human's perceive pitch on a logarithmic/exponential scale, or that the waves 'line up' in a way that creates a sense of 'sameness' between the two frequencies.
It is certainly clear that humans do perceive pitch in a logarithmic manner. My question: why? There must be a physical reason for why humans perceive frequencies that follow such a well defined mathematical relationship as being of the same tone.
Comment: Um, they DO NOT SOUND THE SAME! Who ever told you that? C5 DOES NOT sound the same as C4, C3, C8, C12, etc.  The *reason* why they sound so similar is because they are so similar, because the vibrations are exactly some power of 2. It is not physical, it is mathematical. There is no way to tell the difference between them. Could you tell the difference between to perfect sinusoidals at the same frequency? Of course not. Well, when you compare a note and it's octave they differ the least.
Comment: So if you add a metric to R to get "pitch space" then octaves would be the closest notes. It is sorta like p-adics. Ck is closest to Cn. Why? Because Any other note Xn when compared with Ck will produce "intermodulation distortion", e.g, 320hz and 353hz creates all kinds "extra" frequencies". Why? Because our brains can deduce all the combinations when it filters things. Take a metronome at 100bpm, we also can deduces 200, 400, 300, 50, 75, etc but the further the ratio the less likely to be(and it's imaginary anyways). Take another one though, 125bpm, now what?
Comment: well, we have two quick pulses then a space. Our brain will fill in the space with 25bpm to make a periodic sound. Hence 100 + 125 will sound much faster, but do it with 130 and it will sound even faster when you fill in the gaps because the ratio is not as simple(or it might sound slower in triplets). Our brains, for some reason, tries to simplify and align things probably to reduce complexity so it can understand things...  so it tries to minimize certain things(I don't think anyone has figured out how it actually works so but we know what it does).
Comment: Our brains work a certain way, it is mathematical, but octaves do not sound the same, they are clearly different, it is just that the mathematical nature of the brain represents sound on a manifold where they are the closest notes. I believe this is probably due to the overtone series, since that is what we are conditioned to by nature and mathematics. So octaves are the closest together due to the OT series which we hear in almost everything and our brains pick up on that connection and treats octaves as the most similar pitches.
Answer: There are lots of papers about octave equivalence. Some lean toward a cultural explanation, others (citing birds songs) prefer a physiological explanation.
https://www.quantamagazine.org/perceptions-of-musical-octaves-are-learned-not-wired-in-the-brain-20191030/
https://www.researchgate.net/publication/330865079_Octave_equivalence_perception_is_not_linked_to_vocal_mimicry_Budgerigars_fail_standardized_operant_tests_for_octave_equivalence
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5479468/
These papers prefer a cultural explanation.
Comment: I swear I've read that at least some non-human primates also respect octave equivalence.
Answer: I do not believe that there is a convincing argument for this.  In fact recent research in cultural anthropology suggests that our tendency to hear octaves as "the same note" is due to cultural brain washing.  I cannot recall or locate the article at this moment (I will edit when I do) but there was a recent article that introduced data taken by interviewing people from some indigenous tribe that is not influenced by Western culture and they simply do not hear octave as the same note.  And they're not in reality.
I am not sure why we do this except to say that it must have had some evolutionary advantage like not misinterpreting calls from people when they raise their voice, or something.
Comment: Although as I recall that article, the general tone was "Wow, there are actually humans who don't have octave equivalence, this is very surprising"
Comment: Could you point us to some of this research?  From what I know, octave equivalence is almost the rule, especially in cultures where men and women sing together.  It's unlikely to be a coincidence that the mathematically simplest ratio after the unison, 1/1, is the octave, 1/2.
Comment: @ScottWallace, here is an article. https://www.quantamagazine.org/perceptions-of-musical-octaves-are-learned-not-wired-in-the-brain-20191030/  I do not understand your comment though.  Are you suggesting that light of double frequency would be seen as the same color?  Maybe, after all we cannot see an octave worth of the EM spectrum.
Comment: I'm suggesting, and this is far from original, that the simpler the ratio, the more consonant/seen as identical intervals are.  And I don't think the comparison with the EM spectrum applies to sound usefully, since our color receptors work completely differently than our ears do.


Can TLS certificates be reused on different servers running on same domain/different ports?

Question: I'm a programmer, not a system admin. I have a DreamHost VPS that I screw around with for my personal Website and a number of side projects that are typically just experiments in multimedia through HTML5. Nothing particularly serious, and they all run client-side.
I've started to include signed certificates on my sites as A) it's just good for users, B) I might consider setting up user accounts for some multiplayer features in the nebulous future, and C) it also allows me to request access to certain HTML5 APIs once and only once. For example: speech recognition needs to be reconfirmed every time it is started on HTTP, and it automatically stops listening after a minute. But by using HTTPS, I can make it restart listening without the user needing to reconfirm it; the first confirmation was enough.
I have two separate servers running:

Apache on port 80: https://seanmcbeth.com
a Node.js-based, custom Web server on port 8080: https://seanmcbeth.com:8080.

I keep it this way because the Apache server was already running, it works well, and I'm still very new to Node. I keep Apache running to serve the static pages on my site that serve as a portfolio for my work and just trust that DreamHost has it configured far better than I'd be able to do on my own. The Node server falls over on occasion, and sometimes I don't notice, purely my fault with programming. Keeping the two separate seems like a good idea for now.
For Apache, DreamHost configured the certificates themselves, and I have the htaccess rules setup to redirect HTTP traffic to HTTPS. That works fine.
For the Node server, I copied the certificate and private key out of the DreamHost CPanel, because I couldn't figure out where they were located to use the same copies that Apache uses. I did not copy the intermediate certificate, as I couldn't figure out what to do with it. The Node server also does not automatically redirect HTTP traffic, but that's probably just me not yet having even researched the problem.
The primary issue I'm writing about today is that sometimes, when I type in the address directly for the the Node server on my smartphone (Android 4.4.2: Chrome 37), it tells me the site is "not secure". I then have to jump through hoops to get around it and go on anyway. This never happens on my PC (Windows 7: Chrome 37, Firefox 31, or IE 11) and it never happens on the smartphone if I use a link on a page served by the Apache server to go to the Node server. I'm posting here because I think this is more of a configuration issue than a programming issue.
I'd be more specific on the "not secure" part, but I can't seem to replicate the problem now. I'm concerned that I might have flagged the site as an exception and it now just blanket confirms it, but any new users are going to see the warning.
Answer: You don't have the intermediate certificate installed on the 8080 port. Many (most?) certificates nowadays aren't directly signed by a trusted root certificate, they're signed by an intermediate certificate which in turn is signed by a trusted root certificate. The SSL-enabled service must then supply both the intermediate and the "end" certificate in order for clients to verify that the certificate is valid and trusted.
You can check it with the "openssl s_client host:port" command, that output a lot of info but here are the relevant differences for your sites:
<code>$ openssl s_client -connect seanmcbeth.com:443
[...]
---
Certificate chain
 0 s:/OU=Domain Control Validated/OU=Provided by New Dream Network, LLC/OU=DreamHost Basic SSL/CN=seanmcbeth.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=PositiveSSL CA 2
 1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=PositiveSSL CA 2
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
---
[...]

$ openssl s_client -connect seanmcbeth.com:8080
[...]
---
Certificate chain
 0 s:/OU=Domain Control Validated/OU=Provided by New Dream Network, LLC/OU=DreamHost Basic SSL/CN=seanmcbeth.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=PositiveSSL CA 2
---
</code>
See how the 8080 port doesn't have the AddTrust certificate in the chain.
Comment: +1 - You beat me to it. There's some good commentary for the OP at: http://qugstart.com/blog/node-js/install-comodo-positivessl-certificate-with-node-js/
Comment: Ah, that's perfect. I figured that was probably the case, but I hadn't yet seen anything about configuring the CA in Node. I should be able to handle this now. Thanks.