multiprocessing: How can I ʀᴇʟɪᴀʙʟʏ redirect stdout from a child process?

Question: NB. I have seen Log output of multiprocessing.Process - unfortunately, it doesn't answer this question.
I am creating a child process (on windows) via multiprocessing. I want all of the child process's stdout and stderr output to be redirected to a log file, rather than appearing at the console. The only suggestion I have seen is for the child process to set sys.stdout to a file. However, this does not effectively redirect all stdout output, due to the behaviour of stdout redirection on Windows.
To illustrate the problem, build a Windows DLL with the following code
#include <iostream>

extern "C"
{
    __declspec(dllexport) void writeToStdOut()
    {
        std::cout << "Writing to STDOUT from test DLL" << std::endl;
    }
}

Then create and run a python script like the following, which imports this DLL and calls the function:
from ctypes import *
import sys

print
print "Writing to STDOUT from python, before redirect"
print
sys.stdout = open("stdout_redirect_log.txt", "w")
print "Writing to STDOUT from python, after redirect"

testdll = CDLL("Release/stdout_test.dll")
testdll.writeToStdOut()

In order to see the same behaviour as me, it is probably necessary for the DLL to be built against a different C runtime than than the one Python uses. In my case, python is built with Visual Studio 2010, but my DLL is built with VS 2005.
The behaviour I see is that the console shows:
> stdout_test.py

Writing to STDOUT from python, before redirect

Writing to STDOUT from test DLL

While the file stdout_redirect_log.txt ends up containing:
Writing to STDOUT from python, after redirect

In other words, setting sys.stdout failed to redirect the stdout output generated by the DLL. This is unsurprising given the nature of the underlying APIs for stdout redirection in Windows. I have encountered this problem at the native/C++ level before and never found a way to reliably redirect stdout from within a process. It has to be done externally.
This is actually the very reason I am launching a child process - it's so that I can connect externally to its pipes and thus guarantee that I am intercepting all of its output. I can definitely do this by launching the process manually with pywin32, but I would very much like to be able to use the facilities of multiprocessing, in particular the ability to communicate with the child process via a multiprocessing Pipe object, in order to get progress updates. The question is whether there is any way to both use multiprocessing for its IPC facilities and to reliably redirect all of the child's stdout and stderr output to a file.
UPDATE: Looking at the source code for multiprocessing.Processs, it has a static member, _Popen, which looks like it can be used to override the class used to create the process. If it's set to None (default), it uses a multiprocessing.forking._Popen, but it looks like by saying
multiprocessing.Process._Popen = MyPopenClass

I could override the process creation. However, although I could derive this from multiprocessing.forking._Popen, it looks like I would have to copy a bunch of internal stuff into my implementation, which sounds flaky and not very future-proof. If that's the only choice I think I'd probably plump for doing the whole thing manually with pywin32 instead.
Comment: Yes, I mentioned in the question that "I can definitely do this by launching the process manually with pywin32". It just seemed a shame to abandon the higher-level, platform independent multiprocessing module because of what seems like a trivial bit of missing functionality - the ability to specify stdin/stdout handles for the child.
Comment: The approach I'm taking (unless someone comes up with a better alternative) is to launch the process via the subprocess module, with stdin/stdout redirected to a file, and use a native Windows named pipe for the progress communication.
Comment: Can you use the Win32 API to launch the subprocess, or does it have to be done using existing Python libraries?
Comment: Didn't it work properly if you redirect sys.stdout of the *parent* process, before launching the child?
Comment: As @Luke 's answer shows, it's not so hard to build a "mini-multiprocessing" with this functionality - so is there any fundamental issue for why this shouldn't just be part of Python's own multiprocessing to begin with? Does anyone want to open a ticket requesting this or do you think it will get closed immediately?
Answer: The solution you suggest is a good one: create your processes manually such that you have explicit access to their stdout/stderr file handles. You can then create a socket to communicate with the sub-process and use multiprocessing.connection over that socket (multiprocessing.Pipe creates the same type of connection object, so this should give you all the same IPC functionality).
Here's a two-file example.
master.py:
import multiprocessing.connection
import subprocess
import socket
import sys, os

## Listen for connection from remote process (and find free port number)
port = 10000
while True:
    try:
        l = multiprocessing.connection.Listener(('localhost', int(port)), authkey="secret")
        break
    except socket.error as ex:
        if ex.errno != 98:
            raise
        port += 1  ## if errno==98, then port is not available.

proc = subprocess.Popen((sys.executable, "subproc.py", str(port)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

## open connection for remote process
conn = l.accept()
conn.send([1, "asd", None])
print(proc.stdout.readline())

subproc.py:
import multiprocessing.connection
import subprocess
import sys, os, time

port = int(sys.argv[1])
conn = multiprocessing.connection.Client(('localhost', port), authkey="secret")

while True:
    try:
        obj = conn.recv()
        print("received: %s\n" % str(obj))
        sys.stdout.flush()
    except EOFError:  ## connection closed
        break

You may also want to see the first answer to this question to get non-blocking reads from the subprocess.
Answer: I don't think you have a better option than redirecting a subprocess to a file as you mentioned in your comment.
The way consoles stdin/out/err work in windows is each process when it's born has its std handles defined. You can change them with SetStdHandle. When you modify python's sys.stdout you only modify where python prints out stuff, not where other DLL's are printing stuff. Part of the CRT in your DLL is using GetStdHandle to find out where to print out to. If you want, you can do whatever piping you want in windows API in your DLL or in your python script with pywin32. Though I do think it'll be simpler with subprocess.
Answer: Alternatively - and I know this might be slightly off-topic, but helped in my case for the same problem - , this can be resolved with screen on Linux:
screen -L -Logfile './logfile_%Y-%m-%d.log' python my_multiproc_script.py

this way no need to implement all the master-child communication
Answer: I assume I'm off base and missing something, but for what it's worth here is what came to mind when I read your question.
If you can intercept all of the stdout and stderr (I got that impression from your question), then why not add or wrap that capture functionality around each of your processes? Then send what is captured through a queue to a consumer that can do whatever you want with all of the outputs?
Answer: In my situation I changed sys.stdout.write to write to a PySide QTextEdit. I couldn't read from sys.stdout and I didn't know how to change sys.stdout to be readable. I created two Pipes. One for stdout and the other for stderr. In the separate process I redirect sys.stdout and sys.stderr to the child connection of the multiprocessing pipe. On the main process I created two threads to read the stdout and stderr parent pipe and redirect the pipe data to sys.stdout and sys.stderr.
import sys
import contextlib
import threading
import multiprocessing as mp
import multiprocessing.queues
from queue import Empty
import time

class PipeProcess(mp.Process):
    """Process to pipe the output of the sub process and redirect it to this sys.stdout and sys.stderr.

    Note:
        The use_queue = True argument will pass data between processes using Queues instead of Pipes. Queues will
        give you the full output and read all of the data from the Queue. A pipe is more efficient, but may not
        redirect all of the output back to the main process.
    """
    def __init__(self, group=None, target=None, name=None, args=tuple(), kwargs={}, *_, daemon=None,
                 use_pipe=None, use_queue=None):
        self.read_out_th = None
        self.read_err_th = None
        self.pipe_target = target
        self.pipe_alive = mp.Event()

        if use_pipe or (use_pipe is None and not use_queue):  # Default
            self.parent_stdout, self.child_stdout = mp.Pipe(False)
            self.parent_stderr, self.child_stderr = mp.Pipe(False)
        else:
            self.parent_stdout = self.child_stdout = mp.Queue()
            self.parent_stderr = self.child_stderr = mp.Queue()

        args = (self.child_stdout, self.child_stderr, target) + tuple(args)
        target = self.run_pipe_out_target

        super(PipeProcess, self).__init__(group=group, target=target, name=name, args=args, kwargs=kwargs,
                                          daemon=daemon)

    def start(self):
        """Start the multiprocess and reading thread."""
        self.pipe_alive.set()
        super(PipeProcess, self).start()

        self.read_out_th = threading.Thread(target=self.read_pipe_out,
                                            args=(self.pipe_alive, self.parent_stdout, sys.stdout))
        self.read_err_th = threading.Thread(target=self.read_pipe_out,
                                            args=(self.pipe_alive, self.parent_stderr, sys.stderr))
        self.read_out_th.daemon = True
        self.read_err_th.daemon = True
        self.read_out_th.start()
        self.read_err_th.start()

    @classmethod
    def run_pipe_out_target(cls, pipe_stdout, pipe_stderr, pipe_target, *args, **kwargs):
        """The real multiprocessing target to redirect stdout and stderr to a pipe or queue."""
        sys.stdout.write = cls.redirect_write(pipe_stdout)  # , sys.__stdout__)  # Is redirected in main process
        sys.stderr.write = cls.redirect_write(pipe_stderr)  # , sys.__stderr__)  # Is redirected in main process

        pipe_target(*args, **kwargs)

    @staticmethod
    def redirect_write(child, out=None):
        """Create a function to write out a pipe and write out an additional out."""
        if isinstance(child, mp.queues.Queue):
            send = child.put
        else:
            send = child.send_bytes  # No need to pickle with child_conn.send(data)

        def write(data, *args):
            try:
                if isinstance(data, str):
                    data = data.encode('utf-8')

                send(data)
                if out is not None:
                    out.write(data)
            except:
                pass
        return write

    @classmethod
    def read_pipe_out(cls, pipe_alive, pipe_out, out):
        if isinstance(pipe_out, mp.queues.Queue):
            # Queue has better functionality to get all of the data
            def recv():
                return pipe_out.get(timeout=0.5)

            def is_alive():
                return pipe_alive.is_set() or pipe_out.qsize() > 0
        else:
            # Pipe is more efficient
            recv = pipe_out.recv_bytes  # No need to unpickle with data = pipe_out.recv()
            is_alive = pipe_alive.is_set

        # Loop through reading and redirecting data
        while is_alive():
            try:
                data = recv()
                if isinstance(data, bytes):
                    data = data.decode('utf-8')
                out.write(data)
            except EOFError:
                break
            except Empty:
                pass
            except:
                pass

    def join(self, *args):
        # Wait for process to finish (unless a timeout was given)
        super(PipeProcess, self).join(*args)

        # Trigger to stop the threads
        self.pipe_alive.clear()

        # Pipe must close to prevent blocking and waiting on recv forever
        if not isinstance(self.parent_stdout, mp.queues.Queue):
            with contextlib.suppress():
                self.parent_stdout.close()
            with contextlib.suppress():
                self.parent_stderr.close()

        # Close the pipes and threads
        with contextlib.suppress():
            self.read_out_th.join()
        with contextlib.suppress():
            self.read_err_th.join()

def run_long_print():
    for i in range(1000):
        print(i)
        print(i, file=sys.stderr)

    print('finished')

if __name__ == '__main__':
    # Example test write (My case was a QTextEdit)
    out = open('stdout.log', 'w')
    err = open('stderr.log', 'w')

    # Overwrite the write function and not the actual stdout object to prove this works
    sys.stdout.write = out.write
    sys.stderr.write = err.write

    # Create a process that uses pipes to read multiprocess output back into sys.stdout.write
    proc = PipeProcess(target=run_long_print, use_queue=True)  # If use_pipe=True Pipe may not write out all values
    # proc.daemon = True  # If daemon and use_queue Not all output may be redirected to stdout
    proc.start()

    # time.sleep(5)  # Not needed unless use_pipe or daemon and all of stdout/stderr is desired

    # Close the process
    proc.join()  # For some odd reason this blocks forever when use_queue=False

    # Close the output files for this test
    out.close()
    err.close()

Answer: Here is the simple and straightforward way for capturing stdout for  multiprocessing.Process:
import app
import io
import sys
from multiprocessing import Process

def run_app(some_param):
    sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
    app.run()

app_process = Process(target=run_app, args=('some_param',))
app_process.start()
# Use app_process.termninate() for python <= 3.7.
app_process.kill()

Comment: As the question noted, this doesn't redirect _all_ output, e.g. when calling into external executables or when using non-Python libraries.


finding minimum value of an array

Question: from what I've learned, I should be getting the min value of the array, but instead I am getting a large negative number that doesn't exist in my array.
int size;
size = sizeof(array) / sizeof(array[0]);

int min;
min = array[0];

for(int i = 1; i <= size; i++) {
    if(array[i] < min){
        min = array[i];
    }
}

But for some reason I am getting a large negative number: -9.25596e+061
Answer: for(int i = 1; i <= size; i++) {
                //^^^^array index out of bound, since array index starts from 0
   if(array[i] < min){
      min = array[i];
   }
}

You should only compare elements in your array. You tried to access memory not belonging to the array, so you have strange values in that memory.
Your code should look like this:
int min = array[0];
for(int i = 1; i < size; i++) {
   if(array[i] < min){
      min = array[i];
   }
}

Comment: To elaborate, C arrays are indexed from 0, not 1, so the first element is at `[0]`, and the last element is at `[length-1]`
Comment: lol Thanks had a dumb moment there...I've been coding for 8 hrs straight.
Comment: @tacp can you help me with my avg calculator loop, for some reason I am getting a negative number again like before that should come up
Answer: When doing your comparison, <= size means you're iterating 1 past the end of the array. It's most likely picking up some really huge garbage value and that becomes the minimum.
Use for (int i = 1; i < size; ++i) { /* ... */ } to get what you need.

finding minimum value of an array


.net core - Middleware don't handle requests

Question: I am having a problem with middleware in .Net Core 2. Middleware doesn't handle any coming requests.
What I have implemented.
KeyValidatorMiddleware class:
public class KeyValidatorMiddleware
{
    private readonly RequestDelegate _next;

    public KeyValidatorMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {

        if (!context.Request.Headers.ContainsKey("api-key"))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("No API key found !");
            return;
        }

        await _next.Invoke(context);
    }
}

and in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseCors("MyPolicy");
    app.UseMiddleware<KeyValidatorMiddleware>();
}

