GStreamer/iMX6: streaming h264 encoded video over serial port between iMX6 and PC

Question: Recently, I have started to work on a project that aims at live video streaming applications based on imx6 processors. A quick description of what I have done so far and what I am trying to do:

Setup: imx6 board(Boundary devices Sabre Lite) acting as the video server(using GStreamer imx plugins), and a PC running Ubuntu on it that receives data from imx6 and streams the video using GStreamer features.
On the imx6 processor, I run the 'testvideosrc' and have successfully streamed it using the RTP over UDP using eternet interface between the imx6 and the PC.
Accessing the serial port using the device files in Linux, next I tried out dumping the video data from imx6 board to a serial port and reading this serial port on the PC. For this, the baud rate of both devices was configured to 115200 baud. The encoding 'bitrate' is configured to 5Kbps. Here are the commands:

IMX6:
#gst-launch-1.0 -v videotestsrc pattern=18 ! video/x- raw,width=100,height=50 ! imxvpuenc_h264 bitrate=5 ! h264parse ! filesink location=/dev/ttyUSB1

PC:
#CAPS=video/x-h264
#gst-launch-1.0 -v filesrc location=/dev/ttyUSB1 ! $CAPS ! h264parse ! avdec_h264 ! autovideosink sync=true

There are no errors observed on the imx6 board.
However, I see the following errors at the PC side:
# GST_DEBUG=3 gst-launch-1.0 -v filesrc location=/dev/ttyUSB1 ! $CAPS ! h264parse ! avdec_h264 ! autovideosink sync=true
  Setting pipeline to PAUSED …
  0:00:00.066439392 15475 0x556d8a01d160 WARN basesrc gstbasesrc.c:3583:gst_base_src_start_complete: pad not activated yet
  Pipeline is PREROLLING …
  0:00:21.730466251 15475 0x556d8a000940 WARN capsfilter
  gstcapsfilter.c:455:gst_capsfilter_prepare_buf: error: Filter caps do not completely specify the output format
  0:00:21.730523691 15475 0x556d8a000940 WARN capsfilter gstcapsfilter.c:455:gst_capsfilter_prepare_buf: error: Output caps are unfixed: video/x-h264, width=(int)[ 1, 8192 ], height=(int)[ 1, 8192 ], framerate=(fraction)[ 0/1, 2147483647/1 ]
  0:00:21.730676173 15475 0x556d8a000940 WARN basetransform gstbasetransform.c:2159:default_generate_output: could not get buffer from pool: error
  0:00:21.730742223 15475 0x556d8a000940 WARN basesrc gstbasesrc.c:3055:gst_base_src_loop: error: Internal data stream error.
  0:00:21.730775478 15475 0x556d8a000940 WARN basesrc gstbasesrc.c:3055:gst_base_src_loop: error: streaming stopped, reason error (-5)
  ERROR: from element /GstPipeline:pipeline0/GstCapsFilter:capsfilter0: Filter caps do not completely specify the output format
  Additional debug info:
  gstcapsfilter.c(455): gst_capsfilter_prepare_buf (): /GstPipeline:pipeline0/GstCapsFilter:capsfilter0:
  Output caps are unfixed: video/x-h264, width=(int)[ 1, 8192 ], height=(int)[ 1, 8192 ], framerate=(fraction)[ 0/1, 2147483647/1 ]
  ERROR: pipeline doesn't want to preroll.
  Setting pipeline to NULL …
  Freeing pipeline …

Since, the encoding rate is 5Kbps (bitrate=5, as specified in the above command), I suppose it is possible to send this amount of data via the serial port. I realize that currently, the caps negotiation fails, however, I am unsure of how to proceed with this.
On the PC side, reading the serial port with 'cat /dev/ttyUSB1' succeeds with limited data. The data is unreadable(as expected), however it is not a continuous stream.

Does anyone have an idea, on how to solve this. I also think, I am misinterpreting the usage of Linux device files, when I am attempting to read over the serial data file using GStreamer.
My later test, would be to use an actual camera(MIPI) and try streaming it over serial port. Does it seem feasible or is a completely crazy idea to do?
Comment: The above issue was resolved using the following: `CAPS=video/x-h264,width=100,height=50,framerate=30/1`
Comment: However, at the PC side, the GStreamer does not display any video. I had expected to see a window popup and display the videotestsrc pattern, hoiwever it is not the case.I have tried with different bitrates(1,5,10,50) and the result is same. Does anyone have any more suggestions as to how I can proceed with this.
Answer: With the following commands, I could get this working on serial with a baud of 19200. However, the latency is very high in the range of 5-6 seconds. With a baud of 1M, it works with less noticeable latency < 1s.
imx6:
gst-launch-1.0 -v videotestsrc pattern=18 ! video/x-raw,width=100,height=50
! imxvpuenc_h264 bitrate=5 ! h264parse ! filesink location=/dev/ttyUSB0
blocksize=1024 max-bitrate=19000 sync=false

PC:
gst-launch-1.0 -v filesrc location=/dev/ttyUSB1 blocksize=1024 ! $CAPS !
h264parse ! avdec_h264 lowres=2 skip-frame=0 ! autovideosink sync=false


About $n$-th differentiability

Question: For real function we can use MVT to show that if it is $n$-th differentiable at a point $x_0$ then it can be estimate by an degree $n$ polynomial with error term of $o((x-x_0)^n)$.
Similarly, if we are given an complex function that is $n$-th (complex) differentiable on a point $z_0$ (and not sure about its analycity), then is it true that it can be estimate by an degree $n$ polynomial with error term of $o((z-z_0)^n)$?
In other word, is it true that the function is of such form?
$c_0+c_1(z-z_0)+...+c_n(z-z_0)^n+e(z-z_0)$ where $e\in o(z^n)$
Comment: What do you mean by differentiable? Differentiable as a function of two real variables? Or $\mathbb C$ differentiable ?
Comment: In the real case, using MVT we can prove a stronger statement: $\text{error}=O((x-x_0)^{n+1})$ (this form is called Lagrange's form, while the one you used is Peano's form)
Comment: @mathcounterexamples.net It's complex differentiable. I've edit my question.
Comment: @gabrielecassese I can see that it is true for the real case, but I'm wondering if this is also true for a complex function.
Comment: Oops, I thought Lagrange's form would require $n+1$-th differentiable.
Comment: @TaylorHuang It depends in which form do you give to MVT. In its classical forms, i.e.: $f(z+h)-f(z_0)=f'(z)h$, then you can easily give a counterexample considering: $f=e^{ix}\rightarrow f(2\pi)-f(0)=0\neq f'(z)(2\pi-0)$
About Lagrange's form: it does not require $f\in C^{n+1}(x_0)$, but it does require the function to be $n$ differentiable in a open neighborough of $x_0$
Answer: For $n=1$, the result is true by definition of $\mathbb C$-differentiability.
And for $n \ge 2$, the hypothesis of $f$ being $n$ times $\mathbb C$-differentiable at $z_0$ implies by definition that $f$ is $n-1$ times $\mathbb C$-differentiable in a neighborhood of $z_0$. Hence $f$ is holomorphic around $z_0$. Therefore $f$ can be written as a power series. And it can be approximated with a polynomial to any order.
Comment: I think you might miss cases that $f$ is complex differentiable only at some boundary point. Because we are only given $f$ differentiable at some point rather then in its neighbor or some domain.
Comment: @TaylorHuang I update my answer.

About $n$-th differentiability


VMplayer Virtual Disk Shrinking/Compacting/Defragmenting

Question: I am using VMplayer on Windows 7 and 2008 R2.  Inside the guest OS, in VMware tools, there is a "Prepare to shrink" option on the "Shrink" tab.  In the host VMplayer menu there is     "Defragment" and "Compact" options (available when the VM is shut down).  VMplayer documentation says you should also defragment using an OS based defragment tool within the guest and outside the VM in the host.  That leaves five operations:

defragment within the VM using OS defragmenter.
shrink within the VM using VMtools
defragment outside the VM in the host using OS defragmenter
defragment in the host using VMplayer settings menu.
compact in the host using VMplayer settings menu.

