Networking within the music community

Question: I know this question may not fit with the standards set by the moderators of this site but I ask anyway because I need help. Please don't suspend me for this.
I have been playing music for quite sometime and have gotten to the point where
I am sick of playing by myself in my room.
I live on Long Island and have no friends (really).
I have no friends who play music and have never really known anyone with my interests.
I want to know if anyone knows of any places or communities maybe on the internet or in NYC.
I know of places that host open mics and jam sessions but I am looking for fellow musicians to meet and connect with maybe start a band with.
I would like to play in a guitar duo or band. I play blues, rock, jazz really anything just to get experience.
I really want to start playing with other musicians so badly.
I guess my question is how in your opinion can I go about finding musicians to network with and start a project with a band or duo with.
Should I go to more jam sessions?
Are there websites for networking musically?
I have posted an ad on craig's list but only got one reply.
What should I do to make musician friends and partners?
What should I do to find musicians I can play seriously with you know like be involved in a project a band or jazz guitar duo or something?
Thanks.
Comment: I think this is a dupe. Will have a look once I get back to a computer.
Comment: The standards are set by the community, not just the mods. The moderators are human exception handlers.
Comment: @DrMayhem http://music.stackexchange.com/q/7276/1678?
Answer: When you go to jam sessions, talk to others and ask if they'd be interested in playing with you.  Post more than once on craigslist.  Search Meetup for music and/or guitar meetups in your area.
Following are some NYC-area specific organizations that offer the opportunity for musicians to get together in more or less structured environments.   They do cost some $, but they give you a chance to meet other developing musicians and play in ensembles, often with a teacher/leader.
For Jazz

New York Jazz Academy (they have workshops on Long Island and in Queens)
New York Jazz Workshop
SOJ Jazz Center at the Collective
Lucy Moses School   (Search under Music->Jazz)