And nothing works, What am i missing in order to make the middleware work?
Comment: Where in the pipeline have you added the `UseMiddleware` line? Can you show us a more complete `Configure` method?
Comment: Move the `UseMiddleware` line to be nearer the top, middleware runs in order and it may stop at the MVC level.
Answer: You should move the UseMiddleware line to be nearer the top, middleware runs in order and it may stop at the MVC level.
For example:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseMiddleware<KeyValidatorMiddleware>();

    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseCors("MyPolicy");
}

Comment: OP: It's a slight aside, but you're also going to want to reconsider where `app.UseCors` goes based on this information (and `app.UseHttpsRedirection` actually).
Answer: Registration of middleware is ordered. So anything you register before MVC will run before MVC.
MVC handles the request if it matches a URL that MVC can handle. Anything you register after MVC will only handle the request if MVC fails to match the URL.


Uniform distributed success probability for a coin

Question: $n\in \Bbb N$. Let $X_1 \sim \text{Uni}_{(0,1)}$ and $X_2 \sim \text{Bin}_{n, X_1}$ conditional on $X_1$. I want to find the distribution function of the law of $X_1$ given $X_2 = k$, i.e. $\Bbb P (X_1 \leq t \ \vert \ X_2 = k )$, where $k\in \{1, \ldots , n\}$.
Comment: Use the definition of conditional probability.
Comment: Just use the Law of Total Probability, and Bayes' Theorem.
Answer: We compute
\begin{align*}
&\mathbb{P}(X_1\in(p,p+\mathrm{d}p), X_2=k)\\
&=\mathbb{P}[X_1\in(p,p+\mathrm{d}p)]\mathbb{P}[X_2=k\mid X_1\in(p,p+\mathrm{d}p)]\\
&=\binom{n}{k}p^k(1-p)^{n-k}\mathrm{d}p
\end{align*}
so $X_1\mid X_2$ is a $\operatorname{Beta}(X_2+1,n-X_2+1)$-distributed random variable.
Since Uniform(0,1) is another name for $\operatorname{Beta}(1,1)$, this example is a special case of a conjugate prior.
Comment: Yeah, it is not the best notation, but at least this avoids conditioning on null event $X_1=p$.
Comment: I am not really d'accord with your notation $\in (p, p + \text d p)$ but all in all this helped me to complete my task.
Comment: Ah, it is another notation for the densities.


C99- Condition is always true inside function

