Unable to pass a NSString from One VC to Next VC

Question: I have two VCs and i want to pass resourceName from HomeViewController to SingleWebViewController. But the resourceName is getting null.
HomeViewController.m
#import "HomeViewController.h"
#import "SingleWebViewController.h"

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    singleWebViewController = segue.destinationViewController;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    selectedRow = indexPath.row;

    switch (selectedRow)
    {

        case 0:
        {
            singleWebViewController.resourceName=@"intro";
            NSLog(@"HtmlFileName:%@" , singleWebViewController.resourceName);
            [self performSegueWithIdentifier:@"toSingleWebView" sender:self];
            break;
        }
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
     }

SingleWebViewController.h has the following line
@property (nonatomic,strong)NSString *resourceName;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

        NSString *htmlFile = [[NSBundle mainBundle] pathForResource:self.resourceName ofType:@"html" inDirectory:nil] ;
        NSLog(@"%@se:" , self.resourceName);

        NSURL *url = [NSURL fileURLWithPath:htmlFile    ];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:request];
        _webView.delegate=(id)self;

}

i did notice that didSelectRowAtIndexPath is getting called before prepareForSegue. what's the cause for this. Please suggest.
Comment: You'll want to set the `resouceName` property in `prepareForSegue`.
Comment: Where do you `alloc init` your `singleWebViewController` in HomeViewController?
Answer: In prepareForSegue, you're assigning something new to singleWebViewController.  If this controller is different from the controller that's already assigned in tableView: didSelectRowAtIndexPath:, which I assume it is, then your property will be reset.
Instead, do this:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    singleWebViewController = segue.destinationViewController;
    singleWebViewController.resourceName = @"intro";
}

Comment: have a look in above edit.. the above solution will not be applicable if switch.case .increase..
Comment: @Lalit_vicky Correct, you'll need to save the resource you want in an instance variable.
Answer: In your prepareForSegue you can set the property resourceName
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    SingleWebViewController *singleWebViewController = segue.destinationViewController;
    [singleWebViewController setResourceName:@"Resource name"];
}

Comment: @Lalit_vicky I think that you should set the property in your ``prepareForSegue`` method instead of in ``didSelectRowAtIndexPath``. You can create a property in your view controller, set that property in ``didSelectRowAtIndexPath`` and assign it to the view controller property in ``prepareForSegue``.
Comment: This local variable will hide the instance variable.
Comment: It's not clear if ``resourceName`` is hidden or not, because the question says that ___SingleWebViewController.h has the following line___
Answer: You're setting resourceName after viewDidLoad has been called. Add a custom initialiser, initWithResourceName:(NSString *)resourceName, and set it there. Or move the code from viewDidLoad to viewDidAppear:.
Answer: try this..pass value in prepareforsegue
Edit:  if you want for different case to pass the different value then do this..i m assuming you want to segueway to same ViewController ie SingleWebViewController here.
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
        {
            if ([segue.identifier isEqualToString:@"toSingleWebView"]) {
            SingleWebViewController  *singleWebViewController = segue.destinationViewController;
            NSIndexPath *indexPath = [self.tableView indexPathOfSelectedRow];
            if(indexpath.row == 0){
            singleWebViewController.resourceName=@"intro";
            }
            else if(indexPath.row == 1){
               singleWebViewController.resourceName=@"some other value";
            }
            else{
               singleWebViewController.resourceName=@"something else";
            }
            NSLog(@"HtmlFileName:%@" , singleWebViewController.resourceName);
          }
        }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        selectedRow = indexPath.row;

        switch (selectedRow)
        {

            case 0:
            {

                [self performSegueWithIdentifier:@"toSingleWebView" sender:self];
                break;
            }
            case 1:
            {
                [self performSegueWithIdentifier:@"toSingleWebView" sender:self];
                break;
             }
          [tableView deselectRowAtIndexPath:indexPath animated:YES];
     }

Comment: just to add little more.. i will have to add some more switch..cases..upto..0-4..in that case it wouldn't be possible to pass the resource name in prepareforsegue..
Comment: it's possible even if you use multiple cases..if you want in case 1 the value should be set different then...get the indexpath of selected row in prepareforsegue and send different value.
Comment: the case are actually indexPath.row..will that be accessible in prepareforsegue..?
Answer: Try with:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    HomeViewController *obj = segue.destinationViewController;
    if([segue.identifier isEqualToString:@"toSingleWebView"]){
        obj.singleWebViewController = singleWebViewController;
    }
}


Exercise 3.18 of Fulton's Algebraic curves.

Question: I'm trying to provide a proof of the following fact: If $p$ is a simple point on the curve $F$ then $I(p,F\cap G)=ord_p^F(G)$. Where $I(p,F\cap G)$ denotes the intersection number of the curves at $p$, and $ord_p^F$ is the order function in the discrete valuation ring $\mathcal O_p(F)$. The goal is use only the seven properties of the intersection numbers that him describes in the book.
I have tried with the special case when $p$ is a simple point on $G$ and $F$, $G$ don't share any tangent at $p$; in which case the intersection number is one. But I don't know how to calculate $ord_p^F(G)$ in this simple case,  I even reduce the problem to $G$ irreducible but with no success. In fact I'm having problems with calculations of this kind, when the function $ord$ is involved; I would be very grateful with an answer that helps me in this aspect. Thank you.
Answer: Fulton's axioms for the intersection number are this.
By $(3)$ we may assume $P=(0,0)$, and the tangent of $F$ at $P$ is $Y$. Then we can consider $\overline X$ as a uniformizing parameter of $\mathcal O_P(F)$. Let $n=Ord^{F}_P(G)$, then in $\mathcal O_P(F)$ there exists some unit $u$ such that $\overline G=u\overline X^n$, say $u=\overline A/\overline B$, for some $A,B\in k[X,Y]$, then $A(P)\neq 0\neq B(P)$ as $u$ is a unit. Then $GB=X^nA+CF$ for some $C\in k[X,Y]$.
We have $I(P,F\cap BG)=I(P,F\cap B)+I(P,F\cap G)$ by $(6)$, but $P\notin B$, thus by $(2)$, $I(P,F\cap B)=0$, and thus $I(P,F\cap BG)=I(P,F\cap G)$.
But $$I(P, F\cap GB)=I(P,F\cap (X^nA+CF))=I(P,F\cap X^nA),$$
by $(7)$, however as $A(P)\neq 0$, we prove $I(P,F\cap X^nA)=I(P,F\cap X^n)$ the same way we showed $I(P,F\cap BG)=I(P,F\cap G)$ above, so that $I(P,F\cap G)=I(P,F\cap X^n)$, but by $(6)$ $I(P,F\cap X^n)=nI(P,F\cap X)$, and by $(5)$, $I(P,F\cap X)=1$, thus $I(P,F\cap G)=n$, i.e., $I(P,F\cap G)=Ord_P^F(G)$.


Show that $\sum_{j=1}^{n-1} M_j(M_{j+1} - M_j) = \frac{1}{2}\left( \sum_{j=1}^n X_j \right)^2 - \frac{n}{2}$

Question: The following question is taken from Steven Shreve Stochastic Calculus for Finance Volume 1, question $2.5$

Toss a coin repeatedly. Assume the probability of head on each toss is $\frac{1}{2},$ as is the probability of tail. Let $X_j = 1$ if the $j$th toss results in a head and $X_j = -1$ if the $j$th toss results in a tail. Consider the stochastic process $M_0,M_1,...$ defined by $M_0 = 0$ and
  $$M_n = \sum_{j=1}^n X_j, \quad n\geq 1.$$
  Define $I_0 = 0$ and
  $$I_n = \sum_{j=1}^{n-1} M_j(M_{j+1}  - M_j),\quad n=1,2,...$$
  Show that
  $$I_n = \frac{1}{2}M_n^2 - \frac{n}{2}.$$

My attempt:
$$\begin{align*}
\frac{1}{2}M_n^2 - \frac{n}{2} & = \frac{1}{2} \left( \sum_{j=1}^n X_j^2 + 2\sum_{i\neq j}X_i\cdot X_j \right) - \frac{n}{2} \\
& = \frac{1}{2} \left( n + 2\sum_{i\neq j}X_i\cdot X_j  \right) - \frac{n}{2} \\
& = I_n.
\end{align*}$$
Is there an easier / shorter approach to solve this question?
Comment: Note that $I_n$ is the martingale transform of $M_n$ with itself and the result must therefore be a martingale. Considering the quadratic terms the $M_n^2-n$ result seems most plausible (although there is the factor of $\frac12$ to be concerned about...)
Answer: Note that since $X_j^2 = 1$ and $M_1^2 = X_1^2 = 1$,
$$I_n = \sum_{j=1}^{n-1} \frac{1}{2}(M_j+M_{j+1})(M_{j+1}  - M_j) - \sum_{j=1}^{n-1} \frac{1}{2}X_{j+1}(M_{j+1}  - M_j) \\=  \frac{1}{2}\sum_{j=1}^{n-1}(M_{j+1}^2- M_j^2)- \frac{1}{2}\sum_{j=1}^{n-1}X_{j+1}^2 = \frac{1}{2} M_n^2 - \frac{1}{2} M_1^2 -\frac{n-1}{2} \\ = \frac{1}{2} M_n^2 - \frac{n}{2}$$


ffmpeg - Continuously stream webcam to single .jpg file (overwrite)

Question: I have installed ffmpeg and mjpeg-streamer. The latter reads a .jpg file from /tmp/stream and outputs it via http onto a website, so I can stream whatever is in that folder through a web browser.
I wrote a bash script that continuously captures a frame from the webcam and puts it in /tmp/stream:
while true
do
    ffmpeg -f video4linux2 -i /dev/v4l/by-id/usb-Microsoft_Microsoft_LifeCam_VX-5000-video-index0 -vframes 1 /tmp/stream/pic.jpg
done

This works great, but is very slow (~1 fps). In the hopes of speeding it up, I want to use a single ffmpeg command which continuously updates the .jpg at, let's say 10 fps. What I tried was the following:
ffmpeg -f video4linux2 -r 10 -i /dev/v4l/by-id/usb-Microsoft_Microsoft_LifeCam_VX-5000-video-index0 /tmp/stream/pic.jpg

However this - understandably - results in the error message:
[image2 @ 0x1f6c0c0] Could not get frame filename number 2 from pattern '/tmp/stream/pic.jpg'
av_interleaved_write_frame(): Input/output error

...because the output pattern is bad for a continuous stream of images.
Is it possible to stream to just one jpg with ffmpeg?
Thanks...
Comment: What exactly are you trying to achieve? Static image from your camera on a web page?
Comment: Yes, but one that is updated a few times a second, so effectively, a stream. This is just a first step - later on I am planning on writing a program that will read the image repeatedly and work with it.
Comment: Well, that's not how it's done. Couple of questions: 1) what is the format of input stream? 2) How are you going to display video stream to clients?
Comment: I believe the second question is already answered above: mjpeg-streamer is used to put up the website. It automatically reads from /tmp/stream in my setup, and uses any images there. It is a common setup on the raspberry pi, used together with the program "raspistill" for the raspberry camera. However, this latter program does not seem to work with my (non-raspberry) webcam, so I wanted to use ffmpeg instead.
Why does the input format matter? I read from the webcam, and that works fine, as stated in my question. All I want is ffmpeg to work continuously instead of calling it multiple times.
Comment: Well, it's totally up to you, but when I had to deal with MJPEG stream, I did it in a couple of other ways: 1) I used `ffmpeg` to convert it to FLV stream and fed it to `ffserver` 2) For high bandwidth camera (30mb/sec) I had to split MJPEG stream on JFIF signature to separate JPEG files and then assemble them to 1-minute fragments of MP4 files. The thing is, refreshing JPEG on a client side looks terrible and irritating, especially when it's large enough.
Comment: I noticed that mjpeg-streamer can do what I want natively, without using ffmpeg at all (the latter proved to be quite heavy on the raspberry pi). I now use: `./mjpg_streamer -i "input_uvc.so -r 1280×1024 -d /dev/video0 -y" -o "output_http.so -w ./www"` from within the mjpg's directory, which gives me clear output at large framerates...yay! Thanks for all the help.
Answer: You can use the -update option:
ffmpeg -y -f v4l2 -i /dev/video0 -update 1 -r 1 output.jpg