All the above offer workshops and ensembles - the first two especially have different ensembles you can try to get into.
(Also, if you think you're really good, many jazz clubs in the city have jam sessions, often late at night. The level tends to be quite high though.)
For Rock

The Jam NYC (Jam sessions and networking - chance to form your own band)
The Studio (Structured workshops and jam sessions, and probably the chance to network as well)

Networking within the music community


NTBackup Commands

Question: I am pretty unfamiliar with doing NTbackup via command line but I have a user who had someone setup his computer to backup to a 1TB external drive.
The backup command looks like this:
<code>C:\WINDOWS\system32\ntbackup.exe backup "@C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Windows NT\NTBackup\data\User Backup.bks" ^
  /a /d "Set created 1/7/2011 at 12:12 PM" /v:no /r:no /rs:no /hc:off /m normal ^
  /j "User Backup" /l:s /f "I:\UserComputerBackup\UserBackup.bkf"
</code>
This user has used all the space on his 1TB Drive.  My question is - is there a way to specify NTBackup to to only keep the last 3 or 4 backups and overwrite anything older?
I know this is available in some software backup solutions - but this was done using ntbackup originally and I'd like to continue to do that.
Any ideas?
Answer:
My question is - is there a way to specify NTBackup to to only keep the last 3 or 4 backups and overwrite anything older?

No sorry, ntbackup is a very light weight backup.  It doesn't have keep track of versions or anything, so there is nothing in NTbackup that allows this.  If you want to continue using NTBackup you will have to address its limitations using external scripts/tools.
I wrote a little python script which I used until we upgraded to Windows 2008 to schedule/manage ntbackup. You define your backup details in an xml file and the python tool will run the ntbackup with the correct option.  You set the number of versions you want to keep and so on.
Comment: How about deleting old sets?  Ultimately if I could just delete old sets I would be content as I could delete all the out-dated backups and he would be set going forward.
Comment: Oh, wow.  Sorry didn't look closely at your ntbackup command line.  As far as I know there is no way to remove a set from a bkf file.  You should be creating a different bkf file each backup period.
Comment: alright, that's originally what I thought also.  Kind of got thrown into this mess.  Is the /a tag what is causing it to all get appended to 1 giant file?
Comment: Correct `/a` puts it in append mode.  Here is a list of the command line options.  http://support.microsoft.com/kb/814583
Comment: Thanks Zoredache.  Thanks for the script as well.  I will look into using that in the future I think - looks really helpful.  This pretty much covers everything I thought was going on.  I have this one large backup file that contains a number of different sets... a mess.  I'm thinking a software solution may be in order in the future for this person.
Answer: I had to write a script to accomplish what you are asking to do.  Basically mine is set to backup the system images of some VMs.  These backup to a folder using the current date.  SO they end up in say x:\backup\2012-03-26.  Since the X: is on our NAS, I check the drive once a day to see if there is at least 1TB of storage and simply delete the oldest day one at a time until there is 1TB of storage left (our nightly is about 900GB).  I used VBS to accomplish this.  basically the VBS is running from in the task scheduler on each VM.  The script runs on each machine indepedantly.  But since they all use the date as the common folder name, the files all end up in their own respective folders:
x:\backup\2012-03-26\VSRV06
x:\backup\2012-03-26\VADS01
x:\backup\2012-03-26\VSQL01
....etc.

NTBackup Commands


How can I make a font awesome icon appear behind other text, as to emulate a background image?

Question: I want the icon to appear centered horizontally and vertically behind the text.
I have tried numerous combinations of position:absoulute, position:relative, z-index, display:flex, but have not been able to acheive the wanted effect.

        Header

        Text text text text, etc.

Answer: You will have to give the parent container a position:relative for the children's position:absolute to work. Then wrap your icon in a different span to your text and make the positions absolute.
Eg; https://jsfiddle.net/L9cb8wao/
My fiddle is extremely rough, so apologies about that, however there should be enough there for you to fix your code accordingly to achieve what you're after.
Comment: I had to adjust the vertical position of the icon, because it was rendered at 50% (middle) from the top of the icon. When the icon is really big (`fa-x9`), that is important.
Comment: Yeah you would have had to make some minor tweaks and adjustments (as I said, it was a rough fiddle) but I'm glad it gave you what you needed to achieve your goal!


Continuous bijection to Hausdorff is homeomorphism $\Rightarrow$ compact

Question: There is a famous theorem that for a compact topological space $X$, continuous bijection $f:X\to Y $ where $Y$ is Hausdorff is homeomorphic.
I want to know if the converse is true, i.e.
Let topological sapce $X$ satisfy the following property:

For any continuous bijection $f:X\to Y $ where $Y$ is Hausdorff is homeomorphic.

Then,  can we say $X$ is compact?
For example, if $X=(0,1]$ then let $Y$ be a circle and continuous bojection $f:X\to Y$ be connecting $1\in X$ to $0\notin X$, so we fail to construct counterexample.
If $X=(0,1)$ then connect $0\notin X$ to $\frac{1}{2}\in X$.
Comment: +1 upvote for your curiosity.. I had a prof once who always said a good mathematician is a stubborn mathematician as in one who only believes something if they can prove it or understand a proof of it..
Comment: You mean the convers.. ? Not inverse, inverse of if P then Q is if NOT P, then NOT Q.. youre asking if youre given a conitnuous bijection with range space Hausdorff, is it always the case that the domain is compact?
Comment: I wanna say let $X=\Bbb{R}^+$ and $Y=\Bbb{R}$ and take $f(x):=\ln (x)$.. this may be a counter-example? It is clear to see $\Bbb{R}^+$ is *not* compact..unless I'm missing something here, since my $f$ is 1-1, onto, continuous, the reals are Hausdorff and the positive reals aren't compact.
Comment: Sorry for my bad English, and thank you for your edit.
 I used the "converse" in the sense as follow. property P :$X$ is compact. property Q : for all Hausdorff $Y$ and cont bije $f:X\to Y$, $f$ is homeo.
Answer: If $f:X\to Y$ is continuous then we have a new topology on $X$ generated by subsets of the form $f^{-1}(U)$ over open subsets $U\subseteq Y$. This topology is coarser than that of $X$, and $f$ (seen as a map onto its image) is a quotient map under this topology.
So if $f$ is bijective and a quotient map than it is a homeomorphism. Under the new topology of course. So your question can be restated as:

Given a minimal Hausdorff space, is it compact?

Here "minimal" means coarsest among Hausdorff topologies. Note that a compact Hausdorff space indeed is minimal.
The answer to that question is "no". In other words there is a non-compact Hausdorff space $X$ such that every continuous bijection starting at $X$ onto a Hausdorff space is a homeomorphism. A concrete example can be found in the famous Counterexamples in Topology book, part II, counterexample 100. Also see this: https://mathoverflow.net/questions/36085/minimal-hausdorff
Comment: Do you assume  existence of some continuous bijection $f:X\to Y$ ?
Comment: @Yos there might not exist a bijection (continuous or not) at all between two spaces. What you mean?
Comment: Sorry. I misunderstood a little. However, I have solved the problem and understand your answer. Thank you.


Why is my null check for struct array still prints even it is null for C code?

Question: <code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <conio.h>
#include <windows.h>

int TotalCI = 0;
int count = 0;
struct depend{
    char dependency[200];
};

struct intdepend{
    char interdependency[200];
};

struct infradep{
    char name[200];
    int depcount;
    struct depend Dep[20];
    int intdepcount;
    struct intdepend IntDep[20];
};

struct infradep ci[50];

void menuModel(){

    int menu4;
    system("cls");
    printf("=========================================\n");
    printf("\tDependency Model\n");
    printf("=========================================\n");
    count = 0;
    for (int j=0; j < TotalCI; j++)
    {
        count++;
//      printf("%d)",count);
//      printf("%s\n",ci[j].name);

        for(int k=0; k <= ci[j].depcount; k++)
        {
            if(ci[j].Dep[k].dependency != 0)
            {
                printf(" %s ---> %s\n", ci[j].name, ci[j].Dep[k].dependency);
            }
        }

        for(int m=0; m <= ci[j].intdepcount; m++)
        {
            if(ci[j].IntDep[m].interdependency != 0)
            {
                printf(" %s <---> %s\n", ci[j].name, ci[j].IntDep[m].interdependency);
            }
        }
    }
}
</code>
Im trying to print out the non null value from my struc Dep[20] and struct IntDep[20]. The IF statement works but, it displays like this:
<code>=========================================
        Dependency Model
=========================================
 Drinking Water ---> Food
 Drinking Water ---> Transport
 Drinking Water --->
 Drinking Water <---> Food
 Drinking Water <--->
 Waste Water ---> Chemical
 Waste Water ---> Manufacture
 Waste Water --->
 Waste Water <--->
</code>
The code print extra line with null struct value, making it look weird. Can anyone teach me or help me how to fix this?
Comment: `for(int k=0; k <= ci[j].depcount; k++)` You may want `<` instead of `<=` here.
Comment: `dependency` is a string, not a pointer. It can never be null.
Comment: How do you know that your `if` statement works?
Comment: @JohnnyMopp Thanks man, that works. Its displaying properly now.
Answer: An array can never be equal to 0. If you want to test if the string is empty, check the first character.
<code>            if(ci[j].Dep[k].dependency[0] != '\0')
</code>


For all $m\ge 2$, the last digit of $ 2^{2^m} $ is 6

Question: How to prove that for  $ \forall m\in \Bbb N $ such that $m\ge 2$, the last digit of $  2^{2^m} $ is 6?
Comment: List powers of two starting from the lowest. See a pattern in the last digits? Does that not suggest an approach?
Comment: 23 minute spacing between posting two homework problems? You are giving up awfully quick on them!
Answer: $$2^{(2^m)}=(2^4)^{(2^{m-2})}=(16)^{(2^{m-2})}\equiv6^{(2^{m-2})}\pmod{10}$$
Now, $6^{n+1}-6=6(6^n-1)\equiv0\pmod {10}$ as $6^n-1$ is divisible by $(6-1)=5$ if integer $n\ge 0$
$\implies 6^r\equiv6\pmod{10}$ if $r\ge1$
So we need  $2^{m-2}\ge1\implies m-2\ge 0\implies m\ge2$
Answer: Hint: The last digit of a number is determined by what it is modulo 10. Also, use induction.
Comment: we have by use induction$ 4(2^k)\equiv ?$
Comment: Yes, if we assume that the claim is true when $n=k$, i.e. that $2^{2^k}\equiv 6\bmod 10$ for a given $k\geq 2$, we then want to show that the claim is true for $n=k+1$, i.e. $$2^{2^{k+1}}=2^{2^k\cdot 2}=4\cdot 2^k\equiv 6 \bmod 10.$$ Do you see how to prove this using the inductive hypothesis?
Comment: @agustin: Is $2^{2^{k+1}}=(2^{2^k})^2\equiv 6^2\mod10\ldots$
Comment: @ZevChonoles $2^{2^{k+1}}=4^{2^k}$ not $4.2^k$. subsequent step is using the inductive hypothesis and $2^k.2^k \equiv 6.6 \equiv 6 mod 10 $
Answer: Use Fermat's little theorem to show that $2^{2^m} \equiv 1 [5]$ and deduce from Chinese remainder theorem that $2^{2^m} \equiv 6[10]$.


mysql huge table query optimization group by

Question: I have huge table with about 40 million rows (GPS tracker positions), recorded every 10 seconds from multiple devices inside company. I want to select only the first row of every minute, so I used group by. The problem is that the table is growing up every 10 seconds, I've tried almost everything, googled many hours. So I decided to ask a question.
I'm using MySQL 5.7.11 InnoDB pool 50GB, server is Xeon X5650 with 64GB RAM.
table structure:
CREATE TABLE `eventData` (
  `id` bigint(20) NOT NULL,
  `position` point NOT NULL,
  `speed` decimal(6,2) DEFAULT NULL,
  `time` datetime DEFAULT NULL,
  `device_id` int(9) DEFAULT NULL,
  `processed` tinyint(1) NOT NULL DEFAULT '0',
  `time_m` datetime GENERATED ALWAYS AS ((`time` - interval second(`time`) second)) VIRTUAL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci ROW_FORMAT=DYNAMIC;

ALTER TABLE `eventData`
  ADD PRIMARY KEY (`id`),
  ADD KEY `time` (`time`),
  ADD KEY `device_id` (`device_id`,`processed`),
  ADD KEY `time_m` (`time_m`);

SQL:
SELECT e.time, e.time_m, X(e.position) AS lat, Y(e.position) AS lng
FROM eventData AS e
WHERE
  e.device_id = 86 AND
  e.time BETWEEN '2016-02-29' AND '2016-03-06'
  GROUP BY DAY(e.time),HOUR(e.time),MINUTE(e.time);

Explain:
EXPLAIN SELECT e.time, e.time_m, X(e.position) AS lat, Y(e.position) AS lng FROM eventData AS e WHERE   e.device_id = 86 AND   e.time BETWEEN '2016-02-29' AND '2016-03-06'   GROUP BY DAY(e.time),HOUR(e.time),MINUTE(e.time);
+----+-------------+-------+------------+------+----------------+-----------+---------+-------+---------+----------+---------------------------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys  | key       | key_len | ref   | rows    | filtered | Extra                                                               |
+----+-------------+-------+------------+------+----------------+-----------+---------+-------+---------+----------+---------------------------------------------------------------------+
|  1 | SIMPLE      | e     | NULL       | ref  | time,device_id | device_id | 5       | const | 2122632 |     6.40 | Using index condition; Using where; Using temporary; Using filesort |
+----+-------------+-------+------------+------+----------------+-----------+---------+-------+---------+----------+---------------------------------------------------------------------+

describe:
DESCRIBE eventData;
+------------------+------------------------+------+-----+---------+-------------------+
| Field            | Type                   | Null | Key | Default | Extra             |
+------------------+------------------------+------+-----+---------+-------------------+
| id               | bigint(20)             | NO   | PRI | NULL    | auto_increment    |
| position         | point                  | NO   |     | NULL    |                   |
| speed            | decimal(6,2)           | YES  |     | NULL    |                   |
| time             | datetime               | YES  | MUL | NULL    |                   |
| device_id        | int(9)                 | YES  | MUL | NULL    |                   |
| processed        | tinyint(1)             | NO   |     | 0       |                   |
| time_m           | datetime               | YES  | MUL | NULL    | VIRTUAL GENERATED |
+------------------+------------------------+------+-----+---------+-------------------+

I've tried:

without group by: ~0.06s
group by day,hour,minute: ~4.76s
group by virtual column (time_m): ~4.92s
group by e.time DIV 500: ~5.02s

I need to achieve better results than 5 seconds. Please help.
Comment: Performance questions should include `EXPLAIN ANALYZE` and some information about table size, index, current time performance, desire time, etc. `Slow` is a relative term and we need a real value to compare.

[MySQL](http://dba.stackexchange.com/questions/15371/how-do-i-get-the-execution-plan-for-a-view)
Comment: Hello, I've included explain and describe table, analyze table command says OK. Thanks.
Answer: You could partition the table. For example by year. This would dramatically increase the performance due to much smaller indexes.
If this is not possible on your environment, try
GROUP BY date_format(e.time,'%d%H%i');
Answer: 1) You can try composite index (device_id, time)
2) Try to group by virtual field:
SELECT MIN(e.time), e.time_m, X(e.position) AS lat, Y(e.position) AS lng
FROM eventData AS e
WHERE
  e.device_id = 86 AND
  e.time BETWEEN '2016-02-29' AND '2016-03-06'
  GROUP BY e.time_m;


Where is $|xy|$ function differentiable

Question: I'm trying to solve this problem:
Let $f(x,y) = |xy|$. Find the sets of all points $(x,y) \in \Bbb R$  where $f$ is differentiable and compute the differential in those points.
Can someone explain me how to show differentiability?
Thanks!
Comment: (and $g(x) = |x|$ is not differentiable at $x=0$, but it is weak-differentiable, since $g(x) = \int_0^x sign(t) dt$)
Comment: Should be $(x,y) \in \mathbb R^2$
Answer: The absolute value function $\lvert . \rvert$ is not differentiable at $0$, because the limit of the difference quotient from the left is $-1$ and from the right $1$. A similiar behaviour will show up in your function $f$ for points $(x,y)$ with $xy = 0$.

(Large version left, large version right)
The left image shows $g(x,y) = xy$ (green hyperbolic surface), the right image shows $f(x,y) = \lvert xy \rvert$ (red surface). The negative valued parts got "folded" upwards by the absolute value function.
If you align tangential planes to the red surface you see that you have two choices for the points $xy = 0$ except for the origin.
E.g. if we keep $x$ constant we have
$$
f(x,y) = \lvert x y \rvert = \lvert x \rvert \, \lvert y \rvert = c(x) \lvert y \rvert
$$
so the $V$ shapes turn less and less steep for $x \to 0$ and two choices turn into one along $x=0$.
Comment: "A similar behaviour ... _except possibly_ (and actually) _at the origin_." :)
Comment: But how do you show it mathematically?
Answer: It's very easy. It is differentiable on the 4 open quarters of the plane, that is on
1) $]-\infty,0[ \times ]-\infty,0[$
2) $]-\infty,0[ \times ]0,\infty[$
3) $]0,\infty[ \times ]-\infty,0[ $
4) $]0,\infty[ \times ]0,\infty[$
Indeed, on these 4 open domains, $f$ coincides with a polynomial function ($(x,y)  \mapsto xy$ and $(x,y)  \mapsto -xy$ are indeed polynomial), so $f$ is differentiable.
Assume that we are on the domain number $1$ or the domain number $4$. On these domains, we have $f(x,y) = xy$, so can compute the differential of $f$ by writing:
$$f(x+h,y+k) = (x+h)(y+k) = xy + kx + hy + hk = f(x,y) + kx + hy + o(h,k) $$
The application $(h,k) \mapsto kx + hy$ is a linear application, so the development above proves that it is the differential of $f$. Therefore $df(x,y)\cdot(h,k) = kx + hy $.
On the domains $2$ and $3$, we have $f(x,y) = -xy$, so we find $df(x,y)\cdot(h,k) = -(kx + hy) $
It's more tricky when you get on the x-axis or the y-axis. Here, the idea is to prove that $f$ is not differentiable by proving that it is not differentiable over one direction.
For example, let's say $(x,y)$ is on the right half of the $x$-axis, i.e at the point (x,0) with $x>0$. We have $f(x,y)=f(x,0) = 0$ (obvious), and now, if we compute the derivative over the $y$-axis:
we compute $\frac{f(x,y)-f(x,0}{y} = x \frac{\vert y \vert}{y}$, which is equal to $x$ if $y > 0$, and to $-x$ if $y<0$. So this quantity does not have a limit when $y \rightarrow 0$. Therefore $f$ is not differentiable in the direction $(0,1)$ at this point, so $f$ is not differentiable at the point $(x,0)$.
Same reasoning holds for the 3 other "half-axis".
Comment: but how you show that it is differentiable at (0,0)
Comment: at $(0,0)$, you have $f(h,k)= \vert hk \vert = 0 + o(h,k)$ so it is differentiable with a differential equal to 0.
Answer: By Young's inequality,
$$
2 |xy| \leq x^2+y^2
$$
Therefore
$$
\frac{|xy|}{\sqrt{x^2+y^2}} \leq \frac{1}{2} \sqrt{x^2+y^2}
$$
and hence $Df(0,0)=0$.
Comment: Thanks for the answer, but I've seen this in class too, but I can't connect this approach to showing that the function is differentiable. I mean why can I say this by what you've written?
I've seen that in order to show differentiability I've to use:

$\lim_{x \rightarrow x_0}\frac{|f(x) - f(x_0) - A(x-x_0)|}{|x-x_0|}$
Comment: @Ergo I proved that $$\lim_{(x,y) \to (0,0)} \frac{f(x,y)-f(0,0)}{\|(x,y)\|} =0,$$ so that $A=Df(0,0)=0$ by definition.
Answer: If $x_0y_0\ne 0$ then $f(x,y)=|xy|=xy\vee |xy|=-xy$ in some neibourhood of the point of  $(x_0;y_0)$ and so the function is differenciable at $(x_0;y_0)$.
If $x_0y_0= 0$, say $x_0=0$ and $y_0\ne 0$, then does not exist $\frac{\partial f(x_0,y_0)}{\partial x}$ because does not exist derivative of $|x|$ at $0.$
If $x_0=y_0=0$ then $\frac{\partial f(x_0,y_0)}{\partial x}=\frac{\partial f(x_0,y_0)}{\partial y}=0$ and we must verify that $|xy|=o(\sqrt{x^2+y^2})$ under the definition of differentiability at $(0;0).$  This is true because $2|xy|\le x^2+y^2  $.

Where is $|xy|$ function differentiable


Better way to solve integral

Question: I have the following integral
$$\int_{0}^{\pi / 2} \mathrm{d} x \,\, \frac{\cos^{3}(x/2) - \cos^{4} (x)}{\sin^{2} (x)}$$
My current solution is to use
$$v = \tan \left(\frac{x}{4}\right)$$
to obtain a rational function of $v$, and integrate this.
Is there a more practical / clever way of doing it?
Comment: Where did you see this integral?
Comment: Comes up in my work. I like the Weierstrass trick as it is a blanket method, but am looking for a better way to approach it
Answer: While the substitution $v=\tan(x/4)$ would work, I don't think it's a good method in this case, which just requires elementary antiderivatives.
First, split the fraction and notice that
$$
\int\frac{\cos^4x}{\sin^2x}\,dx=\int\left(\frac{1}{\sin^2x}-2+\sin^2x\right)\,dx
=-\cot x-2x+\frac{1}{2}(x-\sin x\cos x)
$$
This leaves the other piece:
$$
\int\frac{\cos^3(x/2)}{\sin^2x}\,dx=[t=x/2]=2\int\frac{\cos^3t}{\sin^22t}\,dt
=\frac{1}{2}\int\frac{\cos t}{\sin^2t}\,dt=-\frac{1}{2\sin t}
$$
Thus the integral is
$$
-\frac{1}{2\sin(x/2)}+\cot x+2x-\frac{1}{2}(x-\sin x\cos x)
$$
You can also note that
$$
\cot x-\frac{1}{2\sin(x/2)}=\frac{\cos x}{2\sin(x/2)\cos(x/2)}-\frac{1}{2\sin(x/2)}=
\frac{(\cos(x/2)-1)(2\cos(x/2)+1)}{2\sin(x/2)}
$$
which has limit $0$ for $x\to0$.
Answer: $$\frac{\cos^3\dfrac x2}{\sin^2x}=\frac{\cos\dfrac x2}{2\sin^2\dfrac x2}$$ is immediately integrable.
And in
$$\frac{\cos^4x}{\sin^2x}=\frac1{\sin^2x}-2+\sin^2x,$$ the first two terms are also immediate, and
$$\sin^2x=\frac{1-\cos2x}2.$$
Answer: $$J=\int\frac{\cos^3(\frac x2)-\cos^4x}{\sin^2x}\mathrm{d}x$$
$$J=\int\frac{\cos^3(\frac x2)}{\sin^2x}\mathrm{d}x-\int\frac{\cos^4x}{\sin^2x}\mathrm{d}x$$
$$I=J\bigg|_0^{\pi/2}$$

$$I_1=\int\frac{\cos^3(\frac x2)}{\sin^2x}\mathrm{d}x$$
$u=x/2$:
$$I_1=2\int\frac{\cos^3u}{\sin^22u}\mathrm{d}u$$
$$I_1=2\int\frac{\cos^3u}{4\sin^2u\cos^2u}\mathrm{d}u$$
$$I_1=\frac12\int\frac{\cos u}{\sin^2u}\mathrm{d}u$$
$t=\sin u$:
$$I_1=\frac12\int\frac{\mathrm{d}t}{t^2}$$
$$I_1=-\frac1{2t}$$
$$I_1=-\frac1{2\sin(x/2)}$$

$$I_2=\int\frac{\cos^4x}{\sin^2x}\mathrm{d}x$$
$$I_2=\int\frac{\cos^2x(1-\sin^2x)}{\sin^2x}\mathrm{d}x$$
$$I_2=\int\cot^2x\ \mathrm{d}x-\int\cos^2x\ \mathrm{d}x$$
$$I_2=-\bigg(\cot x+\frac12\cos x\,\sin x+\frac32x\bigg)$$

$$I=\bigg(-\frac12\csc(x/2)+\cot x+\frac12\cos x\sin x+\frac32x\bigg)\bigg|_0^{\pi/2}$$
$$I=\frac{3\pi-2\sqrt{2}}4$$

Better way to solve integral


Limitar Input de números Python 3

Question: Usando o seguinte código quero limitar de 0 a 2000 o número que poderá ser informado pela varável num
import collections
num = int(input('Digite um número inteiro: '))    #Inputar número inteiro
binario = bin(num)[2:]     #Cortar o 0b
sequence = binario
collection = collections.Counter(sequence)
print('O número binário de {} é {}'.format(num,binario))
print('A maior sequência de 0 é {}'.format(len(max(binario.split('1'),
key=len))))

Seria limitar o número a ser inputado na variável num.
Answer: Basta fazer uma condição:
if 0 <= num <= 2000:
    # Faça algo

Se quer solicitar ao usuário uma nova entrada enquanto o valor for inválido, precisará de um laço infinito:
while True:
    try:
        num = int(input())
        if not 0 <= num <= 2000:
            raise ValueError('Valor fora do intervalo permitido')
        break
    except ValueError as error:
        print(error)

Limitar Input de números Python 3


FATAL failed to allocate memory

Question: Boa tarde,
Estou utilizando a gem rb-libsvm:

https://rubygems.org/gems/rb-libsvm/versions/1.3.1

Com finalidade de gerar um modelo para classificação de tweets (positivo/negativo).
A partir de uma base de dados com 19000 tweets positivos e 19000 tweets negativos tentei criar o modelo com este código (que é uma adaptação do exemplo de uso que está no github):
require 'libsvm'

path = 'pos.txt'
documents = IO.readlines(path).map do |line|
  [1,line.tr("\n","")]
end

path2 = 'neg.txt'
documents += IO.readlines(path).map do |line|
  [0,line.tr("\n","")]
end

# Lets create a dictionary of unique words and then we can
# create our vectors.  This is a very simple example.  If you
# were doing this in a production system you'd do things like
# stemming and removing all punctuation (in a less casual way).
#
dictionary = documents.map(&:last).map(&:split).flatten.uniq
dictionary = dictionary.map { |x| x.gsub(/\?|,|\.|\-/,'') }
training_set = []
documents.each do |doc|
  features_array = dictionary.map { |x| doc.last.include?(x) ? 1 : 0 }
  training_set << [doc.first, Libsvm::Node.features(features_array)]
end

# Lets set up libsvm so that we can test our prediction
# using the test set
#
problem = Libsvm::Problem.new
parameter = Libsvm::SvmParameter.new

parameter.cache_size = 1 # in megabytes
parameter.eps = 0.001
parameter.c   = 10

# Train classifier using training set
#
problem.set_examples(training_set.map(&:first),training_set.map(&:last))
model = Libsvm::Model.train(problem, parameter)
model.save("ic.model")

Quando uso uma quantidade menor de tweets para fazer o treinamento (2000 por exemplo) não tenho nenhum problema, mas quando tento fazer com os 38000 tweets ocorre o seguinte erro:
FATAL failed to allocate memory
O erro ocorre no seguinte trecho do código:
documents.each do |doc|
  features_array = dictionary.map { |x| doc.last.include?(x) ? 1 : 0 }
  training_set << [doc.first, Libsvm::Node.features(features_array)]
end

Sou novo em ruby e não entendi o motivo desse problema, alguém poderia ajudar?
Comment: Não relacionado ao problema, você está lendo o arquivo em "path" duas vezes, quando provavelmente quer ler uma vez o em "path" e outra o em "path2".
Answer: O problema é que o pc onde estas a correr esse código não tem memória suficiente para correr o Libsvm com 38000 tweets.
Experimenta reduzir a quantidade de tweets.
Answer: Aparentemente você está sem memória. Você está mantendo em memória, ao mesmo tempo:

A String documents;
O Hash dictionary;
O Array features_array;
O Array training_set;

Pela linha do erro você sabe que conseguiu alocar documents e dictionary, faltou espaço para features_array e training_set.
Se for possível (é difícil julgar sem saber exatamente o que os métodos que você está chamando fazem), tente reestruturar o código para usar uma estrutura de pipe.
Ao invés de tentar montar estes na memória, vá chamando .set_examples  durante o loop que você faz em documents.
Outra opção é reescrever esse loop usando documents.pop, assim você vai excluindo os elementos do array e liberando memória.
O ideal seria conseguir ler e tratar um tweet por vez, mais refatoração e não sei se é possível no seu caso.

FATAL failed to allocate memory


Sequencing Multiple Patches on One Synth

Question: My question comes after reading this passage from Paul White's Basic Midi book:

"Most modern synths and PC soundcards are capable of playing back up to 16 different sounds at once, each controlled by a different midi channel, and so even a single synth will allow you to create quite ambitious sequences."

I have a Korg MicroKorg that I'm trying to sequence using an Alesis MMT-8 midi recorder, and right now I'm able to record on multiple channels and playback on one patch (or voice). What I want to do is have the synth play back multiple patches at the same time, as described in the quote above.
Comment: The MicroKorg is not multitimbral, so it won't do what you want to do. I suspect the book you are quoting is old and out of date, because today many synths are more often based on classic designs that are not multitimbral. Electronic multitimbral keyboard instruments with these kinds of features are sometimes called "workstations" today, and they can be pretty expensive.
Comment: That might not be possible with the MicroKorg. I'm not sure it's a multitimbral instrument. Can you play back two independent sounds simultaneously without using MIDI?
Comment: I can create two timbres on the same patch, but I don't know about playing those separately.
Comment: Actually, that gives me an idea. When I change the midi channel on the synth, it applies to all patches, but maybe it will work separately for different timbres on the same patch.
Comment: Yes, the book is a bit dated. So if I wanted multitimbrality, but wanted to avoid the cost of a workstation (I've seen those price tags, whew!), should I look into something like a midi module, or a keyboardless synth?
Comment: If you already own a computer, then a software package that comes with some basic soft synths will be most affordable and most powerful.
Comment: OK, thanks for the advice! Do you mind reposting your comments as an answer so I can close the discussion?
Answer: You want to look for a multi-timbral module.  Often times you can find a 'General MIDI' compatible module that is capable of doing this, often times with rather bland sounds.  Casio Porta-Studios are known for this; they have multi-timbral capability but their sound-sculpting capability is extremely limited.  There are also some sound modules offered by Yamaha and Alesis that were geared towards the orchestrator that will work towards what you want.  Also Roland.


How to use valadoc?

Question: I am currently writing a library in Vala.
I have come to a point where I would like to generate some documentation from my sources.
valadoc seems to be the right tool to do this, but there is not much information on how to use it, the manpage is very short.
I tried to run it with valadoc -o doc src/*.{vala,vapi} which gives me these error messages:
unixodbc.vala:21.7-21.9: error: The namespace name `Gee' could not be found
unixodbc.vala:40.9-40.27: error: The type name `Map' could not be found
unixodbc.vala:42.30-42.48: error: The type name `Map' could not be found
unixodbc.vala:40.9-40.27: error: The type name `Map' could not be found
unixodbc.vala:40.9-40.27: error: The type name `Map' could not be found
unixodbc.vala:40.9-40.27: error: The type name `Map' could not be found
unixodbc.vala:80.63-80.81: error: The type name `Map' could not be found
unixodbc.vala:98.9-98.25: error: The type name `ArrayList' could not be found
unixodbc.vala:99.3-99.19: error: The type name `ArrayList' could not be found
unixodbc.vala:110.4-110.22: error: The type name `Map' could not be found
unixodbc.vala:178.9-178.24: error: The type name `ArrayList' could not be found
unixodbc.vala:180.17-180.32: error: The type name `ArrayList' could not be found
unixodbc.vala:187.10-187.25: error: The type name `ArrayList' could not be found
Failed: 13 error(s), 0 warning(s)

As it seems valadoc was designed to be run on all dependencies as well?
How can I get this to work for my library?
Answer: You need to pass --pkg gee-0.10 (or whatever version you are using), just like valac.  See the valadoc --help and the man page for a list of options and their descriptions.  Many of the options you'll need are the same as those you would pass to valac.
Comment: Ouch, I saw the `--pkg` option, but didn't get the association of `valac` and `valadoc`. This makes a lot more sense now.

How to use valadoc?


Execute a shell script with PHP at a specific Time

Question: This PHP code should start a shell script at the time saved in the $start variable and at the time saved in the $end variable. All Files are chmod a+rwx . It works on command line but not in shell_exec(), also the $start and $end variables are in the correct time Format hh:mm. I found this other Post in which someone had a similar Problem but nothing posted there helped me.
if ($_POST["device"] == "Ventilator") {
    $start = $_POST["start"];
    $end = $_POST["end"];

    if ($_POST["start"] != "0") {
        shell_exec('echo "/home/pi/IOT/gpio21high.sh" | at $start');
        echo "$start".
        "
";
    }

    if ($_POST["end"] != "0") {
        shell_exec('echo "/home/pi/IOT/gpio21low.sh" | at $end');
        echo "$end".
        "
";
    }
}

Comment: start by enabling error reporting and looking at your logs. You may also want to add a few `else{}` and see where that goes.
Comment: See also https://stackoverflow.com/questions/12199353/how-can-i-debug-exec-problems
Comment: the `echo "$start". "";' gets executed every time, so 'else{}' is useless , but you are right in the logfile it said "You do not have permission to use at." . i gave the .sh and the .php file 'a+rwx' rights, do you have an idea what i was missing ?
Comment: i made a misstake while reading , the log files are old sry so thats not the problem
Comment: @mario i checked every answer from the post you linked and none of these worked
Comment: If you have no logs or debugging output, verify if anything got scheduled then: `atq`. Otherwise this isn't answerable I'd guess.
Comment: Possible duplicate of [php shell\_exec($cmd) do not run in a cronjob](https://stackoverflow.com/q/46934471/608639)
Answer: It could be a great idea to execute this as a Cron job, you can execute it at a set interval etc that way.
Hope this helps thanks,
Comment: I think it's not really suitable as cron job, as the script itself schedules "at" cronjobs.


Fuzzy logic rule generator

Question: I have 6 variables with 4 membership functions such as "tiny,small,large,huge".
Is there any tool available that would generate the rules for me. I tried to write the rules and came up with 200 rules but the combinations are killing me and it is still incomplete.
Is there any easier way to do this?
Comment: Your question is a bit vague, it would help to add some more details.
Answer: Combining all input fuzzy sets in a naive way results in 4^6 = 4096 rules which is neither reasonable nor tractable (at least if you have to specify the rules' consequents manually). I'd rather recommend you to infer the rule base from data. The machine learning framework for Mathematica is a software package that can do this pretty nicely. It is commercial, but there is a free trial version. Have a try!
Cheers, UBod

Fuzzy logic rule generator


estado cidade JQuery erro na seleção

Question: JQuery:
$(function() {
  $(document).delegate('#estado', 'change', function() {
    var valor = $('#estado').val();
    $('#cidade').load('_requires/cidades.php?estado=' + valor );
   });

  $(document).delegate('#cidade', 'change', function() {
    var valor = $('#cidade').val();
    alert(valor);
    $('#bairro').load('_requires/bairros.php?cidade=' + valor );
   });

 });

HTML:

   Estado

   <select class="typeTextMedio" id="estado" name="estado" required>
      <option value="">Escolha o Estado</option>
      <option value="MG">MG</option>
      <option value="ES">ES</option>
      <option value="RJ">RJ</option>
      <option value="SP">SP</option>
   </select>

   Cidade

   <select class="typeTextMedio" id="cidade" name="cidade" required>
      <option value="">Escolha a Cidade</option>
   </select>

   Bairro

   <select class="typeTextMedio" id="bairro" name="bairro" required>
     <option value="#">Indiferente</option>

   </select>

Quando selecionar na combo estados, popular a combo cidades. Isto esta funcionando.
Quando selecionar na combo cidades, popular a combo bairro. Isto NÃO esta funcionando. Mas observei que na combo cidades só ocorre o ERRO com a primeira cidade apenas e quando clico nela, o evento não ocorre. Com as demais normalmente ocorre.
Uma observação importante é que se escolher segunda cidade da combo, e a combo dos bairros é carregada, então voltar e selecionar a primeira cidade novamente, então agora funciona. Na primeira tentativa nem o alert funciona!
Como resolver?
Comment: A parte em PHP está recebendo e retornando os dados corretamente?
Comment: Sim. Tudo normal, as combos se enchem normalmente. O problema é que ao selecionar um estado a primeira opção de cidade não dispara o evento para popular a combo bairros. Mas da segunda cidade em diante funciona. E, depois da seguida cidade, se voltar na primeira, então agora ela funciona.
Comment: tenta fazer o BIND do CHANGE da CIDADE  só após   a volta da chamada ao escolher ESTADO  $('#cidade').load('_requires/cidades.php?estado=' + valor );
Comment: http://www.dinamicaimoveis.com.br/novo/buscaAvancada.php
Comment: o combo de cidade é inicialmente carregado com Escolha a Cidade. - verifique se quando você trás as cidades do estado selecionado, esse option esta sendo retornado junto com os resultados. Se não tiver, faça isso então.
Comment: eu inspecionei o elemento e notei que o option="" sumiu das opções do select. Só fica as opções das cidades mesmo
Answer: O problema está ocorrendo porque voce não esta retornando junto com os resultados das cidades o option Escolha a Cidade. Desta forma a primeira cidade vem por default como selecionada mas sem ativar o change do combo.
Outra forma de resolver o problema é trocar o código javascript combo #Estado para:
$(document).delegate('#estado', 'change', function() {
    var valor = $('#estado').val();
    $('#cidade').load('_requires/cidades.php?estado=' + valor, function() {
       $('#cidade').trigger('change');
   });

 });

Observe que o trigger vai invocar o evento de change no combo de #cidade.
Comment: Acho que isso resolve.
Comment: quando faço $('#cidade').trigger('change');, a combo bairros é automaticamente populada mas parece que envia valor vazio para o php como parâmetro da cidade e então retorna sem bairros. Mas mesmo assim, ao selecionar manualmente a cidade então a consulta é feita normamente
Comment: o trigger não funcionou então, pq antes dos valores da cidade retornar, ele invocou a função que popula o bairro. Para funcionar teria que colocar o trigger dentro de um timeOut ou então dentro de um Callback. Mas selecionando manualmente vai resolver. Verifiquei que quando troca o estado o combo de bairro continua populado. Adiciona um codigo para limpar o combo de bairro tambem
Comment: É, testando aqui, mesmo assim não deixa selecionar a primeira opção do mesmo jeito. Vê ai: http://www.dinamicaimoveis.com.br/novo/buscaAvancada.php
Comment: Como seria colocar o trigger dentro de um timeOut ou então dentro de um Callback?
Comment: Voce não adicionou o option Selecione sua Cidade. Adiciona isso ai pra eu testar.
Comment: Se você chamar a URL nao traz serviços @Carlos Rocha  http://www.dinamicaimoveis.com.br/novo/_requires/cidades.php?estado=SP
Comment: Atualizei a minha resposta, colocando o trigger dentro do callback. Tenta dessa forma.
Comment: Ainda esta sendo desenvolvido, só tem cidades cadastradas em MG http://www.dinamicaimoveis.com.br/novo/_requires/cidades.php?estado=MG
Comment: faz os acertos que te falei e libera la naquele link para a gente testar.
Comment: ja foi. Atualizado
Comment: Aqui, não querendo incomodar, mas já incomodando. Estou com uma uma outra dúvida meio que parada e por mais que eu pesquise e tente não consigo solucionar. Será que tem como me ajudar fazendo favor? http://pt.stackoverflow.com/questions/124948/como-definir-focus-no-jhtmlarea

estado cidade JQuery erro na seleção


Can a scale contain both a sharp and a flat note?

Question: So, the question should say it all, but for example:
The G minor scale (G - A - Bb - C - D - Eb - F - G)
To change this into the G harmonic minor scale, I would need to raise the seventh note a half-step; (thus changing F to F#) though, that would mean the scale contains two flats and a sharp..
Would the scale (G - A - Bb - C - D - Eb - F# - G) be incorrect? If so, how can I fix it?
Answer: The G minor key signature is written with two flats, but the scale, as you noted, has a sharp in it.  The G melodic minor scale has E natural and F sharp going up, and F natural and E flat going down.
The key signature is one thing; the scale is another.  Some folk music uses scales very different from the major and minor we are used to.
I have seen music that used non-standard key signatures, like two sharps and a flat.  It's rare, and is sometimes used when transcribing folk music.
Comment: http://en.wikipedia.org/wiki/G_minor states that F# sharp is the correct way to write it. However, the key signature is still written with two flats.
Comment: A general rule:  a scale has the letters in order, with none repeated.  If you use G - A - Bb - C - D - Eb - Gb - G you have to keep putting a flat or natural in front of the G.  Also, you can't have a key signature with both G natural and G flat in it.
Comment: But is there a way to get around it? It's not like I can change the F# to a Gb.. (That would likely be more incorrect than having both accidentals in the mix).
Answer: Sticking with diatonic harmony, the most common examples are going to be scales that outline some extended harmony because there can be multiple altered chord factors which are either nonsensical or impossible to spell without a sharp and flat due to their function relative to the key. Pick up any Aebersold book and head to the scale syllabus and you'll find some examples.
Lydian dominant is a nice self-explanatory one - contains a ♯4 and ♭7. Diminished scales are also frequently impossible to write without a sharp and flat. Say we're in Cmin and want to play a diminished scale over the ii. ii°7 is D-F-A♭-C♭. Something needs to give in order to fill in the gaps without an augmented unison, so this scale will contain a C♯ as the 7th step in order to have an interval of a second between each step while still outlining the correct diatonic chord. Both half-whole and whole-half variants suffer this.
It's worth noting most of the Jazz scales commonly named after modes aren't necessarily used in a "modal" way. For instance the function of the aforementioned lydian dominant would be more likely found played over a V+11 than to actually emphasize the mode itself. The scales just share some common characteristics and inherit the name. Super-locrian is a notorious example that has almost nothing to do with the locrian mode other than it's underlying interval pattern.
Comment: Your diminished should be Cb not B natural.Based on D, the 7th would be C#, flattened to make a minor 7th - C, then flattened again to make the diminished 7th takes it to Cb. Even so, some of these will contain # and b.
Comment: @Tim, you are correct and I've adjusted this answer accordingly.
Comment: Also, in this context I like to think of scale degrees as raised or lowered.  We could be talking about a C# Major scale and a #2 modification isn't as clear as a "raised 2".
Answer: Yes the minor scale has a raised leading Tone that can easily be a sharp. This happens in the Minor scales a few times. There is also the Whole Tone scale that can have sharps and flats. There is no rule that excludes them from being in the same scale.
Answer: The music notation will only enable permutations of the major scale (ie minor natural & all modes) to be written with only sharps or flats, because its structure is built-in the name of the notes (imagine what would happen if the notes were named from 1 to 12).
So yes, there are a number of old or synthetic scales that will need a special alteration scheme to be written, and the first two that will come to mind are, as mentioned in other answers, the flamboyant harmonic minor and the suave melodic minor.


Sample time between time range 08:00:00 and 15:00:00

Question: How to sample the time between the specified range (08:00:00 to 15:00:00).
Please help!
Code I tried, but raises error
sample(seq(as.Date.POSIXct('08:00:00'), as.Date.POSIXct('15:00:00')), 20)

Expected:
[1] "08:01:00" "14:00:50" "12:49:50"

Comment: It's `as.Date.POSIXct()` causing the error, not `sample()`.
Comment: Very related (possible duplicate) - [efficiently generate a random sample of times and dates between two dates](https://stackoverflow.com/questions/14720983/efficiently-generate-a-random-sample-of-times-and-dates-between-two-dates)
Answer: Create sequence of times within the specific duration and sample. The time would have todays date, to get only time component we use format.
all_times <- format(seq(as.POSIXct('08:00:00', format = "%T"),
                         as.POSIXct('15:00:00', format = "%T"), by = "sec"), "%T")

sample(all_times, 3)
#[1] "11:51:16" "09:50:10" "13:09:21"


how to setup rule events for before/after video is played?

Question: How can I set up a rule events for actions to occur before and after videos are played in a node?
Thank you for any tips/ help you can give!
Comment: How is your video being embedded in the page? How do you propose to detect when it is started/ended ? You can trigger a rule via ajax. You have not included even close to enough information for someone to help you.
Comment: Thank you 2pha for your reply, much appreciated. I am new here and learning, so am doing my best - apologies if I haven't given enough information. The videos are a field in a node. Exactly, I am unsure how I can set up a rule for this, to detect/ trigger an action when a video is started (played) and ended. I know how to set up the rules, I see there is 'content is viewed' and can set up the type as that node but that is not specific enough about a video being played. So how to set up this rule is confounding me. Any ideas?
Comment: first figure out how your video is being embedded and how to fire the javascript events.
Comment: Thanks so much. I'm using the Video module. Not sure of how to fire the javascript events, but this is a good guidance to try to start working it out. Much appreciated.
Answer: When video start/end it should call js function which trigger ajax call for path you create on drupal (using hook_menu) the callback of that menu item should call the rule you want using rules invoke function
    rules_invoke_component('rule_name', $arg);
So the case is how to trigger the ajax call on start/end
if you are using youtube, check this page, you can trigger js function to start the ajax
https://developers.google.com/youtube/iframe_api_reference
if you have another player you should look to the api
Comment: Might want to implement some sort of flood control on the callback.
Answer: https://www.drupal.org/project/mediafront_popcornplayer allows you to configure events that are triggered when a video's playback reaches a specific point in time.  This is similar to how the YouTube API works, but abstracted so that it works with any video provider with a Popcorn.js wrapper.  That currently includes YouTube, Vimeo, Archive.org and Solidtango.  https://www.drupal.org/project/mediafront provides the UI and logic for a site builder to use the Popcorn Player on any Media field on the content type or just in a specific View.
https://www.drupal.org/node/2434915
Once the Popcorn Player is being used to load the video, the point that the user is at in the timeline is available to you.  While there isn't anything specific to integrate this with Rules, you can really do anything you want to alter objects in the DOM like http://popcornjs.org/popcorn-with-youtube.  It would be really easy to implement a call back to something like https://www.drupal.org/project/rules_link with Popcorn.
Comment: Kreynan that is so very helpful - very very much appreciated!
Comment: While that gives you a structure to work with, the Popcorn Player is very much under active development.  Feel free to open issues in that project's queue and I'll try to incorporate your needs into the next release.

You can see an example of Popcorn Player running with chapter deeplinking into the video and speakers details as footnotes at http://okv.se/play/region-kronoberg/150225.

Also when someone gives you an answer that is helpful, it is common practice to vote that answer up and/or mark it as the answer.
Comment: Thanks Kreynen. I tried to vote up your answer however as I am new here it does not give me permission. This is very helpful to what I'm doing as yes I would like to trigger actions mid-video. I am particularly interested to trigger a series of choices for what videos can next be played- I will see if that feature/functionality can be done in popcorn (I presume so, from the goals of the project). The initial question was about how to trigger actions before and after video playback (i.e. on cueing the video, and stopping the video)- I am not sure if the popcorn player can do that part of it?


Problema ao apagar um arquivo

Question: eu fiz um pequeno gerenciador de logs. é para algo simples, então como está serve. a cada dia eu quero apagar e gerar um novo, porem meu codigo está apresentando o seguinte erro:

O arquivo já está sendo usado por outro processo: 'teste.log'

def manage_log():
    try:
        logging.basicConfig(filename=f"teste.log", level=logging.INFO)

        arquivo = open("teste.log")
        arq = arquivo.read()
        arquivo.close()

        dia = str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%d'))

        if f'[{dia}]' not in arq:
            logging.info(f" [{str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%d'))}] ")

        elif arq[11:14] != dia:
            os.remove("teste.log")

    except Exception as e:
        print(f"\033[1;31;mmanage_log error: {e}\033[;;m")

Answer: Parece que o arquivo "teste.log" está sendo usado por outro processo quando você tenta abri-lo ou removê-lo. Isso pode acontecer se o arquivo estiver sendo usado por outro programa ou se você tiver aberto o arquivo manualmente e o deixado aberto enquanto o seu código está sendo executado.
Para resolver esse problema, você pode adicionar um bloco "finally" ao seu código para garantir que o arquivo seja fechado corretamente depois que o código terminar de usá-lo. Por exemplo:
def manage_log():
try:
    logging.basicConfig(filename=f"teste.log", level=logging.INFO)

    arquivo = open("teste.log")
    arq = arquivo.read()

    dia = str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%d'))

    if f'[{dia}]' not in arq:
        logging.info(f" [{str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%d'))}] ")

    elif arq[11:14] != dia:
        os.remove("teste.log")

except Exception as e:
    print(f"\033[1;31;mmanage_log error: {e}\033[;;m")
finally:
    arquivo.close()

Isso garantirá que o arquivo seja fechado corretamente, independentemente do que acontecer no resto do código.
Comment: Ao perguntar e ao responder não cumprimente, não agradeça, não use slogans não use frases de efeito. Seja mais técnico e menos passional. Veja [Que tipo de comportamento é esperado dos usuários?](https://pt.stackoverflow.com/help/behavior). Se quiser fazer uma comunicação mais pessoal use o campo de comentários(mas tenha em mente que o bot do site ou a moderação, alertada pela comunidade, pode o remover o comentário).

Problema ao apagar um arquivo


Fourier Integral funny notation

Question: If $f$ is differentiable and $\int\limits_{-\infty}^\infty|f(x)|dx<\infty$ show that $\widehat{(f'_c)}(\omega)=\omega\hat{f_s}(w)$ and $\widehat{(f'_s)}(\omega)=-\omega\hat{f_c}(w)$
$f(x)=\int\limits_0^\infty A(\omega)\cos(\omega x)+B(\omega)\sin(\omega x)d\omega$
$A(\omega):=\int\limits_{-\infty}^\infty f(v)\cos(\omega v)dv$
$B(\omega):=\int\limits_{-\infty}^\infty f(v)\sin(\omega v)dv$
$\hat{f_c}(\omega)=\sqrt{\frac{2}{\pi}}\int\limits_0^\infty f(v)\cos(\omega v)dv$
$\hat{f_s}(\omega)=\sqrt{\frac{2}{\pi}}\int\limits_0^\infty f(v)\sin(\omega v)dv$
All these definitions to give context.  Obviously this is a homework question, but I am not seeking the answer [unless you can't help it ;)   ]. Really what I am not understanding is this notation $\widehat{(f'_c)}(\omega)$, what does this mean? I'm sure I can prove this once I know that.
Comment: Not quite. First the derivative, then the hat. Order does matter.
Comment: Your definitions actually **do** contain the explanation for $\hat{}$; as for $\widehat{...}$, it is just another way to write the same symbol.
Comment: so basically $\widehat{(f_c')}(\omega)$ is the same as $(\hat{f}_c(w))'$?
Comment: so $\hat{f}_c(f'(\omega))$?
Comment: This makes no sense at all. Why would you have a function of function, where did that come from?
Comment: I've seen functions of functions many times $f\circ g$
Comment: I think I see now though... Maybe... He means to replace $f(v)$ in $\hat{f}_c(\omega)$ by $f'$
Comment: Sure enough, you may have $f\circ g$ elsewhere. I mean, why here?
Answer:
Your definitions actually do contain the explanation for $\hat{\circ}$; as for $\widehat{\circ\circ}$, it is just another way to write the same symbol. –  Ivan Neretin

You have: $\quad\widehat {f_c}(\omega)\mathop{:=}\sqrt{\tfrac 2\pi\;}\int\limits_{0}^\infty f(\nu)\cos(\nu\omega)\operatorname d \nu$
Then: $\qquad$ $
\widehat{f'_c}(\omega) = \sqrt{\tfrac 2 \pi \;} \int\limits_{0}^\infty f'(\nu) \cos(\nu\omega)\operatorname d \nu
\\[3ex]
\widehat{f_c}'(\omega) = \dfrac{\operatorname d}{\operatorname d \omega} \left(\sqrt{\tfrac 2 \pi \;} \int\limits_{0}^\infty f(\nu) \cos(\nu\omega)\operatorname d \nu\right)$

Fourier Integral funny notation


Usando PHP no terminal, xampp

Question: Estou tentando usar o PHP através do terminal, mas não consigo, quando eu digito which php ele retorna /usr/bin/php aí por isso não consigo executar arquivos PHP, por que ele não encontra os arquivos.
Estou usando XAMPP para MAC
Answer:
Na raiz da sua pasta de usuário, ~, tem um arquivo chamado .bash_profile. Acrescente o seguinte no final dele:
export PATH="/applications/XAMPP/xamppfiles/bin:$PATH"

Salve o arquivo e reinicie o terminal. Agora o which php deve indicar o php-cli do XAMPP.

Alternativa #1
Para chamar um executável de um diretório específico, basta digitar o caminho completo até ele. Em vez de
php meuscript.php

usar assim:
/Applications/XAMPP/xamppfiles/bin/php meuscript.php

Alternativa #2
Navegando para a pasta onde fica o PHP do XAMPP, e rodando a partir de lá:
cd /Applications/XAMPP/xamppfiles/bin
php meuarquivo.php

Comment: No brackets, digite ⌘+O, navegue para sua pasta de usuário (a que tem o seu nome, na barra da esquerda), e escolha o arquivo `.bash_profile`. Se ele não existir ali, crie um com esse nome.
Comment: É melhor você fazer uma pergunta separada sobre isso, @Elaine. Pode ter a ver com a configuração do PHP.
Comment: como eu encontro e acrescento? não sou familiarizada
Comment: que editor de código você usa?
Comment: eu utilizo o Brackets
Comment: Uma dúvida extra, eu incluo vários arquivos no meu `meuarquivo.php (require)` quando acesso ele na web roda normalmente mas quando é pelo terminal ele não encontra os arquivos... isso tem lógica?

Usando PHP no terminal, xampp


Display block on two different pages

Question: I'd like to view my block on pages where the content type = booking and where the address is node/add/booking (basically add, edit and view nodes), how can I accomplish this? So far my code only shows on pages where content type = booking (i.e. view and edit nodes).
<?php
// Change the type to the one you want to match on
$desired_type = 'booking';
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
   return $node->type == $desired_type;
}

return FALSE;
?>

Answer: You can do it like this. It uses exactly the same principles as your existing if statement.
// Change the type to the one you want to match on
$desired_type = 'booking';
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  return $node->type == $desired_type;
}
elseif (arg(0) == 'node' && arg(1) == 'add' && arg(2) == $desired_type) {
  return TRUE;
}
return FALSE;

Answer: Here you go:
<?php
$desired_type = 'booking';

if ($_SERVER['REQUEST_URI'] == '/node/add/booking') {return TRUE;}

if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
   return $node->type == $desired_type;
}

else {return FALSE;}
?>

Display block on two different pages


Not Able to stop Mysql

Question: I want to stop mysql inorder to start it in rescue mode to retrieve my mysql password but its showing my me an error message and won't stop.
service mysql stop

OUTPUT:

stop: Rejected send message, 1 matched rules; type="method_call",
  sender=":1.131" (uid=1000 pid=7640 comm="stop mysql ")
  interface="com.ubuntu.Upstart0_6.Job" member="Stop" error
  name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart"
  (uid=0 pid=1 comm="/sbin/init")

output of
etc/init.d/mysql stop

Rather than invoking init scripts through /etc/init.d, use the
  service(8) utility, e.g. service mysql stop
Since the script you are attempting to invoke has been converted to an
  Upstart job, you may also use the stop(8) utility, e.g. stop mysql
  stop: Rejected send message, 1 matched rules; type="method_call",
  sender=":1.129" (uid=1000 pid=7246 comm="stop mysql ")
  interface="com.ubuntu.Upstart0_6.Job" member="Stop" error
  name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart"
  (uid=0 pid=1 comm="/sbin/init") subhransu@subhransu-Inspiron-1545:~$
  service mysql stop stop: Rejected send message, 1 matched rules;
  type="method_call", sender=":1.130" (uid=1000 pid=7400 comm="stop
  mysql ") interface="com.ubuntu.Upstart0_6.Job" member="Stop" error
  name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart"
  (uid=0 pid=1 comm="/sbin/init")
Comment: Do you run that command as root?
Answer: Try:
sudo service mysql stop

You have to be root to start and stop mysql server.
If you are not root, you must be a sudo-able user, you must use the command sudo and you must know your sudo-password.

Not Able to stop Mysql


Removing link from slideshow images

Question: Hello I Have Created A Slideshow Using Views  but in slideshow if anyone is clicking The link was opening node/8 I Don't Want To Show Link In When Anyone Clicks on slideshow here is my website link Windowhelpdesk.com
Comment: you can use lightbox module for slideshow,i think that is better.
Answer: Without knowing how your view looks like (or what slideshow module you use, if any) it is hard to give a definite answer - but check the image field in your view. If you edit the field there should be an dropdown titled 'link this image with' and right now it is probably set to 'content'. Set it to 'nothing' to remove the link.
Note: I am not sure about the exact labels as I work with a german drupal instance right now, but they should come close. The dropdown is right above the Design Settings fieldset.
Comment: I am using views slideshow module to make a slideshow in drupal So When Anyone Clicks On Image Opening A Image link I Want to remove that check on windowhelpdesk.com

Removing link from slideshow images


Atualizar arquivos PHP via código

Question: Tenho uma aplicação php no servidor online e tenho essa mesma aplicação instalada em outras máquinas e tablets, gostaria de saber uma forma para que eu conseguisse atualizar minha aplicação no servidor online no caso os arquivos php, js, css, etc ... e consequentemente quando os outros dispositivos conectarem a internet obterem esses arquivos atualizados para a aplicação local neles instalados. Alguém conhece alguma forma de realizar isso?
Answer: As máquinas e os tablets tem acesso à internet?
E a base de dados pode ser a mesma que está hospedada online?
Se sim, será que num seria melhor direcionar o acesso da aplicação para o endereço online.
Comment: Não são obrigadas a ter acesso a internet, porém só irá atualizar a aplicação quando acessar a internet. A base de dados vai ser cada um com a sua porque poucas informações são cadastradas pelo cliente no caso os dispositivos. Ter aplicação apenas em um endereço online, está totalmente eliminada essa opção.
Comment: Você poderia criar um script para pegar os arquivos no FTP e move-los para o servidor local assim como fiz nesse código: [link](http://pastebin.com/1hMg4xZr)

Atualizar arquivos PHP via código


Making a colums total (SUM) with Views

Question: Popular Drupal 7 modules such as Views Calc and Views aggregate plus are not available for Drupal 8, so I'm struggling with achieving the following :
Making the sum of a column (of one integer field of list of child nodes) per parent node, without any custom code. No matter what I do with the "Use Aggregation" feature , I keep on getting a list of the values of entities meeting my criteria and not the sum.
Answer: Your current configuration is doing the SUM of all numbers in that field but per views row, so you'd see numbers added up within each node if you had a multivalue field.
To make it sum up across all results/nodes you need to remove the Sort criteria, that can throw aggregation off.

I don't think your second question is making sense, you want to make a reference to a value calculated within views?
Entityreference creates a list of entities, and the summed up value is not an entity, you can't reference it like that. You can create a Views block and show the summed up value on some content pages and wherever you need it. Is that what you're after?
Comment: Thanks for answering, I appreciate it.  Regarding my second question.  I need  to check that the SUM remains below a treshold value, which is a field of the referenced entity. So I thought I would pull the Views sum to another field as an entity reference to the view...
Comment: Referenced entity or the one doing the referencing? Anyway I don't think Entityreference will let you do that, it expects nodes to be selected. Maybe you can use [Math Field](https://www.drupal.org/project/mathfield) but it still isn't clear where the comparison value is located.
Comment: The entity referenced (Parent)  in the entities I'm summing up (Children).  The parent also holds the field with the treshold. In short, I would need to get that sum into a field of another entity. Thanks for suggesting Math Field. It woudn't solve this problem, but another issue if have, if only it would be available for Drupal 8.... :-(
Comment: I see more clearly now, but this seems to be a wider issue than just sums in views. Maybe you can open a separate question and include all the relevant information, and what your goal is. Maybe Views isn't the way to go for you, maybe something else will turn up.
Comment: I tried to remove the sort criteria, but that didn't have any effect.  Issue remains...
Comment: Did you do that in Entityreference display? Aggregation doesn't make sense in there, try a Page or a Block and you'll get to the correct sum of all the nodes fields. Then you can try some other method to incorporate that number into other operations you need. [Computed field](https://www.drupal.org/project/computed_field) might help and it had alpha4 version for D8.
Comment: Tried switching to a Block, no effect.   Good idea to look at Computed field.
Comment: Can you post a screenshot of the Block configuration? I don't see why it would work on my end and not on yours.
Comment: Found it...  I had to create the view on the Parent, and not on the child (using the parent as contextual filter as I did...)
Answer: In my initial attempts, I tried to created a view on the child nodes to which I applied a contextual filter to limit the results to the parent node.  That didn't work.
In the end, the SUM worked, when I switched things around, I created a view on the parent, and establised a relation with the child nodes (through an entity reference).  When I summed up the field (of the child), it worked.
Comment: can you add print screen of your view..?
Comment: This worked for me. My view of "Child" type with a relation to the parent would not sum a dollar amount field I have on the Child nodes. I recreated the view as a "Parent" type with a relation to the child nodes, and I was then able to aggregate/sum the dollar amount fields.

Making a colums total (SUM) with Views


Entity Reference - show link on referenced node

Question: I have a "Entity Reference" field in a custom content type. I want to show on any referenced node the link to the node. How can I do it?
Answer: I found the solution! I just went to "Manage display" of the content type and I checked "Link label to the referenced entity" in the "Entity Reference" field.
Answer: you can create a view page. while selecting the entity reference field you have to select the "Formatter:" as Title(link)


If $ a \equiv 3\pmod 4$ , $ b \equiv 3\pmod 4 $ Then $ab \equiv 1\pmod4$

Question: If $ a \equiv 3\pmod 4$ , $ b \equiv 3\pmod 4 $ Then $ab \equiv 1\pmod4$.
How can I prove that? If I multiply $a \equiv 3\pmod 4 $ with $ b \equiv 3\pmod 4$
then will it look like? $ab \equiv 9\pmod4 \rightarrow ab \equiv 1\pmod4$ ?
Comment: Yes, that's correct. Alternatively, you could use the naive approach that we have $a=4m+3$ and $b=4n+3$ for some integers $m,n$. So, we have,$$ab=(4m+3)(4n+3)=4(4mn+3m+3n+2)+1\implies ab\equiv 1\pmod 4$$
Comment: Apply the [Congruence Product Rule.](http://math.stackexchange.com/a/879262/242)
Comment: http://math.stackexchange.com/questions/1603652/show-that-if-c-mid-a-b-and-c-mid-a-b-then-c-mid-aa-bb/1603658#1603658
Answer: You know $a=4m+3,\ b=4n+3$ for some integers $m,n$ Now muptiply these, and try to factor out $4$ from as much as possible.
Answer: we define $$a=3+4m$$ and $$b=3+4n$$ with $$m,n\in\mathbb{Z}$$ then we have
$$ab=1+(8+12m+12n+16mn)$$ thus we can write $$ab \equiv 1 \mod 4$$
Answer: $[a\equiv3\pmod4]\wedge[b\equiv3\pmod4]\implies$
$[\exists{m}\in\mathbb{Z}:a=4m+3]\wedge[\exists{n}\in\mathbb{Z}:b=4n+3]\implies$
$[\exists{m,n}\in\mathbb{Z}:ab=(4m+3)(4n+3)]\implies$
$[\exists{m,n}\in\mathbb{Z}:ab=16mn+12m+12n+9]\implies$
$[\exists{m,n}\in\mathbb{Z}:ab=16mn+12m+12n+8+1]\implies$
$[\exists{m,n}\in\mathbb{Z}:ab=4(4mn+3m+3n+2)+1]\implies$
$[\exists{k}\in\mathbb{Z}:ab=4k+1]\implies$
$[ab\equiv1\pmod4]$


Functional inequality $f(x+y)f(x-y)\leq f^2(x)-f^2(y)$

Question:
Let $f:\mathbb{R}\to\mathbb{R}$ be $$f(x+y)f(x-y)\leq f^2(x)-f^2(y)\quad \forall x,y\in\mathbb{R}.$$
  Then prove that $$f(x)=-f(-x)$$ and $$f(x+y)f(x-y)=f^2(x)-f^2(y),$$ where $f^2(x)=\big(f(x)\big)^2$.

Source: KMO $1987$
The first is easy. Let the given assertion be $P(x,y)$
$$P(0,0)\implies f^2(0)\leq 0\implies f(0)=0$$
$$P(x,-x)\implies f^2(x)-f^2(-x)\geq 0\tag{*}$$
$$P(0,x)\implies -f^2(x)-f(x)f(-x)\geq 0\tag{**}$$
$$(*)+2(**)\implies -(f(x)+f(-x))^2\geq 0\implies f(x)=-f(-x)$$
But second is not easy. I'm trying to prove $f(x+y)f(x-y)\geq f^2(x)-f^2(y)$. Can anyone help me?
Answer: \begin{align*}
f(x + y)f(x - y) &= -f(y + x)f(y - x) \\
&\geq -(f^2(y) - f^2(x)) \\
&= f^2(x) - f^2(y)
\end{align*}
Comment: Thank you for nice solution!


jQuery/AJAX: um único form que pode ser submetido para urls diferentes (POST ou PUT)

Question: tenho o seguinte cenário:

Tenho um formulário que serve para cadastrar ou alterar um professor;
Para cadastrar tenho um botão no topo que chama o modal para fazer o POST;
Para alterar tenho um botão em cada linha da tabela de professores que chama o mesmo form, porém populado com os dados do professor correspondente para fazer o PUT;
Tenho um arquivo JS com as requisições AJAX, onde eu pego o form pelo id.

O problema é o seguinte: toda vez que eu clico no botão de alguma linha para alterar o professor o form abre populado corretamente mas é submetido para o POST, isso por causa do id do form. A ação de submeter para cadastro está sempre pegando o form.
Meus AJAX são os seguintes:
<code>$('#formSalvarProfessor').submit(function(event){
    alert('POST');
    event.preventDefault();
    $.ajax({
        url: "professores",
        type: "POST",
        data: $(this).serialize(),
        dataType: "json",
        success:function(data){
            swal("Sucesso!", data.msg, "success");
        }, error: function(data){
            swal("Erro!", data.msg, "error");
        }
    });
});

$('.btn-info').click(function(){
    $('#formSalvarProfessor').submit(function(event){
        alert('PUT');
        event.preventDefault();
        var dados = $(this).data("dados");
        var id = dados.ID_PROFESSOR_PRO;
        $.ajax({
            url: "professores/"+id,
            type: "PUT",
            data: $(this).serialize(),
            dataType: "json",
            success: function(data){
                swal("Sucesso!", data.msg, "success");
            }, error: function(data){
                swal("Erro!", data.msg, "error");
            }
        });
    });
});
</code>
Como posso fazer com que cada função capture o form de maneira adequada?
Answer: Solução:
Verificar se está vindo um id do form e fazer o seguinte:
<code>$('#formSalvarProfessor').submit(function(event){
    event.preventDefault();
    var id = $("input[name=ID_PROFESSOR_PRO]").val();
    if(id){
        $.ajax({
            url: "professores/"+id,
            type: "PUT",
            data: $(this).serialize(),
            dataType: "json",
            success: function(data){
                swal("Sucesso!", data.msg, "success");
            }, error: function(data){
                swal("Erro!", data.msg, "error");
            }
        });
    }else{
        $.ajax({
            url: "professores",
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            success:function(data){
                swal("Sucesso!", data.msg, "success");
            }, error: function(data){
                swal("Erro!", data.msg, "error");
            }
        });
    }
});
</code>
Answer: Se o ajax está dentro do click de <code>.btn-info</code> porque dentro dele tem o submit? Já removeu o sumit de dentro do click?
<code>$('.btn-info').click(function(){
    alert('PUT');
    event.preventDefault();
    var dados = $(this).data("dados");
    var id = dados.ID_PROFESSOR_PRO;
    $.ajax({
        url: "professores/"+id,
        type: "PUT",
        data: $(this).serialize(),
        dataType: "json",
        success: function(data){
            swal("Sucesso!", data.msg, "success");
        }, error: function(data){
            swal("Erro!", data.msg, "error");
        }
    });
});
</code>


PagedListAdapter reload data without placeholders

Question: I am using a PagedListAdapter and have to reload data when the screen is resumed.
For this case, I don't want to clear the adapter and show it empty or placeholders while the data is being loaded.
I want to show the previous data and just update it with the diff once new data is received.
But now when I do dataSource.invalidate() it immediately submits an empty list which causes clearing the adapter and showing placeholders.
Now my code looks like:
class PortfolioListDataSource(
        private val viewModel: PortfolioViewModel,
        private val tabType: PortfolioTabType
) : PageKeyedDataSource<Int, Investment>() {

    override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Investment>) {
        val offset = 0
        viewModel.loadInvestments(tabType, offset, Consumer {
            val nextKey = if (it.data.size < params.requestedLoadSize) null else it.data.size
            callback.onResult(it.data, offset, it.total, null, nextKey)
        })
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Investment>) {
        val offset = params.key
        viewModel.loadInvestments(tabType, offset, Consumer {
            val nextKey = offset + it.data.size
            callback.onResult(it.data, nextKey)
        })
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Investment>) {

    }

    class Factory(
            val viewModel: PortfolioViewModel,
            private val tabType: PortfolioTabType
    ) : DataSource.Factory<Int, Investment>() {

        val sourceLiveData = MutableLiveData<PortfolioListDataSource>()

        override fun create() = PortfolioListDataSource(viewModel, tabType)
                .also { sourceLiveData.postValue(it) }
    }
}

Here I initialize the
val pagedListConfig = PagedList.Config.Builder()
            .setInitialLoadSizeHint(20)
            .setPageSize(20)
            .build()

ordersLiveData = LivePagedListBuilder(factory, pagedListConfig).build()

Here I populate the adapter
viewModel.ordersLiveData.observe(this, Observer {
    adapter.submitList(it)
})

And refreshing it with
// TODO Here I want to fetch new data, but not invalidate current dataset while it is loading
factory.sourceLiveData.value?.invalidate()

How can I leave the previous data and update it when new data is ready?
Update:
I want something like:
if (!refreshing) {
   submitList(it)
}

I mean not to post empty dataset to the adapter when dataSource.invalidate() is called.
I understand that mention just above sample will not work because once it is submitted, data source passes updates to the same instance of the list and it is fully encapsulated.
Also, I have no effect onto the data set itself.
I tried to use PagedList.Callback it lets knowing when the list is updated.
But again, there is no chance to somehow affect the update behavior.
With a regular adpter I would just not set or update it's items until new data is received.
I want to achieve something similar here.
Comment: If I understand you properly I belive you can achieve it using DiffUtils
Comment: I am using DiffUtil. The problem is that once I invalidate the data source - it passes the empty data set what causes PagingAdapter to be cleared. And I don't see a possibility to affect this since the update itself is done under the hood
Comment: Is the data being cleared or the adapter
Comment: As I see, the Data Source cleares the dataset (PagedList), which was initially submitted to the adapter. Thus it causes the adapter to be cleared as well
Comment: @GilGoldzweig Added some more clarification of what I want to achieve
Answer: Yes, invalidate() will clear the current dataset.
So, you will get into a Loading/Placeholder state.
It's also not possible to update a specific page.
Say, you are on the 5th page and you want to update the data in that specific page. This is also not possible without calling invalidate() which will clear the dataset and will take to Recyclerview to the first page(top of the list).
The only way to get rid of all these issues is to introduce a persistence layer with Room.
https://github.com/googlesamples/android-architecture-components/tree/master/PagingWithNetworkSample#paging-with-database-and-network
As per docs here :
https://developer.android.com/reference/androidx/paging/DataSource#updating-paged-data

If you have more granular update signals, such as a network API
  signaling an update to a single item in the list, it's recommended to
  load data from network into memory. Then present that data to the
  PagedList via a DataSource that wraps an in-memory snapshot. Each time
  the in-memory copy changes, invalidate the previous DataSource, and a
  new one wrapping the new state of the snapshot can be created.

https://developer.android.com/topic/libraries/architecture/paging/data#consider-content-updates

As you construct observable PagedList objects, consider how content
  updates work. If you're loading data directly from a Room database
  updates get pushed to your app's UI automatically.

In your case, you can always load the data from the DB when the screen is resumed, until the data from your API gets fetched.


Create module that create Content Type

Question: I'm developing module that creates a content type. I saw the same question and there was a solution. I had tried it but it didn't work.
job_post.info.yml
name: Job Post
description: A job posting content type
type: module
package: Pro Drupal Development
core: 8.x

job_post.module
use Drupal\node\Entity\Node;

$content_type = \Drupal\node\Entity\NodeType::create([
    'type' => 'new_content_type',
    'label' => 'new content type',
  ]);
  $content_type->save();

Comment: Don't reinvent the wheel. There is a "Node" module and a  "Field UI" module doing exactly this, and both are part of Drupal core.
Comment: You do not need a custom module for this, these are modules part of Drupal core. You can do this using a point & click interface: Go to `Manage > Structure > Content types` (in the Admin Toolbar) or visit the url `/admin/structure/types` and click the button "Add content type"
Comment: @Hudri – OP maybe wants to create a shippable module to provide some features and a new content type upon installation. Although it would be nice if they'd clarify about this in their question, OP?
Comment: @ectuser if you export the configuration of created content type to module/config/install directory the content type will be created automatically when the module is installed.
That's how Drupal core creates default content types (Article and Basic page). Check out core/profiles/standard/config for examples.
Comment: The module code above has zero context in what function it is in, it's likely it was never called to begin with.
Comment: Sorry I haven't got it. I should create custom content type. How can I do it if I need to create module for this?
Comment: Yes, I know that I can do this. But it is not my goal...
Comment: Why is it so dificult. I just need a module that creates content type with some fields and that's all. I don't need to make it using Drupal interface. I have to make it programmatically. It is my task.
Comment: @Hudri There is at least a core module that implements a new content type in code and there is also an installation profile adding new content types. That is not wrong, and it is something a module would need to do.
Answer: The code from your question should work in a hook_install(). But you need a lot more configuration for a content type, which you can create the easiest way in UI. See the comment of @Hudri.
Then export the configuration to the config folder of your module, see Organizing config for use with a module

Create module that create Content Type