Question: I am writing a function, that has a part that needs to only be run once. I tried creating a local flag variable, but somehow, I get an error message. that the condition is always true.
A simplified version of my function looks like this:
void showMainMenu(bool *bool_drawMainMenu, TTF_Font *font1, TTF_Font *font2){
        while(*bool_drawMainMenu){
        bool flag=true;
        if(flag){
            flag=false;
            renderMenu(font1,text_Surface,text_Texture,renderer,mainMenu,3);
            SDL_Rect where={720/2,150};
        }
//...

Comment: What is the error message? When is it issued? Who issues it?
Comment: _I get an error message_, do you mean a warning?
Comment: Please present the example to be a complete, runnable [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: Do you mean "run once during each call of the function" or do you mean "run once only during first call of that function."?
Answer: Try it like this:
void showMainMenu(bool *bool_drawMainMenu, TTF_Font *font1, TTF_Font *font2){
    bool flag=true;
    while(*bool_drawMainMenu){
    if(flag){
        flag=false;
        renderMenu(font1,text_Surface,text_Texture,renderer,mainMenu,3);
        SDL_Rect where={720/2,150};
    }
//...

If you re-define the flag variable in each loop, it will always be true when you get to the if.


só consigo abrir imagens png com o tkinter

Question: Estou tentando abrir imagens jpeg com o tkinter usando o PhotoImage, mas não consigo. O programa e a imagem estão na mesma pasta, mas mesmo assim ele dá erro:

couldn't open "imagem.jpeg": no such file or directory

Estou usando o seguinte código:
from tkinter import *

janela = Tk()
janela.geometry('1300x740')

imagem = PhotoImage(file="imagem.jpeg")

lb = Label(janela, image = imagem)
lb.place(x = 550, y = 320)`

janela.mainloop()

Comment: Pode nos mostrar quais os arquivos que estão no seu diretório em que o arquivo.py principal é executado ?
Answer: O PhotoImage do tkinter não trabalhar com todos os formatos de imagem:
https://docs.python.org/3.3/library/tkinter.html
Veja que a documentação ressalta essa parte no seguinte trecho:

PhotoImage can be used for GIF and PPM/PGM color bitmaps.

Quando você tenta abrir uma imagem não suportada pelo PhotoImage do tkinter, a exceção gerada é a seguinte:

couldn't recognize data in image file "imagem.jpeg"

A sua exceção está distinta dessa, logo você também está tendo problema na localização do arquivo, verifique se a extensão do arquivo na verdade não é jpg, é mais comum ser dessa forma.

Para trabalhar com um jpg, você pode utilizar da biblioteca PIL (Python Imaging Library):
https://pillow.readthedocs.io/en/stable/
Instalando o mesmo pelo pip conforme a documentação orienta:

python -m pip install pip
python -m pip install Pillow

Trabalhando com a PIL, seu exemplo ficaria da seguinte forma:
from tkinter import *
from PIL import Image, ImageTk

janela = Tk()
janela.geometry('1300x740')

jpg = Image.open("imagem.jpeg")
imagem = ImageTk.PhotoImage(jpg)

# Pode ser tudo em apenas uma linha
# imagem = ImageTk.PhotoImage( Image.open("imagem.jpeg") )

lb = Label(janela, image = imagem)
lb.place(x = 550, y = 320)

janela.mainloop()


Can't start Git Bash

Question: Having trouble starting Git Bash, not sure where in the stack my errors are occuring. Running Windows 10, Git Bash, ConEmu and Vagrant.
When I start Git Bash, either through ConEmu or the application directly, I receive the following message:
0 [main] bash 4696 fork: child 528 - died waiting for dll loading, errno 11
bash: fork: retry: No child processes
1263234 [main] bash 4696 fork: child 684 - died waiting for dll loading, errno 11
bash: fork: retry: No child processes
3519490 [main] bash 4696 fork: child 2020 - died waiting for dll loading, errno 11
bash: fork: retry: No child processes
7764494 [main] bash 4696 fork: child 7064 - died waiting for dll loading, errno 11
bash: fork: retry: No child processes

I don't know enough about Git Bash (or bash, for that matter) to figure out what's going on and all the answers I can find are about Cygwin.
Answer: Same issue happened with COMODO Firewall since last update.

Adding Git folder to File Rating > File List as trusted file

Adding Git folder to Advanced protection > Milanescious > Shell code exclusion

Setting git-bash.exe as allowed application in Firewall > Application Rules (this one may be optional, but it won't hurt anyway)

Solved the issue on Windows 10.
Side note : Turning COMODO firewall off does not solve the issue, this is quite misleading... But adding exclusions rules does fix the problem.
Other side note: if you use Comodo Firewall, you should consider uninstalling it... It has bugged and ruined my windows install, i've got a lot of BSOD as soon as i removed it... When i think of it in hindsight, he was the root cause of a lot of problem. I mean, how in the world a Firewall could silently block an application or infinite sandboxing it without even a notification. Plus the removall is a pain in the ass, uninstaller crash one time out of two...
Comment: I tried disabling comodo entirely - and I mean all it's components - this did not help and it confused me as I was sure it was the culprit. After adding the rules it works fine now. Thanks!
Comment: That solves my problem. I did not have to add anything to Firewall, though. Anyway thanks for the answer.
Comment: Same for me.... I can't get why some protection is still active when desabled.....
Comment: TL;DR for others: aside from Comodo, another answer in this post points to [BeyondTrust](https://stackoverflow.com/a/49118872/295686) [PowerBroker](https://stackoverflow.com/a/44158372/295686) antivirus; there is a [bug filed](https://github.com/git-for-windows/git/issues/1244) mentioning Cylance (my issue), so I think it is safe to generalize this to a 'check your antivirus logs' - obviously resolutions will differ by AV software and may require IT intervention in a corporate environment.
Comment: Nice :). I wasn't a 100% sure about the `Firewall > Application Rules`, since i tested a lot of thinks to get it work.
Comment: Thank you, it also worked for me on Windows 7. On a site note, it made Git/SourceTree faster (I guess a sign that before that there was already some kind of conflict going on in the background).
I still have a few error messages left, though (but they don't seem to cause any issue)
Comment: Made my git faster as well.
Comment: In case it's not apparent: this problem is _not_ specific to Git Bash - if you use `git.exe`, like me, allowing it through Windows Firewall solves this too.
Answer: Turns out Comodo Antivirus was auto-sandboxing Git Bash. Adding Git Bash as an exception to the sandboxing rules solved my problem.
Hope this saves someone else an hour.
Comment: How did you fix it? I've disabled everything in comodo and still seeing the issue...
Comment: I ended up uninstalling Comodo...not being able to use Git Bash easily is an absurd failure in their product.
Comment: @BogdanVarlamov I had to delete Git Bash and reinstall. I think I disabled Comodo sandboxing entirely, or maybe there are filters for specific .exe. Then reinstall Git Bash. Then update Comodo sandboxing with your desired settings. It's been awhile and I don't use the same environment, so that's from memory. YMMV.
Comment: I'm running into this now after their last update. I disabled everything (including firewall and HIPS) but it's still blocking it. Not sure what else I could do. Uninstalling comodo fixed it for me. I don't even know if it's a "bug" in comodo or if msys needs to update how they call some windows api.
Comment: @Bogdan The feature in question that prevents Git Bash is explicitly one that prevents shell code injection which is what's being prevented here. You can turn it off or add exclusions to it specifically. But yeah, it's annoying that it took so long to figure out the feature even exists for something that I thought was just a network firewall.
Comment: @Jahed, I did try to look through the settings to turn it off, but after wasting about an hour I decided I would just get rid of Comodo...where are the specific settings to fix git bash that you changed?
Comment: @Bogdan Varlamov: how did you manage to uninstall? I tried, but the uninstaller failed. Running a brand new installer on top of it failed too. Loos like I'm stuck with Comodo for the rest of my PC's life :/
Comment: @Jahed: for me, turning off the code injection thing didn't fix it. I really had to add Git the to exclusion list, even with the feature disabled.... #snafu
Comment: Look at my answer, there is some exclusions that need to be added.
Comment: @user14764, the uninstaller worked for me...sorry :(
Answer: The company I work for has BeyondTrust PowerBroker on corporate computers, and that turned out to be the source of the problem.
I solved it by adding a the key ExcludedProfilerApps to HKLM\SOFTWARE\Policies\BeyondTrust\PBDesktops with the value C:\Program Files\Git\*.
Here is a link to some discussion of the issue.
Git Bash complained about some permissions on startup, but I didn't notice any other issues.
Installing Git 2.7.0, as @rakehell have mentioned, also resolved the issue.
Comment: Thanks for this tip! My company also uses BeyondTrust PowerBroker and this worked for me. My Git Bash was located in a different directory than `C:\Program Files\Git`, so I had to add that directory to `ExcludedProfilerApps` instead.
Answer: I have solved this by adding an exclusion for the entire git directory in (c:\Program Files\Git\*):
Advanced Settings -> Advanced Protection -> Miscellaneous -> Detect shellcode injections
See this https://forums.comodo.com/news-announcements-feedback-cis/comodo-internet-security-v10016209-released-t118704.0.html;msg854022#msg854022
Comment: Thanks so much, this is the most easiest solution, worked for me on windows 10 :D
Comment: Solved it for me too. Thanks!
Answer: I had this problem on Win 7 and installed 5 versions of Git working backwards from the latest as well as run every solution I could find by Googling. However, the only thing that worked was this version: 2.7.0
The subsequent updates, 220.127.116.11 and 184.108.40.206, did not work.
HTH
Comment: Whoever worrying for older version here is the link :
https://github.com/git-for-windows/git/releases?after=v2.8.1.windows.1
Comment: FYI, this was the only thing that worked for me as well.  I had 2.15 installed and it failed miserably, but 2.7.0 got it working.  It even launched Git bash as a MINGW64 app with all the nice ASCII colors.  Before, it was just a glorified command prompt that threw error messages all the time.
Answer: It is definitely a BeyondTrust /firewall issue.
Here is what happened on my Windows 7 laptop:

Git (via msi installer) was installed in the local programs directory : C:\Users\myusername\AppData\Local\Programs\Git
But the regedit shows a different value here -> HKLM ->SOFTWARE\Policies\BeyondTrust\PBDesktops shows the value C:\Program Files\Git*

Solution :

Copy the Git folder from C:\Users\myusername\AppData\Local\Programs\ and paste it to C:\Program Files

Can't start Git Bash


Hosting the endpoint in the BizTalk process using non UTF-8 encoding

Question: There is a problem with encoding using WCF detailed described here : blog post
WCF: Text Message Encoding and ISO-8859-1 Encoding
I'm getting similar error in response :

A message sent to adapter "WCF-BasicHttp" on send port "XXXX" with URI "http://XXXXXXXX:8080/index.php" is suspended.
Error details: System.ServiceModel.ProtocolException: The content type text/xml; charset=ISO-8859-1 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly.

I'd like to create a simple proxy WS in BizTalk Environment. I created 1 Receive Location using WCF-BasicHttp / WCF-Custom (neither worked) adapter and send port (SOAP WCF-BasicHttp). Send port is subscribing Receive Location as mentioned here:
Best approach to simple proxy on BIZTALK
I created endpoint in the BizTalk process mentioned here: Codit Blog Hosting WCF HTTP receive location inside BizTalk, without using IIS.
I cannot set other textEncoding than UTF-8, while trying to set ISO-8859-1 I get the error:

"The text encoding ISO-8859-1 used in the text message format is not supported. Parameter name: encoding"

Is there any way to run this using some custom encoders in BizTalk environment?
Answer: I managed to do it myself.
I deleted textMessageEncoding binding from Receive and Send WCF-Custom adapter

and instead of it I put customMessageEncoder binding with soap11 and proper iso encoding. Note that httpTransport should be last on binding list.


Rails (ruby) create empty array when no association found

Question: So I have this bit of code:
= f.input :aspectRatioId, :label => 'Aspect Ratio',
:input_html => { :id => 'dvd_aspectRatio_tokens', :data => { :load => [@dvd.aspectRatio] } }

I'd like to create an empty array when nothing is found in the association. Right now when nothing is found it returns [null] which trips up tokeninoput javascript that expects []
I can do this by creating another method like this:
def self.series_without_empty_values(dvd)
  series = [dvd.dvd_series]
  if series[0].nil?
    series = []
  end
  return series
end

But I would rather do it in the :load => call on the form. Is this even possible?
Comment: you could try `:load => [@dvd.aspectRatio] || []`. Not sure if that will work though.
Comment: @HunterMcMillen: No, that won't work, `[nil]` is true-ish, even `[]` is true-ish in Ruby. @kaukebie, that's a weird way to write that condition :-) even if Ruby had no `Array#compact` you'd simply write: `dvd.dvd_series ? [dvd.dvd_series] : []`.
Comment: It's hardly ever necessary to call `.nil?` on an object that will either be defined or not. Use `if (!series[0])` or `unless (series[0])` instead for simplicity. However, as noted in the answers, `compact` is the solution to this problem.
Comment: @HunterMcMillen that won't work, I tried it. @tokland: The ol' ternary operator, I love it but it doesn't work because dvd.dvd_series will not result in false unless I do something like what I'm doint there: `series[0].nil?` anything else would simply not return the empty array.
Comment: @tadman: I actually think that `if series[0].nil?` is a lot more readable than `(!series[0])`. I always miss those `!` :) Thanks for all the suggestions, that's what this site is all about.
Comment: @kakubei There's a lot of things you'll miss until you develop an eye for them. `=` vs `==` is one, and the binding of `&&` vs `and` is another. I prefer `unless` to avoid ambiguity.
Comment: @tadman: The `=` I'm actually ok with. `&&` vs `and` I'm still on the fence.  But I do prefer `unless`. I think it's a wonderful addition that other languages (I'm looking at you PHP) don't have.
Answer: Use Array.compact to remove nil values in an array:
[ "a", nil, "b", nil, "c", nil ].compact
=> [ "a", "b", "c" ]

[nil].compact
=> []

Comment: Good idea, maybe combine it with "empty?": "if series.compact.empty?"
Comment: This is wonderful! I didn't know about this method. Now I can remove all those extra methods! It was really bothering me to have to add ugly hacks. Thanks a lot. (I love Ruby :)
Comment: Check out the `Enumerable` library as it's full of interesting features.


Is it logical to report standard deviation of the coefficient of Regression model?

Question: I had determined the coefficient for the variables using Multinomial Logit model. The software reported coefficient, t-value and standard error for the variable.
One of my senior want to include Standard Deviation of the coefficient as well. But the software doesn't report SD.
Does it make sense to interpret the coefficient with standard deviation? If yes, what can I do to get the standard deviation of the coefficient?
Thank you
Comment: By way of lending support to rvl's fine answer -- your colleague seems to misunderstand the meaning of the standard error of a coefficient. The first part of the first sentence of the Wikipedia article on [Standard error](https://en.wikipedia.org/wiki/Standard_error) explains: "*The standard error (SE) is the standard deviation of the sampling distribution of a statistic*".
Comment: I suspect your "senior" didn't understand the difference between a standard deviation and standard error.  When reporting the values of estimated coefficients, I think it's best to present confidence intervals.  A lot of information is contained in it.
Comment: Glen_b Thanks for the clarification.     @StatsStudent Presenting confidence interval seems to represent the coefficient well. But, how can I get confidence interval when the software that I am using does not report them?
Comment: @Droko, what software are you using?  I find it hard to believe, if you are using statistical software, that it doesn't provide a standard error or a confidence interval.
Comment: @StatsStudent The software is Easy Logit Modeler (free software esp. for discrete choice modeling). It does provide standard error. I think I can do that by using:  Lower limit = M - Z.95 * SE

Upper limit = M + Z.95*SE. Correct me if I am wrong. Thanks
Answer: It doesn't make sense; either that, or there's no distinction. The term "standard error" refers to the standard deviation of the sampling distribution of an estimate. There is no interpretation of "SD" for the regression coefficient apart from the SE that you already have in your printout.


"The application wrote to memory after end of heap buffer" - Cpp

Question: I am trying to delete a buffer in a function using Cpp,
This is my code so far:
<code>void GetPiece(int size)
{
    //std::cout << "Downloading File Index: " + currFileIndex <<  " More: " + pieceSize - size;
    char * newBuffer = new char[size];
    bitRequest->RecvBySize(newBuffer, size - 4, 5);
    //newBuffer += 8;
    File file("work_torrent.mp3");
    file.WriteToFile(newBuffer + 8, size - 4);
    file.Close();

    pieceSize -= size -4;
    std::cout << "Downloading File Index: " << currFileIndex << " More: " << pieceSize << std::endl;

    if (pieceSize <= 0)
    {
        currFileIndex++;
        pieceSize = pieces.at(currFileIndex).fileSize;
    }

    offset += size - 4;

    if (pieceSize > 16384)
    {
        if (1048576 - offset < 16384)
        {
            requestSize = 1048576 - offset;
            if (requestSize == 0)
            {
                offset = 0;
                currPieceIndex++;
                if (pieceSize > 16384)
                {
                    requestSize = 16384;
                }
                else {
                    requestSize = pieceSize;
                }
            }
        }
        else {
            requestSize = 16384;
        }

    }
    else {
        requestSize = pieceSize;
    }

    bitRequest->RequestPiece(currPieceIndex, offset, requestSize);

    delete[] newBuffer; // Here it throws the error

}
</code>
The error:

It appears only when I am trying to free the char array from memmorry, Someone know why it gives the error?
When the delete line is not there, after some times that I call to the function the program crash due to fail allocation.
Comment: @Y.Franco And, why didn't you think it was important to show us that function, if it **writes** to the buffer, and you are getting an error about **writing** past the end of the buffer?
Comment: `file.WriteToFile(newBuffer + 8, size - 4);` When passing to `WriteFile`, you have moved the buffer pointer forward by 8 bytes, while stating that size is smaller by 4 bytes. It is possible that `WriteToFile` read 4 bytes past the end of the buffer. Can't tell what wrote past the end of the buffer without [mcve].
Comment: What does `bitRequest->RecvBySize(newBuffer, size - 4, 5);` do?
Comment: @NathanOliver Recieve data by size to a specific buffer.
Comment: The crash is likely due to undefined behaviour in some part of your program. The mcve will help you - or us - find it.
Comment: Also, `pieceSize` is not declared or initialized anywhere.
Comment: @Y.Franco `RecvBySize` has two integer parameters. Which one is the size, and what is the other one?
Comment: @AlgirdasPreidžius was right, Thanks! The problem was that the writeToFile function wrote 4 bytes more then the buffer size. Thanks!
Answer: I guess you modified the element outside of the array boundary. You know, in C++ the IDE won't check if the element you are assigning to is outside or within.
Comment: While this might be the answer to the question, I'd personally put these kinds of "I guess" answers first as comments in the question's comment section to ask for clarification. That way- if the guess is wrong, there's less answer noise.


Override a field in a taxonomy terms view

Question: I have a taxonomy terms view, filtered by a vocabulary. I would like to add the dashes before the term name like in the Parent terms field on the edit term page. The code in TermForm.php does that when creating $options using str_repeat based on the item's depth.
This is the code from TermForm.php:
$tree = $taxonomy_storage->loadTree($vocabulary->id());
$options = ['<' . $this->t('root') . '>'];
if (empty($parent)) {
  $parent = [0];
}

foreach ($tree as $item) {
  if (!in_array($item->tid, $exclude)) {
    $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
  }
 }
}

I copied core/modules/views/templates/views-view-field.html.twig to my module's templates directory and renamed it views-view-field--my-view-name--name.html.twig
I added hook_theme to the module file to start using the template.
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'views_view_field__my_view_name__name'=> [
      'render element' => 'elements',
      'template' => 'views-view-field--my-view-name--name',
    ],
  ];
}

