take only 9 chars after specific word in string

Question: I'm receiving from my app string of numbers, and I need to get them
but I don't know them
so in the string I have UID:
so search it in the string and then I need to take from the string 9 chars after the word "UID:" in the string
tried some and didn't word well
I just removing what I want and not extract it from the string
string id = txt.Substring(0, txt.LastIndexOf("UID:") + 9);

I know the string I need after UID: always have 9 chars
the out put I need to get
EXAMPLE:
UID: 994zxfa6q
I don't know what is it but I know its only have 9 chars.
Comment: Why would he use regex for such a simple implementation? Resulting in people needing to comprehend the problem he is trying to solve, and comprehend regex. That seems like he is adding complexity to code that is unnecessary.
Comment: @NathanWerry People love useless complexities :)
Comment: @NathanWerry I've recently started using RegEx but not in my code, only for an extremely fast replace in Notepad++. Hate reading it
Comment: @CamiloTerevinto, don't get me wrong. I love RegEx, and I love when it is necessary. But I also love clean code concepts, in which RexEx violates several principals of clean code. I love reading code that reads like a novel, and not someone smashing the number row with the shift key pressed, lol.
Comment: Why don't you use regex for this?
Comment: @CamiloTerevinto I work on enterprise scale software, so reading other peoples code is my every day, and I am getting thin grey hair because people learn a shiny new thing and over-implement it, just because it works.
Comment: Please check my answer at this post. https://stackoverflow.com/a/53798134/4934682
Answer: You definitely had the right idea. Almost had it.
string id = txt.Substring(txt.LastIndexOf("UID: ") + 5, 9);

Answer: I prefer not to have constants and length of constants hardcoded separate from each other. You need to have your starting index be the index of the searched string plus the size of the search string, and then your length should be the size of your id.
var uid = "UID: ";
string id = txt.Substring(txt.IndexOf(uid) + uid.Length, 9);

Answer: string GetUID(string input)
{
    const int uidLength = 9;
    const string uidMarker = "UID: ";
    var markerIndex = input.IndexOf(uidMarker);
    if(markerIndex==-1 || markerIndex + uidMarker.Length + uidLength > input.Length)
    {
        throw new ArgumentException("Input does not contain UID", nameof(input));
    }
    return input.Substring(markerIndex + uidMarker.Length, uidLength);
}

If I understand what you want, you can use this code (or something along those lines). Sorry, may have gotten it wrong as I'm far from PC right now. This code assumes that there is only one "UID:" substring in the input string.
Also String.IndexOf and String.Substring are nicely documented.
Comment: Thanks, I fixed it.
Answer: Your code is almost correct, but you have to remember that the first parameter of string.SubString is an index. So, you need to change:
string id = txt.Substring(0, txt.LastIndexOf("UID:") + 9);

to:
string id = txt.Substring(txt.LastIndexOf("UID:") + 4, 9);

Comment: Yep i know i was missing something there , thank you for the explain im a newbie :) Thank you alot you guys
Comment: This is missing the space after `:`, it should be `"UID: ") + 5`
Answer:     String txt = "UID: 994zxfa6q";
    int pFrom = txt.IndexOf("UID:") + 4;
    Console.WriteLine("pFrom = " + pFrom.ToString());
    int pTo = txt.LastIndexOf("UID:") + 14;
    Console.WriteLine("pTo= " + pTo.ToString());
    String result = txt.Substring(pFrom, pTo - pFrom);
    Console.WriteLine("result " + result);


Spectators involved in play

Question: In baseball, if a fielder reaches into the stands to attempt a catch, a spectator  has an equal right to try to catch the ball.
Is there any difference if the fielder is reaching over the fence into the other teams bullpen, and a member of the opposing team is the "spectator"?
Answer: From the official baseball rules (http://mlb.mlb.com/mlb/downloads/y2014/official_baseball_rules.pdf):
Rule 3.09:
"Players in uniform shall not address or mingle with spectators, nor sit in the stands before, during, or after a game. No manager, coach or player shall address any spectator before or during a game."
That seems to separate "players" from "spectators" pretty clearly, though neither term is defined in Rule 2.00 (Definitions).
The definition of Interference (Rule 2.00 - Definitions) says:
a) Offensive Interference is an act by the team at bat which interferes with, obstructs, impedes, hinders or confuses any fielder attempting to make a play.
Reaching into the stands is done at the player's own risk and no spectator interference can be called, but players in uniform but not currently active (say, on the bench or in the bullpen) are still players and I believe can still be called for Offensive Interference.
Therefore, I'd conclude that a player or coach in the bullpen may not interfere with a defensive player attempting to make a catch while reaching over the wall. If the bullpen had spectators in it for some reason (stand overflow, maybe?), the spectators could try to catch the ball, but you wouldn't have players/coaches in the bullpen then.
Comment: I agree. Plus when it comes to unwritten rules of baseball, if another team were to interfere, there would be some bean balls flying around.

Spectators involved in play


Two way communication through a HTTP proxy

Question: I'm trying to come up with the most appropriate way to make a two way socket connection through a HTTP proxy - lets say it's a telnet style protocol. Unfortunately I also need to support NTLM authentication (with the proxy) as well as Basic and Digest, in addition to any other future authentication mechanisms that I can't forecast.
If it was just basic and digest I'd handle the connection myself, but I really don't want to get stuck in the mire that is NTLM. Looking at the underlying AuthenticationManager API it looks very tied to HttpWebRequest so I can't leverage that functionality if I'm using a socket/tcpclient/whatever or even writing a new WebRequest derivation.
Playing around with HttpWebResponse yields a stream that can't be written, using the RequestStream after the response stream has been retrieved gives a concurrent io exception.
Having run through all the possibilities I can think of, I've come up with some nasty code that gets out the NetworkStream associated with a HttpWebRequest which allows two way communication:
<code>  .....
  HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  Stream str = resp.GetResponseStream();

  System.Type type = str.GetType();
  PropertyInfo info = type.GetProperty("Connection", BindingFlags.NonPublic|BindingFlags.Instance| BindingFlags.Public);
  object obj = info.GetValue(str, null);
  type = obj.GetType();
  info = type.GetProperty("NetworkStream", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
  object obj2 = info.GetValue(obj, null);
  NetworkStream networkStream = obj2 as NetworkStream;
</code>
Which I'm fairly repulsed by (it won't work with Mono for a start), so I'm wondering if there's a better way using public APIs which will allow me to leverage the built in runtime functionality of proxy authentication.
Answer: HTTP is two way. Clients can send a dataless request using HTTP GET (although even then data can be put in the URL or headers), or they can send data using HTTP POST, and the server gets to send a response with headers and data.
If when you say "two way" you were thinking something more like a simple TCP socket where client and server read and write at will, then sorry, but that's not what HTTP does. The client sends a request and the server sense a response. That's all. Technically, if you didn't have a client side API getting in the way, enforcing the intended constraints of HTTP, and you could cook up your own non-standard server, you could have multiple client<->server exchanges within a single HTTP request, but at that point it wouldn't really be HTTP anymore, it'd be a TCP connection with an HTTP like handshake, and your proxy might not even allow it.
That said, it sounds like you don't really need to write to the response stream at all, either you're quite confused and you just need to do a POST (see GetRequestStream), or you're just a little confused and you can just send a new request after you've processed the response. You can even reuse the same HttpWebRequest instance once you've called the .Close method on the WebResponse you got. And all this will happen on the same TCP socket (if your server and proxy support it).
Okay, I hope that all made sense. If it didn't answer your question one way or the other, just provide a little more detail about what you're trying to accomplish with regard to "two-way" communication. I understand that you have the constraint of going through an HTTP proxy w/ HTTP authentication requirements which limits things a lot.
Comment: You're right if you just think about HTTP, but a typical web proxy also has to deal with HTTPS and cannot cache or inspect it. Therefore proxys also support the CONNECT method which establishes a two way tcp socket that can be abused for anything like SSH. The question here is how to do that
Comment: I've done a bunch of experimentation with the CONNECT method and a typical SSL terminating HTTPS load balancer and I don't think this is well supported. The load balancer allows me to send additional HTTP request on the same socket, but it never supports unconstrained two way socket communications. Maybe this would work with some proxies ♂. I haven't tried two way chunked Transfer-Encoding, which might work, but would not work with the .Net classes out of the box anyway (without the private property hack) because they sends the entire request before they starts returning data.
Comment: It almost has to be well supported! The Proxy typically (unless it's doing mitm) cannot see what is inside the tunneled SSL connection. What it can do and where I ran into problems is that if the wrong side starts to talk first, the proxy might trip on that. Also the first ssl pakets can be inspected to actually be ssl pakets.. I also had some firewalls detect the SSH headers and block the connection. I've done a lot of ssh tunneling over proxys. Another problem of course is the target port. One cannot use a proxy to do a CONNECT to port 25 to send spam, the ports are usually whitelisted
Answer: https://www.replicator.org/journal/201011170043-net-connecting-a-tcpclient-through-an-http-proxy-with-authentication
works for me using VS2010 and .net 4 as well as VS2019 and .net 4.7.
Here is the code:
<code>static TcpClient connectViaHTTPProxy(
    string targetHost,
    int targetPort,
    string httpProxyHost,
    int httpProxyPort,
    string proxyUserName,
    string proxyPassword)
{
    var uriBuilder = new UriBuilder
    {
        Scheme = Uri.UriSchemeHttp,
        Host = httpProxyHost,
        Port = httpProxyPort
    };

    var proxyUri = uriBuilder.Uri;

    var request = WebRequest.Create(
        "http://" + targetHost + ":" + targetPort);

    var webProxy = new WebProxy(proxyUri);

    request.Proxy = webProxy;
    request.Method = "CONNECT";

    var credentials = new NetworkCredential(
        proxyUserName, proxyPassword);

    webProxy.Credentials = credentials;

    var response = request.GetResponse();

    var responseStream = response.GetResponseStream();
    Debug.Assert(responseStream != null);

    const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;

    var rsType = responseStream.GetType();
    var connectionProperty = rsType.GetProperty("Connection", Flags);

    var connection = connectionProperty.GetValue(responseStream, null);
    var connectionType = connection.GetType();
    var networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags);

    var networkStream = networkStreamProperty.GetValue(connection, null);
    var nsType = networkStream.GetType();
    var socketProperty = nsType.GetProperty("Socket", Flags);
    var socket = (Socket)socketProperty.GetValue(networkStream, null);

    return new TcpClient { Client = socket };
}
</code>
Comment: Your code does still use private properties via reflection which is something the OP wanted to avoid due to compatibility concerns.


How to find an element's text in Capybara while ignoring inner element text

Question: In the HTML example below I am trying to grab the $16.95 text in the outer span.price element and exclude the text from the inner span.sale one.

    "Low price!"
    "$16.95"

If I was using Nokogiri this wouldn't be too difficult.
price = doc.css('sale')
price.search('.sale-text').remove
price.text