From the image2 file muxer documentation:

-update number

If number is nonzero, the filename will always be interpreted as just a
filename, not a pattern, and this file will be continuously overwritten
with new images.

Comment: Using v4l2 gives me the error "Unknow input format: 'v4l2' on my raspberry pi (which seems to be a known issue: [link](http://www.raspberrypi.org/phpBB3/viewtopic.php?t=49530&p=385793)). Using -f video4linux2 instead gives me: `"Unrecognized opetion 'update' Failed to set value '1' for option 'update'` (Similar issue when using avconv). Output of ffmpeg --version: `ffmpeg version 0.8.6-6:0.8.6-1+rpi1`
Comment: @Germanunkol Your ffmpeg is too old (and you're probably using a fork of FFmpeg which may not have `-update` in it's current code). This is why you need to include the complete ffmpeg console outputs with your commands.
Comment: `ffmpeg -version` gives: `ffmpeg version 0.8.6-6:0.8.6-0ubuntu0.12.10.1, Copyright (c) 2000-2013 the Libav developers
  built on Apr  2 2013 17:02:16 with gcc 4.7.2
ffmpeg 0.8.6-6:0.8.6-0ubuntu0.12.10.1
libavutil    51. 22. 1 / 51. 22. 1
libavcodec   53. 35. 0 / 53. 35. 0
libavformat  53. 21. 1 / 53. 21. 1
libavdevice  53.  2. 0 / 53.  2. 0
libavfilter   2. 15. 0 /  2. 15. 0
libswscale    2.  1. 0 /  2.  1. 0
libpostproc  52.  0. 0 / 52.  0. 0
`
Answer: It is possible to achieve what I wanted by using:
./mjpg_streamer -i "input_uvc.so -r 1280×1024 -d /dev/video0 -y" -o "output_http.so -p 8080 -w ./www"

...from within the mjpg_streamer's directory. It will do all the nasty work for you by displaying the stream in the browser when using the address:
http://{IP-OF-THE-SERVER}:8080/
It's also light-weight enough to run on a Raspberry Pi.
Here is a good tutorial for setting it up.
Thanks for the help!


DER para aluno, disciplina e curso

Question:
Um estudante só pode ter um curso.
Um curso tem várias disciplinas.
O aluno pode cursar várias disciplinas do curso.

A minha única dúvida é como ficaria isso no DER?

Ficaria realmente desse jeito?
Já que aluno só tem um curso, a table seria disciplinaAlunoCurso? Ou só disciplinaAluno?
Vai que o aluno mude de curso depois, então a melhor opção seria essa? Colocar as três chaves de cada tabela como estrangeira na tabela de ligação?
Comment: E se ele fizer 2 cursos? Se estiver resolvendo dependência? Acho mais interessante o aluno ter uma tabela de relacionamento com turmas de disciplinas. você cria as turmas, e adiciona uma entrada para aquele aluno naquela turma da disciplina.
Comment: Um exemplo pra ficar mais claro: Vamos supor que a disciplina "Neurologia II" tenha uma "turma noturna B do 1o semestre de 2015". Neste caso, o aluno está inscrito nesta turma especificamente, e não simplesmente em "Neurologia II". Semestre que vem, já vão ser outras turmas de Neurologia II, e se esse aluno ficar com dependência desta disciplina, vai ter que se inscrever nesta nova turma. O aluno se relaciona com a turma. A turma é que se relaciona com as disciplinas.
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Vou dar uma resposta para lhe dar uma orientação. Se não é isso que precisa, complicou, porque não dá para ficarmos debatendo aqui até chegar aonde você quer, deixaria de ser uma pergunta e uma resposta.
Você não especificou bem o problema. Claro, quando especificar o modelo fica praticamente pronto. Mas sem especificar fica difícil lhe ajudar. Terei que especular. Principalmente porque você disse que não quer algo mais complexo. Para fazer tudo correto algo mais complexo é necessário. Mas se você aceita que não esteja tudo "correto", qual é o limite aceitável? Só você sabe.
De fato, esse correto é bem entre aspas porque é difícil dizer que tem certo ou errado em modelagem. O correto do ponto de vista acadêmica nem sempre é muito prático. Muitas vezes para otimizar o banco de dados é necessário fazer o "errado".
Quando você quer soluções simples que apenas funcione, fazer tudo como mandam os livros pode ser um exagero.
Mas só você sabe o ponto de inflexão.
Vou dar algumas dicas do que eu faria olhando por cima e fazendo algumas especulações.
Considerações
O campo cursoID de aluno pode até ser usado, mas se quer fazer o certo deveria ter uma tabela que amarra o aluno ao curso. Pode ser exagero criar uma tabela só para isto, mas faz mais sentido (é o que eu falei que não dá para saber o limite). Um aluno não tem por característica um curso, curso é algo transitório, é algo externo e independente do aluno.
Para isto existe o relacionamento 1:1. Curiosamente as pessoas acham que se é 1:1 pode sempre ignorar a criação de uma tabela e juntar tudo. Mas se você achar que é exagero e cabe ficar na mesma tabela, posso concordar. Você é que decide. E quem pode falar que vai dar algum problema?
Eu imagino que o aluno pode ter zero ou um curso e não apenas um. Então é para se pensar. Claro que o null existe para casos como esse. Há muita controvérsia se deve ou não usar nulos para isto (eliminar um relacionamento).
Uma disciplina só existe para aquele curso? Parte da modelagem diz que sim, parte diz que não.
Não importa como vai relacionar, falta ligar a tabela disciplina com curso de alguma forma.
Se a disciplina só existe para aquele curso é uma relação 1:1, então você pode escolher se vai fazer uma tabela para fazer a amarração da disciplina ao curso ou vai usar um campo como você fez. Qual é o mais certo é difícil dizer. Uma disciplina pode ficar sem um curso?
Se a disciplina está vinculada a apenas um curso, se o aluno mudar de curso ele não está mais cursando aquela disciplina.
Mas se a disciplina pode existir em vários cursos tem duas coisas a considerar: precisa ter uma amarração entre cursos e disciplina; e então não importa (?!? depende) em que curso o aluno está cursando-a, ele cursa a disciplina.
E aí o campo cursoId de disciplinaAlunoCurso não seria necessário.
Você levantou essa possibilidade do aluno trocar de curso e ainda continuar cursando a disciplina, então a disciplina não pode simplesmente pertencer ao curso, mas sim vários cursos podem ter relacionamento com as disciplinas.
Depois você vai usar a informação disponível de todas as disciplinas que ele completou e todas necessárias para o curso para saber se ele concluiu o curso. Mas já estamos indo além da modelagem.
Já que se falou tanto em turmas nos comentários e é o correto considere criar uma tabela de turmas e relacionar o aluno e a disciplina à turma. Isto não resolve todas as situações possíveis em uma escola, mas já resolve uma importante. E aí obviamente a amarração será aluno X disciplina X turma. Eventualmente de curso também. Eu sou um exemplo vivo de que isso é necessário porque mudei de turno e tive que fazer diversas disciplinas do meu curso em turmas de outros cursos (o que às vezes descobri que a disciplina não era bem a mesma).
Conclusão
Se for analisar tudo o que pode acontecer, pensar que uma mudança de cursos provavelmente precisa ser registrada adequadamente guardando histórico do que ele fez, que podem existir turmas diferentes, e que tem uma série de outros elementos e fatores envolvidos, vai ficar bem complexo. Se deixar tudo isto de lado em última análise pode ter uma tabela única que cuida de tudo.
Mas não garanto nada disso, pode ser que precise ser diferente. É mais fácil fazer modelagem de situações reais. Ou pelo menos de situações hipotéticas bem especificadas.
Coloquei no GitHub para referência futura.
Comment: Isso + o que o Bacco comentou sobre as turmas já devem dar uma bela ajuda ao usuário, +1.
Comment: Eu quase falei das turmas mas sei lá, pode ser um cursinho furreca que não tem nada disto :) Claro que idealmente teria porque ninguém se matricula em uma disciplina e sim em uma turma. A disciplina não fica inativa quando os alunos terminam ela. A turma sim. Mas é o que eu falei, para fazer certo, pensar em tudo, vai ficando complexo.
Comment: Exatamente, se deixar de associar a uma turma você perde não só o "nome" da turma, mas o ano e o semestre, que provavelmente serão necessários na hora de se associar uma nota ao aluno. Mas, como você já disse, cabe ao AP decidir se o modelo precisa ou não lidar com isso.
Comment: Eu quis não inventar muito além do que ele já definiu mas certamente é algo interessante a adicionar. Eu faria assim. Alias já fiz para uma escola em um dos meus primeiros sistemas quando tinha 17 anos :) Inicialmente em dBase :P e depois Clipper. Boas memórias. Pena não ter mais os fontes para recordar.
Comment: Excelente explicação, estou passando por um problema parecido, ainda estou precisando entender a logica por trás, para modelar o banco de dados e fazer as ligações certas.

DER para aluno, disciplina e curso


The send_keys() method is neither working nor throwing any exception on the webpage's prompt type alerts

Question: When trying to use the send_keys() method to enter the text in a webpage's prompt type alerts, it is doing nothing, nor any exceptoin is being thrown so that I can correct the issue. I have tried this on two different website where I get such prompts. I am using the Selenium version 4.8.2. The complete code is as below:
<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert

import sys
import time

def launch_browser(url:str = None, is_hidden = False) -> webdriver.Chrome:

    chromedriver_path = r"D:\Drivers\chromedriver.exe"
    chrome_service = Service(chromedriver_path)

    browser_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    chrome_options = webdriver.ChromeOptions()
    chrome_options.binary_location = browser_path
    chrome_options.add_argument('--start-maximized')
    chrome_options.add_argument('--log-level=3')

    if is_hidden != False: chrome_options.add_argument('--headless')

    try:
        driver = webdriver.Chrome(service=chrome_service, options=chrome_options)
    except Exception as e:
        print(e)
        sys.exit()

    if url != None: driver.get(url)

    return(driver)

def sample_01():

    url = 'https://www.selenium.dev/documentation/webdriver/interactions/alerts/'
    driver = launch_browser(url)

    element = driver.find_element(By.LINK_TEXT, 'See a sample prompt')

    WebDriverWait(driver, timeout=5, poll_frequency=1).until(ec.element_to_be_clickable(element)).click()
    WebDriverWait(driver, timeout=5, poll_frequency=0.5).until(ec.alert_is_present())
    alert = Alert(driver)

    time.sleep(2)
    try:
        alert.send_keys('Selenium')
    except Exception as e:
        print(e)

    print(alert.text)

    time.sleep(5)
    driver.quit()

def sample_02():
    url = 'https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt'

    driver = launch_browser(url)

    driver.switch_to.frame("iframeResult")
    driver.find_element(By.XPATH, '//button[@onclick="myFunction()"]').click()

    WebDriverWait(driver, 10, 1).until(ec.alert_is_present())

    alert = Alert(driver)

    try:
        alert.send_keys('name_of_person')
    except Exception as e:
        print(e)

    print(alert.text)
    time.sleep(5)

if __name__ == '__main__':
    sample_01()
    sample_02()
</code>
Answer: Your code works, keys are being sent, however the input text is not displayed in Chrome. See this chrome bug:
https://bugs.chromium.org/p/chromedriver/issues/detail?id=1120#c11
Comment: Thank you for your reply, I didn't notice, that accepting the alert on w3school shows the send_keys() values although the same is not visible on the alert.


Calculate Mod of a very big number

Question: How is it possible to calculate modulo of the following equation:
$3^{P^5} \mod P$
If $P$ is a really big prime number 174449211009120179071170527.
Thanks
Comment: Using [PARI/GP](http://pari.math.u-bordeaux.fr/) code `P=174449211009120179071170527;lift(Mod(3,P)^(P^5))` evaluates to $3$. Same thing with P^2 or P^3, etc.
Comment: Is it possible to do it by hand? or I don't know break it down to smaller problems?
Comment: Start with $3^P \pmod P$. Read [Fermat's little theorem](https://en.wikipedia.org/wiki/Fermat%27s_little_theorem).
Comment: By little Fermat and [modular order reduction](https://math.stackexchange.com/a/2033681/242)

$\large \bmod p\!:\,\ 3^{\large\:\! p-1}\!\equiv 1\,\Rightarrow\, 3^{\:\!\large p^{\Large 5}}\!\!\equiv 3^{\:\!\large p^{\Large 5}\bmod p-1}\!\equiv 3^{\large 1^{\Large 5}}\!\!\equiv 3\ $ by $\large\bmod p\!-\!1\!:\,\ \color{#c00}{p\equiv 1}\,\Rightarrow\, \color{#c00}p^{\large 5}\equiv \color{#c00}1^{\large 5}\ \ \ $
Answer: To find $a^M$ mod$p$, first write $M$ in binary, i.e.
$$M=c_0+c_1 \times 2 + c_2 \times 2^2 + ... +c_n \times 2^n, c_i=0 \text { or }1,0 \le i\le n  $$ The $c_i$ are easy to calculate-just keep dividing by 2 and taking the remainder. Then $$a^M=a^{c_0} \times a^{c_1 \times 2} \times a^{c_2 \times 2^2} \times ... \times a^{c_n \times 2^n}$$ and $$a^M \mod p=a^{c_0} \mod p \times a^{c_1 \times 2} \mod p \times a^{c_2 \times 2^2} \mod p\times ... \times a^{c_n \times 2^n}\mod p$$. Note that $$a^{2^{i+1}}=(a^{2^i})^2$$ and $$a^{2^{i+1}}\mod p=(a^{2^i}\mod p)^2$$ Thus all you need to do is start with  $result$ as 1 and $powerofa$ as $a$ and keep track of $powerofa= a^{2^i}$, each time squaring the previous $powerofa$ and leaving the previous $result$ as is if $c_i=0$ or multipling it by $powerofa$ if $c_i=1$, making all calculations mod $p.$ Such a program is easy to write in the language of your choice, fast to execute and uses little storage space.

Calculate Mod of a very big number


Why do prime numbers have this pattern?

Question: I wrote a fairly simple program that works basically like this:

Take a natural number (starting at 2) and test if it is prime
If it is prime, switch direction (from up to down, or from down to up)
Move up 1 up pixel if facing up, or move down 1 pixel if facing down
Move 1 pixel to the right, and draw a point at the current position (move back to left side of the screen if it's reached the right edge)
Increment the integer
Repeat (1-6)

Heres the program I used to run this:
<code>//Note: this is written in processing, so it won't run as a normal java program
void setup() {
  size(500,500);

}
long p= 1;
long hi = 0;
boolean up = true;
long average = 0;
void draw() {
  frameRate(999);
  stroke(255,0,0);
  line(0,height/2,width,height/2);
  for (int i = 0; 20000 > i; i++)  {

  stroke(p/300.%255);
  point(p/300.0 % width,((hi)/100.)+width/2.0);

  if(prime(p)) {
    up = !up;
  }
  if (up) {
    hi-- ;
  }
  else {
    hi++;
  }
  average += (hi);
  if (frameCount % 100 == 0) {
    System.out.println("prime" + p);
  System.out.println("average" + average);
  }
  p++;
  }
}
class point {
  int x = 0;
  int y = 0;
}
boolean prime(long p) {
  for (long i = 2; Math.sqrt(p) >= i; i++) {
    if (p % i == 0) {
      return false;
    }
  }
  return true;
}
</code>
After running this program, it appears that there is a very significant bias towards the starting direction. Here is an image of running this program, all the way up about the integer 5000000. (The red is the center line, where it started)

So my question is, why do prime numbers have this strong bias towards one direction?
Edit:
Here are the first few points plotted:
2 is prime? —> True,     Now direction is up, point at (1,1)
3 is prime? —> True,     Now direction is down, point at (2,0)
4 is prime? —> False,   Direction still down, point at (3,-1)
5 is prime? —> True,     Now direction is up, point at (4,0)
6 is prime? —> False,    Direction is still up, point at (5,1)
Comment: oh the river of primes.
Comment: @RoddyMacPhee It could also be a desert.
Comment: The sequence https://oeis.org/A330547 seems to be pertinent.
Comment: "Take an integer" is very unclear. Do you just use the natural numbers in the usual order ?
Comment: For those of us who have a hard time reading code, could you specify the first few points that are plotted? As I interpret the (numbered) description, they are $$(2,0), (3,-1),(4,0),(5,1),(6,0),(7,-1),(8,0),(9,1),(10,2),(11,3),(12,2),(13,1),(14,2),(15,3),(16,4),(17,5),\ldots$$ Is this right?
Comment: @BarryCipra According to the code, they are $$(1,0),(2,-1),(3,0),(4,-1),(5,-2),(6,-1),(7,0),(8,-1),(9,-2),(10,-3),(11,-4),(12,-3),(13,-2),(14,-3),(15,-4),(16,-5),(17,-6),(18,-5),(19,-4),(20,-5),(21,-6),(22,-7),(23,-8),(24,-7),(25,-6),(26,-5),(27,-4),(28,-3),(29,-2),(30,-3),\ldots$$
Note that this is a image coordinate system (upside down)
Comment: @dodicta, the OP's edit (below the graph) seems to agree with what I got.
Answer: Small prime gaps, would mean it would change direction often.
2->down, 3 to up, 5 down, 7( same line as 3) up, 11 ( just 2 lines above 5) down, 13( same line as 5) up, 17(just 2 lines above 11) down, 19 (same line as 11) up, 23 down, 29 ( same line as 13) up, 31 ( same line as 11,19) down, 37 ( first time below center -1) up, 41 ( same line as 5,13)
only a larger gap facing down could possibly go below center the more long gaps up the less shorter gaps can eat away at that safety net.
Bertrands postulate guarantees us, we won't go more than $p-2$ below the center by the time we hit $2p$ because there's always a prime between $p$ and $2p-2$
You'll also note that unless you go back toward the left, you'll run off your screen edge...
same with height unless you have an infinite screen...
Largest gap is only 154, but gap of 6 is more common showing up 54545 times ( about 15.65%), with a gap of 12 being second most common. so a lot of overlapping lines.
Comment: by 50 million lead is still 6 but it's at 13.8% of the total.

Why do prime numbers have this pattern?


ISA Server NLB and HTTP 403 errors

Question: I have an ISA Server 2006 Enterprise Edition NLB array and, intermittently, users connecting through one of the two servers get an ISA Server 403 (Forbidden) error message:
<code>Technical Information (for support personnel)

* Error Code: 403 Forbidden. The ISA Server denied the specified Uniform Resource Locator (URL). (12202)
* IP Address: [IP address of public web server
* Date: 6/17/2009 4:07:28 PM [GMT]
* Server: [DNS name of ISA server - always the same one]
* Source: proxy
</code>
The exact address that I get them on varies a lot.
I think that the problem is that it's connecting to the other member of the array to access these sites and isn't able to pass the authentication through (users are required to authenticate to access any website), but I have no idea where to even start to enable the authentication.
Answer: I had authentication set up wrongly - the authentication settings for web proxy on the intra-array network must be the same as the authentication settings on the internal network.
However, the servers shouldn't have been connecting through one another to the internet in the first place.
That issue - the much more important one - was a problem with the binding order of the network adapters.  Those nice Microsoft people have a fix.
Comment: Oh yeah, I forgot about the binding order. When I was walking through an in-depth session with an ISA expert that was one of the first things he told me.
Answer: Is the same sort of authentication being used on each of the web hosts. It could be that one is using BASIC and the other is using Windows/NTLM and that is not getting passed through ISA. So check and re-check the IIS configuration to make sure that they are identical. You could also try exporting it on the working server and importing it on the non-working. (first delete the non-working site and import by creating a new site).
Comment: IIS isn't installed on ISA servers.
Comment: I would still double check the web server configuration as it sounds very similar to a situation I had just the other day where authentication prompts would get suppressed if ISA was not configured to pass it through.
Comment: What web server?  These are internal users connecting to web servers on the internet - e.g. bbc.co.uk.  I can't check the config on those servers!
Comment: I think I was misreading your question. I was seeing it as you were using ISA to create a NLB farm that you were then publishing. Are you saying that you are using ISA in a NLB environment to act as a proxy server to the internet and that one of your ISA servers is acting sporatic. In this case, I'm not sure and would contact PSS if that is an option.
Comment: Yep, and I have cracked it - see my own answer.

ISA Server NLB and HTTP 403 errors


nfs file access statistics

Question: For a Linux NFSv3 server, is there any way to see statistics on actual file access?  In other words, I would like to see a timestamped log of every file read or written.
Motivation: I have several NFS servers that are slated to be replaced by some kind of "big iron" storage system.  In my particular case, the NFS client load is virtually all reads of large files (averaging around 700 MB).  One vendor's solution uses a large RAM disk as a cache to provide the kind of massive random read throughput that I need.
What I want is a way to study what the NFS file access pattern looks like so that I can "right size" the cache.
Comment: Nope, haven't found anything.
Comment: Have you found something Matt?
Answer: I've been banging my head against this problem all day, with no solution found.

You can turn up the debugging of the NFS server, but that doesn't provide much detail (if that exmaple is accurate) and will probably dominate a busy NFS server's disk with useless baggage logged in addition to the bare filenames.
Another solution is adding rules to auditd/auditctl to log all reads or writes to the NFS directories, but that doesn't work for our Centos 6.X machines, for reasons I can't quite figure out yet. In /etc/audit/audit.rules on a client machine:
# First rule - delete all
-D

# Increase the buffers to survive stress events.
# Make this bigger for busy systems
-b 8192

# Feel free to add below this line. See auditctl man page
-w /auto/ -p r -k read -k home
-w /auto/ -p w -k write -k home
-w /auto/ -p xa -k other -k home

...where I've given separate keys to reading, writing, and executing/changing attributes. My clients are autofs'd to mount a few different NFS directories, including their home directory, to /auto/ with soft links pointing the client machine's /home/users/ back to /auto/. I get logging of lots of stuff, but none of the files the users themselves seem to be modifying.
Troll the audit logs with ausearch -k read | aureport -f, for instance. grepping for .ODT or .PDF comes up with nothing, the only results are for metacity's configs, Chrome's crap, etc., etc.
Naturally, enabling audit on the server pointing at the real /home/users/XYZ only shows accesses from things interfacing with the server directly (mail clients) or users SSH'd into the server.
If you can figure out the right recipe for audit, or a dedicated solution all together, please, please, please share it! You'd think this would have been solved in 1993.
Answer: Take a look at nfstrace https://github.com/epam/nfstrace. It captures network traffic and perform deep packet inspection. It finds NFSv3/v4 procedures (READ, WRITE etc.) and tracks its statistics. Also, you can develop new pluggable modules for nfstrace.
Comment: Nice tool, but you ought to disclose [your association with the project](https://github.com/epam/nfstrace#authors) whilst plugging it (see, eg, http://serverfault.com/help/behavior).
Answer: Take a look at nfsstat.  It can produce statistics for both a NFS client and server.  It's a part of nfs-common on Ubuntu Linux.  You can also look at iotop for the server-side, but that reports all disk I/O, not just NFS.
Comment: Unless my version of nfsstat is too old, it doesn't have the granularity that I need.  I'm looking for _per file_ statistics.

nfs file access statistics


dcpromo /forceremoval as a file server

Question: I'm working on a customers infrastructure where most of the DCs were not replicating with each other. I managed to bring up another two DC's, bring them to the domain and switch over the FSMO roles.
There's one 2008R2 DC left which I can't gracefully remove and I will need to force remove it, however this one server also turns out to be the only file server for the business. If I perform a dcpromo /forceremoval on this DC, which automatically removes the server from the domain, will it lose the folder permissions? I'm planning on making this a member server again after the removal.
Answer: The SID's and GUID attributes will be retained
You will see question marks regarding the NTFS permissions within the directory structure after you force remove the host from the domain.
After you rejoin the system it will remap all of the SID's and GUID's and you will see the username associated to the GUID's and SID's again.
Comment: I thought this may be the case but just needed to double check, so I didn't have to setup all the permissions again. It worked, thanks!
Comment: All good.  Welcome to the site.  Cheers!

dcpromo /forceremoval as a file server


Very high notes on the treble clef

Question: I was wondering, why on most music sheets the high notes on a treble clef are written above the upper lines and take up so much space on a page whereas it would be better to use 8va and 16va to notate them? Above that, you have to learn those notes to know them whereas using the 8va and 16va makes everything a lot more simple.
In guitar pro, when I write music I often use 8va and 15va. Is it incorrect?
EDIT: Indeed 15va and not 16va, sorry.
Comment: 8va is o.k. 16va should be 15ma.
Answer: Depends. The longer your passage goes on in the highest register, the more sense it makes to switch octaves. But depending on the method of notation, adding this element to the score can be a lot more effort than simply adding note after note, so the threshold at which people consider this worthwhile varies.
Also, a lazy score-writer who is only concerned about making their job easier will make different decisions from a professional who always puts the musician's ease of reading first. So this is one if the many intangibles that distinguish cheap from truly professional-grade music scores.
Comment: Wanted to add here that for many instruments a change in octave also represents different fingerings / shifting / technique. So slapping 8va/15ma above it is not advisable. Many instruments prefer to just read ledger lines.
Answer: First off, 16va is definitely incorrect as explained in the answer to this question and I'm surprised your software lets you write it. The correct ottava notation is 8va/8vb for one octave up/down and 15ma/15mb for two octaves up/down.
As for how often you should use them, I would say sparingly, but it's largely a matter of taste, and will depend on your audience. You may think ledger lines are difficult to read, but frequent changes of octave can be difficult to read too, as can changes of clef. Less experienced players who aren't very confident reading music may well find the ottava notation helpful, but more experienced musicians who are used to ledger lines are likely to find it annoying if overused.
One thing ottava notation is good for is for making it very clear if you're repeating a phrase up/down an octave or two. Also, if you're writing a piece for beginners then it can be a great way to get them exploring the keyboard before they've learnt about ledger lines.
Unless you're going very, very high or very, very low or really, really want to avoid ledger lines then you'll rarely need 15ma/mb. You can cover all the keys on a piano with 8va/8vb and a couple of ledger lines.
Comment: 8vb and 15mb are also incorrect, though widely used.  They arise from the perception that the "a" in 8va and 8vb means "alta," which it does not.
Answer: It depends on the instrument.
On keyboard type instruments such as piano, using ottava (8va) and related notation is useful not only because it saves ledger lines, but because the technique used to play an octave up is essentially the same — you just have to move your hand to a different position on the keyboard.
But for woodwind, brass, or strings instruments, ottava notation is generally not used.  The techniques required to play notes an octave apart on theses instruments is different, and players will associate stave positions with these techniques — the fingering (and embouchure) just won't be the same.
Flute or tuba players especially, get used to reading notes on a number of ledger lines quickly and without any problem.  An 8va passage for these instruments will be confusing, and the players won't appreciate it at all.
Having said that, sometimes in a full orchestral score, ottava notation might be used to save space on the page — but it shouldn't appear in the players parts.

Very high notes on the treble clef


Can Display Suite render content without my theme around it?

Question: I'm just getting familiar with Display Suite and I want to know if I can use it to display only the content - not my header/footer/etc from my theme.
My goal is to display this content in a modal popup so I don't want anything around it.
Answer: aDisplay suite should allow you to modify the output for the fields and even choose some layouts but AFAIK it won't let you completely omit the site theme (i.e. create a page without header or footer).
You can use js/ajax to grab just the portion of the page you want to appear in the modal pop-up so that it doesn't pull in the header/footer. Depending on the JS library(ies) you are using this could be easy or challenging.


OpenGL ES shader compilation

Question: I am trying to create applications with opengl. Debugging on a real device.
I create the context like this::
<code>GLSurfaceView baseView = new GLSurfaceView(this);
baseView.setEGLContextClientVersion(3);
baseView.setRenderer(new GameView());
</code>
I compile shaders like this:
<code>    int program = GLES20.glCreateProgram();
    int idShad = (type == 0) ? GLES20.GL_VERTEX_SHADER : GLES20.GL_FRAGMENT_SHADER;

    int shader = GLES20.glCreateShader(idShad);
    GLES20.glShaderSource(shader, source);
    GLES20.glCompileShader(shader);

    int[] isCompiled = new int[1];
    glGetShaderiv(shader, GL_COMPILE_STATUS, isCompiled, 0);
    if (isCompiled[0] == GL_FALSE) {
        String infoLog = "";
        infoLog = glGetShaderInfoLog(shader);
        glDeleteShader(shader);

        String typeShader = (type == 0) ? "Vertex Shader" : "Fragment Shader";
        Log.e("OpenGl", "Cannot compile " + typeShader + ": " + infoLog);
        System.exit(-1);
    }

    glAttachShader(program, shader);
</code>
But I always getting this error:

Cannot compile: Vertex Shader: 0:3: L0001: Typename expected, found '�'

I get it when loading from a file and when creating a line in the code
For any code, even an empty shader, here are examples:
<code>    public static final String baseMatrixVX =
        "#version 300 es\n"
        + "void main() {\n"
        + "}\0";

        public static final String texMatrixVX =
        "#version 330\n"
        + "layout(location = 0) in vec3 pos;\n"
        + "layout(location = 1) in vec3 color;\n"
        + "layout(location = 2) in vec2 tex;\n"
        + "out vec3 colorOut;\n"
        + "out vec2 texOut;\n"
        + "uniform bool enabledCam;\n"
        + "uniform mat4 projection;\n"
        + "uniform mat4 cam;\n"
        + "uniform mat4 model;\n"
        + "void main() {\n"
        + "if (enabledCam) {\n"
        + "    gl_Position = projection * model * cam * vec4(pos, 1.0f);\n"
        + "} else {\n"
        + "    gl_Position = projection * model * vec4(pos, 1.0f);\n"
        + "}\n"
        + "colorOut = vec3(color);\n"
        + "texOut = tex;\n"
        + "}\0";
</code>
What am I doing wrong?
P.S device supports opengle es 3 and above
Answer: It turned out that the problem is in the last character \0.
Should be used instead \n

OpenGL ES shader compilation


button e grid não passar por cima do menu

Question: olá é a primeira vez que faço alguma questão ou que utilizo esta plataforma algo peço já desculpa.
Bem a questão aqui é como faço para isto não acontecer?

*{
    margin: 0;
    padding: 0;
}
header{
    position: fixed;
    margin-top: none;
}

header .menu {
    background-color: rgb(92, 101, 148);
    height: 100px;
    display: block;

}

.menu {
    padding: 25px;
    position: fixed;
    width: 100%;
}

.logo {
    width: 50px;
    height: 50px;
    margin-left: 130px;
}
.menu a {
    background-color: none;
    color:#ffffff;
    text-decoration: none;
}
a:hover {
    background-color: white;
    color:#ffffff;
    text-decoration: none;
}
.down {
    text-decoration: none;
    background-color: none;
    color: #ffffff;
    font-size: medium;
    padding: 10px;
    text-align: right;
}

.algo{
    background-color: aqua;
    height: 700px;
    margin: 0/*topo*/ 10px/*direita*/ 10px/*bottom*/ 10px/*esq*/;
}

.algo h3{
    text-align: center;
}
/*corpo*/
main{
    margin: 0px;
    padding: 0px;
}

.container{
    margin: 10px;
    padding: 10px;

}

.dropdown-item a{
    text-align: center;
    background-color: white;
    color:#000000;
    text-decoration: none;
}
.grid-container{
    padding: 10px;
}
.card {
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
    padding: 16px;
    text-align: center;
    background-color: #f1f1f1;
}

            Inicio
            Sobre
            Serviços
            Contatos

Algo

Algo

Videos

                <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-bs-toggle="dropdown" aria-expanded="false">
                  Dropdown
                </button>

<button class="dropdown-item" type="button"> Video 1 </button>

<button class="dropdown-item" type="button"> Video 2 </button>

<button class="dropdown-item" type="button"> Video 3 ou + </button>

Video 1

Some text

Some text

Video 2

Some text

Some text

Video 3

Some text

Some text

Video 4

Some text

Some text

Video 5

Some text

Some text

Video 6

Some text

Some text

Video 7

Some text

Some text

Video 8

Some text

Some text

Algo

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Comment: aqui o seu código não está sobrepondo as divs, mas você poderia usar flex grid ou flexbox pra resolver seus problemas
Answer: Provavelmente é a propriedade position: fixed; que vc está dando tanto no header qto no menu. Isso provavelmente está causando esse provlema. Portanto vc tem que dar um margin-bottom no header ou um margin-top na div onde exibe os vídeos!
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Agradeço Pedro Franca mas não deu em nada.. resumindo ele continua a flutuar por cima do menu.


Facing issue with GCM - Message not received on device

Question: I am following the google guidelines for setting up GCM on my device and the server side. I successfully got the device registration ID and when I use it to send a message using the sever side code given by google, I am getting success as well. But no message is received on my phone. Please help.
Comment: I am doing this for a phonegap project. I used all the classes mentioned here https://github.com/marknutter/GCM-Cordova . Just that instead of invoking the registration from a JS, I called                        GCMRegistrar.register(this, "620217706951"); in mainActivity. I added the same SENDER_ID in overridden constructor of GCMIntentService as well.
Answer: Refer the link, understand the concept and refer class GCMIntentService.
Comment: Referred the link. The android side set up of mine is very similar. However, I am using the google provided jar and code as given in the link:http://developer.android.com/google/gcm/gs.html
Comment: Use notification manager to display message and a broadcast receiver for displaying notification that you are getting and i hope you are using sever API key
Answer: According to GCM Architectural Overview, GCM uses ports 5228, 5229, and 5230 to send messages. If you do everything right but still not receiving the message, ask your web administrator and confirm that these ports are open.
Comment: I checked my all three port and seems all three ports are close. But still I am able to receive the message. Can u tell me why???
Comment: If you can get the message even closing all those ports, GCM might also use other ports to send message which are not written in the document.
Comment: and any doc. which backs up your comment!!! Not just because I doubt your comment(which I seriously do), but also it will help me understand the concept and reason for doing so...
Comment: sorry for my bad explanation. I meant... I don't think it would work if not opening the ports unless there are other used ports which are not in doc. I once had the same problem as the title, and I solved it by opening ports. So I'm afraid I can't tell why you could do that!


queryResultWindowSize in Solr Pagination

Question: I understand what is queryResultWindowSize and queryResultMaxDocsCached.
query 1 -> q=car&rows=10&start=0
query 2 -> q=car&rows=10&start=10
(Assume query 1 and 2 are continuous queries by user1)
query 3 -> q=boat&rows=10&start=0
query 4 -> q=car&rows=10&start=10
(Assume query 3 and 4 are continuous queries by user2)
my queryResultWindowSize = 20 and queryResultMaxDocsCached = 20. When query1 is issued by user 20 docs will be cached. So the next 10 paginated docs are ready in cache. Will the cache expires if user2 issues the query3 ? or the cache is meant for individual queries ?
Does solr do a cache for query1 and query3 separately ?
Answer: The caches are pr. query. In general, it will match the query performed and use that to look up for the correct cache, and then return the values from that cache. That means that query1 and query3 will be cached separately (otherwise Solr would only be able to cache the most recent query, and that wouldn't be very helpful in most production settings).


unix read permission

Question: I have a quick question about how the read permission works. Does read permission mean I can open the file?
The situation is this: FTP server where I have an account that is not Root. There, files are owned by Root inside a 777 folder that have 604 permission -- so where "public" can "read".
Why can't I open those 604 files?
Does read mean only that you can see if the files exist?
Just curious if also there's a way to not showing the files at all to non-root users.
Answer: 604 gives no permission to members of the file's group. If your account is a member of that group, it doesn't matter that the last digit is more permissive; you don't have these permissions.

To prevent users from accessing a file's contents, remove the read permission from the file. To hide a file, you can remove a directory's read permission. It can be entered, and files can be accessed and modified (given the correct permissions), but the directory contents will not be available.
Comment: @SandroAntonucci On some Unixes, users are not able to change their group membership (i.e. leave a group). That makes it easy to create e.g. a *quarantine* group. There's a reason the octal digits in a file permission are *usually* descending. Also, it's easier if you think of *owner/group/other*, instead of *owner/group/public*.
Comment: but I tried to make a test on my server. I created a file with 604 permission owned by root:root. The user user1:users can read the 604 file because "public" have read permission
Comment: @SandroAntonucci You didn't mention the file group in your question, so I had to assume. What's the error message when you try to open?
Comment: you are right sorry, I didn't get your answer right and I didn't notice the group. I'm in the same group as the 604 files so that makes sense now. Isn't "stupid" giving access to public but not to an user in the same group?

unix read permission


How to get the size of the output of a Direct2D Effect?

Question: I need to know the size of the output of a Direct2D Effect. Say, for example, to render the effect to a bitmap for later use. For example, of the built-in Gaussian blur effect.
ID2D1Effect does not have a GetSize() member. It does have GetOutput(), but the resulting ID2D1Image does not have a GetSize() member either. Or anything even remotely related.
An effect could have an unlimited output, adapted to the rendertarget, but I expect not. When you write custom effects, the internal transform graph has, somewhere, functions like MapInputRectsToOutputRect(). Is it accessible from the app for built-in effects?
Did I miss anything? Is it at all possible?
Answer: ID2D1DeviceContext::GetImageLocalBounds method probably is what you are looking for.


How to change how ActiveAdmin displays time (every time)

Question: Since the default time in the database is in utc, I wanted to be able to still display it in the users correct time. To do this I had to take column :created_at and change it into this:
index do
...
  column :created_at, :sortable => :created_at do |obj|
    obj.created_at.localtime.strftime("%B %d, %Y %H:%M)
  end
...
end

Seems pretty easy to do once or twice, but when you need to override every index and show method, the process get's a little taxing.
Is there a way to override how ActiveAdmin displays time without having to override each occurrence?
I know I could create a function or probably use the functions provided for time better, but I'd still have to use it each time I want to display time.  I want to override it without worrying I missed one.
Answer: You can target just ActiveAdmin by telling it to always use a particular filter in config/initializers/active_admin.rb , by adding a line like this:
config.before_action :set_admin_timezone

(or config.before_filter :set_admin_timezone for versions of Rails before Rails 4)
Then in your ApplicationController, you can just define the method set_admin_timezone, and ActiveAdmin will use it. For example:
def set_admin_timezone
  Time.zone = 'Eastern Time (US & Canada)'
end

You should be able look up the current admin user in that method (in order to get their particular timezone), but I haven't tried that.
Comment: This does not seem like a good solution. This will set the timezone for activeadmin, but it will also set it for other controller actions, but it seems like it does it intermittently. I dropped a debugger in one of my application controller actions, and printed out `Time.zone` and it would intermittently print UTC sometimes, and EST other times.
Comment: To ensure it's set first: `config.prepend_before_action -> { Time.zone = "Brisbane" }` (also inlined code since it's not used elsewhere).
Comment: For the Rails 5 app I am working on now I needed to use `config.before_action :set_admin_timezone`
Comment: Yes, @dkniffin is correct that this can cause problems - any actions without an explicit Time.zone assignment can have indeterminate timezones as a result of this. The timezone needs to also be torn down at the end of the request. For example see "https://ilikestuffblog.com/2011/02/03/how-to-set-a-time-zone-for-each-request-in-rails/".
Comment: @dkniffin Try putting the debugger inside `set_admin_timezone` and see if it is ever getting called from your other controller actions. If it is, then you may be calling it from somewhere else in your application. If it is not, then some other part of your application may be setting the time zone.
Answer: I've found there are two ways to do this:
1. Javascript
This is the easier method because it is very short and doesn't involve adding a db field.  It works because it uses the users timezone from their browser.  This answer gives insight on how to do this.
2. From the Database
This process can be found in this railscast.
Essentially store a time_zone field in the users table.  Then use an before_filter (although an around_filter might be a better idea) to set the timezone in the controller.
before_filter :set_time_zone

private
def set_time_zone
  Time.zone = current_user.time_zone if current_user
end

Answer: So for my understanding, you need two things:

Localtime/Timezone
You can achieve this by set the right timezone of your rails app, the active_admin will pick up that by default. For example, in your rails config file(config/application.rb):
config.time_zone = 'Eastern Time (US & Canada)'
Default time format
You can refer this Change default date formatter in active admin

Good luck~
Comment: The timezone will be specific to each user, so configuring the timezone like that won't work
Comment: Well, if you are talking about the client time, then `obj.created_at.localtime.strftime("%B %d, %Y %H:%M)` still not work, cause this is still server time, you can display client time using javascript.
Comment: Yeah I'm slowly coming to this realization.  javascript is a good call though, I was about to add a field to the db for it, but that would be unnecessary
Comment: @Zubin datetimes are always stored in UTC regardless of that config option (which just affects how they're displayed by default)
Answer: Setting Time.zone in before action is not safe, since consequent requests, processed in the same thread may be affected.
It is safer to use around action. I.e. in config/initializers/active_admin.rb you'll have:
config.around_action :set_admin_timezone
And in ApplicationController you will have
  def set_admin_timezone
    Time.use_zone('Eastern Time (US & Canada)') { yield }
  end

This will return the timezone to normal after the request, and therefore, consequent requests will be not affected.
Comment: This is the correct answer for changing the format of displayed and entered (form input) dates and times in Active admin to eastern time, without changing the way dates are returned (by your api, for example) to also be in eastern time. I believe OP wants to only change the date _format_. For that, you should edit `config/locales/en.yml` as described [here](https://stackoverflow.com/a/41511930/1137752). However, when I searched for how to change AA's timezone (only) this thread always appears at the top of google's search results. Leaving this here for posterity. Thanks, Serhii.


sqlite3.Connection class inheritance, commit not working

Question: This is my first time using sqlite3 through class inheritance, and I've run into a problem where I get no traceback errors, but the queries I execute won't commit. I simplified my code
import sqlite3 as lite

class BaseModel(lite.Connection):
    def __init__(self, **args):
        lite.Connection.__init__(self, **args)
        self.cur = self.cursor()

    def execute(self, query):
        self.cur.execute(query)

class Model(BaseModel):
    def __init__(self, **args):
        BaseModel.__init__(self, **args)

    def _new_(self):
        queries = []
        queries.append(' '.join(['CREATE TABLE IF NOT EXISTS tb1',
                         '(id INTEGER PRIMARY KEY,',
                         'column1 TEXT,',
                         'column2 INT)']))

        for q in queries:
            self.execute(q) # execute the queries

        self.commit()   # write changes to db

    def tables(self):
        query = 'SELECT name FROM sqlite_master WHERE type="table" ORDER BY name'
        results = self.execute(query)
        return results#.fetchall()

if __name__ == '__main__':
    model = Model(database='test.db')
    model._new_()

    # Test Fails because the queries aren't being saved in the db
    # see Model.__new__ for details

    tables = model.tables() # get all tables

    print 'Tables Created:'

    if tables:
        for t in model.tables():
            print '\t%s' % str(t[0])
    else: print tables

Comment: Normally, it is `__new__`, not `_new_`, but I suspect that was intentional. That makes your code rather confusing to parse.
Comment: Sorry, I didn't really but any thought in that.
Comment: See [Basic Customization](http://docs.python.org/2/reference/datamodel.html#basic-customization), but I think you really do not want or need to use `__new__` in this case.
Answer: You need to call self.commit():
self.commit() # write changes to db

Without the () you are merely referencing the method, not invoking it.
Next, your execute() function doesn't return anything:
def execute(self, query):
    return self.cur.execute(query)

Comment: haha, Thanks I totality missed that. I guess sometimes you need someone to point out the obvious.
Comment: Thanks for pointing that out, but the code dosn't seem to behave any different.


Generate and attach a file in Drupal 7

Question: How do I generate a (text only) file in Drupal 7, and attach it to a particular node automatically.
Is there a way to do this with a module, or should I use code to do it in some way (this seems tricky).
Answer: First create a file using the drupal file_save_data
<code>$data = 'Your text data';     // Text data to be saved to file.
$filename = 'filename.txt';   // Filename
$file = file_save_data($data,'public://' .$filename);
</code>
Now $file will contain the file object that we can attach to the node. Let say you have already created and attached a file field to node type. Lets call it 'field_custom_file'
Then load the node you want to attach then cast the file object to array and attach it to the field.
<code>$node = node_load($nid);  // $nid is the id of the node where you want to attach the file.
$node->field_custom_file[LANGUAGE_NONE][] = (array)$file;
node_save($node);
</code>
Answer: <code>$file = (object) array(
    'uid' => 1,
    'uri' => $filepath,
    'filemime' => file_get_mimetype($filepath),
    'status' => 1,
    'display' => 1,
);
$file = file_copy($file, 'public://');
$node->field_file['und'][0] = $file;
</code>

Generate and attach a file in Drupal 7


Do discontinuous harmonic functions exist?

Question: A function, $u$, on $\mathbb R^n$ is normally said to be harmonic if $\Delta u=0$, where $\Delta$ is the Laplacian operator $\Delta=\sum_{i=1}^n\frac{\partial^2}{\partial x_i^2}$. So obviously, according to this definition, $u$ must be twice differentiable and therefore continuous. However, if $u$ is at least continuous, being harmonic is equivalent to the condition that the average value of $u$ in any ball centered at a point $p$ is actually equal to $u(p)$: $$u(p)=\frac{1}{Vol(B_r(p))}\int_{B_r(p)}u\, dV.$$
My question is whether there are any integrable functions $u$ for which the above equation holds for all $r$ and $p$ but for which $u$ is not continuous.
Comment: See also http://en.wikipedia.org/wiki/Elliptic_operator#Elliptic_regularity_theorem.
Comment: I don't know much about this, but I would have said that a **much** stronger result holds. I would have said that a harmonic hyperfunction is automatically analytic... (I'm considering the usual laplacian on $\mathbb R^n$.)
Comment: @Pierre: $\Phi_r$ in my answer is real analytic on the interior of $B_r(0)$. Therefore, with only a bit more work, my answer shows that $u$ is real-analytic.
Comment: Dear @robjohn: Thanks! I agree. I hadn't read the question carefully enough. The question doesn't ask explicitly if $u$ is harmonic, and, logically, the answers answer the question as asked. But it seems to me the question "is $u$ harmonic?" is very natural. [Wikipedia](http://en.wikipedia.org/wiki/Harmonic_function#The_mean_value_property) says: "all locally integrable functions satisfying the (volume) mean-value property are infinitely differentiable and harmonic functions as well". A proof is a sketched.
Answer: On the interior of its domain, a harmonic function is infinitely differentiable (even with just the mean value property). However, on the boundary of its domain, it can limit to a discontinuous function.
Mean Value Property: $u(x)=\frac{1}{\Omega_nr^n}\int_{B_r(x)}u(v)\;\mathrm{d}v$ for any $r>0$ so that $B_r(x)\subset\mathrm{Dom}(u)$, where $\Omega_n$ is the volume of the unit sphere in $\mathbb{R}^n$.
Define $\displaystyle\phi_r(s)=\left\{\begin{array}{cl}e^{s^2/(s^2-r^2)}&\text{for }0\le s<r\\0&\text{for }s\ge r\end{array}\right.\hspace{.25in}$ then $\Phi_r(x)=\phi_r(|x|)$ is in $C_c^\infty(\mathbb{R}^n)$
We can average the Mean Value Property over a range of sphere radii:
$$
\begin{align}
u(x)&=\frac{1}{\int_0^r\Omega_ns^n\phi_r^\prime(s)\mathrm{d}s}\int_0^r\int_{B_s(x)}u(y)\;\mathrm{d}y\;\phi_r^\prime(s)\;\mathrm{d}s\\
    &=\frac{1}{\int_0^r\phi_r(s)n\Omega_ns^{n-1}\mathrm{d}s}
\int_0^r\phi_r(s)\int_{S_s(x)}u(y)\;\mathrm{d}\sigma(y)\;\mathrm{d}s \\
    &=\frac{1}{\int_{\mathbb{R}^n}\Phi_r(y)\mathrm{d}y}
\int_{\mathbb{R}^n}\Phi_r(y-x)u(x)\;\mathrm{d}x\\
    &=\frac{1}{\int_{\mathbb{R}^n}\Phi_r(y)\mathrm{d}y}\Phi_r*u(x)
\end{align}
$$
Since $\Phi_r$ is in $C^\infty$, $u$ must be also.
Thus, the Mean Value Property implies $C^\infty$ on the interior of the domain.
Comment: I should have seen this. I forgot that the convolution of an integrable function with a $C^\infty$ function is also $C^\infty$.
Comment: @Rohan: it is indeed integration by parts. Before $$v=\int_{B_s(x)}u(y)\;\mathrm{d}y$$ $$dw=\phi_r^\prime(s)\;\mathrm{d}s$$ and after $$w=\phi_r(s)$$ $$dv=\int_{S_s(x)}u(y)\;\mathrm{d}\sigma(y)\;\mathrm{d}s$$ The minus sign is cancelled by the integration by parts in the denominator out front.
Answer: For fixed $r$, the measure of the symmetric difference of $B_r(x)$ and $B_r(y)$ goes to $0$ as $y$ goes to $x$.  Therefore, by (local) absolute continuity of the integral (of a locally integrable function), $\int_{B_r(x)}udV-\int_{B_r(y)}udV$ goes to $0$ as $y$ goes to $x$.  This implies that $u$ is continuous.
Comment: This reminds me of [Nelson's proof of Liouville's theorem](http://dx.doi.org/10.1090/S0002-9939-1961-0259149-4) (only tangentially related).
Answer: I would say "it depends". I was rather surprised by the following example, shown to me by a colleauge the other day. Dropping the assumptions that $u$ is locally integrable, strange things can happen!
Let $f(z) = \exp(-1/z^4)$, and let $u(x,y) = \Re f(x+iy)$. Then $u$ is clearly harmonic outside the origin. Extend $u$ to whole plane, by putting $u(0,0) = 0$. Then (outside the origin)
$$ u(x,0) = \exp(-1/x^4) \quad\text{and}\quad u(0,y) = \exp(-1/y^4). $$
It is not hard to see that both partial derivatives of $u$ exist at the origin, and in fact a little more work shows that the same holds for the second order partial derivatives. (However $u$ is of course not continuous at the origin, and neither is any of its derivatives.) All the derivatives above are in fact equal to $0$! In other words, the function $u$ satisfies "Laplace's equation"
$$ u''_{xx} + u''_{yy} = 0$$
everywhere on $\mathbb{R}^2$. A moment of contemplation also shows that $u$ fails to be integrable on any neighborhood of the origin, and hence does not define a distribution.
Comment: For more about the particular case of $\mathbb{R}^2$ which has intimate connections with complex analysis, one should see [this article in the AMM](http://www.jstor.org/stable/2321164).


How does the cartesian product of set A satisfy an equivalence relation?

Question: Suppose A={a,b,c,d}. Why is A×A an equivalence relation?
Specifically, how would one show the Property of Transitivity simply?
Is it possible to show aRb, bRc ⟹ aRc in this way?
Generally speaking, how is the Cartesian Product of a set like A an equivalence relation?
Note: The professor does not want me to show x ∈ ℝ and the consequence, x − x = 0 ∈ ℤ. He does not want a rigorous proof or anything of the like. Just the intuition.
Comment: The statement $$xRy, yRz\Longrightarrow xRz$$ is true because $(x,z)\in A\times A$. I mean, it's not a consequence of the fact that $xRy $ and $yRz$ but just a fact from the definition of your equivalence relation.
Answer: It's all about the notations and rigorous definitions.
What you write as $a\,R\,b$ is really defined as $R\subseteq A\times A$ and $\bf{(a,b)\in R}$.
$A\times A$ is the relation where every element is related to every element.
Comment: Then the professor should call it a rather self explaining *name*, e.g. the 'all-to-all' relation and  perhaps also avoid the notation $A\times A$.
Comment: I understand what you are saying. However, this is an undergraduate introductory discrete math class. I have had a class in proofs far more rigorous than this class, that tends toward analysis. Unfortunately, the professor wants a very simple, intuitive solution here. Assuming the elements are in the reals is not his desire. I want to know if this can be explained intuitively. I understand the more rigorous definition.
Comment: Agreed. The class is unfortunately geared toward Computer Science majors more than the mathematics major. The rigor required in my proofs class is simply not welcome in this Discrete Math class. The challenge is posed when I want to apply a known fact from another class, construct a lemma or proof, and he marks "correct, but use this instead". It takes away from the math unfortunately, but I suppose that is what is _required_ for the class.
Answer: Let $ A=\{a,b,c,d\}$. $A\times A$ simply has every order pair generated from the elements. So you can prove the Property of Transitivity: Take $a,b,c\in A\times A$. Suppose $(a,b)\in A\times A$ and $(b,c)\in A\times A$. Immediately you have $(a,c)\in A\times A$, because $A\times A$ includes every pair of elements.
Bold words may give you some "intuition". In general, any relation on $A$ is a subset of $A\times A$.
Answer: The cartesian product contains $(x,y)$ for all $(x,y)\subset A$. So $aRc$ is always true. Logically speaking, this means $aRb\land bRc\Rightarrow aRc $, but you don't need to look at $aRb$ or $bRc$ to know that $aRc$ is true.


VMPK: Use common slider control instead of dial control?

Question: It uses a small dial control (Windows term. Maybe "widget" in Linux/Android term.) for changing the values. Maybe this is for someone who uses a real hardware dial and the dial reflects the hardware value? I don't know. But I am using mouse to change the values, so it is very awkward to use it. Is there a way to replace the dial control with something more sensible, like a slider or the numeric up-and-down as other parts of the window are using in the screenshot below?
Answer: In menu Edit you will find Shortcuts which you can define by yourself. The default shortcut for changing the controller value seem to be Alt++ and Alt+-. Note, for + you either need to also hold Shift or use the numeric pad.


Rigorous derivation of expected proportion of collisions

Question: The problem: $S$ is a finite set of $n$ elements. $H$ is a random function from $S$ to $S$ (the image $y\in S$ of each $x\in S$ by $H$ is chosen uniformly at random, with each choice independent; in cryptographic terms, $H$ is a Random Oracle).

What is the limit (as $n\to\infty$) of the expected proportion of elements $x$ of $S$ such that $\exists x'\in S, H(x)=H(x')$?
What is the limit (as $n\to\infty$) of the expected proportion of elements $y$ of $S$ such that $\exists x\in S, \exists x'\in S, x\ne x', H(x)=y=H(x')$?

Note: expectancy is defined over the set of all $n^n$ functions $H$.
I know a non-rigorous way to derive the answers:

a particular $y\in S$ is reached by no $x$ with odds exactly $(1-1/n)^n$, and the limit of that as $n\to\infty$ is $u=1/e$; that is also (but here I am not rigorous) the limit (as $n\to\infty$) of the expected proportion of elements of $S$ never reached;
a particular $y\in S$ is reached by exactly one $x$ with odds exactly $(1-1/n)^{n-1}$ (obtained by summing the odds that it is reached by each particular $x$, and by no other $x'$), and the limit of that as $n\to\infty$ is $v=1/e$; that is also (but here I am not rigorous) the limit (as $n\to\infty$) of the expected proportion of elements of $S$ reached exactly once;
it follows that the limit thought in (1.) is $1-v=1-1/e$, and the limit thought in (2.) is $1-u-v=1-2/e$.

Problem is, when going from the odds for a particular $y$, to the expected proportion of $y$ in $S$, this ignores that the probabilities considered are dependent. How can that be made rigorous?

If we where asked the same questions without "the limit (as $n\to\infty$) of", and answered $\approx1-(1-1/n)^{n-1}$ and $\approx1-(1-1/n)^n-(1-1/n)^{n-1}$, can we bound how large the error is?
Comment: You say "$H$ is a random function from $S$ to $S$." Can you tell us something more about $H$? Is it a random *bijection*? Is the probability that $H(s) = s'$ independent of $s$ and $s'$? From what distribution on the set of all functions was $H$ chosen? Without this information, the question is pretty much meaningless.
Comment: @John Hughes: done.
Comment: Is (1.) supposed to be the expected number of elements of $S$ reached by at least one $H(s)$?
Answer: For any particular function $f$, Consider an indicator variable $u_{f,x}$ which is $1$ if there's an $x' \ne x$ with $f(x) = f(x')$, and $0$ otherwise.
Note that this is a random variable on $F \times S$, where $F$ is the space of all $n^n$ possible functions.
Now look at the expected value (with respect to $f$) of
$$
Q_f = \frac{1}{n} \sum_x u_{f,x},
$$
which is the fraction of elements in $X$ that are "hit twice" under $f$.
Use the fact that expectation is linear, and that you can swap sums. I believe that the result falls out. (Indeed, I think you've already got the proof). The "ignores probabilities that are dependent" is exactly the kind of thing for which linearity of expectation tends to be so useful.
Here's a simple example: on the set $S = \{0, 1\}$, let $X(s) = s$ and $Y(s) = 1-X(s)$. Clearly $X$ and $Y$ are not even slightly independent. But what is $E(X + Y)$? It's just $E(X) + E(Y) = 0.5 + 0.5 = 1$.


Oracle 11g XE: How to transform a LEFT SQL JOIN to a query that uses semijoins and correlated queries?

Question: I need to transform an SQL statement that uses LEFT JOIN:
SELECT t1.FIRST_NAME
FROM EMPLOYEES t1
LEFT JOIN EMPLOYEES t2 ON t1.EMPLOYEE_ID = t2.MANAGER_ID
WHERE t2.MANAGER_ID IS NULL

to an SQL query that uses semijoins and corelated queries. How to do that?
Comment: What result would you get? What should represent each column obtained?
Comment: The result is a table of employees first names that are not present in the list of manager's first names.
Comment: The query looks correct. Why do you want to write it differently?
Comment: It's a quiz that states that: "Select all the EMPLOYEES which FIRST_NAME is not present in the list of manager's FIRST_NAME's using semijoins and corelated queries" thats why I want to know how to do that because I know how to do it with an SQL LEFT JOIN.
Comment: Your query is not a correct answer to the question, even using `LEFT JOIN`, assuming that the manager id can be null in the table.
Answer: SELECT t1.FIRST_NAME
FROM EMPLOYEES t1
WHERE NOT EXISTS
(
    SELECT 1
    FROM EMPLOYEES t2
    WHERE t1.EMPLOYEE_ID = t2.MANAGER_ID
)

Comment: According to the documentation this is a anti-join: http://docs.oracle.com/database/121/SQLRF/queries006.htm#SQLRF52355 is it possible to do the same with an semi-join that uses only EXISTS or IN? I can't think of a solution without a NOT operator. Thanks.
Comment: This query is not quite equivalent to the OP's query.  There are two way for the manager id to be `NULL`, although this is correct for the question.


Matrices in SU(2)

Question: Let $M=\begin{bmatrix}
a & c \\
b & d
\end{bmatrix}\in SU(2)$. we have $M\overline M^t= \begin{bmatrix}
aa^*+cc^* & ab^*+cd^* \\
ba^*+dc^* & bb^*+dd^*
\end{bmatrix}$, and we must have $M\overline M^t=I $.
I wonder how to for these four quadratic equations to get $c=-\overline b$ and $d=\overline a$.
So far I am only able to conclude $a,d$ and $b,c $ have the same magnitudes.
Answer: Use that $$\begin{pmatrix} a & b \\ c & d \end{pmatrix}^{-1} = \frac{1}{ad-bc}\begin{pmatrix} d & -b \\ -c & a\end{pmatrix}.$$Imposing $ad-bc=1$ and setting this equal to $$\begin{pmatrix} \overline{a} & \overline{c} \\ \overline{b} & \overline{d}\end{pmatrix}$$gives the desired conclusion.
Answer: You probably forgot the condition $\det=1$. This implies that the inverse of your matrix is $$\begin{bmatrix}
d & -b\\
-c & a
\end{bmatrix}$$ Since that must be equal to $A^T$, you get that this is equal to
\begin{bmatrix}
\bar a  & \bar c  \\
\bar b & \bar d
\end{bmatrix}
So $a=\bar d, \bar c=-b, \bar b=-c$.

Matrices in SU(2)


Option to saving and not saving UTC time in Azure Table

Question: It seems to me that Azure Table always saves UTC time to the table. Even the date type has time zone, e.g. DateTimeOffset.
Is there an option to save original time, instead of UTC time?
Answer:
Is there an option to save original time, instead of UTC time?

If you are looking to save the data as Edm.DateTime, then the answer is no. That data is always stored as UTC.
From this link about Edm.DateTime:

A 64-bit value expressed as Coordinated Universal Time (UTC). The
supported DateTime range begins from 12:00 midnight, January 1, 1601
A.D. (C.E.), UTC. The range ends at December 31, 9999.

One option for you could be to save the local date/time as String type data or convert the local date/time value to ticks and save that as Int64 and then do the conversion in your application.
Comment: Which one is faster by searching by `String` or `Int64`? Is there any reference?


How can I parallelize this Matrix times Vector operation using OpenMP?

Question: I try to parallelise the for loop in the below code, but I am not sure of what type of OpenMP directives should I add before the for loop and do I need to declare those variables in private or public first?
 #include <stdio.h>
 #include <time.h>
 #include <omp.h>

 void mxv_row(int m, int n, double *A, double *B, double *C)
 {
 int i, j;
 # pragma omp parallel private(?)shared (?)
 for (i=0; i<m; i++)
 # pragma omp for
 {
 A[i] = 0.0;
 for (j=0; j<n; j++)
 A[i] += B[i*n+j]*C[j];
 }
 }

Comment: As this is written, a compiler should reject it on account of the pragma omp for not being applied to an individual for().  It looks like you mean to place the omp for on the outer loop.  You might wish to assure that the inner loop is optimized with simd reduction, although a compiler might do this automatically if A[] is declared with restrict *A and an option like gcc -ffast-math is set (and j is local as mentioned in the answer).
Answer: As you declared j outside the loop, it should be private. If you declare it in the second for loop, it's fine then.
The rest can be shared (except i, as it's your parallel loop index), but doesn't have to, as it's only sizes and pointers.


Print only the first 5 lines of a string

Question: I use the conditional statement: if(count(explode(PHP_EOL, $str) > 5) to check if the string have more than 5 lines, but how can I print only first 5 lines of the string?
Answer: Use array_slice
$lines = explode(PHP_EOL, $str);
echo implode(PHP_EOL, array_slice($lines,0,4)) . PHP_EOL;

Answer: When expolode, put the values into an array. Iterate through an array, and add a counter. When counter is 5, get out from iteration.
$lines = explode(PHP_EOL, $str);
$i = 1;
foreach ($lines as $line) {
   echo $line ."\n";
   $i++;
   if ($i >= 5) {
      break;
   }
}

Comment: Whats the problem with the loop? Anyway, yes, `echo $lines[0]; echo $lines[1]; echo $lines[2]; //etc...`
Answer: I guess I'm late, but you can also limit the results of explode to 5:
explode(PHP_EOL, $string, -(count(explode(PHP_EOL, $string )) - 5 ));

Answer: // split lines with new line
$lines = explode(PHP_EOL, $str);

// loop through first five lines
for($i = 0; $i < 5; $++)
{
   // print line
   echo $lines[$i];
}

Comment: This is bad, if there are less than 5 lines you will be in trouble accessing unindexed array elements.


Slight generalization of differentiation so that Re{z} is differentiable in the complex plane?

Question: If I make a small change $\delta z$ to a complex number $z$, then $\mathbb{R}\mathrm{e}\{z\}\rightarrow \mathbb{R}\mathrm{e} \{z+\delta z\} = \mathbb{R}\mathrm{e} \{z\}+\mathbb{R}\mathrm{e} \{\delta z\}$. Differentiation is closely related to finding linear approximations to functions about points. There is no constant $\alpha$ so that $\alpha \delta z=\mathbb{R}\mathrm{e}\{\delta z\}$, so conventionally we would say that no derivative could exist.
However, if I map $z$ to the real-valued vector $\hat z=[\mathrm{Re}\{z\},\mathrm{Im}\{z\}]^T$, then the real-part function becomes the projecting matrix $R=\bigl( \begin{smallmatrix}1 & 0\\ 0 & 0\end{smallmatrix}\bigr)$. Clearly, the derivative with respect to $\hat z$ of $R\hat z$ is $\bigl( \begin{smallmatrix}1 & 0\\ 0 & 0\end{smallmatrix}\bigr)$. This implies that there is something nearby to complex numbers where the derivative of $\mathrm{Re}\{ z\}$ is defined. What am I dealing with here?
Comment: The function $(x,y) \mapsto x$ is differentiable, the function $z \mapsto \operatorname{re} z$ is not. Differentiability with respect to a complex scalar imposes more constraints that differentiability with respect to two real variables. Analytic functions are open maps.
Answer: Consider $\phi:\mathbb R^2\to\mathbb C:(x,y)\mapsto x+iy$ and its inverse $\phi^{-1}:\mathbb C\to\mathbb R^2:z\mapsto(\mathop{\mathrm{Re}}z,\mathop{\mathrm{Im}}z)$.
If $f:\mathbb C\to\mathbb C$ is holomorphic, then $\phi^{-1}\circ f\circ\phi:\mathbb R^2\to\mathbb R^2$ is differentiable and its differential at any point is of the form $\begin{pmatrix}a&-b\\b&a\end{pmatrix}$, but the converse is not true. The function $f=\mathop{\mathrm{Re}}$ provides an example.
Comment: Just a note, the form of the differential makes it look like it belongs in $\mathbb{R}^{2\times 2}$.


como capturo o value deste input quando clico enter no input e sem usar form?

Question: Como capturo o valor deste input quando clico enter no input e sem usar form?
Apresento o input, abaixo representado:
<input id="searchinputid" type="text" class="searchinput"
    name="txtbuscan" placeholder=" Search..." onkeyup="showUser(this.value)"
    autocomplete="off"></input>

Comment: Seu HTML é inválido. A tag input não aceita fechamento. Isso pode fazer com que sua página não se comporte corretamente em todos os navegadores.
Answer: Utilize o keyCode para capturar o enter e recupere o valor do campo chamando a função em algum evento de tecla(keyPress, keyDown ou keyUp).
Ex:
function ObterValor(e) {
   if (e.keyCode == 13) {
     return $("#searchinputid").val();
   }
}

Comment: e como eu conseguiria guardar esse valor numa variável php?
Comment: Você pode fazer um requisição ajax, por exemplo. (http://www.webmaster.pt/requisicoes-ajax-jquery-2216.html)
Answer: Voçe pode usar EventListener para escutar quando uma tecla é pressionada e keyCode para verificar qual é a tecla, e depois XMLHttpRequest para enviar ao php
Como você não disse se usa jquery, segue o exemplo em js puro:

var input_busca = document.querySelector('#searchinputid')//Seleciona a input

input_busca.addEventListener('keypress', function (e) {
    var key = e.which || e.keyCode;
    if (key === 13) { // 13 = verifica se a tecla é o enter, 13 = enter
      alert("Valor local: " + input_busca.value)//Exibe o valor local
      var xhr = new XMLHttpRequest();
      xhr.open('GET', 'get.php?searchinputid=' + input_busca.value, true);// Informações para enviar ao php
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xhr.onload = function () {

          alert("Resposta servidor: " + this.responseText);//Resposta do servidor
      };
      xhr.send();
    }
});
<input id="searchinputid" type="text" class="searchinput"
name="txtbuscan" placeholder=" Search..." autocomplete="off">

Código de exemplo do get.php
<?php

$variavel = $_GET['searchinputid'];

echo $variavel;


How to read a TSV file into pandas dataframe with datetime as the rownames?

Question: >>> data
                  Open
Date
2020-06-15  182.809924
2020-06-16  191.040258
2020-06-17  193.159706
2020-06-18  192.139603
2020-06-19  196.685578
...                ...         ...         ...         ...       ...        ...           ...
2021-06-08  255.160004
2021-06-09  253.809998
2021-06-10  254.289993
2021-06-11  257.989990
2021-06-14  257.899994

[252 rows x 1 columns]
>>> data['Open']
Date
2020-06-15    182.809924
2020-06-16    191.040258
2020-06-17    193.159706
2020-06-18    192.139603
2020-06-19    196.685578
                 ...
2021-06-08    255.160004
2021-06-09    253.809998
2021-06-10    254.289993
2021-06-11    257.989990
2021-06-14    257.899994
Name: Open, Length: 252, dtype: float64
>>> data.index
DatetimeIndex(['2020-06-15', '2020-06-16', '2020-06-17', '2020-06-18',
               '2020-06-19', '2020-06-22', '2020-06-23', '2020-06-24',
               '2020-06-25', '2020-06-26',
               ...
               '2021-06-01', '2021-06-02', '2021-06-03', '2021-06-04',
               '2021-06-07', '2021-06-08', '2021-06-09', '2021-06-10',
               '2021-06-11', '2021-06-14'],
              dtype='datetime64[ns]', name='Date', length=252, freq=None)
>>> type(data)
<class 'pandas.core.frame.DataFrame'>

I have the above data already in python.
If I have the input data in TSV format, how to read it so that it is the same as above? (<TAB> is a TAB character.)
Date<TAB>Open
2020-06-15<TAB>182.809924
...
2021-06-14<TAB>257.899994

Answer: You can use read_csv() with \t as the delimiter:
data = pd.read_csv('data.tsv', sep='\t', parse_dates=['Date'], index_col='Date')

#                   Open
# Date
# 2020-06-15  182.809924
# ...                ...
# 2021-06-14  257.899994

data.index

# DatetimeIndex(['2020-06-15', '2021-06-14'], dtype='datetime64[ns]', name='Date', freq=None)


How to integrate these: $\iiiint_A\frac{t^2dtdxdydz}{t^2+2x^2+3y^2+4z^2}$ and another one in wolfram alpha?

Question: I tried different methods but I cannot put following integrals into Wolfram Alpha in order to find ou results.
$$
\iiiint_A\frac{t^2\,dt\,dx\,dy\,dz}{t^2+2x^2+3y^2+4z^2},
$$
where $A=\{(t,x,y,z): t^2+2x^2+3y^2+4z^2<1\}$
and $$\iiiint r^5\sin^2(\alpha_3)\cos(\alpha_2)\cos^2(\alpha_3)\,dr\,d\alpha_1\,d\alpha_2\,d\alpha_3,$$
 where $r\in(0,1), ~\alpha_1\in(0,2\pi); ~\alpha_2,\alpha_3\in(-\pi/2,\pi/2)$.
Thank you for help.
Comment: You need to find the right coordinates to describe $A$
Comment: elliptical coordinates will do the job
Comment: @Masacroso No, I want to integrate once over $A$.
Comment: Is in not possible to integrate in wolfram alpha without setting cooridantes first?
Comment: @SekstusEmpiryk I think that it is best that you ask this question [here](http://mathematica.stackexchange.com/) and after use the wolfram language in wolfram alpha or in [wolfram programming lab](https://lab.open.wolframcloud.com/app/).
Comment: Integrate over region
Answer: I don\t know if it works in Wolfram Alpha, but in Mathematica the second integral can be calculated by

Integrate[
  r^5 Sin^2 (x) Cos (y) Cos^2 (z), {r, 0, 1}, {x, 0, 2 Pi}, {y, -Pi/2,
   Pi/2}, {z, -Pi/2, Pi/2}]

(But is also easy to see that this integral vanishes)
For the first integral, I dont know how to do it directly, but if you use coordinate transformations $x\to \frac 1 {\sqrt{2}} x$, $y \to \frac {1} {\sqrt {3}} y$, $z \to \frac 1 {\sqrt4} z$, then $A\to B_1(0)$ and you can use polar coordinates for $\mathbb{R}^4$ and use the same syntax as for the second example.
Comment: You mean rather $x\to \frac{1}{\sqrt 2} x$ and so on, right?
Comment: yes, i will fix it
Answer: Through the substitutions $t=a,\; x=\frac{1}{\sqrt{2}}b,\; y=\frac{1}{\sqrt{3}}c,\; z=\frac{1}{2}d $ and symmetry the given integral boils down to:
$$ \frac{1}{2\sqrt{6}}\iiiint_{a^2+b^2+c^2+d^2<1}\frac{a^2}{a^2+b^2+c^2+d^2}\,d\mu\\ = \frac{1}{8\sqrt{6}}\iiiint_{a^2+b^2+c^2+d^2<1}\frac{a^2+b^2+c^2+d^2}{a^2+b^2+c^2+d^2}\,d\mu$$
and that is just $\frac{1}{8\sqrt{6}}$ times the (hyper-)volume of the unit sphere in $\mathbb{R}^4$, i.e. $\large\color{red}{\frac{\pi^2}{16\sqrt{6}}}$.


Math puzzle not that hard but i cant find what am i missing

Question: The braking distance for a truck with the speed measured in km/h is $\frac{v^2}
{100}$ meters, the
"reaction distance" (distance driven during the reaction time) is about $\frac v 4$. For save driving,
the distance between one truck driving behind another truck should be at least the sum of the
braking distance and the reaction distance. At which speed will a convoy of trucks have the
highest number of trucks passing a point along the road (within a time unit)?
Comment: Please edit to include your efforts.  And for clarity:  is $v_2=v$?  Or was $v2$ meant to denote $v^2$?
Comment: I don't think you can work this problem without knowing the length of a truck.  Or making some assumptions.
Comment: İt is v^2 sory.
Comment: Actually its basically asking the min of save driving distance. and the lenght of the road is infinite or not mentioned so you dont need the lenght of the truck
Comment: Think that i didnt understand is what is it mean with the "within a time unit"
Comment: İs it askin the max number of trucks who passes in the 1 unit time.so if the number of the trucks is N each speed of the trucks is 1/N am ı correct
Comment: The time unit doesn't matter, nor does the length of a truck, just assign values.
Comment: If one truck is a mile long, I think your answer will be different than if one truck is an inch long.
Comment: @B.Goddard  As I understand the problem, the length of a truck is irrelevant.  The optimal gap should be independent of that.  True, the actual number of trucks that pass in a given time interval will depend on the length, but the gap should not.
Comment: The problem is i it just simply asking the min(v^2/100+v/4)but its can be infinitly small
Comment: Small distance more trucks
Comment: @Creedance  Yes, but if $v=0$ then no trucks at all pass a point in a given interval, so that's not optimal.
Comment: First do it for points (assuming a truck is a point).  At speed $v$, how many points pass in an hour (assuming they all maintain safe distance).  Now optimize that number in terms of $v$.  Then, to check @B.Goddard's issue, assume that the "points" have length $L$ and repeat the calculations.  I think the optimal $v$ should be the same but it is definitely worth checking.
Comment: So what is the min of the V.actually this question is from the CAS intelligent scale test so the answer may can be the "smallest vlaue of the given sum"
Comment: @B.Goddard  Counter to my intuition, the length of the truck definitely does matter.
Answer: Min Distance between truck d = $\frac{v^2}{100}+\frac v 4$
Min Time between two trucks t = $\frac{v}{100}+\frac 1 4$
Then min time will achieve with v=0 and every $\frac 1 4$h (reaction distance $\frac v 4$ km? The coefficient may need to be adjusted).
This solution v=0 is stupid. That means infinity trucks are packed together in unit distance, which is impossible. Why?
So we need a truck length term.
Min Distance between truck = $\frac{v^2}{100}+\frac v 4+a$
Min Time between two trucks t = $\frac{v}{100}+\frac 1 4+ \frac a v$
Then find $\frac{dt}{dv}=0$, we have $v=10\sqrt a$ and Min Time = $\frac{\sqrt a}{5}+\frac1 4$
Answer: The formula for the safe driving distance should be $d_s(v)=\frac{v^2}{100}+\frac{v}{4}$.
Then the distance between the front of the trucks should be $d =d_v+l$ with $l$ being the length of one truck.
Then the formula of trucks passing per second (if you convert the velocity to m/s and the distance to m) is $\frac{d}{v}=\frac{\frac{v^2}{100}+\frac{v}{4}+l}{v}$ and then you need to find the minimum of this function.
Comment: Ok thx but can v equal to one there is nothing about v cant be fraction


Combining data from multiple rows into one

Question: First question on here, so i will try my best to be clear.
I have 2 tables:

"TABLE1" which contains a record for each stock code and a list of attributes.
In TABLE 1 there is just one record for each stock_code
"TABLE2" which contains a log of changes to attributes of products, over time.

"TABLE2" contains the following fields:.

stock_code
stock_attribute
old_value
new_value
change_date
change_time

TABLE 2 has multiple entries ofr each stock_code.
Every time a stock item is change, another entry is made in Table2, with the attribute that has changed, the change date, time, old value and new value.
I want to create a query which will result in a table that has one record for each stock_code (from TABLE 1),  and a column for each week over past year, with the value in each field being the last recorded "new_val" for that week (From TABLE 2)
I have tried
SELECT a.`stcode`, b.`week1`, b.`week2`, b.`week3`, b.`week4` etc. etc.
 from (SELECT stcode, )as a
 LEFT JOIN (SELECT stcode,
(CASE WHEN chngdate BETWEEN DATE_SUB(CURDATE(),INTERVAL 363 DAY)  AND DATE_SUB(CURDATE(),INTERVAL 357 DAY)  THEN newval END)week1,
(CASE WHEN chngdate BETWEEN DATE_SUB(CURDATE(),INTERVAL 356 DAY)  AND DATE_SUB(CURDATE(),INTERVAL 350 DAY)  THEN newval END)week2,
(CASE WHEN chngdate BETWEEN DATE_SUB(CURDATE(),INTERVAL 349 DAY)  AND DATE_SUB(CURDATE(),INTERVAL 343 DAY)  THEN newval END)week3,
(CASE WHEN chngdate BETWEEN DATE_SUB(CURDATE(),INTERVAL 342 DAY)  AND DATE_SUB(CURDATE(),INTERVAL 336 DAY)  THEN newval END)week4,
(etc
etc
etc

    FROM (SELECT * from TABLE 2  ORDER BY "chngdate" DESC, "chngtime" DESC )as sub) as b ON b.stcode = s.stcode
ORDER BY stcode ASC

The trouble is with this, i get multiple lines for a stock_code which has mutliple entries....
for example, for stock_code abc123 the result i get is
STCODE       WEEK1     WEEK2     WEEK3      WEEK4      WEEK5     WEEK6
abc123        null      null       4         null      null       null
abc123        2         null       null      null      null       null
abc123        null      null       null      null      3          null

what i WANT is this:
STCODE       WEEK1     WEEK2     WEEK3      WEEK4      WEEK5     WEEK6
abc123        2         null       4         null      3        null

I have also tried the following, but teh query took so long, it never finished (there were 52 derived tables!)
SELECT a.`stcode`, w1.`new_value`, w2.`new_value`, w3.`new_value`, w4.`new_value` etc. etc.
 from (SELECT stcode, )as a
 LEFT JOIN (SELECT stcode,
LEFT JOIN (SELECT stcode, depot, fieldname, chngdate, chngtime, newval from STDepotAmendmentsLog WHERE chngdate BETWEEN DATE_SUB(CURDATE(),INTERVAL 363 DAY)  AND DATE_SUB(CURDATE(),INTERVAL 357 DAY)  ORDER BY "chngdate" DESC, "chngtime" DESC)as w1 on s.stcode = w1.stcode
etc for week 2, 3, 4 etc etc

Comment: *The trouble is with this, i get multiple lines for a stock_code which has mutliple entries....* You need `GROUP BY stcode`, and wrap all pivot fields into some aggregate fulction (for example, `MAX()`).
Comment: Seriously consider handling issues of data display in application code
Comment: What happens if there are two entries for a particular week?
Comment: ... and specify your MySQL server version.
Comment: If there are 2 entries for a articluar week, I need the one with most recent date and time (i.e. the last entry for that week.)    That's why i ordered by change_date DESC and change_time DESC, in hopes that i could select the first record within that week
Comment: MAX aggregate would need to work on change_date and change_time field, I think.
Answer: You could do the following:

Find the greatest date for each "week"
Find the rows corresponding to those dates
Use conditional aggregation to convert rows into columns

Here is a rough outline of the code. It assumes that e.g. if today is 2020-03-03 then week 52 is from 2020-02-26 to 2020-03-03. Adjust if necessary:
SELECT t.stock_code
     , MAX(CASE WHEN weeknum = 51 THEN new_value END) AS week01
     , MAX(CASE WHEN weeknum = 50 THEN new_value END) AS week02
     , MAX(CASE WHEN weeknum =  1 THEN new_value END) AS week51
     , MAX(CASE WHEN weeknum =  0 THEN new_value END) AS week52
FROM table2 AS t
JOIN (
    SELECT stock_code
         , DATEDIFF(CURRENT_DATE, change_date) div 7 AS weeknum -- count multiples of 7
         , MAX(change_date) AS greatest_date
    GROUP BY stock_code, weeknum
    FROM table2
)  AS a ON t.stock_code = a.stock_code AND t.change_date = a.greatest_date
GROUP BY t.stock_code