If I add some markup to the template, like
hello
, hello is printed on the View's page but, no data is being passed to the template.
Ultimately I need to get the term object and update it with
str_repeat('-', $item->depth) . $item->name

before passing the field to the template. I'm guessing I get the term object in a preprocessor and add the updated name field to hook_theme?
Answer: It turns out I don't need the template. Using hook_preprocess_views_view_field() with the following code was all that was required:
/**
 * Implements hook_preprocess_views_view_field().
 */
function my_module_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  $field_id = $field->field;
  if (
    $view->storage->id() === 'my_view_name' &&
    $view->current_display === 'my_display' &&
    $field_id === 'name'
  ) {
    $tid = $variables['row']->_entity->id();
    $label = $variables['row']->_entity->label();

    $parents = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadAllParents($tid);
    $depth = count($parents);
    $path = \Drupal::service('path_alias.manager')
      ->getAliasByPath('/taxonomy/term/' . $tid);

    $link = '' . $label . '';
    $variables['output'] = Markup::create(str_repeat('-', $depth) . $link);
  }
}

solved the problem.
I think this line
    $link = '' . $label . '';

can be improved, but it will do for now.


Determining how much data is needed for statistical significance of a percentage difference between two points?

Question: Imagining the following situation where A/B are independent results:

A is a 51% result, given N datapoints
B is a 50% result, given M datapoints

how many data points (ie N and M) do you need to have confidence that the difference between A/B is statistically significant?
Comment: Are you after an analytic solution? If not, I recommend browsing the site (and the internet) for power calculations for the two sample test. Like here: http://powerandsamplesize.com/Calculators/Compare-2-Proportions/2-Sample-Equality
Answer: There are various sample size calculators you can use online and in various software for a two-sample proportions test.
Here's the calculation using Stata that suggests that you would need N=M=39,240 for a two-sided alternative test at conventional levels:
<code>. power twoproportions .50 .51

Performing iteration ...

Estimated sample sizes for a two-sample proportions test
Pearson's chi-squared test
Ho: p2 = p1  versus  Ha: p2 != p1

Study parameters:

        alpha =    0.0500
        power =    0.8000
        delta =    0.0100  (difference)
           p1 =    0.5000
           p2 =    0.5100

Estimated sample sizes:

            N =    78,480
  N per group =    39,240
</code>
Comment: @enderland Did this clarify things?


PostgreSQL 8 - Substituir a primeira ocorrência de um caracter numa string

Question: Tenho um campo numa tabela num banco de dados PostgreSQL 8 cujos valores são strings e possuem hifens em algumas posições irregulares.
Gostaria de substituir a primeira ocorrência do hífen na string por um espaço em branco, mas não consegui achar nada apropriado na documentação.
As funções que eu achei como REPLACE() substituem todas as ocorrências e não apenas a primeira como eu desejaria.
Atualmente eu estou exportanto os resultados .CSV e abrindo no MS Excel. Com a função =SUBSTITUIR(A1;"-";" ";1), eu consigo fazer isso. Mas eu busco ser mais eficiente e perco tempo fazendo isso.
Agradeço a ajuda da comunidade antecipadamente.
Answer: Diretamente no SQL para POSTGRESQL 8.1+
Use a função REGEXP_REPLACE
Exemplo para o seu caso
SELECT REGEXP_REPLACE('ALGUMA COISA - OUTRA COISA', '^([^-]*)-(.*?)', E'\\2|\\1', 'g');
-- Retorna  OUTRA COISA|ALGUMA COISA
SELECT REGEXP_REPLACE('ALGUMA COISA - OUTRA COISA - MAIS OUTRA COISA', '^([^-]*)-(.*?)', E'\\1 \\2', 'g');
-- Retorna

Para versões anteriores é possível usar overlay ou substring conforme a resposta aceita.
Comment: Obrigado pela sua resposta. Essa opção não está executando na versão 8 do PostgreSQL. A versão do @Rovann Linhalis resolveu meu problema. Muito obrigado mesmo!
Comment: Esta função esta disponível para PG a partir de 8.1.
Answer: Você pode usar a função Position para encontrar a primeira ocorrência do hífen na sua string. Depois disso, pode substituir pelo espaço, usando a função Overlay:
select overlay('Palavra-Teste-X' placing ' ' from position('-' in 'Palavra-Teste-X') for 1)

Resultado: Palavra Teste-X

Coloquei no SQLFiddle
Documentação: String Functions and Operators
Comment: Obrigado, Rovann! Sua solução resolveu meu problema. Infelizmente eu não consigo votar na resposta ainda, mas assim que puder vou dar um +1 pra ela.
Comment: Blz @Eduardo, disponha =]
Answer: A versão 8.0 deixou de ser suportada em Outubro/2010.
Atualize sua instalação para uma versão mais recente.
A versão atual é a 10.3 que receberá suporte até Outubro/2022.


OpenCV: Denoising image / video frame

Question: I want to denoise a video using OpenCV and C++. I found on the OpenCV doc site this:
fastNlMeansDenoising(contourImage,contourImage2);

Every time a new frame is loaded, my program should denoise the current frame (contourImage) and write it to contourImage2.
But if I run the code, it returns 0 and exits. What am I doing wrong or is there an alternative way to denoise an image? (It should be fast, because I am processing a video)
Comment: Show the code that you have tried.  It's impossible to diagnose where exactly it's going wrong without seeing what you've actually tried.
Answer: while you are using c++ you are not providing the full argument try this that way.
cv::fastNlMeansDenoisingColored(contourImage, contourImage2, 10, 10,7, 21);

// This is Original Function to be used.
cv::fastNlMeansDenoising(src[, dst[, h[, templateWindowSize[,     searchWindowSize]]]]) → dst

Parameters:
src – Input 8-bit 1-channel, 2-channel or 3-channel image.
dst – Output image with the same size and type as src .
templateWindowSize – Size in pixels of the template patch that is used to compute weights. Should be odd. Recommended value 7 pixels.
searchWindowSize – Size in pixels of the window that is used to compute weighted average for given pixel. Should be odd. Affect performance linearly: greater.
searchWindowsSize - greater denoising time. Recommended value 21 pixels.
h – Parameter regulating filter strength. Big h value perfectly removes noise but also removes image details, smaller h value preserves details but also preserves some noise

