How do i start reading a text file from a specific point?

Question: So my question is basically, how do i start reading a file from a specific line, like for example line 14 until line 18?
Im working on a simple ContactList app and the only thing missing is deleting the information from a specific name. The user can create a new contact which has a name, a number and an address as information. I want the user to also be able to delete the data of that person by typing in their name. Then, the program should read the name and all of the 4 lines under it and remove them from the text File. How could i achieve this?
Comment: You can't. You need to read the first n lines in order to find out which line has which number. Except if your records have a fixed length per line (which is not a good idea - there's always someone with a longer name that you could think of).
Comment: Does this answer your question? [How to read a specific line of a file in C#](https://stackoverflow.com/questions/51222013/how-to-read-a-specific-line-of-a-file-in-c-sharp)
Answer: You can't. You need to read the first n lines in order to find out which line has which number. Except if your records have a fixed length per line (which is not a good idea - there's always someone with a longer name that you could think of).
Likewise, you can't delete a line from the text file. The space on disk does not move by itself. You need an algorithm that implements safe saving and rearranges the data:
<code>foreach line in input_file:
    if line is needed:
        write line to temporary_output_file
    else:
        ignore (don't write = delete)
delete input_file
move temporary_output_file to input_file
</code>
Disadvantage: you need about double the disk space while input_file and temporary_output_file both exist.
With safe saving, the NTFS file system driver will give the moved file the same time stamp that it had before deleting the file. Read the Windows Internals 7 book to understand it in detail. In Windows Internals 6, part 2, it's chapter 12 ("File systems"), subchapter "Tunneling", page 452 in the first printing.
Depending on how large the contact list is (probably it's less than 10M entries), there's no problem of loading the whole database into memory, deleting the record and then writing everything back.
Answer: You can jump to any offset within a file. However, there isn't any way to know where a particular line begins unless you know the length of every line.
If you are writing a contact app, you should not use a regular text file unless:

You pad line lengths so that you can easily calculate the position of each line.
You are loading the entire file into memory.


Difference between executing .sh/.bash program with sh/bash and executing it directly

Question: If we have a program start.sh, we can execute it with the sh start.sh. But we could execute it giving permission with chmod and run ./start.sh in the command line. What is the difference between those two ways of executing a bash/sh script.
Answer: They both execute shell script but there is some little difference:
sh will use will use the sh interpreter even if a differenter interpreter was indicated in the begining of the file like #!/bin/bash this can be useful if you want your script to be executed using always the same interpreter
for ./start.sh the shell will try to execute as an executable file so the script need a shebang like #!/bin/bash so ./start.sh is more flexible since you can use the interpreter you want
Comment: You don't _need_ a shebang actually. `./start.sh` will still work even without one. I was just testing and I can't quite figure out if it runs using whatever the default `$SHELL` is or not. When I was running a bash shell, it ran with `bash` but from a `zsh` and `dash` shell, it ran with `/bin/sh`. In any case, the main point is that even without a shebang, an executable file containing shell commands can be run with `./script.sh`.


SELECT or INSERT a row in one command

Question: I'm using PostgreSQL 9.0 and I have a table with just an artificial key (auto-incrementing sequence) and another unique key. (Yes, there is a reason for this table. :)) I want to look up an ID by the other key or, if it doesn't exist, insert it:
SELECT id
FROM mytable
WHERE other_key = 'SOMETHING'

Then, if no match:
INSERT INTO mytable (other_key)
VALUES ('SOMETHING')
RETURNING id

The question: is it possible to save a round-trip to the DB by doing both of these in one statement? I can insert the row if it doesn't exist like this:
INSERT INTO mytable (other_key)
SELECT 'SOMETHING'
WHERE NOT EXISTS (SELECT * FROM mytable WHERE other_key = 'SOMETHING')
RETURNING id

... but that doesn't give the ID of an existing row. Any ideas? There is a unique constraint on other_key, if that helps.
Comment: It's sad that you had so say "there's a reason for this table" to have  both a auto-incrementing key AND a unique key.  If at all possible, one should ALWAYS have a unique and not null key if using auto-incrementing surrogate keys.  Otherwise, there is *nothing* preventing duplicate real information.  I'm not saying that surrogate keys don't have their uses, but the pervading idea that having both is somehow wrong is a data quality disaster waiting to happen.
Comment: Related answer dealing with possible race conditions: http://stackoverflow.com/questions/15939902/is-select-or-insert-in-a-function-prone-to-race-conditions/15950324#15950324
Answer: Have you tried to union it?

Edit - this requires Postgres 9.1:
create table mytable (id serial primary key, other_key varchar not null unique);

WITH new_row AS (
INSERT INTO mytable (other_key)
SELECT 'SOMETHING'
WHERE NOT EXISTS (SELECT * FROM mytable WHERE other_key = 'SOMETHING')
RETURNING *
)
SELECT * FROM new_row
UNION
SELECT * FROM mytable WHERE other_key = 'SOMETHING';

results in:
 id | other_key
----+-----------
  1 | SOMETHING
(1 row)

Comment: I suspect it'll work in postgres 9.1. At the very worse, 9.1 will allow to write: `with new_row as (insert ... returning *) select * from new_row ... union select * from ...`
Comment: Interesting, +1. I'll keep this in mind for the future when we upgrade to 9.1.
Comment: @EMP: I agree, fascinating to see this ability; then again, I'm looking forward to writable CTEs in general
Comment: You can also make `SELECT * FROM mytable WHERE other_key = 'SOMETHING'` a CTE since you use it twice.
Comment: @MattDiPasquale I've recently seen that, and the example I saw used a `UNION ALL`, which I'm not quite sure why, other than I think it yields performance.  `UNION` and `UNION ALL` should both only return one record.
Comment: How about performance? This approach requires two index lookups (one for INSERT, another for SELECT).
Comment: @vol7ron, UNION ALL does not eliminate duplicates, in case INSERT worked, you will get two rows, unless you use LIMIT 1.
Comment: @greatvovan: there are better ways to do this now (see Aloyse's answer).
Comment: @DenisdeBernardy I saw it, but I doubt it is better. It does only one lookup (in theory), but UPDATE may require DB engine to move row tuple in the table which involves additional read-write IO as well as index update. It requires load test on big number of rows to find out what it better.
Comment: @greatvovan: You're most welcome to post your findings in an answer. I haven't touched Postgres in years, so I'm probably no longer the right person to ask how the performance differs between the old and the new approaches. I would point out, though, that intuitively Aloyee's approach can be improved with an in-memory table (such as an additional `with` statement), so that only has one index lookup occurs (to check whether the record exists). I'm not seeing any obvious good reason to store `existed` in a table.
Answer: using 9.5 i successfully tried this

based on Denis de Bernardy's answer
only 1 parameter
no union
no stored procedure
atomic, thus no concurrency problems (i think...)

The Query:
WITH neworexisting AS (
    INSERT INTO mytable(other_key) VALUES('hello 2')
    ON CONFLICT(other_key) DO UPDATE SET existed=true -- need some update to return sth
    RETURNING *
)
SELECT * FROM neworexisting

first call:
id|other_key|created            |existed|
--|---------|-------------------|-------|
 6|hello 1  |2019-09-11 11:39:29|false  |

second call:
id|other_key|created            |existed|
--|---------|-------------------|-------|
 6|hello 1  |2019-09-11 11:39:29|true   |

First create your table ;-)
CREATE TABLE mytable (
    id serial NOT NULL,
    other_key text NOT NULL,
    created timestamptz NOT NULL DEFAULT now(),
    existed bool NOT NULL DEFAULT false,
    CONSTRAINT mytable_pk PRIMARY KEY (id),
    CONSTRAINT mytable_uniq UNIQUE (other_key) --needed for on conflict
);

Comment: Does this not lock the row for writing unnecessarily? https://stackoverflow.com/a/42217872/4871468
Answer: No, there is no special SQL syntax that allows you to do select or insert.  You can do what Ilia mentions and create a sproc, which means it will not do a round trip fromt he client to server, but it will still result in two queries (three actually, if you count the sproc itself).
Comment: @TruongSinh - sometimes the answer to a yes or no question is no.  They can't always be constructive.  In this case, the answer is no in regards to version 9.0.  So I fail to understand your motivation for downvoting an accurate answer.
Comment: @GiovanniP - no, Denis's answer only works in 9.1, not 9.0 and in any event I read the question as wanting a special sql statement to do this.
Answer: you can use a stored procedure
IF (SELECT id FROM mytable WHERE other_key = 'SOMETHING' LIMIT 1) < 0 THEN
 INSERT INTO mytable (other_key) VALUES ('SOMETHING')
END IF

Answer: I have an alternative to Denis answer, that I think is less database-intensive, although a bit more complex:
create table mytable (id serial primary key, other_key varchar not null unique);

WITH table_sel AS (
    SELECT id
    FROM mytable
    WHERE other_key = 'test'
    UNION
    SELECT NULL AS id
    ORDER BY id NULLS LAST
    LIMIT 1
), table_ins AS (
    INSERT INTO mytable (id, other_key)
    SELECT
        COALESCE(id, NEXTVAL('mytable_id_seq'::REGCLASS)),
               'test'
    FROM table_sel
    ON CONFLICT (id) DO NOTHING
    RETURNING id
)
SELECT * FROM table_ins
UNION ALL
SELECT * FROM table_sel
WHERE id IS NOT NULL;

In table_sel CTE I'm looking for the right row. If I don't find it, I assure that table_sel returns at least one row, with a union with a SELECT NULL.
In table_ins CTE I try to insert the same row I was looking for earlier. COALESCE(id, NEXTVAL('mytable_id_seq'::REGCLASS)) is saying: id could be defined, if so, use it; whereas if id is null, increment the sequence on id and use this new value to insert a row. The ON CONFLICT clause assure
that if id is already in mytable I don't insert anything.
At the end I put everything together with a UNION between table_ins and table_sel, so that I'm sure to take my sweet id value and execute both CTE.
This query needs to search for the value other_key only once, and is a "search this value" not a "check if this value not exists in the table", that is  very heavy; in Denis alternative you use other_key in both types of searches. In my query you "check if a value not exists" only on id that is a integer primary key, that, for construction, is fast.
Answer: Minor tweak a decade late to Denis's excellent answer:
-- Create the table with a unique constraint
CREATE TABLE mytable (
          id serial PRIMARY KEY
,  other_key varchar NOT NULL UNIQUE
);

WITH new_row AS (
  -- Only insert when we don't find anything, avoiding a table lock if
  -- possible.
  INSERT INTO mytable ( other_key )
       SELECT 'SOMETHING'
        WHERE NOT EXISTS (
                SELECT *
                  FROM mytable
                 WHERE other_key = 'SOMETHING'
              )
    RETURNING *
)
(
  -- This comes first in the UNION ALL since it'll almost certainly be
  -- in the query cache. Marginally slower for the insert case, but also
  -- marginally faster for the much more common read-only case.
  SELECT *
    FROM mytable
   WHERE other_key = 'SOMETHING'

  -- Don't check for duplicates to be removed
  UNION ALL

  -- If we reach this point in iteration, we needed to do the INSERT and
  -- lock after all.
  SELECT *
    FROM new_row

) LIMIT 1 -- Just return whatever comes first in the results and allow
          -- the query engine to cut processing short for the INSERT
          -- calculation.
;

The UNION ALL tells the planner it doesn't have to collect results for de-duplication. The LIMIT 1 at the end allows the planner to short-circuit further processing/iteration once it knows there's an answer available.
NOTE: There is a race condition present here and in the original answer. If the entry does not already exist, the INSERT will fail with a unique constraint violation. The error can be suppressed with ON CONFLICT DO NOTHING, but the query will return an empty set instead of the new row. This is a difficult problem because getting that info from another transaction would violate the I in ACID.
Answer: If you're just trying to do this in a serializable manner, and not necessarily in one statement, you have the following simple options:

Use SERIALIZABLE isolation level (other transactions must also use it)
Lock the table first to prevent concurrent changes

And the following less-simple options.
If you SELECT first then INSERT if it's not there, the row can be inserted by another transaction in between. If you INSERT and then SELECT if that fails, the row can be deleted in between. One option is looping the transaction in the application until it works. Otherwise, you definitely have to do an INSERT, so we need the INSERT to also tell us the id of any existing row. So, insert the row, add RETURNING to get the id of the existing row. Now, you have to do ON CONFLICT ... DO UPDATE for RETURNING to work so you can do SET id=mytable.id which doesn't actually change anything. And finally, to figure out whether the row was indeed inserted in this transaction or another one, we can check the xmin hidden column. Putting everything together:
INSERT INTO mytable (other_key)
VALUES ('SOMETHING')
ON CONFLICT (other_key) DO UPDATE SET id=mytable.id
-- https://dba.stackexchange.com/a/148966/249985
RETURNING id,  xmin::text = (txid_current() % (2^32)::bigint)::text as inserted;

However, if the UPDATE happens, it still counts as an update for trigger purposes which may not be desired.

SELECT or INSERT a row in one command


Hibernate HSQLDB two sessions

Question: I am learning Hibernate by reading books and doing examples. I am looking at the example on
http://www.java2s.com/Code/Java/Hibernate/UseTwoSessions.htm web site.
This is a well know site that has Java examples. In this example it used HSQLDB which I have running in it's own JVM. For some reason this example seems to hang when the second session is used. So the question is, is there a problem with this example? Can you have a person look at it and determine if it is a valid example.
The problem is in the main classs (see code below)  Event event2 = (Event) session2.load(Event.class, event.getId()); this line hangs
Thanks for our help. NOTE: if this code is bad, please tell the people at www.java2s.com... If it does work, PLEASE tell me what I could be doing wrong..
I am using this example and have increased the connection count and a host of other changes. Is there some change that will make the TwoSessions example work?
Thanks for your help
Richard
public static void main(String[] args) {
   // HibernateUtil.setup("create table EVENTS ( uid int, name VARCHAR, start_Date date, duration int);");
<code>// hibernate code start
    HibernateFactory.buildSessionFactory();
    Session session = HibernateFactory.openSession();
    Session session2 = HibernateFactory.openSession();
    Event event = new Event();
    event.setName("Name");
    session.save(event);
    session.flush();
    Event event2 = (Event) session2.load(Event.class, event.getId());
    System.out.println(event2.getName());
    HibernateUtil.checkData("select uid, name from events");
// hibernate code end
</code>
}
Answer: The code was probably written for HSQLDB 1.8 which had limited transaction capabilities. Current versions expect each connection to run in its own thread within the database. Use two separate threads.
Comment: Ok it appears that the code above will not work. You need to create a transaction so a session.beginTransaction();  and a session.getTransaction().commit();  is needed. Please look for this code if you try an Hibernate example.

Hibernate HSQLDB two sessions


CSS transform matrices

Question: I'm using the following CSS rules to do a transformation on a simple H2 element, only text inside it:
<code>-moz-transform: matrix(0, -1, 1, 0, 130px, 118px);
-webkit-transform: matrix(0, -1, 1, 0, 130px, 118px);
</code>
It works as expected in Firefox; i doesn't work at all in Safari/Windows and Chrome/Windows: the H2 stays where it is. Am I doing something wrong or are CSS transforms not active in those two browsers under Windows?
Answer:

There is some sort of implementation, but it's definitely broken.
If I remove the px's I can get it to render at least (it doesn't seem to render with them or see it as valid CSS), but it doesnt let the screen scroll down to it like Firefox does. Point it to an location in frame though (without the px's) and it does display. Removing the px's don't seem to make any difference to the position either, which is good.
Comment: I don't mean to be rude, but the screenshot is very small and I can't even understand what you're talking about. Sorry.
Comment: http://i33.tinypic.com/2nhnl7p.png - direct link to image.

Basically
-webkit-transform: matrix(0, -1, 1, 0, 130, 118);
works
-webkit-transform: matrix(0, -1, 1, 0, 130px, 118px);
doesn't.

I don't know why. WebKit also assumes that the last two parameters are pixels, so you get the same rendering as Firefox.
Answer: The MDC docs are pretty clear:

Note:  Gecko (Firefox) accepts a length  value for tx and ty.
  Safari (WebKit) and Opera currently support a unitless number for tx and ty.

After a lengthy post explaining the logic of the matrix, Brendan Kenny concludes that one must

"add  units to e and f for
  Firefox (which doesn't really make any
  sense, but for now: fine)."

Which is true - for the computer - as the linear translations are technically no different than the other entities of the matrix.
But it is unfair, as - for us humans - it makes logical sense for the linear translations to be in value amounts, and there is no other good way to get the browser to do percentage calculations.
Hopefully, the FF implementation will win.
As an aside, I have read, but not yet tested that the third and fourth values are input into Webkit in order, but in FF and IE in reverse.  From the docs:

-moz-transform:  matrix(a, c, b, d, tx, ty)

<code>Where a, b, c, d build the transformation matrix and tx, ty are the translate values.
   ┌     ┐
   │ a b │
   │ c d │
   └     ┘
</code>

CSS transform matrices


The only way that $\max\{X_1, X_2\} >x$ in the subexponetial case, is if either $X_1$ or $X_2$ is large?

Question: In my book about risk, there is a chapter where they show that
\begin{align*}
\mathbb{P}(\max\{X_1, X_2\} > x) = \mathbb{P}(X_1 > x) + \mathbb{P}(X_2 > x) - \mathbb{P}(X_1 > x, X_2 > x) = 2 \overline{F}(x) - \overline{F}^2(x) \sim 2 \overline{F}(x)
\end{align*}
where $X_1, X_2$ are independent and $\overline{F}(x)$ denotes the tail function for a distribution function $F$ on $(0,\infty)$.. From this, they conclude that  the condition that $F$ is subexponential, i.e. that $\overline{F}^{*n}(x)/\overline{F}(x) \rightarrow n$ as $x \rightarrow \infty$, is that the probability of the set $\{X_1 + X_2 > x\}$ is asymptotically the same as the probability of its subset $\max\{X_1, X_2\} > x$. Therefore, in the subexponential case, the only way that $X_1 + X_2$ can get large is of either $X_1$ or $X_2$ is becoming large.
Can anyone try to explain how they conclude this from the fact that $2 \overline{F}(x) - \overline{F}^2(x) \sim 2 \overline{F}(x)$? I do not seem to understand why.
TIA for any help.
Answer: $$\frac{P(X_1+X_2 > x)}{P(\max\{X_1,X_2\} > x)}=\frac{\overline{F^{*2}}(x)}{2\overline{F}(x)}\frac{2\overline{F}(x)}{ 2 \overline{F}(x) - \overline{F}^2(x) } \to 1$$
as $x \to \infty$. This means $P(X_1+X_2 > x) \sim P(\max\{X_1,X_2\} > x)$ as $x \to \infty$.


Why does probability work like this?

Question: I do not quite understand how the probability, when I know $C$ happened, that $A$ occured is $\frac{P(A∩C)}{P(A∩C)+P(B∩C)}$. I am not sure how to write those probabilities, but I can show you what I mean with a numbers example. Here is the tree diagram:

$C$ and $D$ are the same events each time, but they have different probabilities. Let me make up an example:
Please correct me if I am using syntax wrong, I am a learner and this is why I add comments to each statement.
$P(A)=.3$, the probability that $A$ occurs
$P(B)=.7$, respectively that $B$ occurs
For $A$:
$P_A(C)=.4$
$P_A(D) =.6$
I think that $P_A(...)$ means "when $A$ happened probability of (...)"
For $B$:
$P_B(C)=.8$
$P_B(D) =.2$
At the end:
$$
P(A∩C) = (.3)(.4) = .12
$$
$$
P(A∩D) = (.3)(. 6) = .18
$$
$$
P(B∩C) = (.7)(.8) = .56
$$
$$
P(B∩D) = (.7)(.2) = .14
$$
With this numbers example the probability that, when $C$ happened, that $A$ happened would be $\frac{.12}{.12+.56}$.
I would like to understand why this works and also thoughts on notation. The exercise where I found myself wondering about this uses this notation: $P(A|C)$
Answer: Your $P_A(C)$ is typically denoted $P(C \mid A)$. The end of your post recovers the mathematical definition of this quantity: $P(A \cap C) = P(A) \cdot P(C \mid A)$.
Comment: @creativecreatorormaybenot The other way around: "probability of $A$ when $B$ occurred." The usual phrasing is "probability of $B$ *given that* $A$ occurred."
Comment: Does this mean that $P(A \mid B)$ reads as "probability of $B$ when $A$ occured?".
Comment: I think that this is what I meant. I guess that I was a bit sluggish with my phrasing. Thanks, I will try to incorporate this in the future. To me all three of the statements listed in our conversation mean the same, I think that I am still misunderstanding something, somehow. The phrasing of the solution to the exercise I mentioned was "Probability of event $A$ happening considering that we know that event $C$ happened.". Which of all the statements are applicable to that?
Comment: Ah I think that I got it now. Thanks to [this article](http://www.stat.yale.edu/Courses/1997-98/101/condprob.htm), I think that you made a typo when writing "$B$ given that $A$" and wanted to write it the other way around. Thank you.
Answer: We have the equation
$$
P(A \cap C)= P(C)P(A|C)\,.
$$
In order for $A$ and $C$ to happen simultaneously, $C$ must happen (which takes place with probability $P(C)$) and $A$ must also happen (which takes place with probability $P(A|C)$, since we know that $C$ has already happened).
We can rearrange this into the following.
$$
P(A|C)=\frac{P(A\cap C)}{P(C)}
$$
You get your fraction by observing that $P(C)=P(A\cap C)+P(B\cap C)$.  Why is this true?  Well, you know that either $A$ happens or $B$ happens (but not both).  So, in order for $C$ to happen, either $A$ and $C$ must happen together, or $B$ and $C$ must happen together.
Comment: Thank you for your explanation, I was able to follow it very nicely. What really bugs me is the fact that I cannot explain to myself how the probability of $C$ happening inthe $A$ tree is itself devided by the sum of both probabilities of $C$ happening, i.e. in the $A$ tree and in the $B$ tree. I understand how we can derive it from what you said, but I cannot comprehend the division without looking at your first equation. Can you provide me with some mental aid here?
Comment: @creativecreatorormaybenot OK, think of it this way.  If you know that $C$ happened, then you are restricting to the two branches that end with $C$.  So if we are given that $C$ happened, then those two branches are now our 'world'.  Because we want probabilities to go from $0$ to $1$ in our world, we divide by the probability of ending up in one of those two branches.
Comment: Thank you for trying. I think that I will just accept the rules and not think about it anymore. I hope that it will occur to me somewhen.

Why does probability work like this?


Integral inequality with a function twice differentiable

Question: Let $f:[0,1]\longrightarrow\mathbb{R}$ be a function twice differentiable with continous second derivative and $f(1)=f(0)$. The inequality:
$$\int_{0}^{1}(f''(x))^2dx\geq 120\left(\int_{0}^{1}xf'(x)dx\right)^2$$ holds?
Comment: It smells like integration by parts (because of that x there).
Comment: I didn't know how to formulate the question.
Answer: Let
$$
A=\int_0^1xf'(x)\,\mathrm{d}x\tag{1}
$$
Since $f(0)=f(1)$, we have
$$
\int_0^1f'(x)\,\mathrm{d}x=0\tag{2}
$$
$(1)$, $(2)$, and integration by parts gives
$$
\begin{align}
2A
&=\int_0^1(2x-1)f'(x)\,\mathrm{d}x\\
&=\int_0^1f'(x)\,\mathrm{d}x(x-1)\\
&=\int_0^1x(1-x)f''(x)\,\mathrm{d}x\tag{3}
\end{align}
$$
Apply Hölder to $(3)$:
$$
\begin{align}
4A^2
&\le\int_0^1[x(1-x)]^2\,\mathrm{d}x\int_0^1f''(x)^2\,\mathrm{d}x\\
&=\frac1{30}\int_0^1f''(x)^2\,\mathrm{d}x\tag{4}
\end{align}
$$
Plugging $(1)$ into $(4)$ yields
$$
120\left(\int_0^1xf'(x)\,\mathrm{d}x\right)^2\le\int_0^1f''(x)^2\,\mathrm{d}x\tag{5}
$$

Using $f(x)=x(1-x)(1+x(1-x))$, we see that $(5)$ is sharp: both sides equal $\dfrac{24}{5}$.
Comment: What I wanted was to have $u=x(x-1)$ and $v=f'(x)$ so that the limit terms in the integration by parts would vanish, so I needed $(2x-1)\,\mathrm{d}x$ instead of $x\,\mathrm{d}x$ for $\mathrm{d}u$. I recognized that $f(0)=f(1)$ gives us that $\int_0^1f'(x)\,\mathrm{d}x=0$ and used it.
Comment: Okay, so using integration by parts and then Holder makes sense but one would first try it on $\int_0^1 x^2 f''(x)dx$. Why did it occur to you that the $f(0)=f(1)$ condition would allow for that $x^2$ to be changed to something else? (Nice answer, btw)
Comment: Can you, please, provide a solution with random limits of integration, say a and b, instead of 0 and 1.
Comment: @GeorgeR.: Use $g(u)=f\left(\frac{u-a}{b-a}\right)$ or $f(t)=g(a+(b-a)t)$ and write everything in terms of $u$ instead of $t$.
Answer: Since $f(1)=f(0)\Rightarrow \int_0^1f'(x)\,\mathrm{d}x=0$, By integration by parts,
\begin{equation}\label{MSE-730580}
\int_0^1g(x)f''(x)\mathrm{d}x=g(x)f'(x)\bigg|_0^1-\int_0^1g'(x)f'(x)\mathrm{d}x \tag{1}
\end{equation}
Let $g(x)$ be a polynomial defined as,
$$g(x)=ax^2+bx+c\Rightarrow g'(x)=2ax+b$$
Let
$$g(x)f'(x)\bigg|_0^1=0\Rightarrow g(0)=g(1)=0\Rightarrow b=-a$$
we can get,
$$g(x)=ax(x-1)\Rightarrow g'(x)=2ax-a \tag{2}$$
by $(1),(2)$, we have
$$\int_0^1x(x-1)f''(x)\mathrm{d}x=\int_0^1(1-2x)f'(x)\mathrm{d}x=-2\int_0^1xf'(x)\mathrm{d}x$$
by the Cauchy-Schwarz inequality,
\begin{align*}
\left(\int_0^1xf'(x)\mathrm{d}x\right)^2
&=\left(\int_0^1\Big(-\frac{1}{2}x(x-1)\Big)f''(x)\mathrm{d}x\right)^2\\
&\leqslant\int_0^1\Big(-\frac{1}{2}x(x-1)\Big)^2\mathrm{d}x\int_0^1(f''(x))^2\mathrm{d}x
\end{align*}
Therefore,
$$120\left(\int_0^1xf'(x)\,\mathrm{d}x\right)^2\le\int_0^1f''(x)^2\,\mathrm{d}x$$
because,
$$\int_0^1\bigg(-\frac{1}{2}x(x-1)\bigg)^2\mathrm{d}x=\frac{1}{120}$$


Why does (1/3) mod 3016 = 2011?

Question: So I am taking a class where we are working on a cryptography section. Basically, the course says that:
$$\frac 1 3 \mod(3016) = 2011$$
or when run through Python - modified with SciPi:
$$\frac 1 3 \,\%\, 3016 = 2011$$
I don't understand how or why this happens. Does anyone know why the modulo division would produce this result?
Comment: I can confirm that typing `(1/3)%3016` at the **sage** prompt returns 2011. But no way is this what plain Python gives you. Possibly sage modifies the definition of built-in operators, or performs some other magic, but in any case the question should state that 'sage' is used, not Python. For more information about where the computation actually takes place, try typing `(1/3)%3015` in sage instead.
Comment: I don't know where you type that code into, but it's not the python interpreter (and therefore is not python code), since there's nothing in there to cause it to use the sage mathematics library rather than the standard int library. Python itself will give a result of either 0 or 0.33333333 depending on the version.
Comment: What exactly do you mean run through python? That's not python code.
Comment: The class I'm taking uses Sage Mathematics, which uses Python code. The code: x = (1 / 3) % 3016; print(x); prints out the value 2011, I thought I would just simplify that into one line. I mentioned it was 'ran through python' because I wasn't sure whether this was the actual 'math' answer, or if the Python programming language was just doing the math weird.
Comment: Yes but my point is that python doesn't give 2011 as the result
Comment: I looked it up and Sage says that it uses SciPi -  http://www.scipy.org/, so I guess that is why it gives out 2011.
Comment: My answer at http://math.stackexchange.com/questions/1127483/how-to-make-sense-of-fractions/1127776#1127776 complements @Bye_World s answer here.
Comment: @MarcvanLeeuwen I don't think sage so much modifies the python interpreter as I believe it preforms all kinds of preparsing for it. Including retyping and similar.
Answer: What you're calling $\dfrac 13$ is just the multiplicative inverse of $3$ mod $3016$.  You can easily verify that $2011$ is the multiplicative inverse of $3$.  $$3\cdot 2011 = 6033 = (2\cdot 3016)+1$$
Answer: One can in fact use fractions in modular arithmetic, as long as one only uses fractions with denominator coprime to the modulus. For these fractions the usual grade school arithmetic of fractions holds true. For example, let's consider your problem.
$\quad {\rm mod}\ 3n\!+\!1\!:\,\ 3n\!+\!1\equiv 0\ $ so $\ 1 \equiv 3(-n)\ $ therefore $\ \dfrac{1}3 \equiv -n \equiv 2n\!+\!1.\ $
$\quad$ In your case $\ 3n\!+\!1 = 3016\,$ so $\,n=\dfrac{3015}3 = 1005,\,$ so $\,\dfrac{1}3\equiv 2n\!+\!1 = 2011$
The notation $\,1/3\,$ means $\,3^{-1},\,$ i.e. a root of $\,3x\equiv 1\pmod{3n\!+\!1}.\,$ The inverse exists and is unique because $\,\gcd(3,3n\!+\!1)=\gcd(3,1)=1,\,$ so by Bezout's identity for the gcd we have
$\quad \text{for some } j,k\!:\ \ 3j+(3n\!+\!1)k = 1\ \Rightarrow\ {\rm mod}\ 3n\!+\!1\!:\ 3j\equiv 1\ \ {\rm so}\ \ j\equiv 3^{-1}\! \equiv 1/3$
and inverses are always unique.  Hence the notation $\,1/3\, :=\, 3^{-1}\,$ is well-defined.
Remark $\ $ Generally we can use the extended Euclidean algorithm to compute modular inverses. The above is essentially an optimization for the case when it terminates in a single step, i.e. inverting $\,a\,$ modulo $\,m = an+1,\,$ i.e. when $\,a\mid m-1.$
Answer: No one has mentioned that for any fixed N, {a | gcd(a,N)=1} forms a group. Closure under multiplication is easy to see with elementary manipulations.
The inverses usually are explained using the Euclidean Algorithm. At the very least if you want to understand inverses in modular systems, this desire could sustain you while you read/hear an explanation of the Euclidean Algorithm.
Comment: The OP is asking why the operation works and why his code gives him this answer. You could improve your answer by showing the Euclidean algorithm or at least linking to it and explaining in more detail how it relates to inverses.
Comment: Ok, I prefer motivating concepts to working example details, so I'll stay away from the homework problems. Sorry to have drawn so much negative attention.

Why does (1/3) mod 3016 = 2011?


There is Error: java: package com.fasterxml.jackson.annotation no exist

Question: my programme use java and springboot and gradle technology,I have configure java environment and gradle,I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. when I build my programme there is always a problem like this:
Error:(3, 40) java: package com.fasterxml.jackson.annotation not exist.
I have configure in my build.gradle like this:
repositories {
    maven {
        url "https://maven.aliyun.com/nexus/content/groups/public"
    }
    mavenCentral()
    jcenter()
}

to download jar package but it's useless.
Thanks in advance
Comment: how does the whole gradle file look like?
Comment: Since there are **no dependencies** listed in that Gradle file, why on earth would you believe that it downloaded and added the Jackson library to your project? I highly recommend you **learn how to use Gradle** before asking any more questions on the topic. Any Gradle tutorial will cover *dependencies*, since that is a core part of what Gradle does.
Answer: Probably, you didn't add json serializers into your application.
Please add the following dependency to fix this (however usually it is arrived as dependency of Spring Boot Web or something).
compile group: 'org.springframework.boot', name: 'spring-boot-starter-json', version: '2.3.1.RELEASE'


Can't find Android build tool with ionic2 cordova

Question: when I try to build an APK with

ionic cordova build android

Suddenly I faced this error

  * What went wrong:
    A problem occurred evaluating root project 'android'.

No installed build tools found. Install the Android build tools version 19.1.0 or higher.
          0

I'm sure that a have android build tool from android studio versions (2.1.1 - 22.0.0 - 23.0.0 ) and last version 26.0.1
output of cordova requirements

Requirements check results for android:
  Java JDK: installed 1.8.0
  Android SDK: installed true
  Android target: not installed
  android: Command failed with exit code ENOENT
  Gradle: installed /Applications/Android Studio.app/Contents/gradle/gradle-3.2/bin/gradle
  Error: Some of requirements check failed

and this the uses sdk in AndroidMaifest.xml file
    <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />

Installed platforms: android 6.2.3
Comment: what is the output of `cordova requirements`? and `targetSdkVersion` in AndroidManifest xml in your android platform folder?
Comment: ok .. please check the last edit in the post
Comment: What is your Cordova android platform version?
Comment: Installed platforms:
  android 6.2.3
Answer: Is your android sdk folder saved on your environment variables?
Try to add your root android SDK folder(something like C:\android-sdk or C:\Program Files (x86)\Android\android-sdk\) to both ANDROID_HOME and ANDROID_SDK_ROOT environment variables.
Also add(change it to your current android sdk folder):
C:\Program Files (x86)\Android\android-sdk\tools
C:\Program Files (x86)\Android\android-sdk\platform-tools
And maybe
C:\Program Files (x86)\Android\android-sdk\build-tools\26.0.1
To your system's PATH variable
Then, download only the binary for gradle here

Extract it to C:\Gradle. Example: C:\Gradle\gradle-3.5
Add C:\Gradle\gradle-CURRENTVERSION\bin to the PATH variable.

After that, restart the computer or re-open any terminal you're running the command
Comment: Sorry but where I spouse can find  ANDROID_HOME &  ANDROID_SDK_ROOT ... notice  that I am using mac os .
Comment: @TawfiekKhalaf you don't find them, you add your Android Root SDK path  to your environment variables named ANDROID_HOME and also named as ANDROID_SDK_ROOT
Comment: how I can do that ?!
Comment: Look [here](https://apple.stackexchange.com/questions/106778/how-do-i-set-environment-variables-on-os-x)


How do I stop water from coming out of the dispenser on the door of my refrigerator?

Question: How do I stop water on the door of my refrigerator from coming out?
Comment: Can you provide more information? What type of refrigerator is it? Is the paddle or button for dispensing water stuck, or is it just coming out on its own? Etc...
Answer: Sounds like the valve is broken.  You'll have to locate the shutoff valve, and turn it off there for now.
Pull the fridge out, and look for a valve behind it.  If you can't find one, you'll have to look elsewhere (basement, crawlspace, etc.). It's common for fridges to be fed using saddle valves, so you might want to start looking for that first.
You should be able to find replacement parts online, but you'll have to know the make and model of the fridge.


What benefits do joining city tiles bring?

Question: Cities naturally 'grow' tiles with culture points. The map tiles around your city become the colour of your civilisation, which means that your city can 'work' those tiles. A city also has the ability to purchase these tiles at a cost of gold.
You can join cities by linking their workable tiles together. I understand that doing so gives a territorial border, but are there any other reasons for doing so?
I want to build cities along the coast, which will be joined by harbours, but I am unsure if not linking their tiles will cause me problems.
The image below illustrates three cities that are joined by workable city tiles:
Comment: I think the primary benefit is that your opponents can't claim tiles you've already claimed for yourself (culture bomb is the exception)
Answer: It brings no mechanical advantages, only strategic ones, which include:

Blocking terrain for those civs vith whom you dont have open borders
Defensive line of your territory (bonuses/healing)
By virtue of being close together, roads per city are shorter = cheaper (not important for harbor connected or on strategic (rail)road (one that you would build anyway for troop transport))
When close together, cities can share tiles (only one of them ownds it, but other citty can "borrow" it and work there) and provide fire cover for each other (now with minimal distance 3 tiles, it is only against bad placed ranged units))
Cities are closer, so defense can arrive sooner.
You have no sight gaps between your cities where nasties can lurk.

So nothing really big except distance to travel for defensive units. So if you can defend anyway, don't trouble yourself too much with connecting your borders (but later add cities to use that terrain (or not if you want culture costs low).
Maybe enemies will settle between your cities and then you can puppet them ;)
Answer: Harbors will connect cities to form a trade network, which means that resources found/upgraded around one city will be available to the rest of your cities.  The other way to do this is by road.
Roads have other benefits though, in that they allow the fast movement of units between your cities.  This greatly benefits you if you need to move military units around due to changing political conditions.
You could build roads across non-owned tiles, but then there's a chance another Civ or city state will eventually take that tile, which may lock you out of using that road, depending on the political situation.  Being surrounded by potential enemies with no means to reinforce is a recipe for being conquered.
You could also try to buy up at least a one tile wide strip between your distant cities, assuming they were near enough together to allow this.  This is going to cost you, though, as the gold cost per tile seems to increase with distance from the city center.
This also makes your roads longer, which will slow troop and worker movement.  Also, roads cost gold you per tile used.  This is offset somewhat by the gold income from trade routes, but not really enough to justify very long roads.
You could make each city an independent entity, capable of defending itself, but the maintenance costs associated with this strategy make it only worthwhile when the situation you're in requires it.
Personally, I take a middle of the road (no pun intended...) strategy.  I tend to settle cities far enough apart that they have as many independent tiles as possible, and so that they are individually located near important resources.  However, I also try to keep them close enough together that the road costs aren't prohibitive, and so that I can move troops quickly as needs arise.


Is it silly to write $\phi : [a,b] \rightarrow \phi([a,b])$?

Question: If it is rather silly, how would you express such a function? For example (to be specific), if $\phi : [a,b] \rightarrow \mathbb{R}$ is injective, how would you express the fact that the same function with the co-domain restricted to the range of $\phi$ is bijective?
EDIT: I am assuming I haven't previously defined what the function $\phi$ is in any way.
ANSWER FROM COMMENTS: It is not silly to write $\phi : [a,b] \rightarrow \phi([a,b])$.
Comment: No, it is not silly to write $\phi:[a,b]\to\phi([a,b])$ is bijective.
Comment: Stating the fact in English as you've done in the question is a good way to express it.
Comment: The way you have is fine, but more commonly I have seen $\phi:[a,b]\to\operatorname{Im}(\phi)$. But as I said, making this distinction is not really needed because mostly everyone will know that $\phi$ will be bijective when you restrict the range to the image.
Comment: It's a standard fact that an injective function that is restricted to its image becomes bijective. Mostly any undergraduate math major will know this immediately.
Comment: @NicholasRoberts How would you write down this function?
Answer: It doesn't quite sit so well with me as it seems to with people in the comments, but then I'm usually a bit of a stickler for notation. It strikes me as an abuse of notation.
A function $\phi$ ought be defined with a fixed, known domain and codomain (before you can even define where in the codomain it sends a point $x$ in the domain). In order to parse $\phi([a, b])$, I need to already know where $\phi$ sends the points in its domain, which means I already have some idea of the codomain (these points have to be mapping to somewhere, right?). This original codomain should technically be specified.
If I were doing it properly, I'd prefer to talk about $\phi : [a, b] \to \Bbb{R}$ (or whatever other codomain) first, then define some $\hat{\phi} : [a, b] \to \phi([a, b])$, or something like that.
Now, that said, being an abuse of notation doesn't mean that it's silly, or even that it's at all bad. We use abuses of notation all the time. So long as it is clear what you're saying (and I'd say it is pretty clear), then most people will be fine with it. In fact, it can often be preferable to abuse notation than to, say, define all your functions twice and leave hats over all of them!


Dist-Upgrade to a different Distro-Flavour

Question: I made the mistake to upgrade from Ubuntu 18.04 LTS to Ubuntu 20.04 LTS.
Now I'm desperately looking for an defined migration path ongoing from Ubuntu 20.04 LTS to a system (perhaps 20.04 LTS based) that does not require Snapd to be enabled in the system configuration (for normal operations).
Which migration options exist?

Just as an illustration example as it caused some comments and it is necessary to draw the line that the question does not appear off-topic: If any of the Ask-Ubuntu-on-topic distros (? Flavors? Spin-offs? Any Ask-Ubuntu offical wording here in case of mismatch!) (next to 18.04 LTS / 20.04.2 LTS) would not ship with Snapd by default, this would also be a hypothetically considerable acceptable example. Another one would be to answer that there is no migration path by any of the Spin-Offs and this is known (or an unknown known).
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/121145/discussion-on-question-by-hakre-dist-upgrade-to-a-different-distro-flavour).
Answer: None whatsoever. The normal method is to make a backup of your personal files and reinstall a version you want to use and there is no release without snap.
You can however remove snap from your current installation with
<code>sudo apt autoremove --purge snapd
</code>
That will remove anything snap related and you can install each of the non-snap versions to replace them.
Comment: @24601 Perhaps - I do not view my skills as being so advanced however, and bask in the glow of the awesome computing knowledge of other presented on this site.  I'm a huge fan of backups, and a full install of Ubuntu and all programs I want takes less than an hour.  Learn by doing....
Comment: Running without snapd has been OK for me, although the Ubuntu software store looses functionality, and there may be applications that are not available otherwise.  I have not found any yet...
Comment: However, keep in mind a lot of things may be removed that you want without Debian package equivalents - a lot of things are just Snapped now by default in the Ubuntu 20.04+ environment and metapackages install the snaps.
Comment: I'm a bit puzzled about this suggestion and how serious it is. Is it possible to properly run an Ubuntu 20.04.2 LTS without Snapd? I'm currently testing by disabling it, but already on the dist upgrade there was some kind of force to use Snapd (suddenly). The dist upgrade somehow didn't care it was already explicitly not activated on 18.04 LTS on my system, but still making is a non-optional suggestion.
Comment: @CharlesGreen don't forget you are vastly more experienced than the OP at solving issues which the OP may struggle with, if I may be so bold to say.
Comment: I agree with Charles.  Create a good backup, know how to restore it and start tweaking your system. My experience in Ubuntu taught me how to reinstall my system within 20 minutes with almost zero downtime (I keep using firefox during the installation and the downtime is 1 reboot).
Comment: @Rinzwind: Would you consider the backup that ships with Ubuntu (18.04) a "good backup" in this context?
Comment: Never used it. Files on my machine that are older than a day and are not downloaded files are automatically rsync'd to a NAS every time I turn my machine on. The ability to restore is more important ;-) deja-dup seems to be pretty good (not a lot of issues on AskUbuntu)
Comment: It could be read that's about `$HOME` and the downloads therein, yes fine. I also keep out docker images. And would add the list of apt installed software so it's easy re-install for that purpose.


set values from outside the report to a jasper report

Question: I am going to generate reports using jasper reports. For that, my plan is,

create the jrxml file as needed using iReport tool.
set the values required from out side the report. (I mean if I have a variable called name="james" in my java program set that variable to a text field in the report)
then create the report and generate the pdf.

What I need to know is the possibility of this. Can I set my variables into the fields in my jrxml file? If it is possible, How can I do it?
Answer:
What I need to know is the possibility of this. Can I set my variables into the fields in my jrxml file?

Basically, yes.
You need to define the parameter as a "Parameter" type in the report, then supply the parameter as the "Text Field Expression" on the form in the format $P{...}

Then, when you want to fill the report, you need to do is create a Map of some kind, each key in the map should be the name of parameter your defined in the report, for example...
Map<String, Object> mapParameters = new HashMap<String, Object>(5);
mapParameters.put("USER_NAME", name);

JasperPrint print = JasperFillManager.fillReport(report, mapParameters);

Answer: it resolved !!
para.put(<key>,<value>);
para.put(<key>,<value>);
para.put(<key>,<value>);

JasperFillManager.fillReportToFile(jr, para, new JRemptyDataSource());

if you don't write  new JRemptyDataSource() a message will appear that the document has no pages
and inside your report create a field and in field expression put your parameter (the parameter name should have the same key value )
Answer: I got answer
     parameters.put("ReportTitle", "List of Contacts");
     parameters.put("Author", "Prepared By Manisha");

     JasperPrint print = JasperFillManager.fillReport(sourceFileName, parameters, new JREmptyDataSource());

     JRPdfExporter exporter = new JRPdfExporter();
     exporter.setExporterInput(new SimpleExporterInput(print));
     exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outFileNamePDF));
     SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
     configuration.setMetadataAuthor("Petter");  //why not set some config as we like
     exporter.setConfiguration(configuration);
     exporter.exportReport();


iPad 2 is not getting detected by xcode4.3

Question: I was able to run my projects in iPad and iPhone using the xcode 4.3 till yesterday. But today when I tried, the XCode is not getting connected with the iPad, and it is getting connected with iPhone.
I have checked the deployment target, provisioning profile, all these things are correct, and working fine in iPhone. In the organizer an orange indicator is showing instead of green symbol while connecting. I have restarted both the system and iPad several times and checked, not get solved.
If anybody having idea about this then please help me.
Answer: Just upgrade you Xcode or  if you have another computer which contains xcode 4.5, detect your device on that computer this will also detect your device on computer with xcode 4.3.
I also had same problem and this works for me.
Comment: I have checked this and device is getting connected with xcode 4.5 in another computer but not in xcode 4.3 in my computer
Comment: what you set ios Deployment Taget. set this 4.0 from build setting -> project-> info -> ios Deployment Taget


Ubuntu 20.04 | Any way to get rid of "systemctl suspend" and start using "s2ram" globally?

Question: After days trying to fix suspend issues in my laptop. I would like to get rid of the Ubuntu suspend system and completely replace it with "S2RAM".
So basically when I press the Power button, the Sleep button, Close the lid: I just want my laptop to call "S2RAM" application, nothing more.
S2RAM is the only thing that works well in my laptop. If I type sudo S2RAM when I'm playing a video, my laptop goes off in less than 1 second, the Power led and keyboard go off instantly, then I wait some minutes, I press the power button and everything resumes perfectly.
So far I tried this without success:
sudo systemctl edit systemd-suspend.service

And add the following:
[Service]
Type=oneshot
ExecStart=/usr/sbin/s2ram

I also tried the following alternative (changing the path sometimes):
[Service]
ExecStart=
ExecStartPre=-/usr/bin/run-parts -v -a pre /usr/lib/systemd/system-sleep
ExecStart=/usr/sbin/s2ram
ExecStartPost=-/usr/bin/run-parts -v --reverse -a post /usr/sbin/s2ramlib/systemd/system-sleep

Followed by
systemctl daemon-reload

None of these options seem to work. Because if I type systemctl suspend:

It is not instant like when running sudo S2RAM
Sometimes hangs the system (just like always do)
Sometimes turns off the screens and doesn't come back

So to me, S2RAM is not taking over at all the Ubuntu "suspend" approach.
Is there any other way to achieve this? I think it will be the only solution to make my Dell laptop sleep in Ubuntu. I tried more than 30 solutions, none worked except S2RAM application. I just need to know how to make it default
Comment: Please post output of `cat /etc/systemd/sleep.conf` as well as `systemctl list-dependencies systemd-suspend.service` **PS** all s2ram does is `echo mem | sudo tee /sys/power/state` (I just checked https://git.kernel.org/pub/scm/linux/kernel/git/rafael/suspend-utils.git/tree/) ;-)
Comment: `systemctl status systemd-suspend.service`  please.
Answer: From your Desktop screen, press F1, then Ctrl + L and type man:systemd-suspend.service.8.
Repeat for man:systemd-sleep.conf.5.
You have more experience in this matter than me as evident in question, but I'm sure this might help.
Answer: I had the same situation on Ubuntu 20.04 with same symptoms on choosing "Suspend" button in Gnome as OP.
systemctl suspend was not working, but echo mem | sudo tee /sys/power/state did (which is what S2RAM is also doing). According to the manpage of "systemd-suspend.service" it's the same, what systemctl suspend is doing. So what are the differences?
Systemd is handling additional dependencies, that must return success before doing the "echo mem". So I checked the dependencies in the directory /etc/systemd/system/systemd-suspend.service.requires and found 2 links pointing to nvidia-driver-suspend stuff. I disabled them by renaming the directory as shown - may be there a better ways to do this.
cd /etc/systemd/system
sudo mv systemd-suspend.service.requires unused-systemd-supend.service.requires
sudo systemctl daemon-reload

systemctl suspend is now working and so Suspend works globally again also from Gnome Suspend button - which was my original problem.


Measures, as a supreme, proof

Question: Let $\Sigma$ be a $σ$-algebra over a set $X$, and $μ_1$ and $μ_2$ finite measures in it. It can be shown that the function $μ:\Sigma \to [0,\infty ]$ defined by
$$E\mapsto \sup_{F∈\Sigma}\{μ_1(E∩F)+μ_2(E\setminus F)\}$$
is a measure.
could someone help me see is a measure
I got stuck when i have to show
$$\mu(\bigcup_{n=1}^\infty E_n) \geqslant \sum_{n=1}^\infty\sup_{F\in\Sigma} \left\{\mu_1(E_n\cap F) + \mu_2(E_n\setminus F) \right\} = \sum_{n=1}^\infty \nu(E_n).$$
$E_n $ a secuence of disjoints set
Know you can also use Radon-Nicodym, since $\mu_1$ and $\mu_2$ finite, but i'm more interested in the general case, when you have two measures
Comment: I've attempted to clean up your seemingly copied-and-pasted bit of notation, but I'm still trying to figure out what was intended.  Can you clarify? ${}\qquad{}$
Comment: Sorry, i'm not sure how to say it, but the problem, is tha i'm not able to proove that $$\sup_{F∈\Sigma}\{μ_1(E∩F)+μ_2(E\setminus F)\}$$ is a measure
thanks for correcting me, and sorry for my english
Comment: Can you use the Radon-Nikodym theorem?
Answer: We only need to prove
$$
\nu(E)=\nu(\bigcup_{n=1}^\infty E_n) \geqslant \sum_{n=1}^\infty \nu(E_n)$$
as another case is proved in @Math1000's post.
First we prove
$$
\nu(E_1\cup E_2)\geqslant \nu(E_1)+\nu(E_2)
$$
for disjoint $E_1$ and $E_2$.
By definition of $\nu$, there exist $F_1,F_2\in\Sigma$ such that
$$
\mu_1(E_1\cap F_1) + \mu_2(E_1\setminus F_1)\geqslant \nu(E_1)-\epsilon\quad\text{and}\quad \mu_1(E_2\cap F_2) + \mu_2(E_2\setminus F_2)\geqslant \nu(E_2)-\epsilon
$$
So
\begin{align}
\nu(E_1\cup E_2)&\geqslant \mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cap F_2)
\\
&=\mu_1((E_1\cap (F_1\cup F_2))\cup (E_2\cap (F_1\cup F_2)) + \mu_2((E_1\setminus F_1\cap F_2)\cup (E_2\setminus (F_1\cap F_2))
\\
&=\mu_1(E_1\cap (F_1\cup F_2))+\mu_1( E_2\cap (F_1\cup F_2))+\\&\hspace{10 mm}\mu_2(E_1\setminus F_1\cap F_2)+\mu_2(E_2\setminus F_1\cap F_2)
\\
&\geqslant \mu_1(E_1\cap F_1)+\mu_1( E_2\cap F_2)+\mu_2(E_1\setminus F_1)+\mu_2(E_2\setminus F_2)
\\
&=\nu(E_1)+\nu(E_2)-2\epsilon
\end{align}
Since $\epsilon$ is arbitrary small, we have
$$
\nu(E_1\cup E_2)\geqslant \nu(E_1)+\nu(E_2)
$$
Thus
$$
\nu(E_1\cup E_2)=\nu(E_1)+\nu(E_2)\tag{1}
$$
Next we prove
$$
E_1\subset E_2\implies \nu(E_1)\leqslant \nu(E_2)\tag{2}
$$
Since for any $F\in\Sigma$
$$
\mu_1(E_1\cap F) + \mu_2(E_1\setminus F)\leqslant \mu_1(E_2\cap F) + \mu_2(E_2\setminus F)
$$
So
$$
\nu(E_1)=\sup\{\mu_1(E_1\cap F) + \mu_2(E_1\setminus F)\}\leqslant \sup\{\mu_1(E_2\cap F) + \mu_2(E_2\setminus F)\}=\nu(E_2)
$$
Finally for any disjoint $E_n$, since
$$\bigcup_{n\leqslant m}E_n \subset \bigcup_{n=1}^{\infty} E_n$$
By (1) and (2), there is
$$
\sum_{n\leqslant m}\nu(E_n)=\nu(\bigcup_{n\leqslant m} E_n)\leqslant \nu(\bigcup_{n=1}^{\infty}E_n)
$$
Let $m\to\infty$, it is proved.
Comment: $$\nu(E_1\cup E_2) = sup(\mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cup F_2)) $$
$$\geqslant \mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cap F_2)$$
i'm los in that inecuality, maybe is trivial but, i'm not able to see it
Comment: Since $\nu(E_1∪E_2)=\sup$ is reached for some $F$, it may not be $F_1∪F_2$. But $\sup$ is always larger than other $F$.
Comment: $$\nu(E_1\cup E_2) = sup(\mu_1((E_1\cup E_2)\cap F_1) + \mu_2(E_1\cup E_2\setminus F)) $$
$$\geqslant \mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cup F_2)$$
$$\geqslant \mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cap F_2)$$

i undertand it like you are telling me that,
Comment: 1st line $F$ could be different and 2nd line should be $μ_2(E_1∪E_2∖F_1\cap F_2)$. 2nd line $F$ could be different too.
Comment: $$\nu(E_1\cup E_2) =sup\mu_1((E_1\cup E_2)\cap (F) + \mu_2(E_1\cup E_2\setminus F) $$
$$\geqslant \mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cup F_2)$$
$$\geqslant \mu_1((E_1\cup E_2)\cap (F_1\cup F_2)) + \mu_2(E_1\cup E_2\setminus F_1\cap F_2)$$ is this what you are tryin to tell me?
Comment: Yes, except 2nd line should be $μ_1((E_1∪E_2)∩(F_1∪F_2))+μ_2(E_1∪E_2∖F_1\cap F_2)$
Answer: Let $$\nu(E) = \sup_{F\in\Sigma}\{\mu_1(E\cap F) + \mu_2(E\setminus F)\}.$$
Then for any $F\in\Sigma$, $$\mu_1(\varnothing\cap F)+\mu_2(\varnothing\setminus F) = \mu_1(\varnothing) + \mu_2(\varnothing) = 0.$$
If $E_n$ is a sequence of disjoint sets in $\Sigma$, let $E=\bigcup_{n=1}^\infty E_n$. Then for any $F\in\Sigma$,
$$\mu_1(E\cap F)=\mu_1\left(\bigcup_{n=1}^\infty (E_n\cap F)\right) = \sum_{n=1}^\infty \mu_1(E_n\cap F), $$
and similarly
$$\mu_2(E\setminus F)=\mu_2\left(\bigcup_{n=1}^\infty (E_n\setminus F)\right) = \sum_{n=1}^\infty \mu_2(E_n\setminus F).$$
Hence
$$
\nu(E) = \sup_{F\in\Sigma}\left\{\sum_{n=1}^\infty \mu_1(E_n\cap F) + \mu_2(E_n\setminus F) \right\}$$
and so $$\nu(E) \leqslant \sum_{n=1}^\infty\sup_{F\in\Sigma} \left\{\mu_1(E_n\cap F) + \mu_2(E_n\setminus F) \right\} = \sum_{n=1}^\infty \nu(E_n).$$
It remains to show the reverse inequality. (I got stuck here :/ )
Comment: Sugestion: in $\sup_{F\in\Sigma} \left\{\mu_1(E_n\cap F) + \mu_2(E_n\setminus F) \right\}$ you can, WLOG,  consiser only $F\subseteq E_n$. So we have $\sup_{F\in\Sigma} \left\{\mu_1(E_n\cap F) + \mu_2(E_n\setminus F) \right\}=\sup_{F_n\in\Sigma \textrm{ and } F_n\subseteq E_n} \left\{\mu_1(E_n\cap F_n) + \mu_2(E_n\setminus F_n) \right\}$.
Comment: Then use the disjoint union $\bigcup_{n=1}^\infty F_n$ in the expression of $\nu(E)$ to show that $$\nu(E) \geqslant \sum_{n=1}^\infty\sup_{F\in\Sigma} \left\{\mu_1(E_n\cap F) + \mu_2(E_n\setminus F) \right\}.$$

Measures, as a supreme, proof


php preg_match a date format "yyyy-MM"

Question: I'm trying to use a modified preg format from preg_match: check birthday format (dd/mm/yyyy) to match credit card expiration dates (yyyy-MM formats)
    if (!preg_match('/([0-9]{4})\-([0-9]{2})/', $expirationDate, $matches)) {
        throw new Services_Payment_Exception('Card expiration date is invalid');
    }

For some reason, it also validate invalid values such as 20111-02 (invalid year).
What am I doing wrong here? I want to confirm the year is 4 digits and the month is 2 digits (01, 02.. 12)
Answer: Anchor your regexp:
preg_match('/^([0-9]{4})-([0-9]{2})$/', $expirationDate, $matches)

Your regexp didn't do what you expected because it matches "0111-02" substring of "20111-02".
Anchors ^ and $ match particular positions within the input string: ^ matches the beginning of the string and $ matches the end.
Note also that there is no need to escape the hyphen since it only has a special function in [].
Answer: Use ^ and $ anchors:
if (!preg_match('/^([0-9]{4})\-([0-9]{2})$/', $expirationDate, $matches)) {
    throw new Services_Payment_Exception('Card expiration date is invalid');
}

to ensure the whole string matches the pattern.
In your example 20111-02 matches because it matches the 0111-02 part of 20111-02.
Answer: It's matching 0111-02, which fits your requirements.
Change:
'/([0-9]{4})\-([0-9]{2})/'

to:
'/^([0-9]{4})\-([0-9]{2})$/'

so it only checks against the entirety of the string.
Answer: try this:
     if (!preg_match('/^([0-9]{4})\-([0-9]{2})/', $expirationDate, $matches)) {
Answer: Try this it will help check both date format and check if the date if valid or not:
if (!preg_match('/^([0-9]{4})\-([0-9]{2})$/', $expirationDate, $matches)) {
    throw new Services_Payment_Exception('Card expiration date is wrong format');

}else if ( !strtotime($expirationDate) ){
    throw new Services_Payment_Exception('Card expiration date is invalid');
}

php preg_match a date format "yyyy-MM"


Wind from kitchen sink drainage pipe

Question: We live on a windy coast of North Sea. High wind is a norm here. One of the problems I face with the wind: it comes out from kitchen sink drainage pipe. If it is blowy outside, you can feel a draft coming from the drainage pipe.
I think the problem is because the drainage pipe finishes outside and does not make a sealed connection:

Because the drainage pipe is not sealed, the wind blows up the pipes and comes out from my sink drain. Making the kitchen colder (we have enough vents there already!)
Is there anything can be done to prevent this draft?
I'm thinking cover the drain hole (the one on the picture) with something, but could it not cause more problems?
UPD: Pipes under kitchen sink look like this:

Thin pipe on the first photo on the left is a waste from dishwasher.
Answer: You don't have a trap seal, to prevent air from moving through the drain.

Only the dishwasher is draining through the trap, so there's no trap to prevent air from coming up the drain. you'll have to fix the plumbing, so that both the sink and dishwasher use the trap.
Instead, the plumbing should look more like this...

Use a tailpiece like this, off the bottom of the sink.

This allows you to connect the dishwasher to the drain. You can trim the end of the tailpiece, so that it fits into the space you have.
Connect one side of the trap to the end of the new tailpiece, and the other end to the drain pipe.
You'll also have to add a vent to the system. Depending on where you live, air admittance valves (AAV) can be used.

After looking more at the plumbing, you might not need additional fittings (other than for venting).

Remove the sanitary tee connection from the drain.
Connect the dishwasher outlet to the sanitary tee, where it used to connect to the drain.
Connect the end of the trap (where the dishwasher used to connect), to the drain.

Basically, just swap these connections.
Comment: The back feeding risk into the dishwasher is that a clog in the drain will backup into the dishwasher instead of into the sink. You wouldn't even know there's a clog until you open your dishwasher and find it full of your sink waste. When you affix the dishwasher drain to the underside of the countertop, the sink has to nearly overflow before anything can drain back into the dishwasher.
Comment: A vent is **not** needed, as the pipe exits into a outside drain with a air gap.   Even if the pipe was sealed into the underground pipes, a vent is often not needed provided the underground pipes are vented correct by he soil stack.   (lots of examples in the UK building regs).
Comment: You are a scholar! Indeed I can get away with just swapping these 2 pieces. I think the dishwasher was installed as an afterthought to the plumbing and by somebody not knowing what they are doing. I found a lot of small issues like that left by the previous owner.
Comment: Tester pretty much nails it. You also want that dishwasher drain line affixed to the underside of the counter top in at least one point to minimize the risk of water feeding back. And that's effectively an S trap, not good but fixable. Changing the 90 elbow in the back to a tee with an AAV as close to the countertop as you can get it would be the fast solution.
Comment: @BMitch good suggestion about fixing the dishwasher drain to the top - it is very heavy and pulls the current installation down. See how twisted the bottom U sits comparing to the vertical pipe - it used to be vertical, but been pulled down.
Comment: Thanks @Walker. I'm not familiar with UK plumbing, so it's good to know that the vent is not needed in this situation.  The OP should just be able to swap the connections, and be all set then.
Comment: Yes, indeed. Once I've started looking on this in detail, I realised that. Plumbing needs changed there -(
Comment: @trailmax you'll still have to add a vent, or you'll have gurgling and/or slow drains.
Comment: I would strongly recommend you use two traps, one for the drain and one for the dishwasher. Otherwise you get dishwasher gurgles coming out the plug hole.
Comment: @trailmax Walker says you don't need a vent, so just swap the connections and enjoy.
Comment: @Walker thanks for confirming this. B&Q staff yesterday were puzzled when I asked about AAV. And there is no space for a proper vent anyway.
Comment: @Tester101 Yes, I have tried swapping the connectors yesterday but could not because they are different width and there is not enough space to connect J pipe into the outlet. I'll need to shorten elbow on the outlet, possibly redo the whole connector there.
Comment: AAV are needed on very long pipe runs and when installing a WC unless the WC connects to a ventilated soil stack.   But an "Anti - Siphon Trap" includes a AAV, therefore it is very uncommon to use a AAV for a sink.
Answer: You could put a cover over the drain box but when you do so it has to allow for free air flow so the isolation afforded by that air gap drain box still functions properly. If I was making the cover it would have a baffle design with a double wall construction. See figure below:

The inner wall of the baffle cover would sit on the ground or maybe even set below grade. The outer shell would not come all the way down. The picture is somewhat conceptual and does not attempt to show how the two parts of the cover fasten together.
Before committing to an elaborate construction project you could prototype the design to determine how effective the concept is. This could be done using heavy corrugated cardboard carton material. You easily cut the cardboard with a sharp utility knife and a straight edge. The pieces can then be joined together with hot melt glue. (Hot melt glue sticks to the brown corrugated cardboard amazingly well). Hold your prototype in place using some bricks to keep the howling wind from blowing it away.
Comment: That's pretty awesome drawing! And cardboard prototype is also a great suggestion. What material would you use to make the non-prototype?
Comment: You could use various materials I suppose. Wood would unquestionably be the easiest to work with if you have the tools for that. But sheet metal may be feasible. The most weather resistant may be to use a wood frame that uses flat fiberglass sheeting for the top and sides. (I speak of the type of fiberglass material that is often used in a roof to allow light to come through. It could be glued to the wood frame using construction adhesive.
Answer: While I agree that this was assembled backwards I think the apparent lack of a vent is acceptable here.  It looks like it basically goes through the wall and then into that box outside--so long as it's close enough to the sink that would suffice for venting.
Comment: That's correct - drain pipe goes through the wall and outside. And there is not much space for the vent anyway. Also I checked local DIY store (B&Q in UK) and plumbers there had no idea about vents (does not mean anything though)
Answer: Most drains (in the US) vent thru a vertical pipe which prevents sewer gas from accumulating in the structure (home,apartment,etc)
Part of that system should include a trap (usually a J or S shaped piece of pipe which holds a small quantity of water which prevent air or gasses from passing back into the room from the sink or toilet. If that trap was not included air ("wind") might be noticed.
Check for presense or lack of a trap.
Comment: There is a S-shaped trap under the sink.
Comment: S traps are not permitted in a typical drain setup because they result in the water draining too fast and sucking water out of the trap (your local codes and gray water system may permit it). You want a J trap with a vent connected where the line goes vertical to avoid sucking water out of the trap.
Comment: Possibly it is J-trap, I'm not entirely sure about the difference - it was set up by builders when kitchen was refurbished.
Comment: A properly functioning trap should have water in the bottom of it after you use the sink. I think we'd need to know if your trap never works (never fills with water), gets sucked dry when you drain a lot of water quickly, or dries out due to wind pressure over the outside pipes.
Comment: @BMitch See update - added photos of how it looks under the sink. I think you might be right, the piping looks wrong. Also sometimes I get standing water on the bottom of dishwasher.
Comment: @trailmax the water from the kitchen sink is being siphoned into the dishwasher. You will either need to put in an air-gap, or create a high loop with the dishwasher drain to prevent the water from being backed up into the dishwasher.
Comment: @BMitch: In some older homes, I've seen a variety of what look like anti-siphon arrangements in drain traps that feed through the floor rather than out the back with a riser.  Were those ineffective, or why have I not seen such things as an alternative to P-traps in places where installing a riser would prove problematic?
Comment: @supercat The alternative to connecting to a vented stack is an an AAV. You replace the S trap with a P trap that connects to a tee. Bottom of the tee goes to the drain in the floor, top of the tee goes as high as possible (underside of the countertop) and has an AAV placed on top. This permits the air to enter behind the draining water so the trap isn't sucked dry, while closing in the other direction to block sewer gases.
Comment: @BMitch: The anti-siphon arrangements I've seen in older homes were located entirely under the sinks and appeared to use their geometry to ensure that water's momentum wouldn't be able to carry it completely out.  While a short riser and AAV might be workable when doing renovations in a place which cannot accommodate a rear-mounted vent, I'm curious whether the older anti-siphon systems were unsatisfactory or why I've not seen them used as an entirely-under-sink alternative to an AAV?
Answer: All you need is a trap on both paths like the one you have coming from the dishwasher/washing machine
The trap fills with water and stops draughts although in excessively windy conditions its still possible for very strong winds to force their way through a water trap but normally there wont be enough pressure
I wouldn't personally suggest swapping the fittings over personally as theyre pretty cheap, so I would say its better to get a second trap or I bend and fit it between the sink and the outside pipe
removing it from the other pipe will make it more likely that food waste that goes down the plug hole could end up in the draining pipe from the appliance and risk causing a blockage if there isn't a filter, and even if there is a filter it could could clog the filter up
Answer: An easy test would be to cut a panel out of some junk styrofoam, that would go under the black grate, and block up but not tightly seal, the tub that the white pipes drop into. It's free and easy to work with, and if such a block cuts down on the wind problem, you can then make something more permanent and better looking.
Comment: Sounds like this is the sink drain, so it's actively used.
Comment: I mean around the pipes, not underneath (and thereby blocking the outflow).
Comment: Ah. You might also consider wind blowing up the external drain pipe; there's no info on where it actually goes.
Comment: Cutting a flat panel out of junk styrofoam that would sit where the black grate sits now, roughly around the pipes, but not tightly enough to seal would block wind from the entire system. Put a rock on it to keep wind from flipping it out, and see what effect it has.
Comment: It's unlikely, but I was wondering if wind could come up the lower drain pipe itself (e.g. if it ends pouring off some cliff somewhere). Absent that, good idea, although you might want to make the answer clearer on exactly what you're blocking.

Wind from kitchen sink drainage pipe


App crash after '

Question: My application is crashing when a ' appears  in the title of the JSON code i'm parsing.
This line is loading the title's:
[[cell textLabel] setText:[item objectForKey:@"title"]];

JSON:
 NSString *jsonString = [NSString
                            stringWithContentsOfURL:[NSURL URLWithString:@"**test.php"]
                            encoding:NSStringEncodingConversionAllowLossy
                            error:nil];
    // Create parser
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *results = [parser objectWithString:jsonString error:nil];
    parser = nil;
    // Set tableData
    [self setTableData:[results objectForKey:@"items"]];

Crash:
tableData   NSArray *   0x00000001

2012-04-10 10:29:11.446 *[21222:f803] -[NSNull isEqualToString:]:
  unrecognized selector sent to instance 0x146ace8 2012-04-10
  10:29:11.447 *[21222:f803] * Terminating app due to uncaught
  exception 'NSInvalidArgumentException', reason: '-[NSNull
  isEqualToString:]: unrecognized selector sent to instance 0x146ace8'
  * First throw call stack: (0x13d4022 0x1565cd6 0x13d5cbd 0x133aed0 0x133acb2 0x15e0ff 0x2b10 0xb8c54 0xb93ce 0xa4cbd 0xb36f1 0x5cd21
  0x13d5e42 0x1d8c679 0x1d96579 0x1d1b4f7 0x1d1d3f6 0x1db81ce 0x1db8003
  0x13a8936 0x13a83d7 0x130b790 0x130ad84 0x130ac9b 0x12bd7d8 0x12bd88a
  0x1e626 0x1ded 0x1d55) terminate called throwing an exception(lldb)
Answer: The key part of that crash info is: unrecognized selector sent to instance ... [NSNull isEqualToString:]
It looks like your JSON contains null somewhere that you are expecting a string. Later on, probably inside of setTableData: you will be doing something like this:
NSString* whatever = [items objectForKey:@"whatever"];
if([whatever isEqualToString:@"hello"]){
    ...
}

And that will crash, because the whatever variable contains NSNull, not an NSString like you were expecting.
Comment: O haha sorry! `{"title":null,"description":""}` need to search my glasses again! Thanks haha!

App crash after '


Extract integers from file and output to another file?

Question: I have the following file foo.txt:
1
AbcdJ
8192
Pak78
8291

I would like a bash script that extracts all the lines containing only integers (e.g. 1, 8192 but not AbcdJ or Pak78) and outputs it to bar.txt.
Answer: This extracts lines that contain only digits:
$ grep -E '^[[:digit:]]+$' foo.txt
1
8192
8291

This sends the output to bar.txt:
grep -E '^[[:digit:]]+$' foo.txt >bar.txt

How it works
When you want to select lines from a file, grep is first utility to try.
^[[:digit:]]+$ is a regular expression. In it, ^ matches the beginning of a line, [[:digit:]]+ matches one or more digits, and $ matches the end of a line.  Because this regex starts with ^ and ends with $, it only matches whole lines.  An alternative way of matching only whole lines is to use the -x option:
grep -xE '[[:digit:]]+' foo.txt >bar.txt

The option -E tells grep to use extended regular expressions.  This reduces the need to escape things in the regex.
The > signifies redirection.  It causes the output that would have appeared on the screen to go to a file named bar.txt.
Comment: You can also use the `-x` option to enforce a whole-line match (rather than using explicit `^` and `$` anchors) `grep -Ex '[[:digit:]]+'`
Comment: @steeldriver Good point.  Answer updated with reference to `-x`.
Answer: AWK solution:
$> cat input.txt
1
AbcdJ
8192
Pak78
8291
3 blind mice
$> awk '/^[[:digit:]]+$/' input.txt
1
8192
8291

Use > to redirect output to file
awk '/^[[:digit:]]+$/' input.txt > output.txt

Comment: `sed -n '1p;3p;5p'` will also print the integers from the `foo.txt` file given in the question, since they appear on the first, third, and fifth lines.  However, when a question says, "I have the following file," we generally interpret that to mean, "I have a file like the following..."  The question asks for a solution that extracts all the lines containing **only** integers.  Your answer will extract every line that ***begins with*** a digit; e.g., `3 blind mice`.   P.S. When the question specifies filenames, it's nice to use those same filenames in your answer.
Comment: @G-Man very valid point. The regex originally read as `starting with digit and followed by zero or more matches of next char`. I have corrected that to read `line starting and followed by one or more matches of a digit` , and included your example into the sample output.  As for file naming,  people may not be familiar with AWK syntax, hence i believe it is better to be explicit and state what is input file and what is output file.   It is nice to use same names, but  my goal is to make clear answer, not  pretty ones.
Answer: Some other tools:

sed:
$ sed -n '/^[0-9]\+$/ p' foo.txt
1
8192
8291

bash, slower than other approaches:
$ while IFS= read -r line; do [[ $line =~ ^[0-9]+$ ]] && echo "$line"; done <foo.txt
1
8192
8291

To save the output on another file, use output redirection, >:
sed -n '/^[0-9]\+$/ p' foo.txt >output.txt
while IFS= read -r line; do [[ $line =~ ^[0-9]+$ ]] && echo "$line"; done <foo.txt >output.txt


stylelint giving error on iOs - Error: Could not find "stylelint-config-standard". Do you need a `configBasedir`?

Question: It works ok on ubuntu
I installed stylelint on iOS but when I run it I get
Error: Could not find "stylelint-config-standard". Do you need a configBasedir?
My config file is:
$ cat .stylelintrc.json
{
  "extends": "stylelint-config-standard",
  "rules": {
    "rule-empty-line-before": null,
    "at-rule-empty-line-before": null
  }
}

I tried "extends": ["stylelint-config-standard"],
but it didn't help
Answer: I had that error message until I installed the config
npm install stylelint-config-standard --save-dev
Comment: For global usage, the configuration has to be installed with `npm i stylelint-config-standard --globalconfig --save-dev`.
Answer: If you have the stylelint-config-standard dependency installed already, maybe you need to delete the node_modules folder and package-lock.json or yarn.lock if you're using yarn, and run the following command:
npm install

or with yarn
yarn install

if the stylelint-config-standard dependency isn't installed may you need to install it running:
npm install stylelint-config-standard -D

or with yarn
yarn add stylelint-config-standard -D

Comment: Clarifying how to remove node_modules and package-lock.json and npm install:
rm -rf node_modules package-lock.json && npm install
Answer: The solution for me was adding the overrides section to the config:
module.exports = {
    overrides: [
        {
            files: ["**/*.scss"],
            customSyntax: "postcss-scss"
        }
    ],
    rules: {...},
}

Answer: First, as tried, change the extends to be
"extends": ["stylelint-config-standard"],

but then also do npm install
Comment: Didn't work for me


How to use Google Text to Speech (python) in Ubuntu 20.04?

Question: Here is the screenshot of the errors which I am getting. Please help me! I have also installed mpg321 in my Ubuntu 20.04. It is working fine if I play music from terminal. Here, I am playing a song from terminal. I've tried to play hello.mp3 also(from gtts output) from terminal. It's saying hello world when I run from terminal but when I try run in Pycharm it shows errors. Please help me!!
Answer: Try this,
<code>#pip install playsound
from playsound import playsound
playsound("fileName.mp3")
</code>
Hope this resolved your issue.


Can't simplify this summation

Question: Here's the question:
$\sum_{i=1}^{n} \frac{1}{i^2 + i}$
How do you express this summation in terms of n?
I'm at a loss of where to go with this. I know the formulas for the summation of $i^2$ and $i$, but I'm not sure where to use these (or if it's even relevant) because the only thing I can think of is to sum the denominators and then take their reciprocal, which is clearly wrong.
Answer: Hint: $\frac 1 {i^{2}+i}=\frac  1 i -\frac  1 {i+1}$.
[The answer is $1-\frac  1{n+1}$].
Comment: ...Did not think of that at all - thanks a lot!

Can't simplify this summation


How to disable oracle cache for performance tests

Question: I'm trying to test the utility of a new summary table for my data.
So I've created two procedures to fetch the data of a certain interval, each one using a different table source. So on my C# console application I just call one or another. The problem start when I want to repeat this several times to have a good pattern of response time.
I got something like this: 1199,84,81,81,81,81,82,80,80,81,81,80,81,91,80,80,81,80
Probably my Oracle 10g is making an inappropriate caching.
How I can solve this?
Answer: EDIT: See this thread on asktom, which describes how and why not to do this.
If you are in a test environment, you can put your tablespace offline and online again:
ALTER TABLESPACE <tablespace_name> OFFLINE;
ALTER TABLESPACE <tablespace_name> ONLINE;

Or you can try
ALTER SYSTEM FLUSH BUFFER_CACHE;

but again only on test environment.
When you test on your "real" system, the times you get after first call (those using cached data) might be more interesting, as you will have cached data. Call the procedure twice, and only consider the performance results you get in subsequent executions.
Comment: Hello @Peter Lang, my tables are at system tablespace, so I can't put offline. However I not understand why I should do this? Do you can explain or suggest a good lecture? Thanks.
Comment: flushing before the call I got some interesting results like: 1370,354,391,375,352,511,390,375,326,335,435,334,334,328,337,314,417,377,384,367,393.

I'll study more about it tomorrow and I'll say my results.

Thanks!
Answer:
Probably my Oracle 10g is making a
  inappropriate caching.

Actually it seems like Oracle is doing some entirely appropriate caching.  If these tables are going to be used a lot then you would hope to have them in cache most of the time.
edit
In a comment on Peter's response Luis said

flushing before the call I got some
  interesting results like:
  1370,354,391,375,352,511,390,375,326,335,435,334,334,328,337,314,417,377,384,367,393.

These findings are "interesting" because the flush means the calls take a bit longer than when the rows are in the DB cache but not as long as the first call.  This is almost certainly because the server has stored the physical records in its physical cache.  The only way to avoid that, to truely run against an empty cache is to reboot the server before every test.
Alternatively learn to tune queries properly.  Understanding how the database works is a good start.  And EXPLAIN PLAN is a better tuning aid than the wall-clock.  Find out more.
Comment: Ok, I understand the importance of caching on this situation, but in my case the tables won't be queered with the same interval many times. I just want to see the response time without cache, using my summary table or not.  However, thanks I appreciate. +1
Comment: I read your edit, this a problem. Do you have some suggestion of a better comparison solution between my procedure that use the normal table and the another that use the summary table?
Comment: I repeat the tests flushing the buffer_cache before call procedure and I got: 407,342,413,364,431,354,351,356,344,368,328,341,334,370,333,330,327,401,421,333 (The first result isn't the bigger). Have some function to see the state of physical cache or something?


Pseudo-element after not showing?

Question: I want to add a help logo at the end of some form fields which opens a tooltip.
Everything is working, but the .helptip icon (http://img1.wsimg.com/shared/img/1/small-help-icon.gif) is coming on the left(merged) with the text. I actually want in on the right of span text, so I did .help-tip:after. But then nothing shows up at all.
Can you spot what's wrong?

 Include Columns in Result Set

<select class="advancedSearchFormSelectBox" id="filters_include_columns" multiple="multiple" name="filters[include_columns][]">

<option value="x">X</option>
<option value="y">Y</option>
<option value="z">Z</option>
</select>

 Sort Column

<select class="advancedSearchFormSelectBox" id="filters_sort_columns" multiple="multiple" name="filters[sort_columns]">

<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>

.help-tip {
/* Merged text at the moment. .help-tip:after not working */
    cursor: pointer;
    width: 10px;
    height: 10px;
    background-repeat: no-repeat;
    background-image: url("/assets/small-help-icon.gif");
}

.advancedSearchFormSelectField{
    width:300px;
    margin: 5px;
    height: 60px;
    float:left;
}

Comment: Quick note to avoid others making the same stupid mistake I have: if the outer element has `overflow` set to `hidden`, the `:after` pseudo element won't show...
Comment: Where is your "after" class?
What browser do you use?
Comment: For me the problem was that after did not work on an image tag
Answer: You don't seem to be using a pseudo-element at the moment. Try this setting .help-tip to .help-tip::after and giving is content: "" and display: inline-block:
.help-tip::after {
    content: "";
    display: inline-block;
    cursor: pointer;
    width: 10px;
    height: 10px;
    background-repeat: no-repeat;
    background-image: url("/assets/small-help-icon.gif");
}

Comment: Hey, it's showing perfectly. I think it's cause of the display:inline-block. One problem though is $(".help-tip").live ('click',function()....., isn't working any longer when you click the gif. It's working when you click the text. What should I do?
Comment: UPDATE - Working in firefox but not in Chrome...WHY?
Comment: Difficult to say without seeing an example, all looks fine so it's probably some tiny thing.
Comment: To me, it worked only with `content: '';` and not with `content: "";`

Pseudo-element after not showing?


Sets $[a,b]$ not homeomorphic to $(a,b)$ on the real line with standard topology

Question: I've seen a proof to this statement using connectivity.
It goes something like this: if two sets have homeomorphism between them, connectivity of one implies the connectivity of the other. That's fine.
Now the proof says that since $[a,b]$  has $2$ points we can remove and it will still be connected (true) while $(a,b)$ has none (also true).
What I can't figure out is how that proves they aren't homeomorphic?
Comment: Not using connectivity: One set is compact. the other not
Comment: Points like you desdrive are called "cut points". Prove that a homeomorphism sends cut points to cut points.
Comment: Heine-Borel says a subset $S\subseteq \mathbb R$ is compact if and **only if** it is closed and bounded.
Comment: Suppose you have a set $X$ with a topology $\tau\subset{\cal P}(X)$. If $Y$ is another set and there is a bijection $X\to Y$, then there is an induced bijection $\tau\to\rho$ with $\rho\subset{\cal P}(Y)$. This is called transport of structure. Every homeomorphism of topological spaces arises in this way: they are *the same space*, just with the elements of the space labelled differently, and hence the elements of the open sets also relabelled accordingly. Since they are the same space, they should have the same topological properties, such as existence of a cut point.
Comment: @user251257 Can you prove your statement? I know closed and bounded sets are compact in Rn but how tt prove () aren't?
Answer: If a set $X$ is homeomorphic to $Y$ via a homeomorphism $f$ and we remove a point $x$ from $X$, then $X\setminus \{x\}$ is also homeomorphic to $Y\setminus \{f(x)\}$.
Therefore, if $[a,b]$ is homeomorphic to $(a,b)$, there must exist some point $y\in (a,b)$ such that $(a,b)\setminus \{y\}$ is homeomorphic to $[a,b]\setminus \{a\} = (a,b]$.
But obviously, such a point does not exist (because of the arguments above), so there is no homeomorphism.

This kind of reasoning is very common not only in topology, but in mathematics in general. In order to prove $X$ is not homeomorphic to $Y$, you need to find some property $X$ which translates through homeomorphisms (compactness, connectedness, $T_1$, $T_2,\dots$) and then prove that $X$ has the property and $Y$ does not.
Comment: One should note however that $y$ is not arbitrary. It should be $y=f(x)$ where $f\colon X\to Y$ is a homeomorphism.
Comment: @HagenvonEitzen Agreed. Fixed.


What is similar to VOIP push and call kit of iOS in android for calling

Question: In iOS we I have implemented call kit with VOIP push using push kit. So How can we achieve same in android ?
I don't have idea that android does support pushkit like functionality to send voip push
Any help or suggestion or docs would be great
Comment: Android don't have any pushkit feature. You can achieve this by using android services
Comment: @M.HamzaRajput Thanks for your response. How can we handle this when app is locked. Like are we able to show the app calling screen even when device is locked and app is in killed state
Comment: You can add firebase sdk in your dependences and create a push notification receiver in your android app. When you get a push notification in your app you can awake you application with UI flags.
Answer: This might help.
First you need to create a push notification receiver in your service. Here is service exemple. While your application is background or destroyed. You can receive push notification from receiver. Then you can start your activity as you want to start with windows flags.
If you have a query you can ask.


Input text and radio calculation by javascript

Question: I need help for calculate values by text and radio input field. Here is HTML code:

<input type="text" id="num" name="num" />

<input type="radio" name="yesno" value="yes"> Yes
<input type="radio" name="yesno" value="no"> No

<input type="text" id="result" name="result" />

Now I want to calculate value of by some of conditions:

IF radio button value no then input#result will show same value as input#num
IF radio button value yes then result will show value based on conditional cal culation:
a. IF input#num = 1-10 then input#result = input#num * 4
b. IF input#num = 11-20 then input#result = input#num * 3.5
c. IF input#num = 21-50 then input#result = input#num * 3
d. IF input#num = 51-100 then input#result = input#num * 2.5
e. IF input#num = 101-200 then input#result = input#num * 2
f. IF input#num = 200+ then input#result = input#num * 1.5

Please help me. I don't know javascript very much so I need your help. Thanks in advance for help.
Comment: I don't know javascript too much but I know PHP. That's I don't understand how to start. And I haven't tried yet.
Comment: apni ki bangladeshi ?? @HarunRRayhan
Comment: Yap bro I'm Bangladeshi @AnikIslamAbhi
Comment: @HarunRRayhan glad to see a bangladeshi :)
Comment: @AnikIslamAbhi apnar fb id deya jabe?
Comment: off course . https://goo.gl/PRaXuc
Answer: Try like this
$("input[type='radio']").on("click", function() {

    if ($(this).val() == 'yes') {
        var value = $("#num").val();
        var result = 0;
        if (value <= 10) {
            result = value * 4;
        } else if (value <= 20) {
            result = value * 3.5;
        }
        $("#result").val(result);
    } else {
        $("#result").val($("#num").val());
    }

})

Answer: $("input[name=yesno]").change(function () {
    if ($(this).val() == 'no') {
        $("#result").val($("#num").val())
    } else {
        var ten = $("#num").val();

        if (ten <= 10) {
            var total = parseFloat(ten) * 4;
            $("#result").val(total);
        } else if (ten <= 20 && ten >= 11) {
            var total = parseFloat(ten) * 3.5;
            $("#result").val(total);
        }
    }
})

fiddle
Answer: I guess it's the matter of not knowing how to access html elements via JS.

You can check which radio button is selected using $("[name=yesno]:checked").val(); return Yes/No
You can set value of html element using $("#result").val(someval)


Access existing/old kuberenetes cluster or via kubectl command from a new machine

Question: I have already made a cluster which is running in AWS cloud with 1 master and 5 nodes. Unfortunately the computer(mac book) that I launched the cluster broke down so now I dont know how to access that old cluster with my new computer(mac book) and new kubernetes/kubectl environment in it.
Comment: do you have a backup of your PC? Have you saved your keys and other relevant stuff?
Comment: I have a repo which has yaml files that create deployments, services, hpa, secrets, etc...
Answer: You should be able to ssh to the master (API server) through your AWS account credentials.
From the master, you can try a couple approaches -- see https://kubernetes.io/docs/admin/authentication/ for a list of authentication methods that can be used in your cluster. Most convenient would probably be to locate the --client-ca-file argument that is being passed to your kube-apiserver process, and use that certificate authority private key to generate a new client cert.
Once you have a new client cert you can regenerate your kubeconfig using this guide: https://lukemarsden.github.io/docs/user-guide/sharing-clusters/.
This is probably going to be a bit hairy! Good luck.


Remove Garbage Disposal romex or cap?

Question: My garbage disposal is busted and my wife wanted to be rid of it anyways.  It's hard-wired and, after some trial and error, I found it is on the same circuit as a GFCI above the sink.  (Not the same circuit as the dishwasher).
AFAIK I have two options here regarding the GD romex:
1) Use wire nuts, electrical tape, and a blank electrical box to cap the live wires.  Probably nail it into the kitchen cabinet.  That would allow a future homeowner to wire a new GD if they wanted.
2) Pull the GFCI outlet and see if the GD romex is just extending off the GFCI.  If so, remove and pull the romex completely out.
Advice?  I'm a relatively novice DIYer, I've capped a few blank boxes but I don't want to make my house's wiring even more funhouse than it is.
Comment: Do you have the ability to wire to a new outlet under the sink (if your local laws permit)? That way a new disposal (with a cord) could be later installed with no wiring at all.
Comment: Don't remove the wire.  Its going to be stapled inside the wall so you can't just pull it out.
Comment: @DragonYen  Maybe, but this is a 100-year-old house and the wiring is not great to start with.  And since I don't want a GD to begin with, not eager to put a ton of money into a new installed outlet
Answer: Your best and safest path forward would be to purchase an old work box and a blank cover. Instal the old work box in the wall with the wiring inside the box.
Nailing a box to the cabinet would violate code in many locations as the romex must be protected under the sink.
Old work boxes are inexpensive and made for jobs like this. With the wires safely capped inside the covered box is the least expensive way to do this and the circuit can be used in the future if needed.
Comment: An old work box is what I meant by a "blank box."  Question though, should I try to secure the box to the top of the undersink cabinet with a couple nails?  I would like to keep the box off the floor of the cabinet where water, cleaning chemicals, etc could get to it...  ETA: the romex right now is just coming through a small hole in the lathe&plaster, so I really can't stuff the old work box in it without removing some of the wall.
Comment: Having the romex exit the wall without conduit is a code violation. Making the hole large enough for the old work box to fit in the hole then tighten the wings so it will be secure. Old work boxes some times called remodel boxes usually have 2 wings that are inside the wall and support the box in place. Prior to putting the box in the wall the wires are fed through one of the openings to be contained in the box and the box put in the wall and the wings tightened. Then you could add the blank cover.

Remove Garbage Disposal romex or cap?


What are our options for carpeting the basement of a split-level house?

Question: The basement level of our house (1/2 below grade) is currently just vinyl tile on concrete slab.  It's cold during the winter, so we would like to carpet it.  We do not get water penetration through the floor, but during the humid days of summer, there is frequently condensation on the floor (especially under furniture) where the very humid air contacts the cool floor.
What are our options for carpeting?  Could we just lay down a carpet pad and carpet directly on the concrete / vinyl tile?  Is it necessary to put down a sub-floor?
We were originally going to just do the pad and carpet, but I'm concerned about moisture / mold issues.
Answer: From a comfort and water protection perspective, I think you'll find it beneficial to install a sub floor.  I'd recommend one which allows for ventilation beneath it such as these 2x2 panels you can buy at Home Depot/Lowes
Dricore
This will give you a nice, warm "softer" surface to put your carpet pad on, and help protect from any condensation issues with the cold floor beneath by allowing it a place to form, and then with the proper ventilation openings cut into the subfloor (standard floor vent in the carpet to allow airflow) it'll dry out on its own.
Comment: I'd also pair this with a good dehumidifier. If you live in a humid climate, a dehumidifier is pretty much a necessity for the basement.
Comment: This will come out SO much better than bare carpet on concrete.
Comment: @DA01 Thank you I MEANT to mention a dehumidifier and then completely forgot to!
Answer: This sounds like a job for floor tiles.  There are several brands, and two types.  One has plastic feet, the other main style has foam (a popular brand is Dricore R+).  The foam insulates more and is resistant to "clicking" if the floor is not level.  The plastic feet type probably does a better job drying.
On top of this subfloor, you put whatever you want.  A lightweight underlay and carpet that can breathe a bit, and you're good to go.


Custom raw html

Question: I use codecolorer wp plugin to show raw html codes. But my problem is that I can not customize the codes inside. For example, I would like to make some words in bold. Also, i can not colour the codes exactly as I would like (each code individually).
Do someone know how to customize choosen codes within the raw table or tell me another wp plugin which let us customize each codes?
I could do it by myself without any plugin, just to change ">" and "<" with html names but i have a code which includes both types <, > and " of codes:

<data:post.jumpText/> |

...

What Stackoverflow uses here for the raw html codes (codes between apostrophes) would be the best solution but I did not find on internet.
Answer: Ok, i got the answer ! It is a bit complicated but essential :

You must go to Visual text editor
Paste the code as it is
Change to HTML editor (Text editor)
The > and < are changed to > and < and the " is changed to &quot; automatically.
Beeing already in HTML editor (Text editor), we can add codes for customize, for example to make the line bold, we add the  codes normally :

Take care NOT to swith back to Visual editor or you can start everything from the beginning !

Custom raw html