My question is this.  Which of these operations are required and in exactly what order should they be performed?
Comment: If you plan to compress the compacted vm into archive then [disk zeroing](https://serverfault.com/questions/165070/how-to-zero-fill-a-virtual-disks-free-space-on-windows-for-better-compression) would increase compression ratio.
Answer: First, please realize you don't have to do this maintenance very frequently. If you want to go through the full list, here's the order and rationale.

Defragment within the VM (if the machine is thin-provisioned, defragmenting later will expand the .vmdk as blocks are moved)
Shrink the disks within the VM (this writes zeroes to unused sectors so the host can recognize which blocks are unused). This will temporarily increase the VMDK size to the configured size of the virtual disk. Then power off the VM.
Defragment the disks from within VMware Player. This will move the blocks in the VMDK from their chaotic state (due to growth/use) and order them by actual block number.
Compact the disks from within VMware Player. Since the empty blocks are zeroed, VMware can remove those blocks from the VMDK and reclaim space on the host.
Defragment the host system to reorder all host files (including the VMDK) and remove fragments.
Comment: Somehow it is not working for me. I'm using VMware Player 6.0.1 and have Windows 7 virtual machine. While guest OS reports 5GB of 20GB free the size of virtual hard drive is still 20GB in host OS even after all steps above. What could it be?
Answer: On newer versions of VMWare Player, this should work:
VMTools ui don't exist so do the shrink in an (elevated) cmd prompt:
cd "C:\Program Files\VMWare\VMTools"
VMwareToolboxCmd.exe disk shrink c:\

Comment: This really helped instead of useless VMware Workstation Player 12.5.7 GUI.


Given $c =\sqrt {a^2-b^2}$, $c= ea$, conclude that $\frac {2\pi ab}{(a+c)T} =\frac {2\pi a}T\sqrt {\frac {1-e}{1+e}}$

Question: Given $c =\sqrt {a^2-b^2}$, $c= ea$, conclude that $$\frac {2\pi ab}{(a+c)T} =\frac {2\pi a}T\sqrt {\frac
{1-e}{1+e}}$$
Sorry for the awful formatting of this question. I know this is a pretty simple problem, but for some reason I cannot figure it out. The furthest I have gotten is reducing the b in the numerator to $\sqrt {a^2(1-e)}$, but then I get stuck. I appreciate any help I can get. Thanks in advance.
Comment: @Pythagoras yes, thank you for catching that.
Comment: Read [this](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for introduction to $\LaTeX$. Skip the introduction of [this](https://math-on-quora.surge.sh) (because the introduction is different and does not apply to this site, rest is same).
Comment: I reformatted your post, please check to see that I didn't introduce any errors.  [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a good tutorial on formatting for this site.
Comment: To your question:  As a first step you should make the obvious cancellations.  Why leave the expression with so many cancellable terms?
Comment: typo? why $c$ is assigned 2 values.
Comment: Specific question:  I have no idea whether you intended what I wrote for the square root term on the right or if you intended $\sqrt {\frac {1-e}{1+e}}$.  I just guessed...what you wrote was ambiguous.
Comment: Your formulas are inconsistent. Do you mean $c=\sqrt{a^2-b^2}$?
Answer: Since $\;c =\sqrt {a^2-b^2},\;$ we get $\;b=\sqrt {a^2-c^2}$.
Moreover,
$$\frac {2\pi ab}{(a+c)T} =\frac{2\pi a\sqrt{a^2-c^2}}{T(a+c)}=\frac{2\pi a}T\sqrt{\frac
{(a+c)(a-c)}{(a+c)^2}}=\frac{2\pi a}T\sqrt{\frac
{a-c}{a+c}}=\frac{2\pi a}T\sqrt{\frac
{a-ea}{a+ea}}=\frac{2\pi a}T\sqrt{\frac
{a(1-e)}{a(1+e)}}=\frac{2\pi a}T\sqrt{\frac
{1-e}{1+e}}.$$


Do I need to remove Load, Form_Closing event handlers when the form is being closed to prevent memory leak?

Question: I am developing a big WinForm application and experiencing some memory leaks. One of the problems was closing the form did not free up memory (I used .NET Memory Profiler). Some people suggested that event handlers should be removed from the form manually to prevent memory leaks. Does it mean I need to remove Load, Form_Closing event handlers that were created by the designer when the form is being closed? I am using .NET 4.5. Thank you!
Answer: No.  The concern with event handlers is that the object that executes the handler is referenced by the object with the method, meaning that if the object that fires the event will end up living for a lot longer than the object with the handler that the object with the handler cannot be cleaned up.
There is no issue at all with the object firing the event having a much shorter lifetime than the object handling the event, because the object handling the event doesn't have a reference to the object firing the event.


How to find a matrix for linear transformation?

Question: $T: \mathbb R^2[x] \to \mathbb R^2[x]$ is given with the regulation: $(Tp)(x) = (xp(x))'$
If $q(x) = 1 - x + x^2$, what is T*(q)?
I don't understand what the left side of the regulation means and how to get a matrix from the regulation, also I apologize for the poor formatting.
Edit: The asterisk sign should be above T in the question with q, as in adjugate matrix.
Comment: Why do you need to construct a matrix?  Just multiply by $x$ and take the derivative.
Answer: Hint
The transformation $T$ is acting on the polynomial $p(x)$ to give the output as the derivative of $xp(x)$. For example, $T(x)=\frac{d}{dx}(x^2)=2x$ and so on.
To get the matrix you should determine the behavior of the transformation $T$ on a basis like $\{1,x,x^2\}$.
Comment: Well it changes 1 to 1, x to 2x and x^2 to 3x^2 but I dont know how that helps me get the matrix T
Comment: @KristjanGajšek if you want to compute $T(q(x))=T(1-x+x^2)$, then as Bye-World pointed in the comments, you don't need the matrix. You can simply use linearity to get $T(1-x+x^2)=T(1)-T(x)+T(x^2)=1-2x+3x^2$ and you are done.
Comment: @KristjanGajšek but if you insist on a matrix then think of $x$ as the vector $(0,1,0)$. This gives $T((0,1,0))=(0,2,0)$, likewise think of other polynomials and you can get the matrix based on that.
Comment: Okay, I get it now, thank you very much!


Should we ask for MathJax to use escaped dollar signs as delimiters?

Question: We currently use dollar signs as delimiters, which means that if we want to use real dollar signs, we have to escape them.  Code Review and Electrical Engineering use escaped dollar signs as delimiters.  Should we do this as well?
Code Review discussion here.
Sorry it took me so long to look this up.  I should have been more aggressive when I first realized that we were doing it the other way.
<code>$ dollar sign delimiter $

\$ escaped dollar sign delimiter \$
</code>
Outputs
$ dollar sign delimiter $
\$ escaped dollar sign delimiter \$
I can see at least one question where it looks like the author wrote out "dollar sign" because it was not obvious how to get the symbol to output properly.
Answer: I think we should keep using the dollar sign. As common as it is in economics, I believe it is not that common when discussing economic models. Much more common is to use mathematics without the dollar sign and keeping it as a math delimiter allows us to copy equations directly from $\LaTeX$ or writing them using the acquired muscle memory.
Nevertheless, @Brythan's point is still valid and in the end I don't believe it makes such a huge difference either way.
Comment: (+1) for the point regarding compatibility with \LaTeX.
Comment: Yeah, the dollar sign is not used that much in academic economics. I'm not sure I've even seen it in an academic article.
Answer: Keep as is
We need much more often the Mathjax-operator than the currency denominator. It's much more efficient to have the dollar sign be the operator. Of course, this will hurt beginners, but it's something they will observe once and then apply. Also, this gives some free edits for the badges ;)
I think the efficiency gain is worth the entry barrier.
Comment: (+1) ...which goes to show that perfect competition is not always the ideal framework.
Answer: In my opinion, we should make this change.  A dollar sign is a common symbol here.  We talk about currencies a lot; this is an English speaking site; the largest English speaking country uses a dollar sign as the currency symbol.
We should take this hit (it requires editing existing questions) as soon as possible.
It makes more sense to make MathJax support a little harder than to make using a dollar sign harder for everyone who has to do it.


Is there a graceful way to use os.path.join() when the right-hand side may be /-prefixed?

Question: In the code below, context._arguments['ConfigFile'] returns a string like '/path/file.py' (which I can't change) but due to the way os.path.join() works, I need to remove at bare minimum the first /.
Note: In my use case __file__ will always be in the appropriate position away from the config file.
I also considered giving it context._arguments['ConfigFile'][1:] but I think it's less robust.
config_file = os.path.join(
  os.path.dirname(os.path.abspath(__file__)),
  *context._arguments['ConfigFile'].split(os.path.sep))

I expected there to be something a little more graceful, but maybe handling paths just never is. I am using Python 2.7 but for completeness I'm open to hearing Python 3 answers.
Comment: Have you considered `'./' + context._arguments['ConfigFile']` as the right-hand argument?
Comment: Not sure what happens on Windows, but `'.' + os.path.sep + path` neuters leading `/` on others.
Comment: (shouldn't actually need to use `os.path.sep` when generating paths to be consumed by other `os.path` functions; Python honors `/` even on Windows, so it's generating paths for use external to the Python interpreter where the distinction matters).
Comment: Do you use Python 2 or 3?
Comment: @CharlesDuffy: I avoid Windows, but out of morbid curiosity, what does Python do in `os.path.join` with paths that start with `'C:'`?
Comment: `/path/file.py` is technically an absolute path and join is meaningless in that case. So I don't think there is a more graceful way than what you are already doing.
Comment: I am using Python 2 @DariusMorawiec and I will look into the usage of ./ of __file__ that's a good point. More about the unpacking the split of the ```/path/file.py```is what I think is really gross
Comment: @torek, I don't have a Windows box handy (it's been a long while since I gained familiarity with the above-referenced behavior), but looking at `ntpath.py` from the standard library of Python 2.7.15, it looks like there's a `splitdrive()` function used to identify the drive subset of the path, and `join()` calls that function and honors any drive letter returned thereby, thus treating paths that specify them an absolute.
Comment: Also @torek it seems that the ```'/path/file.py'``` seems to still destroy the``` '.' + os.path.sep``` maybe that is what you meant when you said it neuters it?
Answer: If you use Python 3, you can benefit from the pathlib package:
from pathlib import Path

file_path = '/path/file.py'

config_file = Path(__file__).parent / file_path.lstrip('/')

print(config_file)
# /Users/darius/repos/stackoverflow/questions/path/file.py

If you use Python 2, you can install pathlib2 (pip install pathlib2) which is a backport of the standard pathlib package. To match the module names you can rename the import with import pathlib2 as pathlib.
Answer: (This is a response to a comment, really, but needs formatting.)
>>> os.path.join('/a', '/b/c')
'/b/c'
>>> os.path.join('/a', './/b/c')
'/a/.//b/c'

Use os.path.normpath to clean up:
>>> os.path.normpath(os.path.join('/a', './/b/c'))
'/a/b/c'

The other way to view this is that, at least on Unix systems, os.path.join starts with its first argument.  Then, for each additional argument, it either concatenates or replaces using the return-value-so-far and the extra path component:
def unix_style_join(*args):
    "low quality version, for illustration"
    ret = args[0]
    for extra in args[1:]:
        if extra.startswith('/'):
            ret = extra
        else:
            ret = ret + '/' + extra
    return ret

Since your problem is that context._arguments['ConfigFile'] starts with /, we merely need a variant of context._arguments['ConfigFile'] that means the same thing but does not start with / ... and ./<whatever> means the same as <whatever> except that ./<whatever> starts with ., even if <whatever> starts with /.
The reason I didn't suggest this as the whole answer is that I have no idea how this all works on Windows.


How do you tell if the last value in a list repeats previously?

Question: I.E
Value = [1,2,3,4,5,1]

How do I tell if that one in the beginning repeats at the end. I figured out a somewhat fool proof way but it does not work when ever I plug in a single value instead of them being next to each other.
def last_repeats(list):
  for i in range(1, len(list)):
    if list[i] == list[-1]:
      return True
    else:
      return False
def main():
  last_repeats(list)

############################################
### Don't edit anything below this line. ###
############################################

if __name__ == '__main__':
  main()

Comment: Instead of pasting your code as a comment, please [edit] your code into your question :)
Comment: Also, your question is unclear. Do you mean if the first and last values are equal, or if the last value appears in the rest of the list? Please clarify, your example and code are contradictory.
Comment: forgot to add my code...
Answer: A general way:
if Value[-1] in Value[:-1]:
    # ...

This proves if the last value appears somewhere earlier in the list.
Answer: you can use:
Value[0] == Value[-1]

to check if the first value and the last value are the same

How do you tell if the last value in a list repeats previously?

Value[-1] in Value[:-1]

Answer: you can use Value[-1] to check it denotes the last elements of the list.
if Value[0] == Value[-1]:
    #Do something

Answer: O(1) space and best case O(1) time:
>>> it = reversed(Value)
>>> next(it) in it
True


A sintaxe do Meteor mudou da versão 0.8 para a versão 1.0?

Question: Dentre as diversas mudanças no Framework Meteor da versão 0.8 para a versão 1.0, sei que ele não mais utiliza o Meteorite, e que a engine de template mudou da Handlebars para Blaze. Mas a sintaxe mudou? E mais o que mudou?
Comment: Talvez isso ajude: https://github.com/meteor/meteor/blob/devel/History.md

Ai tem todo o histórico de mudanças ate a presente versão(V22.214.171.124)
Comment: Parece que houve mudanças de API sim: https://github.com/meteor/meteor/blob/devel/History.md#api-changes
Answer: Sim a sintaxe do Meteor mudou em alguns pontos, por exemplo:
Antes da versão 1.0 a definição dos helpers era assim:
Template.leaderboard.player = function(){
    // code goes here
}

Template.leaderboard.goals = function(){
    // code goes here
}

Com a mudança ficou assim:
Template.leaderboard.helpers({
   'players': function(){
      // code goes here
    },
    'goals': function(){
      // code goes here
    }
});

Tambem ouve mudança no created, rendered e destroyed:
O que antes era assim:
Template.leaderboard.created = function(){

}

Acima de 1.0 ficou assim:
Template.leaderboard.onCreated({

});

Acompanhe as mudanças que ocorreram aqui nesse link:
https://github.com/meteor/meteor/blob/devel/History.md#api-changes
esse link talvez possa ajudar tb:
https://forums.meteor.com/t/about-oncreated-onrendered-ondestroyed-and-helpers/165


Generic argument

Question: I would like to create an Java interface with a method that accepts all subtypes of a type:
interface A{};

interface B{
  void method(A a);
}

What I want to accomplish is to make an implementation of the method(A a) accept
all subtypes of A (like return type polymorphism but with an argument).
Is this even possible?
Comment: It already accepts all subtypes of `A`.
Comment: Your current method will indeed accept all subtypes of `A`.
Answer: You've already done it!
To prove it, try something like this:
public class ThisA implements A {}
public class ThatA implements A {}
public class OtherA implements A {}
public class SubclassA extends OtherA {}

then call your method:
B b = new B {
  public void method(A a) {
    System.out.println("Called with "+a);
  }
}

b.method(new ThisA());
b.method(new ThatA());
b.method(new OtherA());
b.method(new SubclassA());

Generic argument


JHipster spring controller with microservices

Question: I have a JHipster gateway+microservice application. I have added a spring service with jhipster spring-controller and then edited the code like this:
@RestController
@RequestMapping("/api/data")
public class DataResource {

    /**
    * GET vin
    */
    @GetMapping("/vin")
    public ResponseEntity<Object> vin(@Valid @RequestBody String address) {
        Chart3DataDTO[] data=new Chart3DataDTO[15];
        for (int i=0;i<15;i++){
            data[i]=new Chart3DataDTO(System.currentTimeMillis()+i, 200+i, 201+i, 202+i);
        }
        return ResponseEntity.ok(data);
    }

For completeness, this is the DTO
public class Chart3DataDTO {

    private Long xAxis;
    private Integer[] yAxis=new Integer[3];

    public Chart3DataDTO(Long xAxis, Integer yAxis1, Integer yAxis2, Integer yAxis3) {
        this.xAxis = xAxis;
        this.yAxis = new Integer[]{yAxis1, yAxis2, yAxis3};
    }

    public Long getxAxis() {
        return xAxis;
    }

    public Integer[] getyAxis() {
        return yAxis;
    }
}

Then I have dockerized gateway and microservice, jhipster docker-compose and started all. Everything works but when the Angular frontent asks for /api/data/vin I get:

if not logged in: 401 (which is fine)
if logged in: the JHipster page 'an error has occurred', instead of returning the JSON of the DTO

What did I miss?
Also, it doesn't appear listed on the Jhipster registry API
2ND EDIT: Added client angular code
import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':'*'

  })
};
//const apiUrl = 'api/vin';
const apiUrl = '/api/data/vin';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) {}
  /*
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
*/
  getInputVoltage(address: String): Observable<[]> {
    return this.http.get<[]>(`${apiUrl}` + '?address=' + address,httpOptions);
  }
}