OpenCV: Denoising image / video frame


How to eliminate extra Drupal Logout Link

Question:
Hi, there, I am working with Organic Groups on an existing drupal 7 site. For some reason, there are three log out links. I checked with User Menu, which is not even enabled in this site. How can I find out why there are three log out links?
Any ideas?
Thanks!
Answer: Try using the Devel Themer (https://drupal.org/project/devel_themer). That works kinda like a firebug/backtrace for themeing, and it should point you to where those links are coming from. Keep in mind Themer is a bit buggy, and can cause some issues, so you might want to switch it off when your done, but it should help you diagnose your problem.


It is necessary that A such that B is sufficient.

Question: The task is to find an expression/value for A and B (in either mathematic or natural language) that causes the above statement to be true. I find this question very ambiguous as I do not understand the final few words, 'such that B is sufficient.' What is B supposed to be sufficient for?
I would normally assume that the question is asking what B could be to make it sufficient for A, but the previous question asks quite a similar thing and makes it clear that B is meant to be sufficient for A, so I can only assume that they would always include this information in the question if it were relevant.
Answer: It is necessary that there be a question posted on Math StackExchange such that giving the answer I'm writing right now is sufficient.
Comment: Thank you for your answer. I still do not understand how this satisfies the question (please note that this is an issue with my understanding rather than your answer). What is the relevance of B being 'sufficient,' and what is it sufficient to?
Comment: Honestly I also think "It is necessary that A such that B is sufficient" sounds strange... I'm not sure it's a well thought out exercise.
Comment: Ok - thanks for the help.
Comment: It's not really grammatical if A and B are supposed to be the same of thing. You can't say "It's necessary that 1+1=2 such that 2+2=4"... it doesn't parse into a sentence.


Facebook Like Box - monitoring clicks

Question: Is it possible to somehow monitor who "Likes" my Facebook page, by intercepting the clicks in the Facebook Like Box?
http://developers.facebook.com/docs/reference/plugins/like-box
I would like to find out if the user who comes to my site already likes it, and enable some additional functionality based on this (for example, less advertising).
Comment: Eugh, real benefits for "Likes". Facebook has enough of a problem with spam in exchange for fake benefits.
Answer: You can use the javascript sdk to subscribe to the event edge.create. See the documentation here for that: http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe
FB.Event.subscribe('edge.create', function(response) {
  // A user liked the item, read the response and handle
});

Note, this will only work if you are using the xfbml version of the Like box. It wont work on the iframe version.
Answer: I don't know how to fetch just all people that have pressed the like button for an object, but you can subscribe to the like-button-press event. You can then use the information about the current user, and save it to your own database.
The event that you are listening to is edge.create, and you do that with FB's own FB.Event.subscribe.
It could look something like this:
window.fbAsyncInit = function() {
    FB.init({
      appId  : 'xxxxxxxxxxxxxxxxxxxxxxxxx',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
    FB.Event.subscribe('edge.create', function(href, widget) {
        FB.api('/me', function(response) {
            alert(response.first_name + " " + response.last_name + ":" + response.id +" pressed " + href); // Replace this with an ajax call to your server
        });
    });
};

Answer: It's embedded in an iFrame, so from the way they suggest you implement it, no it isn't possible.
However if you take a look at the code:
http://www.facebook.com/plugins/likebox.php?href=http://www.facebook.com/platform&width=292&colorscheme=light&connections=10&stream=true&header=true&height=587
There may be a way if you fiddle with it to call another function on the like buttons click that calls an ajax function you determine if you host all the code on your site, although FB probably has put things in place to not make that possible, or if it is it may be against T&C so worth checking out.

Facebook Like Box - monitoring clicks


Bayesian Algorithm for sorting hotel reviews

Question: i'm trying to find a Formula or algorithm to sort the most useful rating for a set of hotel reviews.
The thing is that i have in a determined place three different hotels that has the following information:
Hotel A: 124 reviews, 8.6 avg rating.
Hotel B: 10 reviews, 8.8 avg rating.
Hotel C: 1000 reviews, 8 avg rating.
i tried the algorithm used here:What is a better way to sort by a 5 star rating?
WR = (v * R + m * C) / (v + m)
But i'm not being able to reflect that the "score" should be higher for Hotel C, because the quantity of reviews is the biggest.
If i can get that solved, I imagine that the sort should be close to: 1) Hotel C; 2) hotel A and 3) hotel B.
Thank you!
Diego.-
Answer: This seems a duplicate of this one. It seems that to have the proper order you have to assign a predefined number of downvotes equal to the greatest number of reviews an item has, instead of summing the total number of votes of all items and dividing by the number of items as I had thought before. In python:
<code>pretend_votes = [1000, 0, 0, 0, 0, 0, 0, 0, 0, 0]
rating = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def score(item_votes):
  votes = [iv+pv for (iv,pv) in zip(item_votes,pretend_votes)]
  return sum(v*u for (v,u) in zip(votes,rating))/float(sum(votes))
</code>


Webservice para aplicativo Android

Question: Preciso desenvolver um aplicativo na plataforma Android. Para tal, a aplicação deverá ser acessada através de um Webservice. A pergunta é: as tabelas do banco de dados do meu aplicativo, para cadastro de usuario, etc., podem ser feitas em MYSQL e hospedadas em um servidor e acessar esses dados pelo aplicativo? Como diferentes usuários podem manter as informações atualizadas? Dessa maneira, preciso utilizar também o SQLite?
Comment: Sim, sem nenhum problema. Pode ser usado somente um banco no lado do servidor, um banco do lado do cliente, ou os dois juntos.
Answer:
As tabelas do banco de dados do meu aplicativo, para cadastro de
  usuario, etc., podem ser feitas em MYSQL e hospedadas em um servidor e
  acessar esses dados pelo aplicativo?

Sim, podem sem feitas em MySQL. Na verdade a base de dados utilizada para armazenamento e acesso dos dados no lado servidor é indiferente; e a decisão de escolha entre uma "marca" e outra varia conforme a necessidade do projeto.

Dessa maneira, preciso utilizar também o SQLite?

Depende. Se você pensa em desenvolver algum mecanismo para guardar em cache os dados capturados a partir do servidor, o SQlite pode ser muito útil.

Como diferentes usuários podem manter as informações atualizadas?

Esta pergunta é pouco difícil de responder por ser um tanto ampla. Depende das tuas regras de negócio. Se o teu sistema fosse um sistema de voto, por exemplo, os usuários manteriam os dados atualizados conforme dessem seu voto. Daí poderia se obter em tempo real informações sobre quem estaria ganhando a votação.
Answer: A geração dos dados podem ser feitas pelo aplicativo e guardadas em um servidor MySql, PHP, APS, Java, tanto faz.
Você pode até guardar esses dados para não ter que ficar fazendo requisições ao servidor toda vez que precisar deles, mas como você precisa mantê-los atualizados, então faça um trabalho só :)

Webservice para aplicativo Android


Pick UIDocument automatically in UIDocumentBrowserVC

Question: I am using a uidocumentbrowservc and want to pick a UIDocument programmatically. In my case it is because i want to automatically load the last used UIDocument to save the user some time on launch, as my app seldom changes documents.
My naive approach is to store last used URL in UserDefaults. Then in the viewDidLoad() of my  uidocumentbrowservc I call presentDocument(at: URL). But it doesn't work. And when i call URL.checkResourceIsReachable() I get the error:

Error Domain=NSCocoaErrorDomain Code=257 "The file "myFile" couldn't
  be opened because you don't have permission to view it."

The file path is:
/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/MyApp/myFile.

As far as I understand, I don't have access to it because it is not in my sandbox (It could be anywhere the user saves it?).
Any suggestions? I am sure there exist better ways to do this.
Comment: please improve the formatting
Answer: You cannot just save the URL. You need to save the sandbox extension granted to you by UIDBVC as well. Saving a bookmark instead of the URL will do that. In addition, a bookmark will keep working if the user moves the file (e.g. renamed inside iCloud Drive on a different device). A plain URL will not.
Check out URL's bookmarkData(options:includingResourceValuesForKeys:relativeTo:) with options .withSecurityScope and URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error: (and then don't forget to call start/stopAccessing on the resulting URL)
Comment: Right, withSecurityScope is only available on macOS. I guess you actually don't need it for UIDBVC-originated items. The sandbox info seems to be persisted in a different way.
Comment: Thanks, it worked!  As a note I didn't find the .withSecurityScope option, maybe it only is available on macOS?. Also as far as I understand UIDocument takes care of start/stopAccessing.


Obtuse Angle using sine function

Question: An airplane flew 490 miles at a bearing of N65°E from airport A to airport B. The plane then flew at a bearing of S38°E to airport C. Find the distance from A to C if the bearing from airport A to airport C is S60°E.
Comment: You are trying to find the distance from A to C. Could you explain what the "obtuse" angle in the title has to do with the question?
Answer: Hint: Draw triangle $ABC$. Notice that:

$\angle A = 180^\circ - 65^\circ - 60^\circ = 55^\circ$
$\angle B = 65^\circ + 38^\circ = 103^\circ$
$\angle C = 180^\circ - 55^\circ - 103^\circ = 22^\circ$
$AB = 490$ miles

So to find $AC$, you can just apply Sine Law.

Obtuse Angle using sine function


Is the definition of symmetric distribution using cdf correct?