However Capybara navigates rather than removes nodes. I knew something like price.text would grab text from all sub elements, so I tried to use xpath to be more specific. p.find(:xpath, "//span[@class='sale']", :match => :first).text. However this grabs text from the inner element as well.
Finally, I tried looping through all spans to see if I could separate the results but I get an Ambiguous error.
p.find(:css, 'span').each { |result| puts result.text }
Capybara::Ambiguous: Ambiguous match, found 2 elements matching css "span"

I am using Capybara/Selenium as this is for a web scraping project with authentication complications.
Answer: There is no single statement way to do this with Capybara since the DOMs concept of innerText doesn't really support what you want to do. Assuming p is the '.price' element, two ways you could get what you want are as follows:

Since you know the node you want to ignore just subtract that text from the whole text
p.find('span.sale').text.sub(p.find('span.sale-text').text, '')

Grab the innerHTML string and parse that with Nokogiri or Capybara.string (which just wraps Nokogiri elements in the Capybara DSL)
doc = Capybara.string(p['innerHTML'])
nokogiri_fragment = doc.native
#do whatever you want with the nokogiri fragment

Comment: Appreciate the answer, but I ended up just scraping the html with Capybara and processing with Nokogiri. I needed to navigate through many results pages, and the combination of parsing with slow Capybara nodes and strange JS effects made the script usually throw a StaleElementReferenceError.


Is there more than one use for Roman Numerals in music notation?

Question: I'm used to the standard use of Roman Numerals to note chord sequences in a key-independent way e.g. I vi IV V
But I'm sure I've seen people also use them in some other context in answers on this site to talk about chord variations or voicings or something. I can't think what to search for to find an example though.
Am I right?
Comment: Without an example, your pretty much asking "Does anyone use Roman Numerals for anything other then chords and analysis in the context?" which is rather broad.  Does _somebody_ use Roman Numerals to represent something else in music? Probably. I can see it being used to denote form and other repetition patterns, but _the standard way to use them_ is for analysis. Even within the context of analysis people use slightly different nuances  with just a basic alternative of your example being `I VIm IV V`.
Comment: Yeah - the thing is now I can't find any examples, I'm looking for some at the moment...
Answer: Roman numerals can be used for aspects of instrumental notation, which are for performance, rather than analytical purposes. For instance, Roman numerals are used to denote: positions in classical guitar music (for instance, see this post); which string a note or passage is to be played on in bowed string music.
The wikipedia page about Roman Numerals gives examples of both analytical and performance markings:

In music theory, the diatonic functions are identified using Roman numerals. (See: Roman numeral analysis)
In musical performance practice, individual strings of stringed instruments, such as the violin, are often denoted by Roman numerals, with higher numbers denoting lower strings.