And
import { Component, OnInit } from '@angular/core';
import * as Highcharts from 'highcharts';
import { ApiService } from '../api.service';

@Component({
  selector: 'jhi-device-graph',
  templateUrl: './device-graph.component.html',
  styleUrls: ['./device-graph.component.scss']
})
export class DeviceGraphComponent implements OnInit {
  Highcharts: typeof Highcharts = Highcharts;
  chartOptions: Highcharts.Options = {
    xAxis: {
      type: 'datetime'
    },
    yAxis: {
      title: {
        text: 'Voltage'
      }
    },
    title: {
      text: 'Input voltage'
    },
    series: [
      {
        data: [
          [Date.UTC(2010, 0, 1), 29.9],
          [Date.UTC(2010, 2, 1), 71.5],
          [Date.UTC(2010, 3, 1), 106.4]
        ],
        type: 'line',
        name: 'Vin1'
      },
      {
        data: [
          [Date.UTC(2010, 0, 1), 39.9],
          [Date.UTC(2010, 2, 1), 91.5],
          [Date.UTC(2010, 3, 1), 96.4]
        ],
        type: 'line',
        name: 'Vin2'
      }
    ]
  };

  data: String[] = [];
  isLoadingResults = true;

  constructor(private api: ApiService) {}

  ngOnInit(): void {
    this.api.getInputVoltage('10.1.30.1').subscribe(
      (res: any) => {
        this.data = res;
        //console.log(this.data);
        this.isLoadingResults = false;
      },
      err => {
        //console.log(err);
        this.isLoadingResults = false;
      }
    );
  }
}

