Proving If $\int^{\frac{\pi}{2}}_{0} f(x) \cos x dx \lt f \left(\frac\pi2\right),$ then $ \int^{\frac{\pi}{2}}_{0} f'(x) \sin x dx \gt 0. $

Question: how do i tackle such problems?
Let f(x) be a function differentiable on the interval$ $$\Bigl[$$ 0, \frac\pi2 $$\Bigr]$$ $
such that f'(x) is integrable on this interval.
Prove the following assertions:
(1)
If $$\int^{\frac{\pi}{2}}_{0} f(x) \cos x dx \lt f \left(\frac\pi2\right),$$ then $$ \int^{\frac{\pi}{2}}_{0} f'(x) \sin x dx \gt 0. $$
(2)
If $$f\left(\frac\pi3\right) = \sqrt{3}f\left(\frac\pi6\right),$$ then
$$ \int^{\frac{\pi}{3}}_{\frac{\pi}{6}} f(x) sinx dx = \int^{\frac{\pi}{3}}_{\frac{\pi}{6}} f'(x) cosx dx.$$
Comment: Hint: Use integration by parts for both.
Answer: For (1), using integration by parts we have
\begin{align}
\int_{0}^{\pi/2}{f(x)\cos x dx} \ & = \left. f(x)\sin x \right|_{0}^{\pi/2}-\int_{0}^{\pi/2}{f'(x)\sin x dx} \\
& =f(\pi/2)\sin(\pi/2)-0-\int_{0}^{\pi/2}{f'(x)\sin x dx} \\
& =f(\pi/2)-\int_{0}^{\pi/2}{f'(x)\sin x dx}
\end{align}
Then $\displaystyle{\int_{0}^{\pi/2}{f(x)\cos x dx}}<f(\pi/2)$ implies $\displaystyle{\int_{0}^{\pi/2}{f'(x)\sin x dx}}>0$.
For (2) we can use integration by parts too.
\begin{align}
\int_{\frac{\pi}{6}}^{\frac{\pi}{3}}{f(x)\sin x dx} & = \left.-f(x)\cos x\right|_{\frac{\pi}{6}}^{\frac{\pi}{3}} + \int_{\frac{\pi}{6}}^{\frac{\pi}{3}}{f'(x)\cos x dx} \\
& = -f(\pi/3)\cos(\pi/3)-[-f(\pi/6)\cos (\pi/6)] + \int_{\frac{\pi}{6}}^{\frac{\pi}{3}}{f'(x)\cos x dx}\\
& = -\frac{1}{2}f(\pi/3)+\frac{\sqrt{3}}{2}f(\pi/6)+ \int_{\frac{\pi}{6}}^{\frac{\pi}{3}}{f'(x)\cos x dx}\\
\end{align}
From here it is clear that $f(\frac{\pi}{3})=\sqrt{3}f(\frac{\pi}{6})$ implies $\displaystyle{\int_{\frac{\pi}{6}}^{\frac{\pi}{3}}{f(x)\sin x dx}=\int_{\frac{\pi}{6}}^{\frac{\pi}{3}}{f'(x)\cos x dx}}$.
Comment: what about (2)?


Record video and and download it with border in python using open cv and flask

Question: I'm attempting to record a video and download it with a border. I'm using the RGB color values 0, 0, 255 for the border. While I can easily download the recorded video, the border does not appear on it. When I click on the 'Start Recording' button, recording is initiated. Upon clicking the 'Stop Recording' button, a download button appears containing the link to download the video. However, the downloaded video lacks the border.
APP.PY
from flask import Flask, render_template, send_file
import cv2
import numpy as np

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def add_border_to_video(video_path, output_path, border_thickness=20, border_color=(0, 0, 255)):
    cap = cv2.VideoCapture(video_path)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path, fourcc, 20.0, (frame_width, frame_height))

    while True:
        ret, frame = cap.read()
        if not ret:
            break
        # Add border to the frame
        bordered_frame = cv2.copyMakeBorder(frame, border_thickness, border_thickness, border_thickness, border_thickness, cv2.BORDER_CONSTANT, value=border_color)
        out.write(bordered_frame)

    cap.release()
    out.release()

@app.route('/record_video')
def record_video():
    # Record video with OpenCV
    # Make sure to save it to a file
    # For simplicity, let's assume the file is named 'recorded_video.mp4'
    recorded_video_path = 'recorded_video.mp4'

    # Add border to the recorded video
    bordered_video_path = 'output_with_border.mp4'
    add_border_to_video(recorded_video_path, bordered_video_path)

    return 'Video recorded and bordered successfully!'

@app.route('/download_video')
def download_video():
    # Serve the bordered video file for download
    bordered_video_path = 'output_with_border.mp4'
    return send_file(bordered_video_path, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)

INDEX.HTML (HTML AND JS)

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Record and Download Video</title>

Record and Download Video

        <video id="video" width="640" height="480" autoplay></video>

    <button id="startRecord">Start Recording</button>
    <button id="stopRecord" disabled>Stop Recording</button>
    Download Video

Comment: is this a flask problem or an opencv problem, or matter of figuring out what code to write? [mre] please
Comment: Just for debugging purposes: have you tried to do the record part directly inside the donwload_video and test the download route?
Comment: yes, but still same issue, can you figure where im doing wrong
Comment: so, the bordered video display the right images but lakes of border?
Comment: yes i can download the video without border, there is no border applied.
Answer: This aim to be a minimal example with focus on how and where pre- and post-process a video. No JavaScript is needed.
Due to the huge amount of online tutorial copying each other out I tried to give an "improved" version and also use coroutines to better separate the tasks of pre and post processing.
Once opening the root page, for ex localhost:5000/, the the camera will be turned on and automatically the video will be recorder. For stop the recording close the window (or partially reload the page).
import time
from flask import Flask, render_template, Response, render_template_string, stream_with_context
import cv2

def coroutine(func):
    def start(*args, **kwargs):
        cr = func(*args, **kwargs)
        next(cr)
        return cr
    return start

@stream_with_context
def stream_main(target, path_video):
    cap = cv2.VideoCapture(0)

    if not cap.isOpened():
        print("Cannot open camera")
        # do routing stuffs
        #cap.release() # don't forget it:)
        return

    # type of the file extension that defines the output format
    frame_ext = '.jpg'
    if not frame_ext.startswith('.'):
        frame_ext = '.' + frame_ext

    # frame info
    frame_size = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # "initialize" coroutine
    target = target(path_video, *frame_size)

    # wrap binary image to html content
    def video_frame_content(frame:bytes) -> bytes:
        return b''.join((b'--frame\r\nContent-Type: image/jpeg\r\n\r\n', frame, b'\r\n'))

    while True:
        # capturing data (frame) from the camera
        ret, frame = cap.read()
        if not ret:
            print('Stream ended/interrupted?')
            break

        # save the frame
        target.send(frame)

        # pre-process the "live"-frame    <--------------
        # example: flip along the y-axis
        frame = cv2.flip(frame, flipCode=1)

        # prepare for streaming
        #
        # encodes an image into a memory buffer
        ret, buffer = cv2.imencode(frame_ext, frame)
        if not ret:
            print('At Frame XY a problem occurred')

        yield video_frame_content(buffer.tobytes())

        # FPS
        time.sleep(0.04) # not mandatory

    cap.release()
    target.close()

@coroutine
def video_writer(dst_video, frame_width, frame_height):
    # post processing the frames

    # or declare them as parameters
    border_thickness = 20
    border_color = 0, 0, 255

    # video recording
    out = cv2.VideoWriter(
        dst_video,
        cv2.VideoWriter_fourcc(*'MJPG'.lower()),
        10,
        (frame_width+2*border_thickness,frame_height+2*border_thickness)
    )

    try:
        while True:
            # read the frame
            frame = (yield)

            # post-processing  <----------------
            # example: add border
            bordered_frame = cv2.copyMakeBorder(
                frame,
                border_thickness, border_thickness, border_thickness, border_thickness,
                cv2.BORDER_CONSTANT,
                value=border_color)

            out.write(bordered_frame)
    except Exception:
        # Done
        pass
    finally:
        out.release()

# routing
#########

# to add
path_video_border = # path of the new .mp4 file

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('Testing camera:
')

@app.route('/video_feed')
def video_feed():
    # returns the streaming response
    return Response(stream_main(video_writer, path_video_border), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == "__main__":
    app.run(debug=True)

Notice further that in the OP there is a mistake when the writer is initialised: by adding a border to the frames their size change as well out = cv2.VideoWriter( [...], (frame_width + 2*border_thickness, frame_height+2*border_thickness)).
Comment: still no border
Comment: ok, I will investigate further. I found very strange that you were able to read the video with the wrong frame size
Comment: I fear is on JS/HTML-side... opencv is not processing that video (this explain why you didn't saw the mistake of the frames) and the downloaded video is called `recorded_video.webm` which has a different extension than the one in your code. Maybe you should add some Jinja code in index.html which process the output of the recording process
Comment: Jinja is installed together with Flask if I remember well, check it with `pip list`. It is a templating engine
Comment: Notice further that opencv support (multi) video capture with the following syntax `v2.VideoCapture(0)`. At the moment I can do much more than this
Comment: check [this](https://www.dynamsoft.com/codepool/web-camera-recorder-oepncv-flask.html) tutorial
Comment: the tutorial is about recording and download that video, no border is applied on it.
i have alredy done this
Answer: Your code for adding a border doesn't take into account that the border makes the individual frame of the video larger. For this reason, the edited video cannot be played.
You also added the URL of the unedited video to the download button. The original is never sent to the server. Because of this, the code to add the border is not executed and the border is also not visible in the downloaded video.
The following example shows you how to record a video on the client side and send it to the server where it is edited. The edited video is then offered for download.
from flask import (
    Flask,
    abort,
    render_template,
    request,
    send_from_directory
)
from mimetypes import guess_extension
from werkzeug.utils import secure_filename
import cv2
import os
import tempfile

app = Flask(__name__)
app.config.from_mapping(
    UPLOAD_FOLDER=os.path.join(app.instance_path, 'uploads')
)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html')

@app.post('/upload')
def upload():
    file = request.files.get('video')
    if file and file.filename != '':
        extname = guess_extension(file.mimetype)
        if not extname:
            abort(400)

        # Check the allowed file types here.

        with tempfile.TemporaryDirectory(dir=app.config['UPLOAD_FOLDER']) as tmpdirname:
            srcfile = secure_filename(f'{file.filename}{extname}')
            srcpath = os.path.join(tmpdirname, srcfile)
            dstfile = f'output.mp4'
            dstpath = os.path.join(tmpdirname, dstfile)
            file.save(srcpath)

            convert(srcpath, dstpath)

            return send_from_directory(tmpdirname, dstfile)

    abort(400)

def convert(src, dst, border=10, clr=(0,0,255)):
    cap = cv2.VideoCapture(src)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    out = cv2.VideoWriter(
        dst,
        cv2.VideoWriter_fourcc(*'mp4v'),
        20.0,
        (frame_width + 2*border, frame_height + 2*border)
    )

    while True:
        ret, frame = cap.read()
        if not ret:
            break
        frame = cv2.copyMakeBorder(
            frame,
            border, border, border, border,
            cv2.BORDER_CONSTANT,
            value=clr
        )
        out.write(frame)

    out.release()
    cap.release()

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>

        <video id="video" width="640" height="480" autoplay></video>

    <button id="start">Start Recording</button>
    <button id="stop" disabled>Stop Recording</button>
    Download

Comment: there is some issue in your app.py file, cant run my project
Comment: @MEB The application ran without any problems for me. Which issue? Is there an error message?
Comment: @MEB I didn't add an `if __name__ == '__main__': app.run(debug=True)` line because I run the application via `flask --app app.py --debug run`. Add the line and you can run the app as usual.
Comment: I'm glad I could help you. If you are satisfied with the result, please click on the check mark to accept the answer.


Fiber link suddenly degrades, cold weather? (Turns out not.)

Question: I live in a dorm where the network is mostly resident-managed and budget is limited.
The network is a basic star topology, with a central switch in the server room branching out to switches that feed two hallways each, with no redundancy. The links from the server room to the hallway switches are fiber optical runs, running at 1 Gbps.
Yesterday, one of the links suddenly degraded heavily, and begun intermittently losing large amounts of packets. The link still somewhat works, but there are periods ranging from a few seconds to upwards 15 minutes where almost all packets are lost. There are no signs of faults in router or switch software or hardware. Our testing shows it is most likely the fiber run that is failing.
We have tried degrading the link to 100 Mbps, this does not improve the quality. We still haven't finally determined the fiber link to be the fault, but intend to make a final check for that later.
There is no option of running a copper cable.
I suspect that it may somehow be caused by the winter weather, although there shouldn't be a good explanation for this, I assume there is proper insulation where the cable runs. The real question here is: Is cold weather a plausible explanation for this sudden fault, and in that case, can we expect the link to improve again once the weather gets warmer?
Update: It turns out that the fiber pair is in fact fine and it has to be a failing client causing the problem. We should be able to handle that.
Comment: Have you traced the fiber line to make sure someone do something stupid like bend it around a corner or pinch it into a too tight crevice in the wall?
Comment: Everywhere the fiber is exposed is behind locked doors, so nobody without business should have had access. The run has worked flawlessly for years.
Answer: I've seen fiber do weird things when it fails. Usually though it just drops, period, and won't sync up. You're saying that it just "degrades".
Have you determined that it isn't being flooded with something? It's odd that it works but is just dropping packets. No excess network traffic? Mainly because I wouldn't be surprised seeing as this is a dorm room you're getting degradation from.
Is it possible that winter weather causes something? It's possible. Depends on how exposed the conduit is. Glass is glass, if exposed to extreme temps it could do something odd. Ideally it's not exposed to such circumstances, though.
One thing to try if you're not using VPNs or special network configuration is switch the working fiber on the switch with the non-working one and see if the behavior suddenly shows up on the other dorm while the other one has it go away. That will tell you if it's the fiber connection on the switch and not the fiber run. If it's a Cisco switch with modules you can switch the modules on the dorm side to see if it's the hardware causing issues.
I'd definitely rule out someone trying to use file sharing or torrent software though. Any of that can bog down a switch fairly easily, depending on the hardware.
Comment: Not if the routing tables are being overwhelmed. We've had that happen with malware that hits hundreds of IP's in a very short span of time.

For the fibers, you mean two pair (one to building one, one to building two) are affected, or one building is being affected?

It's *possible* that cold can cause it. But it shouldn't be. If it's that exposed, you're going to probably have trouble over time and it should be replaced with new fiber (better insulated) or a radio link of some kind, depending on the configuration of the site.
Comment: If your switch supports it, you can mirror traffic to another port. Then monitor traffic through traffic sniffing. You see a lot of weird traffic via all email, or random streams of requests all over with no rhyme or reason, chances are malware or torrents can be contributing. SNMP may help also with gathering stats on how much traffic is going by protocol where and on what port.
Comment: It would be very hard for a single room to overload the fiber link, as the links to individual rooms are 100 Mbit. The traffic graphs towards the Internet don't show any irregular traffic patterns.
I forgot to mention, both fibres seem affected, traffic in either direction is lost so there is no fallback.
It's good to know that the cold may affect it, unfortunately the forecast shows the freezing weather may continue for another two weeks.
Comment: Better insulated meaning the conduit path, not some special fiber clad in space age cladding :-)
Comment: It's just one fiber pair that is affected, this pair is servicing two hallways in the building. (There is only one building.) The remaining 7 fiber pairs seem to be unaffected. I'm not sure how thorough a malware check has been performed, so another may be in order.
Comment: When you're asking about temperature, is the fiber actually exposed outside or in a particular location? I.e., does it make sense that it's affecting this one pair and not the others, when or if other pairs are running in similar paths to this one and similar environments?
Comment: Again, moving that pair to another fiber module on the switch where they all consolidate links in the central server area can narrow down if it's the ports on the switch vs. the run. If you just swap them on the central concentrator and the problem suddenly moves to a new location, bing! You know it's the fiber module on the switch. If you can swap modules on the remote side of the link that can narrow that down too.
Comment: While it would not make you popular with the other hallway, you could try swapping the fiber pair to another hallway.  That would narrow down it to be a switch/user/application issue, or if it really is in the fiber.  Fiber properly installed is fairly resistance to environmental issues, but there are a lot of mistakes that can be made.  In this case you may have a pinch or a kink somewhere and the movement of the fiber with temp shrinkage has cause a failure.  If that is the case it may not come back when temps warm up.
Comment: We tried hooking up a PC directly to the fiber, instead of the switch, obviously taking the entire hallway down. There were no problems with the link then, so the problem in fact has to be a failing client. We'll figure out which port is causing the problem and talk to the resident. Thank you for your help!
Answer: If parts of the system are getting very cold, there could be mechanical changes due to thermal expansion. I seem to recall that fiber is very sensitive to alignment issues.
Though I would be surprised to find that an issue with this cause was intermittent.


Grouping nodes in a graph to minimize sum of edges (Does this problem have a name?)

Question: I came across this problem at work trying to decide the most efficient way to group services in processes. I don't have the right words to google it.
I will use shops as a metaphor.
Let's say you have N stores that you want to place in M shopping centers. For each pair of stores you have a count of how many times per day a person will walk from each store to each other store. When stores are placed in the same shopping center, the cost to walk between them is low, but when you have to walk between shopping centers, the cost is high. How do you place the stores to minimize the total cost? (Let's assume that every shopping center needs to have N/M stores in it)
Right now I'm thinking you can represent each store as a node on a graph and then each node would have an edge (both ways) to ever other node. Then you want to somehow combine the N nodes in the graph into M big nodes so that they have some internal travel cost, and some external travel cost.
Does this problem have a name (like traveling salesman etc)? Are there existing algorithms to solve it? What words do I google?
Answer: This is called the quadratic assignment problem.  The traveling salesman problem is a special case.


parsing meta tag with Beautiful Soup and Python

Question: Im having trouble parsing a HTML page using Beautiful Soup 3, and python 2.6.
The HTML content is this:
content='

When

<meta itemprop="startDate" content="2012-11-23T10:00:00.0000000">
STARTSFri 23 Nov,10:00AM

<meta itemprop="endDate" content="2012-12-03T18:00:00.0000000">
ENDSMon 03 Dec,6:00PM

 Cal

'

And I want to get the string 'Fri 23 Nov,10:00AM' out of the middle into a variable, for concatenating, and sending back to a PHP page.
To read this content, i use the following code:
(the content above comes through from a html page read (http://everguide.com.au/melbourne/event/2012-nov-23/life-with-bird-spring-warehouse-sale/)
import urllib2
req = urllib2.Request(URL)
response = urllib2.urlopen(req)
html = response.read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html.decode('utf-8'))
soup.prettify()
import re
for node in soup.findAll(itemprop="name"):
    n = ''.join(node.findAll(text=True))
for node in soup.findAll("div", { "class" : "egV2_EventReportCardLeftBlockShortWidth" }):
    d = ''.join(node.findAll(text=True))
print n,"|", d

Which returns:
[(ssh user)]# python testscrape.py

LIFE with BIRD Spring Warehouse Sale |
When
STARTS
STARTSFri 23 Nov,10:00AMENDSMon 03 Dec,6:00PM
ENDS

 Cal

[(ssh user)]#

(And it includes all those line breaks etc).
So you can see there at the end, Im grouping both of those stripped strings into one printout, with a separator character in the middle to PHP can read back the string as one, and then break it apart.
Problem is - the python code can read that page and store the text, but it includes all those rubbish  and  tags etc, that are confusing the PHP app.
I really just want returned:
Fri 23 Nov,10:00AM

is it because Im using the findAll(text=True) method?
How can I drill down and get just the text only in that div - not the span tags too?
Any help would be greatly appreciated, thank you.
Rick - Melbourne.
Answer: Why not try something like
In [95]: soup = BeautifulSoup(content)

In [96]: soup.find("span", {"class": "egV2_archivedDateEnded"})
Out[96]: STARTS

In [97]: soup.find("span", {"class": "egV2_archivedDateEnded"}).next
Out[97]: u'STARTS'

In [98]: soup.find("span", {"class": "egV2_archivedDateEnded"}).next.next
Out[98]: u'Fri 23 Nov,10:00AM'

or even
In [99]: soup.find("span", {"class": "egV2_archivedDateEnded"}).nextSibling
Out[99]: u'Fri 23 Nov,10:00AM'

Comment: Awesome! I had'd even thought to use Next Sibling! Its not exactly the easiest documentation (BS4) to read through!  Cheers.
Answer: If you are just trying to extract a single tag that is easily identified with a particular attribute, pyparsing makes this pretty simple (I would go after the meta tag with its ISO8601 time string value):
from pyparsing import makeHTMLTags,withAttribute

meta = makeHTMLTags('meta')[0]
# only want matching <meta> tags if they have the attribute itemprop="startDate"
meta.setParseAction(withAttribute(itemprop="startDate"))

# scanString is a generator that yields (tokens,startloc,endloc) triples, we just
# want the tokens
firstmatch = next(meta.scanString(content))[0]

Now convert to a datetime object, which can be formatted any way you like, written to a database, used to compute elapsed times, etc.:
from datetime import datetime
dt = datetime.strptime(firstmatch.content[:19], "%Y-%m-%dT%H:%M:%S")

print (firstmatch.content)
print (dt)

Prints:
2012-11-23T10:00:00.0000000
2012-11-23 10:00:00


Prove that two polynomials of degree $m$ and $n$ intersect in at most $m$ points

Question:
Let $m \leq n$ be two positive integers. Prove that two polynomials of degree $m$ and $n$ intersect in at most $m$ points.

This seemed simple enough: $f(x) = (x-x_1)\cdots(x-x_m)$ and $g(x)=(x-x_1)\cdots(x-x_n)$. When we set them equal we can simplify to get a polynomial with degree $n$ which has at most $n$ zeroes.
Does this proof work or do I need to be more rigorous?
Comment: $x^2$ and $x$ intersect at 2 points. I think you mean to prove that they intersect in at most $n$ points.
Comment: What does it mean for polynomials to intersect? Do you mean that when viewing them as functions, their graphs intersect?
Comment: Why should they necessarily have the same roots?
Comment: Are you sure you asked the right question? A line (degree 1) and a parabola (degree 2) can intersect in two points.
Comment: @HenningMakholm at most $n$ actually.
Comment: $f(x)-g(x)$ is a polynomial of degree at most $n$, that has at most $n$ roots. As @Dedalus said, your argument is wrong.
Comment: @YvesDaoust at most $n$
Comment: @LeGrandDODOM: at nost.
Answer: You shouldn't assume that the two polynomials are monic or split into linear factors. They might not, unless the underlying field is algebraically closed.
Fortunately, you don't need that assumption. Just subtract the polynomials and note that the difference will have degree at most $n$.
... unless $m=n$ and the polynomials are equal, in which case they'll have lots and lots of points in common.
Answer: As pointed out in the comments, they intersect at most $n$ times.
As for your reasoning, it is basically correct. If they intersect at more than $n$ points, then $f - g$ is an $n^{\text{th}}$ degree polynomial with more than $n$ roots which is impossible.
This reasoning breaks when $m = n$, can you see why?
Comment: So the question is wrong? It should say $m < n$?
Comment: @user19405892, Actually, the reasoning breaks when $m=n$ _and_ $f=g$.
Comment: Not necessarily. There should just be a caveat. Perhaps it should read, "Prove that two unequal polynomials of degree $m$ and $n$..."
Comment: @User8128 It is though. The question says $m$ instead of $n$ as well.
Comment: I'm just pointing out that the statement isn't true when $f = g$. That's all.


Why does samba server fail to start with PANIC error?

Question: I'm seeing an error when trying to start smbd:
# smbd -i
smbd version 3.2.5 started.
Copyright Andrew Tridgell and the Samba Team 1992-2008
===============================================================
INTERNAL ERROR: Signal 6 in pid 3082 (3.2.5)
Please read the Trouble-Shooting section of the Samba3-HOWTO

From: http://www.samba.org/samba/docs/Samba3-HOWTO.pdf
===============================================================
PANIC (pid 3082): internal error
BACKTRACE: 18 stack frames:
 #0 smbd(log_stack_trace+0x1c) [0x5ae5cd]
 #1 smbd(smb_panic+0x5b) [0x5ae6db]
 #2 smbd() [0x59b1e4]
 #3 /lib/libpthread.so.0(+0xef60) [0x7fb6c8bacf60]
 #4 /lib/libc.so.6(gsignal+0x35) [0x7fb6c714f175]
 #5 /lib/libc.so.6(abort+0x180) [0x7fb6c7151f80]
 #6 /usr/lib/libtalloc.so.2(+0x2070) [0x7fb6c604f070]
 #7 /usr/lib/libtalloc.so.2(_talloc_free+0x31c) [0x7fb6c605079c]
 #8 /usr/lib/libwbclient.so.0(wbcSidToGid+0xc6) [0x7fb6c74825c6]
 #9 smbd(winbind_sid_to_gid+0x5f) [0x588735]
 #10 smbd(sid_to_gid+0xd4) [0x569918]
 #11 smbd(create_local_nt_token+0x212) [0x5eec64]
 #12 smbd(get_root_nt_token+0x116) [0x5ef191]
 #13 smbd(svcctl_init_keys+0x20) [0x4f8fa4]
 #14 smbd(registry_init_full+0xf1) [0x74f2e1]
 #15 smbd(main+0xa0e) [0x470243]
 #16 /lib/libc.so.6(__libc_start_main+0xfd) [0x7fb6c713bc4d]
 #17 smbd() [0x46ee09]
dumping core in /var/log/samba/cores/smbd
Aborted (core dumped)

When I run it from /etc/init.d/samba start I also see the above error in the /var/log/samba/log.smbd log file.
I'm using Debian Lenny (latest upgraded version). The error seemed to come from nowhere, I've been using the same setup for years now, and today samba won't start (even after rebooting). I can't think what I might have changed to cause this.
I've read the howto section as advised, but this provides only basic troubleshooting steps, nothing for an error quite as severe as this.
Answer: You need matching versions of libwbclient0 and samba, according to this thread on the samba list.
The dependency on the Debian package is not tight enough; that's the cause of bug #593823.
(Found by googling "smbd" "winbind_sid_to_gid": since reinstalling didn't help, a library problem was next on the list of things to check.)
Comment: Ah, yes they're slightly different -- samba: 2:3.2.5-4lenny13 / libwbclient0: 3.4.2-1
Comment: Fixed by running: `apt-get install libwbclient0=2:3.2.5-4lenny13`
Answer: Have you configured Samba with LDAP ?
If yes maybe this thread could be useful :
http://www.uluga.ubuntuforums.org/showthread.php?t=1330637&page=7
Comment: Hmm, nope, just normal Samba auth (`security = user` and `encrypt passwords = yes`).


Feature selection for very sparse data

Question: I have a dataset of dimension 3,000 x 24,000 (approximately) with 6 class label. But the data is very sparse. The number of non-zero values per sample ranges from 10-300 (approx) out of 24,000. The non-zero values in the dataset are real numbers. I need to perform feature selection/reduction before the classification. Which technique would be better for such dataset?
Comment: Have you considered L1 regularization?
Comment: I am trying to apply elasticnet for feature selection.
Comment: Elasticnet is L1 and L2; for feature selection L1 only offers better functionality AFAIK.
Answer: Feature selection and feature reduction are two very different strategies.
Generally speaking, non-parametric tests is probably your best option, I'd go towards a Kruskal-Wallis rank sum test to get overall differential features or a Mann-Whitney rank sum test for each class label.
For feature reduction, I believe zero-inflated factorial analysis (ZIFA) is a good solution (Pierson, Emma, and Christopher Yau. "ZIFA: Dimensionality reduction for zero-inflated single-cell gene expression analysis." Genome biology 16.1 (2015): 241.). However, more classical factor analysis, NMF or t-SNE may work.
Now the data you describe really looks a lot like a single-cell RNAseq dataset. If this is the case, I encourage you to take a look at the following resource:
https://hemberg-lab.github.io/scRNA.seq.course/biological-analysis.html#de-in-a-real-dataset
Comment: I believe it is more correct to say factor analysis than factorial analysis, despite I don't know because didn't read those articles you cite. We say, factorial design, but that is very different.
Comment: Edit. Thanks for the comment, it was an incorrect translation.

Feature selection for very sparse data


Help integrating the mean of the minimum order statistic

Question: I have a problem that asks me to show that $Y_{(1)}$ is a biased estimator for $\theta$ where a random sample of size n is taken from a uniform distribution $U(0,\theta)$.
I am stuck on integrating the mean $E{(Y_{(1)})}$. I let $$g_1(y) = \frac n \theta[1-\frac Y \theta] ^{n-1}$$ be the density function of $Y_{(1)}$. Therefore I let $$E(Y_{(1)}) = \int_0^\theta \frac y n \theta (1-\frac y \theta)^{n-1} dy$$
I have no idea where to start with this integral. I know this is what is needed to be solved to show it is a biased estimator. Can someone help me break down this integral showing all steps?
Thank you
Answer: Just substitute $1-y/\theta = x$, then $$
dy = -\theta dx,
$$
and you will get an immediate integral.


Boot error on Windows "Couldn't delete target"

Question: Well, basically I'm facing a problem just on Windows, when I run "boot run dev" on macOS or Linux, it works perfectly, but on Windows, the dream is over, the boot starts but get an error soon as it starts, this is my build.boot:
<code>(set-env!
  :source-paths #{"src"}
  :resource-paths #{"src" "resources"}
  :dependencies '[[org.clojure/clojure "1.9.0" :scope "provided"]
                  [adzerk/boot-cljs "2.1.4" :scope "test"]
                  [adzerk/boot-reload "0.5.2" :scope "test"]
                  [pandeiro/boot-http "0.8.3" :scope "test"]
                  [nightlight "RELEASE"]
                  [org.clojure/clojurescript "1.9.946"]
                  [rum "0.10.8"]
                  [org.roman01la/cljss "1.5.13"]
                  [org.clojure/core.async "0.4.474"]
                  [io.replikativ/konserve "0.4.11"]
                  [ring/ring-core "1.6.3"]
                  [bidi "2.1.2"]
                  [congomongo "0.5.0"]
                  [cljs-http "0.1.44"]
                  [http-kit "2.2.0"]
                  [com.hypirion/clj-xchart "0.2.0"]])

(require
  '[adzerk.boot-cljs :refer [cljs]]
  '[adzerk.boot-reload :refer [reload]]
  '[pandeiro.boot-http :refer [serve]]
  '[nightlight.boot :refer [nightlight sandbox]])

(task-options!
  aot {:namespace   #{'brad.server}}
  pom {:project     'brad
       :version     "0.1.0"
       :description "FIXME: write description"
       :url         "http://example/FIXME"
       :scm         {:url "https://github.com/yourname/brad"}
       :license     {"Eclipse Public License"
                     "http://www.eclipse.org/legal/epl-v10.html"}}
  jar {:main        'brad.server
       :file        "brad.jar"}
  cljs {:ids #{"brad/admins" "brad/fisicos"}})

(deftask dev []
  (comp
    (watch)
    (reload :asset-path "brad"
            :cljs-asset-path ".")
    (sandbox :file "java.policy")
    (cljs :source-map true
          :optimizations :none)
    (target)))

(deftask run []
  (comp
    (serve :dir "target/brad" :port 3000)
    (dev)
    (nightlight :port 4000 :url "http://localhost:3000")))

(deftask build []
  (comp
    (cljs :optimizations :advanced
          :compiler-options {:fn-invoke-direct true})
    (aot)
    (pom)
    (uber)
    (jar)
    (target)))
</code>
Sorry about the extensive code, I think that maybe the problem is with some permission that I didn't give, I was trying to run boot on git bash, then I tried on windows powershell, the same error was ocurred, please, help me, and I'm sorry about my english.
Comment: Have you tried to Run as administrator the git bash / powershell? Have you tried manually deleting the target directory?
Comment: Yes, the target was created by boot, even with the error, before I run again I deleted the target folder manually, but the same error occurred and other target was created. I tried to run as administrator, even with another account of windows.
Answer: There are known issues on Windows, please try on Windows 10.


what is the main Difference between out mode and in out mode?

Question: Difference between out mode and in out mode? As far i have collected the info is
 the main difference i know is that in  both out and in out mode the actual parameter is expected to be altered even writing and reading is also possible then what is main difference please help me to understand?
Comment: possible duplicate of [The use of IN OUT in Ada](http://stackoverflow.com/questions/3003480/the-use-of-in-out-in-ada)
Comment: Please do not close this as a duplicate; there are some differences that are not covered by the linked question.  I am working on an answer now.
Answer: The best explanation of the difference is in RM 6.4.1(11-15).
Semantically, there is a difference only for parameters that are passed by copy.  If you call a subprogram that has an in out parameter, the actual parameter is expected to have a legitimate value before the call.  On entry, the subprogram makes a copy of the variable and checks to make sure it satisfies the constraints.
For an out parameter, the actual parameter does not need to have a value going in; it could be uninitialized garbage.  The intent is that the subprogram will not use the value of this parameter until it has been set, by the subprogram (it can be set either by assignment or by being passed as an out parameter to some other subprogram, or to a Default_Value, or perhaps by other means).  This is not enforced, however.
This can cause different behavior in some cases.  For example:
subtype Int10 is Integer range 1 .. 10;

procedure Proc (Param : in out Int10) is
begin
    Param := 5;
end Proc;

Y : Integer := 100;
...
Proc (Y);

Since Param is an in out parameter, the constraints are checked on entry.  Thus, the call to Proc(Y) raises a Constraint_Error.  However:
subtype Int10 is Integer range 1 .. 10;

procedure Proc (Param : out Int10) is
begin
    Param := 5;
end Proc;

Y : Integer := 100;
...
Proc (Y);

In this case, no Constraint_Error is raised.  In fact, Y does not need to be initialized at all, because the expectation is that the procedure will not use the input value.  According to the RM, the value is not even copied, for certain classes of parameter types.  So in this case:
Save_Param : Integer;

procedure Proc (Param : out Int10) is
begin
    Save_Param := Param;  -- legal but not recommended
    Param := 5;
end Proc;

Y : Integer := 3;
...
Proc (Y);

Save_Param will probably be set to some garbage value, not 3.  (In Ada 2012, there is a Default_Value aspect that can be applied to subtypes; in a case like that, an out parameter would be set to this default value instead of uninitialized garbage, while an in out parameter would still get the value from the actual parameter.)
For parameters that are passed by reference, there really is no difference in behavior.
The rules in Ada 83 were different.  A subprogram with an in out parameter could both read and write that parameter, while a subprogram with an out parameter was allowed to assign to the parameter but could not do anything that would read that parameter's value (barring some cases where there was no way around reading discriminants).  Thus:
procedure Proc (Param : out Int10) is
begin
    Param := 5;
    Save_Param := Param;  -- illegal in Ada 83, legal in Ada 95 and later versions
end Proc;

In other words, an out parameter really was output-only.  The rule was relaxed in Ada 95, though, as programmers found it too restrictive.


Changing a melody from major to minor key, twice

Question: I thought of an interesting idea but I have very little music theory knowledge so I don't know how to look up additional information about it.
The idea is the following:
Say I have a melody in A major key. It's some happy tune. If I want to convert it to a minor key I can do that by lowering the third, sixth and (let's say) seventh notes in the scale. To me the melody usually changes to a sadder tone.
Now, all the notes in the melody could just as well be interpreted as if they were in C major since it contains the same pitches so I wondered what would happen if I converted it to a minor key again. From C major to C minor.
I've tried this a couple of times and I think I get a different melody from both the original and the second transformation. I could presumably just keep going repeating the same method. What would happen to the melody?
To make this a concrete question, is there a name for this process and is there any use for it in music?
Answer: You end up in Ab Lydian. (Which is a major mode, by the way.)
A minor and C major aren't the same thing. The tonal centre, the "home" tone, is very much different. In A major, your tonal centre was A. In A minor, your tonal centre is still A. Now you put flats on B, E and A - and your tonal centre still isn't moving to C or Eb, it's just shifted by the flat you put on it.
Now, you can change key from A major to C major or Eb major or whatever major. This is called transposition. When you transpose a song, you move the tonal centre, while all the intervals are kept intact. The whole tune is just moved up or down, most often in order to fit a singer's vocal range. When you hear it, you aren't likely to even realise there's any change from the original at all.
But that isn't what you're describing here. Switching from major (Ionian) to minor (Aeolian) or Lydian or etc. scale does involve changing intervals, and the new tune is distinctly different from the original. You're creating a variation on the theme (which is a broader term that encompasses other possible changes than scale mode but I'm not aware of a more specific one).
Comment: Related - https://www.youtube.com/watch?v=roFVo0ePOZw
Answer:
I've tried this a couple of times and I think I get a different melody from both the original and the second transformation. I could presumably just keep going repeating the same method. What would happen to the melody?

In terms of keys, you come back around to the starting key again pretty quickly:
C -> Cm -> Eb -> Ebm (D#m) -> F# -> F#m -> A -> Am -> C
There are four transformations from major to minor, and each one means lowering three notes, which means twelve total note lowering occur. The twelve lowerings are not evenly distributed across the twelve different note classes. Five note classes in your melody will be lowered twice each, and two will be lowered once each.
This means after coming back around to the starting key, the melody will have been lowered one diatonic step. In other words, if you start in C major, once you've gone around to C major again, every C will be a B, every F will be an E, and all the other notes will be lowered a whole step (D to C, E to D, etc.). The melody shape will remain intact but the tonality will be altered. If you keep going, the whole thing goes down another diatonic step every time you come back around to C.
Linking what happens to Divizna's answer, every time you come back to the first key you've moved the melody to the mode below the previous one. So the C major melody turns into B Locrian, then A Aeolian, G Mixolydian, etc. After seven cycles of four transformations, you'll be back in the original key and mode but an octave lower.
Here's a melody I transformed repeatedly in this way. Note that the initial melody uses every scale degree at least once and establishes C major as the tonality.
Comment: @Darwin One thing to note: You write about major being "happy" and minor being "sadder." If your question "What would happen to the melody" is thinking about emotive impact (e.g. "if lowering the third makes things sadder, would lowering even more stuff make it even sadder?"), then hopefully this answer shows that it's not that simple. The answer above is the objective answer to "what would happen to the melody": you put it through a defined process and get interesting, different results. The emotive impacts of the various mutations is harder to quantify, and might depend more on other factors
Comment: Thank you for the answer! I'll need to read up on modes.
Answer: Start in A major. 3 sharps. Losing those sharps, and playing the same name notes (which is what I think you're getting at), will take you into A minor. Not key C, although now, you have the same notes as key C. But the tonic is still note A. You haven't modulated into key C.
To do that, you have to move the melody so that it revolves around C, not A. You can, of course, do that, then change to 3 flats, still using C as home/base, and move on from there.
As far as naming is concerned, I guess it's using parallel keys, then relative keys. I'll leave you to work out which is which..! It's a ploy that's used a fair bit, in all kinds of music, so it's not a new concept, sorry.


No of ways choosing $6$ persons from $6$ Married couples

Question: Find number of ways to choose $6$ persons from $6$ married couples such that there is exactly one couple.
To solve, I have first chosen one couple which is $6$ ways.
Now remaining $4$ persons have to chosen from $10$ persons left such that among these four there should be no couple. Number of ways this can be done in
$$\binom{10}{4}-5=205$$
so the total number of ways is $205 \times 6=1230$,
but answer is given $480$. What is my mistake?
Comment: Not sure where you got the `-5` part from, but there are clearly more than 5 ways to choose 4 people from 5 couples such that you include at least one couple.
Answer: Pick the couple: $\binom 61 =6$ ways
Pick the other couples that you're going to choose one partner from: $\binom 54 = 5$
Pick which partner from those couples: $2^4=16$
Answer : $6\cdot 5\cdot 16 = 480$
Your mistake is in overestimating the number of ways to pick the four without including a couple.  As you can see here there are only $5\cdot 16=80$ ways to do that.

You can also get the $80$ options of picking $4$ people without any couples from $5$ couples by inclusion-exclusion, starting with your initial "free" choice of $4$:
$$\binom {10}{4} - \binom {5}{1}\binom {8}{2} + \binom {5}{2}\binom {6}{0} = 210 - 5\cdot 28 + 10\cdot 1 = 80$$
where the first subtraction is all the ways of choosing one couple and any two other people, and the final addition remedies the "oversubtraction" of cases where two couples were chosen.
Comment: Why isn't it true that there are 10 ways to choose the 3rd person, 8 ways to choose the 4th, 6 ways to choose the 5th and 4 ways to choose the 6th?
Comment: That overcounts, for example by choosing the third person and the fourth person the other way around
Answer: Let married couples as $aa',bb',cc',dd',ee',ff'$
Then number of ways of choosing exactly one married couple is $\displaystyle \binom{6}{1} = 6$
now choosing $4$ other people which are not couple , is $$\displaystyle \binom{5}{4}\times \binom{2}{1}\times \binom{2}{1}\times \binom{2}{1}\times \binom{2}{1} = 5 \times 16$$
So total number of ways is $\displaystyle 6\times 5 \times 16 = 480$


Is there any way to export data to CSV file and then import updated data?

Question: I have a website I started to build couple years ago. But the website itself grew up to something bigger, with more fields and details - and old data are missing these. E.g., recently added Long./Lat. fields but old content doesn't have them. So I wonder if it's possible (and what module) to export all data into csv file, update it (I think it's much easier than open one by one node) and than import the updated data? Or something like that.
Thanks for any help.
Comment: How about Data Export Import? I found interesting comment about it here http://drupal.stackexchange.com/questions/41003/how-to-export-import-all-nodes-of-a-specific-content-type.

"What I like about data_export_import is that it is an all-in-one module (for export AND import of data. Whereas as with some other solutions, the import and export stages are done by separate modules, which could mean that extra work is needed ensuring compatibility of the export with the import.)"
Answer: If you want to do it that way, use Views data export. Here is an excerpt about it from the module's project page:

... designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:

CSV.
Microsoft XLS.
Microsoft DOC.
Basic TXT.
XML.

Then, re-import using the Feeds module. Here is an excerpt about it from the module's project page:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files
Comment: I'm already playin' with Views Datga Export but wondering (of course I'll test it by myself but if you already tried this...) do I need to export ALL fields of the content type and then import them all again once they are updated, or I can export just some of them, like nid, title and "problematic" fields (e.g. long/lat), update them and then import only these? Would I delete e.g. Body if I not import it again?
Comment: No, you do not need all fields. You will need to export at least one field to use as the unique identifier. Feeds does not modify fields that are not mapped in the import.
Answer: The feeds module, as suggested by RoloDMonkey seems indeed the way to go for re-importing updated data.
However, to export the data, you may want to consider the Forena module. Here is a quote from that page:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

The steps for creating such CSV files are:

a connection to an external database (one time only, for each database).
a custom SQL query (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

These steps do not require any PHP coding.
If you're interested in an online demo site (prior to installing/testing Forena), then checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module).

Disclosure: I'm a co-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.
Answer: You can use the Data export import module for data importing exporting purpose. Here is an excerpt about it from the module's project page:

The purpose of this module is to be able to export nodes, taxonomy terms and users to data files and then be able to import these data files into Drupal sites. There may be many uses for this module but the main one would be that it can provide a way to export data from a live Drupal site and then to import that live data into an updated version of that site.
So, data can be exported and then imported - hence the name; Data Export Import.


Why temporarily add 1 to an error when squaring it?

Question: I'm trying to understand how the optimisation is working in an algorithm.  In support of the optimisation, errors are calculated.
For one type of error, before it returns the value, it squares the number, then subtracts one:
x = 1 + error / maxOverallError
error = x * x - 1

Does adding the 1, squaring, then subtracting the one have any statistical significance?
Does it overcome any issues?
Comment: The error is nonpositive for any estimate that's within 1 unit of the actual value. Perhaps this error function is allowing for slight deviations from actual to be non-penalized? I'd expect negative errors to be rounded to 0, though, as I'm not sure how to interpret negative error.
Comment: ok. I'd asked the editors to unlock the question so I could provide a formal answer.  I'll put one in here as a comment, instead.  The above construct is to overcome the issue where squaring a fraction gives a smaller fraction.  We're squaring the result error to exaggerate them.  But, squaring a number less than one actually makes it smaller.  So, the algorithm adds `one` to the result (to force it to be above one), then squares it, then removes the original `one`.
Well, that's my current best guess.
Answer: You can change the original error values e = actual - estimated with a cost function C(e) = (squaring) * (negative) that better suits your need for the optimization algorithm.
Squaring the error creates a high penalty on larger errors, which can accelerate optimization algorithms such as the gradient descent.
Multiplying by -1 forces the cost function to be negative, which usually occurs when you are using a maximization optimization algorithm, i.e. optimizing by maximizing the cost function.

Edit: Added source of plot in Python.
import numpy as np
x = np.linspace(0, 2, 100)
plt.plot(x, x**x, label="square")
plt.plot(x, x, label="linear")
plt.plot(x, x**x*-1, label="squared_negative")

plt.ylabel("Cost Function")
plt.xlabel("Error")
plt.legend()
plt.show()

Comment: Thanks for your submission @francisco-fonseca .  Late that night I realised I'd misinterpreted the operator significance (BIDMAS).  So, the square is performed first, and then the `1` is subtracted.  I've had a go at explaining this in a comment on my original question.


Express the complex number in rectangular form $a + ib$

Question: $12e^{2-\pi*i/3}$ express this in rectangular form $a + i\cdot b$
Not sure how to solve when fractions are involved
Example $2.6\cdot e^{3+i} = 2.6\cdot e^3\cdot e^i$ ?
Comment: You might want to visit the following site to see how to format your question: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference.  As it is, your question isn't clear.
Answer: $$12e^{2-i\pi/3}=12e^2e^{-i\pi/3}$$ Now use $e^{i\theta}=\cos\theta+i\sin\theta$ to find that remaining exponential.
Answer: Might be useful to think of the desired answer as $$a+ib=r(\cos\theta+i\sin\theta)=re^{i\theta}$$
where $a=r\cos\theta, b=r\sin\theta$.
Also, note that
$$ke^{p+i\theta}=ke^p\cdot e^{i\theta}=re^{i\theta}$$
where $r=ke^p$ is a real number (assuming $k$ is real).
That should get you going.


How to style html elements in javascript output in php

Question: I have a problem with the code I am writing and need some help. I am trying to style and also attach classes and id's to some html elements. These html elements are javascript outputs. And the javascript code is embedded in a php tag.
I've already tried this in different ways but I am mostly having issues with the quotation marks
<?php
echo '';
?>

You'll notice that this code won't run because of the class, id and style options. I know the style can be removed, but the others need to be there. I am using a while loop in php, so the script is different for each loop. What's the best method to handle this situation. I am a beginner so I would really appreciate help. Thanks in advance
Comment: Break out of the PHP block instead of echoing it. Your quotes are messing everything up, and you're not using any variables in there anyway.
Answer: You can just add the script outside of the <php> block and have an easier time with quotation problems:
<?php
  # do PHP stuff
?>

;

Comment: @MichaelDavid yes, it can. `while(1) { ?> html stuff here <?php }` is perfectly valid syntax.
Comment: I'm using a while loop as I said earlier and so, the script cannot be outside the php block
Answer: Use \ to escape them:
echo '';

Btw if you use double quotes for the echo you would only have to escape one before the div
Answer: You can put the code out of the php tag.
<?php
//PHP Codes
?>
Your JS / HTML code
<?php
//PHP Codes
?>

Comment: Please, clarify the answer, otherwise you'll get downvoted


How can I include standard bits of text in a node, depending on the node location or a particular term?

Question: I have a product page that is mostly original content, however I would like to include a block of text that is included on similar nodes. Eg, I have several pages for hotels in London, so I would like to include a block of text called 'About London', which then carries a couple of paragraphs about London.
I assume that this could be made to happen based on the node's Location or for a particular term attached to the node, but I don't know the best way forward with what I'm trying to do.
Comment: Does the text need to be inserted in the node itself, or can it be anywhere on the page (like in a block)?
Answer: If you create a new content type, say "Location Description", you could add a node reference field into your hotel content type referencing the respective location node.
Comment: That sounds feasible - I've never tried doing something like this, so I'll give it a shot and see how it works out.
Answer: You can also use a "location" vocabulary and create a term reference from the node to the location.


Theorems about finite sets the proof of which require the notion of infinite set

Question: I believe that there should exist theorems about finite sets which are not provable without the notion of infinite sets.
I am curious if I am right.
What are the examples of such theorems if they ?
The question may be a duplicate of an early question, but I could not find one.
I agree this question is vague and does not have a unique answer.
Though any useful comment or answer would be appreciated.
P.S. As a possible example I guess one can think of theorems proved by mathematical induction. But I am not sure if it is relevant or not here.
Comment: How about Goodstein's theorem?
Comment: Induction does not require the existence of an infinite set.
Comment: Sure, Goodstein's seems to follow the lines of my question.
Comment: @DanielWainfleet Please elaborate more on induction for finite sets. I would grateful if you share some must-know reference (ideal if relatively short but showing the matter of things)
Answer: A precise version of your question might be: are there statements in Peano Arithmetic (PA) that can't be proved in PA, but can be proved in set theory, say the Zermelo-Fraenkel axioms including Choice (ZFC)?
If you accept this as equivalent to your question, then there are lots of examples. The granddaddy of them all is the statement that PA is consistent. By Gödel's Second Incompleteness Theorem, this cannot be proven in PA, but it is almost trivially provable in ZFC.
As Aphelli commented, Goodstein's theorem is another famous example. So is the Paris-Harrington Principle (discussed here). That's particularly interesting, because the PHP is a slightly modified version of Ramsey's Theorem for finite sets, a famous combinatorial result. Ramsey's Theorem is provable in PA, but the PHP is not.
In other words, in ZFC we have two nearly identical proofs of two very similar statements: the infinite Ramsey theorem, and the infinite Paris-Harrington Principle. Then using compactness, we can use these to prove the finite versions. But within PA, we can prove only the finite Ramsey theorem, not the finite PHP.
It's worth noting that PA can be reformulated as a theory of finite sets. You'll find an extensive discussion of this here. Briefly, replacing the Infinity Axiom with its negation, we obtain a theory (call it ZF$\neg\infty$) that talks only about finite sets---in other words, a very good theory in which to do finite combinatorics. And there are ways to convert proofs "back and forth" between PA and ZF$\neg\infty$, so that any theorem of PA corresponds to a theorem of ZF$\neg\infty$, and vice versa.
You will notice I immediately started talking about theories, and not "notions". That's because the question is about provability. What's provable about a given notion (or mathematical concept) depends on what we assume about it. In other words, the axioms we accept.
Comment: +1....(1). Although Ramsey's Theorem is provable in PA, it is very easily provable by contradiction in ZFC with a little Model Theory (the Henkin Theorem, a.k.a. the Completeness Theorem: A theory is consistent iff it has a model)....(2). The Henkin Theorem itself  is not provable in ZFC-Inf. It is easy to produce a finite selection of some of PA that has no finite model.
Comment: @DanielWainfleet Right. And proofs of the Ramsey theorem for infinite sets can be easily tweaked to prove the infinite version of the Paris-Harrington Principle. Then an easy compactness argument proves the finite version. So the interesting fact is that the finite version of Ramsey's theorem is provable in PA, but not of the PHP.
Comment: Are you related to Prof. William Weiss of U. of Toronto? I took some courses from him on Set Theory and Model Theory.
Comment: @DanielWainfleet Afraid not. By the way, in your reference to Henkin's theorem, do you basically mean the compactness theorem? That enables us to deduce the finite version of Ramsey's theorem from the infinite version. But I don't see how you can deduce the infinite Ramsey Theorem from the Completeness Theorem.
Comment: Yes, with regards to the Ramsey Theorem , I meant to refer to the Compactness Theorem, not the Henkin.


How to give a consistent mathematical explanation to a paradoxical divergent/convergent phenomena.

Question: How can be explained, in a "clean" mathematical way, the "stabilization" of the different digits in the following divergent sequence?
$$\tan(89°)=57.28996163...$$
$$\tan(89.9°)=572.9572134...$$
$$\tan(89.99°)=5729.577893...$$
$$\tan(89.999°)=57295.77951...$$
$$\tan(89.9999°)=572957.7951...$$
etc...
Comment: What is *paradoxical*?
Comment: Did you check the suggested duplicate? $180/\pi = 57.2957795131\ldots$.
Comment: I don't know but I guess it has something to do with the fact that $$\lim_{n\to\infty}\frac{\cot10^{-n-1}}{\cot10^{-n}}=10\ ?$$
Comment: @mrf I mean that there is an apparent paradox in having a convergence of the digits whereas the sequence is divergent...
Comment: @bof You are right, due to the series for $\cot(x)=1/x+...$, but why these digits $5,7,2,9,5,7...$
Comment: @mrf thanks, I checked it and acknowledged it as duplicate.
Answer: $\frac{\sin{x}}{x} \to 1$ when $x \to 0$, so $\cos(90^\circ-x)=\sin{x} \approx x$, meaning when you're $10$ times closer to $90^\circ$ cosine is $10$ times smaller and the tangent is $10$ times bigger because sine is approximately equal to one.


Truth-tellers, liars and ambiguous, solution verification

Question: Consider the following problem

In a certain country, there are three kinds of people: workers (who always tell the truth), businessmen (who always lie), and students (who tell the truth and sometimes lie). A worker, a businessman and a student are standing at the side of the road but are not identifiable. By asking two yes or no questions, find out which fork leads to the capital.

I believe I know the idea of solving this puzzle. The first question should answer who is not a student. As for the second one, locate which fork leads to the capital.
I know what to ask once I identify the student with a yes/no question, so I was wondering if I really understand the approach that is mentioned in What is the Name of This Book (Smullyan, 1978, p.116)
According to Smullyan (1978, p.116), let me first label each person with $A, B$ and $C$. Then ask, say $A$, the following question "Is the statement: You are a worker if and only if $B$ is a student, true?"
If the answer is "Yes", then it is clear that $C$ is not a student if $A$ is a worker because it is necessary that $B$ is a student to make the statement true. If $A$ is a businessman, then the actual truth value of the statement is false. This is only the case when $B$ is indeed a student and so $C$ is again not a student.
Let us see what will happen if the answer is "No". Then if $A$ is a worker, $B$ is not a student. If $A$ is a bussinesman, then the actual truth value of the statement is true, which give the information that $B$ is not a student.
What if $A$ is a student? then the statement is true. If $A$ is telling the truth, then s/he should answer "Yes"  because only one of them is a student. and so $C$ is not a student (and $B$). Otherwise, $A$ will answer "No", but $B$ is still not a student.
In conclusion, whatever $A$ may be, we can ask $B$ the second question if $A$ answers "Yes". Otherwise, ask $C$ if $A$ answers "No". The followed question is then "Is the statement 'You are a worker if and only if the left-hand branch leads to the capital' true?"
Edit: I decided not to choose the word "a truth-teller". So I replace it with "a worker". A "liar" is also changed to "businessman".
Answer: In general you got the logic just fine, but I still have two comments:

You have to be careful when using 'truth-teller'… or at least make clear what you mean by it. Is A being a 'truth-teller' the same as A being a worker?  Or do you mean to say that in that particular instance A was telling the truth ( and so A could be a worker or a student)?  Same goes for your use of 'liar'.

Indeed, in the case of A answering 'Yes' to the first question, you seem to use 'liar' to cover both the case where A is a businessman and the case where A is a student.  But in the case where the answer is 'No', you use 'truth-teller' for just the case where A is a worker. So… for a clearer proof, this needs to be cleared up.

The proof shows that with that first question you can figure out whether B is a student or  not. But you also said that the overall strategy was to first figure out who the student is. But if you find that B is not a student after the first question, that does not mean that you know who the student is. So … maybe the overall strategy us not such a clear 'first figure out the student and then…' strategy.

In fact, while I understand that you are really only asking to see if you understand the logic of the first half of the proof (dealing with the first question), I would encourage you to work out the second half (dealing with the second question) as well. And note: that second question involves the use of 'truth-teller' … so again: what exactly is meant by that? Since the first question refers to 'worker', I am inclined to think that the use of 'truth-teller' in the second question means 'worker or student-who-currently-tells-the-truth' … but I am not sure. But if you analyze the logic, you should probably be able to tell how this meant. Again, in general you are doing a good job with the logic, so I think you'll be able to get this. Good luck!
Comment: 1. You are right, the worker is a truth-teller: someone who is always telling the truth. The businessman is a liar: always tells lies.
2. Right...so the strategy is actually "first find out who is not the student, then ...".
Other than that this solution should be fine right?
Comment: 1. Sure, any worker is a truth-teller … but is any truth-teller a worker?  2. You are right! The strategy is apparently to find someone who is *not* a worker. So when A answers Yes to question 1 then you know C is not a worker, and if A answers No then you know B is not a worker. But for this to be a solution/proof you still need to work out the logic of that second question.


Retain the div shown after the form is submitted

Question: I created 3 divs that are displayed using input type buttons, these buttons are used to show and hide the divs that are hidden initially. In those divs there are forms that used to store data. Now what I am trying to do is to retain the current used div after submitting data in a form.

This is my jquery codes.
$("#add_exams").hide();
  $("#exams").hide();
  $("#add_accts").hide();

  $("#view_exam").click(function(){
      $("#add_exams").hide();
      $("#exams").hide();
      $("#add_accts").hide();

      $("#exams").fadeIn();
  });

    $("#create_exam").click(function(){
      $("#add_exams").hide();
      $("#exams").hide();
      $("#add_accts").hide();

      $("#add_exams").fadeIn();
  });

    $("#manage_accts").click(function(){
      $("#add_exams").hide();
      $("#exams").hide();
      $("#add_accts").hide();

      $("#add_accts").fadeIn();
  });

 //$(document).on("click", "#selectall",function(){
  $(document).on("submit","#submit_acct", function(){

       $("#add_accts").fadeIn();

  });

My html is something like this

 <input type="button" id="create_exam" value="Create Exam" title="Click to create new exam."  />
  <input type="button" id="view_exam" value="Exam" title="Click to view exam."  />
  <input type="button" id="manage_accts" value="Accounts" title="Click to view exam."  />

       /*forms goes here */

       /*forms goes here */

       /*forms goes here */

When I try to submit data, the div is not displaying, i tried to used a jquery that will display the div I want but it does not work, all of them are hidden. I just need to retain to show the current displayed div, Any Idea on this?
Comment: try adding event.preventDefault(); to your on-submit js and do ajax after
Comment: i think you have missed something
Answer: As far as i understand, you want to retain the visible div even after post-back. you can use a hidden field for retaining the div visibility. try the following code snippet for reference
$("#view_exam").click(function(){
      $("#add_exams").hide();
      $("#exams").hide();
      $("#add_accts").hide();

      $("#exams").fadeIn();
      $("#FiddenField_For_Current_Form").val("exams");
  });

And At page load Check the value in FiddenField_For_Current_Form and show the appropriate form as the following
$(document).ready(function(){
  switch($("#FiddenField_For_Current_Form").val())
  {
    case "exams":
             $("#exams").fadeIn();
             break;

    default :
            $("#add_exams,#exams,#add_accts").hide();
             break;

  }

});

Comment: had a problem with this..  I used this input type, and as expected is changes the value on click event, but it is still the same, I manually added value="exams" to the input, it works just fine.
Comment: Change from  $("FiddenField_For_Current_Form").val("exams"); to  $("#FiddenField_For_Current_Form").val("exams");


Arquivo Existe PHP

Question: estou usando esta função para verificar se o arquivo existe:
<?php
    header('Content-Type: text/html; charset=utf-8');
    //header('Accept-Ranges: bytes');

    $nome_real = $_FILES["Arquivo"]["name"];
    $pastadestino = "/pasta/$nome_real";

    //verifica antes de passar - para apagar o existente
    if (file_exists($pastadestino))
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }
?>

Porém, ele retorna OK mesmo se eu deixar o caminho vazio. Ou até mesmo se o nome do arquivo for diferente, alguem poderia me explicar?
Comment: Parece tudo certo pra mim... aqui deu `NOK`, veja no [ideone](https://ideone.com/Y6eXl3).
Answer: Pegadinha do malandro 1:
A função file_exists(), apesar do nome, verifica se o caminho existe, independente dele ser um arquivo ou diretório.
Quando você deixa o parâmetro vazio, seu teste é o mesmo que isso:
if (file_exists( '/pasta/' ))

o que deve retornar verdadeiro caso a pasta realmente exista.
Solução:
A solução seria trocar a função por is_file(), que é especifica para arquivos:
if (is_file($pastadestino))
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }

Se quiser verificar pastas/diretórios apenas, há a função análoga is_dir(), que verificar se o caminho existe e é diretório.
if (is_dir($pastadestino))
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }

Pegadinha do malandro 2:
Cuidado se precisar fazer a verificação em arquivos logo após a mudança de algo no filesystem, pois todas as funções acima têm um cache no PHP.
Solução:
Para ter certeza de estar lidando com o caminho atualizado, existe o clearstatcache():
clearstatcache(); // Limpamos o cache de arquivos do PHP
if (is_file($pastadestino)) // is_dir() para pastas, is_file para arquivos.
    {
        echo "OK";
    }
    else
    {
        echo "NOK";
    }

Clique nos nomes das funções acima para saber mais detalhes, eles estão linkados com a documentação online do PHP.
Comment: Depende o que você chama de válido. Da forma que eu pus, é para verificar se o arquivo no caminho fornecido existe ou não. Se não funcionar, precisa verificar se o valor da variável está correto. Para pastas, is_dir(). Para arquivos, is_file().
Comment: OK, é isso mesmo, obrigado Bacco.
Comment: então se eu atualizar meu arquivo .php e por desta forma, ele vai verificar se o arquivo identificado no caminho é válido ou não?

Arquivo Existe PHP


How to set a custom style on a switch

Question: I have been trying to set a custom style for the past 3 hours, and it's been very frustrating.  I use http://android-holo-colors.com/ for all my styles and it suggests I use switch-backport.  I have tried this but can not figure out a way to customize the switch to match my applications colors.
How does one set the colors of the Switch, with or without an extra library?
Note: The switch I am trying to customize is on a Preference Screen.
Comment: also please edit your question since you are talking about a switch and the question reads about a spinner
Answer: You can set the android:thumb and android:track to your own drawable in order to customize a switch.
I did this in my preferences screen by creating a custom view that extended from SwitchPreference, and setting the thumb, track, and background of this custom view.
Then in my preferences.xml, instead of putting SwitchPreference I put this:
<com.path.tofile.CustomSwitchPreference
    android:key="key"
    android:title="title" />

Comment: That being said, this only works on most devices. I've seen some Samsung devices override my switch and use the custom Samsung one
Comment: Also when you say you are setting them are you doing this in the custom SwitchPreference Java file?
Comment: I've tested it on api level 14 and above.
That is correct, I am setting them in the custom file
Answer: Yes you can use switch-backport and in order to match the colors according to your application, you will have to create your own drawables with the colors. since the switch-backport uses nine-patch images, you could either create your own nine-patch images, or else create drawables using shape.
Hope that helps.!
You could pull the project from here for a better understanding.
Comment: Did what you did with the style, only I used [android-switch-backport](https://github.com/BoD/android-switch-backport) since I can add it with gradle.  Works perfectly thanks!

How to set a custom style on a switch


Is it practical to be able to quickly jump to another octave in another position while still remaining in key, without having to do much thought?

Question: This question is going to seem weird, so I will do my best to describe the problem. Are musicians able to jump to any arbitrary note without giving it much thought and not go out of key?
Assume for this entire post that we stay in one key.
My problem is this: I've played the guitar for so long that I can rifle up and down any scale, arpeggio, exotic weird shape, you name it, and it always sounds fine. I see in patterns and shapes, and I know how every pattern stitches itself together. This means when I'm coming down a major arpeggio and want to transition into a scale, I know the shape that I want to play based on the melody in my head. I'm also at the point where I can map the melody in my head onto the nearby notes without any problems. This is very nice, but I can only do this in the current region of where I am.
However, the patterns thing is a bit painful in one area. If I'm going down some scale and need to do a large note shift (like dropping down at least an octave and then some), unless it's exactly a full octave or something with a tangible marker, there's a chance I will screw up and land on the wrong note. This is not a technical problem, it's a "oh crap I don't know what note to play" and since it's done while I'm letting the melody play out in my head, I have to make a split second decision. Mostly it works well, but this is unacceptable if I were to improvise live because a wrong note is bad.
Things I've done to work around this are to bend if out of tune, or vibrato if landing on the note correctly (like a preemptive bend just in case, but vibrato if it's correct). This is only masking the problem.
While I can figure out what any note I'm on within a few seconds due to various reference points, I really need it to be much faster.
This made me think "properly learn all the notes this time instead of only knowing a few strings off by heart" because then I would go to a note I require to land in key... however this doesn't solve the problem either. I would need to know all the notes ahead of time, since knowing every note on the fretboard, while useful, does not solve the problem entirely.
Suppose I'm playing C minor, and I know the place I want to shift to because after decades of playing my instrument, the sound I want is within an area of 3 notes. By three notes, I mean I have my "target note" that I feel it is, and then the notes that are immediately beside it. For example, I'm about to shift down to an F. Next to it are E and F#.
Problem is... which of the three are in C minor? I feel like it's F based on many years of experience, and I could figure this out if needed given a few seconds, but I cannot solve this in the 200 milliseconds or so that I have. It feels like it almost has to be reflexive that I know which of those three notes it is. I would need to instantly know on the fly that F is the note that I want, and to not touch the other two adjacent notes or else it will sound quite bad. Sure, in this instance I guessed the right note, but I could just have easily shifted down one too far and end up on the wrong one, and this happens.
As such, this problem can be stated with: How can I learn to pick a random set of three contiguous notes on the fretboard, and select the proper one in key?
The only way I could see this being done is to know every single note instantly, know every single note in the target scale instantly, and then use this information to pick the right note, all in the span of a few hundred milliseconds at most.
Is this how musicians do this? Or what is the best way of doing this? Or is this not possible? How would you do it?
I want to be able to say "I'm going to freestyle in C minor today" and never hit the wrong note. When I stay in my local area, this is no problem and I will stay in key all the time without question. However, when I do a large shift like, say, 17 "notes" down, that is when I run into problems.
Comment: Note that in addition to the usual variation between individuals, this will vary dramatically between instruments.
Comment: Wrong notes in improvisation are only wrong till you repeat the pattern!
Comment: @LukeSawczak - often, yes, but not E or F# in key Cm...
Comment: @Tim Those notes lead to wonderful modulations in Cm! But of course one has to work to get there. What I mean is you can build a structure around any choice in improvisation. I find often if I hit a note I didn't intend, repeating the context and note, or a slight change, makes it sound intentional and interesting. But it's beside the point if OP is having lots of trouble hitting intended notes, I guess
Comment: @LukeSawczak - well aware of that. The problem is, the other guys who are playing along at those moments may have vastly different ideas! Yes, to get to an F harmony either can work - E (leading note), F# (tts), but if the harmony goes somewhere else, it'll sound like what it is - a mistake. True, OP is searching for notes from the key.
Comment: @Tim Ah, as a solo improviser, I didn't even take into account the need for others' sanity. Good point.
Comment: Playing E natural in the key of C minor is quite common in the blues, if not other places.
Comment: @ToddWilcox - playing Eb in the key of C major is quite common in the blues, not the other way round!!!
Comment: @Tim Ok I'll phone John Mayer and Jimmy Page and tell them they've been doing it wrong all this time. The literature I've worked on has the major 3 added to the pentatonic minor scale a **lot**. And John Mayer recorded a whole video extolling the virtues of adding the major 3rd scale degree to pentatonic minor solos.
Comment: @ToddWilcox - if the *key* is minor, then the 3rd will tend to stay minor. If the *key* is major, then M3 *and* m3 are used all the time.  We're not discussing the same thing. Playing the min.pent. over major (or 7th) chords is commonplace, but sticking M3 into essentially a **minor** blues isn't good. I've played this stuff for 50+ yrs, and that's never worked.
Answer: It sounds to me like you can instinctively find the notes you need within certain small intervals, but once you go beyond an octave or so you start guessing at speed which may or may not work.
You could possibly improve this by improvising with a metronome at a slow tempo, ideally with some kind of a looping backing track with possible. Choose a scale, like C minor, to improvise over, with an emphasis on big jumps every phrase or couple of phrases. The point of the metronome is to force you to play in time and therefore think in real time, rather than pausing and going "uhhhh where's E again?" If you can't make a jump in time with the metronome, slow down the metronome and try again. Find the first BPM at which you can improvise like this comfortably for a couple of minutes, and don't worry about sounding good. Focus on nailing those jumps in time with the metronome.
Then, when you get more confident with your jumps (this might take a while but it's worth the sweat), try and increase the BPM a little bit more each time. And make sure you cover all the different keys/scales, don't get too comfortable in just a couple of them. The hope would be that over time you would develop the instinct to make the jumps at normal playing speed without having to think.
Comment: The OP says he doesn't know which of the notes is in-key for C minor: E, F or F#. Which is a problem. In the context of C as a tonic, E has to mean "major third" and "4 frets, 4 semitones", and F immediately has to mean "fourth" and "5 frets, 5 semitones" and "distance between two strings except between G and B strings it's plus one fret". And F# has to mean at least "blue note" and "tritone" if not more. These have to be completely instinctive, instantaneous, no thinking and no figuring out.
Comment: @piiperiReinstateMonica I would also find it worrying if a seasoned player didn't immediately recognize that F# and E natural aren't in C minor. A way for OP to improve this is by messing it up enough times in practice to realize that F#/E will sound "bad" when trying to limit your improvisation to a particular scale (in this case C minor). Another thing OP could do is just play the C natural (or melodic?) minor scale up and down at first w/ metronome, then start jumping around the scale to build fluidity. There is the possibility that OP just doesn't have the ear to hear this naturally.
Answer: My sense of the core issues is first one of ear training and second of making the physical associations between ear and fingers.
There are also two issues getting tangled up: playing entirely in a single key ("I'm going to freestyle in C minor today") versus playing over changing keys or with out-of-key (i.e., chromatic) alterations ("I'm about to shift down to an F. Next to it are E and F#").
However, these can generally all be handled by the same — or largely similar — practice techniques.
Are musicians able to jump to any arbitrary note without giving it much thought and not go out of key?
Yes — many, with enough training and experience (or natural ability, for the lucky ones).
And musicians — even the best — miss, and know how to recover, as described in the question.
How to improve

Transcribe: learn to play songs you like just by listening. In this case, try to gravitate toward songs that force you into large leaps. Toward this end, you might find How can I slow down a YouTube video I'm trying to analyze or transcribe? helpful.

Exercises: play scales "in ninths" (or "in "). So, practice C minor by playing, for example, C4 – D5 – D4 – Eb5 – Eb4 – F5 – .... This will work for any interval in any key, and it will also work for chromatic intervals — say, for example, "in minor ninths": C4 – Db5 – D4 – Eb5 – Eb4 – E5 – .... And, of course, this can be done descending as well. The scales and/or the intervals can be both ascending or descending.

A similar exercise can be used with arpeggios. Precede each note of the arpeggio with a) a scale tone; b) a tone a fixed interval away. Thus, for a C minor arpeggio, the exercises might be a) Bb – C, D – Eb, F – G, Bb – C; b) B – C, D – Eb, F# – G, B – C.

Ear training (self or course). There are plenty of other posts with lots of ways to do this. Here are a couple to get started: 1) Melodic Dictation Practice; 2) Recognizing intervals without interval songs?.
Answer: You say you can go up and down scales/arpeggios etc with alacrity. So you know the shapes. If that was true, you'd know that in C minor, there's no E or F♯. The target would have to be E♭ to stay in key. In the patterns you know and play, you'll never be fretting an E or an F♯ while playing scales and notes in C minor. All that if I read the question right.
So, if that's true, you need to brush up more on notes in scales, and if it helps (it should), say the note names out loud as they're played.
Answer: If you are, like me, at ease with patterns and shapes (like you seem to tell in the question), my advice is to start with the local before you extend to a broader dimension.
For example, if you know the position of the note you want to play in your current position, start by that, then extend to the octave. You'll know on a bass that for example on the upper string it will be 7 frets in direction of the neck. (I take example of the bass because it has the same interval between each string, on a guitar you'll adapt for the special case of the B string)
Practice this slowly, and with time, this will get more and more natural for you to see all octaves of the same note on the neck so when you think of the next note you want to play, you instantly know all the positions on the neck where you can reach it, being an octave upper, lower, or the same on a different string..
Answer: I had a few thoughts that might be useful while I was busy misunderstanding your problem. As a player of a fretless instrument, I'm always dealing with the need for physical hyper-precision in shifts. Sure, I can do an arpeggio, but a piece with huge unprepared leaps is challenging. For this, I'd encourage you to think of the physicality rather than the note theory. If I think, "I have to memorize what it feels like to go from a low B to a G 3 octaves above," then I also have to separately memorize a C to an A, and have a slot in my memory for every single combination of the 12 chromatic tones times four octaves of my instrument's range.
Instead, I find it more helpful to describe how my hand and fingers are actually moving in physical space. I say "I'm shifting up four positions, going over three strings, changing from my second finger to my third, and extending that third finger." Then a shift between different notes might still be the same distance for my arm, even if different fingers are involved or the extension doesn't happen.
The main point of your question seems to be "how do you know which note to play when improvising," which is a common question here. I would answer your question "Are musicians able to jump to any arbitrary note" by saying "Well, maybe it's not all that arbitrary." Outside of true free improv, in which absolutely anything goes... then, as you've noted, there's a reason you're looking for a certain note and not another. It might be a "surprise" note, a non-chordal note, a pivot note, a note that subverts the obvious expectation—but it does it for a reason. Yes, studying theory will help (Oh, guess what, it's just part of a diminished 7th), but ultimately time will help, as these patterns continue to become engrained. You already point out that you're fluent in lots of chordal and scalar patterns; you're just looking to extrapolate those skills across octaves.
I'll also make the somewhat obvious suggestion: Ease into a new skill. If it's improv, why do you have to make a big jump? Start out getting used to jumps of about one octave, then two, then three. Take what you already know and build on it, then build on what you've built.
Comment: It's easy to think of playing an instrument as only those moments during which we're actually creating a pitch. It's valuable to remember that the physical movement between pitches is at least as important.
Answer: Yes, I think you want to be able to move freely from one octave to another.
From your description it sounds like you may be "stuck" in fretboard boxes.
Maybe one way to think about it is: you can do what you train. If your training is predominantly ascending/descending scale and arpeggio patterns in fixed positions, starting on the tonic, then you cannot get out of position easily. Practicing basic scale and arpeggio patterns that way isn't necessarily bad, but it maintains the same fingering position constantly. Eventually you want to be able to get out of one position and into another with flexibility to combine different patterns. Or, in the case of your question to change octaves. So, train for that specific skill.
Try thinking about how a figure could be alternately fretted with "lower", "middle", and "upper" positions. (I made up those three names. The idea is based around the E on string 5, fret 7 with all the other fretting being lower frets, the E in the middle, or all other fretting above the E.)

Each of the three is a different fingering position. You could change the rhythm a bit to make the changes continuous and then need to do something for a "transitional" fingering to get into the next position, like this, with a slide...

Those two examples just repeat a figure in one octave, so you might be wondering what that has to do with moving to another octave. The connection is being able to change fingering positions flexibly instead of being stuck in a basic scale/arpeggio box pattern. If we repeat the pattern at the octave, notice how we can use one of the lower/middle/upper fingerings to execute the jump into the upper octave...

Two other ways to get out the scale/arpeggio box patterns are:

practice scales and arpeggios in "broken" patterns
don't start a pattern on the tonic, start on another tone like one from the dominant chord and then end on the tonic. This helps develop the ability to sort of "jump right in" to a new position...

You can vary the broken scale pattern many ways by direction or using another interval, like fourths instead of thirds. You can also do broken patterns with arpeggios, just skip tones, like up a fifth down a third, up a fifth down a third, etc. etc.

... I have my "target note" that I feel it is, and then the notes that are immediately beside it. For example, I'm about to shift down to an F. Next to it are E and F#. Problem is ... which of the three are in C minor? ... It feels like it almost has to be reflexive that I know which of those three notes it is.

This is very different from the question posed in the title.
I think the short answer is: yes, you need to make this a reflexive action.
It seems to set up a conflict between changing register for purely timbral reasons versus harmonic reasons. I don't mean to suggest you would never change register, or the main purpose for such a change would not be about timbre, but confining the target area to just three frets - that's a range of a single whole step - it too restrictive harmonically. If your ideal timbral location is around the fifth of the chord, but your really want to play the chord's third, you don't have enough lee way in three frets to reach it. That suggests a kind of indifference to harmonic targets and I think you don't want to do that.
But, this is where I think we can get back to your original question in the title about jumping between octaves. If you widen the timbral target zone, you could think in terms of one or two octave shifts. Then, assuming you have really learned the harmonic structure of your scales, you hit the tone you want harmonically. Or, you might visualize a segment of the scale in the new register, like ^3 ^2 ^1, around which a lick is based.

How can I learn to pick a random set of three contiguous notes on the fretboard, and select the proper one in key?

You don't move randomly. You do need to know where you are moving harmonically. But you have options. There isn't only one right target. But that isn't the same as random. A lot will depend on the harmony style. I think you want to at least know where the tonic and dominant of the key or in terms of chords the root, third, and fifth.
All that should be easier to manage if you work in relative terms. Instead of thinking like: I'm in C minor, where is F. Try: I'm in C minor, all  the roots are in these places, and all the perfects fourths these points, those fourths are the subdominant, the ^4 scales degree, or FA in solfege. When you know the generic interval pattern you can do it relative to any tone, any key. The specific letter names are then the incidental details of a particular key. You don't really need to know those letter names to play the pattern right on the spot.


Decay of a function which is integrable against an exponentially growing function

Question: Let $f$ be a measurable function and suppose there exists $\varepsilon>0$ s.t. $\int_{\mathbb{R}}e^{\varepsilon\left|x\right|}f(x)dx<\infty$.
Is it possible to deduce from this that $f(x)\leq Ce^{-\delta\left|x\right|}$ for $\left|x\right|$ big enough for some $\delta>0$ (perfectly fine if $\delta$ is much smaller than $\varepsilon$)?
There obviously has to be sequences $x_{n}$ along which this is true, but I can't get a handle on the potential irregularities of $f(x)$ in the sense that it could be big on sets of small measure.
Any suggestions as to what sort of result is possible would be much appreciated.
EDIT: Alternatively, is it possible to say something about the integrability of $e^{\delta\left|x\right|}f(x)^{p}$ for $p=2$ and beyond.
Comment: As you have said yourself: $f$ can be very big on sets of very small measure. In general, such an inequality will not hold. You would need some further assumptions, like uniform continuity.
Comment: @Dominik. Thanks for your comment - I was afraid of that. What about proving something like $\int_{\mathbb{R}}e^{\delta\left|x\right|}f(x)^{2}dx<\infty$? I feel like the "overall decay" of f should be enough for this even if it occasionally behaves badly, but I'm not making any progress trying to prove it.
Comment: Can we assume that $f$ is nonnegative?
Comment: @Dominik. Yes, certainly! My motivation was to think of it as a density of a random variable.
Answer: You can't conclude this. Let $f$ be a density that has a value proportional to $\exp(\exp(n) - 2n)$ in an $\exp(-\exp(n))$-interval around each integer $n$ and is zero otherwise. Then $\exp(x) f(x)$ is integrable, but $\exp(\delta x) f(x)^{1 + \varepsilon}$ is not integrable for any $\varepsilon > 0$ (not even for negative $\delta$).
Comment: Many thanks for the counterexample! Looks like an apriori $L^{\infty}$ bound could be quite helpful in ruling out this kind of behavior.


Is there a name for when a line is too long for the metre?

Question: In some songs, a line in one verse will be a syllable longer than the matching line in other verses, and this will be resolved by adding an extra note to the start or end of that line of melody (in that verse), making the line longer by cutting into the time between lines.
The first example that comes to mind is Queen's Death On Two Legs, which has this on almost every line in the last verse.
What is this called?
Something similar also happens commonly in hymns. The extra syllable is added by splitting (e.g.) a minim into two crotchets, adding the extra note without lengthening the line. I'm not specifically asking about this, but maybe it is covered by the same name.
Comment: I've not come across a musical term for this myself, but in poetry such a line might be called hypermetrical or hypercatalectic.
Answer: Hymnals that classify their contents by meter (in an appendix) refer to this simply as IM, which is an abbreviation for Irregular Meter.  In other words, the metrical construction of each verse does not exactly match that of every other verse.
However, that does not really answer your question, because I take you to be asking about the adding of extra notes in the music to adjust for the irregularity of the meter.  I have heard that called "rhythmic adjustment," but only by a few organists and choir directors, and I don't believe it's a generally accepted term used by musicians in general.
I'm tempted to call certain examples of it "The Carly Simon Effect," because in her early songs she did that more than any other songwriter I've ever run into.  She would often cram three or four extra syllables into the end of a line, with no effort to make the stress points in the meter match the beat of the music.  She always did it at the end of lines, rather than throughout a line, as a lot of hymns do.
Sorry to be of so little help.  I fear there is no established term for the phenomenon.  If there was, somebody would have posted an answer before now!