Limit Involving Factorials

Question: How would you go about calculating
$$
\lim_{x \to \infty} \frac{x!}{(x - k)!}
$$
for some constant $k > 0$?
Comment: Stirling approximation.
Answer: Hint: $\frac{x!}{(x-k)!} = (x-k+1)*(x-k+2)*...*(x-1)*x$
Answer: Take upper and lower bounds:
$$
(x-k+1)^k \leq x(x-1) \ldots (x-k+1) \leq x^k
$$
and apply squeeze lemma. What do you get?

Limit Involving Factorials


Schlafli symbols for antiprisms, crossed antiprisms

Question: I am familiar with Schlafli symbols for polygons and polygrams, but it gets way more complicated for antiprisms.  I get that {7} describes a heptagon, {7/2} describes a heptagram with 7 edges where each edge skips to every 2nd vertex around the shape, and {7/3} describes a heptagram with 7 edges where each edge skips to every 3rd vertex around the shape.
However, looking at an antiprism, , the Schlafli symbol is either s{2,2n} or sr{2,n}.  Does anyone know how to interpret this?
Finally, does anyone know how to notate with a Schlafli symbol how many vertices are skipped from the top base to the bottom base (or vice versa) in the following crossed antiprisms?  Also, does anyone have a good definition for a crossed antiprism?  Any help on any part of this is appreciated.
Comment: I don't really know what {2,n} means, that's one of the things I was asking about.  I was ideally looking for a solution explained more as a concept (as in "7/2 means that the shape has seven edges and each edge skips to every 2nd vertex") rather than a formula for determining the number or location of vertices or faces.
Comment: Okay, how about this: A $\{p/q\}$ antiprism is two congruent $\{p/q\}$ polygons, sharing their axis of symmetry, connected by equilateral triangles.... Given one of the two polygons, there are only two possible ways to place a triangle, sharing one edge with the polygon, such that the triangle's opposite vertex could be a vertex of the second polygon. Specifically, the triangle could slope away from the axis, or it could go through the axis. The latter case has $q>\tfrac12p$, and is crossed.
Comment: In this context, it helps to make a distinction between $\{7/3\}$ and $\{7/4\}$. (I think of the latter as being inside-out, in some sense, even though a star polygon doesn't really have an inside. This notion can be formalized using normal vectors.) A [crossed antiprism](https://en.wikipedia.org/wiki/Antiprism#Star_antiprism) is just an antiprism of a polygon $\{p/q\}$ where $q>\tfrac12p$.
Comment: I would hesitate to call an antiprism a snub. As an abstract polyhedron, $sr\{2,n\}$ would have some [digon](https://en.wikipedia.org/wiki/Digon) faces and only rotation symmetry, while an antiprism has no digons and has reflection symmetry. And some level of abstraction is necessary, if we're talking about star polygons or $\{2,n\}$. Considering that $\{2,n\}$ is made of only digons, I think we'd need to add something to the Schlafli symbol $sr\{2,n\}$ to explicitly remove the digons in the end.
Comment: Anyway, take a look at [these](https://youtu.be/8TSDZlJuTfc) [videos](https://youtu.be/zVqwaEffkTg) (time 7:32-7:54 and 1:36-2:30 respectively) to see how snubs can be constructed in general.
Comment: For your first question: Do you know what $\{2,n\}$ means by itself? (There are several possibilities.)
Comment: For your last question: Continuing from my first comment, an antiprism of a polygon $\{p/q\}$ has vertex coordinates as given on Wikipedia, with $n=p/q$: $$v_k=(\cos(k\pi q/p),\sin(k\pi q/p),(-1)^kh),$$ $$0\leq k<2p,$$ and it has triangular faces connecting vertices $v_k,v_{k+1},v_{k+2}$ (modulo $2p$), and a polygonal $\{p/q\}$ face connecting the even vertices $v_{2k}$, and another connecting the odd vertices $v_{2k+1}$. You can equate a triangle's two edge lengths, and solve to find the antiprism's half-height $h$. -- Is that sufficient as a definition?
Comment: (The triangle can rotate around the first polygon's edge, so that its opposite vertex traces a circle. The symmetry and congruence of the two polygons imply that all vertices must be on a cylinder. The circle intersects the cylinder in two points, so there are two ways to place the triangle.)
Comment: (Actually, the circle intersects the cylinder in four points, but two are above and two are below the first polygon. The four resulting antiprisms are congruent in pairs.)
Comment: Thanks for those.  If you put one as an answer rather than a comment I can award you the bounty.
Comment: To compare my answer with relatives of the cube, see the picture on the right here: https://en.wikipedia.org/wiki/Archimedean_solid#Construction_of_Archimedean_solids
Answer: I think your questions should have been split into two posts: one about Schlafli symbols for convex antiprisms, and one about crossed antiprisms. The latter has been answered in comments, so here I'll answer the former. (I hope you're familiar with Schlafli symbols for relatives of the cube $\{4,3\}$, for comparison.)
$\{2\}$ is a digon, a polygon with two edges. $\{n,2\}$ is a dihedron, a polyhedron with two $n$-gon faces. $\{2,n\}$ is a hosohedron, a polyhedron with $n$ digon faces. These can be thought of either as abstract polyhedra, or as polyhedra with curved faces, or as degenerate polyhedra with coincident faces.

(Each polyhedron is shown from a top view and a side view.)
The operations of truncation and rectification can be applied to these:

And then the cantellate $rr\{2,n\}$ can be twisted to make the snub:

As you can see, this is not quite an antiprism; it has some digon faces, and no reflection symmetry.
As a different way to construct the snub, the omnitruncate $tr\{2,n\}$ can be alternated (meaning every other vertex is deleted, so e.g. a decagon becomes a pentagon). But what is alternation exactly, when digons are allowed? Does a square become an edge, or a digon? It is ambiguous.
Well, if the digons are removed in the end, everything seems to work fine.


Table without date and Primary Key

Question: I have 9M records. We needed to do the following operations:-
daily we receive the entire file of 9M records with 150GB of file size
It is truncate and loads in Snowflake. Daily deleting the entire 9B records and loading
We would want to send only incremental file load to Snowflake. Meaning that:
For example, out of 9Million records, we would only have an update in 0.5Million records(0.1 M Inserts,0.3 Deletes, and 0.2 Updates). How we will be able to compare the file and extract only delta file and load to the snowflake. How to do it cost-effectively and fast way in AWS native tools and load to S3.
P.s data doesn't have any date column. It is a pretty old concept written in 2012. We need to optimize this. The file format is fixed width. Attaching sample RAW data.
Sample Data:
https://paste.ubuntu.com/p/dPpDx7VZ5g/

In a nutshell, I want to extract only Insert, Updates, and Deletes into a File. How do you classify this best and cost-efficient way.
Comment: You've tagged this for Oracle, Teradata, and DataStage but your question doesn't seem to indicate that you are using any of these three tools.  You've also tagged this for SQL but it's not clear that using SQL would make sense if you're trying to compare the data in two different flat files which is what it sounds like you're doing.
Answer: CDC stage comes by default in DataStage.
Using CDC stage in combination of Transformer stage, is best approach to identify new rows, changed rows and rows for deletion.
Comment: There is no unique keys in my table. You may have seen the data in the question. Should I use all the columns if I do not have primary key column?
Answer: Your tags and the question content does not match, but I am guessing that you are trying to load data from Oracle to Snowflake. You want to do an incremental load from Oracle but you do not have an incremental key in the table to identify the incremental rows. You have two options.

Work with your data owners and put the effort to identify the incremental key. There needs to be one. People are sometimes lazy to put this effort. This will be the most optimal option
If you cannot, then look for a CDC(change data capture) solution like golden gate
Answer: You need to identify column(s) which makes row unique, doing CDC with all columns is not recommended, DataStage job with CDC stage consumes more resources if you add more change columns in CDC stage.
Work with your BA to identifying column(s) which makes row unique in the data.
Comment: To make row unique if you had to use all columns, then doing truncate and load is the right option.
Answer: I had the similar problem what you have. In my case, there are no Primary key and there is no date column to identify the difference. So what I did is actually, I used AWS Athena (presto managed) to calculate the difference between source and the destination. Below is the process:

Copy the source data to s3.
Create Source Table in athena pointing the data copied from source.
Create Destination table in athena pointing to the destination data.
Now use, SQL in athena to find out the difference. As I did not have the both primary key and date column, I used the below script:

select * from table_destination
except
select * from table_source;

If you have primary key, you can use that to find the difference as well and create the result table with the column which says "update/insert/delete"
This option is aws native and then it will be cheaper as well, as it costs 5$ per TB in athena. Also, in this method, do not forget to write file rotation scripts, to cut down your s3 costs.

Table without date and Primary Key


Communicating via Command Mode with IBM HS22 IMM via AMM

Question: On previous model blades that contained a BMC, I was able to communicate from our external management station via pass-through commands to the BMC to do things such as power blades on/off, set VPD parameters, reboot the BMC, etc.
Now on the HS22, a bunch of things happen differently. For example, we can no longer use the same pass-through commands to write VPD information pages and have them persist across reboots of the IMM - it looks as though those VPD pages are populated from information contained in the IMM.
How do we use the Advanced Settings Utility from an external host to communicate with HS22 IMMs? Alternatively, what TCP Command Mode commands do we need to send to the AMM to communicate with the IMM?
For our purposes, we specifically cannot communicate with the IMM from the blade itself.
Specific example:
When I send a pass-thru IPMI command via the AMM to the blade BMC to write information (such as MTM, Serial) into VPD page 0x10, it persists on blades with a BMC (HS21 for example). I can send the same IPMI command to write data to the VPD page on the HS22, however it does not persist across reboots of the IMM.
What IPMI commands do I need to send to the IMM? What IPMI commands are asu sending when it sets the MTM & Serial?
Comment: This has to be about the most technical question I've ever seen asked here. Perhaps it's something for an IBM technician to answer?
Comment: Heh, I've tried going that route to no avail. Figured I may as well take a stab at it here :)
Answer: As of ASU (Advanced Settings Utility) version 82k/9.50, out-of-band communication to blade IMMs is supported.
Here is an excerpt from pages 83-84 of the ASU user manual (http://download.boulder.ibm.com/ibmdl/pub/systems/support/system_x_pdf/ibm_util_asu_asu82k_anyos_noarch.pdf):

OOB Configuration for blades on AMM
ASU supports the configuration of blade settings through the out-of-band (OOB)
  mode. This section describes how to use it to configure blades on AMM.
The OOB configuration is designed to configure settings of blades on AMM. Before
  you use this function, ensure that the following requirements are met:

The remote blades on AMM are connected to your network environment.
The blade is an IMM-based server.
Add the --slot argument to force ASU to connect with the remote AMM. If not,
  ASU will try to establish a connection with the provided IP address in an IMM
  out-of-band mode by default. And the --slot argument also can identify the
  blade's IMM node bay.
Add the --host, --user and --password connectivity options because it is on
  out-of-band mode.
– --host provides the IP address of the remote AMM where the blade is.
– --user and --password authenticate to the AMM.

Command Examples:
To show a remote blade UEFI setting: asu show uefi --host x.x.x.x --user xxx --password xxx --slot x
To set a remote blade setting: asu set SETTING_NAME xxx --host x.x.x.x --user xxx --password --slot x --port 6090
In the examples, --host x.x.x.x is the IP address of the remote AMM, --user xxx and --password xxx are used to authenticate the connection, --slot x refers to the IMM node bay of the blade, and --port provides the port number for AMM chassis interface; the default is 6090.
The commands supported by OOB configuration for blades on AMM are listed
  below.

Command           Description

show              Display IMM server setting
set               Update IMM server setting
showdefault       Display IMM default server setting
showvalues        Display IMM values server setting
showgroups        Display IMM setting for server groups
batch             Execute several ASU commands simultaneously
createuuid        Generate a UUID value and set it
comparedefault    Compare the default value with the current value
delete            Delete an instance of a setting
help              Show description for selected settings
loaddefault       Load the default value
replicate         Replicate settings saved in a settings file
restore           Restore settings saved in a settings file
save              Save all or some settings to a settings file
setenc            Apply an encrypted value to a setting

Answer: Well, the procedure below should do what you want:
Issue the following command to view the current settings for the machine
type and model:
asu show SYSTEM_PROD_DATA.SysInfoProdName
Issue the appropriate ASU command to set the machine type and model:
asu set SYSTEM_PROD_DATA.SysInfoProdName 7870-mmm

Where 7870 is the machine type for HS 22, and mmm is the model,  e.g. D2G
Issue the following command to verify that you set the machine type
and model number correctly:
asu show SYSTEM_PROD_DATA.SysInfoProdName
Issue the following command to view the current setting of the serial number:
asu show SYSTEM_PROD_DATA.SysInfoSerialNum
Issue the following ASU command on the SONAS node to set the serial number:
asu set SYSTEM_PROD_DATA.SysInfoSerialNum xxxxx
The variable xxxxx in the command stands for the serial number.
Issue the following command to verify that you set the serial number correctly:
asu show SYSTEM_PROD_DATA.SysInfoSerialNum

I didn't have a chance to verify it, so YMMV.
This however, must work. It's the official guide to updating VPD on HS22 using ASU (with botched HTML escaping). If it doesn't work, then open a ticket with support.
Edit: amendment and elaboration
The procedures above directly answer your question: "How do we use the Advanced Settings Utility from an external host to communicate with HS22 IMMs?" and specifically your example of setting VPD. They also meet your criteria of not requiring to communicate with IMM from the blade itself (you can access IMM over a network).
They also, albeit indirectly, answer your final questions: "What IPMI commands do I need to send to the IMM? What IPMI commands are asu sending when it sets the MTM & Serial?"
If you try these procedures and verify, that any of them does work correctly, you can dump the network traffic and see what is being sent. This isn't a very user-friendly approach, but if you want things done, it will work.
Comment: You can't actually communicate with the IMM of a blade over the network from outside the chassis.


What should I do when a question has been incorrectly marked as duplicate?

Question: A question has been marked as duplicate saying it has already an answer on another question.
However it does not and even if the question could sound similar, it is a totally different problem.
I do not think it happens very often as it's very unlikely that 5 different people can miss such subtitle situation but I was wondering what should I do?
FYI the question I'm referring to is this one: Error after installing patch 7405 on Magento 184.108.40.206
Comment: This might seem like I'm targeting your meta questions, I'm not! This question has also been asked a thousand times across the network. No need to ask it again.
Comment: No worries mate that's my bad as I said on my other comment I'll do better the next time
Answer: The best (and only) thing to do is to post here in Meta for us to review. I have reopened and added a comment to the answer to signify that it is due to the version you are running.
Comment: Great thanks for that
Comment: I think there really needs to be a mechanism where the author of the question can appeal the closure or post more information to clarify why their question is not a duplicate. My questions have been incorrectly closed several times and it's fucking maddening.


Why is that $\widehat{\mathbb{R}/\mathbb{Z}}\cong\mathbb{Z}$?

Question:
$\widehat{\mathbb{R}/\mathbb{Z}}\cong\mathbb{Z}$, that is, every character of $\mathbb{R}/\mathbb{Z}$ is of the form $x\mapsto e(mx)$ for some integer $m$.

I was considering the dual of ${\mathbb{R}/\mathbb{Z}}$. What confused me is why we can assign an integer $m$ to the character $\chi.$
Thanks in advance! Any comment is appreciated!
Answer: We can identify $\mathbb R / \mathbb Z$ with the circle group
$\mathbb T=\{z \in \mathbb C \mid |z|=1\}$,
 with the multiplication coming from $\mathbb C$.
We map $x \to e^{2 \pi i x}$. Then $x+y \pmod 1 \mapsto e^{2 \pi i (x+y) \pmod {2\pi}}$, so this will be a group isomorphism.
Then the characters of $\mathbb T$ are the continuous group homomorphisms from $\mathbb T \to \mathbb T$.  So, thinking about this geometrically, we start at $1$ and then wind our way around the circle an integer number of times. It must be an integer because group homomorphisms must map $1$ to $1$. Anticlockwise or clockwise will correspond to positive and negative integers. Clearly, each integer will give us a different character and we obtain all characters in this way.
So the set of characters is given by
$$
\{x \mapsto e^{2 \pi imx} \mid m \in \mathbb Z \}, \text{ for } x \in \mathbb R/\mathbb Z.
$$
Comment: Tom, it is a great answer! I have a further question, though. What are the things like if $m$ is not an integer, that is, the dual group of $\mathbb{R}^+$ or $\mathbb{R}^×$ with additive character $\chi_\alpha$ of the form $\chi_\alpha: x\mapsto\chi_\alpha(x)=e(x\alpha)$ for some complex number $\alpha$? It seems to me that we could not think it this geometrical way.
Answer: $m$ is the size of the pre-image of 1. (And $m=0$ if the preimage is everything.)
Comment: @Phiar, thanks for the answer! I have one more question. Like my reponse to Tom, how can we explain if $m$ is not an integer, that is, the dual group of $\mathbb{R}^+$ or $\mathbb{R}^×$ with additive character $\chi_\alpha$ of the form $\chi_\alpha: x\mapsto\chi_\alpha(x)=e(x\alpha)$ for some complex number $\alpha$?


Number of integer solutions $0 < x < y < z < 25$

Question: Question 11 from Practice Exam #1 pg. 24 of Counting: The Art of Enumerative Combinatorics by George E. Martin.
How many integer solutions are there to the system 0 < x < y < z < 25 ?
My solutions is count the number of permutations of 3 C's (for choose ) and 21 R's (for reject). Using this technique, I get the following answer:
$$
    \frac{24!}{3!21!} = 2024
$$
Is this answer correct?
Comment: Can you post the statement of the question?
Comment: Just to add color - x>=1 and z<=24
So all numbers have to be bound between [1;24]. As x<y<z, the three numbers are distinct and (x;y;z) is a sorted array. Hence the question can also be treated as choosing 3 numbers (without repetition) between 1 and 24 where only one order (ascending) is required. So its 24C3
Answer: Yes, this is correct. Incidentally this is also the number of three element subsets of a set with $24$ elements, also known as $\binom{24}3$.
Answer: Yes your answer is correct. The fact that the no of ways using that is correct because when three numbers are selected randomly from 24 numbers with order not being important ,then  x, y, z gets satisfied. So the thing is 24p3/3!


Termination of a server program by a button in Java

Question: I am writing a server application in Java where i have in an activation method of MyServer class:
    System.out.println("The Base Station was activated");
    Socket s;       //Here it listens for new connections

    this.server = new ServerSocket(this.getPort());

    while(activated == true)
    {
        s = this.server.accept();
        ClientHandler ch = new ClientHandler(s);
        Thread servingThread = new Thread(ch);
        servingThread.start();
    }

It is waiting for clients to connect and it spawns a thread to accommodate each client. I also want to support a deactivation button in my GUI, but i can't see how the ActionListener for that button, which is defined in a MyServerFrame class, can ever be called and change the status of activated variable if the above server code is stuck waiting in accept. How can i overcome this problem?
Answer: You will have to give access to the server socket inside the class holding the stop button handler (for example by passing the MyServer instance to the MyServerFrame instance) and inside the handler close the socket, such that the call to accept returns and then you can exit the while loop.
So inside the handler you should be able to do:
myServer.setActivated(false);
myServer.closeSocket(); // inside you have this.server.close();
// assuming you have passed the MyServer object to the form.

Comment: i did that but my problem seems to be that i can't click on "Deactivate" button of the Frame, so i never reach the handler code. The button is 'dead' and the program is stuck on the above while loop
Comment: Are you running the code with the while loop on a different thread or the same thread as main form?
Comment: the main form creates a Frame instance, and on the frame constructor i have the ActionListener that calls the method of the while loop. On the same Frame constructor i have the ActionListener that must end the server program. So it is the same thread i guess.
Comment: You will need to create another thread to run the code with the while loop. The main thread of the form needs to listen to messages from the user like your button click, but if you block it with the while loop, it cannot intercept your button click.
Comment: ok i got it thank you! (if i create a seperate thread to listen for connections, it will be able to spawn new threads to accommodate each client, right?!. Sorry for the dumb questions but i am new at Java!)


How come > working as >?

Question:
suppose we have
class Fruit implements Comparable<Fruit>
{
    @Override
    public int compareTo(Fruit o) { return 0; }
}

class Apple extends Fruit{}

class Main
{

    public static void main (String args[])
    {
        function(new Apple()); // this shouldn't work because Apple is implementing Comparable<Fruit>, not Comparable<Apple>
    }

    public static<T extends Comparable<T>> void function(T t){}
}

Code is working without any issue.
My question is why <T extends Comparable<T>> working like <T extends Comparable<? super T>>. whats the difference ?
Thanks.
[Edited] -  A passage from book
Image
Comment: No both scenarios are different.
Comment: Possible duplicate of [Difference between  and  in Java](http://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java)
Answer: In this case it is beacuse class Fruit is a superclass of itself
The difference is here
<T extends Comparable<T>> accepts Comparable with arguement of type T
<T extends Comparable<? super T>> accepts Comparable with arguements of type T and its super classes. Here Since in java every class is a superclass of itself, Fruit is also a superclass of Fruit .Thats why you see like they are working the same way
But if you used class Apple as T you will see the difference.
Comment: if this is the case then this should also work but it isn't.

call : `function(new ArrayList());` ---

protoype : `private static> void function(List t){}`

it requires `>` as it should be.
Comment: no in generics List is not a subclass of List.
Comment: @Ibrahim In your case ,  the comment // this shouldn't work because Apple is implementing Comparable, not Comparable is not right. in this case Apple in implementing Comparable Because you are passing type Apple to function
Comment: Okay but we know that Apple is a subclass of Fruit So whether it implements comparable  even Apple will fit there beacause apple IS A FRUIT
Comment: `f=a; // Error : Type mismatch: cannot convert from List to List`
Comment: Thanks..Thats where super comes in
Comment: yea exactly, but why java going against book. don't know.
Comment: Yeah i think its java version issue. as well now
Answer: You compile with Java 8 I think.
Because, before Java 8, you should not pass the compilation and have this error :

Bound mismatch: The generic method function(T) of type Main is not
  applicable for the arguments (Apple). The inferred type Apple is not a
  valid substitute for the bounded parameter >

I think what you read in your book refers to generic use before Java 8.
But i didn't know that Java 8 had less constraint on this kind of case.
Is it a side-effect of the large use of inference in Java 8 that Java 8 calls the "improved inference" ?
Comment: yes i was using java8. Just Compiled with jdk 1.6 and got compilatation error, while java8 compiles smoothly.
Comment: It kinda seems to be java 8 bug because if we change function defination to
Comment: `private static> void function(List t){}`
Comment: and then call it like
Comment: `function(new ArrayList());`
Comment: Java 8 also gives compilation error, which seems right.
Thanks for clearing. @davidxxx
Comment: Just for your information, book is written for java 8. Core Java Volume 1 - Fundamentals 10th edition by Cay S. Horstmann

How come > working as >?


Como quebrar minha String corretamente?

Question: Bom, estou utilizando o {split()} para extrair dados enviados de uma API. Estou fazendo um get dentro do código e pegando a resposta para tratamento. A resposta desse get é longa e preciso somente do corpo... {body}. Quando utilizo o {response.body} junto com split acabo recebendo um vetor separado por caractere e não por linha como normalmente. Segue código abaixo:
Response response = client.newCall(request).execute();

        String respostaRequest = new String(response.body().string());

        String respostaAutomatica = respostaRequest.split("\r")[0];

        System.out.println(respostaAutomatica);

        System.out.println(respostaAutomatica.length());

        String idCaixaOperacaoRetorno = respostaAutomatica.split("|")[3] +
                respostaAutomatica.split("|")[4] +
                respostaAutomatica.split("|")[5] +
                respostaAutomatica.split("|")[6] +
                respostaAutomatica.split("|")[7] +
                respostaAutomatica.split("|")[8] +
                respostaAutomatica.split("|")[9];

        String status = respostaAutomatica.split("|")[0] + respostaAutomatica.split("|")[1];

        if (respostaAutomatica != null && respostaAutomatica != "") {

            if (status.equals("OK")) {

                try {

                    System.out.println("Id Caixa Operação: " + idCaixaOperacaoRetorno);
                    System.out.println("Satus: " + status);

                } catch (Exception e) {

                }

            }

        }

Quero poder separar a string por linha e não por caráctere.
Comment: Já descobri meu problema, agora tenho que descobrir como resolver hehe... Seguinte o método split não está conseguindo interpretar o "|" como separador da string e ai separa cada carácrete. Preciso entender mais sobre carácteres especiais para poder resolver isso.
Comment: Pronto, resolvido...

Na função split quando pede o regex, coloquei assim:

String status[] = respostaRequest.split("\\|");

Isso foi falta de experiência da minha parte, obrigado quem possa ter pensado para responder.
Answer: Quando eu colocava o seguinte código:
String status[] = respostaRequest.split("|");

O Java separava a string respostaRequest por caráctere e não dividia corretamente pelo "|", então encontrei em alguns lugares para testar com "\|" e ficou assim:
String status[] = respostaRequest.split("\\|");

Então a String OK|6339105|Isento foi dividida em um vetor com valores.

Citação

Como quebrar minha String corretamente?


Is there a number field with + and - feature?

Question: I am working with Form API to create a customized form shown in a block. Most of the fields are textfields.
I need a +/- feature for a numeric textfield, i.e.:

Is there an existing field like the above I can use?
Comment: As an alternative, why not use a standard html5 number field instead? That already has an up/down button spinner provided by the browser
Answer: Try the Stepper Field module

The Stepper Field module is based in a plugin for jQuery UI called jQuery.ui.Spinner and provides a new steps widget that can be added to any Integer field.

Here is the image
Answer: There is SpinInt module for this

Spinint provides a simple up down arrow widget for integer number fields.


Https causes too many redirects on Safari

Question: I recently started redirecting my domain to https and I am getting a "too many redirects" error on Safari, especially on mobile. Everything works fine on any computers and in any other browsers.
Here's how I've done my redirects.
for main domain
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example\.com%{REQUEST_URI} [R=301,L,NE]

I also disabled Cloudflare because it was causing issues with my SSL and I fixed some issues with DNS propagation.
EDIT:
It affects all safari browsers except for computers and deleting the cache doesn't solve the issue. I only have one domain, but a few subdomains.
I do have other directives in .htaccess:
RewriteCond %{HTTP_HOST} ^example.com$ [OR]
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^folder\/?(.*)$ "http\:\/\/example\.com\/all\-categories\/folder\/$1" [R=301,L]

EDIT: SOLVED
Changing host solved this problem for me.
Comment: If this problem is only affecting one browser, on one machine(?) then it strongly suggests a client-side caching issue. If there was something wrong with the directives in .htaccess then it would affect _all_ browsers on _all_ machines. Do you have multiple domains? Do you have any other directives in your .htaccess file?
Answer: As you're using CloudFlare's Flexible SSL; the web server might not be able to correctly identify when the connection should be over SSL and when it shouldn't.
As such you should attempt to install Mod_CloudFlare on your webserver to resolve this, if you can't do this, you can instead set your SSL environment variable from the X-Forwarded-Proto header in your Apache .htaccess:

SetEnvIf X-Forwarded-Proto https HTTPS=on
Comment: I disabled CloudFlare.
Answer:
RewriteRule ^folder\/?(.*)$ "http\:\/\/example\.com\/all\-categories\/folder\/$1" [R=301,L]

Since you are redirecting everything to https, you should also be doing this in the above redirect. Otherwise you are going to end up with additional (unnecessary) redirects. So this should be rewritten as:
RewriteRule ^folder/?(.*) https://example.com/all-categories/folder/$1 [R=301,L]

I have also tidied up the regex and substitution (this looks like something cPanel would generate?). There is no need for all the backslash escapes (and double quotes) in the RewriteRule substitution. And the backslash escape in the RewriteRule pattern is also superfluous.
However, I doubt whether this alone is enough to satisfy Safari (mobile). (?)
Comment: Thanks for your feedback. I decided to change web host because my website was down too often lately so I will try this solution shortly.
Comment: Everything works well with the new host, but I still rewrote my redirects just to have a cleaner code.
Comment: Any luck at the new host?
Answer: I fixed it by using following method
RewriteCond %{SERVER_PORT}  !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} off

is causing the error. use

RewriteCond %{SERVER_PORT}  !^443$

to fix it.


Switch Membership Profile to other Profile without password?

Question: I've an application where every user stores his settings with the AspNetSqlProfileProvider in the aspnet_Profiles table. Now I want to give the administrator the possibility to switch to another user to see his settings. But I don't know the windows password of the other user (and I don't want to know it) so I'm not able to use the windows impersonate function, right?
So is there any possibility to switch to another user profile without password?
Thanks!
Comment: Do you use Windows Authentification or Form Authentification ?
Comment: Windows Authentication (sorry, forgot it)
Answer: Yes it is possible to switch from user profile without password, you have to implement your own membership provider and your own loginpage for the super user. In the custom membership provider you do not authenticate the login on username and password, but on the username and superuser credentials. If the superuser is logged on he can access the 'switch' page.
Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
Comment: Isn't this for form authentication only?
Comment: Yes it is. I'm almost sure it is not possible with windows authentication.


When can we say that something is equal to, rather than something approaches a limit?

Question: As an example, if we have a binary term $x$, like this

$x = 0.d_1 d_2 d_3 \dots$
Where $d_1 = 1$ if $x < \frac{\pi}{ 10}$ else $d_1 = 0$
$d_2 = 1$ if $x < \frac{\pi}{ 10}$ else $d_2 = 0$
$d_3 = 1$ if $x < \frac{\pi}{ 10}$ else $d_3 = 0$
$\dots$
$d_n = 1$ if $x < \frac{\pi}{ 10}$ else $d_n = 0$
$\dots$

Then we will probably agree that we approach our limit or $\lim\limits x \to  \frac{\pi}{ 10}$
but  will $x = \frac{\pi}{ 10}$ or will $x$ always be $x < \frac{\pi}{ 10}$

Note: $ \frac{\pi}{ 10} = 0.314159 \dots$ or binary $
> 0.01010000011011001 \dots$
Comment: Perhaps you intended to use the finite truncations of $x$ in your setup.  As it is you have defined the bit sequence $d_i$ in two (inconsistent) ways.
Comment: The definition of $x$ is circular: $x$ depends on $d_i$ and $d_i$ depends on $x$.
Comment: Suppose that $x$ and $\frac{\pi}{10}$ are given numbers.  The condition $x \lt \frac{\pi}{10}$ is then either always true or always false, but you've used this same condition to "define" the bit sequence $d_i$ in the second way.  But now either all $d_i=1$ or all $d_i=0$, depending on whether that condition involving $x$ and $\frac{\pi}{10}$ happened to be true or false.  I suggested that maybe you intended to use the truncations of (the binary expansion of) $x$ in some fashion, and thus avoid defining all the $d_i$'s to be the same bit.
Comment: I'm pretty sure I understand the idea for building the "base 2" representation of a number "with a spreadsheet" that you allude to, but the language of your Question repeatedly tests the condition $x \lt \frac{\pi}{10}$ to determine bit $d_i$.  This is not the test "if the sum of all rows is less than our target".
Comment: @Cuspy Code the $d_i$ depends on $ \frac{\pi}{ 10}$, if $d_1$ is 1/2 then $x$ will be greater than the target $ \frac{\pi}{ 10}$, even if all the other digits are 0, so it must be 0. And $d_2$ must be 1/4 because if all the other values were 0, would still be less than our target. And so on, each $d_i$ can only have one value, thus it is not circular.
Comment: @hardmath I don't understand why you say "inconsistent", as there is only one way our bit sequence can be. Or so it seems to me.
Comment: @hardmath I can use that method to convert base 10 to base 2 with a spreadsheet. Just set every row to 0 then set the first cell to 1/2. Then if the sum of all rows is less than the target, then our binary number will begin with 0.1 else 0.0, then set the next cell to 1/4 and if the sum of all rows is less than our target, then that bit is 1 else 0. The idea is simple, there just may exist no math notation to represent the idea, but that is irrelevant to the question being asked. I just want to know do we "approach" or "equal" our target?
Answer: No, we wouldn't agree.
In general, given the binary digits $d_1, d_2, \ldots$,
$ x = .d_1d_2d_3 \ldots $ is a single number, not something depending on $n$.  It's actually
$$\sum_{k=1}^\infty d_k 2^{-k} = \lim_{n \to \infty} \sum_{k=1}^n d_k 2^{-k}$$
so the limit as $n \to \infty$ is "built-in".
Comment: The question was does $x$ equal $\frac {\pi}{10}$ or does $x$ approach $\frac {\pi}{10}$.
Comment: I suppose if you put "$x =$" in front of your first sigma then you will have answered the question.
Answer: All  expansions below are binary, not decimal.
You're treating $x$ as both a sequence and a real at the same time; as a result, the definition of $x$ you've written is indeed circular. Put another way:

It doesn't make sense to check "Is $x<{\pi\over 10}$?" without having fully defined $x$ first, so you can't refer to $x$ while defining $x$.

This doesn't mean that your idea is meaningless, just that you haven't written what you intend. So before I can answer your question, I need to clear up your definition of $x$.
What you're really trying to do is define a sequence of approximations to the real $x$ you want to build. Informally, to get from $x_n$ to $x_{n+1}$ we "tack on" the biggest binary digit to the end of $x_n$ which keeps us below ${\pi\over 10}$. Formally, we define $x_n$ recursively (or inductively) as follows:

$x_0=0$.
Having defined $x_n$, we let $x_{n+1}=x_n+2^{-n-1}$ if that's $<{\pi\over 10}$ and $x_{n+1}=x_n$ otherwise.

For example:

$x_0+{2^{-1}}={1\over 2}>{\pi\over 10},$ so $x_1=0.0$ (which is of course a silly way to write $0$, but it's clearer in this context I think).
$x_1+2^{-2}={1\over 4}<{\pi\over 10}$, so $x_2=0.01$.
$x_2+2^{-3}={3\over 8}>{\pi\over 10}$, so $x_3=0.010$.

And so forth. We then define $x$ to be the limit of the $x_i$s: $$x=\lim_{n\rightarrow\infty}x_n.$$
Now in everything we write from now on, we need to be careful to distinguish between the specific (and now well-defined!) real number $x$ and the sequence $(x_n)_{n\in\mathbb{N}}$ of real numbers we've built (and which we've used to define $x$). For example, when you write $$\lim x,$$ what you really want to write is $$\lim_{n\rightarrow\infty} x_n,$$ since you take the limit of a sequence rather than a single number.

Having repaired the language, we can now answer your question:

$x={\pi\over 10}$, even though for each $n$ we have $x_n<{\pi\over 10}$.


Custom Google Maps Overlay like Disney Maps

Question: I am interested in creating a google map like this https://disneyworld.disney.go.com/maps/ but I am having trouble finding information on how to go about it. I've looked on the googlemaps api but I can only see how to change the tiles on one zoom level and the colors. Can anyone point me in the right direction to create something like this?
Answer: The tiles are served from a GIS tile server. Google Maps requests tiles using three parameters: X, Y, and Z (can be thought of as Lat, Long, and Zoom). The server gives entirely different tiles based on the zoom level (more detailed location items and labels). Google Maps doesn't do much work at all in this instance, it is all handled by the server and Google Maps renders what it is given.
Comment: You can create your own tile images using software such as GDAL2tiles: http://www.gdal.org/gdal2tiles.html
Comment: So basically all I would need to do is tell google maps where the new tiles are on the server correct?
Comment: Take a look at image map type overlays. Read the docs: https://developers.google.com/maps/documentation/javascript/maptypes#ImageMapTypes and example: https://developers.google.com/maps/documentation/javascript/examples/maptype-image


How does one calculate the centroid of an equilateral triangle using integration

Question: Edit: The vertices are $(0,0)$, $(1, 0)$, $(1/2,  \sqrt{3}/2)$. Please confirm. Confirmed.
Answer: I will assume the equilateral triangle of side one with a vertex at the origin.  Clearly, the $x$-centroid is $\bar{x} = 1/2$ by symmetry, so we need only find $\bar{y}$.  The expression for the centroid of a region $R$ is
$$\bar{y} = \frac{\displaystyle\iint_R dA \, y}{\displaystyle\iint_R dA}$$
It's all about picking the bounds of the integral.  In this case, you can see that the triangle is bounded by the lines $x=y/\sqrt{3}$ and $x=1-y/\sqrt{3}$.  I chose $x$ as a function of $y$ rather than vice-versa because I can do the calculation with a single integral rather than break up into two.  The integrals are then
$$\bar{y} = \frac{\displaystyle\int_0^{\sqrt{3}/2} dy \, y \: \displaystyle\int_{y/\sqrt{3}}^{1-y/\sqrt{3}} dx}{\displaystyle\int_0^{\sqrt{3}/2} dy \: \displaystyle\int_{y/\sqrt{3}}^{1-y/\sqrt{3}} dx}$$
I leave it you to do these integrals out.  The result I get is
$$\bar{y} = \frac{\sqrt{3}}{6}$$
Comment: Shouldn't we get sqrt(3)/4 since centroids should stay the same when flipped on axes of symmetry?
Comment: By your reckoning, the centroid is halfway up the triangle.  Does that make sense?  Most of the "weight" of the triangle is toward the bottom.
Comment: I have no idea how you got the four integrals on the fraction. Where does that come from? Idk how to do double integrals; this is calc 2.
Comment: You work from right to left.  The integrals over $x$ are trivial (just the top - the bottom limit).  That will leave you with single integrals over $y$ that involve at worst quadratics, which I assume you can do.
Comment: Yes, I can do them. I think I was trying something similar to what you did but I didn't put in terms of y. I was having great difficulty breaking up the integrals. Thanks!!
Comment: Your welcome.  If you found a solution useful, please remember to accept it.
Comment: Those integrals just give y = y I think
Comment: Uhhhh...no.  You should get, for the denominator,$$\int_0^{\sqrt{3}/2} dy \, (1-2 y/\sqrt{3})$$ Perhaps you are not used to the $dy$ being first.  It is how I write integrals.
Comment: Oh... I just don't know how to do double integrals like that.
Comment: I didn't know that they got combined
Comment: Are those separate integrals? I'm not really sure what's going on. I don't know how you derived the initial thing
Comment: I got it. Sorry.
Answer: Well, if you insist to find it by integration, there is a method (though, for the beginning, the best if you draw the triangle on a paper and find the middle point right away..)
We want the average of all coordinates $(x,y)$ that lie within the triangle, that would give the center. The average can be calculated by integral, divided by the whole area, and it is also possible to do it coordinatewise. So we can get
$$\bar x=\frac{\int_{x=0}^1\int_0^?x\,dydx}{{\rm Area}(\Delta)} \quad \quad
\bar y=\frac{\int_{x=0}^1\int_0^?y\,dydx}{{\rm Area}(\Delta)}\,.
$$
You have to split the integrals for $x=0...1/2$ and $x=1/2...1$ and calculate the equations of the sides of the triangle to get the upper limit for $y$ for a given $x$.


Equality of Completeness property (Supremum and Infimum property) and Cauchy criterion in Real numbers

Question: I need to prove Completeness property and Cauchy criterion in Real numbers are equal, and I think its true. to prove this equality I think should use Bolzano-Weierstrass Theorem. I be so thankful if anyone could help me.
Comment: Can you elaborate? One of the standard definitions of completeness is that the Cauchy criterion holds. What's your definition of completeness?
Comment: Welcome to MSE! Your question is interesting. However, the context is missing. Can you update your question in that direction? Of what kind of spaces are you speaking? Normed spaces? Equipped with a distance? Also I have the impression that the question you're asking is a classical topology theorem. Not sure then that this forum is the right place for such questions.
Comment: @Vercassivelaunos  definition. Completeness Property of R Every nonempty set of real numbers that has an upper bound also has a supremum in R. so you can see  Cauchy criterion is not in  standard definitions of completeness. my source book is INTRODUCTION TO REAL ANALYSIS (Robert G. Bartle
Donald R. Sherbert)
Answer: supremum property $\Rightarrow$ Cauchy criterion
The supremum property (which is what you call completeness) also implies the infimum property: every subset $S\subset\mathbb R$ which is bounded below has an infimum. For proof, just apply the supremum property to $-S:=\{-s~\vert~s\in S\}$. These two imply the existence of limit superior and limit inferior for all bounded sequences, since they are defined as
$$\limsup a_n:=\inf_{k\in\mathbb N}\sup_{n\geq k} a_n,\\
\liminf a_n:=\sup_{k\in\mathbb N}\inf_{n\geq k} a_n,$$
both of which exist for bounded $a_n$ due to the supremum and infimum properties. If limit inferior and superior of a sequence are equal, then the sequence converges. Now the limits superior and inferior of a Cauchy sequence can't be different if they exist (I leave the proof to you). And since Cauchy sequences are bounded (again, I leave the proof to you), the limits superior and inferior do in fact exist. They are then equal, and thus the Cauchy sequence has a limit.
Cauchy criterion $\Rightarrow$ supremum property
Let $\emptyset\neq S\subset\mathbb R$ be a set which is bounded above. Let $b_0$ be an upper bound of $S$ and let $a_0\in S$. Now define recursively that if $\frac{a_n+b_n}{2}$ is an upper bound of $S$, then $a_{n+1}:=a_n$ and $b_{n+1}:=\frac{a_n+b_n}{2}$, and otherwise $a_{n+1}:=\frac{a_n+b_n}{2},~~b_{n+1}:=b_n$.
With these definitions, both $a_n$ and $b_n$ are Cauchy sequences since $\vert a_m-a_n\vert\leq\frac{1}{2^{\vert m-n\vert}}\vert b_0-a_0\vert$, same for $\vert b_m-b_n\vert$. Because of the Cauchy criterion, both sequences converge. Even more, both converge to the same number, since the sequence $b_n-a_n=\frac{1}{2^n}(b_n-a_n)$ converges to $0$. The limit of these sequences must be an upper bound of $S$ because all the $b_n$ are upper bounds. There also can't be a lower upper bound because none of the $a_n$ are upper bounds (if $b$ is an upper bound, then all $c>b$ are upper bounds, too). So this limit is a least upper bound, in other words, a supremum.
Comment: thank you for your answer but I need equality so can you get to completeness property by assuming the cauchy criterion is correct.
Comment: @mohammadfattahian I added the other direction to my answer.


Chrome extension not changing DOM correctly

Question: I just starting chrome extension programming. I have some experience in js and html programming. As my first extension I wanted to get rid of the ad bar on facebook. It is an div with the class "ego-column". Here is my code:
{
 "name": "DOM",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Change DOM",
    "browser_action": {
    "name": "Manipulate DOM",
    "icons": ["icon.png"],
    "default_icon": "icon.png"
  },
    "content_scripts": [ {
        "js": [ "jquery.min.js", "background.js" ],
        "matches": [ "http://*/*", "https://*/*"]
    }]
}

background.js:
$("body").css("background-color","green");
$(".ego-column").empty();

The background color correctly changes to green (very beautiful :) But nothing changes with the "ego-column". Any idea what I might be doing wrong?
Answer: You mispelled the class name. It should be ego_column. So the fixed code will be:
$(".ego_column").empty();


Indoor / outdoor track and field different records?

Question: Why there are different records from indoor / outdoor performances?
I mean maybe distances 200m and 400m has different tracks (with different lengths of curves and straights) but why there are two different record between on the following speciality

long jump
triple jump
high jump
pole vault
Answer: tl;dr:

Track distance, tightness of curves, and banked curves
Event distances
Different implement weights
Lack of wind
Differences in runways (length and responsiveness)

For the track events, you've nailed it: the 200m standard indoor track means races of the same distance (e.g. 800m) can be notably different from races on a standard 400m outdoor track. In the sprints, the tight banked turns can significantly change the athlete's approach to the race, and some events (e.g. 60m) are only held indoors.
For the field events, the reasoning for different records is more tricky. In the throws, e.g. shot put, the implements are different (size and weight). For the jumps, though, the differences are entirely environmental: lack of wind (either supporting or impeding) and different runway surfaces, mostly. In these events, competing indoors can actually be easier (although long jump and triple jump may be limited in the length of their run-up - I'm not sure if that would help or hurt an athlete).
Comment: I can't see how a shorter run up would help - if it did, outdoor athletes could always just walk the first 5m out whatever.
Comment: Yeah, I was thinking more of questioning the value of a longer run-up past a certain point, but didn't really make that clear.
Comment: To me the pole vault is an interesting case study. Jenn Suhr improved her indoor world record last weekend (January 30th) and made three attempts at a height which would better the outdoor WR. One might argue that conditions are *better* indoors for the vault and the only reason the outdoor mark is better is because it's contested more often outdoors.
Comment: The 2020 season showed that the men's PV is even weirder than the women: Mondo Duplantis now holds both records, but the indoor mark is superior to the outdoor (and therefore, oddly, the IAAF doesn't see the outdoor mark as a World Record).
Comment: The IAAF will see whichever is the world record as the world record - I doubt they'd care if it's outdoor or indoor.
Comment: @a53-416 because the IAAF (now World Athletics) are the ones who ratify World Records, what they "see" as the World Record is how the record is determined. The definition of the record originates with them.
Comment: I'm relatively certain that indoor shot put uses same weight equipment as outdoors. Everything you say about banked curves and tight bends is spot on. Differences in runways are speculative, but it sure looks like there is more variation in indoor runways. +1 was there already.
Comment: Indoor shots may have the same weight as outdoors, but their construction is different; rather than being simple steel balls, they're generally coated with some rubber/plastic layer so they don't demolish the floor of the throwing sector. (Outdoor venues put into sand.)


How can my eCommerce site only showcase products without an Add to cart option?

Question: I want my Drupal eCommerce site to only show products which contain only product name, description, PDF file.
I don't want price & Add to cart options. Is there any possibility in Drupal?
Answer: Yes, there is a possibility. You can achieve that by using the Views module.
Create a content type for Products (say products) or you can also use default content types Basic Page or Article .
Add fields whatever you want to show for products (say description, file for PDF).
Create a View for to display the Product content type nodes (products)

You need Views if

You like the default front page view, but you find you want to sort    it differently.
You like the default taxonomy/term view, but you find you want to    sort it differently; for example, alphabetically.
You use /tracker, but you want to restrict it to posts of a certain    type.
You like the idea of the 'article' module, but it doesn't display    articles the way you like.
You want a way to display a block with the 5 most recent posts of    some particular type.
You want to provide 'unread forum posts'.
You want a monthly archive similar to the typical Movable    Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts
  for that month.

Views can do a lot more than that, but those are some of the obvious
  uses of Views.
Comment: Thanks for your reply. Is there any possibility to use enquiry form in that view for each and every prodcut?
Comment: Its not a new question. Am having doubt in previous your explanation.
Comment: Tamil Vaalga..then how can reply only regarding this question?


How can I create conductor's annotations in Lilypond?

Question: I'm writing a second edition of a Legend of Zelda: Ocarina of Time medley I wrote and conducted in high school (it was indeed as fun as it sounds).  Through our rehearsals, my director and I penciled in a bunch of changes that I somehow never got around to putting into the source code.  Unfortunately, I lost all that code—it was before I'd begun my computer science studies and discovered git and make.  However, this gives me the opportunity to do things over the right way.
My project structure is the same as the example given in section 5.5 of the Lilypond Usage manual.  While some of the edits we made were applicable to the parts—articulations added or removed, etc.—some of them are meant purely for the conductor, such as reminders to cue sections of the orchestra.  What's the best way to insert these?  As far as I can tell, the .ly file containing the full score is nothing more than a series of \include directives, but that denies me the ability to add further information to a staff once it's included.
Answer: I guess a good, pure-Lilypond way would be using tags (see docs).
In short: you can annotate anything in your score with \tag #'whatever. An example could be
flutes = { \global
  \tag #'fullscore { c4-\markup\italic "wave hands at the flutes!" }
    \tag #'parts { c4 } d e f |
  g4 a b c' |
}

Then, you can use \keepWithTag or \removeWithTag. So, in the conductor's score, you would replace \new Staff \with { instrumentName = "Flutes" } { \flutes } with \new Staff \with { instrumentName = "Flutes" } { \keepWithTag #'fullscore \flutes }. That will keep only things tagged with #'fullscore and with nothing, and discard everything else, so you will get the "wave hands at the flutes!" markup.
Similarly you would use \removeWithTag #'fullscore (or \keepWithTag #'parts) in the parts to get rid of the markup.
Comment: Just tried this, and it works perfectly.  Thanks!


How to traverse the tree structure of rpart object in R? I need to get all the nodes associated with a subtree, how can I do it?

Question: I am using rpart for building a decision tree classifier. I wish to use my own pruning function based on certain parameters of the leaf nodes corresponding to a subtree. For this, I think I need to traverse the tree. I explored the documentation of rpart, but could not come up with a way to do it. Please help.
Comment: The function `dendrapply()` might be what you're looking for
Comment: You could use the `as.party()` coercion function from the `partykit` package. This transforms the `rpart` structure to a structure called `party` that comes with many convenience tools including a `nodeapply()` and a `nodeprune()` function. See `vignette("partykit", package = "partykit")` for an introduction and `vignette("constparty", package = "partykit")` for examples including coercion from `rpart`.
Comment: @Andrie `dendrapply()` function applies a passed function to each node and returns the altered tree. This is not what I'm looking for. I wish to get every leaf node corresponding to a subtree.
Answer: Take a look at the tree traversal code I had at extracting predictors from ctree object
Potentially, this will be useful.


Register for content-available push notifications only

Question: For which UIRemoteNotificationType should I register when I only want to send 'silent' push notifications which trigger a background refresh? This is for a non-newsstand app.
Comment: any luck? Ideally for silent push it would be great to obviate explicit user approval
Answer: =You can register for the two notification types:
        UIRemoteNotificationTypeAlert and UIRemoteNotificationTypeBadge

using a pipe operator like this
UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge
If no sound is required you could leave out the sound type (UIRemoteNotificationTypeSound).
Hope this helps.


Printing a pcl file in c# not working, suggestions?

Question: I'm trying to print a pcl file programatically in c#.
I'm using the following Microsoft link for reference. (Note it's in VB)

http://support.microsoft.com/kb/298141

Unfortunatly, it's not work .. I'm only getting blank pages printed.
Note that if I just copy the pcl file to the printer from prompt - i.e. copy filename printer. The page gets printed corrrectly.
Suggestions?
<code>public class PrintRaw
  {
    [StructLayout(LayoutKind.Sequential)]
    public class DocInfo
    {
      [MarshalAs(UnmanagedType.LPWStr)] public String docName;
      [MarshalAs(UnmanagedType.LPWStr)] public String outputFile;
      [MarshalAs(UnmanagedType.LPWStr)] public String dataType;
    }

    [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi,
      ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter,
                                          IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true,
      CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi,
      ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level,
                                              [In, MarshalAs(UnmanagedType.LPStruct)] DocInfo di);

    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true,
      CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true,
      CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true,
      CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true,
      CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    public void Print(String printerName, String filename)
    {
      IntPtr lhPrinter;
      OpenPrinter(printerName, out lhPrinter, new IntPtr(0));

      if (lhPrinter.ToInt32() == 0)
        return; //Printer not found!!

      var rawPrinter = new DocInfo() {docName = "My Document", dataType = "RAW"};

      StartDocPrinter(lhPrinter, 1, rawPrinter);

      using (var b = new BinaryReader(File.Open(filename, FileMode.Open)))
      {
        var length = (int) b.BaseStream.Length;
        const int bufferSize = 8192;

        var numLoops = length/bufferSize;
        var leftOver = length%bufferSize;

        for (int i = 0; i < numLoops; i++)
        {
          var buffer = new byte[bufferSize];
          int dwWritten;

          b.Read(buffer, 0, bufferSize);
          IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
          Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
          WritePrinter(lhPrinter, unmanagedPointer, bufferSize, out dwWritten);
          Marshal.FreeHGlobal(unmanagedPointer);
        }

        if (leftOver > 0)
        {
          var buffer = new byte[leftOver];
          int dwWritten;

          b.Read(buffer, 0, leftOver);
          IntPtr unmanagedPointer = Marshal.AllocHGlobal(buffer.Length);
          Marshal.Copy(buffer, 0, unmanagedPointer, buffer.Length);
          WritePrinter(lhPrinter, unmanagedPointer, leftOver, out dwWritten);
          Marshal.FreeHGlobal(unmanagedPointer);
        }
      }

      EndDocPrinter(lhPrinter);
      ClosePrinter(lhPrinter);
    }
  }
</code>
Comment: For some reason the call to StartDocPrinter is failing, the Win32 error code is 1804, invalid datatype.
Comment: Here is a link to the c# version of the code you reference at the top: http://support.microsoft.com/kb/322091
Answer: Ok, it seems like the datatype that I was using was invalid in the example. I updated it to the following (note the setting of Charset) and it fixed the problem.
<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOC_INFO_1
{
  [MarshalAs(UnmanagedType.LPStr)]
  public string pDocName;
  [MarshalAs(UnmanagedType.LPStr)]
  public string pOutputFile;
  [MarshalAs(UnmanagedType.LPStr)]
  public string pDataType;
}
</code>


Qual a melhor prática para restringir o acesso ao sistema de administração do site?

Question: Eu queria criar um sistema de administração para o site, fiz de forma que os utilizadores tem associado a si um campo nível e se este for um dado valor eles conseguem aceder ao controlo de administrador, doutra forma se tentarem são direccionados para o índex, não sei se esta é uma forma eficiente.
Reparei noutro sistema de criar diretórios protegidos.
Podem me dizer qual das formas é mais eficiente e se existe alguma vulnerabilidade na forma como eu decidi implementar?
Comment: Eu sei que não é bem uma resposta, e mais uma indicação, então resolvi fazer por aqui... Você já viu a bilioteca ACL do framework phalcon do PHP? http://docs.phalconphp.com/en/latest/reference/acl.html
Comment: depende também da política de uso interno.. a grande maioria dos usuários, mesmo num ambiente corporativo, se não tiverem disciplina ou políticas internas restritivas, de nada adianta criar um complexo sistema de níveis de permissão pois normalmente por preguiça criam um único usuário admin com todas as permissões possíveis e compartilham com todos..rrsrs  Portanto, verifique com os usuários qual política de segurança pretendem usar. Se forem desleixados, crie um unico usuário root que será o seu e um único admin, que será deles. Nesses casos, jamais ensine-os que existe um user root.
Comment: Existe inúmeras formas de fazer esse processo.
Acredito que o melhor são controles de sessions, ao logar no seu sistema defina um nível de acesso, crie uma função para verificar o nível de acesso e o acesso a página. É uma maneira simples, mas bem efetiva. Abs.
Answer: Existem muitas práticas que podem elevar o nível de segurança de um sistema. Estarei listando algumas mais comuns e importantes.
Força das Senhas
Uma prática bastante recomendada é recomendar/obrigar o usuário (principalmente os com acesso ao sistema de administração) a escolher uma senha com uma força razoavelmente forte, contendo letras minúsculas, maiúsculas, números e talvez até símbolos, por exemplo 3sSa.e.Minh4$3nH4. Isso dificulta bastante na hora de quebra-la.
Faça com que Senhas expirem
A prática de expirar a senha é muito comum hoje em dia, principalmente em ambientes corporativos. Isso mantém o ambiente em constante atualização, podendo até ser possível atualizar hashs de seguranças  de tempos em tempos. Por exemplo pesquisando a senha 3sSa.e.Minh4$3nH4 no site How Secure is my Password, mostra que para um computador comum quebrar essa senha pode demorar 39 quadrilhões de anos, mas digamos que o hacker possua inúmeros computadores zumbis, então esse número pode ser reduzido consideravelmente, mas se você possui uma rotina de segurança que obriga as senhas serem atualizadas de 6 em 6 meses, você estenderá o tempo de quebra da sua segurança em até um tempo infinito.

Não Criptografe apenas com md5
Utilizando o app MD5 Decrypt do site Hash Killer é possível quebrar hashs simples, com apenas números ou letras, como por exemplo 123456, carlos12. Por isso é incentivado utilizar no mínimo um salt na senha antes de criptografa-la.
Eu não vou ficar reescrevendo a teoria da relatividade, então aqui tem uma pergunta e resposta sobre hashs de segurança..
Evite o nome Admin
Utilizar o endereço meusite.com/admin ou admin.meusite.com é muito óbvio, dê preferências a nomes alternativos como mspanel (abreviação para MeuSitePanel) ou algo do tipo, um nome fácil de ser lembrado e que não existe links de entrada, mas também que não seja tão óbvio. Também, se possível, restrinja o acesso por IP.
SSL
Se possível invista em Certificados Digitais, mas para um sistema interno você mesmo pode gerar suas chaves de segurança. Então veja o que vale mais a pena para o tipo de sistema.


Find the power series for the function

Question: How do I find the power series for f(x)=$\frac{x^3}{x+3}$ ?
That to in summation notation.
Answer: $$\frac{x^3}{x+3}=\frac13x^3\frac1{1+\frac x3}=\frac13x^3\left(1-\frac x3+\frac {x^2}{3^2}-\frac {x^3}{3^3}+\frac {x^4}{3^4}\cdots\right)$$
Comment: How did you get from the second to the third part? Like how did you come up with the terms and the alternating?
Comment: I used $\frac{1}{1-x}=1+x+x^2+x^3+x^4+\cdots$ and substituted $x\mapsto -\frac x3$.

Find the power series for the function


Postgres archive_cleanup_command is not recognized

Question: I put this in my postgresql.conf (line 193):
archive_cleanup_command = 'pg_archivecleanup C:\\pg\\archivedir %r'

Now, when I am trying to launch my server, I get this error :
LOG:  unrecognized configuration parameter "archive_cleanup_command" in file "c:/pg/postgresql.conf" line 193
FATAL:  configuration file "c:/db_slave/postgresql.conf" contains errors

Do you know why the command isn't recognized/
C:\bin\pgsql is in my path and pg_archivecleanup can be executed from by cmd.
Last info :
pg_ctl --version

> pg_ctl (PostgreSQL) 9.2.3

Thanks in advance.
Answer: archive_cleanup_command is a command that you put in the recovery.conf file of a standby server.
It's not meant for postgresql.conf
See Archive Recovery Settings in the docs.


javascript replace random letters with underscore

Question: I want to write this google spreadsheet javascript code to replace random letters in a string.
I have created a code that does it but not randomly, plus it also replaces the spaces with an underscore (which is problematic).
The end result I'm interested in is to go from this (the sentences are in French btw.):
'J'habite à New York.'
to this:
'_'h_b_t_ à _ew _or_.'
Let's say that given a sentences, at least half of the number of letters must be replaced with an underscore.
Thank you for your help. (ps: i'm not a programmer)
The code I have so far:
var v =  [['J'habite à New York.', 'Sì', ], ['Je m'appelle John. !']];

for (var r in v){
  for (var c in v[r]){
    var d = v[r][c];
    var l = d.length;

    var u = l;
    while(u > 0){
    var res = d.replace(d[u-2], '_');
    d = res;
    u = u - 2;
      }
    console.log(res);
      }
    }

Comment: Why was this question downvoted, might I ask ?
Answer: You are overcomplicatig a bit. Just turn the string into an array of characters, then map it to an array of characters with some letters replaced and turn it back into a string.

function replace(str) {
  return str.split("").map(char => Math.random() > 0.5 ? "_" : char).join("");
}

var v = [
  ['J'habite à New York.', 'Sì', ],
  ['Je m'appelle John. !', 'Non!',]
];

for (const pair of v) {
  pair[0] = replace(pair[0]);
  pair[1] = replace(pair[1]);
}

console.log(v)
Comment: This is what I was going to post, however, he mentions `at least half of the number of letters must be replaced with an underscore` which this doesn't always do.
Comment: @getOffMyLawn currently thinking about a good solution, haven't yet found one except "retry until it fits"
Comment: I was thinking count the number of underscores and if it is less than half replace some that aren't underscores
Comment: This one looks nice. However how to: 1: add a space between underscores 2: exclude punctuation marks ?
Answer: You might try something like this :)
var a = "Text i want to replace text from";
var splitted = a.split('');
var count = 0; // variable where i keep trace of how many _ i have inserted

while(count < a.length/2) {
   var index = Math.floor(Math.random()*a.length); //generate new index
   if(splitted[index] !== '_' && splitted[index] !== ' ') {
       splitted[index] = '_';
       count++;
   }
}

var newstring = splitted.join(""); //the new string with spaces replaced

EDIT: i tried it now on console and seems to be working. What problem does it give to you?
2° EDIT: you could do:
splitted[index] = ' _ ';

instead of
splitted[index] = '_';

also notice that i changed the if condition from:
if(splitted[index] !== '_')

to
if(splitted[index] !== '_' && splitted[index] !== ' ')

to avoid replacing empty spaces with '_'
:)
Comment: This seems like a good way to solve the "at least 50% replace" problem, i foxed some formattig, feel free to rollback.
Comment: Thanks for your answer. Could you please improve the last line since it doesn't seem to work. Thanks !
Comment: Now it works, thanks a lot. I know it's a further demand but how can I obtain a result that is going to render sth like "w_ _ t" instead of "w__t" ? (want). Each underscore corresponds to one letter and when you have two next to each other it's confusing.
Comment: Thanks Murys for your solution. It is simple and it works perfectly. I also want to avoid the punctuation marks (in French there are more than in English) so I have come up with a solution but I'm wondering if it couldn't be done in a more efficient and simpler way (and more exhaustive, i.e. including all the signs). Thanks. Here is the code: https://gist.github.com/pnnaoned/4cc7d1a421430b2e795786dd0ebb7511


Como fazer requisições com Guzzle\Http fingindo ser "AJAX"?

Question: Costumo utilizar a bibliotecaGuzzle\Http para poder fazer requisições à algumas urls com PHP.
Estou fazendo webservice com sistemas nossos, onde, se a requisição for reconhecida como Ajax, o resultado retornado é Json. Caso contrário, é retornado HTML.
Porém, preciso agora fazer requisições nessas urls com o Guzzle, e quero que, quando a requisição for feita pelo Guzzle, também me seja retornado a resposta em Json.
Como fazer requisições com a biblioteca Guzzle\Http, como se ele fosse o AJAX executado por um navegador?
Preciso colocar algum ou alguns headers para isso funcionar?
Comment: A pessoa que deu o negativo podia oferecer informações no que poderia ser melhorado na pergunta.
Answer: Na verdade não tem como detectar se é ajax de verdade (e isso é o que nos ajuda), o que fazemos é um envio de um header que usa o prefixo x-, geralmente em HTTP o uso desse prefixo quer dizer experimental.
Um caso de uso disto é o jQuery, por exemplo eu criar uma simples requisição GET com XmlHttpRequest sem nada eu não vou ter como detectar, então o jQuery envia esse header:
X-Requested-With: XMLHttpRequest

Não quer dizer que é Ajax, na verdade quer dizer que é XMLHttpRequest (como explicado aqui Ajax não é uma linguagem de programação. Então o que é?)
No caso detectamos se o envio é XMLHttpRequest, no Guzzle\Http você pode definir na instância do Guzzle\Http, para "herdar" as configurações em outras requisições. Assim, você simplifica a configuração:
  $client = new Guzzle\Http(['headers' => ['X-Request-With' => 'XMLHttpRequest']]);

  $client->put(/** **/);

  $client->post(/** **/);

  $client->get(/** **/);

Ou usando o GuzzleHttp\Client assim:
$client = new GuzzleHttp\Client(...);

$client->request('GET', '/caminho/foo/bar/baz', [
    'headers' => ['X-Requested-With' => 'XMLHttpRequest']
]);

Apenas um adicional, frameworks como Laravel e cakephp usam estes métodos pra detectar se é possui o header X-Requested-With' => 'XMLHttpRequest:

Laravel:
public function index(Request $request)
{
    if($request->ajax()){

cakephp:
if ($this->request->is('ajax')) {

Comment: O `Symfony` então, de acordo com sua opnião, fez certo. Lá o método chamasse `$request->isXMLHttpRequest()`. Creio que o `$request->isAjax()` veio para "simplificar a bicicleta".
Comment: @WallaceMaxters no meu framework é apenas `Request::is('xhr')` :)


Google ad click is not opening the external web browser

Question: I am trying to implement the ad in my app with Custom Native Ad Format - https://developers.google.com/ad-manager/mobile-ads-sdk/android/native/custom-formats#java_1
So, according to the documentation I am going with the approach described there and creating the ad
...
private void setListeners() {
...
    imageView.setOnClickListener(v -> {
        nativeCustomFormatAd.performClick("IMAGE");
    });
...
}

private NativeCustomFormatAd nativeCustomFormatAd;

AdLoader adLoader = new AdLoader.Builder(context, "/6499/example/native")
    .forCustomFormatAd("10063170",
      new NativeCustomFormatAd.OnCustomFormatAdLoadedListener() {
          @Override
          public void onCustomFormatAdLoaded(NativeCustomFormatAd ad) {
              // Show the custom format and record an impression.

             nativeCustomFormatAd = ad;
              Drawable drawable = vm.nativeCustomFormatAd.getImage("IMAGE").getDrawable();
              imageView.setDrawable(drawable);
          }
      },
      new NativeCustomFormatAd.OnCustomClickListener() {
          @Override
          public void onCustomClick(NativeCustomFormatAd ad, String s) {
              // Handle the click action
          }
      })
    .withAdListener( ... )
    .withNativeAdOptions( ... )
    .build();

            @SuppressLint("VisibleForTests")
            AdManagerAdRequest adManagerAdRequest = new AdManagerAdRequest.Builder().build();
            adLoader.loadAd(adManagerAdRequest);
...

So, it looks pretty simple I try to make a request for the ad then I got (in a callback) NativeCustomFormatAd, save it as a class member, and along with it get drawable and set it to the imageView (to present it in the UI). Once a user clicks on the imageView I get an event in the click listener and invoke nativeCustomFormatAd.performClick("IMAGE");.
The problem is that I expect that once I transfer the ad click to the SDK (by nativeCustomFormatAd.performClick("IMAGE");) SDK is supposed to open the external browser, but instead nothing happens.
P.S. I am sure that nativeCustomFormatAd.performClick("IMAGE"); getting invoked and also I see that SDK gets the click as I got a callback event here:
...
      new NativeCustomFormatAd.OnCustomClickListener() {
          @Override
          public void onCustomClick(NativeCustomFormatAd ad, String s) {
              // Handle the click action
          }
      })
...

What am I missing here?
Answer: According to the docs you linked:

When a click is performed on a custom format ad, there are three possible responses from the SDK, attempted in this order:

Invoke the OnCustomClickListener from AdLoader, if one was provided.
For each of the ad's deep link URLs, attempt to locate a content resolver and start the first one that resolves.
Open a browser and navigate to the ad's traditional Destination URL.

Also:

If you pass a listener object in, the SDK instead invokes its onCustomClick method and takes no further action.

Therefore, it seems you have to pass a null OnCustomClickListener.


What does "filing retirement papers" actually mean?

Question: This might be applicable to any worldwide major sport, but I'm most familiar with how it pertains to the 4 North American major sports.
What does it mean when a player files their "retirement papers" with their respective league?  I know in the NFL or MLB it starts the clock for when you can be considered for the Hall of Fame.  But does that process categorize the athlete in other ways?  I think I also heard that you have to go through some formal reinstatement process in order to play again (Brett Favre and Michael Jordan are good examples).
Does anyone know the terms of these retirement papers?
Answer: Retirement papers can serve several purposes. First, if you are currently under contract with a team, filing retirement papers would void your current contract but you also could not sign a contract with another team. Second, If you are not under contract with a team (free agent), filing retirement papers would let teams know that you no longer intend on playing or signing another contract. Thirdly, I think all major leagues have some sort of pension program set up for its retired players and filing those papers makes you eligible to claim your pension. Also like you said in your question it also determines when you are eligible to be on a hall of fame ballot
Comment: Thanks.  It all makes sense, but do you have any sources to back this up?
Comment: Yeah, I also had zero luck with Google on this front.  I think your answer is the best I'm going to get.  Thanks!
Comment: I have searched up and down google for any sort of documentation on this but have come up empty... What I wrote here comes from my experience as an avid sports fan meeting and talking with different people. I have wondered this myself and this is the list that I came up with. It is very much a legal document that says he is no longer employed by that company. I would compare it to any other job. When you quit you somehow have to let your employer know, same with these guys. Filing papers seems just like they are formally telling everyone that im legaly no longer an employee of this company
Comment: Sorry I could not be of more help
Answer: I heard an NFL player who retired after 10 seasons discuss this topic.  He said that he and no one else has ever filed retirement papers because they do not exist. The discussion of whether someone has filed his papers makes for great "will he or won't he play" discussions for the media and the fans but that's all
Comment: Do you have any source for this info?  Who was the player?  Who was he talking to?


Extract SMS from Android

Question:
Possible Duplicate:
How can I read SMS messages from the inbox programmatically in Android?

I'm trying to build a program that extracts SMS from android devices through a java program. Does anyone know an API that does this?
I'm aware the SMS (the backups anyway) are stored in a database so I was hoping to find this database on the phone, extract it and then load it into a database.
Comment: Check into the various android "backup" programs - they can back up the sms archives.
Answer: Check the following link.
http://www.apriorit.com/our-company/dev-blog/227-handle-sms-on-android
Answer: Manas provided a good link.
Here is another one that I used.
http://www.androidcompetencycenter.com/2008/12/android-api-sms-handling/
  is broken => try via archive.org
I think you are referring to reading the database. If so,then this question is a repost, see here:
How can I read SMS messages from the device programmatically in Android?
Comment: Thanks for links. Just want to write a desktop java application that'll extract SMS from android and print them to a relational database. I'm expecting some sort of encryption is place.

Extract SMS from Android


A New, Possible Proof of the Infinitude of the Primes?

Question: $$1=1$$
$$2=2$$
$$3=3$$
$4=2\cdot2$ At $4$, the first prime number, $2$, is there as a factor. So I say that at the square of $2$, $2$ comes into play as a prime factor. At this point, $2$ is the only prime factor in play, and therefore, until $3$ comes into play at $9$, there will be a prime at every other integer.
\begin{align}
5 & = 5 \\
6 & = 2\cdot3 \\
7 & = 7 \\
8 & =2^3
\end{align}
$9$ is the square of $3$, where $3$ comes into play at. With 2 and 3 being the only prime factors in play between 9 and 25, there have to be primes in this interval because 2 and 3 can only hit at most three out of four consecutive integers.
When 5 comes into play at 25, 2,3, and 5 are the only prime factors in play until the square of the next prime, 7, which comes into play at 49. Out of six consecutive integers, 2,3, and 5 can hit at most five of them. So the biggest prime gap between 25 and 49 is 6.
Each prime comes into play as a factor at its own square. So each time we arrive at the square of a prime, one more prime factor is in play, however, the gaps between the squares of the primes grow such that there will always be another prime, at least one in each gap.
Is this sufficient to prove the infinitude of the primes? Are the mathematical concepts presented here correct? Can the way this is presented be improved? Can the wording of the mathematical facts be improved?
An explanation is in order. Let us examine some of the gaps between consecutive squares of primes. Quite simply, the number of prime factors in play before the square of the first prime is 0. Therefore each integer between 1 and 4 is prime. After 4 and before 9, 2 cannot hit every point in the gap. The size of this gap equals 2·2, so there are 4 integers of which 2 can at most hit 2. Likewise, between 9 and 25, the number of integers in the gap is equal to 25-9-1, which is 15. In any span of 4 integers, with 2 and 3 being the only prime factors in play, they will miss at least one space. There is a simple proof for this. Once 5 comes into play, the prime factors begin to follow a great pattern.
The great pattern of how the prime factors are arranged is such that they will miss infinitely many spaces. Factoring all composite numbers from 4 to 30 will reveal this great pattern. Note that 30 is the product of the first three primes.
Comment: Question 1: no. Question 2: no. Question 3: yes. Question 4: yes.
Comment: @JeffreyYoung That sounds like what I suspected.  In this case, "I believe that this great pattern continues indefinitely" is very, very far from a new proof.  In fact, this pattern would imply the very difficult conjecture that there is always a prime between the squares of two consecutive primes.  AFAIK this is not known, being slightly weaker than Legendre's conjecture and morally (although maybe not provably) much stronger than Baker-Harman-Pintz.
Comment: In order to have specific suggestions for wording, I'd need at least some good guesses as to what you're trying to say.
Comment: There is a huge gap in logic in the second last paragraph, which amounts to "I don't see why this pattern shouldn't continue" as opposed to any sort of argument.  How confident can you possibly be that the biggest possible prime gap when the first 1 billion primes are in play is smaller than the gap between $p_{1000000000}^2$ and $p_{1000000001}^2$?
Comment: I find this very vague.  Certainly it is widely known that among numbers less than the square of a particular prime $p$, every number is either prime or divisible by some prime number less than $p$.  Where you say "one in each gap", do you mean one in each gap between squares of primes?  Are you trying to say that some prime number must appear in each gap between squares of primes?  If so, how do you prove that?  And when you arrive at the square of the largest prime, if any, then there are no gaps between squares of primes beyond that, so what happens to your argument then?
Comment: 2 as a factor is at every other integer. 2 hits every other point.
Comment: @ErickWong So a tighter bound on prime gaps is required.
Comment: @MichaelHardy My guess would be that the OP is referring to the maximal spacing between elements of ${\mathbb Z}_{30}^\times$ being equal to $6$.  It's not at all clear, but it would be a reasonable interpretation that can be made precise.
Comment: I am having some initial suspecions about what is intended.  I'll be back, maybe..... ${}\qquad{}$
Comment: @ErickWong I would multiply the first 1 billion primes and mark the product on the whole number line. Then I would factor each composite number up to the product and examine the arrangement of the 1 billion prime factors. However, it is not practical to do this because of the limits of space and time. Do this with 30, 210, and 2310. I believe that this great pattern continues infinitely.
Comment: this looks to be on track, though theres a lot of excess words. the easiest proof in layman terms: consider a world with finite primes, you multiply them all together to get a huge number. then you add 1. this number is divisible by zero of your "finite primes" therefore there are infinite primes
Answer: The approach seems to be:
Consider the $n$-th prime $p$. Between $p+1$ and $p^2$ every number is either prime or divisible by one of the first $n$. TAMO. Therefore, there is at least one prime between $p+1$ and $p^2$, hence there are infinitely many primes.
I don't know what the miraculous step in the middle is supposed to be. I mean, you can't use the Chinese Remainder Theorem since you'd get
$$
\prod_{\text{primes }q\le p} \frac{q-1}{q}
$$
primes but they'd be spread out among the numbers up to
$$
p\#=\prod_{\text{primes }q\le p}q
$$
which is much larger than $p^2$ unless $p$ is tiny.
Let me put it another way. Suppose all you knew about prime divisors was that in a range of $n$ numbers the prime $p$ divides either $\lfloor n/p\rfloor$ or $\lceil n/p\rceil$ of the numbers. So if you look at the range 6 to 30 (25 numbers) you know that 12 or 13 are even, 8 or 9 are divisible by 3, and exactly 5 are divisible by 5. But that's not enough to conclude that there are any primes in that interval, since $13+9+5=27\ge25.$ Now it happens that the numbers don't conspire that way and there are primes (like 7) in that interval. But how could you know that a conspiracy doesn't happen with larger intervals? If you look at the interval $(97,\ 97^2]$ you'll find that there are 16777 to 16799 primes 2-97 dividing the 9312 numbers in that range so it's entirely possible (a priori) that every number would be covered and there wouldn't be a single prime.
Comment: Yes, indeed it happens that as we go toward infinity that there will be enough prime factors in play to cover every space. Now, not attempting a proof here, but simply stating some facts, the prime factors, although more than enough in quantity to cover every space, will always leave another space open. The primes are where the prime factors are not. Since there are infinitely many primes, the prime factors must be arranged in some orderly way such that there will be infinitely many spaces where none of them will be.
Comment: @JeffreyYoung: That approach doesn't work. You don't have enough control of the congruence classes in the limit.
Comment: @Charles: +1 for TAMO. (I was wondering what that acronym meant.)   :)
Comment: Your link is dead. I guess it was the Sidney Harris cartoon?
Comment: @DanielFischer Indeed.
Answer: OK, here's a guess as to what is meant: among the numbers $1,2,3,4,\ldots,(p_1\cdots p_n)$,
where $p_1<\cdots<p_n$ are the $n$ smallest primes, only $p_1\cdots p_n - (p_1-1)\cdots(p_n-1)$ of them can be divisible by at least one of the primes $p_1,\ldots,p_n$; therefore the others must be divisible by some other primes; hence there are more primes than $p_1,\ldots,p_n$.
But the argument is not clearly expressed here.


Calculate the time difference between two rows for work time

Question: I have one table:
timedate                 workclock
2018-01-01 09:00:00      check-in
2018-01-01 12:30:40      check-in
2018-01-02 09:00:00      check-in
2018-01-02 11:29:00      check-out
2018-01-03 14:29:00      check-out

I need output to look like this:
date          checkin      checkout     working-time
2018-01-01    09:00        none         missing checkout
2018-01-02    09:00        11:29        02:29
2018-01-03    none         14:29        missing checkin

I'm unable to join the rows so any help will be appreciated
There is a third col that represent the worker tag but this should be easy to group.
Comment: Are you missing a `2018-01-01 12:30:40   none   missing checkout`?
Comment: Does the table have *any* way to identify which check-in matches which check-out? Perhaps some ID of the person/item that checked in or out? Without that, the calculated times will be wrong since the rows will not be associated with the corresponding check-in/out.
Comment: @Wrokar I believe it's the date. I also believe OP has a typo in their Desired Results/Output where that last record should be fore `2018-01-03` (perhaps clearing some of the confusion?)
Comment: Sorry, the last requested result has a typo and should be 2018-01-03 as the input data. I just fix it.
Answer: There's probably a better way to do this, but here's how you can do this as a three part query.
First, find all the checkins and use a sub-query to select the first checkout after that checkin on the same day.
select
    date(t1.timedate) as date,
    time(t1.timedate) as checkin,
    (
        select time(t2.timedate)
        from timetracker t2
        where workclock = 'check-out'
          and date(t2.timedate) = date(t1.timedate)
          and t1.timedate < t2.timedate
     ) as checkout
from timetracker t1
where t1.workclock = 'check-in'

+------------+----------+----------+
| date       | checkin  | checkout |
+------------+----------+----------+
| 2018-01-01 | 09:00:00 | NULL     |
| 2018-01-01 | 12:30:40 | NULL     |
| 2018-01-02 | 09:00:00 | 11:29:00 |
+------------+----------+----------+

Note: I assume you're missing the 12:30:40 row from your set.
Then in a separate query, find all the check outs that have no checkin. This is done with a self-join against the checkin rows.
select
    date(t3.timedate) as date,
    null as checkin,
    time(t3.timedate) as checkout
from timetracker t3
left join timetracker t4
     on date(t3.timedate) = date(t4.timedate) and
        t4.workclock = 'check-in'
where t3.workclock = 'check-out'
  and t4.timedate is null

+------------+---------+----------+
| date       | checkin | checkout |
+------------+---------+----------+
| 2018-01-03 |    NULL | 14:29:00 |
+------------+---------+----------+

union them together.
select
    date(t1.timedate) as date,
    time(t1.timedate) as checkin,
    (
        select time(t2.timedate)
        from timetracker t2
        where workclock = 'check-out'
          and date(t2.timedate) = date(t1.timedate)
          and t1.timedate < t2.timedate
        order by t2.timedate
        limit 1
     ) as checkout
from timetracker t1
where t1.workclock = 'check-in'

union

select
    date(t3.timedate) as date,
    null as checkin,
    time(t3.timedate) as checkout
from timetracker t3
left join timetracker t4
     on date(t3.timedate) = date(t4.timedate) and
        t4.workclock = 'check-in'
where t3.workclock = 'check-out'
    and t4.timedate is null

+------------+----------+----------+
| date       | checkin  | checkout |
+------------+----------+----------+
| 2018-01-01 | 09:00:00 | NULL     |
| 2018-01-01 | 12:30:40 | NULL     |
| 2018-01-02 | 09:00:00 | 11:29:00 |
| 2018-01-03 | NULL     | 14:29:00 |
+------------+----------+----------+

The final part is the formatting and ordering. Rather than try to do this in this already giant query, make a new query just for the formatting. Use this query as a subquery table.
select
    t.date,
    case
    when t.checkin is null then
        'none'
    else
        t.checkin
    end as "checkin",
    case
    when t.checkout is null then
        'none'
    else
        t.checkout
    end as "checkout",
    case
    when checkout is null then
        'missing checkout'
    when checkin is null then
        'missing checkin'
    else
        time(checkout - checkin)
    end as "working-time"
from (
    select ...
    union
    select ...
) t
order by t.date, t.checkin

+------------+----------+----------+------------------+
| date       | checkin  | checkout | working-time     |
+------------+----------+----------+------------------+
| 2018-01-01 | 09:00:00 | none     | missing checkout |
| 2018-01-01 | 12:30:40 | none     | missing checkout |
| 2018-01-02 | 09:00:00 | 11:29:00 | 02:29:00         |
| 2018-01-03 | none     | 14:29:00 | missing checkin  |
+------------+----------+----------+------------------+

Or save yourself some hassle and do the formatting on the receiving end.
Comment: Changing time(checkout - checkin) to TIMEDIFF(checkout,checkin) fix the Truncated issue. Now just need to speed this query
Comment: Schwern, Thanks. Your query work great but how can I add the working time between the check-in to check-out. Is there a way to speed the query as it's taking a long time to fetch just 22 rows (almost 20 sec).
Comment: Adding the working time result also with some errors like Truncated incorrect time value: '55568' ErrorNr. 1292
Comment: @Sam The time between checkin and checkout is already there. Use the usual ways to check for performance problems, but I'm going to guess having `date(timedate)` in the where clause will kill performance because it cannot be indexed. See [this question for work arounds](https://stackoverflow.com/questions/95183/how-does-one-create-an-index-on-the-date-part-of-datetime-field-in-mysql). Amir's answer is much cleaner, even if you have to expand out all the views manually.
Answer: Using views simplifies the queries, so use something like
create view in_gate_times as
select date(date_time) xdate, time(date_time) xtime
  from gate_times where gate_op = 'check-in';

create view out_gate_times as
select date(date_time) xdate, time(date_time) xtime
  from gate_times where gate_op = 'check-out';

and then use following query
select i.xdate, i.xtime, ifnull(o.xtime, 'missing')
  from in_gate_times i
  left join out_gate_times o on i.xdate = o.xdate
 union
select o.xdate, ifnull(i.xtime, 'missing'), o.xtime
  from in_gate_times i
 right join out_gate_times o on i.xdate = o.xdate
 order by 1, 2, 3

Check it on SQLFiddle
If using union made your query slow, use union all with following change
select i.xdate, i.xtime, ifnull(o.xtime, 'missing')
  from in_gate_times i
  left join out_gate_times o on i.xdate = o.xdate
 union all
select o.xdate, ifnull(i.xtime, 'missing'), o.xtime
  from in_gate_times i
 right join out_gate_times o on i.xdate = o.xdate
 where i.xdate is null
 order by 1, 2, 3

check this on SQLFiddle

If views are forbidden just replace each view with its query, so the last query will be
select i.xdate, i.xtime, ifnull(o.xtime, 'missing')
  from (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-in') i
  left join (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-out') o
    on i.xdate = o.xdate

union all

select o.xdate, ifnull(i.xtime, 'missing'), o.xtime
  from (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-in') i
 right join (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-out') o
    on i.xdate = o.xdate
 where i.xdate is null
 order by 1, 2, 3

It can be checked on SQLFiddle
Comment: Amir, thanks but I couldn't check this as I can't use view just SQL query.
Comment: @Sam You can manually replace `in_gate_times` and `out_gate_times` with the selects in the views. This approach is more elegant than my solution.
Comment: Amir, WOW. Your query fetch the info 100 time faster. Instead 20 Sec it's 0.2 Sec. THANK YOU.
Comment: @Sam You're welcome. If views are forbidden, you can replace each view usage in the last query with its query (in the parentheses). And if the answer is proper for you, just accept it.