Comment: Why do you use RequestBody for a GetMapping? Not very RESTful, see http://dolszewski.com/spring/how-to-bind-requestparam-to-object/, How does your angular client build the request? Please share some code.
Answer: Assuming you are sending a parameter when you make the get call (seeing that @RequestBody address) and without seeing the logs, you can try changing the ResponseEntity<Object> to ResponseEntity<Chart3DataDTO[]>
Comment: Tried but didn't help. I've enabled logs, but didn't show anything. So I changed everything to "TRACE" but then I got overwhelmed. Any tip on the loggers which I should check?
Comment: In the logs you see some things related to httpget. Some jackson exception perhaps
Answer: Your angular client sends a GET request on /api/data/vin with query parameters while your REST controller expects a request body, this can't work.
Your controller must expect a @RequestParam
Also, as the request goes through a gateway, it must be prefixed by /services and your service name, so in your case the URL is /services/graph/api/data/vin.
Also using @Valid on a String does not do anything unless you add some other validation annotations like @NotBlank  or @Size(max=30)
@GetMapping("/vin")
public ResponseEntity<Object> vin(@Valid @RequestParam String address) {

@RequestBody must be used only for POST or PUT.
Comment: I implemented your suggestion but saw no difference. I assume the error is on the gateway, and the backend don't even receive the request.
Comment: On the gateway the URL should be prefixed by service name.
Comment: It looks like the correct path is `services/graph/api/data/vin`
Comment: Yes that's required for routing


How to set R_LIBS_SITE or how to share package site?

Question: This is a somewhat generalized version of this question. How do I set R_LIBS_SITE? I am not able to get proper values for it on both CentOS 7.2 and openSUSE 42.1 with the most recent R 3.3.1.
On CentOS 7.2 (Linux x86_64) with R from EPEL I get:
R version 3.3.1 (2016-06-21) -- "Bug in Your Hair"
...
Platform: x86_64-redhat-linux-gnu (64-bit)
...
> .libPaths()
[1] "/usr/lib64/R/library" "/usr/share/R/library"
> .Library
[1] "/usr/lib64/R/library"
> .Library.site
[1] "/usr/lib64/R/library" "/usr/share/R/library"
> R.home(component = "home")
[1] "/usr/lib64/R"

However, the respective Renviron includes the following:
$ grep R_LIBS_SITE /usr/lib64/R/etc/Renviron
R_LIBS_SITE=${R_LIBS_SITE-'/usr/local/lib/R/site-library:/usr/local/lib/R/library:/usr/lib64/R/library:/usr/share/R/library'}

Apparently, this setting is not applied properly when I start R. However,
changes for example in R_LIBS_USER in the same file are applied. In addition, R_LIBS_SITE is not ignored completely because setting it to
R_LIBS_SITE='/usr/local/lib/R/site-library'

produces
> .Library.site
character(0)

I don't see where R_LIBS_SITE could be overwritten elsewhere. I get
the same behaviour in R when I start it with
R --no-environ --no-site-file --no-init-file

I can reproduce a similar behaviour with openSUSE.
Or is there another recommended way to set a package site shared amongst all users?
Answer: A possible explanation of the problem is that some of the directories do not exist. Directories that do not exist are silently removed from the list. So, if you set
R_LIBS_SITE='/usr/local/lib/R/site-library'
and the directory does not exist, .Library.site will be an empty string (like in your example). Following the outputs from your example, if directories /usr/local/lib/R/site-library and /usr/local/lib/R/library do not exist, they will be silently removed from the list given in R_LIBS_SITE of your Renviron file (again like in your output).


Como criar a condição booleana AND em um código .bat?

Question: Tenho um programa simples que deleta certos arquivos caso existam, mas gostaria de aperfeiçoá-lo utilizando uma condição booleana para caso os dois arquivos não existam. É possível de forma simples? Achei respostas em inglês mas todas são muito antigas (2010 ou mais antigas) e involve comandos que desconheço e são confusos, criar variáveis, etc.
Parte do código que uso no momento, funciona perfeitamente:
echo. & echo "Deletar WoWCombatLog.txt" & echo.

IF NOT EXIST "C:\Program Files (x86)\World of Warcraft\_retail_\Logs\WoWCombatLog.txt" (
        echo "CombatLog não encontrado"
    )

Como eu gostaria que funcionasse (não há motivos para postar todo o código):
echo. & echo "Deletar WoWCombatLog.txt" & echo.

IF NOT EXIST "C:\Program Files (x86)\World of Warcraft\_retail_\Logs\WoWCombatLog.txt" AND NOT EXIST "C:\Program Files (x86)\World of Warcraft\_retail_\Logs\WoWCombatLog-split*.txt"  (
            echo "CombatLog não encontrado"

Answer: Se as duas condições têm que ser verdadeiras, coloque uma aninhada na outra.
IF NOT EXIST "C:\Program Files (x86)\World of Warcraft\_retail_\Logs\WoWCombatLog.txt" (
    IF NOT EXIST "C:\Program Files (x86)\World of Warcraft\_retail_\Logs\WoWCombatLog-split*.txt" (
        echo "CombatLog não encontrado"
    )
)

Answer:

Use dir com múltiplos arquivos e use o errorlevel

set "_wow_path=%ProgramFiles(x86)%\World of Warcraft\_retail_\Logs"

2>nul >nul dir /b "%_wow_path%\WoWCombatLog.txt" "%_wow_path%\WoWCombatLog-split*.txt"
if %errorlevel% == 0 echo\Arquivo(s) encontrado(s)!

Ou em bloco com uso de operadores (dir arq1.txt arq*.txt) &&  listou 1 (ou 2) || não listou nada:

set "_wow_path=%ProgramFiles(x86)%\World of Warcraft\_retail_\Logs"

( dir /b "%_wow_path%\WoWCombatLog.txt" "%_wow_path%\WoWCombatLog-split*.txt"
) 2>nul >nul && echo\Arquivo(s) encontrado(s)! || echo\Arquivos nao encontrados!!

1. Define o path para a pasta dos arquivos que desejas verificar:
set "_wow_path=%ProgramFiles(x86)%\World of Warcraft\_retail_\Logs"
2. Execute um comando para listar, como o dir arquivo1 arquivo2
 dir /b "%_wow_path%\WoWCombatLogX.txt" "%_wow_path%\WoWCombatLog-split*X.txt"
3. Limite a execução acima num bloco (dir arquivo1 arquivo2) 2>nul >nul e suprimir qualquer erro(s) de arquivo não encontrado:
( dir /b "%_wow_path%\WoWCombatLog.txt" "%_wow_path%\WoWCombatLog-split*.txt"
) 2>nul >nul && Arquivo(s) sim encontrado(s)! || echo\Arquivos nao encontrados!!

Obs.: 1 Ou use uma só linha no bloco:

( dir /b "%_wow_path%\WoWCombatLog.txt" "%_wow_path%\WoWCombatLog-split*.txt" ) 2>nul >nul && echo\Arquivo(s) encontrado(s) || echo\Arquivos nao encontrados!!

Obs.: 2 você pode passar por parâmetro mais de um arquivo para o comando dir
*dir /b arq1.log arq2.txt arq3.dat..., se um apenas um arquivo for listado, dir retorna return 0 e se nenhum for listado, return non 0.

4 Utilize o operador && para tratar return 0 e o operador || para tratar return non 0:

rem :: lógica aplicada na listagem de 2(+) arquivo(s) ⁄⁄ mensagens ::

rem :: Não listou os 2 arquivos  ==  ||  Arquivos nao encontrados
rem :: Sim listou os 2 arquivos  ==  &&  Arquivo(s) encontrado(s)!
rem :: Não listou 1 dos arquivos ==  &&  Arquivo(s) encontrado(s)!

rem :: Output/saídas nas listagem de 2(+) arquivo(s) ⁄⁄ mensagens ::
rem :: Arquivo(s) nao encontrado(s) (dir) || mensagem
rem :: Nao exist True  ==  WoWCombatLog-split
rem :: Nao exist True  ==  WoWCombatLog-split*.txt
rem ::    Return "1"   ==  Arquivos nao encontrados

rem :: Um Arquivo encontrado (dir) && mensagem
rem :: Nao exist False  ==  WoWCombatLog-split
rem :: Nao exist False  ==  WoWCombatLog-split*.txt
rem ::     Return "0"   ==  Arquivo(s) encontrado(s)

rem :: Um ou (*) Arquivos encontrados (dir) && mensagem
rem :: Nao exist True   ==  WoWCombatLog-split
rem :: Nao exist False  ==  WoWCombatLog-split*.txt
rem ::     Return "1"   ==  Arquivo(s) encontrado(s)

rem :: Um ou (*) Arquivos encontrados (dir) && mensagem
rem :: Nao exist False  ==  WoWCombatLog-split
rem :: Nao exist True   ==  WoWCombatLog-split*.txt
rem ::     Return "1"   ==  Arquivo(s) encontrado(s)

rem :: para apagar os dois arquivos somente se existirem:

set "_wow_path_files=%ProgramFiles(x86)%\World of Warcraft\_retail_\Logs"

2>nul >nul dir /b "%_wow_path%\WoWCombatLog.txt" "%_wow_path%\WoWCombatLog-split*.txt"
if %errorlevel% equ 0 del /q /f "%_wow_path%\WoWCombatLog.txt" "%_wow_path%\WoWCombatLog-split*.txt"

Resumindo:

Somente se não existirem os dois (ou mais: ...split*.txt)

cd /d "C:\Program Files (x86)\World of Warcraft\_retail_\Logs"
2>nul >nul dir WoWCombatLog-split*.txt WoWCombatLog.txt || echo\Arquivos Nao Encontrados

Resulta:

Arquivos Nao Encontrados

Somente se existe(m) 1 ou mais // ...split*.txt

cd /d "C:\Program Files (x86)\World of Warcraft\_retail_\Logs"
2>nul >nul dir WoWCombatLog-split*.txt WoWCombatLog.txt && echo\Arquivo(s) Encontrado(s)

Resulta:

Arquivo(s) Encontrado(s)

As duas opções acima em um bat:

@echo off

cd /d "C:\Program Files (x86)\World of Warcraft\_retail_\Logs"
>nul 2>&1 dir WoWCombatLog-split*.txt WoWCombatLogx.txt && <nul ^
echo\Arquivo(s) Encontrado(s) || echo\Arquivos nao Encontrados

Apagando esses arquivos caso dois ou mais existirem:

@echo off

cd /d "C:\Program Files (x86)\World of Warcraft\_retail_\Logs"
>nul 2>&1 dir/b WoWCombatLog-split*.txt WoWCombatLog.txt && <nul ^
    del /q /f WoWCombatLog-split*.txt WoWCombatLog.txt >nul 2>&1 ^
        || echo\Arquivos nao Encontrados


Unprovable sentence, but provably it is provable.

Question: Work in Peano Arithmetic, PA. Let Prov(n) be a standard proof predicate, so that $PA \vdash Prov(\ulcorner \phi \urcorner) \text{ iff } PA \vdash \phi$ .
By Löb's theorem, we know that if $PA \vdash Prov(\ulcorner \phi \urcorner) \rightarrow \phi$ then $PA \vdash \phi$. The fact that this is a theorem  psychologically implies that we do not get the stronger result - if $PA \vdash Prov(\ulcorner \phi \urcorner)$ then $PA \vdash \phi$.
I am looking for counterexamples for the latter implication. Can anyone provide a sentence $\phi $ in PA such that $PA \vdash Prov(\ulcorner \phi \urcorner)$ and $PA \not\vdash \phi$?
Comment: Your second sentence is making an assumption you're unwilling to make in the rest of the question. Namely, your second sentence claims "PA$\vdash Prov(\ulcorner\varphi\urcorner)$ iff PA$\vdash\varphi$," but then you ask whether we can have a $\varphi$ such that PA$\vdash Prov(\ulcorner\varphi\urcorner)$ but PA$\not\vdash\varphi$ - which would clearly contradict that initial claim! The issue is, per my answer below, your initial claim about how the provaibility predicate behaves assumes the $\Sigma_1$-soundness of PA, but your question itself doesn't. So there's a "metatheoretic mismatch" here.
Answer: No such $\varphi$ is known, nor is such (generally) believed to exist.
It is generally believed - similarly to how it is generally believed that PA is consistent - that no such $\varphi$ exists. Specifically, it is generally believed that PA is $\Sigma_1$-sound (= every $\Sigma_1$ sentence provable in PA is true), and indeed fully sound (= only proves true sentences). Of course, this tends to invoke at least a limited amount of Platonism; I'm not trying to argue the philosophical point, I just want to make it clear that the vast majority of mathematicians do not expect such a $\varphi$ to exist.
This is a nontrivial assumption, however: even PA+"PA is consistent" does not prove "PA is $\Sigma_1$-sound. So the phenomenon you're looking for, even though almost everybody thinks it won't happen, is still plausible at least in a very limited sense.

If we look beyond PA, however, we can easily find examples of this phenomenon. For instance, consider the theory $T=$ PA+"PA is inconsistent." By Godel's second incompleteness theorem, if PA is consistent then so is $T$, so $T\not\vdash 0=1$. However, we clearly have $T\vdash Prov_T(\ulcorner 0=1\urcorner)$.
That is, if PA is consistent, then PA has a consistent $\Sigma_1$-unsound extension.
Comment: Thank you, and great example.


Spivak Chapter $2$ Problem $22$ Clarification

Question: From Spivak's calculus 3rd edition:

The result in Problem 1-7 has an important generalization: If $a_1,...,a_n \geq 0$, then the "arithmetic mean" $$A_n = \frac{a_1+...+a_n}{n}$$
and "geometric mean"
$$G_n = \sqrt[n]{a_1...a_n}$$
satisy $$G_n \leq A_n$$(a) Suppose that $a_1 < A_n$ Then some $a_i$ satisfies $a_i>A_n$; for convenience, say $a_2>A_n$. Let $\bar{a_1} = A_n$ and let $\bar{a_2} = a_1 + a_2 - \bar{a_1}$. Show that $$\bar{a_1}\bar{a_2} \geq a_1a_2$$
Why does repeating this process enough times eventually prove that $G_n \leq A_n$?

I've got the first part but I'm struggling to understand the "repeating process" aspect of the proof. From what i understand it comes from each iteration of the process increasing $G_n$ but keeping $A_n$ constant but i don't get how exactly the process is repeated.
For example,
Given a set of values $\{a_1, a_2\}$,
if $$a_1 < A_2 < a_2$$
$$\bar{a_1}=A_2\\ \bar{a_2}=a_1+a_2-\bar{a_1}$$
then a new set $\{\bar{a_1}, \bar{a_2}\}$ can be created where $\bar{A_2} = A_2$ and $\bar{G_n} \geq G_n$
How would you repeat the process for $\{\bar{a_1}, \bar{a_2}\}$?
Answer: The set that you're working with always has $n$ elements, but at each step you change only two at a time.
If all of the elements are equal to the arithmetic average $A_n$, then we see
$$G_n = \sqrt[n]{(A_n)^n} = A_n.\tag{1}\label{1}$$
On the other hand, if not all of the elements are equal to $A_n$ then there must be at least one that is less than $A_n$, and likewise, at least one that is greater than $A_n$. (Can you see why?)
In this case, by assumption, we have $a_1$ and $a_2$ with
$$a_1 < A_n < a_2.$$
For the first step, we replace $a_1$ and $a_2$ with $\bar{a_1}$ and $\bar{a_2}$, where
$$\bar{a_1} = A_n,$$
and
$$\bar{a_2}=a_1+a_2-\bar{a_1}.$$
Some arithmetic will show you that the set formed with these new elements $\{\bar{a_1}, \bar{a_2}, a_3,\dots, a_n\}$, has the same arithmetic mean as the original set $\{a_1, a_2,\dots, a_n\}$ and a geometric mean that is greater than that of the original set.
$$A_n' = A_n,$$
$$G_n' > G_n.$$
If all of the elements of this new set are equal to $A_n'$ then combining the above and \eqref{1}, we have
$$G_n < G_n' = A_n' = A_n.$$
On the other hand, if there is at least one element of the new set that is less than $A_n$, we can repeat the process, this time calling the two elements $a_2$ and $a_3$, with
$$a_2 < A_n < a_3.$$
Note that $\bar{a_2}$ from the first step might be either one of these numbers. $\bar{a_1}$ on the other hand, cannot be either. (Remember, we set $\bar{a_1} = A_n$. We are done messing with $\bar{a_1}$.)
So, if this second step is needed, we replace the above numbers $a_2$ and $a_3$ with $\bar{a_2}$ and $\bar{a_3}$, where
$$\bar{a_2} = A_n,$$
and
$$\bar{a_3}=a_2+a_3-\bar{a_2}.$$
The set formed with these new elements $\{\bar{a_1}, \bar{a_2}, \bar{a_3}, a_4, \dots, a_n\}$ has the same arithmetic mean as the previous set, which has the same arithmetic mean as the original set. Our new set has a greater geometric mean than the previous set, which has a greater geometric mean than that of the original set.
We continue in this way until every element equals $A_n$. How do we know we will eventually reach this state? Each round in the process takes two elements that are not equal to $A_n$ and replaces them with two elements, at least one of which equals $A_n$. There is at least one less "bad" element not equal to $A_n$ after each round.
Eventually, all of the elements will equal $A_n$ and equation \eqref{1} will apply.
A helpful exercise: assume the set has only two "bad" elements $a_1$ and $a_2$ (with all other $a_i = A_n$) and proceed with the prescribed substitutions: replace $a_1$ and $a_2$ with $\bar{a_1}$ and $\bar{a_2}$, where
$$\bar{a_1} = A_n,$$
and
$$\bar{a_2}=a_1+a_2-\bar{a_1}.$$
In this case, how does $\bar{a_2}$ compare with $A_n$? (Hint: remember that the sum of the two elements and hence the arithmetic mean of the set remains unchanged.)


There are low variations in the explanatory variables

Question: I am running a regression and find coefficients of my explanatory variables very interesting (they are dummy variables). When I informed that to my lecturer, he told me that there are not much variations in the explanatory variables then the results might not very good. (I did not check that before because I jumped to the regression without descriptive statistics, I have learned my lesson)
I feel vaguely that if the explanatory variable does not vary much, then it might not be a good regressor. But anyone can provide some proof/intuition/reading on the issue? Can we get around that problem?
For the explanatory variable in my example, 94% of the sample are native (1) and 6% are foreign. I don't think there is a sample selection bias here because the data are collected in a country so why would one expect to have a balanced nationality.
Answer: The basic idea is that more variation in the regressors allows you to more confidently pin down the relationship between $y$ and $X$ in your regression.
Recall that the slope coefficient of the estimated regression is to provide an answer to the question: "How does $y$ change, on average, when $X$ changes by one unit?" Now, in the limit, if $X$ does not vary at all, the sample is of course entirely uninformative about that question. If $X$ only varies a little, the slope will be estimated very imprecisely.
For example, when you want to estimate the returns to more education in terms of additional salary, but your sample consists of, say, $n-1$ students with a BSc degree and one with an MSc, the return to completing an MSc will be estimated from that student alone. Since that student may have all sorts of pecularities, the effect on salary from completing an MSc will be estimated very poorly.
Here is a simulated example where the purple dots are pairs $(x_i,y_i)$ where the regressors are uniform on $[0,1]$, whereas the golden dots are from regressors uniform on $[-2,3]$, thus their variation is larger.
The true $\beta$ is .5 in both cases, and the errors are $N(0,0.5^2)$ (the code is below for completeness), $n=50$.
As we observe $X$ over a wider range in the golden case, regression finds it easier to spot the slope of the true regression line. We see that the estimated slope for the purple sample is quite off (in fact, even negative), whereas the golden one is quite good. Of course, the figure is for a single sample and thus only suggestive. You could run the code many times (aka, a simulation study) to assess the difference in precision for this (or of course other) design(s).

One can also show this effect analytically: In a regression with constant (as in my example), the variance of the estimated slope coefficient is (with $\sigma^2$ the variance of the error terms)
$$
Var(\hat{\beta})=\frac{\sigma^2}{\sum_{i=1}^n(x_i-\bar{x})^2}
$$
We notice that as the variation in $X$ increases, the variance of the OLS estimate decreases.
Code for the plot:
<code>n <- 50
u <- rnorm(n,sd=.5)
beta <- .5

X1 <- runif(n,0,1)
X2 <- runif(n,-2,3)

y1 <- X1*beta + u
y2 <- X2*beta + u

plot(X1,y1,xlim=c(-2,3),ylim=c(-2,3),col="purple",pch=19)
abline(a=0,b=beta)
abline(lm(y1~X1),col="purple")
points(X2,y2,col="gold",pch=19)
abline(lm(y2~X2),col="gold")
</code>


Define a relation $\sim$ on ℕ by $a\sim b$ if $ab$ is a perfect square

Question: So, for this problem:
a. Prove that $\sim$ is an equivalence relation on ℝ². (I'm not sure if this is a typo on my professor's part since we are defining a relation on ℕ.)
b. Describe the equivalence class $[1]$.
c. If $p ≠ q$ are primes, then prove that $[p]∩[q] = ∅$.
d. If $n > 1$, then use the fundamental theorem of arithmetic to give a complete description of the equivalence class $[n]$.
So for a, I have that if we let $a\sim a$, we get that $aa = a^2$, and so $a\sim a$ for reflexivity and $\sim$ is reflexive. For symmetry, $ab$ is square, and so is $ba$, so $\sim$ is symmetric. For transitive, let $a\sim b$, and $b\sim c$. Then I get that $ab = x^2$ and $bc = y^2$. So
$$ac = \frac{ab\cdot bc}{b^2}=\frac{x^2\cdot y^2}{b^2}=\Big(\frac{xy}{b}\Big)^2 ,$$
 and therefore, $ac$ is square, and $\sim$ is transitive.
For b, I get that $[1]$ is by definition the set of all $n \in ℕ$ such that $1\sim n$ or $n$ is square. But that is all I have for it.
For c, can I say that we suppose there is an element, let's say $c$, in the intersection of $[p]$ and $[q]$. Then, $c\sim a$ and $c\sim b$. But since $p$ and $q$ are primes that do not equal each other, then their only possible common element in the intersection is $1$?
For d, I get that the Fundamental Theorem says that every integer $n >1$ can be factored into a product of primes. And so can I say that then $[n]$ is the set of all perfect squares that share the same prime factors of $n$?
So, can anyone tell me if my part a and d are correct, and if anyone can help me with the b, and c?
Comment: For anybody else who's reading this, note that in a, you need to show that xy/b is an integer.
Answer: b) Seems to be correct: you want $1 \times n$ to be a square, so the equivalence class of $1$ is all the prefect squares in $\mathbb{N}$.
c)Hint: assume that there is an element in $[p] \cap [q]$. What can you say about this element, and in particular its divisors?
d) What does the fundamental theorem of arithmetic state? How can you apply this? What is the prime factorisation of a perfect square?
Comment: For c, if we assume that the intersection is nonempty, then there exists an element c in the intersection of [p] and [q]. Then, that being the case, c~a, and c~b. But, can I then say since they are primes not equal to each other, and there is an element that is related to both of them that this element must have a divisor of both p and q?
Comment: @J-Play This element, c, is such that $cp = a^2$ and $cq = b^2$, for some $a, b \in \mathbb{Z}$. What can you say about the divisors of $c$ if each of these products is a perfect square?
Comment: Can I say that c must have the same divisors as p and q?


