Use integration to find which function has Fourier series $\frac{4}{\pi} \sum\limits^{\infty}_{n = 1, n\text{ odd}} \frac{\sin(nt)}{n^3}$

Question: Problem
It can be shown that the function
$$
f(t) = \begin{cases}
\dfrac{\pi}{2} + t & , -\pi < t < 0,\\
\dfrac{\pi}{2} - t & , 0 < t < \pi,
\end{cases}
$$
has Fourier series $FS_f(t) = \dfrac{4}{\pi} \sum^{\infty}_{n = 1, odd} \dfrac{\cos(nt)}{n^2}$.
Use integration to find which function has Fourier series $\dfrac{4}{\pi} \sum^{\infty}_{n = 1, odd} \dfrac{\sin(nt)}{n^3}$.

I understand that term-by-term integration of a $2\pi$-periodic Fourier series is the formula $\int^t_{-\pi} f(\alpha) \ d\alpha = \sum_{n = 1}^{\infty} \dfrac{a_n}{n}\sin(nt) - \sum_{n = 1}^{\infty} \dfrac{b_n}{n}(\cos(nt) - \cos(n\pi))$. However, I do not understand how to solve this problem.
I would greatly appreciate it if people could please take the time to explain the reasoning involved in solving this problem.
Comment: The result is a primitive function of $f(t)$ made of second degree polynomials. Take care to find the adequate constant of integration
Comment: a primitive of f(t) is $(\pi/2)t \pm t^2/2 + C$, that's all...
Comment: You might consider [rewriting your Fourier series as the Fourier transform of a function](http://lpsa.swarthmore.edu/Fourier/Xforms/FXFS.html) and then using the [Fourier inversion theorem](https://en.wikipedia.org/wiki/Fourier_inversion_theorem). You can use [dominated convergence](https://en.wikipedia.org/wiki/Dominated_convergence_theorem) to swap the integral with the sum in your inverse Fourier transform.
Comment: @JeanMarie But how do I solve such a problem in the first place?
Comment: @JeanMarie I knew there must have been some reason the Fourier series of $f$ was given. Silly me. My method would work in the general case where you might not have been given a hint like the one here.
Comment: @JeanMarie Indeed, but how does this help us solve the problem? In other words, what is the reasoning involved in solving such a problem?
Comment: There is no reasoning: see if the conditions in the theorem about term by term integration of a Fourier series are fulfilled...
Comment: @JeanMarie Ahh, I understand now. Thank you all for the assistance.
Answer: Using the property that the function evaluated at $t=0$ is the average of the left and right piece-wise function evaluated at zero and
$$\sum_{n=0}^{\infty} \frac{(-1)^n}{(2 \, n + 1)^3} = \frac{\pi^3}{32}$$
then the following is obtained:
Integrating
$$
f_{c}(t) = \begin{cases}
\frac{\pi}{2} + t & , -\pi < t < 0,\\
\frac{\pi}{2} - t & , 0 < t < \pi,
\end{cases}
$$
becomes
$$
f_{s}(t) = \begin{cases}
c_{0} + \frac{\pi \, t}{2} + \frac{t^2}{2} & , -\pi < t < 0,\\
c_{1} + \frac{\pi \, t}{2} - \frac{t^2}{2} & , 0 < t < \pi.
\end{cases}
$$
Now, using $f_{s}(0) = (f_{s}(0-) + f_{s}(0+))/2$, then $c_{1} = - c_{0}$ and
$$
f_{s}(t) = \begin{cases}
c_{0} + \frac{\pi \, t}{2} + \frac{t^2}{2} & , -\pi < t < 0,\\
-c_{0} + \frac{\pi \, t}{2} - \frac{t^2}{2} & , 0 < t < \pi.
\end{cases}
$$
In order to determine $c_{0}$ evaluate the series at the point $t = \pi/2$ leading to
$$f_{s}\left(\frac{\pi}{2}\right) = - c_{0} + \frac{\pi^2}{4} - \frac{\pi^2}{8} =  - c_{0} + \frac{\pi^2}{8} $$
From the series it is determined that
$$f_{s}(t) = \frac{4}{\pi} \, \sum_{n=0}^{\infty} \frac{\sin(2\,n +1)t}{(2\, n +1)^3}$$
and
$$f_{s}\left(\frac{\pi}{2}\right) = \frac{\pi^2}{8}.$$
This yields $c_{0}=0$ and
$$
f_{s}(t) = \begin{cases}
\frac{\pi \, t}{2} + \frac{t^2}{2} & , -\pi < t < 0,\\
\frac{\pi \, t}{2} - \frac{t^2}{2} & , 0 < t < \pi.
\end{cases}
$$
One can verify this by using
\begin{align}
f_{s}(t) &= \sum_{n=0}^{\infty} B_{n} \, \sin((2\, n +1) \, t) \\
B_{n} &= \frac{1}{\pi} \, \int_{- \pi}^{\pi} g(t) \, \sin((2 \, n +1) t) \, dt \\
g(t) &= \begin{cases}
\frac{\pi \, t}{2} + \frac{t^2}{2} & , -\pi < t < 0,\\
\frac{\pi \, t}{2} - \frac{t^2}{2} & , 0 < t < \pi.
\end{cases}
\end{align}


MySQL: Select * where filename LIKE 'C:\Boston Office\User\SQL\RevitFile.rvt'

Question: I have a file path like the one above, and I actually copied and pasted from my MySQL table. I know that the path is correct, but I can't get any results.
I have also tried

'C:\\Boston Office\\User\\SQL\\RevitFile.rvt'
'%C:\Boston Office\User\SQL\RevitFile.rvt%'
'C:\Boston Office\User\SQL\RevitFile.rvt%'

and all the above with double quotes. Why isn't this working?
Comment: Jediah, you can edit your post... And please only use tags that are relevant to the software you're using. `sql-server` is the the same as `mysql`, which are you using?
Comment: 3 should read 'C:\Boston Office\User\SQL\RevitFile.rvt%', apologies
Comment: You have a user named SQL?
Comment: Why don't you just look for the `filename like '%RevitFile.rvt%'`? See what that returns.
Comment: that is looking good! Will I have issues if for example I had two close files, such as RevitFile2 etc.?
Comment: @JediahLankitus are u sure C is typed on Latin? (it may be the same key on english and russian keyboard). just a thought
Comment: @WEI_DBA It is also a little inconvenient to not use the whole filepath (I am automating this in c# for alot of files, but it isn't that bad. Curious as to why the full path doesn't work though
Comment: What is the value of this settings: https://dev.mysql.com/doc/refman/5.5/en/sql-mode.html#sqlmode_no_backslash_escapes
Comment: Also, why are you using `LIKE`? What is the definition of the column `filename`?
Comment: @UsagiMiyamoto global: 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
Comment: @UsagiMiyamoto Session: 'NO_BACKSLASH_ESCAPES'
Comment: @UsagiMiyamoto I tried = as well, but it didn't have results so I tried like. The column filename is a bunch of strings, including the exact one I included (C:\Boston Office\User\SQL\RevitFile.rvt)
Comment: If `NO_BACKSLASH_ESCAPES` is enabled, you should not double the backslashes.
Comment: @UsagiMiyamoto it is working using '='. For anyone with this issue, use the command `SET sql_mode = 'NO_BACKSLASH_ESCAPES' ` to fix it. Thank you so much!
Answer: Thanks to @UsagiMiyamoto I found that I could use the original file path after using the command SET sql_mode = 'NO_BACKSLASH_ESCAPES'
Final answer:

SET sql_mode = 'NO_BACKSLASH_ESCAPES'
SELECT * FROM revit.fileindex where filename = 'C:\Boston Office\User\SQL\RevitFile.rvt'

Appreciate the help from everyone :)


Implication of absolute value in $f_X(x)=|x|/10$ for $-2\le x\le4$

Question: $$f_X(x)=\frac{|x|}{10}\qquad-2\le x\le4$$
For the above density function, it is explained that in finding $E[X]$, the expression must be split up because for $x<0$, $|x|=-x$.
I thought that $|x|$ is always $x$ whether $x$ is negative or positive.
How is it true in this case that for $x<0$, $|x|=-x$????
Comment: Note if $x<0$, then $-x>0$. For example, $|-7|=-(-7)=+7$. Here $x=-7$, if we would have written $|x|=x$ then in this case it would have given us $|-7|=-7$ which is definitely not true.
Answer:
I thought that |x| is always x whether x is negative or positive.
  How is it true in this case that for x<0, |x|=−x????

So, this is an integer number line

Any number we don't know yet, we can just call $x$.
(Geometric) Definition: $|x|$ is the distance of $x$ from $0$.
Now if $x=-3$, the distance of $-3$ from $0$ can't be $-3$, because the distance is always positive.
That's why $|-3|=-(-3)=3$ is the distance of $-3$ from $0$ (using the fact that $- \cdot - = +$)
And in general (the mathematical definition)
$$|x| = \left\{
   \begin{array}{rl}
     x, & \text{if }  x \geq 0, \\
     -x, & \text{if } x < 0.
   \end{array}\right.$$
and $|x|$ is always not negative.
$$E(X)=\int_{-2}^{4}x~f_X(x)~dx=\int_{-2}^{4}x|x|/10~dx =-\int_{-2}^{0}x^2/10~dx+\int_{0}^{4}x^2/10~dx=28/15$$
Answer: The absolute value function, by definition, never produces a negative result, and produces the unsigned distance of its argument from $0$. Thus if $x<0$, it must be that $|x|=-x$, to make the negative argument positive again.


Proper Steps to Shutdown NetApp FAS 3020 with Shelves?

Question: I have a netapp with several shelves that is going to have to be moved.  Various servers have NFS mounts from it.  What is the proper procedure to shut it down and start it up?  I would guess shutting down the servers before the netapp and then the otherway when starting it up would make sense... what about the netapp itself?
Answer: As far as the filer itself, "halt" from the CLI is pretty much all you need to know.
(You'd obviously want be sure that no servers are using it).
Power off the head, then the shelves, and do in reverse after you've moved.
http://now.netapp.com has some valuable best-practice guides for this sort of scenario - as an aside, if you're physically moving the netapp, it would be very wise to make sure that your netapp support is current.
Comment: Ya I have a NOW account, but was feeling a bit lazy and figured someone could just spoon feed me the nice short and to the point answer :-)
Comment: Yes, this, good answer
Comment: I'd go with `halt -f` to inhibit failover.
Answer: Shutdown - Perform steps on both heads of the filer
Cf status
Cf disable
Cf status

Cifs terminate

sysstsat -x
lun stats -i 10

If the numbers are not close to zero determine why there is traffic.
Halt

Shows halt on the front
Use powerswitch to turn them all off.

Powerup

Turn on the disk shelves first ….wait 1 minute
Turn on the heads (Ones with LCD's on the front)
Cf status
Cf enable
Cf status

Answer: You might want to add a couple steps if no physical access is available.
SP status

After the HALT command you can cut the power to the building
Once you are safe to start the filer back up you can access the console via the SP/RLM management port from the IP you got from the SP status info
Log in via naroot
system console
boot_ontap
once both nodes in the filer pair are up you can enable the cluster
cf enable
Answer: If you trigger a halt -s would be the cleaner way for shutting down a filer.
Performs a clean system shutdown. The behavior of this command is different across releases. In Data ONTAP releases prior to 8.0.4 and 8.1.2 the end result of this command is to power off the controller. The user has to power on the controller using the RLM or SP. In Data ONTAP releases 8.0.4, 8.1.2 and beyond, it will no longer power off the controller. Instead, it will halt at the LOADER prompt. For platforms that have FRU attention LEDs on the motherboard, Data ONTAP will clear these LEDs when subsequently booted. This applies only to Data ONTAP 8.0 and later.


closed embedding is open iff ideal sheaf idempotent

Question: Let $f: \mathrm{Spec}(R) \to \mathrm{Spec}(A)$ be a closed embedding of affine Noetherian schemes, given by the ideal $I = \mathrm{ker}(A \twoheadrightarrow R)$. If $I = I^2$, then it's not too hard to show that $I = (e)$ for some idempotent element $e \in A$. This gives a partition of $\mathrm{Spec}(A)$ into disjoint closed subsets $V(e)$ and $V(1-e)$, so $V(I) = V(e)$ is clopen. Conversely, if $im(f) =V(I)$ is open, then we can find an idempotent element $e \in A$ such that $V(e) = V(I)$. To show that $I=I^2$, I want to conclude that $I = (e)$, but a priori we only know their radicals are equal. Is this even true? More generally, is it true that $I = I^2$?
What I'm actually trying to prove is that a finite flat group scheme is etale iff the unit section is open.
Answer: Suppose $\text{Spec}(A/I)\rightarrow \text{Spec}(A)$ is an open immersion. Then in particular it is flat, hence $A\rightarrow A/I$ is a flat morphism.
Hence we have an exact sequence $$0\rightarrow I \otimes_A A/I\rightarrow A\otimes_A A/I\rightarrow A/I\otimes_A A/I \rightarrow 0$$
That reduces to
$$0\rightarrow I/I^2\rightarrow A/I\overset{\text{id}}{\rightarrow} A/I \rightarrow 0$$
So $I=I^2$ and as $I$ is finitely generated (because $A$ is noetherian) we get $I=(e)$ with $e^2=e$ (as discussed in here).
For the converse it is not enough to show that $\text{Im}(f)$ is open to conclude that $f$ is an open immersion. There are some immersions with open image that are not open immersions (for example $X_\text{red} \rightarrow X$). But the result is still true because you can prove that $A/(e)\cong A_{(1-e)}$ when $e$ is idempotent and a localization correspond to an open immersion.
Comment: Thank you! I should have thought of flatness. You're right about the converse. I was implicitly using that the image was the basic open $D(1-e)$. For future reference the proof that $I = I^2$ implies $I = (e)$ with $e$ idempotent also follows easily from Nakayama's lemma as mentioned [here](https://math.stackexchange.com/a/348834/52299).


anyone doing php-fpm and APC? cache files missing in /tmp

Question: I have been using xcache for a long time. Recently I put together php-fpm and nginx. I see apc is installed and enabled in the configuration. I was assuming that apc will automatically opcode the files and store it somewhere. According to config it should be in /tmp/apx.xxxx but there is no such thing there.
What am i missing? any clues to investigate would be of much help.
Please note I am using php 5.3 fpm.
thanks mates.
UPDATE: i looked at apc.php it says things are fine. will just have to take its word for it.
Answer: the cache files did show up eventually. Cant remember the exact location. The APC admin page shows that caching is working as you can see from the graphs.
In the combination of nginx and php-fpm I have noticed that for changes to take effect (like installing a new module) you need to retstart both nginx and php-fpm. This could be something only with my versions of the install.
hope it helps.
Answer: I've found the exact same behaviour, and I'm still wondering where the files are.
Did you use chroot with php-fpm? If so, if you set into the pool's config file /tmp, where did the file go? Into the chrooted /tmp directory, or outside the chroot?
Comment: no i did not use chroot. the pool config is standard unedited version. APC does work but I just did not see the files.
Comment: It is weird however. I was hoping that setting different paths for different pools would allow me to secure each user in his own memory region... but it seems it doesn't works that way. I think I'll try to hack it ;)
Comment: i believe you will have to run each pool as different user, if that's possible. else it should theoretically work with different pool configs. It could be  a bug. I am using php 5.3.8 with fpm.
Comment: I am already running each pool with his own user, and it is not a bug since the APC module is loaded at php-fpm startup: then, when the process forks, it is using the same shared memory for all the processes. Now, even if I do understand this behaviour, I don't understand why using different files doesn't mean using different memory locations :S In my case, I am using php 5.3.14-1, and the "bug" is still present... so I think somebody else should explain us what does apc.mmap_file_mask really do (as in my question: http://serverfault.com/questions/403135/what-does-apc-mmap-file-mask-really-do)


VMWare Server with multiple processors

Question: I have a new linux machine with two Core Duo CPUs. However, VMWare Server only recognizes one. In the host summary it shows: Processors: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz 1 CPU x 2 Cores
On another machine, it shows: Intel(R) Core(TM)2 Quad CPU Q6700 @ 2.66GHz 1 CPU x 4 Cores
This machine also has two CPUs.
Why is VMWare not seeing all the CPUs?
Answer: No you don't, none of those chips are multi-processor capable.
Can you tell us what the machine actually has rather than what linux says it has, then we can help.

VMWare Server with multiple processors


Number of orbits of a subgroup of the symmetric group $S_9$

Question:
Let $H=\langle (3\quad 4\quad 5),(1\quad 2\quad3)(7\quad8\quad9)\rangle \le S_9$ be a subgroup in $S_9$. Find number of orbits and their order.

First I noticed $\mathrm{orb}(6)=\{6\}$. I also think that $\mathrm{orb}(3)=\{1,2,3,4,5\}$ but I can't explain how (and if so, then also $\mathrm{orb}(7)=\{7,8,9\}$). Another problem is I don't know to explain myself why a permutation send one of $\{1,2,3,4,5\}$ to $\{7,8,9\}$ does not exist. How can I explain both problems?
Comment: Have you listed down all the elements in $H$?
Comment: Prahlad, yes.@PraphullaKoushik I meant this orbit: http://en.wikipedia.org/wiki/Orbit_%28group_theory%29#Orbits_and_stabilizers
Comment: @PraphullaKoushik I think that my edit sorted that out.
Answer: This is not a complete answer, but rather a hint on what you need to understand.
I assume (though you should specify) that the set upon which your $S_9$ is acting is $\{1,2,3,4,5,6,7,8,9\}$. If this is the case, then the permutation $\sigma=(3,4,5)$ takes $3$ to $4$, takes $4$ to $5$, takes $5$ to $3$, and leaves $1,2,6,7,8,9$ fixed. In the same manner you can see what the permutation $\tau=(1,2,3)(7,8,9)$ does to each element of the set $\{1,\dots,9\}$. In order to compute the orbits of this group action you need also to consider composing the two permutations that generate your subgroup, for example, $(\tau\circ\sigma)(5)=1$. Methods for doing that involve Burnside's lemma and the orbit-stabilizer theorem.
Comment: so as follows I can just write the composition of $\sigma\circ\dots\circ\tau\dots\tau$ never takes a numbef from 1..5 to 7..9?
Comment: @CoarguAliquis There different orders in which you can compose permutations (composition of permutations is not commutative!), but eventually there is no permutation in your subgroup that takes an element of $\{1,\dots,5\}$ to an element of $\{7,8,9\}$.


RODBC in Ubuntu truncates text strings to 255 characters

Question: I am using RODBC installed on Ubuntu 16.0.4, and I am porting my Windows-based R project/package to this Linux environment. I am running into the issue where sqlQuery returns only the first 255 characters of a text string from an MS SQL Server database. I have found many references to this issue, and I have changed the column type in the database to nvarchar(3500) to presumably solve this issue. This was not a problem in the Windows environment. I cannot seem to get around this 255 character limit, in spite of many folks saying that changing the column variable type to nvarchar(4000) or less, would solve this. I've tried many things, including the cast(...as nvarchar(1000)), for instance, to no avail.
Where am I going wrong?
Comment: What about using JDBC drivers in stead of ODBC drivers?
Comment: See my fix below. I did switch drivers, but not to JDBC.
Answer: I was using FreeTDS. I switched to native MS SQL Server drivers, and this fixed the issue. I do not know where the problem lies, but replacing FreeTDS with the MS drivers for SQL server did the trick.


Erro em query SQL

Question: Olá tenho uma tabela no banco de dados que nela estão armazenados vários horários.  E estou fazendo uma consulta só que esta dando erro.
Consulta:
select proximo from (select localizacao.horario as proximo from localizacao where localizacao.horario > CURRENT_TIME LIMIT 1) as tb_proximo, ultimo FROM (select localizacao.horario as ultimo from localizacao where localizacao.horario < CURRENT_TIME) as tb_ultimo;

Erro:
2 errors were found during analysis.

This type of clause was previously parsed. (near "FROM" at position 148)
Unrecognized statement type. (near "FROM" at position 148)

Answer: Acho que tem aí alguma confusão na sua consulta. Esse ultimo está aí a mais, assim como o 2º FROM.
Experimente desta forma:
SELECT  (
            SELECT  localizacao.horario AS proximo
            FROM    localizacao
            WHERE   localizacao.horario > CURRENT_TIME LIMIT 1
        ) AS proximo
    ,   (
            SELECT  localizacao.horario AS ultimo
            FROM    localizacao
            WHERE   localizacao.horario < CURRENT_TIME
        ) AS ultimo

Comment: Sim a disposição é essa, deu certo, muito obrigado!
Comment: De nada! Dê a resposta como certa ;)

Erro em query SQL


Silverstripe /admin/ suddenly stopped working

Question: Currently I am working on a SilverStripe project, and everything seems to be running smooth.
But then things changed.. This morning I tried to login and I got the message that an error occured.
Running in development mode gave the following errormessage:

[User Error] Couldn't run query: SELECT "SiteTree_Live"."ClassName",
  "SiteTree_Live"."Created", "SiteTree_Live"."LastEdited",
  "SiteTree_Live"."URLSegment", "SiteTree_Live"."Title",
  "SiteTree_Live"."MenuTitle", "SiteTree_Live"."Content",
  "SiteTree_Live"."MetaTitle", "SiteTree_Live"."MetaDescription",
  "SiteTree_Live"."MetaKeywords", "SiteTree_Live"."ExtraMeta",
  "SiteTree_Live"."ShowInMenus", "SiteTree_Live"."ShowInSearch",
  "SiteTree_Live"."HomepageForDomain",
  "SiteTree_Live"."ProvideComments", "SiteTree_Live"."Sort",
  "SiteTree_Live"."HasBrokenFile", "SiteTree_Live"."HasBrokenLink",
  "SiteTree_Live"."Status", "SiteTree_Live"."ReportClass",
  "SiteTree_Live"."CanViewType", "SiteTree_Live"."CanEditType",
  "SiteTree_Live"."ToDo", "SiteTree_Live"."Version",
  "SiteTree_Live"."ParentID",

Read full error message: http://pastebin.com/TrjrEzUn
<code>... WHERE ("SiteTree_Live"."ClassName" IN ('Page','BlogEntry','BlogTree','DienstHolder','DienstPage','FaqHolder','FaqPage','FrontPage','MemberPage','TeamPage','ErrorPage','RedirectorPage','VirtualPage','UserDefinedForm','BlogHolder')) AND (ParentID = ) ORDER BY "Sort" You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY "Sort"' at line 1
GET /Security/login?BackURL=%2Fadmin

Line 525 in /home/admin/domains/stargroup.nl/public_html/sapphire/core/model/MySQLDatabase.php
</code>
I checked mysql on empty classnames, some where found but got their proper classname.
Anyone has any suggestions on how to overcome this error and get the login back to working again?
Thnx in advance!
Comment: Bug is fixxed. For details see: http://www.silverstripe.org/general-questions/show/19479#post312599
Comment: PLEASE mark the answer as accepted. it's frustrating to see resolved questions not marked as such.
Answer: The problem in the posted query is that one of the parameters is missing a value - right at the end:
<code>AND (ParentID = ) ORDER BY "Sort"
</code>
Without knowing silverstripe, I'd guess one of your articles/posts is somehow missing an ID or ParentID.
Comment: it has indeed to do with an invalid ParentID.
I somehow thought it was a good idea to get the ParentID as an integer. Did didnt turn out quite well to work.

But I got it fixxed now :)
Comment: PLEASE mark the answer as accepted. it's frustrating to see resolved questions not marked as such.
Comment: @schellmax you should post this comment on the question - so the OP gets an update - not the answer
Answer: Bug is fixxed thanks to Bollig|DesignCity in the SilverStripe IRC Channel.
It all had to do with some code in page.php
Wrong code
<code>    function Siblings() {
       $whereStatement = "ParentID = ".$this->ParentID;
    return DataObject::get("Page", $whereStatement);
    }
</code>
Fixed Code
Note to self: Always be aware of small mistakes like this..
<code>    function Siblings() {
       $whereStatement = "ParentID = '".$this->ParentID."'";
    return DataObject::get("Page", $whereStatement);
    }
</code>


Comparing aspects of the Boss GT-10 and the POD HD500

Question: Both of them are pretty stellar for an amateur like me. I don't intend on playing in large venues and probably will not record much. Both of them have pretty good effects; although, the HD500, I've heard, has good amp samplers.
How do the two compare in regard to the following aspects?

Can they be easily connected to my Boss Looper?
Can they be connected to my computer?
Can I download presets easily from the community?
Do they have good outlets to amps and headphones?
Comment: I've edited to make this question more on-topic. If you feel I've changed the question to much, feel free to edit it back.
Comment: This question is off-topic here. Whichever one you prefer will depend on you. I'm a Line6 man, couple of my mates swear by Boss.If you already have Boss kit, you could stick with it.
Comment: The GT10 has a built in looper. (I have one).  I returned an HD500 because I thought the build quality was poor and it wouldn't stand up to the 4 - 6 times a month I play out or rehearse.  If you like lots of gain, I'd avoid both and get the Zoom G5.  Both the GT10 and the HD500 are decent computer interfaces.
Answer: I had a BOSS GT and got quite a bit of RF interference, especially on high-gain presets so I went to individual pedals ... for a while. But I decided to get the HD500 because I've always like Line 6. Here are my answers to your questions:

I don't know about your Boss Looper, but if it is line-level, why not? However, the HD500 has a looper of its own. It may be worth a look.
I connect my HD500 to my computer all the time and it's worth its weight in gold to me. I hate dorking around with the little knobs and buttons that control a zillion settings when a computer interface will do the job much more quickly and intuitively. Once I get my presets dialed in, I can live with a little dorking around with knobs and dials :)
There are tons of community presets on CustomTone. You should consider these starting points because they are both someone else's idea of what sounds good, and may be colored by your rig.
There are L/R outputs for driving up to two amps, two XLR outputs, MIDI I/O and yes, there is a headphone jack (1/4").

I love the HD500. I've used it in my band and the only problem I had was the same one I always have -- when I plug into someone else's gear, I need to neutralize the effects they have on their amps. But really, to appreciate the HD500, you have to try it. Not for a little while, put some time into it. GC might give you some time to goof with one if they have stock. It's worth it to know whether you "get" their tone generation model.


(very) beginner's example Markov Chain

Question: Person X is on holidays for T weeks. At the end of each week, she gets a mosquito-bite, which infects her (for the following week) with a probability of 0.2. The state-space $Y_t$ is hence either I ("infected") or N ("no disease"). $Y_1$ is "N" - the person starts out healthy. No medication is available, so once infected the person is infected until the end of the holidays.
The tasks are now to (a) specify $P(Y_1)$ as well as $P(Y_t | Y_{t-1})$ for t = 2,3,...,T (b) to draw the transition diagram and (c) to determine the probability that person X is not infected in $Y_4$, i.e. in the fourth week.
My ideas and questions: (a)..? $P(Y_1)$ is obviously 1..? Am I missing something? For $P(Y_t | Y_{t-1})$ I would just specify the transition matrix P as follows (row 1 = infected, row 2 = not infected):
$
  \left[ {\begin{array}{cc}
   1 & 0 \\
   0.8 & 0.2 \\
  \end{array} } \right]
$
is there another way to specify $P(Y_t | Y_{t-1})$? (b) The transition diagram contains two states, from the state "I" there is only an arrow to itself with probability 1, from the state "N" an arrow to itself with probability 0.8 and an arrow to "I" with probability 0.2. Regarding (c), I would calculate the respective entry in $P^3$, calculating first the respective entry in $P^2$ we get 0.2*0+0.8*0.8 = 0.64, and then $P(Y_4=N)$ = 0.64*0.8 = 0.512, the probability that X is not infected after 4 weeks of holidays.
Are my solutions correct? Thanks for your help!
Comment: "P(Y_1)" is what is written in the old exam sheets though...There are questions, for instance if there is another way to define the conditional probability in (a), and else I would like to know if my solutions in (b) and (c) are correct. Your comment seems unnecessarily sarcastic
Comment: @Pegah your clarification will increase the chances of getting a good answer, and it will also increase the productivity of people who do a lot of work helping others on this site.
Comment: What exactly was unclear? Serious question, so I can write better posts. I appreciate the help very much and so usually also try to put some effore into the formulation of my questions, but I find some charitability towards each other also important..my question seems reasonable to me, and the way I put it also clear.
Comment: (a) "$P(Y_1)$" makes no sense--perhaps you mean $P(Y_1=\text{N})$. (b) and (c) are not questions, so it seems you haven't actually asked anything.
Answer: You know without a doubt that at time $t=1$ the person is not infected, so $P(Y_1 = N) = 1$. Maybe you are used to seeing a Markov chain start with an initial distribution that's not just a point mass at one value but a deterministic start is perfectly reasonable.
For the transition matrix, let $\Omega = \{I, N\}$ denote the set of possible values. You have one conditional distribution per value in $\Omega$, each distribution specifies $|\Omega|$ probabilities, and the distributions do not change over time, so you'll need to have $|\Omega|^2$ probabilities specified which is what is accomplished by your $2 \times 2$ transition matrix. So there's no way that does not involve specifying 4 probabilities. This matrix is unique up to relabeling of the states.
Finally, you need to compute $P(Y_4 = N)$. Here is how I would do it: you know that $Y_t = I \implies Y_k = I$ for all $k \geq t$ so the event $\{Y_t = N\}$ is equivalent to the event $\{Y_1 = N, \dots, Y_t = N\}$. This means
$$
P(Y_4 = N) = P(Y_1 = N, Y_2 = N, Y_3 = N, Y_4 = N) \\
= P(Y_4 = N | Y_3 = N)P(Y_3 = N | Y_2 = N)P(Y_2 = N | Y_1 = N)P(Y_1 = N) \\
= (0.8)^3 \times 1 = 0.512
$$
which agrees with your computation. You got the right answer but if I can avoid computing powers of matrices by hand I try to do so, and since we have $P(Y_t = N | Y_{t-1} = I) = 0$ the computations simplify to the point that we can get away with this more direct approach. But in total generality you would indeed need to compute powers of matrices.
Comment: @Pegah glad this was helpful! As long as you know exactly what it all means and can be rigorous if you'd like to be, I wouldn't worry too much about the $P(Y_t)$ notation. It is an abuse of notation but in my experience such abuses are pretty common
Comment: Maybe the P(Y_1) is a typo in the old exam sheets, but we are not allowed to ask any questions about old exams...>_>..Anyway, perfect explanation, thank you so much!

(very) beginner's example Markov Chain


RAID 0 for Development

Question: Hello fellow administrators, I am seeking high level guidance on the following situation:
First the context of the environment: internal, all virtual (vmware), development use only, performance optimized across the full stack, down time is acceptable (1-2 days for a few servers at a time), budget conscious, heavy write OLTP workload, 10Gbps links between SAN (Synology all flash SAS) and hosts, small team none of us are formal DBAs, all databases have simple recovery model, san volumes are ext4, thick provision on the LUNs as well..
Since I was just a baby administrator backups and redundancy has been pounded into my head. Which I have followed until now, because the budget is limited and there is significant amount of data 90 TBs across 20 servers (SQL Server on Linux (Ubuntu to avoid windows licensing costs)) with about 40 databases. Therefore we use RAID 0. This is done because we have heavy write workloads and the use case / application / business requires high throughput even for development, all drives are on the support list synology.
There are many situations that lead to the current configuration. The config being, single volume storage pools (4 x 4/8TBs SSDs in RAID 0), single volume, single LUN, single VMFS, if 4TB drives volume has 2-6 VMs (6 to 2TBs) double that for 8TBs, thick eager provisioning, SAN LUNs uses 98% of available capacity, everything else uses 100%. I know this reduces visibility across the board for capacity planning, that is handled else how not covered here. Because we use RAID 0 for cost savings and performance we limited it to 4 drives to reduce affected servers if a drives fails. This also helps with the servers not running into each other, there is low appetite to use vmware IO limiting.
For the sake of the conversation lets say significant budget increases ($2,000+) is not possible. It should be known that we have full c level sign off on the risk of downtime.
Last piece, we have to have a couple of 50TBs datastores where storage pools are config'd with RAID 10 8 x 7.2K HDDs instead of RAID 0 with SSD and this level of performance is not enough because the workloads are just too much for the IOPS that HDDS can produce.
This brings us to my question, given the restrictions, is this a good approach for performance? What have others done with similar goals and restrictions? Please remember downtime is acceptable for some servers at a time in the case of a drive failure because this is not production workloads, those are at AWS and Azure.
I know this question cross many areas but I also know many DBAs now a days have had to become familiar with those areas, I am really looking for advice for those with similar situations.
Thank you
Comment: Remember that RAID 0 is 0 RAID. It's good only for stuff you don't care if it disappears when a drive fails. But if you ran out of IOPS with spinning rust then it's time to move to SSD anyway, whether you use RAID 0 or 10 or anything.
Answer: Complete a backup restore test during the day.  Destroy the storage volumes to simulate RAID 0 storage pool failure, which will take the test systems down. Copy from backup media, and complete a restore. If the organization is satisfied with the recovery and tolerates that amount of downtime, then a RAID 0 scheme could work. (I am skeptical they will tolerate a few hours down, but maybe.)
Restore tests are useful on any storage, but extra important if restores are necessary on the first drive failure.
Doing such a restore test during business hours is important. Drive failures don't wait for after hours. So, this forces users to appreciate how much downtime a restore really means. Also, you the system admin should not have to work odd hours for a test system that is documented to be of lesser importance.

Regarding performance, for your capacity planning define an IOPS budget. Look at IOPS numbers from the database, host, or storage array level, and observe when performance is acceptable.
7200 RPM drives under small block random load might get 70 IOPS each, raw. Not a lot. Divide your IOPS requirement by this to approximate the number of spindles required. Do the same for solid state, which should be thousands of IOPS per drive. Compare price per IOPS as well as price per capacity.
This barely covers the beginning of the possibilities for storage design. For example, hybrid arrays with both SSDs and spindles are possible. However, those work best in storage that has a caching tier, or an obvious bottleneck like RAID 4. Uniform storage is simpler to manage for most RAID types.
Comment: *7200 RPM drives under small block random load might get 70 IOPS each*  And 5,000ish RPM drives can be under 50...

RAID 0 for Development


What is difference between File.Exists("") and FileInfo exists

Question: I have an *.exe file in \ProgramFiles(x86)\MyAppFolder.
In x86 application I check if the file exists (64 bit system).
simple:
bool fileExists = File.Exists(@"\ProgramFiles(x86)\MyAppFolder\Manager.exe");

The result is:
"fileExists == false" (the file is really there). It's Virtualization as I understand.That issue described here Its ok.
But next code:
bool fileExists = new FileInfo("\\Path").Exists;

"fileExists == true"
Why is the result different in 1st and 2nd cases?
var controller = new ServiceController(Product.ServiceName);
_manager.Enabled = controller.Status == ServiceControllerStatus.Running;

var info = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);

var s = File.Exists(@"D:\TFS\GL_SOURCES\Teklynx_LPM\Dev\Server\Debug\Manager.exe");

string pathToManager = string.Empty;

if (info.Parent != null)
{
    var pathToModule = info.Parent.FullName;
    pathToManager = Path.Combine(pathToModule,"Manager.exe").Replace(" ",string.Empty);
}

//works good
var fileInfo = new FileInfo(pathToManager);
var managerSeparator = new ToolStripSeparator()
{
    Visible = _manager.Visible = fileInfo.Exists // true
};

//Does not work
var managerSeparator = new ToolStripSeparator()
{
    Visible = _manager.Visible = File.Exists(pathToManager ) // false
};

Thanks!
Comment: I can imagine that the only reason to use FileInfo.Exist over File.Exists is if you are going to use the FileInfo object later on.
Comment: Are you using "ProgramFiles(x86)" as described? because this folder name contains spaces "Program Files (x86)"
Comment: oh, its  mine mistake. I have used the Assembly.GetExecutingAssembly().Location and then combined the path like (Path.Combine(pathToModule,"Manager.exe")). so the slashes shoul be correct.
Comment: Have you tried:
bool fileExists = File.Exists(@"C:\Program Files (x86)\MyAppFolder\Manager.exe"); ?
Comment: For windows, file system paths use `\\ and not `/, and... your example calls use different paths...?
Comment: @crashmstr: You can use either slash on Windows file systems.
Comment: sure that is not a problem of relative path? check the path where the File.Exist() check for the file.
Answer: This is about the only difference and it has more to do with the nature of FileInfo:
FileInfo fileInfo = new FileInfo("myFile.txt"); // non-existent file
Console.WriteLine(fileInfo.Exists);             // false
File.Create("myFile.txt");
Console.WriteLine(File.Exists("myFile.txt"));   // true
Console.WriteLine(fileInfo.Exists);             // false

So as you can see the value of fileInfo.Exists is cached the first time you use it.
Other than that, they do the same thing behind the scenes.
Comment: This is actually a critical difference in behavior! On the face of things, I'm pretty sure most people would expect that to fail or succeed based on the current status of the file, not on some cached status of that file.
Comment: @ouflak yeah, [that definitely happens](http://stackoverflow.com/q/17839745/188246)
Answer: There is no difference, these methods use the exact same internal helper method inside the .NET Framework.  Something you can see with a decompiler or the Reference Source source code, the helper method name is File.FillAttributeInfo().
Having duplication like this in the .NET Framework is pretty unusual, not exactly a Good Thing to have more than one way to accomplish the same thing.  The File class is however special, it got added after a usability study conducted when .NET 1.0 shipped.  The test subjects just had the basic BCL classes to work with, like FileStream and FileInfo, and otherwise only had MSDN documentation available.  The test results were not very good, the File class got added to help programmers fall in the pit of success writing very basic file manipulation code.  Like File.Exists() and File.ReadAllLines().
So it doesn't have anything to do with the classes, you are just using them wrong.  Like not actually using the same path.  Do go easy on the forward slashes, the mapping to backward slashes happens inside Windows and is inconsistently implemented in other code.  Using // certainly doesn't do what you hope it does.
Comment: Looks like i am going crazy, but now I cant reproduce the issue after VS restarting(same code). The issue has been found as a bug on our software, and has a really strage way for reproducing, actually, when you start app first time everything is fine, but "File is not found!" after OS rebooting. I can stably reproduce this on a software. Anyway, I am agreed - File.Exists() and .Exist prop. are the same things and the problem somewhere else. Thanks!
Comment: Note: Per https://stackoverflow.com/a/22046285/361842 there is a difference... i.e. `File.Exists(myFilePath)` is invoked when you call it, so checks the current state; `myFileInfo.Exists` is invoked the first time it's called; then the same value is returned for each subsequent call, even if the underlying filesystem's state has changed (i.e. the file has been created or deleted).
Answer: The difference between File.Exists() and new FileInfo().Exists on it's behavior when full path (directory name + file name) is long:
var f = @"C:\Program Files (x86)\MyAppFolder\many_subfolders\manager.exe";

//f.length > 260 characters

bool fileExists = File.Exists(f); //return false, even if the file exists

// Throw exception: "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."
bool fileInfoExists = new FileInfo(f).Exists;

Answer: I just found this thread and wanted to update it as I had an issue with FileInfo vs File.Exists.
Let's take a scenario where we create a fileinfo object for a file that currently doesn't exist on a UNC share.
bool fileInfo  = new FileInfo(@"\\uncshare\name\filename.txt");

At this point, the file does not exist, but if I create it using another tool (other code or outside my app) and then do this...
fileInfo.Refresh();
bool exists = fileInfo.Exists;

The result is false, it does not exist, even though it does and the fileInfo was refreshed.
To get the correct result requires..
bool exists = File.Exists(f);

Hope that helps others.
Answer: I've replicated your scenario using the below Linqpad script
var f = @"C:\Program Files (x86)\MyAppFolder\manager.exe";

bool fileExists = File.Exists(f);
bool fileInfoExists = new FileInfo(f).Exists;

fileExists.Dump();
fileInfoExists.Dump();

Ran this both when the file existed and when it did not and both produced the same output each time.
 Maybe try this on your system and see if you still see differences.
Answer: in your first case, the file path is incorrect, you need spaces in "Program Files (x86)".
Secondly, the Path.Combine will return a Directory path so you'll end up with something like "C:\Program Files (x86)\MyAppFolder\Manager.exe\"
so it's a bad idea.
Both methods work the same way, so make sure you check that the path is correct.
Comment: I have never seen the problem you describe in your "Secondly" paragraph. Can you show an example where you do not explicitly have a "\" at the end of the final Path.Combine parameter?


If $f$ and $g$ are continuous maps on a topological space $(X,\tau)$ then $f+g$ is

Question:
If $f$ and $g$ are continuous maps on a topological space $(X,\tau)$ then $f+g$ is
$(a)$ maybe continuous.
$(b)$ may or may not be continuous.
$(c)$ is continuous.
$(d)$ none of these.

I think the answer should be continuous which is option $(c),$ but my book says option $(a)$ i.e. maybe continuous. I don't understand how do I prove this or contradict this. Any help is appreciated thanks. An example demonstrating the fact that if $f,g$ are continuous then $f+g$ may be continuous will also work. Thanks.
Comment: Why does it say (a)?  Perhaps because the question does not mention $\mathbb R$ as the range of $f$ and $g$?  So continuity could fail for some other choice of range?
Answer: Start by thinking about what does $f+g$ really mean. There is a hidden composition of two functions here. Define $h:X\to \mathbb R^2$ (or change $\mathbb R$ for wherever space you are summing) by $h(x) = (f(x),g(x))$ and define $(+): \mathbb R^2 \to \mathbb R$ as $(+)(x,y) = x+y$ (this is essentially what's called polish notation). Now, you have $f+g = (+) \circ h$. In other words, you first compute $f(x), g(x)$ and then you add them.
Now you have split a hard problem into three easier problems:

Is $h$ continuous? (Remember that $f$, $g$ are continuous)
Is $(+)$ continuous?
Is the composition of two continuous functions (namely $(+)$ and $h$)  continuous?
Comment: Yup, my bad, corrected
Answer: In a general topological space, what does $+$ even mean?
If we assume that $f$ and $g$ are maps into euclidean space, say, then for any point $x_0$, $\forall\epsilon$ we need a $\delta\gt0$, such that we have $|x-x_0|\lt\delta\implies |(f+g)(x)-(f+g)(x_0)|\lt\epsilon$.  Just choose $\delta$ such that $|x-x_0|\lt\delta\implies |f(x)-f(x_0)|\lt\epsilon/2$ and $|g(x)-g(x_0)|\lt\epsilon/2$.
It is easy to see that this $\delta$ will do the trick, given that $(f+g)(x):=f(x)+g(x)$.


FileNotFoundError every time I try to download a video using PyTube

Question: Every time I try to download a video using Pytube, it generates this error:
FileNotFoundError: [Errno 2] No such file or directory:

Recently it has been showing this error. Before, it worked completely fine. Here's my code:
def vid_only():
    for stream in yt.streams.filter(only_video=True, adaptive=True, file_extension="mp4"):
        res_avail.add((stream.resolution))
    r = ", ".join(res_avail)
    print(f"Available resolutions:  {r}")

    res_choose = input("Input your desired resolution: ")
    print("Downloading . . .")
    vid_download = yt.streams.filter(res=res_choose.lower()).first()
    vid_download.download(filename=yt.title + " VIDEO ONLY.mp4")

link = input("Input youtube link: ")
yt = YouTube(link)
res_avail = set()
stream_type = int(input("Types: \n1. Video only \n2. Audio only \n3. Video with audio \nEnter the number of the type you want to download: "))

if stream_type == 1:
    vid_only()

Is there something wrong with this line?
vid_download.download(filename=yt.title + " VIDEO ONLY.mp4")

Comment: Maybe it's the way you run the script, because it works for me
Answer: I had this same error, in my case the file contained illegal "filename" characters...  as the script above simply passes yt.title to the download call without making it "safe".
So I changed the filename line to...
filename = "".join([c for c in yt.title if c.isalpha() or c.isdigit() or c==' ']).rstrip()

... based on SO Answer (https://stackoverflow.com/a/7406369/1327508)


Simple javascript for a clock not working

Question: Hi this is my first javascript and it is not working. The script is programmed to display a clock. The code is as follows:

The javascript is :
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}

function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}

When execute I get a blank screen. What and where is the mistake ?
TIA :)
Comment: try to write your js code in the same HTML file in between `
Comment: Your code runs well. No errors.
Comment: There are few corrections, but let me know which browser are you using?
Answer: You should probably be consistent with ending lines in semi-colon. Also, you should check that clock.js is loading; finally put the onload handler in quotes like

function display_c() {
  var refresh = 1000; // Refresh rate in milli seconds
  mytime = setTimeout('display_ct()', refresh);
}

function display_ct() {
  var x = new Date();
  document.getElementById('ct').innerHTML = x;
  tt = display_c();
}

Answer: Please enclose your onload attribute value of body tag inside " " .
It should be

Answer: Try using setInterval(), also this line won't work in some browsers:
setTimeout('display_ct()',refresh)

var ct;

function display_c() {
  //timer block
  setInterval(function() {
    ct.innerHTML = new Date().toString();
  }, 1000); //execute every 1 second
}

function display_ct() {
  ct = document.getElementById('ct'); //initialize once.
  display_c();
}

  Loading ...

Answer: You made two errors when entering the display_ct function. You needed to wrap the 's onload event with quotes, and remove the quotes and the parentheses on the setTimeout. See below.

function display_c() {
  var refresh = 1000; // Refresh rate in milli seconds
  mytime = setTimeout(display_ct, refresh);
}

function display_ct() {
  var x = new Date();
  document.getElementById('ct').innerHTML = x;
  display_c();
}

Comment: thanks for your input, just adding on to what you explained how do I align the display to top center ? I tried the align tag but it does not work.
Comment: Learn more HTML. Search this site for your answer.


Factorization of $(1+2i)z^2+6iz+2i-1$ to find the residues, but it doesn't work

Question: I'm doing complex analysis and I have the following $$\int_{C}\frac{2dz}{(2i+1)z^2+6iz+2i-1}$$ where $C$ is the unit circle. I tried factorizing this polynomial and find the residues but I really can't solve this.
This is my work:
$$z_{1,2} = \frac{-3i\pm \sqrt{-9-(-4-1)} }{2i+1}=\frac{-3i\pm 2i}{1+2i} \cdot \frac{1-2i}{1-2i}= \frac{-3i-6\pm 2i\pm 4}{5}$$ which gives $z_1 = -\frac{2}{5}-\frac{i}{5}$ and $z_2 = -2-i$. Now clearly $z_2$ is outside the unit circle so I just have to consider the residue of $z_1$.
However I think I'm either making a factorisation mistake or a mistake in the roots. Indeed if we check the roots, I don't get the same polynomial! $$(z+2+i)\left(z+\frac{2}{5}+\frac{i}{5}\right) = z^2 +z\left(\frac{12}{5}+\frac{6i}{5}\right)+\frac{4i}{5}+\frac{3}{5}$$ which is clearly not the same polynomial I started with. Also if I try to calculate the residue using the limit, I don't get the correct one. Where's my mistake?
EDIT
As requested, I'll add some more calculations. To calculate the residue I did the following: $$\lim_{z\to z_1}(z+\frac{2}{5}+\frac{i}{5})\frac{2}{(z+2+i)\left(z+\frac{2}{5}+\frac{i}{5}\right)} = \frac{2}{\frac{8}{5}+\frac{4i}{5}} = \frac{5}{4+2i} = \frac{20-10i}{20}=1-\frac{i}{2}$$ which is clearly wrong as this integral is the mapping of a real integral of the first type (rational function in sine and cosine). Indeed by Cauchy's Residue Theorem this should give that the value of the initial real integral is $2\pi i (1-\frac{i}{2}) = 2\pi i+\pi$ which is a complex value, so this is wrong
Comment: Multiply through by the coefficient of the $z^2$ term to check the polynomial.
Comment: @MichaelBurr do you mean $(2i+1)$? I know this is a stupid question, however how come I don't get the correct polynomial by finding the roots?
Comment: @Euler_Salter Of course, if $p(x)$ is a polynomial, then $\lambda p(x)$ is another polynomial with the same roots for any nonzero scalar $\lambda$... but does multiplying with $2i+1$ even fix the mistake above?
Comment: @MichaelBurr and is there a quicker way to factorize these kind of polynomials?
Comment: @rschwieb true. So whenever I have a polynomial with a coefficient of $z^2$ different from $1$ or $0$, I have to find the roots and after that I multiply the polynomial $(z-z_1)(z-z_2)$ by that coefficient?
Comment: Yes, you should multiply through by $1+2i$ and you should get your original polynomial.  The quadratic formula is fairly quick to get the roots, I can't suggest an alternate way.  As for the residue theorem, $1+2i$ is going to play a role, so perhaps that is what you are missing.   More details on the calculation would allow us to check it more thoroughly.
Comment: @MichaelBurr I'll update
Comment: Sorry, I was scribbling in the solutions to see what was going on and accidentally submitted something I didn't intend to be a solution.
Comment: @rschwieb don't worry. I tried multiplying by $2i+1$ and it gave the correct polynomial. So where's the problem with the residue? Do I have to rewrite the denominator differently?
Comment: Yes, whenever you use the denominator (like in the limit calculation), you need to include a factor of $(1+2i)$.  This will make all answers agree.
Comment: If you are only interested in the result you can set z = Exp( i a] and integrate over a from 0 to 2 Pi. The integral is elementary but a jump of size Pi in the antiderivative must be taken into account. It is just this jump which gives the result, viz. Pi.
Comment: @Dr.WolfgangHintze ,  here $z = e^{i\theta}$ indeed the real integral used to be $$\int_0^{2\pi}\frac{d \theta}{3+2\cos(\theta)+\sin(\theta)}$$ and I've used the substitutions $z=e^{i\theta}$, $d\theta = -\frac{idz}{z}$ and $\cos(\theta) = \frac{z+z^{-1}}{2}$ and $\sin{\theta}=\frac{z-z^{-1}}{2i}$. I don't understand the rest of your comment sorry
Comment: @Dr.WolfgangHintze , do you mean that in order to solve this I should go back to the real integral? Or what? And also how do you see that "jump"? I'm very lost right now
Comment: @Euler_Salter Sorry for having been very brief. I'll give an answer soon.
Comment: @Dr.WolfgangHintze thank you
Answer: Let's start with the factorization question.  The given integrand is a fraction, and to use the residue theorem, we must find the roots of the denominator, i.e., the roots of
$$
(2i+1)z^2+6iz+(2i-1).
$$
To find the roots of this polynomial, it's easiest to use the quadratic formula to get that the roots are
\begin{align*}
\frac{-6i\pm\sqrt{(6i)^2-4(2i+1)(2i-1)}}{2(2i+1)}&=\frac{-6i\pm\sqrt{-36+20}}{4i+2}\\
&=\frac{-6i\pm\sqrt{(6i)^2-4(2i+1)(2i-1)}}{2(2i+1)}\\
&=\frac{-6i\pm\sqrt{-16}}{4i+2}\\
&=\frac{-6i\pm4i}{4i+2}
\end{align*}
Therefore, the roots are $\frac{-2i}{4i+2}=\frac{-i}{2i+1}$ and $\frac{-5i}{2i+1}$.  Multiplying through by the conjugate of the denominator, $(1-2i)$ gives that the roots are $\left(-\frac{2}{5}-\frac{1}{5}i\right)$ and $(-2-i)$.
As the OP observes, the polynomial
$$
\left(z-\left(-\frac{2}{5}-\frac{1}{5}i\right)\right)(z-(-2-i))=z^2+\left(\frac{12}{5}+\frac{6}{5}i\right)z+\left(\frac{3}{5}+\frac{4}{5}i\right)
$$
is not the original denominator.  This is another polynomial with the same roots, as the original polynomial.  To make the polynomials the same, we should multiply by $(1+2i)$ to correct the coefficient of $z^2$.  In fact
$$
(1+2i)\left(z^2+\left(\frac{12}{5}+\frac{6}{5}i\right)z+\left(\frac{3}{5}+\frac{4}{5}i\right)\right)=(2i+1)z^2+6iz+(2i-1),
$$
the original polynomial.
Therefore, the original polynomial factors as
$$
(2i+1)z^2+6iz+(2i-1)=(2i+1)\left(z-\left(-\frac{2}{5}-\frac{1}{5}i\right)\right)(z-(-2-i)).
$$
To deal with the residues, the OP correctly determines that $-2-i$ is outside the unit circle, so it doesn't matter for the integral (although it could be used to calculate the integral, but that is a story for another time).
Therefore, the value of the given integral is $2\pi i$ times the residue at $\left(-\frac{2}{5}-\frac{1}{5}i\right)$.  Rewriting the integral as
$$
\int_\gamma \frac{2}{(1+2i)(z-(-2-i))}\cdot\frac{1}{z-\left(-\frac{2}{5}-\frac{1}{5}i\right)}dz,
$$
the value of the residue can be calculated by substituting $\left(-\frac{2}{5}-\frac{1}{5}i\right)$ for $z$ in $\frac{2}{(1+2i)(z-(-2-i))}$.  This substitution results in $-\frac{1}{2}i$ and Cauchy's residue theorem gives that the integral is $\pi$.
The only mistake that the OP seems to make throughout is forgetting the factor of $(1+2i)$ when factoring the denominator.  When that is included, all of the answers (and the limit approach in the question) agree.
Comment: perfect I'd say!
Answer: If you were only interested in the value of your integral $f$ you could let $z=\exp (i \theta )$ and get
$$fr=\int_0^{2 \pi } \frac{1}{\sin (\theta )+2 \cos (\theta )+3} \, d\theta$$
In order to calculate the integral we attempt to use the fundamental theorem of calculus, i.e. taking the difference of the anitiderivative at both ends of the integration interval. But this holds only for continuous antiderivatives. If the antiderivative contains jumps these must be taken into account.
An antiderivative of the integrand is
$$fa=-\tan ^{-1}\left(\frac{2}{\tan \left(\frac{\theta }{2}\right)+1}\right)$$
In the region of integration the denominator vanishes at $\theta =\frac{3 \pi }{2}$. Here the antiderivative makes a jump from
$$\lim_{\theta \to \left(\frac{3 \pi }{2}\right)^-} \, fa=\frac{\pi }{2}$$
to
$$\lim_{\theta \to \left(\frac{3 \pi }{2}\right)^+} \, fa=-\frac{\pi }{2}$$
i.e. it jumps by an amount of $\pi$.
Now the antiderivative at both ends of the integration interval is equal to $-\tan ^{-1}(2)$. Hence the difference is zero, and we are left with the jump which gives $f=fr=\pi$.
EDIT
I'm afraid I have made it more complicated than necessary.
Let us therefore apply a "standard" procedure and do this for the more general integral (displayed here in original form and reduced form)
$$\int_0^{2 \pi } \frac{1}{a+b \cos (\theta )+c \sin (\theta )} \, d\theta =\int_0^{2 \pi } \frac{1}{a+\sqrt{b^2+c^2} \cos (\phi )} \, d\phi =\frac{2 \pi }{\sqrt{a^2-b^2-c^2}}$$
which holds for $a^2-b^2-c^2>0$
Making the "standard" substitution $\theta \to 2 \tan ^{-1}(t)$, $\text{d$\theta $}=\frac{2 \text{dt}}{t^2+1}$ and splitting the integral into the two parts from $0$ to $\pi$ and form $\pi$ to $2 \pi$ gives the complete integration range in to from $-\infty$ to $\infty$.
We have
$$\cos (\theta )=\cos ^2\left(\frac{\theta }{2}\right)-\sin ^2\left(\frac{\theta }{2}\right)=\left(1-t^2\right) \cos ^2\left(\frac{\theta }{2}\right)$$
$$\sin (\theta )=2 \sin \left(\frac{\theta }{2}\right) \cos \left(\frac{\theta }{2}\right)=2 t \cos ^2\left(\frac{\theta }{2}\right)$$
$$\frac{1}{\cos ^2\left(\frac{\theta }{2}\right)}=t^2+1$$
The integral becomes
$$2 \int_{-\infty }^{\infty } \frac{1}{a \left(t^2+1\right)+b \left(1-t^2\right)+2 c t} \, dt$$
Supplementing the square, shifting the integration varibale (this makes no dfference in our infnte interval) and extracting factors gives finally
$$\frac{\int_{-\infty }^{\infty } \frac{2}{v^2+1} \, dv}{\sqrt{a^2-b^2-c^2}}=\frac{2 \pi }{\sqrt{a^2-b^2-c^2}}$$
Comment: you lost me half way but this looks like an elegant way of solving it
Comment: See my 2nd EDIT
Comment: One sort of shortcut: periodicity and the angle sum formula (amongst other things) tell you that $\int_0^{2\pi} f(a+b\cos\theta+c\sin\theta)\,d\theta = \int_0^{2\pi} f(a+\sqrt{b^2+c^2}\cos\phi)\,d\phi$, and playing around with the homogeneity in $a,b,c$ means that the only integral you really need to compute is $\int_0^{2\pi}\frac{1}{1+\varepsilon \cos \psi}\,d\psi$ for $|\varepsilon|<1$.
Comment: @πr8  You are right. This was originally in my text. I have dropped it for brevity, but have now reinserted it.


python class empty dataframe

Question: The purpose of this script is:
•   Read a group of csv files.
•   Scrape the date and extract some features out of it.
•   Merge these csv files into a single data frame.
•   Import the final data frame into another class and print it.
Here is the code:
import pandas as pd
import os

class DataSource:
    def __init__(self):
        self.dfs = []
        self.final = pd.DataFrame()
        self.names = ['Date', 'Time', 'open', 'high', 'low', 'close', 'Volume']
        self.directory = os.chdir(r"C:\Users\Sayed\Desktop\forex")

    def merge(self):
        for file in os.listdir(self.directory):
            df = pd.read_csv(file, names=self.names,
                             parse_dates={'Release Date': ['Date', 'Time']})
            self.dfs.append(df)

        self.final = pd.concat(self.dfs, axis=0)
        self.final = self.final[['Release Date', 'open', 'high', 'low', 'close']]
        print(self.final.head())
        return self.final

class test():
    def __init__(self):
        self.df = DataSource().final

    def print(self):
        return print(self.df)

x = test()
x.print()

Here is the output:
Empty DataFrame

Columns: []

Index: []

Comment: It never calls `merge`.
Answer: You should call function to create something. Try this one.
class test():
def __init__(self):
    self.df = DataSource(). merge()

python class empty dataframe


how to read from and write to a csv file using csv module

Question: import csv

with open("C:\\Users\\ki386179\\Desktop\\output.csv","r") as f:
    reader = csv.reader(f)
    for row in reader:
        if 'india' in row:
            pass
        if 'india' not in row:
            with open("C:\\Users\\ki386179\\Desktop\\output.csv","w") as f:
                writer = csv.writer(f)
                writer.writerow('india')

I am trying to achieve something like this , to check for a particular value in a particular column  and if not write to it.
Comment: I'm guessing your problem may be you have 2 variables f. Also you're trying to write to file you have open
Comment: What I meant by **exactly** is that you edit your question, providing sample initial state of the `output.csv` file and expected final state of the file
Comment: "to achieve something like this" - please provide what **exactly** you expect
Comment: Hi @JanStránský  Thanks for your response ,  I have a string to check in the first column of a csv file,  if it is there , i want to do nothing if it is not then i want to write at the end of the first column. all using csv modlue .. ,
Comment: Code which doesn't do what you want is a poor way of explaining what you do want anyway.
Answer: You can't write to a file whilst you are in the middle of reading from it. Also, surely you don't want to require every line to contain the string, like your current logic does?
I'm guessing you want to add one line at the end if none of the lines matched:
import csv

seen_string = False

with open("C:\\Users\\ki386179\\Desktop\\output.csv","r") as f:
    reader = csv.reader(f)
    for row in reader:
        if 'india' in row:
            seen_string = True
            break

if not seen_string:
    # Notice append mode; "a" not "w"
    with open("C:\\Users\\ki386179\\Desktop\\output.csv","a") as f1:
        # Noice this one is f1
        writer = csv.writer(f1)
        writer.writerow('india')

Maybe notice also that in looks for a substring; if the file contains e.g. amerindian" the code will regard that as a match. Check for string equality with == instead if that's what you want.
Answer: You can use r+ mode for both reading and writing. Although it is difficult to understand what you are trying to achieve here, an example code that can do what you're probably trying to achieve is shown below. I put the above code in a script india.py and made it executable (chmod +x india.py)
#!/usr/bin/env python

import sys
from csv import reader, writer

with open(sys.argv[1], "r+") as f:
    for row in reader(f):
        if "india" in row:
            break
    else:
        writer(f).writerow("india")

A test run
$ cat test_write.csv
us,canada,mexico
france,germany,norway
brazil,argentina,colombia
china,japan,korea
$ ./india.py test_write.csv
$ cat test_write.csv
us,canada,mexico
france,germany,norway
brazil,argentina,colombia
china,japan,korea
i,n,d,i,a


How to test right-skewed distribution hypothesis?

Question: Statistics is new to me. My dataset has 7000 incidents that were processed within x number of days. I took a sample of 400 from the population:
ID      closedindays"
"1"     2
"2"     27
"3"     64
"4"     2
"5"     16
"6"     5
"7"     4
"8"     7
"9"     4
"10"    1
"11"    35
"12"    1
"13"    2
"14"    1
"15"    33
"16"    22
"17"    6
"18"    6
"19"    27
"20"    1
"21"    0
"22"    2
"23"    0
"24"    16
"25"    1
"26"    10
"27"    1
"28"    2
"29"    16
"30"    0
"31"    4
"32"    9
"33"    0
"34"    16
"35"    66
"36"    1
"37"    0
"38"    11
"39"    9
"40"    25
"41"    5
"42"    7
"43"    70
"44"    0
"45"    7
"46"    67
"47"    10
"48"    74
"49"    0
"50"    1
"51"    7
"52"    17
"53"    14
"54"    6
"55"    6
"56"    11
"57"    2
"58"    14
"59"    4
"60"    14
"61"    2
"62"    97
"63"    0
"64"    17
"65"    3
"66"    4
"67"    3
"68"    2
"69"    0
"70"    6
"71"    7
"72"    3
"73"    8
"74"    58
"75"    13
"76"    53
"77"    3
"78"    0
"79"    1
"80"    9
"81"    1
"82"    1
"83"    0
"84"    45
"85"    1
"86"    14
"87"    4
"88"    4
"89"    6
"90"    1
"91"    0
"92"    0
"93"    3
"94"    1
"95"    0
"96"    7
"97"    1
"98"    4
"99"    5
"100"   4
"101"   13
"102"   1
"103"   66
"104"   0
"105"   3
"106"   0
"107"   50
"108"   13
"109"   36
"110"   2
"111"   3
"112"   0
"113"   50
"114"   35
"115"   57
"116"   0
"117"   4
"118"   1
"119"   1
"120"   3
"121"   0
"122"   4
"123"   20
"124"   16
"125"   53
"126"   4
"127"   9
"128"   4
"129"   50
"130"   51
"131"   0
"132"   6
"133"   3
"134"   58
"135"   3
"136"   1
"137"   1
"138"   4
"139"   66
"140"   0
"141"   4
"142"   1
"143"   1
"144"   16
"145"   11
"146"   1
"147"   9
"148"   12
"149"   0
"150"   1
"151"   7
"152"   1
"153"   17
"154"   2
"155"   1
"156"   12
"157"   0
"158"   5
"159"   6
"160"   13
"161"   9
"162"   5
"163"   12
"164"   2
"165"   0
"166"   1
"167"   0
"168"   1
"169"   3
"170"   1
"171"   1
"172"   0
"173"   16
"174"   9
"175"   16
"176"   1
"177"   3
"178"   1
"179"   2
"180"   4
"181"   5
"182"   55
"183"   14
"184"   49
"185"   2
"186"   63
"187"   0
"188"   5
"189"   3
"190"   51
"191"   50
"192"   11
"193"   1
"194"   17
"195"   65
"196"   26
"197"   26
"198"   1
"199"   6
"200"   0
"201"   3
"202"   8
"203"   2
"204"   18
"205"   0
"206"   2
"207"   1
"208"   0
"209"   0
"210"   1
"211"   53
"212"   10
"213"   2
"214"   11
"215"   0
"216"   8
"217"   2
"218"   0
"219"   11
"220"   1
"221"   1
"222"   5
"223"   0
"224"   6
"225"   3
"226"   1
"227"   17
"228"   2
"229"   1
"230"   36
"231"   50
"232"   1
"233"   2
"234"   1
"235"   31
"236"   3
"237"   31
"238"   1
"239"   0
"240"   70
"241"   13
"242"   1
"243"   6
"244"   0
"245"   8
"246"   0
"247"   0
"248"   5
"249"   5
"250"   66
"251"   1
"252"   12
"253"   5
"254"   17
"255"   1
"256"   0
"257"   9
"258"   2
"259"   5
"260"   1
"261"   1
"262"   0
"263"   5
"264"   15
"265"   0
"266"   0
"267"   3
"268"   13
"269"   0
"270"   1
"271"   1
"272"   48
"273"   46
"274"   1
"275"   1
"276"   11
"277"   59
"278"   0
"279"   0
"280"   50
"281"   6
"282"   1
"283"   0
"284"   1
"285"   3
"286"   0
"287"   34
"288"   50
"289"   70
"290"   116
"291"   15
"292"   31
"293"   153
"294"   3
"295"   1
"296"   7
"297"   6
"298"   9
"299"   6
"300"   4
"301"   13
"302"   8
"303"   1
"304"   4
"305"   7
"306"   11
"307"   14
"308"   8
"309"   1
"310"   12
"311"   7
"312"   0
"313"   1
"314"   66
"315"   52
"316"   21
"317"   1
"318"   2
"319"   5
"320"   26
"321"   1
"322"   2
"323"   30
"324"   18
"325"   9
"326"   26
"327"   10
"328"   24
"329"   0
"330"   0
"331"   1
"332"   1
"333"   0
"334"   0
"335"   1
"336"   7
"337"   2
"338"   20
"339"   5
"340"   6
"341"   1
"342"   13
"343"   23
"344"   5
"345"   69
"346"   1
"347"   8
"348"   1
"349"   3
"350"   1
"351"   35
"352"   1
"353"   10
"354"   17
"355"   64
"356"   6
"357"   7
"358"   41
"359"   0
"360"   26
"361"   1
"362"   9
"363"   35
"364"   1
"365"   5
"366"   7
"367"   65
"368"   4
"369"   2
"370"   0
"371"   62
"372"   5
"373"   7
"374"   1
"375"   4
"376"   3
"377"   0
"378"   70
"379"   25
"380"   5
"381"   1
"382"   5
"383"   10
"384"   2
"385"   51
"386"   0
"387"   1
"388"   4
"389"   72
"390"   73
"391"   8
"392"   3
"393"   2
"394"   70
"395"   10
"396"   3
"397"   2
"398"   2
"399"   26
"400"   56

The population and sample seems to have a right-skewed distribution.
What is my hypothesis?
My hypothesis is that tickets are processed within 14 days on average. I made the following hypothesis:
H0: <= 14
H1: > 14
What is the problem?
The problem is that my data is not normally distributed. Because of this I don't think i can do the one tailed Student's t-test.
The Wilcoxon signed rank test seems to be a option. But this one checks on the median.
How can i test my hypothesis on the mean?
Comment: You have some zeros there, presumably if daily date notified == daily date closed. You could defensibly consider working with log(days + 1) or log(days + 0.5) as a check on working with data as they arrive.
Comment: With $n \approx 7000$ and only a couple of outliers beyond 70 (if I scanned your data accurately) you might be able to use a one-sample t test. // Or you might use a bootstrap procedure as [here](https://stats.stackexchange.com/questions/92542/how-to-perform-a-bootstrap-test-to-compare-the-means-of-two-samples/92553#92553).
Answer: Robustness of t Tests for Huge Badly-Skewed Samples
Failing to reject when null hypothesis is true. I won't use your data, leaving that for you to explore.
However, consider a sample of size $n = 7000$ simulated using R from a (highly skewed) exponential population with $\mu=14.$
set.seed(2020)
x = rexp(7000, 1/14)
summary(x)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
  0.00208   4.19694  10.06145  14.25631  19.42518 126.88984

boxplot(x, horizontal=T, col="skyblue2")
  abline(v=mean(x), col="red", lwd=2)

Now I do a t test of $H_0: \mu = 14$ against
$H_a: \mu \ne 14.$ Does the t test fail to reject, which would be the correct result?
t.test(x, mu=14)

        One Sample t-test

data:  x
t = 1.5181, df = 6999, p-value = 0.129
alternative hypothesis: true mean is not equal to 14
95 percent confidence interval:
  13.92534 14.58729
sample estimates:
mean of x
 14.25631

Fails to reject and the confidence interval includes $14.$
Rejecting when null hypothesis is false. Now consider a sample of the same size from an exponential population with $\mu = 14.5.$ Again testing $H_0: \mu = 14$ against
$H_a: \mu \ne 14,$ one would hope to reject $H_0.$
set.seed(428)
y = rexp(7000, 1/14.5)
summary(y)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
  0.00473   4.26687  10.00742  14.45444  19.99045 139.90676

t.test(y, mu=14)$p.val
[1] 0.008786323

Rejects $H_0$ with P-value $0.0088 < .05.$
Summary. My simulated exponential samples may not be as unruly
as your real data. And two tests doesn't provide a lot
of evidence. However, experience has shown that t tests
perform well even with skewed data when sample sizes
are very large.
Means of huge exponential samples are nearly normal With an exponential distribution I can show you that
a sample mean of $n=7000$ observations is nearly normally
distributed. Here is a simulation to show this using 100,000 averages. (The theory isn't difficult because then average of 7000 exponential random variables is a gamma random variable with shape parameter 7000, which is very nearly normal---according
to the Central Limit Theorem.)
a = replicate(10^5, mean(rexp(7000, 1/14)))
hist(a, br=40, prob=T, col="skyblue2")
 curve(dnorm(x, mean(a), sd(a)), add=T, col="red", lwd=2)

The red curve through the histogram of sample means is
the best-fitting normal distribution. Clearly averages of
7000 exponential observations are nearly normal.


How can I copy files recursively without overwriting duplicate file names?

Question: Let's say I have files nested in subdirectories with potentially duplicate file names. I want to copy all files to a new directory but prevent overwriting AND preserve filenames (mostly).
The following does not work because it overwrites duplicate filenames:
find /SourceDir/. -type f -exec cp -pv \{\} /DestDir/ \;

Adding noclobber (cp -n) doesn't help either because duplicates are just skipped.
Current File Structure:
SourceDir
--SubdirA
----File1.gif
---- ...
----File1000.jpg
--SubdirB
----File1.gif
---- ...
----File1000.png
...
--SubdirZ
----SubdirAA
------File1.sh
------ ...
------File1000.jpg

Desired File Structure:
DestDir
--File1.gif
--File1_1.gif   <-- original name was `File1.gif` but this already existed
--File2.jpg
--File2.gif     <-- `File2.jpg` already exists, but not `File2.gif`
--File3.gif
--File3_1.gif
--File4.jpg
--File4_1.jpg
--File4_2.jpg   <-- original name was `File4.jpg`, but `File4_1.jpg` already existed too.
-- ...
--File1000.png

I do not want to rename every file. And I don't want to give arbitrary hashes to those I need to duplicate. What do you recommend?
I'm on a Mac, so Linux commands are all fair game.
Answer: Here is one solution.
#!/bin/bash

SourceDir=".";
DestDir="../dest";

cd ${SourceDir}
find .  -type f |
while read x
do
  bn=`basename $x`;
  if [ -f "${DestDir}/$bn" ]
  then
    for i in {1..9999}
    do
        if [ ! -f "${DestDir}/${bn%.*}_${i}.${bn##*.}" ]
        then
            echo "Next free file extension is no $i";
            bn="${DestDir}/${bn%.*}_${i}.${bn##*.}"
            break;
        fi
    done
  fi
  echo "copy file $x to ${DestDir}/$bn";
  cp -p "$x" "${DestDir}/$bn";
 done

Please let me know if that works for you.
Comment: sorry, i will change it , so that it also copy duplicates
Comment: @Ryan , if have change my Answer. so it extend the filename file_[1..9999] if a file exists
Comment: change thise line **if [ -f ${DestDir}/$bn ]** to **if [ -f "${DestDir}/$bn" ]**. So is it possible that you have file with a space in the filename
Comment: yes, it only (i hope) one line more to change **cp -p "$x" "${DestDir}/$bn";** . I have change both lines in my Answer
Comment: Cool. Thanks. The `if [ ! -f ../dest/$bn ]` line returns `too many arguments`. Can you suggest an alternative?
Comment: did you mean the find command. you can change the first line to **find SourceDir -name *.gif -type f |** to get only gif files
Comment: Also, how does this handle duplicate names? I don't see where duplicates are appended a `_1` (where `file.jpg` becomes `file_1.jpg` if `file.jpg` already exists).
Comment: Re: did you mean the find command...  I have your script above saved as a shell script. It returns `./img-cp.sh: line 7: [: too many arguments`. And line 7 (in my script) is `if [ ! -f ../dest/$bn ]`. It could be referencing an earlier problem but I'm not proficient enough in shell to know where to look.
Comment: Looks good, except I still get "too many arguments" at the same place. I think name-based exclusions, and running it more than once could create even more duplicates. Can you suggest an alternative to your `if [ ! -f ...` line?
Comment: That's it. I'm getting similar errors on `cp` usage for copy as well. Can you change everywhere to allow spaces in file names?
Comment: Thanks so much! Great answer. I hope it is useful to others as well.


sorting strings using bubblesort in java

Question: I tried sorting strings using bubblesort, but I dont know whether it makes any sense but can someone just help me figure out how to sort strings and let me know if my logic is correct? i have converted the strings to character just to check if they are in alphabetical order..eg app ban acc will be sorted to acc app and ban..can anyone give the logic to this problem.
import java.io.*;
import java.util.*;
class sort
{
    public static void main(String args[])throws IOException
    {

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        System.out.println("enter the strings");
        String str=br.readLine();
        StringTokenizer st=new StringTokenizer(str,",");
        String s1=st.nextToken();
        String s2=st.nextToken();
        String s3=st.nextToken();
        char ch1[]=s1.toCharArray();
        char ch2[]=s2.toCharArray();
        char ch3[]=s3.toCharArray();

        if ((ch1[0]<ch2[0])&&(ch1[0]<ch3[0])&&(ch2[0]<ch3[0]))
            for(int i=0;i<4;i++)
            {
                System.out.println(+ch1[i]);
                System.out.println(+ch2[i]);
                System.out.println(+ch3[i]);

            }
        else if((ch2[0]<ch1[0]&&ch2[0]<ch3[0]&&ch1[0]<ch3[0]) )
            for(int i=0;i<4;i++)
            {
                System.out.println(+ch2[i]);
                System.out.println(+ch1[i]);
                System.out.println(+ch3[i]);
            }
        else if((ch3[0]<ch1[0])&&(ch3[0]<ch2[0])&&ch1[0]<ch2[0])
            for(int i=0;i<4;i++)
            {
                System.out.println(+ch3[i]);
                System.out.println(+ch1[i]);
                System.out.println(+ch2[i]);
            }
    }
}

Comment: One ugly looking code.
What are you trying to sort?
Comment: MakesNoSenseLogicalException.
Comment: Then use `java.util.Arrays.sort()`. Boom, one line, you're done.
Comment: Is this a homework task?
Comment: What's that? Are you really following a right method to sort strings in your program? I don't think so?
Comment: i am actually newbie :-(,anyways i want to sort strings in alphabetical order
Comment: In general, a bubble sort requires two nested loops.  There are ways to do it with one loop, but they're not straight-forward.  And you can compare Java strings "lexicographically" with `compareTo` -- no need to extract and compare individual characters.  As to the rest of it, I'll have to say it makes little sense.  There's a Wikipedia article on the topic of [bubble sort](http://en.wikipedia.org/wiki/Bubble_sort) that you should maybe study.
Comment: (But at least I give you kudos for starting with something simple vs jumping into iPhone programming or some such by simply modifying examples.  Far too many folks show up here doing that, and they're usually hopelessly lost.)
Comment: thanks..i wanna learn stuff by doing,i dont care if i make any mistakes...kudos to you too..
Answer:
Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better. Wikipedia

The following is the sort-cut way to do so.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

final public class Main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter the strings:->");
        String str=br.readLine();

        String strArr[]=str.split(" ");//your sentence will be split into words.
        Arrays.sort(strArr);

        for(int i=0;i<strArr.length;i++)
        {
            System.out.println(strArr[i]);
        }
    }
}

If you wish, you can apply your own logic as follows.
final public class Main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter the strings:->");
        String str=br.readLine();

        String strArr[]=str.split(" ");

        String temp;

        for(int i = 0; i<strArr.length - 1; i++)
        {
            for(int j = 0; j<strArr.length - 1; j++)
            {
                if(strArr[j].compareTo(strArr[j+1]) > 0)
                {
                    temp = strArr[j];
                    strArr[j] = strArr[j+1];
                    strArr[j+1] = temp;
                }
            }
        }

        for(int i=0;i<strArr.length;i++)
        {
            System.out.println(strArr[i]);
        }
    }
}

In both the cases, I have assumed spaces as word separator and not commas , that you're using in your example.
Answer: First you need to choose how do you want to sort strings ?
is it by length ? is it by alpha order ?
After you choose the appropriated method, you just need to sync it for the existing sorting method of bubblesort.
public static int[] bubble(String[] str_arr) {
    for (int i = 0, temp; i < str_arr.length-1; i++) {
        for(int j = 0; j < str_arr.length-1; j++) {
             if (str_arr[j] < str_arr[j+1]) {
                    temp = str_arr[j];
                    str_arr[j] = str_arr[j+1];
                    str_arr[j+1] = temp;
             }
        }
    }
    return str_arr;
}

As i mentions theres couple of ways of comparing strings:

Length - length of a string
Lexicographically - explanation here

If we want to use one of the two method mentioned above, we should change the line:
if (str_arr[j] < str_arr[j+1])
to
if (str_arr[j].length < str_arr[j+1].length)
Or for the lexicographically order we will use:
if (str_arr[j].compareTo(str_arr[j+1].length) < 0)
compareTo is a java String method that checking lexicog.. order.
it returnes:

0 - strings are identical.
positive number - first string is bigger then second string.
negative number - first string is smaller then second string.
Answer: String implements interface Comparable (so overrides compareTo() method), thus you can compare two strings (>,<,>=,<=). That's why you don't have to compare every char element by element. Not worth trying even.
The solution: put Strings into array:
String[] stringArray = new String[]{"element1","element2"};

and then use default bubble-sort algorithm:
    for (int x = 1; x < stringArray.length; x++) {
        for (int y = 0; y < stringArray.length - x; y++) {
            if (stringArray[y].compareTo(stringArray[y + 1]) > 0) {
                temp = stringArray[y];
                stringArray[y] = stringArray[y + 1];
                stringArray[y + 1] = temp;

            }
        }
    }

and you should receive sorted array.


WPF - Freezable in a style of a button not inheriting DataContext

Question: I am modeling an attached command pattern after the AttachedCommandBehavior library here. My button looks like this:
<Button>
    <Button.Style>

    </Button.Style>
</Button>

Everything works great, but when the setter on the Behavior is executed, the Command is null.
Behavior is a Freezable, and Behaviors is a FreezableCollection<Behavior>. It just doesn't seem to be inheriting the DataContext from the Button.
On the other hand, this works correctly:
<Button>
    <vms:Attached.Behaviors>
        <vms:Behavior Event="Click" Command="{Binding ClickCommand}" />
    </vms:Attached.Behaviors>
</Button>

Unfortunately I can't do it this way, because I need to target generated ListViewItems using ItemContainerStyle.
Is there some way to get the DataContext in the Style?
Comment: your link isn't valid.  Can you edit and fix, please?
Comment: I'm not really following how your `vms:Attached.Behaviors` maps to that library. I can only find stuff like `CommandBehaviorCollection.Behaviors` and so on so I'm unable reproduce
Comment: It is based on that library, but not the same. vm:Attached.Behaviors is a Behaviors (maps to CommandBehaviorCollection.Behaviors), but it is not a read-only dependency property.
Answer: The Attached Command Behavior library is the germ of the idea that became Blend Behaviors.  The Blend Behaviors are much more powerful and standardized and so I recommend you switch to using them.  But whether you are using Attached Command Behavior or Blend Behaviors, the problem is essential the same: they don't work as expected when trying to set them using a style.  I've solved this problem for Blend Behaviors with full support for binding in this StackOverflow answer:

How to add a Blend Behavior in a Style Setter

Without testing it, I guess you have to move the ACB behavior to a resource marked with x:Shared="False" in order to get the binding to work.
Comment: This looks very promising, I'll take a look at it.
Comment: This worked for the button example above, but unfortunately still did not work for a ListView's `ItemContainerStyle`. Any idea how it could work for that?
Comment: In an items control the binding will be evaluated in context of the item, not its parent so you either have to have your command in the items context or use relative source or element name binding to get to a different context that has one.
Comment: Actually the command for the item _was_ null, and everything seems to be working well now.
Answer: I had the same problem, and using RelativeSource did the trick.  I'll show you my before and after code...
Before: (This DIDN'T work)
<DataTemplate x:Key="MenuNodeWithChildrenTemplate">
    <StackPanel Orientation="Horizontal"
            behaviors:EventCommand.CommandToRun="{Binding OpenMenuItem}"
            behaviors:EventCommand.EventName="MouseLeftButtonUp">

    </StackPanel>
</DataTemplate>

After: (This DOES work)
<DataTemplate x:Key="MenuNodeWithChildrenTemplate">
    <StackPanel Orientation="Horizontal"
            behaviors:EventCommand.CommandToRun="{Binding Path=DataContext.OpenMenuItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}}"
            behaviors:EventCommand.EventName="MouseLeftButtonUp">

    </StackPanel>
</DataTemplate>

You'll obviously have to tweak the parameters of the Relative Source to your specific situation.  It seems that, for whatever reason, attached properties don't inherit the data context, so you have to tell if how to.


Prove that two subspaces of a vector space intersect only at 0

Question: Let $V \subset \mathbb{R}^n$ & $W \subset \mathbb{R}^m$ with set of basis $S_V=\{v_1,v_2,...,v_n\}$ and $S_W=\{w_1,w_2,...,w_m\}$.
The vector space spanned by these basis vectors is the direct sum of $V$ and $W$ with a dimension of $n+m$.
How do I prove that $V \cap W=\{0\}$?
I understand how to draw it conceptually because the only intersection that both subsets share is the zero vector. But I don't quite know how to do the proof mathematically.
Comment: How can we sum subspaces of different vector spaces ?
Comment: What definition do you use for direct sums?
Comment: Doesn't it follow directly from definition of direct sum?
Comment: Think about the dimension of the direct sum. If the intersection had anything else in it....
Comment: I gave it a shot below, any feedback would be greatly appreciated!
Answer: Thanks for the responses, everyone. This is what I came up with:
$\forall u \in \mathbb{R}^{m+n}, u=v_i \in V \lor u=w_i \in W$
Therefore, because of the definition of the direct sum and subspaces, we know that $u_i \neq v_i \land u_i \neq w_i$ unless $u_i=0$ therefore $V \cap W = \{0\}$.
Comment: $u$ is not equal to $v_i$ or $w_i$ but instead a linear combination of the $v_i, w_i$. Put differently y, you could write $u = v + w$, where $v \in V, w \ in W$

Assume that some vector $v$ is in both $V$ and $W$; try and use the linear independence of $\{v_1, …, v_n, w_1, …, w_m\}$ to conclude that $v = 0$.
Comment: Not sure if this is correct though, feedback would be greatly appreciated!
Answer: Since $V$ and $W$ are subspaces of different vector spaces, so $V\cap W=\emptyset$. But we can try to make the question meaningful by introducing the maps
\begin{align}
F\colon V\subset\mathbf{R}^m&\to\mathbf{R}^{m+n}\\
v&\mapsto(v,\underbrace{0,\ldots,0}_{n\text{ copies}})
\end{align}
and
\begin{align}
G\colon W\subset\mathbf{R}^n&\to\mathbf{R}^{m+n}\\
w&\mapsto(\underbrace{0,\ldots,0}_{m\text{ copies}},w)
\end{align}
$F$ and $G$ are injective and if we define $V':=F(V)\subset\mathbf{R}^{n+m}$ and $W':=G(W)\subset\mathbf{R}^{n+m}$, the maps $V\ni v\mapsto F(v)\in V'$ and $W\ni w\mapsto G(w)\in W'$ are vector space isomorphisms. You can easily prove that $V'\cap W'=\{0\}$ and if $V$ and $W$ span $\mathbf{R}^m$ and $\mathbf{R}^n$, respectively, then $\mathbf{R}^{n+m}=V'\oplus W'$.


saving strings that are 'connected' and reading them and their 'connected'

Question: This is something I am not at all familiar with.
I want to try to make a simple form with 4 edit boxes, 2 at the top, 2 at the bottom, and a button. Basically what I want to do is type a couple of things in the top two boxes that are related to each other.
When I have them both filled in I click on the button and it saves this information in a database, preferable an external file (doesn't have to be text, I think it would be better if not). So I can do that a couple of times. Saving from the edit fields into a database.
Then when I type one of the words saved in one of the edit fields at the bottom it automatically types the other word in the last edit field. The form should remember to connect to the database every time it's opened so that when I open it another time I can still work the edit fields.
Can anyone advise me on how to do this?
Comment: I think you need to narrow down your question, in its current form it reads like "how do I program", and I'm not sure SO is the best medium for general teaching. What specifically has you stumped in this project right now, if you can narrow it down to a single question to begin with, that would probably give you something to start with.
Comment: Question is too broad, so I've voted to close it. Please ask more specific questions. Among the things you seem to want to know are how to connect to a database and how to look something up in a database. Apparently, you already know how to store things in a database (although I'm not sure how, since you don't know how to connect to it yet). Ask about each of those things separately. Be sure to mention what database you're using. (If you don't know that, then ask for advice on choosing a database, too.) Be sure to search prior questions before asking new ones.
Answer: What you are looking for is known as a dictionary, if I understand you correctly.  In other languages it is known as an associative array or sometimes a hash.
You are going to want a modern version of Delphi, I'd guess 2010 or XE.  If you can't access those then you'd need a 3rd party library, or a home grown based off a TStringList. In fact TStringList can operate in a dictionary like mode but it's a bit clunky.
You declare the dictionary as follows:
dict: TDictionary<string,string>;

You can add do it as follows:
dict.Add(box1.Text, box2.Text);

The first parameter is the key. The second is the value. Think of this as an array but indexed with a string rather than an integer.
If you want to recover a value then you use:
dict[key];

In your case you would write:
box4.Text := dict[box3.Text];

If you want to save to a file then you would iterate over the dict:
var
  item: TPair<string,string>;
...
for item in dict do
  AddToTextFile(item.Key, item.Value);

I've ignored all error handling issues, dealing with adding keys that already exist, asking for keys that are not in the dict, and so on. But this should give you a flavour.
I'd recommend reading up on associative arrays if you aren't already familiar with them. I'm sure there will be a page on Wikipedia and you would do worse than read an tutorial on Python which is sure to cover them – the issues are really the same no matter what language you consider.
Comment: As a curiosity, I thought one used the EM dash in English, not the EN dash? As a UK citizen, what is your experience in this matter?
Comment: @Andreas em-dash is too long for that context, it's en-dash that you want, ALT+0150!
Comment: @David: OK. In Sweden we only use EN, so maybe EM is a US thing.
Comment: @Andreas I mean, I think the grammar police would do me for using en-dash there, but I prefer it!!
Comment: @David: Yes, I would also guess that, for I have always thought one does use EM in English (in contrast to the Swedish rules). Still, I am glad you don't use the hyphen-minus as most people do...
Comment: @Andreas I hate hypen there too. I'm so glad for Unicode Delphi which means I can now safely use en-dash in my app's error messages!
Comment: Me too. Actually, as a mathematician, I also use U+2212 MINUS SIGN (−) a lot, too.
Comment: @Andreas now that's verging on OCD! Actually, as a mathematician you should be setting it in LaTeX, using the plain minus sign and letting Donald and Leslie do the rest for you!! I used to be a mathematician too!
Comment: (Well, there is HTML, Delphi code etc. where TeX isn't an option...)
Comment: @ David Heffernan -  thx, thats actually very interesting. What do you recomend is you want 4 column of information, 2 string 2 integer?
Comment: I'm just thinking ahead, possible expanding the database?
Comment: you thinking of one key and three values? That's easy using generics: TDictionary
Comment: More like 2 keys and each have two pieces of information. one string and one integer. When I lookup in the the Tdictionary for the string of the first key, i can get the rest of the values as well. but I dont think that is possible in dictionary. So maybe i need a different type of database.
Comment: you need to work out what your question really is!


no such table: tbcarro

Question: Após seguir alguns exemplos, estou com duvida sobre o seguinte erro:
11-24 20:49:14.803 18215-18215/tiburski.rg.cadastrocarro E/SQLiteDatabase: Error inserting nome=ggggg modelo=ggggg placa=hhhh
android.database.sqlite.SQLiteException: no such table: tbcarro (code 1): , while compiling: INSERT INTO tbcarro(nome,modelo,placa) VALUES (?,?,?)
    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
    at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
    at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)

De acordo com alguns exemplos já criados, seguem as classes responsáveis pelo banco de dados.
public class DataModal {

    private static final String DB_NOME = "carro.db";
    private static final int DB_VERSAO = 4;

    private static final String TBL_CARRO = "tbcarro";
    private static final String COLUNA_ID = "_id";
    private static final String COLUNA_NOME = "nome";
    private static final String COLUNA_PLACA = "placa";
    private static final String COLUNA_MODELO = "modelo";

    public static final String[] COLUNAS = {COLUNA_ID, COLUNA_NOME, COLUNA_PLACA, COLUNA_MODELO};

    public static String criarTabela() {
        String CREATE_TABLE = " CREATE TABLE IF NOT EXISTS "+ getTblCarro() +" ( "
                + getColunaId() +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + getColunaNome() +" VARCHAR NOT NULL, "
                + getColunaPlaca() +" VARCHAR UNSIGNED NULL, "
                + getColunaModelo() +" VARCHAR UNSIGNED NULL ); ";
        return CREATE_TABLE;
    }

    public static String getDbNome() {
        return DB_NOME;
    }

    public static int getDbVersao() {
        return DB_VERSAO;
    }

    public static String getTblCarro() {
        return TBL_CARRO;
    }

    public static String getColunaId() {
        return COLUNA_ID;
    }

    public static String getColunaNome() {
        return COLUNA_NOME;
    }

    public static String getColunaPlaca() {
        return COLUNA_PLACA;
    }

    public static String getColunaModelo() {
        return COLUNA_MODELO;
    }

public class DataSource extends SQLiteOpenHelper {

    private SQLiteDatabase mDb;

    public DataSource(Context context) {
        super(context, DataModal.getDbNome(), null, DataModal.getDbVersao());
        mDb = this.getReadableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(DataModal.criarTabela());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        onCreate(sqLiteDatabase);
    }
}

Outros exemplos com o código basicamente parecidos funcionam corretamente. Entretanto, neste exemplo está ocorrendo o erro mencionado. Poderiam me apontar aonde esta a falha ou as falhas no código?
Mais um ponto importante é que neste exemplo, na classe de persistência, inseri um novo método, o qual ainda não havia utilizado até então.
private Context mContext;
    private static Persistencia mInstance;
    private static SQLiteDatabase mDb;

    public static Persistencia getmInstance(Context context) {
        if (mInstance == null) {
            synchronized (Persistencia.class) {
                if (mInstance == null) {
                    mInstance = new Persistencia(context);
                    mDb = context.openOrCreateDatabase(DataModal.getDbNome(), Context.MODE_PRIVATE, null);
                }
            }
        }
        return mInstance;
    }

    private Persistencia(Context context) {
        this.mContext = context;
    }

Comment: Tenta utilizar um Log.i() depois de gerar os SQL e ve exatamente o que esta sendo executado e posta aqui, as vezes voce ta com algum erro de concatenacao que no olho nu esta passando batido. Consegue postar aqui exatamente qual SQL ta sendo executado?
Answer: segundo o link ao lado -> https://stackoverflow.com/questions/6554269/android-sqlite-no-such-table-error o erro é o seguinte:
existe uma versão antiga do banco de dados em seu dispositivo que faz o app achar que não existe o banco de dados. se for isso mesmo, a solução é desinstalar e reinstalar do zero o banco de dados.
Comment: Sobre a duvida que havia postado, segue link o qual me auxiliou, e que pode vir a auxiliar mais pessoas -> https://androiddevbr.wordpress.com/2013/02/19/sqlite-banco-de-dados-no-android/

no such table: tbcarro


Dynamic property selector lambda function

Question: I'm trying to build the property selector expression with the type and property name given. i.e. t => t.PropertyName.
The following code compiles just fine but results in empty value. Can someone please point to an error in the code?
    public static Expression<Func<T,object>> CreatePropSelectorExpression(string propName) where T:class,new()
    {
    var temp = Activator.CreateInstance<T>();
    ParameterExpression t = Expression.Parameter(typeof(T),"t");
    MemberExpression member = Expression.PropertyOrField(Expression.Constant(temp),propName);
    return Expression.Lambda<Func<T,object>>(member,t);
    }

Thanks in advance
Comment: Don't bother. Already found the solution.
Needed to use the member expression instead of temporary variable
Answer: You don't actually need to create an instance of your object T, you're just creating some expression trees.  It all boils down to this really:
Expression<Func<T, object>> CreatePropSelectorExpression<T>(string propertyName)
{
    var parameter = Expression.Parameter(typeof(T));
    var body = Expression.Convert(Expression.PropertyOrField(parameter, propertyName), typeof(object));
    return Expression.Lambda<Func<T, object>>(body, parameter);
}

Comment: The convert method ensures that the expression is of a certain type. It boils down to being a cast in the end. It will be required if the property type is a `ValueType` since it will turn into a boxing operation. Though when building expressions, it's best to generate expressions of the expected type whenever possible.
Comment: what is the purpose of Expression.Convert()? It looks like it's working with just: var body = Expression.PropertyOrField(parameter, propertyName);
Comment: Good but could you provide a nested selector with ``IEnumerable propertyNames`` as arguments
Answer: A nested version
static Expression<Func<R, O>>
CreatePropSelectorExpression<R,O>(IEnumerable<string> propertyName)
{
    ParameterExpression parameter = Expression.Parameter(typeof(R));
    Expression selector = propertyName
         .Aggregate((Expression)parameter,
               (a, name) => Expression.PropertyOrField(a, name));
    return Expression.Lambda<Func<R,O>>(selector, parameter);
}