Question: Based on wikipedia (https://en.wikipedia.org/wiki/Symmetric_probability_distribution), a distribution is symmetric about $x_0$ if and only if it is a distribution whose pdf(or pmf) $f(\cdot)$ satisfies $f(x_0+x)=f(x_0-x)$ for any $x\in \mathbb{R}$.    Can we also define symmetry about $x_0$ using cdf?  That is, we say a distribution is symmetric about $x_0$ if and only if $F(x_0+x)=1-F(x_0-x)$ for any $x\in\mathbb{R}$. It seems that this definition is also okay, right?
Comment: The simplest counterexample is a Bernoulli$(1/2)$ distribution, which is symmetric about $x_0=1/2.$ For $x=1/2$ notice that $1= F(1/2+1/2) \ne 1 - F(1/2-1/2)=1/2.$ However, $\lim_{x\uparrow \frac{1}{2}}F\left(\frac{1}{2}-x\right)=\frac{1}{2}=\lim_{x\uparrow \frac{1}{2}}F\left(\frac{1}{2}+x\right).$
Comment: Take the derivative, $\dfrac{dF}{dx}$, and remember the chain rule.
Comment: When a distribution has a pmf, $F$ is not differentiable everywhere.  The definition you give in the question works only for continuous distributions and fails for all distributions with pmfs (the discrete ones).  A general definition is given at https://stats.stackexchange.com/questions/28992/what-is-the-definition-of-a-symmetric-distribution.  To express that definition in terms of the CDF requires a limiting operation.
Comment: @whuber Thanks! This is very clear! It makes sense that the cdf definition only works for the continuous case.
Comment: @Dave Thanks, Dave!
Comment: @whuber Thanks, Whuber! This is very helpful. Do you have a counterexample in mind that invalidates the discrete case? Thanks!
Answer: You can characterize symmetry in terms of the CDF -- but it's a little tricky.
Recall that a random variable $X$ has a symmetric distribution when there exists a number $a$ for which $X$ and $2a-X$ have the same distribution function.  Since this is the same thing as saying that $Y=X-a$ and $-Y=a-X$ have the same distribution, we lose no generality by analyzing the variable $Y.$  Let $F$ be its distribution function, which by definition is
$$F(y) = \Pr(Y\le y) = \Pr(X-a\le y) = \Pr(x \le a+y)$$
for all numbers $y.$  The symmetry of $Y$ implies
$$\begin{aligned}
F(y) &= \Pr(Y\le y)\\
& = \Pr(-Y\le y) \\
& = \Pr(Y \ge -y) \\
& = \Pr(Y \gt -y) + \Pr(Y=-y)\\
& = (1-\Pr(Y \le -y))+\Pr(Y=-y)\\
& = 1 - F(-y) + \Pr(Y=-y).
\end{aligned}$$
That extra term $\Pr(Y=-y)$ is a nuisance unless the distribution is continuous (which means that $\Pr(Y=-y)=0$ for all $y$).  Our challenge is to express the probabilities $\Pr(Y=-y)$ in terms of the distribution function $F.$
To accomplish this, equate the set $\{-y\}$ with the intersection of the countable family of intervals $(-y-1/n,-y],$ $n=1,2,3,\ldots,$ and exploit the axioms of probability to deduce
$$\Pr(Y=-y) = \lim_{n\to\infty}\Pr\left(-y-\frac{1}{n} \lt Y \le -y\right) =  F(-y) -\lim_{\epsilon\downarrow 0} F(-y-\epsilon).$$
Substituting this into the foregoing equation for $F(y)$ leads to the general characterization

$F$ is symmetric around $0$ if and only if $$F(y) = 1 - \lim_{\epsilon\downarrow 0}F(-y-\epsilon).$$

As an example, consider this graph of $F$ when $X$ has a Bernoulli$(1/2)$ distribution.  Here, the center of symmetry is $a=1/2,$ so $Y = X-1/2$ takes on the values $\pm 1/2$ each with probability $1/2.$

The definition of $F$ causes its values at each jump to be the upper limit, whereas changing $F$ to $1-F(-y)$ rotates its graph around its center at $(0,1/2),$ thereby switching the "up" and "down" directions and causing the graph to attain the lower values at each jump.  We fix that in the definition of $\tilde F$ by sneaking up to the jumps from the left side, as shown in the right hand panel.
We may summarize this English characterization, and re-introduce the center of symmetry $a$ for full generality, by stating

A distribution function $F$ is symmetric around a number $a$ if and only if it coincides with the function obtained from $F$ whose graph (a) uses the lower values at each jump and (b) is rotated around the central point $(a,1/2)$ by 180 degrees.
Comment: Thank you, whuber! This is very clear and helpful!


How can i create correct line breaks in a sns sms message?

Question: I'm using the AWS .NET-SDK for sending SMS messages with the AWS SNS service. So far, so good; but when I use line breaks, I see the ? char at this point before the line break begins in the SMS. After that character, the line break is added as expected. Is there any possibility to get a line break without this ? character?
I have also tried following:

StringBuilder.AppendLine,
"\\n",
"\\r\\n",
@"\n",
@"\r\n",
Environment.NewLine

And encoding the string into UTF-8.
Example which doesn't work:
// Create message string
var sb = new StringBuilder();
sb.AppendLine("Line1.");
sb.Append("Line2.\\n");
sb.AppendLine(Environment.NewLine);
sb.Append(@"Line4\n");

// Encode into UTF-8
var utf8 = UTF8Encoding.UTF8;
var stringBytes = Encoding.Default.GetBytes(sb.ToString());
var decodedString = utf8.GetString(stringBytes);
var message = decodedString;

// Create request
var publishRequest = new PublishRequest
{
    PhoneNumber = "+491234567890",
    Message = message,
    Subject = "subject",
    MessageAttributes = "Promotional"
};

// Send SMS
var response = await snsClient.PublishAsync("topic", message, "subject");

Comment: Remove *all* the UTF8 related code. .NET strings are UTF16 already.
Comment: That i have already attempt before i tried the UTF8 stuff. The encoding had made no diffenrence.
Comment: *Remove* any attempts at encoding to begin with. It *does* make a difference. Maybe not with `\n` and `\r` as they are part of US-ASCII, but it will definitely mangle any non-English character and many special characters like `£`, `¦` or `¤`.
Comment: I was able to send multiline messages without any kind of encoding. The question's code doesn't use `publishRequest` though while `MessageAttributes` is a dictionary, not a string
Comment: yes you are right, my mistake. I had paste the wrong publish-method. Sorry
Answer: Simply remove all attempts to encode the string. .NET strings are Unicode, specifically UTF16 already. PublishAsync expects a .NET string, not UTF8 bytes.
As for why this error occurs, it's because the code converts the string into bytes using the local machine's codepage and then tries to read those bytes as if they were UTF8, which they aren't - using UTF8 as a system codepage is a beta feature on Windows 10 which breaks a lot of applications.
The newline character for SMS is \n. Environment.NewLine returns \r\n unless you use .NET Core on Linux. StringBuilder.AppendLine uses Environment.NewLine so you can't use it.
You shouldn't need anything more than String.Join to combine multiple lines into a single message:
var message=String.Join("\n",lines);

If you need to use a StringBuilder, use AppendFormat to append a line with the \n character at the end, eg :
builder.AppendFormat("{0}\n",line);

Update
I was able to send an SMS containing newlines with this code:
var region = Amazon.RegionEndpoint.EUWest1;
var  snsClient = new AmazonSimpleNotificationServiceClient(region);

var sb = new StringBuilder()
                .Append("Line1.\n")
                .Append("Line2.\n")
                .Append("Line4\n");
var message = sb.ToString();

// Create request
var publishRequest = new PublishRequest
{
    PhoneNumber = phone,
    Message = message,
};

// Send SMS
var response = await snsClient.PublishAsync(publishRequest);

The message I received contained :
Line1.
Line2.
Line4.

I decided to get fancy and changed the last line to :
.Append("Line4ΑΒΓ£§¶\n");

I received this text without problems too


ASP.NET Model binder cannot bind collection of complex of object containing collections

Question: I sumbmit folliwing json via an ajax call to the mvc controller. JSON contains one property which is just and int. and another property which is an collection of objects and that objects themselves have collection of otherobjects and the properties of otherojbect are promitive types. the thing is that if I sumbit just the second property of that json (collection of complex objects) model binder does a very good job and binds it to model but when i submit that collection of objects alongside with the primitive int model binder just binds int property and the seccond property is just empty collection. I use ext-js ajax call. I tried submiting json with params property and with jsonData property nothing seems to work ? what is the best solution to this problem. any help would be appriciated.
public class ModelToBind
{
    public int IntParam { get; set; }
    public IEnumerable<CompexObject> ComplexObjectParam { get; set; }
}

public class CompexObject
{
    public int AnotherIntProp { get; set; }
    IEnumerable<AnotherComplexObject> AnotherComplexObject{ get; set; }
}

public class AnotherComplexObject
{
    // some primitive properties here
}

public JsonData DoSomething(ModelToBind model)
{
    model.IntParam; // this property is binded
    model.ComplexObjectParam; // this is binded as empty collection
}

Comment: Please post your code.
Comment: here is the core @Maess
Comment: Post your javascript and view please
Comment: Is there a big chance that it ia a javasvript problem ? Because I thing that everything is being posted quiet well its juat an model binder problem. I cannot post javascript. And why do you need view ? I@Maess
Comment: It's likely an issue with how you are posting the data, hence wanting to see the js or view code.
Comment: okay thanks. If I would be able I will post the json here @Maess
Answer: What are your action's parameters ?
Logically, if you want to bind {int - Object}, you should have a c# type with the same properties like
public class MyType{
     public int MyPrimitive{get;set;}
     public MyOtherType ComplexType{get;set;}
}

and this type as a parameter of your action.
Of course, other scenarios are possible, but we need more information about your action.
Comment: this is not the case. please see the edit, i have posted some code
Comment: you got a collection, it's not just a type, we need to see the client side. Logicially a collection can be posted like ComplexObjectParam [0].property=... COmplexObjectParam[1].property=


Some counterexamples

Question: I want to know examples of the following statements.
If $V=S\bigoplus T=S'\bigoplus T'$, then $S\approx S'$ does not imply $T\approx T'$.
If $S$ is a subspace of both of the vector spaces $V$ and $W$, then $V\approx W$ does not imply $\frac {V}{S}\approx \frac {W}{S}$.
Answer: Take $S$ be infinite dimensional and $T,T'$ finite dimensional vector spaces of different dimension.
Comment: For a direct sum to make sense, isn't the intersection of $S$ and $T$ should be $0$?
Answer: Hint If $V$ is a finite-dimensional vector space over $\Bbb K$, then $V \cong \Bbb K^n$ for some unique $n$, and if $S$ and $T$ are finite-dimensional vector spaces over $\Bbb K$, then $\dim (S \oplus T) = \dim S + \dim T$. So, if $V$ is finite-dimensional, $V = S \oplus T = S' \oplus T'$ and $S \cong S'$, we conclude that $T \cong T'$. In particular, any counterexample must have $V$ infinite-dimensional and hence at least one of $S$ and $T$ infinite-dimensional.
A similar hint applies to the question about quotients.
Comment: For the second one, we know that either both $V$ and $W$ are infinite dimensional or both are finite dimensional since $V\approx W$. Then in either case, actually four cases since $S$ can be either finite dimensional or infinite dimensional, why $V/S \not\approx W/S$?
Comment: In fact, if $V$ and $W$ are both finite-dimensional, then, $V / S$ and $W / S$ both have dimension $\dim V - \dim S$, so $\dim V$ must be infinite.

Some counterexamples


How to colour MatPlotLib graph with gradient colour

Question: I have a graph in python I've made with matplotlib with the following code:
def to_percent(y, position):
    s = str(250 * y)
    if matplotlib.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'

distance = df['Distance']
perctile = np.percentile(distance, 90) # claculates 90th percentile
bins = np.arange(0,perctile,2.5)  # creates list increasing by 2.5 to 90th percentile
plt.hist(distance, bins = bins, normed=True)
formatter = FuncFormatter(to_percent)  #changes y axis to percent
plt.gca().yaxis.set_major_formatter(formatter)
plt.axis([0, perctile, 0, 0.10])  #Defines the axis' by the 90th percentile and 10%Relative frequency
plt.xlabel('Length of Trip (Km)')
plt.title('Relative Frequency of Trip Distances')
plt.grid(True)
plt.show()

What I'd like to know is, is it possible to colour the bars with gradient instead of block colour, like in this picture from excel.

I've not been able to find any information on this.
Comment: Instead of calling `hist` you could use `numpy.histogram` and plot with `bar`.   Then [example from the documentation](http://matplotlib.org/examples/pylab_examples/gradient_bar.html) would apply.
Comment: Possible duplicate of [How to fill matplotlib bars with a gradient?](http://stackoverflow.com/questions/38830250/how-to-fill-matplotlib-bars-with-a-gradient)
Answer: Take a look at the gradient_bar.py example from the matplotlib documentation.
The basic idea is that you don't use the hist() method from pyplot, but build the barchart yourself by using imshow()  instead. The first argument to imshow() contains the color map which will be displayed inside of the box specified by the extent argmument.
Here's a simplified version of the example cited above that should get you on the track. It uses the values from your Excel example, and a color map that uses the CSS colors 'dodgerblue' and 'royalblue' for a linear gradient.
from matplotlib import pyplot as plt
from matplotlib import colors as mcolors

values = [22, 15, 14, 10, 7, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1, 7]

# set up xlim and ylim for the plot axes:
ax = plt.gca()
ax.set_xlim(0, len(values))
ax.set_ylim(0, max(values))

# Define start and end color as RGB values. The names are standard CSS color
# codes.
start_color = mcolors.hex2color(mcolors.cnames["dodgerblue"])
end_color = mcolors.hex2color(mcolors.cnames["royalblue"])

# color map:
img = [[start_color], [end_color]]

for x, y in enumerate(values):
    # draw an 'image' using the color map at the
    # given coordinates
    ax.imshow(img, extent=(x, x + 1, 0, y))

plt.show()


I need drop down menu to close after # selection in mobile

Question: In our mobile site we are using a hamburger drop-down menu to navigate to different sections on the mobile home page.  Our problem is that the menu does not automatically close afterwards.  The user has to click off afterwards to make the drop down hide.
HTML

About

Academics

Cost

Orientation

Student Life

                        <asp:ContentPlaceHolder ID="ContentPlaceHolder11" runat="server"></asp:ContentPlaceHolder>

javascript
        $('#menuSlideIn').css("bottom", function () { return (-1 * $('#menuSlideIn').height()); });
        $("#menuSlideIn").toggle("slide");
        $('#menuHamburger').click(function () {
            $("#menuSlideIn").toggle("slide");
        });

css
#menuHamburger{
    float:left;
    padding: 8px 5px;
}
#searchImg {
    float:right;
    padding: 8px 5px;
}
.menuText{
    float:left;
    font-size:24px;
    color: #ffce00;
}
#menuSlideIn{
    height: auto;
    width: auto;
    background: #000;
    position:absolute;
    z-index: 100000;
}
#menuSlideIn li{
    padding: 5px 10px;
}
#menuSlideIn li a{
    color: #fff;
}