UNC name resolution issue

Question: Have a win 2008 r2. after installing some patches the xp client machine can no longer access the file share. Win 7 machine was okay.
\\servername\    path not found
\\x.x.x.x\    path not found
\\servername.contoso.com\    path found
ping servername    okay
ping x.x.x.x    okay
ping servername.contoso.com    okay
netbios over tcp/ip is enabled
TCP/IP Helper Service is enabled
dcdiag & repadmin /replsum    okay
The DC is a PDC, RID, Infra master.
just no idea what when wrong after the server OS patching ...
Answer: Try changing the value of
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\DependOnService
from SamSS Srv2 to SamSS Srv
and reboot your server.
Comment: the server in questions is already on SamSS Srv but still not working. Thanks
Answer: https://support.microsoft.com/en-sg/kb/3161949
NETBIOS communication outside of the local subnet is hardened. Therefore, by default, some features that depend on NETBIOS (such as SMB over NETBIOS) will not work outside the local subnet.
SUBKEY: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBT\Parameters
Value Name: AllowNBToInternet
Type: Dword
Value: 1

UNC name resolution issue


repeated cross section v. panel data

Question: What is the best way to describe the difference between a repeated cross-sectional and panel dataset?
I consider an example of measuring blood pressure for a set of patients $i\in\{1,...,N\}$.
A repeated cross-section data in this case would mean that the hospital has the blood pressure records for Sam and Suzy at different points in time and not necessarily at the same time. For example, Sam might have his readings on Monday and Tuesday, and Suzy on Friday and Saturday.
In a panel data set-up, the hospital has 3-month worth of blood pressure data on everyone, but $N$ is quite larger than 3 months, so it is "longitudinal" in this sense.
Does this example portray the difference between a repeated cross-sectional and panel dataset? Why and why not? What might be a better example to explain the difference(s)?
Comment: I see a clear explanation here (https://dam.ukdataservice.ac.uk/media/455362/changeovertime.pdf)
Answer: I think they are often used interchangeably depending on the field, but the way I think of it is panel data explicitly views the repeated measurements as occurring through time whereas repeated cross-sectional can be some arbitrary dimension. Your example sounds pretty good to me.
To expand on it, let's say you have observational data of 100 patients' daily blood pressure measurements for 3 months. For a single patient $i$, we can think of their data as a time series with 3 months worth of daily observations. This is panel data.
On the other hand, perhaps some patients only recorded measurements every other day while some recorded it several times a day. It is still repeated through "time", but the time index is somewhat meaningless now since the $j$th observation for two different patients may correspond to different timestamps entirely.
The practical implication is that if we wished to include time effects such as seasonality (perhaps there is an overall increase in blood pressure in the population over summer due to increased consumption of hot dogs), panel data can allow for identification whereas repeated cross-sectional data cannot.
Comment: Please see
https://stats.meta.stackexchange.com/questions/6304/my-upvoting-policy,
when you find a question sufficiently clear to
write an answer, consider to upvote the question!
Comment: If you found this answer helpful, then please consider
[upvoting](https://stats.stackexchange.com/help/why-vote)
and/or
[accepting](https://stats.stackexchange.com/help/accepted-answer)
it.

repeated cross section v. panel data


In equilateral triangle,One vertex of a square is at the midpoint of the side, and the two adjacent vertices are on the other two sides of triangle

Question: In the equilateral triangle $ABC,AB=12.$One vertex of a square is at the midpoint of the side $BC$, and the two adjacent vertices are on the other two sides of the triangle.Find the length of the side of the square.

Let $DEFG$ be the square.Let $D$ be the midpoint of the side $BC.BD=DC=6.$
Let $E$ be on the side $AC$ and $G$ be on the side $AB$ such that $AG=12-a,BG=a$ and $AE=12-b,EC=b$.
In triangle $DEC,$ applying Cosine law,
$\cos 60^\circ=\frac{1}{2}=\frac{b^2+36-DE^2}{12b}........(1)$
In triangle $DGB,$ applying Cosine law,
$\cos 60^\circ=\frac{1}{2}=\frac{a^2+36-DG^2}{12a}........(2)$
I am stuck here.
Comment: You must have $BG=EC$, so side length is just $\frac{6\sin 60}{\sin 75}\approx 5.38$.
Answer:
1) $\triangle ADB: \angle D=90^{\circ}, DB=6, AD=\sqrt{12^2-6^2}=\sqrt{108}, AB=12$
2) $DG - $ bisector $\angle ADB$
$$DG=\sqrt2 \frac{AD \cdot DB}{AD+DB}=\sqrt2 \frac{6\sqrt3 \cdot 6}{6\sqrt3+6}=\frac{6\sqrt6}{\sqrt3+1}=3\sqrt6(\sqrt3-1)$$
Comment: @GCab No. The two vertices adjacent to the vertex at $D$. Roman83's triangle is rotated!
Comment: You introduced a spurious $\sqrt6$ right at the end.
Comment: @Roman83 the question seems to require that E and F be on the triangle sides
Comment: @almagest: Thank you!
Comment: I want to ask one thing ,how did you know $AD$ is perpendicular to $BC$ and why $F$ came on $AD$?@Roman83
Comment: @VinodKumarPunia: The square and equilateral triangle are symmetric figures
Comment: @VinodKumarPunia please make clear the "adjacent" .. to D, or to each other ? in your question
Comment: They are adjacent to $D$@GCab
Answer: Let $x$ be length of side of square.Triangles DBG and CDE are congruent because they have an angle and two corresponding sides which are equal.Implies BG=EC.In which case Angle BDG = $45^0$ and Angle BGD = $75^0$.Applying sine rule in Triangle BGD $$\frac{x}{\sin{60^0}}=\frac{6}{\sin{75^0}}$$
I hope this was helpful.
Comment: A neat solution.
Comment: By which similarity criteria,you proved triangles $DBG$ and  $CDE$ similar.Because there are only three similarity criterias,$SSS,AAA,SAS$.@VarunKumar
Comment: @Vinod Kumar Punia he appears to have used ASS congruence, which only exists in the case of right angles (as RHS). I think it Is a mistake..


Using the Windows.Management namespace in C++ builder XE2

Question: I am very new to C++ on Embarcadero XE2. Currently I want to transfer the following class
http://weblogs.asp.net/whaggard/archive/2006/02/11/438006.aspx
to c++ version.
But I wonder I can use System.Management on Embarcadero XE2, or I still have to use wbemidl.h to deal with WMI. (I have just given it a try and it returned Error: Management is not  a member of System)
Any help will be appreciated.
Answer: The System.Management is a .Net namespace, C++ Builder not is a .Net development tool, so you can't use this namespace under c++ builder. The natural way to access the WMI from C++ is using COM directly using the interfaces defined in the wbemcli.h or wbemidl.h files.
Comment: Thank, I will do the way you suggested!


What is $\frac{dc}{dt}$ where $c(t) = (S\circ q)(t)$ for $S$ a surface and $q$ a plane curve?

Question: Consider a parametric smooth surface:
$$S:R^2 \to R^3, \quad S(u,v)=(X_S(u,v),Y_S(u,v),Z_S(u,v)), \quad for \ u,v \in R$$
a parametric smooth plane curve:
$$q:R \to R^2, \quad q(t)=(X_q(t),Y_q(t)), \quad for \ t \in R$$
and the space curve:
$$c:R \to R^3, \quad c(t) = (S\circ q)(t)$$
Now, I believe that the following hold:
$$\frac{dq}{dt}\in R^2 \ , \ \frac{\partial{S}}{\partial{u}},\frac{\partial{S}}{\partial{v}} \in R^3, \quad \frac{dc}{dt} \in R^3   $$
$$\frac{dc}{dt} = \left. \frac{dS(u,v)}{dt}\right\vert_{(u,v)=q(t)}* \frac{dq(t)}{dt} $$
So obviously something is wrong. What kind of multiplication is $R^3*R^2$?
Is$\left. \frac{dS(u,v)}{dt}\right\vert_{(u,v)=q(t)} \notin R^3$?
Answer: You are multiplying Jacobian matrices, which are the higher dimensional analogs of the derivative for maps $f:\mathbb{R}^m\rightarrow \mathbb{R}^n$.  In your notation, $dq/dt$ is the $2\times 1$ Jacobian matrix of $q$:
$$\begin{bmatrix}\frac{dX_q(t)}{dt}\\
\frac{dY_q(t)}{dt}\end{bmatrix}$$
In your notation, concatenating $\partial S/\partial u$ and  $\partial S/\partial v$ into a matrix we obtain the Jacobian of the map $S$:
$$\begin{bmatrix}\frac{\partial X_S(u,v)}{\partial u}&\frac{\partial X_S(u,v)}{\partial v}\\
\frac{\partial Y_S(u,v)}{\partial u}&\frac{\partial Y_S(u,v)}{\partial v}\\
\frac{\partial Z_S(u,v)}{\partial u}&\frac{\partial Z_S(u,v)}{\partial v}\\
\end{bmatrix}$$
You'll find that the product of these two matrices will give you a higher dimensional analog of the chain rule. You should get the corresponding $3\times 1$ Jacobian for the composed map.
Comment: Yes it should be fixed now
Comment: First of all, thank you for your answer! However I have a question. In the second column of the second jacobian matrix, did you mean to use $X_s$ instead of $X_u$?
Comment: What would I do if I wanted the second derivative of c(t)? $d^2c/dt^2$


Module build failed: SyntaxError: C:/....../main.jsx: Unexpected token

Question: I've been stuck on a problem for hours now. Whenever I try to run WebPack it gives me the module build error where it complains about the <. I've tried many solutions on this site and others but I still can't figure it out. Any help would be appreciated.
main.js
import Main from './main.jsx';

main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import { Switch } from 'react-router';

class Nav extends React.Component {
  render() {
    return {

hello

    }
  }
}

class App extends React.Compnent {
  render() {
    return {

    }
  }
}

ReactDOM.render (
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("mainContent")
);

webpack.config.js
const path = require('path');

module.exports = {
    entry: './js/main.js',
    output: {
        path: path.resolve(__dirname, 'docs'),
        filename: 'file.js'
    },
    devServer: {
      contentBase: path.join(__dirname, "docs"),
      port: 9000
    },
    module: {
      loaders: [
            { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
        ]
    },
};

have also tried
    module: {
      loaders: [
            { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ , query: {presets:['es2015', 'react']} },
        ]

package.json
{
  "name": "connectthrumusic",
  "version": "1.0.0",
  "description": "Shows the location of people around the world that are listening to the same song at the same time and allows you to chat with them.",
  "main": "webpack.config.js",
  "scripts": {
    "start": "webpack-dev-server --open",
    "test": "echo \"Error: no test specified\" && exit 1",
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/andrew2chan/ConnectThruMusic.git"
  },
  "author": "Andrew Chan",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/andrew2chan/ConnectThruMusic/issues"
  },
  "homepage": "https://github.com/andrew2chan/ConnectThruMusic#readme",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2016": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "webpack": "^3.10.0"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2016": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "webpack-dev-server": "^2.11.1"
  }
}

index.html
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ConnectThruMusic</title>

.babelrc
{
    "presets": ["env", "react", "es2015"]
}

Error
Files
Comment: Consider using a linter, it will make your life and code much easier, the proper syntax for JSX return is `()` not `{}`
Comment: not sure if it fixes it but one improvement would be using => entry: './js/main.jsx',
Comment: Thanks for the suggestion, I will look into it. Also, thanks for the help. It work fine now. Can't believe that was all I needed.
Answer: Was simply () instead of {}. Thanks to Sterling Archer for pointing that out.


How to display the user edit-picture form in custom block?

Question: I am trying to customize the user edit page in Drupal7 using Panels for user-edit page. How can i display the user edit-picture form in any specific region in Drupal 7. In my panels, i added a custom text in my sidebar region as:
<code><?php
drupal_get_form("edit-picture") ;
?>
</code>
However, it does not show anything. I got the form id by looking at the css. Any suggestions?
Answer: The ID you pulled from the DOM isn't the form ID, unfortunately. It's just the ID of the user image picker fieldset.
Take a look at the User Picture Field module. I haven't used it, so I can't personally vouch for it. However, it does make the user picture a field, which adds a lot of flexibility. I think Panels will let you move the field to the place where you want it to appear. You should also be able to use the editablefields module to make the image editable in the display.


Select latest date

Question: <code>    SELECT
    distinct

        HRM_Employee.EmployeeId EmployeeXId,
      ([HRM_Employee].[FirstName] +' '+ISNULL([HRM_Employee].[MiddleName],' ')+' '+ISNULL([HRM_Employee].[LastName],' ')) AS FirstName
     -- ,[FirstName]
          ,[HRM_Employee].[MiddleName]
          ,[HRM_Employee].[LastName]
          ,[HRM_Employee].[Code]
          ,[HRM_Employee].[UserName]
          ,[HRM_Employee].[Password]
          ,[HRM_Employee].[DateOfBirth]
          ,[HRM_Employee].[OriginalBirthDate]
          ,[HRM_Employee].[Gender]
          ,[HRM_Employee].[BloodGroup]
          ,[HRM_Employee].[Height]
          ,[HRM_Employee].[MaritalStatus]
          ,[HRM_Employee].[DateOfMarriage]
          ,[HRM_Employee].[IdentificationMark1]
          ,[HRM_Employee].[IdentificationMark2]
          ,[HRM_Employee].[Religion]
          ,(SELECT [A].[FirstName] +' '+  [A].[MiddleName] +' '+ [A].[LastName]
              FROM [dbo].[HRM_Employee] [A] WHERE [A].EmployeeId = [HRM_Transfer].[ReportingOfficerXId]
           ) [PersonInCharge]
          ,[HRM_Department].[Name] [DepartmentName]
          ,[HRM_Branch].[Name] [BranchName]
          ,[HRM_Division].[Name] [DivisionName]
          ,[HRM_Designation].[Name] [DesignationName]
          ,HRM_Transfer.TransferDate
    from HRM_Employee
    LEFT join [dbo].[HRM_Division]
            ON [HRM_Employee].DivisionXId  = [HRM_Division].DivisionId
            JOIN [dbo].[HRM_Designation]
            ON [HRM_Employee].DesignationXId = [HRM_Designation].DesignationId
            JOIN [HRM_Department]
            ON [HRM_Employee].[DepartmentXId] = [HRM_Department].[DepartmentId]
            JOIN [HRM_Branch]
            ON [HRM_Employee].[BranchXId] = [HRM_Branch].[BranchId]
            INNER JOIN HRM_Transfer
            ON HRM_Transfer.EmployeeXId=HRM_Employee.EmployeeId
    WHERE
        Convert(varchar(11),HRM_Transfer.TransferDate,103) <=Convert(varchar(11), getdate(),103)
END
</code>
When I excecute this i got the output as follows
<code>EmployeeXId    FirstName               TransferDate
34             Ambarish   V               2012-08-09 00:00:00.000
54             Anil  N P                      2012-08-09 00:00:00.000
55         Ann  Rose Abraham              2012-08-08 00:00:00.000
55         Ann  Rose Abraham              2012-08-09 00:00:00.000
74             Anees  M S                     2012-08-09 00:00:00.000
</code>
From this I want to display data with latest Transfer date only. That is in EmployeeId 55 I need to display data with Transfer date 2012-08-09 00:00:00.000 only. What modification is I want to do in above SP to get required answer?. Please help me to solve this.
Answer: Group by EmployeeXId and select MAX(TransferDate).
Comment: In above sp Where I want to add this line?
Comment: In the above Sp whre do I add the line "Group by EmployeeXId and select MAX(TransferDate)". Please help me to solve this...
Comment: If you don't know how to use GROUP BY, read up on it on [MSDN](http://msdn.microsoft.com/en-us/library/ms177673.aspx). Same goes for the MAX aggregate.
The GROUP BY will be your last line, and should repeat each column you have in your select statement, except for TransferDate column. In the SELECT statement, change the last column to "MAX(HRM_Transfer.TransferDate)".

Select latest date


Prove statement about determinants.

Question: $A$ is a $3\times 3$ matrix over $\mathbb{R}$, I want to show that if $$\det(A + I_3)=\det(A+2I_3),$$ then $$2\det(A+I_3) + \det(A-I_3) + 6 = 3\det A.$$
Can you help me?
Comment: Yes, that's what i mean.Could you help me?
Answer: First show that you can assume $A$ diagonal. Then the question reduces to proving a basic identity between two polynomials.
More explicitely, you can write $\det (A+ x I_3) = \sigma_3 + x \sigma_2 + x^2 \sigma_1 + x^3$, where $\sigma_3=a_1 a_2 a_3$, $\sigma_2 = a_1 a_2 + a_1 a_3 + a_2 a_3$ and $\sigma_1 = a_1 + a_2 + a_3$, if the $a_i$ are the diagonal elements of $A$. The assumption gives you $\sigma_2 = -3 \sigma_1 - 7$, and the wanted equality follows readily.
Answer: If $a,b,c$ are the eigenvalues of $A$, then $\det(A)=abc$, and $\det(A+dI)=(a+d)(b+d)(c+d)$.
So we are given that
$$
(a+1)(b+1)(c+1)=\det (A+I)=\det (A+2I)=(a+2)(b+2)(c+2),
$$
and hence
$$
(ab+bc+ca)+(a+b+c)+1=2(ab+bc+ca)+4(a+b+c)+8,
$$
or simpler
$$
(ab+bc+ca)+3(a+b+c)+7=0.\tag{1}
$$
We need to show that
$$
2\det (A+I)+\det (A-I)+6=3\det(A)
$$
which is equivalent to
$$
2(abc+(ab+bc+ca)+(a+b+c)+1)+(abc-(ab+bc+ca)+(a+b+c)-1)+6=3abc,
$$
or simpler
$$
(ab+bc+ca)+3(a+b+c)+7=0\tag{2}
$$
Clearly $(1)$ and $(2)$ are identical and hence we are done.

Prove statement about determinants.


How to get the template file using hook block view?

Question: <code>function tgs_user_block_info() {
  $blocks = array();

  $blocks['user-list'] = array(
    'info' => t('List of Users'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function tgs_user_block_view($delta = '') {
  $block = array();

$variables['logo'] = theme_get_setting('logo');
$variables['module_path'] = drupal_get_path('module', 'tgs_user');
$variables['current_path'] = '/' . current_path() . '/';

switch($delta) {

  case 'user-list':
    $block['content'] = theme('user_list', $variables);
    break;
  }

  return $block;
}

/**
 * Implements hook_theme().
 */
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'template' => 'templates/users',
  );

  return $theme;
}
</code>
This is my code in module. It doesn't call in template that I have been created on my hook_theme.
Answer: Try doing it this way, you need to separate your template name from the filepath.
<code>/**
* Implements hook_theme().
*/
function tgs_user_theme() {
  $theme = array();

  $theme['user_list'] = array(
    'path' =>  drupal_get_path('module', 'my_module') . '/templates',
    'template' => 'my_template'
  );

  return $theme;
}
</code>


No compiler errors, but there is a bug somewhere

Question: I compiled with "gcc -ansi -pedantic -W -Wall -o  ". I only get 2 errors when I compile, and here they are:
easter_eggs.c: In function 'main':
easter_eggs.c:23:18: warning: multi-character character constant [-Wmultichar]
    if (prompt == 'egg1')
                  ^
easter_eggs.c:23:4: warning: comparison is always false due to limited range of data type [-Wtype-limits]
    if (prompt == 'egg1')

when I run the program and hit S, it displays the top 2 printf statements 2 times each. If I type anything and press enter nothing happens it just goes back to the prompt. Even if I type egg1, it still goes back to prompt. Here is the source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char first_option;
    char prompt[16];

    system("clear");
    system("toilet -f future -F gay Easter Eggs");
    printf("\nFind all the easter eggs and you win. Simple enough.\n");
    printf("Hit S to start and Q to quit\n");
    scanf("%c", &first_option);

    if (first_option == 's')
    {
        while (1)
        {
            printf("To exit hit Ctrl + C\n");
            printf("You must find all easter eggs simply by typing stuff in the prompt below: \n");
            memset(prompt, 0, sizeof(prompt));
            scanf("%16s", prompt);
            getchar();
            if (!strcmp(prompt, "egg1"))
            {
                printf("Found 1\n");
            }
        }
    }

    if (first_option == "q")
    {
        exit(0);
    }

    else
    {
        printf("Invalid input. Press Enter to continue\n");
        getchar();
        main();
    }

    return 0;
}

Edit 1: I have edited the source
Edit 2: Changed the source again. This time I use strcmp() to compare the strings, not ==
Last Edit: I managed to make it work. Also updated the source so that it works. Thx to all for being patient with me. Havn't slept in idk how many days. :/
Comment: You really need to check the result of `scanf`. If it returns `0` then your char will contain a garbage value.  It will be `0` if you didn't type in `>` before your input.
Comment: Note: be sure to use `"%15s"` with `char prompt[16]`.
Comment: Do not destructively edit your post.  Maybe append information changes.  As the post stands now, the below answers about "cannot use == operator to compare strings" now do not make sense.
Answer: Read more about C programming. You are confused about char and strings.
If you want to read a word as a a string of at most 16 bytes with a terminating null byte, use e.g.
  char prompt[16];
  memset (prompt, 0, sizeof(prompt));
  if (scanf("%15s", prompt)<1) return;
  if (!strcmp(prompt, "egg1")) {
     /// found

Also, you are right to compile with -Wall. But compile also with debugging information and extra warnings:
  gcc -Wall -Wextra -g easter_eggs.c -o easter_eggs

and learn how to use the gdb debugger.
Read also the man pages (type man man in your Linux terminal) of scanf(3) & strcmp(3)
Comment: Please use the `gdb` debugger. Don't expect us to debug your code. You need to learn.
Comment: Basile: I modified my code using your example, but nothing has changed.
Comment: Your `scanf` contains a `>` but mine don't.
Answer: When you compare a char variable, you have to compare it with a char.
As the compiler told you, you have a multi-character here.
strcmp() will help you.
Answer: As mentioned in other comments, Read C. Below are some suggestions

To store string in C, You must use char[] or char * after allocating memory.
You cannot use == operator to compare strings. Use strcmp() instead.


Prove that the adjacency matrix of graph G can be written as in the picture.

Question: Let G as a bipartite graph. Show that the adjacency matrix of G can be written as in the picture given below (Actually I don't know how to make that matrix with the dashline like that, can you show me?), but if you ask me to make the matrix:
$\begin{bmatrix} O & P \\ Q & O \end{bmatrix}$
Adjacency matrix of graph G
O, P, and Q are submatrices;
O is a submatrix whose entries are 0 (Zero).
P is a transpose matrix of Q.
I have learn about bipartite graph very well and understand about adjacency matrix, but the problem above seem hard for me to solve (Well, i am stuck)
Please help me. Thank you very much.
Comment: It would be best if you try it out yourself on any bipartite graph. But make sure that if $U$ and $V$ are two vertex partition sets then the ordering of vertices in adjacency matrix does not mix these subsets.
Answer: A bipartite graph has vertices in two sets $S_1$ (size $n$) and $S_2$ (size $m$), such that all vertices are either in $S_1$ or in $S_2$, and the vertices in $S_1$ are not connected to other vertices in $S_1$, and the vertices in $S_2$ are not connected to other vertices in $S_2$.
You can sort the vertices as follows
$$\text{vertices}=\left\{\underbrace{v_1,\cdots,v_n}_{\in S_1},\underbrace{v_{n+1},\cdots,v_{n+m}}_{\in S_2}\right\}$$
Because the vertices in $S_1$ are not connected to other vertices in $S_1$, you know that the $(1,1)$ block in your adjacency matrix must be zero, and the same for your $(2,2)$ block.
Answer: A bipartite graph is conventionally represented with each part ordered consecutively, so that the adjacency matrix of a bipartite graph with parts $S_1$ and $S_2$ is the block matrix $$\begin{bmatrix} 0_{|S_1|} & A \\ A^{T} & 0_{|S_2|}\end {bmatrix} $$ where $0_{n} $ is a $n \times n $ matrix of zeroes, and $A $ is a $|S_1|\times |S_2|$ matrix indicating adjacency between elements of $S_1$ and $S_2$. From this structure, the symmetry of eigenvalues can be seen using algebra (not only using combinatorics).


how to get part of string by regular expression in python

Question: I want to get part of string by regular expression I try this but it returns more than I need. This my code :
Release_name = 'My Kitchen Rules S10E35 720p HDTV x264-ORENJI'
def get_rls(t):
    w = re.match(".*\d ", t)

    if not w: raise Exception("Error For Regular Expression")
    return w.group(0)

regular_case = [Release_name]
for w in regular_case:
    Regular_part = get_rls(w)
    print(">>>> Regular Part: ", Regular_part)

This code for this example " My Kitchen Rules S10E35 720p HDTV x264-ORENJI "
return this "My Kitchen Rules S10E35 " but i do not need the "S10E35" just return this My Kitchen Rules
Answer: You may use
w = re.match(r"(.*?)\s+S\d+E\d+", t)

and since the value you need is in Group 1:
return w.group(1)

See the Python demo, output is >>>> Regular Part:  My Kitchen Rules.
Pattern details

(.*?) - any 0+ chars other than line break chars, as few as possible
\s+ - 1+ whitespaces
S\d+E\d+ - S char, 1+ digits, E and 1+ digits

The re.match will only start matching from the start of the string, ^ at the start of the pattern is not necessary.


Prove that $(AB)C = A(BC)=ABC$ for ideals $A, B, C$

Question: This is from Theorem 2.6 (iii) of Hungerford.
My Try:
$$(AB)C=\sum_kc_k\sum_{k_i}a_{k_i}b_{k_i}$$
$$A(BC)=\sum_ka_k\sum_{k_i}b_{k_i}c_{k_i}$$
Now how can I prove they are same?
Comment: It is much more handy to work with definition of the product of ideals in terms of generators.
Comment: Can you elaborate?
Answer: The two expressions you have written down are equivalent - they both run over all finite sums of elements of the form $abc$, where $a\in A,b\in B,c\in C$.
Explicitly, you have:
$$
(AB)C=\left\{\sum_k c_k\sum_{i_k} a_{i_k}b_{i_k}\right\}\\
A(BC)=\left\{\sum_k a_k\sum_{i_k} b_{i_k}c_{i_k}\right\}
$$
Now define
$$
ABC=\left\{\sum_k a_kb_kc_k\right\}
$$
Try and show that
$$
(AB)C=ABC\\
A(BC)=ABC
$$
Comment: I think $$\sum_kc_k\sum_{i_k}a_{i_k}b_{i_k} = \sum_ja_jb_jc_j$$ since each product has the same form. So they are equal. Is this correct?
Comment: @zed111 What you've written doesn't really make sense, but I think you're close to the right answer.  What are $c_k,a_{i_k},b_{i_k},a_j,b_j,c_j$?
Comment: Do I have to show that the two are equal by showing $(AB)C\subseteq(ABC) and (ABC) \subseteq (AB)C$? i.e. for every summmation of one form there exists a summation of another form which is equal to it
Comment: @zed111 Exactly.


How to get notified about error 500 using elastic beanstalk

Question: I set up an application using elastic beanstalk and I would like to receive an email everytime an error 500 is caught containing the error message.
I'm able to receive an email using load balancer HTTPCode_Backend_5XX alarm in CloudWatch service but I don't get the error message so I can't dig through the error efficiently.
Answer: We are handling these errors in a BaseController class directly in our application and send out the notification including all data we want (exception text, stacktrace, url that generated the exception, POST values, HTTP headers, etc.) using SNS to the developers (they love it... not ;)


Override default register form

Question: <?php
/*
** Implements hook_menu().
*/
function custom_register_menu() {
    $items = array();
    $items['custom-register'] = array(
    'title' => 'Custom register',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_register_form'),
    'access arguments' => array('access content'),
  );
    return $items;
}
/*
** Implements hook_form().
*/
function custom_register_form($form, &$form_state) {
  // Display page 2 if $form_state['page_num'] == 2
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
    return custom_register_page_two($form, $form_state);
  }
  // Otherwise we build page 1.
  $form_state['page_num'] = 1;
  $form['egn'] = array(
    '#type' => 'textfield',
    '#title' => t('EGN'),
    '#size' => 20,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['last_digits'] = array(
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 4,
    '#title' => t('Last digits from the card '),
    '#required' => TRUE,
  );
  $form['authorization_code'] = array(
       '#type' => 'textfield',
     '#size' => 20,
     '#maxlength' => 6,
     '#title' => t('Authorization code'),
     '#required' => TRUE,
  );
  $form['transcation_date'] = array(
       '#type' => 'textfield',
     '#size' => 20,
     '#title' => t('Transaction date'),
     '#required' => TRUE,
  );
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Forward>'),
    '#submit' => array('custom_register_next_submit'),
    '#validate' => array('custom_register_next_validate'),
  );
  //dsm($form_state);
  return $form;
}
/**
* Validate handler for the next button on first page.
*/
function custom_register_next_validate($form, &$form_state) {
    if(!is_numeric($form_state['values']['egn'])) {
        form_set_error('egn', t('Please enter only numbers!'));
    }
    $egn_length = strlen($form_state['values']['egn']);
    if($egn_length == 10) {
    }  else {
        form_set_error('egn', t('Please insert proper ЕГН'));
    }
    if(!is_numeric($form_state['values']['last_digits'])) {
        form_set_error('last_digits', t('Please enter only digits!'));
    }
    $last_digits_length = strlen($form_state['values']['last_digits']);
    if($last_digits_length == 4) {
    }  else {
        form_set_error('last_digits', t('Please enter 4 digits!'));
    }
    $authorization_code_length = strlen($form_state['values']['authorization_code']);
    if($authorization_code_length == 6) {
    }  else {
        form_set_error('authorization_code', t('Please enter 6 digits!'));
    }

I'm building a multistep form for custom registration on Drupal 7.
The reason that I don't use hook_form_alter is because later I have to create a submit handler to a webservice and other database, but I'll open a new thread later for that.
This is a part of my code (sorry about putting text the down bellow, but drupal.stackexhange is not so friendly for putting text and codes) and you can see that I've created a menu page (custom-register).
On that page there are four fields with custom validators and next button. On the next step it should be displayed the Drupal four fields (username, password, password repeat and email) and after that it should redirect to some register successful message page.
My questions are:

How can I redirect /custom-register to user/register page? I've read about hook_form_alter, but I didn't find a way how to override user/register page.
For the second step of the form after submitting how can I create a new user like on the core user module?

EDIT:
I've managed to alter the default register form with my new form created. :) This is the code:
<?php

    function custom_register_menu_alter(&$items) {
        $items['user/register']['page arguments'] = array('custom_register_form');
        return $items;

    }

Now the next thing is to create the 4 fields (username, password, password repeat and email) and to find a right submit handler to save the user.
Answer: You can still use hook_form_alter and have a special variable (in the $_SESSION for example) to define which part of the form do you need to show. Code sample below:
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
  if ($form_id === 'user_register_form') {
     switch ($_SESSION['register_step']) {
         case 1:
              // confirm smth
         break;
         case 2:
              // establish the connections to other services, etc.
         break;
         default:
              // show initial form
         break;
     }
  }
}

Hope this is helpful.
EDIT
Some links:

Creating a user programmatically
Custom submit
handlers
Comment: Thank you for your comment, but I don't get it. If I use hook_form_alter, how can I link the first step from my custom-register form with the core register form, or do you mean I can create a multistep form with hook_form_alter?
Comment: Exactly. Alter the form to create extra steps. You can use the $_SESSION for saving the form state.
Comment: Igor, I've tried now with hook_form_alter, but I have some difficulties with it. I've put the new 4 fields from my form above and now the default username, pass, pass repeat and email are displayed too. How can I hide them on the first step and after click on the next button, the default fields to be displayed? I've didn't find any example of multistep form with hook_form_alter.
Comment: If you could show me some code example using my form it will be very nice, so I can understand how to achieve the multistep form in right order.
Comment: I would appreciate if you could tick the answer if it helped :)
Comment: Hi, t!gor. This is an old thread and previously I've answered myself here and posted the link with the solution. I've thick the answer.The multistep form in a Drupal works with a $form_state['storage'] and couple of modifications. Thanks anyway! BTW, I'm not using Drupal for a year.
Answer: I've finally done it! :)
This thread https://drupal.org/node/999420 has a great examples how to achieve the multistep form with hook_form_alter.

Override default register form


Four times the distance from the $x$-axis plus 9 times the distance from $y$-axis equals $10$.

Question: What geometric figure is formed by the locus of points such that the sum of four times the distance from the $x$-axis and nine times its distance from $y$-axis is equal to $10$?

I get $4x+9y=10$. So it is a straight line, but the given answer is parallelogram. Can anyone tell me where my mistake is?
Comment: The distance of the point $(-1,-1)$ from the $x$-axis is $1$, not $-1$.
Answer: If $P$ has coordinates $(x,y)$, then $d(P,x\text{ axis})=|y|$ and $d(P,y\text{ axis})=|x|$. So your stated condition requires $4|y|+9|x|=10$, the graph of which is shown below.


Stop lapply from printing to console

Question: When I use lapply and print to the console it prints unwanted [[i]]NULL though I want the intended message to print to the console.  I've tried suppressWarnings and suppressMessages but these do not remove the unwanted offender.  I searched lapply and don't see an argument to silence it.  This is more aesthetic as it doesn't interfere with the function.  I'm not opposed to allternative printing to the console so long as the user can turn it off if they wish.
Here's an example function, the output and what I'd like to get:
Sample function:
FUN <- function(x) {
    FUN2 <- function(z) message(z)
    lapply(1:3, function(i) FUN2(paste(x, i)))
}

FUN("hello")

Output:
hello 1
hello 2
hello 3
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

Desired Output:
hello 1
hello 2
hello 3

Comment: use `purrr::walk` instead of `lapply`
Answer: Use invisible, eg:
invisible(FUN("hello"))
hello 1
hello 2
hello 3

You can wrap it around the lapply call in the function too to make it tidier.
Comment: It's not `lapply` printing its progress as you seem to think, its R printing the returned object as James says. That's why there's no option to `lapply` that you could see. Doing `junk <- FUN("hello")` would have the same visual effect.
Comment: It temporarily disables printing of the returned object.
Comment: Perfect.  I'll add mark it as correct as soon as the time expires.  Works great (I wrapped the call to `lapply` as you suggested),
Comment: Still not sure why this works.  I've used invisible many times but not for this purpose.
Answer: Use l_ply from plyr:
library(plyr)
FUN <- function(x) {
    FUN2 <- function(z) message(z)
    l_ply(1:3, function(i) FUN2(paste(x, i)))
}
FUN("hello")

Answer: You could use a plain ol' for loop instead of lapply():
FUN <- function(x) {
  for (i in 1:3) {
    message(paste0(x, i))
  }
}
FUN("hello")

Stop lapply from printing to console


The Bass-Serre tree for BS(1,2)

Question: I'm trying to find the Bass-Serre tree corresponding to the Baumslag-Solitar group $BS(1,2)$. I could find only one reference from the Internet, which I don't understand, and although I have the corresponding graph of groups, I cannot reconstruct this tree.
Edit: from the comments below, the corresponding tree would be an infinite binary tree but I'm missing the action of the group on that tree.
Comment: For $BS(m, n)$, every vertex has $n$ edges going in and $m$ coming out. The stable letter of your HNN-extension cycles these edges.
Comment: Could you make that as an answer ? Btw, I have trouble in picturing the action of either generator... if the stable letter cycles through the edges, I end up with a cyclic group, not the infinite cyclic group.
Comment: I didn't make it an answer because I'm not 100% sure! Also, what I said was incorrect - I meant the *non*-stable letter cycles through the edges (the stable letter is the edge stabiliser, while the other letter is the vertex stabiliser.)
Comment: From what I understood, the tree is indeed an infinite binary tree. If the relation in $BS(1,2)$ is $ts=st^2$, I thought at first $t$ would shift the vertices which belong to the same level of the tree. But this doesn't seem to work, and I cannot find the action of $s$
Comment: Well, what I am certain about is that the tree *looks* like what I described (so, yes, an infinite binary tree for your case). The action...I am less sure about. Perhaps the thing to do is to work out what the action is so that the fundamental domain is what we want it to be (a single vertex and a loop edge).
Answer: I believe it works like this:
Your tree $T$ is an infinite binary tree, where each vertex has one edge going in, and two edges going out.
Let your group be given by $G=\langle a,b\mid bab^{-1}=a^2\rangle$, and let it act on the right for this tree $T$, and pick a "starting vertex".
Find a copy of the real line in this tree, with the "starting vertex" at coordinate $0$.  So at each vertex, $b$ sends some vertex along one of its children, left or right.  $a$ acts by swapping these choices.
For example, if $b$ pushes the starting vertex along its left child, then $ab$ pushes it along its right child. $b^{-1}ab$ will send a vertex up to its parent, and down the other branch.
A nice set of pictures for this is in Meier's Groups, Graphs, and Trees.  He doesn't discuss this action directly, but he shows how the Cayley graph of $G$ projects to the trivalent tree.  It is pages 117--118 in my copy.
Comment: I was thinking about something exactly like you said, but then it seemed to me that the action of $b^{-1}$ is not well defined for every vertex. Instead a figured something in which the real line on the extreme left of the tree gets translated as you said, and whatever lies on the right is folded back on the left part (It is actually quite difficult to explain without a picture...). In this view, I agree with you that conjugation translates vertices which are on the same level...
Comment: Yes, I think taking "left all the time" works fine.  I think that the action I described is correct though, because $a^2$ should act trivially.

The Bass-Serre tree for BS(1,2)


Variance of Rao Blackwellization for MC Estimate of Expectation

Question: from https://arxiv.org/abs/1401.0118
If we have a function $J(X,Y)$ of two random variables $X$ and $Y$ and we want to compute the expectation $\mathbb E_{p(X,Y)}[J(X,Y)]$.
We define $\hat J(X)= \mathbb E_{p(Y)}[J(X,Y)\mid X]$.
Note that: $$\mathbb E_{p(X,Y)}[J(X,Y)] = \mathbb E_{p(X)} [\hat J(X)]$$
So we can use $\hat J(X)$ instead of $J(X, Y)$ in a Monte-Carlo Estimate.
For the variance holds (variance reduction)
$$
var(\hat J(X)) = var(J(X,Y)) - \mathcal E[(J(X,Y) - \hat J(X))^2]
$$
Here I have one questions:

How can we prove that (variance reduction)? In the paper, no proof is given.

Here is one proof of this question (from this link):
The variance reduction follows from the the law of total variance. Suppose that $W,Z$ are two random variables, then it follows that
$$
\mathbb{V}(W)=\mathbb{V}(\mathbb{E}(W\vert Z))+\mathbb{E}(\mathbb{V}(W\vert Z))
$$
then, replace $W$ by $J(X,Y)$ and $\mathbb{E}(W\vert Z)$ by $\hat{J}(X)$ and we obtain:
$$
\mathbb{V}(J(X,Y))=\mathbb{V}(\hat{J}(X))+\mathbb{E}(\mathbb{V}(J(X,Y)\vert X))
$$
Notice that the second summand on the right hand side is given by
$$\mathbb{V}(J(X,Y)\vert X)=\mathbb{E}(J(X,Y)^2\vert X)-(\mathbb{E}J(X,Y)\vert X)^2=\mathbb{E}(J(X,Y)^2\vert X)-\hat{J}(X)^2
$$
plug into the ANOVA identity, solve with respect to $\mathbb{V}(\hat{J}(X)$ to obtain
$$
\mathbb{V}(\hat{J}(X))=\mathbb{V}(J(X,Y))-\left(\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2)\right)=\mathbb{V}(J(X,Y))-\mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
as desired.
======================== end proof ==========================
But the can't follow the idea of the last line:
$$
\mathbb{V}(J(X,Y))-\left(\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2)\right)=\mathbb{V}(J(X,Y))-\mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
why the following equality holds?
$$
\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2) = \mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
Thanks.
Answer: Another form of answer can be the following, based on the proof outlined in the post you've linked:
If you open up the square form:
$$\mathbb E[(J(X,Y)-\hat J(X))^2]=\mathbb E[J(X,Y)^2]-2\mathbb E[J(X,Y)\hat J (X)]+\mathbb E[\hat J(X)^2]$$
The middle term can be written as (using Law of Total Expectation):
$$\mathbb E[J(X,Y)\hat J (X)]=\mathbb E[\mathbb E[J(X,Y)\hat J (X)|X]]=\mathbb E[\hat J(X)\mathbb E[J(X,Y)|X]]=\mathbb E[\hat J(X)^2]$$
When substituted, you've the equality.
Answer: The Pythagorean decomposition of the variance
$$\mathbb{V}(W)=\mathbb{V}(\mathbb{E}(W\vert Z))+\mathbb{E}(\mathbb{V}(W\vert Z))$$
shows that the original variance is a sum of two positive terms, hence
$$\mathbb{V}(W)\ge\mathbb{V}(\mathbb{E}(W\vert Z))$$
showing that both versions have the same expectation and that the conditional expectation has a smaller variance.