However, inversions (I think this is what you mean by voicings) of chords are shown using either letters or numbers (in figured bass), as an addition to either a Roman numeral or bass note. For example, a first inversion of chord I can be shown as Ia or I6.
Comment: Looks fine to me.
Comment: Roman numerals are also used in Schenkerian Analysis to direct the listener to specific harmonic moments or shifts.
Comment: I put some links in for you. You can change them if you want. I just want to point out in the second paragraph the figured bass along with the Roman Numeral is pretty standard and I would not say is different from the typical use (although I agree it's probably what the OP is thinking of).
Comment: @Dom, I think we were editing this post at the same time - feel free to have another look to see if you can improve my edit.
Comment: Good point, JJ. I'll add that in later, if that's okay with you.
Answer: They can also be used to designate strings, I II II IV (or Ie IIe IIIe IVe) for orchestral strings (violin, viola, cello, bass).
So instead of a passage for violin being marked "sul G" (on the G string) it might be marked "IVe" (or, in full "IVe corde" -- French "quatrième chorde", i.e., "fourth string"). The little "e" would normally be printed as a superscript.
They are occasionally used in pedagogical works to indicate position instead, hopefully with some clarifying text rather than just the roman numeral (e.g., III pos. rather than just "III"). Arabic numerals are also used for this purpose: something like "3 pos." would mean third position, while just a bare "3" would always mean third finger.


Triggering shouldStartLoadWithRequest with multiple window.location.href calls

Question: Im trying to pass multiple things from a webpage inside a UIWebView back to my iPhone app via the shouldStartLoadWithRequest method of the UIWebView.
Basically my webpage calls window.location.href = "command://foo=bar" and i am able to intercept that in my app no problem.  Now if i create a loop and do multiple window.location.href calls at once, then shouldStartLoadWithRequest only appears to get called on once and the call it gets is the very last firing of window.location.href at the end of the loop.
The same thing happens with the webview for Android, only the last window.location.href gets processed.
Comment: I found a clever solution.  Dynamically create an iframe for each command and set its src to "command://foo=bar", you can fire this off multiple times in a loop and shouldStartLoadWithRequest gets called every time!  Now to study how to optimize this.  I dont think it would be good to create thousands of iframes (even though they are hidden).  Any suggestions on that?
Comment: I would try to optimize every location call as well. If you can only send say 60 calls a minute, then make sure you are jamming every call with enough query vars and fragments to handle multiple commands per call. Also, you might want to check out wkWebView: http://nshipster.com/wkwebkit/ it automates much of this process and is more reliable.
Answer: <code>iFrame = document.createElement("IFRAME");
iFrame.setAttribute("src", "command://foo=bar");
document.body.appendChild(iFrame);
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
</code>
So this creates an iframe, sets its source to a command im trying to pass to the app, then as soon as its appended to the body shouldStartLoadWithRequest gets called, then we remove the iframe from the body, and set it to null to free up the memory.
I also tested this on an Android webview using shouldOverrideUrlLoading and it also worked properly!
Comment: I want to follow up since i posted this 2 years ago.  I wrote an Android and iPhone app that was basically a webview wrapped in a native app.  I used this solution so i could communicate from the webview to the native app and its worked flawlessly for the past 2 years i've had over 500k+ downloads of my app.
Comment: This solution is hideously ugly, but it seems to be the least hideously ugly solution possible.  It seems Javascript "optimizes" by ignoring window.location calls that are subsequently replaced by other window.location calls.  Thank you for saving me from a very painful debugging session!
Comment: 3 year followup, 4,000,000 ios+android downloads combined and this solution has been flawless. Yes it's ugly but it works.
Comment: You, sir, are brilliant.  I've been battling this for hours.  Finally the right Google search led me here.  Thank you.
Comment: @Arkaaito +1 for the hideously ugly, i totally agree
Answer: I struck this problem also and here is my solution that works for me.
All my JavaScript functions use this function __js2oc(msg) to pass data
and events to Objective-C via shouldStartLoadWithRequest:
P.S. replace "command:" with your "appname:" trigger you use.
<code>/* iPhone JS2Objective-C bridge interface */
var __js2oc_wait = 300; // min delay between calls in milliseconds
var __prev_t = 0;
function __js2oc(m) {
  // It's a VERY NARROW Bridge so traffic must be throttled
  var __now = new Date();
  var __curr_t = __now.getTime();
  var __diff_t = __curr_t - __prev_t;
  if (__diff_t > __js2oc_wait) {
    __prev_t = __curr_t;
   window.location.href = "command:" + m;
  } else {
    __prev_t = __curr_t + __js2oc_wait - __diff_t;
    setTimeout( function() {
      window.location.href = "command:" + m;
    }, (__js2oc_wait - __diff_t));
  }
}
</code>
Answer: No, iframe's url changing won't trigger shouldOverrideUrlLoading, at least no in Android 2.2.


Inserting selected row into mysql

Question: EDITED I´ve changed the SQL code and it works, but I get the exception:
"cannot set a null tableModell
I´ve seen many very similar examples but not the one I need.
Therefore here we go:
It´s simple - In a InternalFrame I insert Code, ProjectName, Teamleiter, Description and click "Teilnehmer" to list all members of all projects from a table "tbl_teinehmer". Just the Lastname is shown.
So, I insert the correspondent data into the fields, list the projectmembers and select the members who will take part of this new project I´m creating.
In order to insert the data and the selected row from "teilnehmer" into a new Table:
   private void buttonAnlegenActionPerformed(java.awt.event.ActionEvent evt) {
            String data = tbl_teilnehmer.getValueAt(tbl_teilnehmer.getSelectedRow(), 0).toString();
            String sql = "INSERT INTO TBL_PROJETO (PROJEKT_ID, PROJEKTNAME, TEAMLEITER, BESCHREIBUNG,**TEILNEHMER**)"; //now it works but I get the exception: cannot set a null TableModell.
                    + "  VALUES(?,?,?,?,?)";
            menu = new HauptMenu();
            try{
                PreparedStatement pst = conn.prepareStatement(sql);
                pst.setString(1, ct.getText());
                pst.setString(2, nt.getText());
                pst.setString(3, st.getText());
                pst.setString(4, beschreibungText.getText());
                pst.setString(5, data);
                pst.execute();
                menu.listaProjetos();
                JOptionPane.showMessageDialog(null, "Projekt added to Database");

            }
            catch(Exception e){
                System.out.println(e);
            }
            try{
                conn.close();
            }catch(SQLException ex){
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
            ct.setText("");
            nt.setText("");
            st.setText("");

        }

This is the error:
  java.sql.SQLException: Parameter index out of range (5 > number of parameters, which is 4).

Maybe the problem is by PreparedStatemend declaration.
I´ve set
pst.setString(5, data);

as it would recognize the selected row from the variable data but I guess it´s wrong.
Comment: Try removing `pst.setString(5, data);` and re-run your program
Comment: Change `VALUES(?,?,?,?,data)` or `VALUES(?,?,?,?,?)`
Answer: Thank you for helping me!
I solved the problem first by changing the SQL declaration:
First at I´ve placed '"+data+"', which is an placeholder(If I´m not mistaken) but I wanted to set the selected row into the respective column in DB.
Therefore I´ve changed it to the columnname: TEILNEHMER and set another questionmark '?' as VALUE.
It worked but I still got the error>> cannot set a null TableModel
and under this error >> Unsupported collation 'Latin7'  or smth like that.
So I´ve set the Collation of my table from Lati7 to TableDefault and now it works entirely.
THANK YOU ALL AGAIN FOR HELPING ME!
Answer: do it as follows
 pst.setString(0, ct.getText());
 pst.setString(1, nt.getText());
 pst.setString(2, st.getText());
 pst.setString(3, beschreibungText.getText());
 pst.setString(4, data);

Answer: There is no placeholder for 5th parameter in your sql query:
String sql = "INSERT INTO TBL_PROJETO (PROJEKT_ID, PROJEKTNAME, TEAMLEITER, BESCHREIBUNG,'"+data+"')"
             + "  VALUES(?,?,?,?,?)";

Comment: @bruno-kommers Replace "String sql" line in your code to as shown in Answer.
Comment: It worked just by adding sql from '"+data+"' to the column Teilnehmer set in database.
Comment: now it "works" BUT ... I still have a problem: java.lang.IllegalArgunmentException: cannot set a null TableModel

Inserting selected row into mysql


Can someone explain to me the harmonic reasoning behind this chord progression?

Question: E minor 7 9    G dim 7     D# dim 7 9    E minor 7 9
Let's just say we're in the key of E minor
Please I'm so confused
Answer: I think we can safely ignore the 9's in all the chords--I don't believe they affect harmonic function here.
G dim 7 is enharmonically equivalent to A♯ dim 7, which is a secondary dominant chord in the context of E minor. Specifically, it's vii°7/V in E minor.
The A♯ dim 7 chord leads to a dominant-function D♯ dim 7 9 chord.
Then we're back to the decorated Em 7 9-chord tonic.
Comment: In other words, it's Em - F#7 - B7 - Em in disguise.
Comment: A# dim 7 is the secondary dominant of what chord? And is the d# borrowed from E major? Thanks for the quick reply :D
Answer: Just re-wording from existing answer and comments...
Enharmonically respell Gdim7 to A#dim7 as A# C# E G
The D#dim7 is D# F# A C
Extend that with the part @piiperi hinted at:
some theory treats leading tone diminished seventh chords as incomplete dominant ninth chords.
If we put the supposed root of those incomplete dominant ninths in parenthesis we get these chords: (F#) A# C# E G then (B) D# F# A C then Em, which is straight-forward Em: V9/V V9 i


How to find the image of this function?

Question: I have been struggling with this math problem for a few days. I really need some help.
Find the image of $h : (0, 1) \rightarrow \mathbb{R}$ defined by $h(x) = 1/(x^2 + 8x)$ for $0 < x < 1$.
I know the answer is $(1/9, \infty)$, but I have no clue about how to prove it. In other problems, I can usually define a set $S$ to equal this interval and choose an element in that set and show it's in the image. Then choose am element in the image and show it's in the set. So, the image equals my set. But, I couldn't get that to work here.
As another attempt, I proved the function is strictly decreasing on $(0, 1)$, so it's injective. I couldn't get anywhere after that though.
Answer: \begin{align}
\frac1{x^2+8x}=\frac{1}{(x+4)^2-16}
\end{align}
Hence if $0<x<1$, we have
$$4<x+4<5$$
$$4^2-16<(x+4)^2-16<5^2-16$$
$$0<(x+4)^2-16<9$$
$$\frac19<\frac1{(x+4)^2-16}$$
Comment: That is clever. What about the infinity part ?
Comment: $(x+4)^2-16$ can get arbitrarily small and positive, hence when we divide by $1$, it gets arbitrarily large.
Answer: Note that $x^2+8x$ is an increasing function which maps the interval $(0,1)$ onto $(0,9)$
Thus your function which is the reciprocal of $x^2+8x$ maps the interval $(0,1)$ to $(1/9,\infty)$
Answer: Since $g\colon x \mapsto x^2+8x$ is increasing on $0 < x < 1$, you have $g(0)=0 < x^2+8x < 9=g(1)$ if $0<x<1$. But $g$ is also continuous, hence for $0 < x < 1$ it reaches all values between $0$ and $9$. So $h(x)= 1/g(x)$ reaches all values between $1/9$ and $+\infty$.
Answer: Let $y$ be any number such that $y \in (1/9, \infty)$. Then the formula
$$x = \sqrt{\frac{1}{y} +16} -4 $$
will explicitely give you an $x\in (0,1)$ such that $h(x) = y$.

How to find the image of this function?


show conditional expectations are equal in distribution

Question: This is from Kallenberg.
Let $(\xi, \eta) \stackrel{d}{=} (\tilde{\xi}, \tilde{\eta})$, with $\xi \in L^1$. Then $E[ \xi | \eta ] \stackrel{d}{=} E[ \tilde{\xi} | \tilde{\eta} ]$.
The hint is to let $E[ \xi | \eta] = f(\eta)$ and first argue that $E[\tilde{\xi} | \tilde{\eta}] = f(\tilde{\eta})$. Supposing this, then the result should follow.
My idea was to try to show for all measurable $g$, we have $E[ g(f(\eta)) ] = E[ g(f(\tilde{\eta})) ]$. I can see this for $g$ identity, but I'm having trouble seeing this for arbitrary measurable $g$.
Thanks!
Answer: For $g= 1_B$ for $B$ a Borel set, $E[g(f(\eta))] = E[g(f(\tilde \eta))]$ says $P(\eta \in f^{-1}(B)) = P(\tilde \eta \in f^{-1}(B))$. The result then follows by approximating an arbitrary $g$ by simple functions.


Ionic 2 Leitura json

Question: Pessoal Estou tentando ler um json no ionic, criei o service da seguinte maneira :
http://pastebin.com/0btbuC83
minha classe esta assim :
http://pastebin.com/6gdpBth4
e meu json é assim :
http://pastebin.com/gVSVCsQN
Porem o meu alert da classe só retorna undefined... Como posso arrumar ?
Obrigado
Answer: O código alert(data.id); não irá exibir nada mesmo. Afinal data é um vetor.
Para acessar o atributo id, será necessário especificar a posição do vetor ou utilizar um laço (for, foreach, etc).
Exemplo:
alert(data[0].id);

Comment: Diego, nesse caso, coloque as flags informando que a pergunta está incompleta! Obs: Do meu ponto de vista, isso ainda sim responde a pergunta. Afinal estou mostrando o problema com o código dele.
Comment: Diego: "Porem o meu alert da classe só retorna undefined... Como posso arrumar ?". Minha resposta responde isso perfeitamente para os detalhes que foram providos.
Answer: Para aparecer no alert o seu resultado é necessario utilizar um metodo de conversao do objeto para string.
ex: JSON.stringify(data);

Ionic 2 Leitura json


Como escapar aspas de uma chave do json no Postgresql?

Question: Tenho uma função que recebe JSON's, acontece que é possivel o usuario colocar do seguinte modo:
Normal:
'[{"nome":"João Carlos"}, {"nome":"Maria Silva"}]'

Problema:
'[{"nome":"João - "Carlos" - "}, {"nome":"Maria Silva"}]'

Reparem que é possivel o usuario colocar aspas duplas ou simples no campo  nome, como eu poderia escapar essas aspas?
Eu utilizo a função JSON_ARRAY_ELEMENTS para separar em linhas cada JSON.
SELECT
    *
FROM
    json_array_elements('[{"nome":"João - "Carlos" - "}, {"nome":"Maria Silva"}]')

Comment: já tentou usando o scape ou aspas duplas repetidas? tipo `json_array_elements('[{"nome":"João - \"Carlos\" - "}, {"nome":"Maria Silva"}]')` ou `json_array_elements('[{"nome":"João - ""Carlos"" - "}, {"nome":"Maria Silva"}]')`
Comment: @AdrianoGomes Até pensei, mas eu como eu poderia colocar essas barras invertidas?
Comment: vc está usando alguma linguagem de programação para executar o script sql?
Comment: Node.JS para executar a função do postgresql que recebe o JSON e insere em tabela.
Comment: Ao invés de usar a função json_array_elements e usar apenas o node para criar essa lista é uma opção?
Comment: O problema é que o formato do json está inválido, você precisa informar a barra invertida quando existe aspas duplas numa string, como o @AdrianoGomes sugeriu. Se não fizer isso você não vai conseguir fazer o parse. Uma alternativa seria tratar pelo node os dados informados pelo usuário, acrescentando as barras.
Comment: No node só consegui fazer a usando ao invés de uma barra invertida, duas, ficando dessa forma: `var str = '[{"nome":"João - \\"Carlos\\" - "}, {"nome":"Maria Silva"}]';
var obj = JSON.parse(str);
console.log(obj); `
Answer: Não há nada de errado na sua função!
Este dado em formato JSON que você está tentando processar está malformado, veja bem:
'[{"nome":"João - "Carlos" - "}, {"nome":"Maria Silva"}]'

Repare que não há como diferenciar as aspas que devem ser escapadas das que não devem ser!
O problema está fora do escopo da sua função.
O chamador (caller) da sua função precisa ter o cuidado de passar um JSON válido como argumento ao chamá-la.
Talvez isso possa ajudar: https://www.postgresql.org/docs/9.5/libpq-exec.html#LIBPQ-EXEC-ESCAPE-STRING


Google Recaptcha: Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame

Question: I have integrated google recaptcha in vite-react-ts app and created the build of that.
const script = document.createElement('script');
script.src = url;
script.async = true;
script.defer = true;
script.onload = renderCaptcha;
document.body.appendChild(script);

return () => {
    document.body.removeChild(script);
}

const renderCaptcha = () => {
    if (window?.grecaptcha) {
        try {
            if (captchaRef.current.captcha) {
                captchaRef.current = { ...captchaRef.current, pendingCaptcha: true };
                window?.grecaptcha.reset(captchaRef.current.captcha);
            } else {
                const captcha = window?.grecaptcha.render(captchaContainerRef.current, {
                    sitekey: CAPTCHA_V2_KEY,
                    callback: () => {
                        captchaRef.current = { ...captchaRef.current, pendingCaptcha: false };
                    },
                    'expired-callback': (data: any) => {
                        console.log("expired")
                        console.log(data)
                    },
                    'error-callback': (error: any) => {
                        console.log("error")
                        console.log(error)
                    }
                });
                captchaRef.current = { ...captchaRef.current, captcha, pendingCaptcha: true };
            }
        } catch (e) {
            console.error('captcha generation error', e);
        }
    }
};

JSX

Now i am trying to load this build using script tag in other app.
I am getting the error
Uncaught DOMException: Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame.

I am running the app locally using http-server with ssl
I have whitelisted localhost in re captcha dashboard
I am expecting it to load recaptcha properly
Comment: I don't know if this is the case but, have you checked your browser extensions? Maybe you have an extension that is blocking the script.
Comment: No i dont have any extension at all @Klian
Answer: Did some research to find a way, looks like its not possible as its a blocker from browser itself.
Only solution i can do now is to attach the recaptcha with document body intead of my app, which will give access to DOM of recaptcha and it will work.
Answer: Google's ReCAPTCHA and Chrome team are in conflict. They've made some broken code, especially v2 of recaptcha.
Even if you direct the api.js to http:// it redirects it internally and then tries to scan for a window.yoursite.a-12945u12 type of property and it can't because it's trying to read it from an iframe it places into your website.
Webpack dev server doesn't allow it even with "cross-origin allowed".
Neither does any AWS infrastructure settings to allow cross-origin, or specifically https://google.com
Uncaught DOMException: Failed to read a named property 'a-9tu39a56hre3' from 'Window': Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame.
at Q.Yv (https://www.gstatic.com/recaptcha/releases/MHBiAvbtvk5Wb2eTZHoP1dUd/recaptcha__en.js:1004:346)
at Array.<anonymous> (https://www.gstatic.com/recaptcha/releases/MHBiAvbtvk5Wb2eTZHoP1dUd/recaptcha__en.js:531:92)
at Object.init (https://www.gstatic.com/recaptcha/releases/MHBiAvbtvk5Wb2eTZHoP1dUd/recaptcha__en.js:1011:141)
at https://www.google.com/recaptcha/api2/bframe?hl=en&v=MHBiAvbtvk5Wb2eTZHoP1dUd&k=6LcrDmQpAAAAABDVugX2X1AuLCoiEBNR5PETxkP5:184:30

Solution: Build your own captcha with better code and let's reduce our reliance on Google's badly tested products.


Dumping route changes from openbgpd

Question: I have an openbgpd installation running on FreeBSD. I want to capture the routes whenever there is a change. Is there any way of getting this from the logs, or writing a hook to listen for such events?
Comment: Do the dump or log updates configuration options not do what you want ?
Comment: @Iain - Yes, these seem to be what I am looking for. Thanks.
Comment: For reference. I've never run a freebsd system in my life. All I did was go and read the documentation for you. You really should learn to do that yourself.
Answer: There are dump and log updates configuration options that may do what you want.

Dumping route changes from openbgpd


Views Load More for products listing page in ajax

Question: For my ecommerce website i am using View Infinite Scroll module which is for Products listing page lazy loading,
Lazy loading works fine for my products listing view, but my requirement is when i click View More button then only it gets to load more products.
Is there options to call View More button or anyother modules supports for my requirement, please tell me if anyone have any idea means.
Answer: You can use views load more module. It provides a button. Clicking that button lists more contents only. The pager should be defined in your views settings.
Answer: It's actually really easy to do with standard Views and jQuery.autopager in your theme.
The most important part is using the correct classes, I can't find my working example at the moment, but it should look something like:

$.autopager({
  // where contents would be appended.
  // use "appendTo" or "insertBefore"
  appendTo: '.views-content',

  // a selector that matches a element of next page link
  link: '.pagination .next a:first',

  // a selector that matches page contents
  content: '.views-row',
});
Answer: In views, there is option for

Use AJAX

from advanced settings, there we can select Yes, then it will work Ajax view more


Alias one set of Subdomains to another

Question: I have to domains that I want to effectively mirror one another on select subdomains. Let's say they are pirates.com and ninjas.com and i want ninjas to mirror the content on pirates.
When I visit foo.ninjas.com I want to see the content on foo.pirates.com. Due to app restrictions I need to do this in DNS for an undefined number of subdomains. I was under the impression i could do this with a CNAME, but it appears that setting a CNAME for * subdomain of the ninjas.com domain to point to pirates.com will make any subdomain of ninjas.com point at pirates.com instead of the associated subdomain. I.e. foo.ninjas.com would reference pirates.com instead of foo.pirates.com.
Is there a way to do this using DNS? Am I missing something basic?
Answer: DNS is only one part of the story. The web server must be aware of the domain names that you intend to use. So you will have to set up the names in the web server as well (e.g. using Apache's ServerAlias directive.
Comment: So you're saying that the CNAME part should be working correctly that `foo.ninjas.com` should be pointed at `foo.pirates.com` but i have to change my server config on pirates?
Comment: Correct. Unless the web server knows what to do with `foo.ninjas.com` then it will just serve the default virtual host, which is probably a test page.
Answer: If you control the DNS server, and if it uses zonefiles, you can make both domains use the same zonefile.
An example for bind:
zone "ninjas.com" IN {
    type master;
    file "master/ninjas.com.zone";
};

zone "pirates.com" IN {
    type master;
    file "master/ninjas.com.zone";
};

I use this technique to make ~2500 domainnames look exactly the same :)

Alias one set of Subdomains to another


Expectation Maximization-Log Likehood interpretation

Question: I am using EM algorithm in weka for genomic data, get the results in the images, but a don't know how interpret the log likehood index. Is better when is higher or lower, negative or positive. How interpreted?
Answer: EM is a maximum-likelihood estimation (MLE) algorithm, a higher
likelihood means that the data are more likely to be generated by the the parameters estimated.
Higher likelihood values are not always better because of overfitting, which is usually a problem of MLE methods.
Comment: how can i evaluated the EM, exist some metric for a quality evaluation of algorithm (like Dunn or silhouette), or only the likelihood is enough?
Answer: EM is an optimization procedure, optimization procedures often run into problems so the Log likelihood gives you an idea of how good your estimate is relative to other estimates - if you're optimizing the same model with the same data multiple times.
Comment: can you be more specific about what problems do they run into, or talk about why you would get different answers with the same data and model?
Answer: In Expectation-Maximization, you want to find the Maximum-Likelihood Estimator of the parameter $\theta$, that is, the one that maximizes the probability (the log-probability, actually, which is a similar problem) of your observed data $X$:
\begin{align}
argmax_{\theta} \ln p(X | \theta)
\end{align}
The problem is, you don't always know how to maximize this function. What you do in EM is augmenting the model with some latent data $Z$. If you knew the value of this data, then you could maximize the function.
So, you do
\begin{align}
\ln p(X | \theta) = \ln \int_{Z}  p(X, Z | \theta)
\end{align}
and then try to maximize this second function. Yet, we are still blocked here. So we do a little trick:
\begin{align}
\ln p(X | \theta) = \ln \int_{Z}  p(X, Z | \theta) =
\ln \int_{Z}  \frac{p(X, Z | \theta)}{q(Z)} q(Z) = \ln \mathbb{E}_Z[\frac{p(X, Z | \theta)}{q(Z)}]
\end{align}
where $q(Z)$ is any probability distribution. Now, Jensen's inequality tells us that the log of an expectation is greater or equal to the expectation of the log. Then we have
\begin{align}
\ln p(X | \theta) =  \ln \mathbb{E}_Z[\frac{p(X, Z | \theta)}{q(Z)}] \geq  \mathbb{E}_Z[\ln \frac{p(X, Z | \theta)}{q(Z)}] = \mathbb{E}_Z [\ln p(X, Z | \theta)] - \mathbb{E}_Z(\ln q(Z)]
\end{align}
where we just created a lower bound of our target function $\ln p(X | \theta)$. The equality holds (the lower bound touches the target function) when $q(Z)$ is actually the posterior of $Z$ given your observed data and the parameter $\theta$ (because this makes the ratio inside the log equal to $p(X | \theta)$, which does not depend on $Z$).
So, the EM trick is to maximize $\theta$ in the lower bound (M-step). But then we break the equality and are again below the target:  we have to re-compute the expectation (E-step) of $Z$ since the current expectation was given the old $\theta$!).
Thus, the every time we re-compute the expectation according to the last $\theta$, the value of our lower bound is actually the value of $\ln p(X | \theta)$. This is the log-likelihood value that you observe in the screen. The higher the log-likelihood, the closer you are to the solution of the problem.
And when the algorithm converges, you have a local (global, if you get lucky or if the function is concave) maximum for $\ln p(X | \theta)$.


How to make changes to the database? (DRF)

Question: In the model of the Post object, I have field created = models.DateTimeField field (auto_now_add = True)
There is another field end_time, in which - today's date + 1 month in advance. That is, if a post was created, then it will have today's date in the created field (January 5, 2020), and in the end_time field it will be a month ahead (February 5, 2020).
def next_month():
    now = timezone.now()
    return now + relativedelta(months=+1)

end_time = models.DateTimeField(default=next_month, blank=True, editable=False)

To all this, I'm need to add the is_actual field, in which -
  @property
  def is_actual(self):
    return bool(self.end_time and self.end_time > now())

But in this case, I can not use the filter to display the fields, where is_actual == true. For me, a filter using this field is very important.
What needs to be done so that I can apply a filter by the is_actual field? As far as I understand, here you need to make once a day, for example, changes to the database. But how? To write some kind of custom script, or to do it somehow using Django methods?
Comment: I believe overloading the model manager will let you add custom filters. You will need to write the logic using the actual columns instead of the property.
Comment: https://docs.djangoproject.com/en/3.0/topics/db/managers/
Answer: I would suggest to make "is_actual = model.BooleanField(default=False)" and do what necessary in the clean method. For example:
class MyModel(models.Model):
      is_active=models.BooleanField(default=False)
      ...
      def clean(self):
          super(MyModel, self).clean()
          if self.end_time:
             self.is_active = self.end_time > now()

Check here for more insights: https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.clean
Answer: Filter with:
from django.db.models.functions import Now

# is_actual is True
MyModel.objects.filter(
    end_time__gt=Now()
)

# is_actual is False
MyModel.objects.filter(
    end_time__lte=Now()
)


How can I conditionally show a field in the node/add page?

Question: When users are in node/add/page, I want to show the body field when the title is not empty. How can I achieve this?
Comment: You want this when the page is viewed? or when someone is in the create a new page form?
Comment: When someone is in the create a new page form
Comment: @kiamlaluno can you re-open this so I can answer the question?
Comment: @no-sssweat answer please
Answer: By default in Drupal 8 "Seven" is the admin theme.
(Assuming you're using Seven as your admin theme) In /core/themes/seven/js add/create custom.js file.
custom.js
(function ($) {

   $('#edit-body-wrapper').hide();

   (function Forever(){

     var title = $('#edit-title-0-value').val();

     if (title != '') {
       $('#edit-body-wrapper').slideDown(1500);
     }
     // slides down and shows the body field in 1.5 secs if the title field is not empty

     else if (title == '') {
       $('#edit-body-wrapper').slideUp(1500);
     }
     // slides up and hides the body field in 1.5 secs if title is empty

   setTimeout(Forever, 1);

   })();

})(jQuery);

Now edit seven.libraries.yml
In the node-form: section add
  js:
    js/custom.js: {}

So it should look like this:
node-form:
  version: VERSION
  css:
    layout:
      css/layout/node-add.css: {}
  dependencies:
    - node/form
  js:
    js/custom.js: {}

PS: Don't forget to clear the cache to see changes.
Comment: **PPS:** When you go to add a page for a slight second you can see body field. If you don't want that, you can go to `/core/themes/seven/css/layout` and edit **node-add.css** and add `#edit-body-wrapper { display: none; }` and flush cache to see changes.


Change Python Class attribute dynamically

Question: I have a Class B inheriting Class A with a class attribute cls_attr.
And I would like to set dynamically cls_attr in class B.
Something like that:
class A():
   cls_attr= 'value'

class B(A):

   def get_cls_val(self):
       if xxx:
          return cls_attr = 'this_value'
       return cls_attr = 'that_value'
   cls_attr = get_cls_val()

I tried several things. I know i might not be looking in the right place but i am out of solutions.
EDIT: Classes are django admin classes
Thanks.
Comment: I think you need to explain the behaviour you want to see more clearly. That is, do you intend for `A.cls_attr` to change after calling `get_cls_val()`, or should the change only be seen on `B` and instances of `B`.
Comment: Have you seen this answer http://stackoverflow.com/a/2584050/471899 ?
Comment: Hi @Dunes, the latter, i want the change only in B.
Answer: class attributes can be read on the class or an instance, but you can only set them on the class (trying to set them on an instance will only create an instance attribute that will shadow the class attribute).
If the condition is known at import time, you can just test it in the class body:
xxx = True

class A(object):
   cls_attr = 'value'

class B(A):
   if xxx:
       cls_attr = 'this_value'
   else
       cls_attr = 'that_value'

Now if you want to change it during the program's execution, you either have to use a classmethod:
class B(A):
   @classmethod
   def set_cls_attr(cls, xxx):
       if xxx:
           cls.cls_attr = 'this_value'
       else:
           cls.cls_attr = 'that_value'

or if you need to access your instance during the test:
class B(A):
   def set_cls_attr(self, xxx):
       cls = type(self)
       if xxx:
           cls.cls_attr = 'this_value'
       else:
           cls.cls_attr = 'that_value'

Comment: This is the correct answer, and thanks for the suggestions. I need to remember to drink coffee before answering.
Comment: Hi I tried your @classmethod solution. It seems that function set_cls_attr in not called...
Comment: @jcs Why would it be called if _you_ don't call it ? If you know the value at import time, please check the first part of the answer. Else please try to clarify your question.
Comment: @brunodesthuilliers The if part depends on user profile so i need to access 'request' (Django), can't use first part. Yes, i know i have to call the function, that is why i added the `cls_attr = get_cls_val()` in my example, even though it is not the right way to do it.
Comment: @brunodesthuilliers How can i get the function to be executed within the class itself?
Comment: @brunodesthuilliers Ok i called the function without decorator,  randomly somewhere else and it works! Thanks a lot!
Comment: "i called the function without decorator" : if you remove the `@classmethod` decorator it's not a classmethod no more, the first argument will be an instance, and it will set an instance attribute, not a class attribute. This being said, given your use case, you definitly _DONT_ want a class attribute. You really should post about your _real_ use case and not about what _you_ think is the solution, because given your questions you obviously don't have a clear enough understanding of Python's object model to assert that "it works" (even if it _might_ seem to work with a single user).
Answer: What about using classmethod and polymorphically overriding it in subclass?
class A:
    @classmethod
    def cls_attr(cls):
        return 'value'

class B(A):
    @classmethod
    def cls_attr(cls):
        if cond():
            return 'this'
        else:
            return 'that'

assert A.cls_attr() == 'value'
cond = lambda: True
assert B.cls_attr() == 'this'
cond = lambda: False
assert B.cls_attr() == 'that'

Comment: @ŁukaszR. this will NOT set a class attribute.
Comment: @kirbyfan64sos properties don't work when the attribute is looked up on a class - it has to be looked up on an instance. So you couldn't do `B.cls_attr`, which is kind of the point of having a class attribute at first...
Comment: You should also mention properties, which might be a slightly more elegant-looking solution.
Comment: @kirbyfan64sos I've never seen `@property` with `@classmethod`. Is it a thing? For instance attributes, sure, but will it work for class attributes / methods?
Comment: Properties automatically work without need of being defined as a classmethod.
Comment: Whoops, I was thinking of a more general data descriptor, rather than a property.
Answer: The easiest solution for me is with property decorator:
class B:
    @property
    def attr_name(self):
        """ do your stuff to define attr_name dynamically """
        return attr_name

Answer: This seems to do what you want:
>>> class B(A):
     @classmethod
     def set_cls_val(cls, x):
             if x == 1:
                     cls.cls_attr = "new"

>>> c = B()
>>> c.cls_attr
'value'
>>> c.set_cls_val(B, 1)
>>> c.cls_attr
'new'
>>> B.cls_attr
'new'

Just set it within the function.
EDIT: Updated to set the class attribute and not the instance attribute, thanks @bruno-desthuilliers.
EDIT: Updates once again, thanks @bruno-desthuilliers. I should think my answers through more clearly. But what you want is answered below.
Comment: What's the use of a `classmethod` if you hard-code the class name ? (hint: the convention for classmethods is to name the first param 'cls' - can you guess why ?)
Comment: Wont change the class attribute, sorry.
Comment: Fixed sorry. Thanks for that. I had instance and not class.
Comment: Still true.  It's more so used in metaclassing, and this is a weird situation. It really in this case should be a staticmethod or separate function.


Fuso Horário Brasileiro no MySQL

Question: Tenho uma tabela do banco de dados MySQL chamada registros.
Nela, eu tenho então a seguinte estrutura:
id_registro, nome_registro, data_registro.
Em data_registro eu estou usando o current_timestamp(), buscando a hora do servidor na hora de adicionar. A questão é: Esta hora não é a mesma do Brasil, por estar num servidor dos EUA.
Como eu faço para que ao adicionar no banco de dados, faça a inserção da hora brasileira? (4 hs de diferença).
Comment: Mostre o que vc tentou fazer...
Comment: Não tenho nada, porque o horário do sistema está correto, se eu der echo date("d/m/Y H:i:s") funciona normal, mas minha duvida é sobre o SQL mesmo, como eu faria? Queria alterar algo dentro do php admin ou do php.ini que fizesse então essa alteração automaticamente, que eu não precisasse manipular os dados na hora de inserir.
Comment: Você precisa explicar melhor essa para *buscando a hora do servidor na hora de adicionar. A questão é: Esta hora não é a mesma do Brasil, por estar num servidor dos EUA*
Comment: data_registro poderia ser utilizado now(), por exemplo.
Comment: É que na hora de inserir, eu passo o campo vazio, pra que ele insira o current_timestamp() do mysql já
Comment: O mysql não sabe o fuso daqui, então ele coloca a hora diferente
Comment: E como eu manipulo isso?
Comment: **SUBDATE(now(), INTERVAL 3 hour** coloque isso
Comment: Onde eu colocaria? Não entendi bem..
Comment: aonde vc deixa em banco, coloque isso
Comment: Estranho você falar em "hora do Brasil", o Brasil tem faixas do território com 4 diferentes fusos horários: UTC - 5 horas, UTC - 4 horas, UTC - 3 horas (horário de Brasília), UTC - 2 horas.
Answer: Altere a variável global de fuso horário:
SET @@global.time_zone = '+3:00';
QUIT

A variável time_zone pode ser ajustada direto no console do cliente MySQL.
Verifique a sua hora atual com a função NOW(), antes de começar a brincar:
SELECT NOW();

Em seguida, altere a variável global de fuso horário e desconecte do servidor:
SET @@global.time_zone = '+3:00';
QUIT

Você precisa sair e entrar de novo na sua sessão MySQL para poder ver os efeitos.
Assim que reiniciar a sessão do MySQL, verifique novamente a hora atual:
SELECT NOW();
Se você tiver o banco de dados de nomes de zonas de fusos horários adequadamente configurado, pode se referir às zonas pelos seus nomes. Veja um exemplo:
SET time_zone='America/Sao_Paulo';

SELECT @@time_zone;

Para poder se referir a um nome de zona de fuso horário, como 'Brazil/DeNoronha', você precisa estar com o banco de dados de nomes de timezones corretamente configurado. Se você tiver dúvidas sobre este assunto, ou não estiver conseguindo usar os nomes das zonas de fusos, leia este artigo.
Para ver todos os fusos válidos para o Brazil, por exemplo, use a seguinte query:
SELECT * FROM mysql.time_zone_name WHERE Name LIKE '%Brazil%';

Veja mais detalhes nessa resposta.
Comment: Pra eu fazer isto, preciso de acesso super global né? acesso root
Comment: Ai acho que tem que pedir para executar este comando no servidor.. penso eu.. @TalesBreno
Comment: [Sim](http://stackoverflow.com/a/19881949/2740371)
Comment: @AndréBaill Mas se o cliente não tem tal privilégio, como faz?
Answer: Adicione date_default_timezone_set('America/Sao_Paulo'); no inicio do seu código PHP, assim o timezone ficará corretamente configurado. Lembrando que você tem que adicionar na página que faz o insert no MySQL.
Comment: Isso alterar no PHP a data?
Comment: @GOKUSSJ4 não.. isso você coloca no arquivo .php que tem o INSERT INTO tabela... Esse código você adiciona no arquivo PHP mesmo
Comment: Legal, não sabia que dava para fazer dessa forma também, +1

Fuso Horário Brasileiro no MySQL


advantages of drush bam vs. drush sql-dump / drush sql-connect

Question: Is there any comparative advantage in terms of best practice, ease of use, or speed in terms of using the drush back up and migrate command (drush bam) or is it just preference?
I'm often using just a simple drush sql-dump > exportdb.sql and a $(drush sql-connect) < importdb.sql to backup a database. I find it pretty easy to use.
Answer: There aren't giant differences between the two approaches. Here are a few small differences:
drush sql-dump uses mysqldump program in the background and so is must faster than the pure PHP approach taken by BAM.
You can easily skip tables with sql-dump as well. See the help for this command.
Finally, some folks might want to use sql-sync which does all of these steps in one command. It works faster than sql-dump+sql_connect when one of the machines is remote. It also includes optional data sanitization.
Comment: Thanks for the info, and for your work with drush and devel.  I don't know how I could could get anything done w/o those two things.
Comment: We do pass the right params to mysqldump so that it's dump is consistent and safe ... Drupal's maint mode is not needed.
Comment: Moshe, does sql-dump take care of locking tables, maintenance mode, etc to ensure a safe backup?
Answer: I think the biggest advantages of bam-backup is that you can choose a profile.  With this you can do a bunch of different things.  The most useful is the ability to exclude the rows from the cache and watchdog tables.  I also think (though I have never confirmed it), that taking a backup this way will use maintenance mode just like via the UI, if you have it configured.  This can result in better backups if you have active traffic.
When I am doing normal backups as safeties, I just use bam-backup.  When I am doing a neuritic backup, or sending a db to a client for deployment, I also take a full backup with MySQL Administrator, which will properly lock tables.


How do you practice soccer effectively alone?

Question: I'm 15 and I want to practice soccer. So I searched for training projects and I've found 2 of them. But I don't have any friends at home, only at school. I've tried to go to those projects alone but I returned back, I don't know why, probably scared.
So my only chance is to practice by myself. How can I practice soccer with just a ball, no equipments?
Comment: Where do you live? No football clubs with youth teams in your vicinity? Practicing football on your own is very difficult. You might be able to pass/kick a ball perfectly where you want it, etc. But if you've got no idea where to run on a pitch/what to do in a game that serves to nothing in the end. If no other oppurtunities are availble, I'd say put up and finish one of those training projects.
Answer: Medicine ball such as 3kg for an adult and 1-2kg for adolescent is an awesome investment to improve your balance, patience and leg-eye coordination technique. Learn to balance on top of the medicine ball to work on your core, vital to fast turns and more advanced shots in soccer. Learn to keep the medicine ball on your leg and then proceed to real ball -- it is extremely motivating to see how fast you develop your technique!
If you cannot afford medicine ball, put a rock inside a styrofoam or tape and do your ball with some weight. Also experiment with some physics and put the weights on the exterior of the styrofoam and you realise that you are able to get a ball of similar properties as earlier with the weight in the middle but less weight.
My favourite thing while training alone is to use Medicine balls. You can use them for weight training, for technique, for massage, for anything creative -- go to a silent basement and learn to stand on top of medicine ball while getting support from the wall is one of the wow effect: little by little you learn new things and suddenly you realise how awesome you are getting in your technique proceeding from your basement to the fields.
Motivate yourself with awesome things such as

Freestyle Football: a lot of technique training, youtube with a lot of videos such as here
Balls of different weight: developing coordination and balance is easier with heavier balls because mass has its slowness, more mass so more force needed to adjust the ball -- my favourite are Medicine Balls such as 1,2,3,4 kg
Balls of different sizes

The good thing in medicine ball is that they are timeless.
Whatever your age, you can find them. You can find medicine balls of different weights and they don't get old. 1kg ball is awesome after an intensive game to relax your muscles. 1kg ball is equally awesome for a kid to feel his/her muscles better in his/her legs. If a child is not ready for 1kg ball, have an orange in a picnic or play some other round thing on April's fools day with your children.
Improving ligaments and joints early can safely be done in many other ways. The ways contain gymnastic, yoga, skateboarding, surfing, horse riding, dancing as well as balancing with medicine balls. Choose a method you like most and combine freely together as you wish. And remember to drink a lot of water so your joints, ligaments and bones are more resilient and no injuries in trying new things. Have fun.
Comment: OK well, "projects", in our country, are trainings of soccer with coaches and many balls. The projects have 4 levels; A, B, C and D. Level D is for beginners and A is for adult pros which probably will be chosen by a team to play in. I've joined the project once with a friend, for few days but I thought it as very tiring and a waste of time (the project starts in the early morning). And yes i can get that kinda wall.
Comment: And I have another case. There's a field in our neighborhood. I go there with a hope of somebody is there that I can play. I sometimes find some people a little older and much more skilled than me. One time, I played with them and scored an amazing goal from a distance. I play well at home. But at school, during, PE sessions, I could barely touch the ball(literally). I don't know if it is nervousness or anything(I feel a little nervous even if this is the third year in this school). And BTW I have a friend that is probably the top player from 9th grade, he'll probably be my mentor.
Comment: I suspect one thing to be a factor and it's that I don't get the ball that much. My teammates don't pass to me(b/c I can't play), and the other team which has the best players from our section. One time I got in to a team with my friend, the mentor, and made an assist for a great header.
Comment: Yeah, agree but i don't think I'm just gonna go to the field and just start running and shooting to an empty net. Should I just go to the project or do what I mentioned above?
Comment: Can you elaborate on the projects? You need to balance your efforts working alone with working socially, only way to get to the top is to make things progressively harder, quality is the key: playing against just one player can revolutinize your skills or open eyes to key weaknesses. Instead of shooting to a net, you can shoot to a wall where you have faster rebounds and more shots. Can you find a wall on which you can practise alone?
Comment: I would recommend to test different projects -- if you can find someone like mentor who has got best level, I would ask him/her to guide you. There can be big quality differences between projects. In [Finland](https://fi.wikipedia.org/wiki/Suomen_jalkapallon_sarjaj%C3%A4rjestelm%C3%A4), projects sound like divisions (From 1st, best, to lower). When I was your age, I got from 3rd division to the first division (playing in one year older group) and the intensity of the training, games, finance become just harder and harder. In 1st, perfect technique crucial to save energy, bones, joints...
Comment: @BenJunior It takes time to get used to high intensity training, not necessarily the best time to enter. Interval training is usually practised during winter season when no games while high intensity training during game season. When you feel tired, enough proper nutrition is crucial -- if you feel tired when you wake up, it can be due to low iron or low ferritin storages. Feel free to ask more specific questions about being tired after football training -- it can have many reasons.
Comment: @BenJunior variety of balls can be an issue, reason why you feel like not in touch when in school: the school balls can be old and over-used. Even though balls can be the same, age of the ball can matter or a reason you don't know, girls, peer-pressure? When I was in school for PE and I was not in touch, I relaxed and did warm-up instead -- you have good days and bad days, let it be like that. Make sure the next day is better than the one at a point. People may smirk at you and pressure you to be, new Ronald -- ignore them. Listen to yourself, your body, act diligently, focus on real training.
Comment: @BenJunior Dominance is an important thing in football that is hard to measure, a bit like dominance in chess. If player passes a ball, s/he does not want it to get lost and the goal is to score. A good player is able to predict 2-5 shots ahead. Please do not feel afraid to ask new questions.


Azure Form Recognizer Not Finding Content with Python on Databricks

Question: I am executing the following Python on Databricks with the relevant Cognitive Form recognizer libraries:
<code>from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import FormRecognizerClient
credential = AzureKeyCredential("aaa6123af5b843a38044538d95584c3d")
endpoint= "https://myformrecognizr.cognitiveservices.azure.com/"

form_recognizer_client = FormRecognizerClient(endpoint, credential)

with open("/dbfs/mnt/lake/RAW/export/Picturehouse.pdf", "rb") as fd:
    form = fd.read()

poller = form_recognizer_client.begin_recognize_content(form)
form_pages = poller.result()

for content in form_pages:
    for table in content.tables:
        print("Table found on page {}:".format(table.page_number))
        print("Table location {}:".format(table.bounding_box))
        for cell in table.cells:
            print("Cell text: {}".format(cell.text))
            print("Location: {}".format(cell.bounding_box))
            print("Confidence score: {}\n".format(cell.confidence))

    if content.selection_marks:
        print("Selection marks found on page {}:".format(content.page_number))
        for selection_mark in content.selection_marks:
            print("Selection mark is '{}' within bounding box '{}' and has a confidence of {}".format(
                selection_mark.state,
                selection_mark.bounding_box,
                selection_mark.confidence
            ))
</code>
The pdf form looks like the following:

The libraries recognizes
Cell text: Item
Cell text: Qty
Cell text: Seat Allocation
Cell text: Subtotal
Cell text: Adult
Cell text: 1
Cell text: D-11
Cell text: 14.50
But it doesn't recognize the following text from the pdf:

You can go straight to the screen by showing your e-ticket to an
usher. Alternatively, you can collect your tickets at Box Office at
least 15 minutes before the advertised start time of the film or
event. You need your Booking Reference and/or payment card to help us
find your booking. You can print this page by clicking the "Print This
Page" link above.

Is that by design? Or am I missing something in my code?
Answer: Unfortunately, the design is like that. The form recognizer is working on pre-trained models and that can recognize the key-value pairs, text, and tables from your documents and the table contents in the file uploaded as the input. Even though the file contains a large amount of text in paragraphs and table content in the middle or at any place, it will be recognized.
To know more details please Refer this link:
https://www.drware.com/extract-data-from-pdfs-using-form-recognizer-with-code-or-without/
https://www.youtube.com/watch?v=iBQO4QdUp6A&t=10s
https://github.com/tomweinandy/form_recognizer_demo
Comment: This looks exactly like what I need. Do you think the link will also help with my other question https://stackoverflow.com/questions/72304994/cognitive-text-anaytics-with-databricks-in-pyspark-mixing-string-and-dictionary
Comment: Yes, these links will be useful for other question too  : )


Problema com função mouseleave do jQuery para disparar popup

Question: Eu estou usando a função mouseleave para abrir uma popup quando o usuário mover o mouse para fora do site.
Esse é o código:
jQuery('body').mouseleave(function() {
            if (!jQuery('body').hasClass('leave-on') && localStorage.getItem("leave") != "closed") {
                jQuery('body').addClass('leave-on');
            }
        });

Mas eu tenho um problema com a trigger porque se eu clico no botão com a setinha para deslizar o slider, o mouseleave é disparado e a popup aparece.
Os botões que estão fazendo o mouseleave ativar:
Comment: Esse site está em português, então da próxima vez, por favor poste em português. Já traduzi a sua pergunta.
Answer: Realmente ao clicar em um elemento o evento mouseleave é disparado. Seria isso um bug uma vez que o mouse não saiu do body? Ou o evento click esteja disparando o evento? Fiz uma breve pesquisa e vi comentários de que isso seria mesmo um bug, enfim...
Para resolver isso fiz este código que cancela o evento mouseleave ao clique e restaurando-o após um breve delay de dez milésimos de segundo (10ms). Esse delay é necessário porque se você restaurar o evento imediatamente ele será disparado de qualquer jeito.
Mas mudei o foco dos eventos ao document em vez do body, o que é mais interessante porque irá detectar o mouse saindo da área do documento em vez do body, o que não é a mesma coisa. O body da página é apenas onde a tag  possui conteúdo, já o document é a área toda da janela onde é exibida a página, independentemente se tem conteúdo ou não.

Comentei as linhas do if para não exibir erro no snippet por causa
  do localStorage. Ao copiar o código, descomente as linhas.

Veja:

jQuery(document).ready(function(){
   var t = jQuery(this);
   t.on("click", function(){
      t.off("mouseleave");
      setTimeout(function(){
         t.on("mouseleave", function(){
            console.log("saiu"); // apenas para ilustrar, pode remover esta linha
            //if (!jQuery('body').hasClass('leave-on') && localStorage.getItem("leave") != "closed") {
               // jQuery('body').addClass('leave-on');
            //}
         });
      }, 10);
   });
   // disparo o evento para ativar o mouseleave
   t.trigger("click");
});

Ao clicar na div abaixo o evento mouseleave não é disparado e o console.log não será exibido:

Clique aqui

Comment: eu estava lendo aqui e é algum problema em relação ao svg...
esqueci de falar q `pointer-events:none` resolve o problema porém o botão não ficará mais funcional pois não aceitará o evento de click.

dê uma olhada nesse tópico: https://stackoverflow.com/questions/13631598/both-mouseleave-and-mouseout-triggering-too-often
e
https://stackoverflow.com/questions/24636602/mouseout-mouseleave-gets-fired-when-mouse-moves-inside-the-svg-path-element
Comment: Qual é o código mesmo desse svg?
Comment: Testei nos outros svg da pagina e eles também ativam o popup ao colocar o mouse em cima... Exemplo de um svg que no caso é só um icone com um link:
`

`
Obs: apenas no mozilla que ocorre o problema de ativar o popup ao colocar o mouse em um svg como esse.
Comment: Abre a popup apenas ao passar o mouse em cima, sem clicar?
Comment: exato... apenas no mozilla q ta ocorrendo isso


Mann-Kendall test for multiple groups

Question: I'm currently working on a problem, where I want to test weather there is a trend in the course of a certain metric in an animal, where I wanted to use something like the Mann-Kendall test. The problem is that I have data for multiple animals, which presumably have different starting values.
Therefore I think it is not wise compare all data points with each other but rather only data points of the respective animal with each other but I still want a result across all animals, e.g. the value decreases over time in all animals (with some tau value).
Is there a good way of doing it?
My Idea would be to modify the Mann-Kendall so that the mean of the rank difference is not taken across all possible pairs of permutation but rather only on the pairs of the same animal. But then also the variance has to be changed which seemed to me quite tedious to calculate and was probably done already. Does anybody know a source to that or how it is called?
Or is there a better way of doing it?

Thanks for your detailed response.
Regarding

A parametric model might be more powerful and more informative. A parametric model can provide information about the magnitude and linearity of the trend, not just whether it's "statistically significant."

I could find different opinions on weather to use parametric or non-parametric tests.
My current consense out of all what I read is that one should use parametric tests if there is reason to believe that the requirment is meet, i.e. most of the time some sort of normality assumption and else use non-parametric although parametric are often quite good also for not normality distributed data but are usaly outperformed by non-parametric test in this scenario. For my case there is no good reason to assume why the data should be normal distributed i even expect the error is more leaning to one side then to the other.
Furthermore I'm at the moment mainly interested in testing for trends in the data and i'm not sure weather they are linear.

Model time flexibly, for example with restricted cubic regression splines. You can then test whether there is evidence of a significant non-linear component to the trend.

This maybe solves this problem but i don't have any experience with such test and have to look into it.

Do separate Mann-Kendall tests on each of the animals. Get the normalized score value for each animal (S divided by square root of var(S), both provided by the MannKendall() function in the Kendall package). Determine whether the mean of the normalized score value over all animals is different from 0 via a one-sample t-test.

This works independent to the sample size? Because i only have 4 animals in total.
I just read about the seasonal mann Kandell test, this should yield similar results to your proposed method right? (each animal is one season)
Answer: Plot and inspect your data before you jump to a non-parametric test.
A parametric model might be more powerful and more informative. A parametric model can provide information about the magnitude and linearity of the trend, not just whether it's "statistically significant."
The Mann-Kendall test is just the Kendall rank-correlation test of values against time. As the manual for the Kendall() function in the Kendall package says:

It may also be noted that usual Pearson correlation is fairly robust and it usually agrees well in terms
of statistical significance with results obtained using Kendall's rank correlation.

The Pearson correlation is the standardized linear regression coefficient. So why not try simple linear regression versus time? Or, better, allow for a flexibly non-linear association of your outcome metric versus time. You can do that with a parametric regression model that includes time and the individual animals as predictors of your outcome metric.
Model time flexibly, for example with restricted cubic regression splines. You can then test whether there is evidence of a significant non-linear component to the trend.
Choose whether to treat animals as fixed or random effects based on your study design. Either approach will account for "different starting values." You could also allow for different trends among animals beyond their "different starting values" with interaction terms for fixed effects, or with random slopes.
If you nevertheless want to do Mann-Kendall tests you might take advantage of the following characteristic of the Kendall rank-correlation, from the above manual page:

An advantage of the Kendall rank correlation over the Spearman rank correlation is that the score function S nearly normally distributed for small n and the distribution of S is easier to work with.

Do separate Mann-Kendall tests on each of the animals. Get the normalized score value for each animal (S divided by square root of var(S), both provided by the MannKendall() function in the Kendall package). Determine whether the mean of the normalized score value over all animals is different from 0 via a one-sample t-test.
In response to revised question:

there is no good reason to assume why the data should be normal distributed

The data don't have to have a normal distribution. It's ideal if the errors around the model predictions are. Under much weaker assumptions, a linear regression (potentially including non-linear terms like regression splines) can provide very useful models.

I'm at the moment mainly interested in testing for trends in the data and i'm not sure weather they are linear

Restricting yourself to a trend test might undercut your ability to find the true association between outcome and time. For example, say you have a very rapid initial trend followed by a slow continued trend or no later trend. The Mann-Kendall test might well show no trend at all, depending on the proportion of your data from the late slow/no-trend timepoints. That's why I suggested looking at your data first. A regression spline or a generalized additive model can pick up that type of behavior over time while a simple trend test might not.

This [one-sample t-test] works independent to the sample size? Because i only have 4 animals in total.

With only 4 animals in your sample you have limited power to detect a true response, but you can still perform a 1-sample t-test to see if the mean normalized score over those 4 is different from the null hypothesis of a 0 mean value.

I just read about the seasonal mann Kandell test, this should yield similar results to your proposed method right?

I don't have experience with the seasonal test. If each animal has all measurements from a single season, it wouldn't seem to be helpful for you, as it evidently tries to account for seasonal variation within each time series.
Comment: @joaocandre In general, when there are correlations you are best served by a multivariate model and test. You might get the same point estimates, but the (co)variance estimates will be better as they account for the correlations. I don't have specific experience with the multivariate MK test, however.
Comment: There are [multivariate implementations of the MK test](https://rdrr.io/cran/trend/man/mult.mk.test.html) however, how would they compare to this simple t-test over independent MK tests? (In particular, does correlation between different time series have impact on the result?)
Comment: One additional comment I would make is that using a t-test allows testing for both (positive/negative) trends simultaneously, by using the absolute value of the test statistic (unsure if test requirements/assumptions remain valid)
Answer: Use z-Cusum because your variable may be increasing during a particular time interval and then decrease thereafter, effectively cancelling out over the whole timespan. Cusum can show when it is increasing and when it's not.

Mann-Kendall test for multiple groups


insert data into database using web service

Question: I am creating a custom web service. In this, as soon as service call, data should be store into database. I am using Hook_service_resource() function. How can i implement insertion into database using services. I created my_module.install file and prepare database schema. BUT i actually don't know how to use query in hook_service_resource() function.
Answer:
Create a Custom Drupal Module

Create these empty files in the new directory:

my_module.info
my_module.module
my_module.install
my_module.resource.inc
my_module.services.inc

Place this code in the my_module.info file:
name = My Module
description = My custom Drupal module.
package = Other
core = 7.x
dependencies[] = services
dependencies[] = rest_server

Place this code in the my_module.module file:
<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_module_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'my_module.services.inc'
    );
  }
}

Place this code in the my_module.services.inc file:
<?php

function my_module_services_resources() {
  $resources = array(
    'my_module_resources' => array(
      'actions' => array(
        'insert_into_database' => array(
          'help' => t('Insert Database Example.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'my_module',
            'name' => 'my_module.resource',
          ),
          'callback' => 'my_module_insert_into_db',
          'args' => array(),
          'access arguments' => array('access user profiles'),
          'access arguments append' => FALSE,
        ),
      ),
    ),
  );
  return $resources;
}

Place this code in the my_module.resource.inc file:
<?php

function my_module_insert_into_db() {
  $id = db_insert('example_table') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
))
->execute();
  if ($id) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Change the access arguments as per your permissions settings..
Call the service
http://www.example.com/?q=serviceendpoint/my_module_resources/insert_into_database.json


Commerce 2.0: How can multiple email addresses receive copies of orders?

Question: If I understand the configuration correctly, only one email address can be specified when defining a Store (the text under the field says "Store email notifications are sent from this address".
When a person places an order, they will receive an email confirmation showing as being sent from that Store owner's email address. No one else - not even the store owner - gets an email copy of the order.
I am converting a client's website from Wordpress to Drupal 8. Their current configuration is that four different people in the office all receive email copies whenever an order is placed. How can the same be implemented in Commerce 2.0? (They don't want to log into the site and check the database for new orders - they want the email notifications sent to them if and when orders are actually placed.)
Has anyone already implemented something similar?
Answer:
Their current configuration is that four different people in the office all receive email copies whenever an order is placed.

See our documentation for order receipt emails: https://docs.drupalcommerce.org/commerce2/user-guide/orders/customer-emails
I think you'll be fine adding those four emails separated by commas.
EDIT: Also see our docs for setting up HTML emails https://docs.drupalcommerce.org/commerce2/developer-guide/core/html-emails
Comment: Matt:  Sorry for my delay in responding - I was busy taking the client's site live.  At the time I made my original post that section of the documentation you referred to was blank.  AndyD328 over on Drupal.org indicated on Oct 17 that he was going to add that section to the docs.
Comment: marrer let me know if my answer works, to send multiple emails by just entering `firstname.lastname@example.com, email@example.com` and so on. That way it can be found here and we can update the docs.


Does every sequence $4^nx_0+\frac{4^n-1}{3}$ contain a prime?

Question:
Does every sequence $4^nx_0+\dfrac{4^n-1}{3}$ contain a prime?

Fix some odd positive integer $x_0$ and define the sequence $x_0,x_1,x_2,\ldots$ as follows:
$x_n=4^nx_0+\frac{4^n-1}{3}$
So for example choosing $x_0=1$ gives the sequence:
$1,5,21,85,\ldots$
And choosing $x_0=3$ gives the sequence:
$3,13,53,214,\ldots$

Does every such sequence contain a prime number?

Dirichlet's Theorem states that there are infinitely many primes in every arithmetic progression:
$a, a+d, a+2d,\ldots$
where $a,d$ are coprime.  But I'm unaware of similar results for other progressions.  I found this paper (which is beyond me) but my rudimentary understanding suggests this is saying the result is unknown for geometric progressions.
The progressions I'm asking about are exponential in nature.  These are in fact the canonical set of linear combinations of the Lucas Sequences $U_1(5,4)$ and $V_1(5,4)$ over the odd integers.
Every successor $x_n:n\geq0$ is of course $\equiv 5\mod 8$ while every sequence for which $x_0\not\equiv\{1,3,7\}\mod 8$ is a subsequence of a longer sequence (with a smaller starting number), which does start with $x_0\equiv\{1,3,7\}\mod 8$.
So the set of all odd integers can be canonically indexed according to membership of the sequences starting with $x_0\equiv\{1,3,7\}\mod 8$.
I suspect these sequences have a close relationship with the kernel of the 2-adic logarithm, although I don't know a lot about that.
EDIT
So far we have found that $5$ is the only prime in $1,5,21,85,...$ so not every sequence has infinitely many primes.
UPDATE
Peter posted this related question for a candidate for a sequence with no primes and Paolo Leonetti has elegantly verified it has no primes, plus provided a class of such sequences which contain no primes; those for which $3x_0+1$ is a square number.
Comment: Look up [Dirichlet's theorem](https://en.wikipedia.org/wiki/Dirichlet%27s_theorem_on_arithmetic_progressions)
Comment: Does Dirichlet's theorem have a case that covers exponentially distributed sequences?
Comment: $4^{72}\cdot 8+\frac{4^{72}-1}{3}$ is a Fermat-pseudoprime to bases $3$ and $5$ , but composite. $x_0=8$ is a hard case as well.
Comment: @stevengregory thanks. I was aware of that... And can see it's related. But does it decide this? These sequences are neither arithmetic not geometric progressions.
Comment: @Valborg precisely
Comment: For a fixed n, they are indeed arithmetic progressions.
Comment: @stevengregory But that doesn't stop some fixed $x$ from dodging all primes, at least not obviously.
Comment: In the example, $1,5,21,85\dots,$ what is $x$?  In particular, how do you get $1$?
Comment: @saulspatz I believe that had n=0 and x=1
Comment: Then the question should say $n=0,1,2,\dots$ instead of $n=1,2,3,\dots$
Comment: If we are going to exclude $n=0$, it would appear that $x=5$ is a great candidate to hunt for a prime free sequence. If we include $n=0$, then try $x=21$.
Comment: @saulspatz you're right about the possibility of starting that sequence at 0 but the subsequence i give starting at 1 is also such a sequence. In fact for every sequence you can start at any point along it and that is also such a sequence so I am actually asking if every sequence has infinitely many primes. Although the weaker result that we can start as low as possible, i.e. at some number $\equiv 1,3,7\mod 8$ and always find at least one prime would be something.
Comment: @Peter I was only considering odd numbers and yes, sequences including $x_0$. If i understand correctly you mean the sequence $x_0\ldots=33,133,533,\ldots$ is a hard case?
Comment: @Peter if you allow even $x_0$, every $x_1$ is $\in \{1,3,7\}\mod 8$ anyway so it makes no odds, they're the same sequences
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/75052/discussion-between-peter-and-producer-of-bs).
Answer: Aside of the nice solution provided in the other thread, which uses the algebraic factorization of the original formula when $3 x_0+1$ is a square, I have found a list of further solutions for $x_0$ such that the associated sequence contains no primes/only composites.
The sequences from $$x_0 \in \{371,495,775,1671,2171,3211,3955,4215,4655,4711,... \} \\
\text{have as well no prime entries.} \hspace{160pt} $$
This can easily be proved by looking at the small primefactors $p \in \{3,5,7,13\}$ : their cyclical occurences in the respective iteration sequence $S(x_0)$ have lengthes $\text{cyclen}(x_0,p) \in \{2,3,6\}$ and cover completely the $6$ leading entries of their sequence. Due to cyclicity each entry of the sequences $ \gt 13$ cannot be prime.
Example for $x_0=371$:
 N     primefact's x_N   Covering periodically
                          6 of 6 residueclasses
- - - - - - - - - - - - - - - - - -
[ 0           "7.53"]       __7_        == 371
[ 1       "3^3.5.11"]       35__        == 4*371+1
[ 2         "13.457"]       ___1        == 4*(4*371+1)+1
[ 3       "5.7^2.97"]       _57_
[ 4        "3.31687"]       3___
[ 5      "5.113.673"]       _5__
- - - - - - - - - - -
[ 6     "7.11.19753"]       __7_
[ 7    "3.5^2.81119"]       35__
[ 8    "13.293.6389"]       ___1
[ 9  "5.7.1427.1949"]       _57_
[10 "3^2.1423.30403"]       3___
[11  "5.11.28317907"]       _5__
- - - - - - - - - - - -
 ... ... ... ...  ...

Unfortunately I didn't find any further algebraical expression of this phenomenon, like the style of the one that has already been given with the $3x_0+1 \text{ -is-square}$ class of solutions.
Moreover there might be some further characteristics in/by the following list of $x_0$. The list has been created by checking the computing time up to $1000$ iterates, where the ones with $0$ msecs have been the suspect ones, and which gave the examples of the above mentioned covering-primefactors-solutions:
$$ \quad \text{covering } \; \mid \; \text{ heuristics}  \phantom{sequence beginning at $35$ has a prime (see update at bottom)} \\
\small \begin{array} {rrr||rrr}
 x_0 & \# & \text{msecs}& x_0 & \# & \text{msecs}\\ \hline
 371 & 0 & 0 & 35 & 0 & 125  & \text{sequence beginning at $35$ has a prime (see update at bottom)}\\
 495 & 0 & 0 & 603 & 0 & 171 \\
 775 & 0 & 0 & 1195 & 0 & 282 \\
 1671 & 0 & 0 & 1335 & 0 & 218 \\
 2171 & 0 & 0 & 1379 & 0 & 266 \\
 3211 & 0 & 0 & 1611 & 0 & 31 \\
 3955 & 0 & 0 & 1751 & 0 & 141 \\
 4215 & 0 & 0 & 2755 & 0 & 172 \\
 4655 & 0 & 0 & 2775 & 0 & 234 \\
 4711 & 0 & 0 & 2791 & 0 & 156 \\
 4971 & 0 & 15 & 3179 & 0 & 250 \\
 5195 & 0 & 0 & 3379 & 0 & 140 \\
 5831 & 0 & 16 & 4011 & 0 & 204 \\
 5955 & 0 & 0 & 4235 & 0 & 94 \\
 6235 & 0 & 0 & 5395 & 0 & 141 \\
 7131 & 0 & 0 & 5495 & 0 & 47 \\
 7631 & 0 & 0 & 5751 & 0 & 93 \\
 8671 & 0 & 0 & 5975 & 0 & 125 \\
 9415 & 0 & 0 & 6215 & 0 & 93 \\
 9675 & 0 & 0 & 6571 & 0 & 141 \\
 10115 & 0 & 0 & 6671 & 0 & 140 \\
 10171 & 0 & 0 & 6875 & 0 & 126 \\
 10431 & 0 & 0 & 7551 & 0 & 171 \\
 10655 & 0 & 0 & 7775 & 0 & 203 \\
 ... & ... & ... & ... & ... & ...
 \end{array}$$
where "#" denotes the number of primes found up to tested  iterations.
The timings were measured for up to $N=1000$ iterations
(using primecertifying isprime() in Pari/GP vers. 2.14, 64 bit.
updated table:The column headed with "covering" contains that cases of $x_0$ for which the covering by the small primes occurs, so this gives proven non-prime sequences, the column headed with "heuristics" contains the cases, where the primecertification showed all iterates being composite but only up to $N=1000$ (for up to $N=8000$ iterations I used the ispseudoprime() test).
For instance, $x_0=35$ needs further work to discern whether the iterations sequence has primes or not; there have been a couple of prime-canditates by a fast (pseudo)prime-test for $N>1000$ but which were certificated to be composite with the more intense isprime()-function. The time to do this increases excessively and unpredictable, so I stopped testing of $x_N$ at $N=2000$.
update 3.feb.2022 The sequence beginning at $x_0=35$ seems to contain a prime at $(106 \cdot 4^{4553}-1)/3$ as certified by the prime-tester of Dario Alpern. The number $x_{4553}$ has $2743$ digits and leading and trailing digits $5 337343 165620  \ldots 969933 010261$
Comment: see a pdf-version in https://go.helms-net.de/math/divers/mse/PrimesInSyracuseTree.pdf
Comment: Nice work.


Is all integration that are computable able to be compute by the substitution method and/or integration by parts method?

Question: Is all single-variable integration that are computable by mathematician theoretically able to be compute by the substitution method and/or integration by parts method?
If not, does that mean much work have to been done additionally by the mathematician in the future?
Comment: The result [$\int_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi}$](https://en.wikipedia.org/wiki/Gaussian_integral) is one that cannot be achieved by finding an antiderivative (since $e^{-x^2}$ has no elementary antiderivative), so it certainly can't be found by substitution or integration by parts.  There are many such definite integrals that may be found without computing an antiderivative.
Answer: Every antiderivative that can be expressed in closed form can (in a somewhat trivial sense) be obtained by substitution. If $\int f(x)\,dx=F(x)+C$, then the substitution $u=F(x), du=F'(x)\,dx=f(x)\,dx$ does the trick.


why does twig's render function create a subrequest

Question: why does twig's render function create a subrequest ? Why dont they just render the response and send it as part of the response ?
Also I can see that the rendered response appears in the browser just after the main template shows up. How does it happen ?
Answer: I created an answer on Stackoverflow which basically goes through the different alternatives of the render function.
It also explains why you should be using the render function over a regular include.
I'd advise you to read the chapter about embedding controllers in Twig. An interesting quote from the doc about when you should consider using the render function:

Whenever you find that you need a variable or a piece of information that you don't have access to in a template, consider rendering a controller.

TL;DR
By default, the render function only takes a URL (either absolute or relative).
By analogy it is like getting HTML through ajax and injecting it in the page: one request that queries a controller to get some HTML which get injected it into the page.
There are different render calls like render_esi (for support of the ESI tags) that have their own rendering strategies. If you start with the inline rendering (through the default render function) you will have the opportunity later on to use other rendering strategies without refactoring your code.
The render function is meant to scale your application.
For more details about its usefulness, let's look at the render_esi function.
With the render_esi function you can implement ESI tags to use with Varnish.
(There are other solutions than Varnish but it's among the most popular ones)
Varnish is a caching solution that is located between your web servers and the users. Varnish will filter the response from your web servers, cache the entire page then look for these ESI tags.
If Varnish cached your page for a day but the render_esi function are set to be cached for 2 hours, Varnish will only query (through a URL when the cache expired) for these specific render calls instead of the entire page (which is why render_esi do sub-requests) and replace parts of the template with the sub-requests' response.
Caching in general is very interesting and very broad so it's hard to go over every details in my answer but I hope my answer will help you.
Caching (or cache) according to Wikipedia:

In computer science, a cache (/ˈkæʃ/ kash)[1] is a component that transparently stores data so that future requests for that data can be served faster.
Comment: I like your answer, but as I understand, you don't need any Twig functionality to use ESI. It is a proxy (Varnish in this case) functionality, you just put ESI tags wherever you want and proxy makes requests (and caching) for that tags, so no subrequests (inside an app) are needed. I may be wrong, I never used ESI, this is just how I understand it.
Comment: You don't have to use `render` in order to use the ESI tags but you might as well use it because it's [officially documented/supported](http://symfony.com/doc/current/book/http_cache.html#edge-side-includes), convenient and provides consistency in the app, right?
Comment: Yes, but I'm pointing out that statement *"with the render function you can implement ESI tags"* can be wrong. You don't use `render` for it, you use `render_esi`, as documentation says. Is that correct?
Comment: Correct, I didn't phrase my response properly, I'll change that
Answer: Render is used when you not just want to include another template snippet, but also want to execute specific businesslogic, that belongs to this template. Or in other words: When include just isn't enough, you use render.
Because render doesn't only include a template, but also executes controller logic, it is encapsuled as a subrequest.
Imagine you want to display the latest news in a box on every page of your website. If you want to solve this with an include, you would have to fetch the latest news in each of your actions and pass it to your template.
But if you use render, you just write one action for this, and put a render tag everywhere in your templates where you would like to have that news box. The render tag executes the associated controller action, renders the response, and injects it into your current template.
Because I suck at explaining, you might also want to read this part of the symfony doc: http://symfony.com/doc/current/book/templating.html#embedding-controllers
Answer: In my opinion, answer should sound like this:

Controller is pretty simple "unit" which receives request and sends response.
Creating sub request for rendering controller gives you more power (flexibility).

About flexibility. Look at your controller, just like it just receives request and sends response and for example, you want to somehow filter request or decorate response? Where will you put this logic? Of course, at event listeners which can use other services to solve this task.
For example, I often use parameter converters for my controllers (it's not about good design, just for example). So how can I use "render", with specifying just id of my entity, to render only controller without creating sub request?
If you really want just to render some data you can use "include" or create an extension. Or you can create extension to render controllers without sub request, but think about it carefully, because further you can add more logic to filtering response and so on.
I can be wrong, it's just my opinion ;)
Comment: I agree with this answer. render needs a whole Request process as it calls a Controller.