Answer: You could add an event handler to the links in #menuSlideIn that closes the hamburger menu.
$('#menuSlideIn li a').click( function() {
    $("#menuSlideIn").toggle("slide");
});

Comment: This worked.  How do I select a comment as the answer?
Comment: Just click on the "checked" grey icon right under the number of upvote for this post (you may have to wait a few minutes before checking it as a valid answer)
Answer: i had the same issue , i close it down manually when it click on any of the navigation item (although i check that this should only happen when user is using mobile browser)


hook_menu_alter() with node URL alias

Question: I have a node with ID equal to 60, which has a URL alias that is "mynodes/about-us." I would like to change the access callback of that node to myfunction().
It doesn't work when I use the URL alias:
function celsis_forms_menu_alter(&$items) {
    $items['mynodes/about-us']['access callback'] = myfunction;
}

function myfunction() {
     return FALSE;
}

But it works when I use the node number:
$items['node/60']['access callback'] = myfunction;

How can I get the url alias to work and would it be possible to change the access callback for all nodes with alias starting with mynodes/*?
Answer: You cannot do that because when Drupal invokes hook_menu() and hook_menu_alter() the value contained in $_GET['q'], which is used to find the menu callback to use, has been already changed from the path alias to the normal path.
drupal_path_initialize(), which is called by drupal_bootstrap() contains the following code:
  if (!empty($_GET['q'])) {
    $_GET['q'] = drupal_get_normal_path($_GET['q']);
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }

What you are trying to achieve can be accomplished in another way: implementing hook_node_access(). Differently from the equivalent hook in Drupal 6, it can be implemented also from modules that don't define a new content type.
function mymodule_node_access($node, $op, $account) {
  if ($op == 'view') {
    $path_alias = request_path();
    // ...
  }
}

$account contains the user object to which is being given access to the node. If the hook returns NODE_ACCESS_ALLOW, then the user has access to the node for the operation passed in $op; if the hook returns NODE_ACCESS_DENY, the user doesn't have access to the node; when it returns NODE_ACCESS_IGNORE, it leaves to other modules the decision.
request_path() returns the path alias if one was used. This means that if the user is using a URL like example.com/node/60, it returns "node/60"; if the user is using
example.com/mynodes/about-us, which is an alias for example.com/node/60, it returns "mynodes/about-us." In the case the user is using example.com/index.php, the function returns an empty string.
Answer: How about this? It's a bit of a simpler alternative. I'm guessing that you want the access callback to continue functioning even if you later create a new node and give it this same alias:
    function celsis_forms_menu_alter(&$items) {
      // Retrieve the Drupal system path for the page's alias
      $about_us_path = drupal_get_normal_path('mynodes/about-us');
      $items[$about_us_path]['access callback'] = 'myfunction';
    }

    function myfunction() {
      return FALSE;
    }

Note that if you do point this alias at a different node, you will need to clear the cache for this logic to keep working. hook_menu_alter is called when the menu is rebuilt.
Comment: kiamlaluno is right -- you need to `if (!isset($items[$about_us_path])) $items[$about_us_path] = $items['node/%'];` just before the `'myfunction'`.
Comment: Drupal doesn't define a menu callback for "node/60"; using that hook implementation, you are probably going to get a partial menu callback definition.
Comment: The OP said node/60 worked, so I was running with that assumption. If it doesn't, my code would need to be adapted. The underlying logic is what I wanted to convey. Thanks for enhancing and correcting it!

hook_menu_alter() with node URL alias


Finding chords that match with single notes

Question: I just heard Lenka's "Everything at Once".
The Background chord progression is quite catchy. I tried to figure out its chords, but to no avail.
I tried singular notes: I found F A C A and also C E G. E (where G is down an octave).
How do I find Chords that match up with single notes?
And what are they called?
Comment: Strangely enough, I don't find this to be a dupe of that other question. Rather, I think the titles actually need to be switched -- that question is about finding chords that actually sound like a single note (i.e. Power Chords) whereas this song's chords are quite clearly not power chords.
Comment: possible duplicate of [Finding the chord for a single note](http://music.stackexchange.com/questions/6512/finding-the-chord-for-a-single-note)
Comment: Much more similar to [Is it possible to find the correct chords from melody notes alone?](http://music.stackexchange.com/q/5348/133), though still not quite.
Comment: The chords used in the song are Dm, C, A, and Bb (in order of how often they occur). You'll have to figure out where/when each is used yourself as a homework assignment. :-)
Answer: As I listen to the song, I don't really hear any tonality change. In such cases, the circle of Fifths is you forever ally.
Around a tonality, there are five chord positions that instinctively sound good. You guess them with that circle.
With the notes like c,g,e,a,f... you're probably in C Major or A minor(both are instrincally linked), so you can go easily to G major, E minor, F major, D minor.
Answer: Without actually listening to the song, there are a few facts you might not be aware of, misconceptions about which could easily lead to the qustion you ask.
The whole point of a chord is the several note blend together and become unified, united. The notes sound as one. On an equal-tempered instrument (piano, guitar, etc) most of the intervals are actually just a little bit out-of-tune with each other. This results in the individual notes becoming more distinct: it's easier to identify the separate notes that compose the chord.
With other tuning systems (Just tuning, Helmholtz tunings) the blending effect can be intensified so many notes unite into a sonic pattern from which the separate notes are very difficult to pick out. With the explosion of computers and digital synthesizers, this territory has been opened-up for colonization.
Often the strongest note you hear (the "melody" of the chords) will be a third or a fifth rather than the root due the effects of "voice leading" or counterpoint.
When you're trying to figure out the chords to a song, 99% of the time you should try to listen for the "bass-line" and ignore everything else. The bass may not play the roots of all the chords; but 99% of the time it will play the root every time the tonic (the Key chord) comes around.


Nginx only recognises files in root dir (Permission denied on symlink'ed dir/files)

Question: UPDATE -- This is driving me nuts (or back to Apache...)
The issue is definitely symlinks and permissions
When I setup symlinks to directories in the same tree, for example /var/www/html/html2 --> /var/www/html2 it works fine. Also /var/www/html/test_alias --> /var/www/html/test works fine. It's just when pointing out a different volume that I get 403. I have sprinkled all those directories with read and exec rights and nginx ownerships, but nothing works. I have also tried adding
sendfile off;
  autoindex on;
  disable_symlinks off;
but to no avail! There must be something fundamental I am missing??

OK so I'm a beginner with Nginx, however I have successfully setup a number of Apache websites, so this can't be that difficult right?
Well, not really. At least not for me. I have struggled for a couple of days while setting up a server that can interpret PHP code. Nothing fancy at all.
I have FINALLY a version of nginx.conf that somewhat works. It loads php and html in that order, and defaults to index.php and index.html.
My root is /var/www/html, owned by user nginx. Files in "html" loads OK, but when I symlinked a directory under "html", they won't load. Can anyone give me a hint about whats wrong?
This is my conf:
events {
  worker_connections  1024;
}

http {
  index index.php index.html;
  server {
    listen 80 default_server;
    server_name _; # This is just an invalid value which will never trigger on a real hostname.
    server_name_in_redirect off;
    root  /var/www/html;

    location ~ \.php$ {
      root           /var/www/html;
      try_files $uri $uri/ =404;
      fastcgi_pass   127.0.0.1:9000;
      fastcgi_index  index.php;
      fastcgi_split_path_info ^(.+\.php)(.*)$;
      fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
      include        fastcgi_params;
    }
  }
}

Directory structure is:
/var/www/html

these files load OK
/var/www/html/mysite

these files are not found/loaded
It would be great if someone could give me a solution to this problem. And if you also know a good reference with simple config examples I'd love to hear about them. God knows there exist plenty with incorrect/outdated/plain confusing config examples.
Comment: Check your error log.
Comment: Could be a permissions problem, they're pretty common. Copy the files from the symlink to the actual folder, as a test, setting permissions properly.
Comment: yes I forgot to mention that part. The error logs says 13: Permission denied. But the symlink and everything it points to is owned by nginx:nginx. But your comment triggered my tired brain, so I created a test subdir, with one php file in it, and that loaded OK. That means that the problems comes from the fact that I'm using a symlink??
Comment: What does the nginx documentation say on symlinks? Permissions can be tricky to work out sometimes.
Comment: You don't mention your OS, but I had similar issues with CentOS and SElinux. So your error log aside, also check your SElinux audit log.
Comment: Actually CentOS 7 is the OS running in a VM. Sysadmins choice I'm afraid. I will look into the log, if I can find it. Is it /var/log/audit/audit.log ?
Answer: Have you made sure that your php-fpm process can access the PHP files from the place where you have made the symlinks? You should be able to test this with a simple PHP script at your /var/www/html directory which tries to open a file from your other volume.
Personally I would change the root directory to point directly to the actual place where the website root is, and not use symlinks for that purpose. And then use alias directives in location blocks to change the filesystem location for the URIs which are in different places.


Issues with Python / Tinker Please: TypeError: unsupported operand type(s)

Question: I am trying to build a volume per foot calculator using Python and Tkinter. I keep getting this error message. I know it is probably something simple I am overlooking. Can anyone see where I am going wrong? Thanks in advance.
This is my code:
from tkinter import *

root = Tk()
root.title("Volume Calculator")

def volume_per_foot():
    gallons_per_foot = inside_diameter * inside_diameter / 1029.4
    return (gallons_per_foot)

frame = LabelFrame(root, text="BHA", padx=5, pady=5)
frame.grid(padx=10, pady=10)

component_label = Label(frame, text="Component")
component_label.grid(row=0)
component = Entry(frame)
component.grid(row=1)

component_length = Label(frame, text="Length")
component_length.grid(row=2)
length = Entry(frame)
length.grid(row=3)

component_outside_diameter = Label(frame, text="Outside Diameter")
component_outside_diameter.grid(row=4)
outside_diameter = Entry(frame)
outside_diameter.grid(row=5)

component_inside_diameter = Label(frame, text="Inside Diameter")
component_inside_diameter.grid(row=6)
inside_diameter = Entry(frame)
inside_diameter.grid(row=7)

submit = Button(frame, text="Enter", command=volume_per_foot)
submit.grid(row=8)

gal_per_foot = Label(frame, text="Gallons Per Foot")
gal_per_foot.grid(row=9)
component_volume = Label(frame)
component_volume.grid(row=10)

root.mainloop()

And this is the error message:
Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "volume.py", line 34, in volume_per_foot
    gallons_per_foot = inside_diameter * inside_diameter / 1029.4
TypeError: unsupported operand type(s) for *: 'Entry' and 'Entry'

Answer: You have to get the value from the Tk object Entry and convert it to a number like:
gallons_per_foot = float(inside_diameter.get()) * float(inside_diameter.get()) / 1029.4

Update
You can't get a return value from the button callback. To display the result in a label you could do the following: introduce a StringVar, bind it to the label, pass it to the button callback (I am using a closure and a lambda function here) and change its value there after the computation:
def volume_per_foot(result_text):
    gallons_per_foot = float(inside_diameter.get()) * float(inside_diameter.get()) / 1029.4
    result_text.set(str(gallons_per_foot))

result_text = StringVar()
result_text.set("Gallons Per Foot")

submit = Button(frame, text="Enter", command=lambda *args:volume_per_foot(result_text))
submit.grid(row=8)

gal_per_foot = Label(frame, textvariable=result_text)
gal_per_foot.grid(row=9)

Comment: Thank you for this thorough explanation. It makes sense to me now, and this solved my problem.
Comment: @LoudEye Glad it helped! Please consider [accepting my answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) if it was useful.
Comment: Absolutely. Just another quick one. Do you know how to hide a frame until a button is clicked? I am trying to add components to this volume calculator and I can make them all visible, but sometimes a user will not need a specific component. I have searched the command option in the Tkinter docs, and can't find that command.
Comment: I have done it before with 'if' statements, but not using Tkinter.
Comment: def frame():
    Frame(root, text="BHA", padx=5, pady=5)                                                                                framebutton = Button(frame, text="Add Component", command=frame)
framebutton.grid(row=11)
Comment: @LoudEye Thank you! [This site](https://www.delftstack.com/howto/python-tkinter/how-to-hide-recover-and-delete-tkinter-widgets/) shows how labels can be shown and hidden via buttons. The same should work for a frame or other types of widgets. For checking if a value is visible you can use `pack_info`, `grid_info` and `place_info`. These methods throw an exception if the widget has not been packed or placed.
Comment: Thank you so much for this. You have been extremely helpful.


definition of rectangle

Question: I am wondering whether it is fine to define a rectangle with right angles like Wikipedia's page of rectangle.

In Euclidean plane geometry, a rectangle is any quadrilateral with four right angles. It can also be defined as an equiangular quadrilateral.

Because that the sum of the angles of a quadrilateral is 360 degrees is a theorem, it is little ambiguous for me to define a rectangle with a theorem and some calculation (360/4=90).
And if that's is the case, is it fine to say a regular polygon (except equilaterial triangle) is a polygon which has equal sides and equal inner angles?
Comment: Why would the equilateral triangle be excluded?
Answer: The definition is correct.
It is normal to define objects after a theorem, even if at first it seems counterintuitive. In advanced mathematics it happens all the time that a result (like a theorem) permits you to write a definition that otherwise wouldn't make sense.
There is no ambiguity because:

Quadrilaterals are defined before rectangles;
You can prove that for any quadrilateral, the sum of internal angles is $360°$;
Therefore, there exist only one type of equiangular quadrilateral: the one with four right angles. No other one!

You can call this unique case "rectangle", with no ambiguity.
(The only ambiguity, strictly speaking, is that there are many rectangles, of different sizes and ratios. But that is not a problem.)
The definition you gave for regular polygons is also correct.
Answer: well, you know that right angles exists (it's an axiom). So I think it make sense to state that if a figure having four right angles exists, then you call it rectangle. You just have to show that such a figure exists :-)

definition of rectangle


How to customize default add content page

Question: I want to customize the default add content page, more specifically, to get rid vertical tab in the bottom, and add explanation text to each field.
How can i do this?
what php file should i tinker ?
is there already some modules to to this ?
thank you for reading this.
Answer: You can use the Renderable Elements module. If you've ever had any experience with Display Suite, it works exactly like that, but for forms like Add Content. You can change up the display, remove the vertical tabs below, etc.
For the explanation, each field comes with a description/help field that you can fill out. Now it depends on the admin theme you're using on how that text is displayed.
Comment: display suite is the best option for begginers
Comment: @KyleTaylored : Thank you for the info. Now I can get rid of the vertical tabs,add explanation text,and change the display by setting admin theme. However,after I eliminated the additional settings in the vertical tab,the created content is not automatically published (which is a side effect i like, because i want my site's user to post anything they want, but only I who have the authority to publish )


How to exclude nodes from a view if they appear on another view?

Question: I have two views called 'slider' and 'latest news'.
The slider view lists 5 nodes with content type news, article and blog post and if a custom field is selected on this nodes.
The latest news list the 5 latest nodes with content type news.

What I want to do is to exclude nodes from latest news view if they appear on the slider view.
If the slider view has only the news content type, it would be easy to exclude nodes by using the offset feature but because the slider view could have nodes from all these three content types and it's uncertain how many nodes come from each content type I couldn't solve my problem.
How to exclude nodes from latest news view if they appear on the slider view?
Answer: Try the Views Excluded Previous module:

The Views exclude previous module provides a views filter that excludes nodes that have already been loaded/displayed on the current page.
This is very useful when you have pages with several embedded views, and you want to make sure that a given node only appears once in the page.
Comment: Sorry, forgot to mention in my question: I have already seen this module but there isn't a stable version of this module so it scares me. Have you ever tried it? Thanks.
Comment: I know of sites that use it in Production. Works great.
Answer: Step 1) Add a new boolean type field to your Article content type.

Step 2) Type Yes for on value, No for off value

Step 3) Checkmark ☑ Use field label instead of "On Value" as label

Step 4) Go to your Events and Blogpost content types and add the boolean field using existing fields.

Step 5) Edit the 5 nodes you want to see on the slider and ☑ checkmark show on slider.

Step 6) Go to your Slider View and add a filter of Show on slider, and select Yes.

Step 7) Go to your Latest News View and a filter of Show on slider, and select No.

Once you have all of this setup. You will need to print your views programmatically on the front page template using this technique: Multiple Views on a page - How to exclude already shown nodes?
Comment: @herci, understood. Seeing this Q again reminded of a nifty little trick. I will add a new answer soon, when I finish my project.
Comment: Thanks for your answer. But it doesn't work for the case, unfortunately. Because I want to exclude nodes from the latest news view if only this nodes currently appear on the slider view. But if I exclude the nodes by using the custom field the latest news view disappear completely because almost on all the news content type the custom field is selected. What I want to do is to display the node in slider at first then when the time is up (5 more nodes come into the slider), display this node inside the latest news view.
Comment: @herci updated my answer with pictures, hopefully it's clear to you now `:)`
Comment: Thanks for the detailed answer but I think there is a misunderstanding here `:)`. Because, in your answer the latest news view will not display the contents `show on slider` enabled. But, the Latest News views shouldn't care if "show on slider" is enabled or not, the only thing it should consider is if the content appears on the slider views **right now**. If so, don't show it on the Latest News views. For example there are 5 content on the slider and I added a new one. Then the oldest (6th) one will disappear from slider but not show on Latest News because "show on slider" is still enabled.
Comment: @herci, I found it, the trick is here [Multiple Views on a page - How to exclude already shown nodes?](http://drupal.stackexchange.com/questions/52529/multiple-views-on-a-page-how-to-exclude-already-shown-nodes#52537)