App crashes when taking photos quickly

Question: In my app I have a button that takes a photograph and saves it. The preview is not displayed.
The app works fine if i click the button every 1-2s but if I click it faster the app crashes. I am able to take all the photos I want as long as I don't click the button too fast.
PhotoFragment.java:
public class PhotoFragment extends Fragment {
    private final static String LOG_TAG = PhotoFragment.class.getSimpleName();
    private Camera mCamera;
    private SurfaceTexture mSurfaceTexture; // mSurfaceTexture must be global to avoid log error spam

    public static PhotoFragment newInstance() {
        Bundle args = new Bundle();
        PhotoFragment fragment = new PhotoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public PhotoFragment(){}

    @Override
    public void onStart() {
        super.onStart();
        getActivity().setTitle(R.string.photo);
    }

    @Override
    public void onResume() {
        super.onResume();
        safeCameraOpen();
    }

    @Override
    public void onPause() {
        super.onPause();
        releaseCamera();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_content, container, false);

        Button yo = (Button) rootView.findViewById(R.id.pic);
        yo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mCamera == null){
                    Log.w(LOG_TAG, "@onCreateView mCamera is null!");
                }
                mCamera.takePicture(null, null, mCall);
            }
        });

        Button yoyo = (Button) rootView.findViewById(R.id.vid);
        yoyo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        return rootView;
    }

    Camera.PictureCallback mCall = new Camera.PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            //decode the data obtained by the camera into a Bitmap and save it

            FileOutputStream outStream = null;
            try {
                String sdCardDirectory = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                        .getPath();

                outStream = new FileOutputStream(sdCardDirectory
                        + Utils.getPictureFilename());

                outStream.write(data);
                outStream.close();
            } catch (FileNotFoundException e){
                Log.d("CAMERA", e.getMessage());
            } catch (IOException e){
                Log.d("CAMERA", e.getMessage());
            }
            mCamera.startPreview();
        }
    };

    private boolean safeCameraOpen() {
        boolean qOpened = false;
        try {
            releaseCamera();
            mCamera = Camera.open();
            mSurfaceTexture = new SurfaceTexture(Activity.MODE_PRIVATE);
            mCamera.setPreviewTexture(mSurfaceTexture);
            mCamera.startPreview();
            qOpened = (mCamera != null);
        } catch (Exception e) {
            Log.e(LOG_TAG, "failed to open Camera");
            e.printStackTrace();
        }
        return qOpened;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

}

Stacktrace:
E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.dcs.hiddencamera, PID: 10561
                                                                      java.lang.RuntimeException: takePicture failed
                                                                          at android.hardware.Camera.native_takePicture(Native Method)
                                                                          at android.hardware.Camera.takePicture(Camera.java:1434)
                                                                          at android.hardware.Camera.takePicture(Camera.java:1379)
                                                                          at com.dcs.hiddencamera.PhotoFragment$1.onClick(PhotoFragment.java:72)
                                                                          at android.view.View.performClick(View.java:5204)
                                                                          at android.view.View$PerformClick.run(View.java:21153)
                                                                          at android.os.Handler.handleCallback(Handler.java:739)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                          at android.os.Looper.loop(Looper.java:148)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Answer: Handle runtimeexception in your onClick, also try disabling the button inside onclick and re-enable it after the picture has been saved. The camera apparently cant process two consecutive take picture commands if given too fast. the exception source is inside native camera code.
Comment: I tested it and fixed it. Thanks. It was really simple.
Comment: Thanks for the reply, how do you suggest enabling/disabling the button? Maybe a global variable?
Comment: yeah go with a instance variable for button.

App crashes when taking photos quickly