What is wrong with this proof (that all vector bundles of the same rank are isomorphic)?

Question: Suppose I have two vector bundles $E \rightarrow M, E' \rightarrow M$ of rank $k$ on a smooth manifold $M$. Let $\mathcal{E}(M), \mathcal{E'}(M)$ denote their spaces of smooth sections. We can choose some arbitrary isomorphism $\phi_p: E_p \rightarrow E'_p$ for all $p \in M$, where $E_p, E'_p$ denote the fibers above $p$.
Now we use this to define a map $\mathcal{F}: \mathcal{E}(M) \rightarrow \mathcal{E'}(M)$ as follows. For any smooth section $\sigma \in \mathcal{E}(M)$, define the section $\mathcal{F}(\sigma)$ by $\mathcal{F}(\sigma)(p) = \phi_p(\sigma(p))$. Then $\mathcal{F}$ is linear over $C^\infty(M)$, so there is a smooth bundle map $F: E \rightarrow E'$ over $M$ such that $\mathcal{F}(\sigma) = F \circ \sigma$ for all $\sigma$. Defining a map $\mathcal{F}^{-1}: \mathcal{E}'(M) \rightarrow \mathcal{E}(M)$ using $\phi_p^{-1}$, we see by the same reasoning that there is a smooth bundle map $F^{-1}: E' \rightarrow E$ which is the inverse of $F$. So the two bundles are isomorphic.
Answer: The problem is that $\mathcal{F}(\sigma)$ is not going to be a smooth section of $E'$ unless the $\phi_p$'s are "coherent".
For example, let $E\to M$ and $E'\to M$ both be the trivial line bundle $\mathbb{S}^1\times\mathbb{R}$ on the circle $\mathbb{S}^1$. Let $A=\{e^{2\pi it}\mid t\in\mathbb{Q}\}\subset\mathbb{S}^1$. If we choose our isomorphisms on the fibers to be $$\phi_p=\begin{cases}\;\;\;\;\text{id}_{\{p\}\times\mathbb{R}}\text{ if }p\in A\\ -\text{id}_{\{p\}\times\mathbb{R}}\text{ if }p\notin A\end{cases}$$
then the smooth section $\sigma:\mathbb{S}^1\to E$ given by $\sigma(p)=1$ is sent to
$$\mathcal{F}(\sigma)(p)=\begin{cases}\;\;\;\;1\text{ if }p\in A\\ -1\text{ if }p\notin A\end{cases}$$
which is not even continuous.
Answer: In addition to the problem Zev pointed out, there's further a problem with topology. Say you intend to avoid Zev's construction, so you do the following:
Since $(E,M,\pi, V)$ is a vector bundle, for every point $p \in M$ there is a neighbourhood $U\ni p$ such that $\pi^{-1}U$ is diffeomorphic to $V\times U$. Okay, so instead of just defining the isomorphism pointwise by $\phi_p$, you additionally require that it extends locally over $U$ to a smooth map between $V\times U$ and itself.
If you indeed are able to find such a map, you would have found a bundle isomorphism. But in reality it may not be possible to find such a map. In the case where $M$ is simply connected, the usual arguments can be used to show that the local definition can be extended to a well-defined global one. But when that is not the case, you can consider the example of the Möbius strip as an $\mathbf{R}$ bundle over $S^1$, and the trivial $\mathbf{R}$ bundle over $S^1$. It is clear to see that any smooth section of the Möbius strip must vanish at some point. On the other hand, there exists non-vanishing sections of the trivial bundle. So any smooth map which commutes with projection from the latter to the former must, at some point in $S^1$, fail to be surjective.


div smooth scroll animation complete callback

Question: I am using your plugin DivSmoothScroll for one of my websites.
Works very well.
I have enabled touchScrolling on it.
I need to know if there is a callback function that gets called when the user drags the div and releases it.
I have two smoothScroll divs on one page, I want to control the second div based on the drag/scroll movement done on the first div.
Please advise.
Comment: http://smoothdivscroll.com/callbacks.html
Comment: @PedroEstrada there is no callback function for animation complete in that list. I had already checked it.
My requirement is to be able to call a function when the user is dragging the scroll div and when its released.
Comment: Are you talking about mouseover and mouseout? if so, you can set up those events with jquery after the scroll is initialized. The plugin has `mouseOverRightHotSpot` so maybe that can help you.
Comment: no @PedroEstrada, I need to know if there is a callback function that gets called when the user starts dragging the div or the dragging animation gets complete. None of the callback functions mentioned in http://smoothdivscroll.com/callbacks.html cater to that need.
Answer: Very interesting question!
When you asked it, there where no such callbacks implemented in Smooth Div Scroll, but now that you mentioned it, I think they should be implemented. So that's what I have done. :-)
If you check out the repository on GitHub , you'll find that two new callbacks are implemented. Use them like this:
<code>$("#makeMeScrollable").smoothDivScroll({
    touchStopped: function(eventObj, data) {
        alert("Touch stopped");
    },
    touchMoved: function(eventObj, data) {
        alert("Touch moved");
    },
});
</code>
These callbacks just forward the callbacks that jQuery.kinetic has. Please note that they are not documented on smoothdivscroll.com (yet).
I hope you find them helpful - good luck with the scrolling!


Issue with system audio and microphone audio

Question: So I recorded audio & video with my computer ( NVidia Geforce instant replay ) of my mom singing a very deep song, completely out of her head with the guitar. I really want to save what she sang, but the problem is, the system audio that I had on almost completely blocks out what she was singing. I need to somehow remove the recorded system audio from the file and only leave the microphone's audio.. Is there any possibility to do this?
Answer: Sadly no, unless it is only on one track and you can remove it, or if your audio is on one track and system audio is on both left and right (you may be able to invert and cancel out the system audio), or if the system audio is at one frequency that you can EQ out.
Basically, once you have recorded audio, it is very difficult or impossible to remove sounds from that recording to leave your desired sounds.


Scrapping with parallelelized wget/curl command

Question: I created a script which tries all possible combinations of a hash(number) of a URL which represents a link to some social media file (video or audio) like https://www.youtube.com/watch?v={hash} or https://ok.ru/video/{number} or etc. The script runs thousands of wget commands in parallel to figure out whether the URL is valid (represents an existing media) and writes it into a log if true.
Purpose: Create a huge hashmap (hash -> title) which contains all valid links and use it offline for a full search. Why? Because I convinced that the search mechanism of almost all social networks is not full: something is skipped by complicated algorithms (depending on location etc), someones do output only limited number of occurrences. Also it is never exact search (only whole word, no special chars) etc etc. I want a stupid and guaranteed sub-string search like "grep" which searches all volume of data and never misses. Also my approach opens possibility to search by exact duration.
I convinced on practice that if the script runs in 100+ parallel instances and on several PCs at the same time it becomes very efficient and according to my measurements I need only several months to pass all combinations of URLs for a certain big social network if I have 20-25+ PCs. But I have not such resources at home.
Questions:

Where I can find such web services which provide me sufficient number of PCs with different IP for each PC for my experiment? Is AWS a good choice for this?
Is it legally dangerous to do what I want? I mean is there a threat of something more serious than just an IP ban? I do know every URL which I test is public, so there should be no problem theoretically, but I would prefer to feel safe if possible.
Comment: *"I need only several months to pass all combinations of URL's"* immediately gives a small feasibility concern  because by the time you've exhausted all hash values a portion of content will already have been deleted, invalidating the hash location and probably even more new content  will have been added.
Comment: There are about 10^19 possible combinations of youtube hash alone. To go through them all in 3 months (10^6 seconds) you need to do 10^13 checks per second. How much bandwidth do you need for that if you get at least one packet per check?
Comment: This site is for business environments. We don't give recommendations and we especially don't give legal advice.
Comment: YouTube is the hardest one that should be considered separately, because its hashes are not ascending by date. But for VK, OK, Spaces (and other primitive websites, for sure) they are ascending, so it is pretty feasible. The recently appeared items won't be counted, yes. But since the number of new items (let's say for last 6 months) is dramatically smaller than the whole size it can be easily beaten by running of the script once again from time to time with "from N=..." parameter for achieving of the latest uploaded stuff.
Comment: For instance, I tried also browser VMs, a nice one was www.onworks.net and I tested it well, but it is a browser VM which closes the session after 5 min of inactivity. If I find a similar with no limit I can open let's say 20+ tabs in a browser and run it there completely parallel on remote side.
I found also many other browser VMs. but they have isolated network inside a container which prevents accessing real internet.
Answer: Enumerating sequential IDs in order to access some hidden objects is called Insecure direct object reference (IDOR). If the objects aren't intended to be public, accessing them could be considered illegal in some jurisdictions (IANAL).
Major social platforms are well aware of IDOR and apply appropriate measures - randomized IDs, proper auth checks etc. They also don't like scrapers and apply request rate limits. I would expect that an attempt to scrape with a request rate of 100 rps would end in a few minutes with 429. I have the impression that scrappers spend most of their effort finding and managing proxies to bypass rate limit restrictions. Bypassing restrictions would definitely violate ToS and could also be considered illegal in some jurisdictions (IANAL).
From the technical point of view, the idea grossly underestimates the amount of resources needed. There are billions of sites, Google index contains hundreds of billions of documents. Even if we simplify the task to just existing YouTube videos, there are 20 billion of them. curl to a YouTube video to get a title returns about 700-800 Kbytes, which amounts to 14 PBytes for all videos. It would require 14 GBits/per second for 3 months. time curl shows about 0.1-0.2s of user+sys time, which means we can do about 5 requests per CPU core per second (without any scheduling and postprocessing overhead). To process 20 billion requests in 3 months it would require 400 CPU cores. To store 20 billion entries with a hash and video title (say 100 bytes) we need about 2 TB of storage without any indices. Simple grep in a 2 TB file would take about 10 minutes from SSD and 2 minutes if it is in the memory. To get a reasonable search response time <5 seconds we need to spread the search over at least 25 instances with a total of 2 TB RAM which would result in 80 GB RAM per instance. To get a total of 400 CPU cores we need at least 16 vCPU per instance. The cheapest instance that fits the requirements is r6g.4xlarge which costs $588 per month on demand. The total cost of 25 instances would be $14700 per month.
Comment: The questions about legality are off-topic here. You'll be able to find better answers on https://law.stackexchange.com/
Comment: Thanks for your professional estimations, Alexey. I agree the task is quite difficult in a maximal scope.
What about "hidden objects" and IDOR topic. I understand I have to be careful. The problem is however that the formulation is not 100% clear. I am not going to access hidden objects, but iterate through all objects and note those ones which are public. If I reference a hidden object during this iterative process it must lead to an "access denied" error. If it turns out to be accessible due to a bug it is not my fault, because my intention is to take all public ones, right?
Comment: Just for comparison. I am in a big library which is full of bookshelves. The catalog says there is no book that I want, but I don't trust and start looking just every single book in the library and write down its title and shelve/position number. I don't approach the locked shelves, only open ones. After I finally leave the library with a huge list of records about the seen books, am I a thief or a cheater?


Let $R$ be a field and $I$ be the set of non units in $R[[x]]$. Prove $I$ is an ideal.

Question:
Let $R$ be a field and $I$ be the set of non units in $R[[x]]$. Prove $I$ is an ideal.

So far, I have that an element of $R[[x]]$ is a unit iff its constant term is a unit in $R$ because for any constant term which is a unit its inverse must exist. But if $R$ is field wouldn't all the constant terms be units? Thus $I = \{0\}$, which seemed to be incorrect.
Answer: In a field there is a non-unit, namely $0$. It follows that $I$ is the set of power series with constant term $0$. You should be able to show that this is an ideal in $R[[x]]$.


Is there a name for this: text syncopates otherwise unsyncopated vocal music?

Question: There's an interesting musical phenomenon in "O Virgo Splendens" (14th century, in the Llibre Vermell de Montserrat) as it is consistently interpreted across all editions I have ever encountered.
The piece (a round of three) consists of 12 musical phrases of identical length and rhythm: 15 eighth notes (5 triplets) followed by a dotted quarter or in the interpretation I prefer, a dotted half -- in any event, an on-beat cadential note.  There is no rhythmic variation in the pitches of the phrases.  All of them have the exact same rhythm, and it's the simplest possible rhythm: a series of 15 notes of identical length, then a held note on the end.
The text, however, is assigned to the notes in ways which syncopate them.  For instance, the 7th phrase starts with the word "conscendunt", each of the three syllables of which gets two eighths, turning those two triplets into a frank 3/4 hemiola.  Examples of this sort of syncopated text underlay abound throughout the piece.
As a consequence, the piece is actually much more rhythmically challenging to sing, even just as a solo, than "15 eighths in a row, all starting on a downbeat" would ever suggest.  Sung as a round, it becomes quite rhythmically complex and texturally rich, to the point of being challenging to sync the lines properly -- even though, technically, rhythmically, all the notes are strictly homophonic!
Is there a technical term for this?  For syncopation that exists entirely in the syllabic assignment of a text in a vocal work and is otherwise not represented in the durations or marked dynamics of the notes?
And are there other examples?[*]  Either contemporaneous or otherwise?
[* The only other thing I can think of is a brief moment in the 16th cen instrumental pavan version of "Mille Regretz", third system "...brief mes jours definer", where if you don't know how the text goes in the original Josquin chanson, you will misconstrue the phrases. But that's not even really syncopated.]
Comment: I do not think there is a specific term for this.  I nominate *Syllabic Syncopation* as the terminology (if one does not exist).  A web search found a few examples of people using the term *Syllabic Syncopation* but I don't see a formal definition for it.  (Your description of the piece sounds intriguing.)
Answer: I don't know of an established term.  I'd propose "prosodic counterpoint".  While this would include more than the verse metre (for example inflection), "metric counterpoint" would be too ambiguous since "metre" has an established meaning in music that is different from that of verse, and the lyrics do not need to rise to the actual level of metered poetry in order to accentuate music.
"syllabic" seems to fall a bit short to me since a syllable as such is not determining word stress: you need to assemble them into words first before you can find where the accents lie.
Answer: I think you'll find it enlightening to look at this PDF of the original manuscript (O Virgo Splendens starts on p 44 of the PDF).
The origional notation, I think, drives home that this isn't really an issue of "syncopation" so much as an entirely different way of conceiving of meter, pulse, and accent. Taking your "conscendunt" as an example, the neumes are very clear that the groupings are two, then two, then four (co-on-scé-én-du-u-u-unt) — quite different from the CPDL version, which beam together two groups of 9 eighth-notes (or, better, a group of 18) into consistent units of three, leading the incautious performer to apply the modern assumption that the first note in each group of three should get a stress. This assumption would be totally anachronistic for the 14th century.
I suspect this is a case of bowing to the assumptions made by the notation software, rather than even an editorial decision — if you look at the edition by nakamura, it preserves the note groupings of the origional, using beams only to indicate when the neumes are joined together and inserting "bar lines" only when there are divisions in the manuscript. I would recommend that edition, or better yet just working from the original.
So, I'm not sure of a term for this per se, but that's because I don't think this is exactly an instance of "syncopation" so much as an example of the fundamentally different way pulse was organized in Renaissance music.


What's pratical use of Derivate function calculus?

Question: I would like to know whats the pratical use of derivate calculus? Or what it means?
If you can give some pratical example I'll be grateful.
Eg.:
I can use an definite integral to know area of a function knowing the expression of the function and the limits.
Know how to solve exercises make no sense if i cant imagine the real purpose and the objective meaning.
Thanks in advance.
Comment: Maybe here: http://www.teach-nology.com/teachers/subject_matter/math/calculus/                                                                                http://www.ijee.ie/articles/Vol18-1/Ijee1262.pdf                                                                                http://www.intmath.com/applications-differentiation/applications-of-differentiation-intro.php?PageSpeed=noscript
Comment: Because I *simply do not understand* what exactly you are asking for. Your question is very general, the answers given do not satisfy you, for given practical applications you then ask *why to use the derivative*. Look at the links which everybody can find and then maybe you can ask more specific questions.
Comment: Also [What do we mean by derivative of a function? What does it tell?](http://math.stackexchange.com/questions/938004/what-do-we-mean-by-derivative-of-a-function-what-does-it-tell)
Comment: @MJD, you completely right. The accepted answer is what my mind needed for. Thanks
Comment: I'm glad I could help.
Answer: it was originally invented to calculate the trajectory of planets.
More generally, almost all physical laws describing how a system evolves are naturally expressed in term of derivatives. To compute the evolution of a system according to these laws, you need derivate calculus...
Comment: I know the history @Denis, and the usage (well, since i was born i have seen this on formulas, and where other guys decide use it). I wonna take the same base as the same guy who express : vel = dS/st
Answer: There are a variety of applications especially in physics.
Suppose you know the force that acts on a particle with mass $m$ as a function of time, i.e. $F = F(t)$. Suppose you furthermore know that at $t = 0$, the velocity of the particle is given by $v_0$. It can be shown that
\begin{align*}
v(t) = v_0 + \int_0^t \frac{F(t^\prime)}{m} \mathrm{d} t^\prime
\end{align*}
where $v(t)$ denotes the velocity of the particle at time $t$ for $t \geq 0$.
Comment: My question that @hick: Why use derivate on this formula? I can memorize the formula but i wonna understand why to use.
Comment: I used an integral in this formula which is the opposite of a derivative. Alternatively: suppose you know the velocity of the particle as a function of time. The acceleration is per definition $a = \frac{\mathrm{d} v}{\mathrm{d} t}$. As the force acting on the particle is given by $F(t) = m a(t)$, we have $F(t) = m \frac{\mathrm{d} v}{\mathrm{d} t}$.
Comment: Thanks again @Hick. But a insist bro, my problem is not know the formulas, but understand why is the formula as it is. I know how to get the aceleration, but why use derivate when we have a variation on time.
Comment: The time derivative of the velocity gives you the rate of change of the velocity at a given time $t$. We call that the acceleration.
Comment: Hum... I'm getting sarted to understand. Thnks again @hick
Answer: [Copying my answer from here]
The derivative function says how fast the original function is changing at each point.  If $f(t)$ is the position of a particle or a rocket ship at each time $t$, then the derivative $f'(t)$ is the speed of the particle or the rocket ship at time $t$.
Consider as an example $f(t) = -5t^2 + 20t$.  Suppose this describes the height of a rocket above the ground at time $t$.  This curve is a downward-facing parabola with $f(0) = f(4) = 0$ and the peak of the parabola at $f(2) = 20$:

At $t=0$ we have $f(t) = 0$ and the rocket is on the ground.   The rocket goes up, quickly at first, then more slowly, until at $t=2$ it stops going up and starts to come down, slowly at first, then more quickly as time goes by, until it hits the ground again at $t=4$.

What if you want to know the speed of the rocket?  That is the derivative, $$f'(t) = -10 t+20.$$

The derivative is the blue line in the picture.  It represents the upward speed of the rocket at each point.
When $t=0$, the derivative has the value $20$, representing a fast upward motion.  When $t=1$, the upward speed has decreased to $10$.  When $t=2$, the rocket has reached the peak of its flight and has stopped going up and is about to come back down.  $f'(t) = 0$, meaning that the rocket has no motion at this instant.  Then at $t=3$ the derivative is $-10$, which represents a downward motion, and at $t=4$ when the rocket hits the ground its downward motion is twice as fast, since $f(4) = -20$.
Answer: One practical use: Approximate ugly functions with nice ones. In fact, we like Lines, they are simple. The equation of a line is just
$$ Ax + By = C $$
Where $A,B,C$ are numbers. This is a nice function. Sometimes you may encounter functions like this one:
$$ f(x) = \sin ( e^{x^2} )\cdot e^{\arctan x} + x^8 - \ln x $$
$f$ is a horrible function. Calculus then help us. Derivative help us because we can approximate this $f(x)$ in a vicinity of a point $(x_0,y_0)$ where $f$ would make sense with a line, in fact explicitly given by
$$ \mathcal{L}(x) = y_0 + f'(x_0)(x-x_0)$$


How can I get Date list from year and month name

Question: How can I get (java.util.Date) date list from specific year and month
Example : I have a year like as  '2017' and month name like as 'February' I want to get date list of February or any other months.
such as
2017-02-01,
2017-02-02,
2017-02-03,
2017-02-04,
2017-02-05,
2017-02-06,
2017-02-07
....
2017-02-28.

Please help me sample code, Thanks
Comment: Just iterate through them, as far as I know such thing is not predefined in java
Comment: I tried to get list of date between two dates and get result but i need through month name and year not two date
Comment: Add the code that you have tried in order to solve this problem here in the question.
Comment: @Md.NasirUddin: have a look at the updated answer.
Answer: java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:
List<LocalDate> getDateList(int year, String monthname) {
    int month = Month.valueOf(monthname.toUpperCase()).getValue();

    return IntStream
            .rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
            .mapToObj(i -> LocalDate.of(year, month, i))
            .collect(Collectors.toList());
}

Demo:
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        // Test
        getDateList(2017, "February").forEach(System.out::println);
        System.out.println("=*==*==*=*=");
        getDateList(2016, "February").forEach(System.out::println);
    }

    static List<LocalDate> getDateList(int year, String monthname) {
        int month = Month.valueOf(monthname.toUpperCase()).getValue();

        return IntStream
                .rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
                .mapToObj(i -> LocalDate.of(year, month, i))
                .collect(Collectors.toList());
    }
}

Output:
2017-02-01
2017-02-02
...
...
...
2017-02-27
2017-02-28
=*==*==*=*=
2016-02-01
2016-02-02
...
...
...
2016-02-28
2016-02-29

ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Answer: java.time
Use the modern date-time classes, in the java.time package.
String input = "2017 February" ;

Parse as a YearMonth object. Define a formatting pattern to match your input.
    String input = "2017 February";
    DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuu MMMM" , Locale.US );
    YearMonth ym = YearMonth.parse ( input , f );

Loop for the number of days in that month. For each day-of-month, get a LocalDate object.
System.out.println ( "===== Days of " + ym + " =====" );
for ( int i = 1 ; i <= ym.lengthOfMonth () ; i ++ ) {
    LocalDate localDate = ym.atDay ( i );
    System.out.println ( localDate );  // Uses standard ISO 8601 format by default when generating a string.
}
System.out.println ( "=================" );

===== Days of 2017-02 =====
2017-02-01
2017-02-02
2017-02-03
  …

You can see that code run live at IdeOne.com.
If you want to see this kind of code written using Java Streams, see my Question: Use Java streams to collect objects generated in a for loop

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Answer: First, you need to find the number of days you can get for a specific month, this is easy with Calendar.getActualMaximum(int field)

Returns the maximum value that the specified calendar field could have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 in some years, and 13 in other years in the Hebrew calendar system.

From this, just use a loop to create every value (or might be easier with Stream API, but I am not good with it...).
Here is a simple example of the usage of this method (not the answer at all):
Calendar c = Calendar.getInstance();
    for(int i = 0; i <= c.getActualMaximum(Calendar.MONTH); ++i){
        c.set(Calendar.MONTH, i);
        System.out.format("There is %d days in %d\n", c.getActualMaximum(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH));
    }

Output :
There is 31 days in 0
There is 28 days in 1
There is 31 days in 2
There is 30 days in 3
There is 31 days in 4
There is 30 days in 5
There is 31 days in 6
There is 31 days in 7
There is 30 days in 8
There is 31 days in 9
There is 30 days in 10
There is 31 days in 11

Answer: You can use this :

First you should to get the first day from date from your input year and month 2017/February
Second you should to get the number of days of this month
Third you should to loop until the number to your days in your case from 1 to 28 and add a day to your date

public static void main(String[] args) throws ParseException {
    int year = 2017;
    String month = "February";
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MMMM", Locale.US);
    Date utilDate = format.parse(year + "/" + month);
    //get first day of your month
    System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(utilDate));

    //get days of months
    Calendar cal = Calendar.getInstance();
    cal.setTime(utilDate);
    int monthMaxDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    //loop and add a day to your date
    for (int i = 0; i < monthMaxDays - 1; i++) {
        cal.add(Calendar.DATE, 1);
        System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime()));
    }
}

See this code run live at IdeOne.com.
Good luck
Comment: FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes.
Comment: No, not about being nonsensical. Your Answer's code appears to be correct, and functional as we can see when [running it live at IdeOne.com](http://ideone.com/l1dXqr). I suggest recommending the use of the legacy date-time classes is poor advice given their many flaws, poor design, and confusing nature. We have the java.time classes, an *enormous* improvement, so use the modern alternative. Why drive a [Yugo](https://en.wikipedia.org/wiki/Zastava_Koral) when you have a [Honda](https://en.wikipedia.org/wiki/Honda_Civic) in the driveway?
Comment: Thank you so much. It's a great solution .
Comment: mmmm so what should i do @BasilBourque do you find my answer with no sense?
Answer: As part of solution I created this high order property to get an array of dates from current month. This was for Android below API level 26.
val daysOfMonth: List<Date>
get() {
    val cal = Calendar.getInstance()
    val start = cal.getActualMinimum(Calendar.DAY_OF_MONTH)
    val ends = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
    val days = mutableListOf<Date>()
    for (i in start..ends) {
        cal.set(Calendar.DAY_OF_MONTH, i)
        days.add(cal.time)
    }
    return days
}

Comment: Well, the question was not about Android (and it seems you forgot to state that your answer was). I am no Android developer myself, but I read in many places that java.time and `LocalDate` are not limited to API level 26 and above. The solution for lower levels is [core library desugaring](https://developer.android.com/studio/write/java8-support-table).
Comment: The `Calendar` class is poorly designed and long outdated. Using it is not recommended. Use `LocalDate` and/or other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/).
Comment: The problem is that LocalDate on Android is just supported after API 26, but I agree that Calendar is sad
Comment: definately, you are right! thanks a lot for sharing that
Answer: I have used JODA-data time to make my life easier and here is the solution:
package com.github.dibyaranjan.service;

import org.joda.time.DateTime;

public class Test {
    public static void main(String[] args) {
        DateTime dateTime = new DateTime();
        dateTime = dateTime.withDate(2017, 02, 01); // Used the date and time mentioned in your question
        int currentMonth = dateTime.getMonthOfYear();
        boolean isCurrentMonth = true;
        while (isCurrentMonth) {
            isCurrentMonth = (dateTime.getMonthOfYear() == currentMonth);
            if (isCurrentMonth) {
                String dateTimeFormatter = "yyyy-MM-dd";
                System.out.println(dateTime.toString(dateTimeFormatter));
            }
            dateTime = dateTime.plusDays(1);
        }
    }
}

Comment: Is it really necessary to use Joda for this ? It seems it would be the same with Calendar or probably LocalDate (not sur for the last)
Comment: @AxelH: Yeah, not a *must* but, I do have Joda in every project I work. So every solution related to dates come to my mind includes usage of Joda.
Comment: @AxelH : And yeah. Code looks very clean and tidy as well, I don't want the next developer who sees my code to curse me :)
Comment: I understand, that's part of your standard API package. No problem, the algorithm can be easily reproduce if someone doesn't want Joda.


Bootstrap subtheme - theme_menu_link(array $variables) not reacting

Question: I'm using the Bootstrap theme and I've successfuly created a bootstrap subtheme that I named bootstrapdreve
I've already overidded successfully two templates, but now I'm facing a problem I'm stuck for hours on.
I wanted to overide the bootstrap_menu_link theming function located in bootstrap/theme/menu/.
So I copied it into my
bootstrapdreve/template.php

and renamed it
function bootstrapdreve_menu_link(array $variables)

Before bringing my adaptations I set a dsm('test'); on first line:
function bootstrapdreve_menu_link(array $variables) {
  dsm('test');
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Prevent dropdown functions from being added to management menu so it
    // does not affect the navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = drupal_render($element['#below']);
    }
    elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
      // Add our own wrapper.
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '
' . drupal_render($element['#below']) . '
';
      // Generate as standard dropdown.
      $element['#title'] .= ' ';
      $element['#attributes']['class'][] = 'dropdown';
      $element['#localized_options']['html'] = TRUE;

      // Set dropdown trigger element to # to prevent inadvertant page loading
      // when a submenu link is clicked.
      $element['#localized_options']['attributes']['data-target'] = '#';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    }
  }
  // On primary navigation menu, class 'active' is not set on active menu item.
  // @see https://drupal.org/node/1896674
  if (($element['#href'] == $_GET['q'] || ($element['#href'] == '<front>' && drupal_is_front_page())) && (empty($element['#localized_options']['language']))) {
    $element['#attributes']['class'][] = 'active';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

... and nothing's displayed
I've followed the idea given by this subtheme preprocess functions inheritance post by creating this structure:
bootstrapdreve/theme/menu/menu-link.func.php

and by setting also a dsm('test'); at first line of code...
Still no message... and thus as I interpret it no execution of this function...
I don't understand why. Could you please help me find why this theming function overiding doesn't work ?
Rem.: There's no problem with the dsm(), I've tried to put one at top of bootstrapdreve/template.php and it works fine...
Rem. 2: I've offcourse cleared the cache at every modification I made
Comment: If you put dsm() in the parent theme, can you verify it fires?
Comment: I've putted the dsm('test'); in the bootstrap/theme/menu/menu-link.func.php and there it fires well...
Comment: What version (revision) are you using of bootstrap theme, also you may check the changes in theme directory structure in issues #2170829, #2217037.
Comment: I'm using the 7.x-3.0 version. I've tried with an upgrade to the 7.x-3.1-beta2 version and it didn't change anything
Comment: can you confirm theme registry?

`$registry = theme_get_registry();`
`dsm($registry['menu_link']);`
Answer: I maintain a Bootstrap subtheme that I use for most of my projects and I override theme_menu_link() in my subtheme using the same method with no problem:
/**
 * Overrides bootstrap_menu_link().
 *
 * Resets theme_menu_link() to the default that ships with Drupal. Bootstrap
 * attempts to make every menu with children into a dropdown menu. Remove this
 * function if you want drop down links.
 */
function bootstrap_ignitor_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

You must have a problem somewhere else.
Comment: You're right, the problem seems to be in my implementation of subtheme. I've gitted and activated your subtheme, set a dsm at the top of your bootstrap_ignitor_menu_link function and it displays well...
Thanks for this trail.
Comment: @Adam Balsam, I made a mistake with the bounty, I wanted to assign 50 for you, sorry for that.
Comment: @regilero Ha! Oh well - glad it could point you in the right direction at least.
Answer: try using
option 1:     function THEMENAME_menu_link(&$variables) {}
option 2:
 /**
* theme_menu_link()
*/
function THEMENAME_menu_link(array $variables) {
//add class for li
   $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//add class for a
   $variables['element']['#localized_options']['attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
//dvm($variables['element']);
  return theme_menu_link($variables);
}

option 3 :
function bootstrapdreve_preprocess_menu_link(&$variables) {
        $variables['element']['#attributes']['class'][] = 'menu-' . $variables['element']['#original_link']['mlid'];
        $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#title'])));
        // Another option $menu_title_class = preg_replace("/[^a-zA-Z0-9]/", "-", strtolower(strip_tags($variables['element']['#original_link']['link_title'])));
        $variables['element']['#attributes']['class'][] = 'menu-' . $menu_title_class;

        if ($variables['element']['#original_link']['menu_name'] == 'user-menu') {
            $variables['element']['#localized_options']['html']= true;
            $variables['element']['#title'] = ''.$variables['element']['#title'].'';
        }
    }

Comment: Neither of these options worked, but as Adam Balsam mentionned below, there must be something in the implementation of bootstrap subtheme I've done wrong, because with his subtheme, the dsm appears well...
Comment: So you have tried using (&$variables) instead of (array $variables) in your function call?
Answer: You need to add function bootstrapdreve_menu_link(array $variables) { in your template.php and not in a .func.php file.
If you add it in a func.php file then you need to include this file in the template.php file somehow.
Just copy the code inside template.php and it should work.


Why does nobody use the deduction symbols $A \Rightarrow B \Rightarrow C \Rightarrow D$ in their thesis/dissertation?

Question: I am studying for a Master's degree of mathematics.
There are some deduction in my thesis is written
as the following form.
$A  $
$\Rightarrow  B $
$ \Rightarrow  C $
$ \Rightarrow  D $
But my adviser does not allow me write my thesis in such a form.
He said there's nobody who writes a thesis like this,
and requested that I use text rather than use mathematical symbol.
But I found a book, "Abstract Algebra", written by Dipak Chatterjee that does.

I don't plan to take this book to my boss,
because I want to graduate.
Here are some reasons from my classmate against me:

There's nobody who writes a paper like this.
But this is not reasonable for me.
It doesn't mean this method is bad.
In addition,
If the professor adopts such form in his lecture,
why I can't use such method in my thesis/dissertation?
If you use text rather than mathematical symbols,
then your article will be understandable for a non-professional reader.
This is also not reasonable for me.
Is there a non-professional reader who will read my thesis?

Would anyone give me some opinion?
Whatever support or against, thanks.
Comment: The advice of your advisor is entirely reasonable and proofs written in the style you advocate tend to be simply unreadable. Note that even the book you mention as your Exhibit A adopts this style in one or two occasions only (hence your "But I found a book ... that does" is not true, strictly speaking).
Comment: I have a hard time believing your adviser would oppose against writing with symbols as in the text book example. It makes the proof perfectly clear. If someone thinks otherwise, I would say that person is against the norm. On other instances, however, words might be more clear to most people.
Comment: It's fine in the middle of a long computation that's just symbol manipulation, as in the example if you give. It's not a good style elsewhere, though, and it shouldn't be used in running text. For example, "If $f$ vanishes at some $x\in \mathbb{R}$, then there exists $x'\in \mathbb{Q}$ with $f(x) = 0$" shouldn't be replaced with, "then $\exists x'\in \mathbb{Q}$ with $f(x) = 0$," and "then $\exists x'\in \mathbb{Q}: f(x) = 0$" is worse.
Answer: Personally, I totally agree with your advisor. I hate the use of symbols where words could be used to produce a better result. You can use symbols on the blackboard, but my opinion is that a thesis is like a book: it should be carefully written, and the final result should be aesthetically good.
Many years ago, mathematics books were written with a particular care about the style. Take books like those written by Walter Rudin or Serge Lang: they even used words where symbols could have been perfectly legitimate.
But you might be right: it is a matter of taste, above all.
Comment: It seems you move from an assumption that is not necessarily true: there are mathematicians that do not fill up their papers with symbols where words should be used.
Comment: At a guess,
many years ago,
if the mathematician are used to write their paper
prefer to use the implication symbol ``$\Rightarrow$''
rather than use words,
then the books written by Rudin or Lang and the journal
will be of the form today?
Answer: First, it is right that most mathematics is presented as written text and not as a series of logical symbols (the Pricipia Mathematica being one of the more famous examples - even the very formal books by Bourbaki are written mainly as text - basically, only introductionary books for undergraduates use formal manipulations).
I also agree that it is more appropriate to write a mathematical text rather than a series of logical symbols. Although it is correct that you should strive to be as precise and concise as possible, I think the reason to use text over symbols is that mathematical texts are much more about communicating ideas rather than facts. Having a proof in a formal and rigorous way is nice. But it is more difficult to extract the basic idea of a proof from a series of formal manipulations  than from a written text. Hence, I would suggest that you try to write your thesis with the goal of explaining things as good as possible rather than "being as precise as possible". Although it may sound paradoxical, I suggest: Do not sacrifice clarity for precision.
Answer: If you were writing your own book or if you were the only author of a paper you were submitting to a journal, I would say use whichever style you like but be aware that different journals/publication bodies may reject items which don't conform to their preferred style/template.
However, since you are a Master's student I would observe that what you write may be seen as a reflection on your advisor. Furthermore, your university may have some style requirements which bear on this issue.
If it makes you feel better I recall that I had put throughout my thesis "ploof" instead of "proof" and was forced by my advisor to use the latter. Not quite the same thing, but I was quite adamant.
Answer: I agree with your thought. One of the objects in mathematics is to have things presented in a concise and precise manner. If the implication sign does the job nicely, continue using it (after you pass your thesis).
Answer: Firstly, overuse of symbols does decrease readability, and not just to "non-professionals".
Secondly, consider these two distinct assertions:

statement $D$
statement $A$ is a sufficient condition for statement $D.$

Your suggested presentation

$A\\\Rightarrow  B\\ \Rightarrow  C \\ \Rightarrow  D $

expresses option $(2),$ and notably does not actually conclude that statement D is true.
Your cited example

has the modus ponens structure
\begin{align}&A \Rightarrow B \Rightarrow C \Rightarrow D\\\text{and}\:\:&(A\Rightarrow D)\Rightarrow P;\\\text{therefore}\:\:&P\end{align}
(the middle line is implicit), and genuinely utilises the implication $A{\Rightarrow}D$—rather than statement $D$ itself—to argue that a latter statement $P$ is true.


Rails getting data inside an ActiveRecord object which is inside an array

Question: Ok, convoluted title, I know, but the situation is the following:
I have a query (failed_by_apps = Search.failed_by_app) that returns something like this:
s.each_with_index { |item, i| puts "index: #{i} item: #{item}" }
index: 0 item: #<Search:0x007faf858da068>
index: 1 item: #<Search:0x007faf858d9cd0>
index: 2 item: #<Search:0x007faf858d9960>
index: 3 item: #<Search:0x007faf858d95a0>

Each of the search items is an ActiveRecord item which contains something like this:
s.each { |item| puts "#{item.app}: #{item.appFailed}"  }
book: 23885
dvd: 9563
cd: 4850
game: 629

The problem comes when I try to get the value of appFailed without doing a .each loop. See, I have another bit of code where I want to put together information from different queries into one hash, it looks like this:
i = 0
appTotals.each do |app|
    @appHash[app.app] =  {"appTotal" => app.appTotal, "percent" => failed_by_apps[i].appFailed }
    i += 1
end

This works, but I'm thinking there must surely be a better (more elegant) way of doing this no?
Edit:
Please ignore former question about math, I just want to figure out a better way to get the value inside failed_by_apps[x].appFailed
Comment: I'm a bit lost. What's `appTotals`? How does it relate to `failed_by_apps`? What are you ultimately trying to achieve - filling `@appHash` with... what?
Comment: You will have to excuse me, my crystal ball is a bit shady today, who is `appTotals` again ? And what does it have to do with apps failed by  something? So what are you trying to achieve (in words) ? Maybe [Enumerable#group_by](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-group_by) and [Enumerable#map](http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map) are of interest ?
Comment: Doesn't really matter what appTotals is, (it's the sum of all those numbers spit out in the second block of code). What I'm trying to figure out is how to access the values inside this array `failed_by_apps[i].appFailed` in a better fashion. I've figured out the math bit so please ignore that.
Comment: So, `failed_by_apps` contains a set of database records, each of which contains `app` (string) and `appFailed` (integer); and you want to get `appFailed` for each entry... without using `each` or an `i` index? You want to stuff the `appFailed` values into something else? I think we're close to being able to help, but things are just a little hazy still.
Comment: @Chowlett that is correct. Exactly what I want. Like I said above, it works this way, but I think there's a better way to to it no?
Answer: I'm still a little confused as to exactly what you want, but hopefully we can get there be progressive refinement. How about this is a starting point?
failed_by_apps.map(&:appFailed)
# => [23885, 9563, 4850, 629]


Is there an API to read file content?

Question: Most references seem to read files using PHP functions like file_get_contents(), fgets(), fread(), or readfile().
Is there is any Drupal API that allows to read uploaded files independent of underlying storage?
We are using AWS S3 as our file field storage. Our ec2 instance is in a private subnet with an interface to S3 services. Say the URI is s3://bucketname/object.csv. I need a Drupal API that does an s3 getObject() SDK call under the hood that way I don't get blocked on network level instead request goes through the S3 network interface.
Comment: Please tag the question with the major Drupal version, like 7 or 10.
Comment: Sorry. This is for Drupal 10.
Answer: Drupal implements access to managed files through stream wrappers.
So you can access files using native PHP functions as follows.
file_get_contents('public://some/public/file.txt');
file_get_contents('private://some/private/file.txt');
file_get_contents('temporary://some/temporary/file.txt');

Comment: The S3 module defines a stream wrapper for `s3://`. Whether that does what you specifically want under the hood you'd have to check, but I think that's the only existing implementation out in the wild that's been battle-tested
Comment: Thanks. There is a nuance here. We are using AWS S3 as our file field storage. Our ec2 instance is in a private subnet with an interface to S3 services. Say the URI is s3://bucketname/object.csv. I need a Drupal API that does an s3 getObject() SDK call under the hood that way I don't get blocked instead request goes through the S3 network interface.
Comment: @Clive, sure. I will try and let you know.

Is there an API to read file content?


Show that for any $a, b \in \mathbb{C}$ with real parts of $a,b$ to be lesser or equals to $0$, one has $|e^b-e^a| \leq |b-a|$

Question: Show that for any $a, b \in \mathbb{C}$ with real parts of $a,b$ to be lesser or equals to $0$, one has $$|e^b-e^a| \leq |b-a|$$
Let $a = a_1+ia_2,b=b_1+ib_2$
I have done almost all parts of this proof but I just need one part of the proof to be true to complete the whole question, namely: In my last step, I want to show that $$\frac{2}{2!}-\frac{2(a_2-b_2)^2}{4!}+\frac{2(a_2-b_2)^4}{6!}- \frac{2(a_2-b_2)^6}{8!}...+... \leq 1$$
I forgot how to show this kind of upper bound and would appreciate some help.
Comment: Can you relate that to the cosine function?
Comment: Yes I can, but I kinda only see $\cos z = 1-\frac{z^2}{2!}+......$ which looks slightly different and hence cannot deduce it.
Comment: $e^b-e^a=\int^{b}_{a}e^z dz$, and choose the integral curve in the left half plane. Because $e^z$ has primitive.
Answer: From $$|e^w|=e^{{\bf Re} \ w}<1$$
$$|e^b-e^a|=|\int_a^b e^z\ dz|=
|\int_0^1e^{a+(b-a)t}(b-a)\ dt|\leq\int_0^1 |e^{a+(b-a)t}|\ |b-a|dt=|b-a|$$
where ${\bf Re} \ (a+(b-a)t)<0$.
Answer: $e^{b}-e^{a}=(b-a)\int_I e^{tb+(1-t)a} \, dt$ where $I=[0,1]$. [ Because $(b-a) e^{tb+(1-t)a}$ is the derivative of $ e^{tb+(1-t)a}$].  Hence $|e^{b}-e^{a}| \leq (b-a)\int_I e^{\Re (tb+(1-t)a)} \, dt \leq (b-a)$


Changing the language using payload in Node-RED for Watson language translator

Question: The Node-RED Info tab for Watson IoT Language Translator states: Source and destination language parameters can be configured through the editor panel or set dynamically using the language codes in the following properties, msg.srclang and msg.destlang. Please see the documentation linked below for the currently supported source and destination language codes.
However the linked documentation contains no such help on what codes to use - and a google web search reveals nothing. Anyone have any clues ?
Comment: You're right, that link appears to be broken.  I'll report it to the Watson documentation team and see if I can find any further info for you.
Answer: That link should point to this documentation page:
https://www.ibm.com/watson/developercloud/doc/language-translator/
See below the translations currently supported, use the 2 digit iso code for the srclang and destlang.
Today, the basic Language Translator service offers three domain-specific translation models:
News - targeted at news articles and transcripts, it translates English to and from Arabic, Brazilian Portuguese, French, German, Italian, Japanese, or Spanish. It also translates Spanish to and from French.
Conversational - targeted at conversational colloquialisms, it translates English to and from Arabic, Brazilian Portuguese, French, Italian, or Spanish.
Patents - targeted at technical and legal terminology, it translates Brazilian Portuguese, Chinese, or Spanish to English.
Comment: Its actually a 2 or 5 character IETF language tag, which are related to the ISO codes.


What do I need to do to set up Visual Studio to be able to manipulate an Excel File?

Question: Let's say I want to find the value of a cell in an Excel file.  In VBA, I would do this:
Dim varValue As Variant
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Sheet1")
varValue = ws.Range("A1").Value

How do I set up a Visual Studio project so I can access and modify an Excel file in C# rather than in VBA?
What references might I need to add?
Does the file need to be open in order to work with it?
Answer: You can use Excel automation or a third-party library.
To use Excel automation, you should install the Office PIAs and add a reference to Microsoft.Office.Interop.Excel.dll.   You would then write code to open the file (using the ApplicationClass class) and manipulate it.
This approach would use the same object model that you're used to in VBA.  However, since C# 3 does not support optional parameters or weak typing, it will be somewhat annoying.  It would be easier to do it in VB .Net or C# 4 (currently in beta)

Excel automation is not suitable for code running in non-interactive context.  There are a number of third-party libraries written entirely in .Net that can read and write Excel files.
In addition, if you only need to manipulate table-like data, you can use OleDb to run SQL statements against Excel files using this connection string.
You can use OleDbCommands to run SELECT * FROM [SheetName], assuming that the sheet is a table.  You can also select from a named range.  You can get the available tables by calling oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null) and looking at the TABLE_NAME column ion the returned DataTable.
Answer: I wrote my own, fairly simple class to extract data from an Excel spreadsheet via C#. You need to include:
using Microsoft.Office.Interop;

Then you can do something like this to get started:
Excel.Application excel;
Excel.Workbook workbook;
Excel.Worksheet worksheet;
Excel.Sheets sheets;
Excel.Range range;

excel = new Microsoft.Office.Interop.Excel.Application();
workbook = excel.Workbooks.Open(workbookName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
sheets = workbook.Worksheets;
...

Comment: you can also reference Microsoft Excel Object Library from the COM tab.
Answer: You do not have to use interop.
You simply need a reference to...
System.Data.OleDb

Define a connection string as you would any other data source:
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=YourPath;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";";

And add some code to query your database:
OleDbConnection objConnection = new OleDbConnection();
string strSQL = "SELECT * FROM [YourTable]";
objConnection = new OleDbConnection(connectionString);
objConnection.Open();
OleDbCommand cmd = new OleDbCommand(strSQL, objConnection);
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);

...Then enumerate through your data rows.
Comment: This is only useful if the spreadsheet contains a table-like structure, and you're not interested in formatting.  See my answer.
Comment: Ah -- noted.  Thanks! I'll still leave the answer up as a reference in case someone else does meet those qualifications.
Answer: You have to used Microsoft.Office.Interop.Excel.
You'll need to use COM Interop. Here's a detailed tutorial about how it's done.


Is my regularized logistic regression model overfit?

Question: I have a dataset with the following characteristics:

moderate sample size (~300 samples)
moderate class imbalance (~20% positives)
high-dimensional (the number of independent variables, again ~300, is comparable to the number of samples)

I fitted a logistic regression model with Lasso regularization and two-level 3-fold cross-validation (the outer split is used exclusively for performance evaluation, while the inner CV is used for tuning the regularization hyperparameter). I am using scikit-learn's LogisticRegressionCV with class_weigh='balanced' to try and make up for at least some of the imbalance.
The performance as evaluated on the outer CV split is quite good: the model achieves a ROC AUC of around 0.97 ± 0.02 and a Matthews' correlation coefficient of 0.8 ± 0.05 when using a decision threshold of 0.5. This all sounds fun until I look at the model parameters. The regularized model contains around 60 non-zero coefficients, and the optimized regularization hyperparameter is tiny ($\frac{1}{C} = \frac{1}{50}$). Furthermore, when I check the predictions on the training set, I can see that the model achieves complete separation of the classes, which is a known problem with optimizing logistic regression using the standard cross-entropy loss (which is what scikit-learn does).
Now my problem with this is that the number of non-zero coefficients is comparable to the number of positive samples, i.e., the cardinality of the smaller class. I know of the common advice that in an imbalanced-class logistic regression modell, one should adjust the number of predictors based on the cardinality of the smaller class, and this seems reasonable enough (even obvious): if there's one predictor for each positive sample, then it would be trivial to overfit the model and basically have it memorize every single training data point.
So, my question is: do you think my model is overfit? The small regularization parameter and the relatively high remaining dimensionality of the final model would suggest so, but the cross-validated performance suggests that it really is as good as it sounds like. What do you think?
P.s.: I was careful enough to apply at least some basic measures for preventing information leakage. The dataset I am trying to model is from a biomedical study, and sometimes, multiple samples are present by certain patients. I am using the StratifiedGroupKFold splitter to take this into account, by ensuring that the same patient never shows up in multiple splits during cross-validation.
Answer: The sample size is not large enough to be able to reliably choose the shrinkage coefficient (penalty; regularization).  The sample is barely large enough to estimate the overall prevalence of the outcome ignoring predictors, i.e., to estimate just the intercept in a logistic model.    For a margin of error of 0.05 on the probability scale the sample size needed (with zero predictors) is 384; for a margin of error of 0.1 it is 96 observations.  Your effective sample size is 3p(1-p)n where p = 0.2, which helps you determine the dimensionality of the features that you are allowed to analyze.
The only real hope is to reduce the feature space to something the effective sample size will support, which is perhaps 2-5 collapsed features.  Features can be collapsed using unsupervised learning (data reduction) blinded to Y.
These issues are discussed here and here.
Comment: I'm afraid I don't really follow how this answers my question. How does this explain the apparently good generalization power, then? Another question would be why I experience the same phenomenon when I do not try estimating the shrinkage coefficient using cross-validation, if that is an issue. For example, I since tried separately selecting the 10 top features most correlated with the target, based on your claim of the effective sample size ($\approx 144$), then applying LDA, both with Ledoit-Wolf shrinkage and without. The results were approximately the same in all three cases.
Comment: I also couldn't find the sample size formula (let alone a derivation of it) that you mentioned. Based on the binomial distribution, $np(1 - p)$ seems logical enough, but where exactly does the factor of 3 come from?
Comment: I found a common definition of "effective sample size" as used in the context of weighting samples, which is $N_{eff} = \frac{(\sum{w_i})^2}{\sum(w_i^2)}$. If I plug in the inversely-weighted case (i.e., the negative class is weighted $\frac{p}{1-p}$ times compared to the positive class), I get $N_{eff} = 4Np(1-p)$. That's closer, but still 4, not 3. What gives?
Comment: That's a slightly different context.  I'm refer to the effective sample size in terms of power/information content using a Wilcoxon test to compute power, which is identical to considering the variance of a log odds ratio in a proportional odds semiparametric ordinal model.  Said more simply we are computing the $N_\text{eff}$ for a continuous $Y$ with no ties that gives the same power of a two-group comparison (even though we may not be doing this comparison) with the original $N$ observations that may contain ties.  Details at https://hbiostat.org/rmsc/multivar#sec-multivar-overfit


Show orbit map $g\to g\cdot x$ factors through well-defined bijective map as defined below

Question: I am given a group $G$ acting on $X$. Let $x$ be any element of $X$. Denote by $G\cdot x$ its orbit and $G_x$ its isotropy. I need to show orbit map $g\mapsto g\cdot x$ factors through the well defined bijective $G/G_x \to G\cdot x$  that maps $gG_x\to g\cdot x$, to define the following $G$- equivariant commutative diagram
$\require{AMScd}$
\begin{CD}
G\\
@VVV @.\\
G/G_x @>>> G\cdot x
\end{CD}
I am familiar with the notations of orbits and isotropy but I don't really know how will i be defining the elements of these groups to prove that it factors that way? Any hints?
Comment: Do you know it is well-defined and bijective? Then the key is showing the map factors that way.
Comment: @ThomasAndrews It is quite easy to show there is a one to one correspondence but after that, showing the map factors that way is giving a bit trouble here ? I don't get it how will I show that? what does it mean to factor in this case ?
Answer: For the map $\varphi\colon G\to G\cdot x$ to factor through $\overline\varphi\colon G/G_x\to G\cdot x$ means that there exists a map $\pi\colon G\to G/G_x$ factoring $\varphi$; that simply means $\varphi$ can be written as $\varphi=\overline\varphi\circ\pi$.
So what you have to do is finding the map $\pi$, for which there is an obvious canidate, and verify the equation $\varphi=\overline\varphi\circ\pi$ for your chosen map. Then the next step is verifing $G$-equivariance. Can you take it from here?
Comment: Thank you for your response. Yes, I think i  can take it from here.
Comment: @HaneenHussam Glad to help!
Comment: https://math.stackexchange.com/questions/21932/what-does-it-mean-to-say-a-map-factors-through-a-set
Comment: This is incomplete you need to show phi is well defined
Comment: @Buraian I'm not sure what you mean? As I don't give a complete such details are naturally left to the reader.


Unipotent subgroups and nilpotent subgroups

Question: Let $G$ be a connected complex Lie subgroup of $GL_n(\mathbb C)$.  Let $N$ be the maximal nilpotent normal subgroup of $G$. Is the center $Z$ of $N$ unipotent?
Answer: No, consider the subgroup of diagonal matrices, it is abelian and is not unipotent.
Another example consider the space of $3\times 3$ matrices of the form:
$\pmatrix{a&0&0\cr 0&1&c\cr 0&0&1}$
$\pmatrix{a&0&0\cr 0&1&0\cr 0&0&1}$ is in the center.
Comment: What if $G$ is not abelian, would this change anything?
Comment: But $\pmatrix{a&0&0\cr 0&b&c\cr 0&0&d}$ is not nilpotent?


mysql server freezes on inserts on a InnoDB table

Question: <code>CREATE TABLE IF NOT EXISTS `music_batch_song` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `music_batch_id` bigint(20) DEFAULT NULL,
  `song_id` bigint(20) DEFAULT NULL,
  `comment` varchar(10) DEFAULT NULL,
  `position` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `music_batch_song_idx` (`music_batch_id`,`song_id`),
  KEY `song_fk` (`song_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=142506 ;
</code>
I have this table that counts about 90k records on a mysql db on amazon aws. Yesterday after a couple of hours of very slow simple inserts (hundreds of them) the db stopped responding to inserts via PHP PDO.
After a mysql server restart it was working again. Do you have any idea how this can happen?
The server was almost inactive when the problem came up. And a single one-row PDO insert query couldn't reach the end. The insert was something like: "INSERT INTO music_batch_song (music_batch_id, song_id) VALUES (188, 32866)". After server reboot the query took a fraction of second as usual...
Comment: From your description, looks like either due to bad configuration or hardware limits, you are at the end of what MySQL can handle. error_log in the mysql directory can perhaps provide some clues.
Answer: Dig up the mysql logs.  Chances are it'll show a deadlock or some other InnoDB error.  Deal with it as appropriate.


A linear operator between Banach spaces is weakly continuous iff norm continuous?

Question: Claim : a linear function $T$ between Banach spaces is weakly continuous iff norm continuous?
Okay, So I think I have realised weakly continuous implies norm continuous. As weakly continuous implies weakly sequentially continuous. Now suppose that $T$ is unbounded. But we also know that 'weakly convergent implies weakly bounded', which implies norm bounded. But this would then imply that '$T(x_{n})$ converges weakly implies that $\|T(x_{n})\|$ is bounded'.
Hence $T(x_{n})$ is not weakly convergent, so $T$ cannot be weakly continuous. Contradiction! Hence T is bounded.
Any ideas on the converse? I.e How do I show norm continuous is weakly continuous?
Comment: Yes, norm-open sets are not necessarily weakly open (e.g. the unit ball), but: By definition the weak topology is the weakest (coarsest) topology for which all norm-continuous functionals are continuous.
Comment: See http://math.stackexchange.com/q/301745/49437
Comment: @Martin Thank you for your link. But it isn't sparking any ideas!
Comment: By definition norm-continuous functionals are weakly continuous. I show the converse: if a functional is weakly continuous then it is a norm-continuous linear functional (take $F = X^\ast$, $w_F$ is the weak topology and $s$ is the norm topology in the notation of that answer).
Comment: Why does it follow from the definition that norm continuous implies weakly continuous? Take any weakly open set, this is norm open, so the pre-image is norm open, but not necessarily weakly open?
Comment: Sorry, I made a typo in my question. I am wanting to consider a linear function/map between two arbitrary Banach spaces. (I.e the map is not a functional.) Then it does not directly follow from the definition does it?
Comment: @Martin Write it as an answer?
Answer: For definiteness consider the linear operator $T:X\to Y$. If $T$ is norm continuous, then for each $f \in Y^*$ we have $f \circ T \in X^*$. Thus $f\circ T$ is continuous w.r.t. the strong topology on $X$ and hence also w.r.t. the weak topology on $X$. But if $f \circ T$ is continuous from $X$ with the weak topology to $\mathbb{F}$ for every $f \in Y^*$ then $T$ is weak-weak continuous from $X$ to $Y$ since the weak topology on $Y$ is the induced topology of the continuous linear functionals on $Y$.
The other direction follows since if $T$ is weak-weak continuous then the graph of $T$ is a weakly closed convex set in $X \times X$ and hence a strongly closed set. The Closed Graph Theorem implies that $T$ is norm continuous.
Answer:
$T:(X,\lVert \cdot \rVert)\rightarrow (Y,\lVert \cdot \rVert)$ is continuous if and only if $ T: (X,\sigma(X,X^*))\rightarrow (Y,\sigma(Y,Y^*)) $ is continuous.

$(\Rightarrow) $ $ T: (X,\sigma(X,X^*))\rightarrow (Y,\sigma(Y,Y^*)) $ will be continuous if and only if $y^*\circ T:(X,\sigma(X,X^*))\rightarrow \mathbb{R} $ is continuous for every $y^*\in Y^*$. However, because $T$ is continuous, $y^*\circ T\in X^*$ and this direction follows.
$(\Leftarrow)$ This is considerably harder. Let us prove some lemmas first.

Lemma 1: There are no extra continuous linear functionals in the weak topology. Precisely: $$(X,\sigma (X,X^*))^*=X^*$$

Proof: $X^*\subseteq (X,\sigma (X,X^*))^*$ by definition of the weak topology. Now take $g\in (X,\sigma (X,X^*))^*$. If $g\equiv 0$, we are done. Suppose there is $x_o\in (\ker g)^C$. Because $\ker g$ is closed in the weak topology we have:
$$x_o\in \cap_{i=1}^n \{x| \:|f_i(x)-f_i(x_o)|<\varepsilon\}\subseteq (\ker g)^C$$
If it doesn't hold that $\cap_{i=1}^n \ker f_i \subseteq \ker g$ there is a certain $x$ satisfying  $f_i(x)=0$ for every $i$ and $g(x) \not=0$. But this means that $x_o+\lambda x\in (\ker g)^C$ for every $\lambda$, which is absurd, say $\lambda=-g(x_o)/g(x)$. Hence $\cap_{i=1}^n \ker f_i \subseteq \ker g$ and by this result, we have, $g=\sum_i \lambda_i f_i\in X^*$ and we are done.

Lemma 2: weak convergence implies norm boundedness.

Proof: This has been done in other  MSE posts. Brezis also does this as a consequence of the uniform boundedness principle.

Finally let us prove our result. Because $y^*\circ T$ is continuos with respect to $\sigma(X,X^*)$, by Lemma 1, we have $y^*\circ T \in X^*$. Suppose by way of contradiction that there are $x_n$ in the circle with $\lVert T(x_n)\rVert \geq n$. Clearly:
$$\frac{x_n}{\sqrt{\lVert T(x_n) \rVert}}\rightarrow 0$$
But because $y^*\circ T\in X^* $, this implies:
$$y^*\left(\frac{T(x_n)}{\sqrt{\lVert T(x_n) \rVert}}\right)\rightarrow 0\quad \text{but $y\in Y^*$ is arbitrary, so:}\quad  \frac{T(x_n)}{\sqrt{\lVert  T(x_n)\rVert}}\rightharpoonup 0$$
But by Lemma 2 this means:
$$\sqrt{n}\leq \left\lVert \frac{T(x_n)}{\sqrt{\lVert  T(x_n)\rVert}}\right \rVert \leq C$$
This contradiction implies $T$ must be bounded.


Como utilizar método parse() em javascript?

Question: Tenho a seguinte implementação:

minhaDataRetornada = "Dez 20, 2016";
minhaDataTratada = Date.parse(minhaDataRetornada);
console.log(minhaDataTratada);

Executando o código acima, meu retorno é :NaN.
Se eu alterar a palavra Dez para Dec, funciona perfeitamente.
Gostaria de saber como resolver, pois meu webService retorna Dez.
Answer: Date.parse espera uma string de representação de datas no formato RFC2822 ou ISO 8601 (outros formatos podem ser utilizados, mas os resultados podem não ser os esperados).
No caso dos nomes do mês, o esperado é em inglês:

month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug"               "Sep" / "Oct" / "Nov" / "Dec"

O que pode ser uma solução é renomear os meses antes de fazer parse, algo como:

var mesesEn = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"],
    mesesPt = ["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago", "Set","Out","Nov","Dez"];

minhaDataRetornada = "Dez 20, 2016";

// verifica se o mês para renomeá-lo
if (mesesPt.indexOf(minhaDataRetornada.split(" ")[0]) !== -1)
  var idx = mesesPt.indexOf(minhaDataRetornada.split(" ")[0]);
  minhaDataRetornada = minhaDataRetornada.replace(mesesPt[idx], mesesEn[idx]);

minhaDataTratada = Date.parse(minhaDataRetornada);
console.log(minhaDataTratada);


status report asks me to run update.php but getting 'no pending updates'

Question: I'm on core version 7.58.
My status report says "Some modules have database schema updates to install. You should run the database update script immediately."
But when I run update.php (or drush updb) I get 'no pending updates'.
I'm not experiencing any problems with the site (except for a small bootstrap-issue that doesn't seem related) and the log doesn't display any errors or warnings.
What can cause this?
Comment: Re-Run cron and check for status report again. If the message still appears then check for hook_update_N in modules and try to update that module using "drush pm-update --no-core module-name"
Comment: Thanks @AjayReddy . Sorry, but can you spell out for me how to check for the hook, haven't a clue how to do that
Comment: Have you run "drush pm-update --no-core module-name"? Kindly try this and let me if problem still appears.
Comment: Done. Status report still asks for an update, and update.php still says 'no pending updates'.
Here's the terminal output:

Name         Installed Version  Proposed version  Message
module-name  Unknown            Unknown           Specified project not found
No code updates available.
Comment: Can you attach status report page screenshot?
Comment: yes @AjayReddy, it's added to original question. Screenshot is from my remote install, same situation on local
Comment: Did that help @AjayReddy?
Answer: Go to systam.module and check for if (max($updates) > $default) { line after this add dpm($module) you will get to know which module prevents this database update and fix that module accordingly. The code will look like below:
if (max($updates) > $default) {
   dpm($module);
   $requirements['update']['severity'] = REQUIREMENT_ERROR;
   $requirements['update']['value'] = $t('Out of date');
   $requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the database update script immediately.', array('@update' => base_path() . 'update.php'));
   break;
}

Comment: Thanks @AjayReddy. You mean system.install right? Tried it but then the status report'-page gives me a "The website encountered an unexpected error. Please try again later.".
The log says "Error: Call to undefined function dpm() in system_requirements() (line 418 of .../modules/system/system.install).
Comment: You have to install DEVEL module for this. Otherwise do print_r($module); exit;
Answer: @AjayReddy's answer was very close. I found this thread on Drupal.org and by following hermes_costell's comment I resolved my issue. It turned out to be the taxonomy module.
Here's the steps I followed (I'm quoting the Drupal.org thread):
in /modules/system/system.install (not in sites/all/... but instead up at the root level) - should be around line 420 change
$requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the database update script immediately.', array('@update' => base_path() . 'update.php'));

to
$requirements['update']['description'] = $t('The @which_module module (and possibly others) has database schema updates to install. You should run the database update script immediately.', array('@which_module' => $module, '@update' => base_path() . 'update.php'));

And now on the admin/reports/status page you'll see the exact name of the module.
Now that you have found the name of the offending module you need to go into the module's .install file and do a bit of detective work to try and figure out which schema_version value should actually be set in there, by essentially starting at the bottom of the module and going through the various MODULE_NAME_update_XXXX functions one by one, asking yourself if the database changes stated in that function HAVE or HAVEN'T been applied to the database yet. You want to start with the highest XXXX value (which should be the lowest in the .install file if they followed standard coding practice) and step lower one-by-one until you hit the function which HAS apparently successfully happened.
For instance let's say you are encountering this issue with the 'cheese' module (which I hope to see soon in Drupal btw), so you go into cheese.install and take a look.
function cheese_update_7005 changes the cheese_sauce.how_much_sauce
field and turns it into a blob. Looking at the database directly you see that in the cheese sauce table, the how_much_sauce field is of type 'int' - so you know cheese_update_7005 hasn't successfully done its job yet.
Then in cheese_update_7004 you see that cheese_sauce.how_much_sauce
is changed from being type 'varchar' into type 'int' - so you deduce that this function has indeed successfully done its job, but as mentioned, 7005 hasn't yet.
Next, you force Drupal to realize it's completed the 7004 step (and is therefore ready to do step 7005 on the next run of update.php) by running the SQL statement on your database:
UPDATE system SET schema_version = 7004 WHERE name = 'cheese';


Cassandra without jvm

Question: I have a question:
can install database Cassandra without java virtual machine? Or you must have virtual machine to run Cassandra?
Thanks.
Answer: From http://wiki.apache.org/cassandra/GettingStarted :
Step 0: Prerequisites and connection to the community
Cassandra requires the most stable version of Java 1.6 you can deploy. For Sun's jvm, this means at least u19; u21 is better. Cassandra also runs on the IBM jvm, and should run on jrockit as well.

Cassandra without jvm


Android device appearing in adb but not Eclipse

Question: Android debug bridge (adb) recognises a connected phone in usb debugging mode
<code>$ ./adb devices
List of devices attached
SH11KPL04620    device
</code>
But Eclipse doesn't see the same device:

Run as -> Android application

Android Device Chooser
Choose a running Android device
(none listed)
Comment: Did you try to just restart `Eclipse`?
Comment: enable `USB debugging` in your Phone
Comment: DDMS can see the device (can even take screenshots of the phone) yet still the "Android Device Chooser" is blank
Answer:
Make Sure Ur use debuging is On
Make Sure ur code built version is compatible with device android version
ur can try adb reset as shown below:
Comment: @OJW whats ur device version?
Comment: That seems to be it - phone was too old to meet the "minimum android version" of the project, so must have been filtered-out in that list.  Reducing android:minSdkVersion makes it work.


How to prove that if the language L is regular , then K is also regular

Question: Let $L$ be any language over $\{a,b\}$.
Let $K$ be the language : $K=\{v:va \in L \}$
In other words, the word $v$ is in $K$ if he has the properties that if we add an $a$ at the end of $v$ we get a word of $L$
Show that if $L$ is regular then $K$ is also regular.
Watch out : Do not mistake $K$ with $L \circ\{a\} $
Example : if $L$ is represented by the regular expression $(ba)^*$ then $K$ is represented by $(ba)^*b$
So now it's said that to proove this, an option could be that we can show how we can modify an automaton that recognize $L$ to get an automaton that recognize $K$. A formal proof is not required but we have to be clear. We can also show an example.
Based on this last paragraph i started to draw an automaton for both $L$ and $K$ but i am not sure what to do next and how can this proove that $K$ is regular..
Drawing tool if u need it : http://madebyevan.com/fsm/
Thanks for your help.
Answer: You can use almost the same automaton for $K$, changing just which states are accept. State $x$ will be accept state for new automaton iff $\delta(x, a)$ is accept state for old automata.
Assume word $va \in L$. Then original automaton accepts this word in some state $y$, and after reading $v$ it will in in state $x$ s.t. $\delta(x, a) = y$ - so $x$ will be accept state for new automaton. Thus new automaton accepts all words $v$ s.t. $va \in L$.
Now, assume new automaton accepts word $v$ in state $x$. Then $\delta(x, a)$ is accept state in old automaton, so old automaton accepts $va$. Thus if new automaton accepts word $v$, then $va \in L$.
Answer: For the language in your example there is a simpler DFA for $K$. You can use the DFA for $L$ with one simple modification: make state $2$ the acceptor state instead of state $1$. Any word that takes the DFA to state $2$ is in $K$, because adding an $a$ to the end will drive the DFA to state $1$, where the word will be accepted.
This idea works more generally. Suppose that you have a DFA $M$ for $L$, and it has a transition $q_i\overset{a}\longrightarrow q_j$, where $j$ is an acceptor state. If a word $v$ takes $M$ to state $q_i$, the word $va$ will take $M$ to state $q_j$, so $va\in L$, and $v\in K$. Thus, you want $v$ to be accepted, so you want $q_i$ to be an acceptor state in the DFA for $K$. This is true for all $a$-transitions to acceptor states of $M$: the states at the starting points of those transitions should be the acceptor states in the DFA for $K$.
Comment: @codetime: No, it has nothing directly to do with regular expressions: it's based entirely on an understanding of how a DFA works.
Comment: Thanks for the answer, after showing and explaining that, i was wondering if this was referring to a precise rule or properties of regular expressions ? Because i don't remember seeing this. ( So i can end my proof seeing something like : this refer to this x properties) Thanks. Edit: is it this one ? : it is the language accepted by an alternating finite automaton


Partial derivatives problem

Question: I have a problem with the following paragraph:
"""
... If we set $y = f(x)$, the equation $g(x, y) = 0$ is an identity for $x \in U$; (nb we are talking about implicit function, so $y = f(x)$ is the implicit function defined by $g(x,y)$; that is to say $g(x, f(x)) = 0 \ \ \forall x \in U$)
We can then derive with $g(x, y) = 0$ respect to $x$ and obtain $$g_x + g_yy' = 0$$Hence the formula $y' = \large \frac{g_x}{g_y}$.
"""
I do not understand why if we derive with respect to $x$ we get that. Why is $$\frac{\partial g(x, y)}{\partial x} = g_x + g_yy'$$?
Answer: It's a form of the chain rule:
Given a differentiable function $f:\mathbb{R}^n\to\mathbb{R}$ and $n$ continuously differentiable functions $g_1, \ldots, g_n:\mathbb{R}^m\to \mathbb{R}$ if we define the application $F:\mathbb{R}^m\to \mathbb{R}$ by
$$
F(x)= f(g_1(x),\ldots,g_n(x))
$$
Then $F$ is differentiable and its $i$-th partial derivative is given by
$$
D_iF(x)=\sum_{k=1}^nD_kf(g_1(x),\ldots, g_n(x))\cdot D_ig_k(x)
$$
Where $D_if(x)$ denotes the $i$-th partial derivative of $f$ at the point $x$.
In your case, we have $m=1$ and $n=1$ with $g_1(x)=x$, $g_2(x)=f(x)=y(x)$ and $g=F$. Hence, there's only one partial derivative for each $g_i$ and usinge the formula above you get the result
Comment: awesome :-) can you also provide a link to this theorem?

Partial derivatives problem


Variance of the Average of Two Half Normal Distributions

Question: Say I have two independent normal distributions (both with $\mu=0$, $\sigma=\sigma$) one for only positive values and one for only negatives so their pdfs look like:
$p(x, \sigma) = \frac{\sqrt{2}}{\sqrt{\pi} \sigma} exp(-\frac {x^2}{2 \sigma^2}), \forall x>0$ and
$p(y, \sigma) = \frac{\sqrt{2}}{\sqrt{\pi} \sigma} exp(-\frac{y^2}{2 \sigma^2}), \forall y<0$.
If I pluck samples from both and then take the average $ = \frac{x+y}{2}$ I would imagine the expected value of this average to be zero but I would imagine the variance would be less than the variance of the individual distributions because the averaging of a positive and negative number would "squeeze" the final distribution.
I think the correct way to calculate it is using the following integral.
$Var( \frac{x+y}{2}) = \frac{2}{ \pi \sigma^2} \int^{\infty}_{0} \int^{0}_{- \infty} \frac{(x + y)^2}{4}exp(-\frac {x^2}{2 \sigma^2}) exp(-\frac {y^2}{2 \sigma^2}) dx dy$
But I am not sure if I am over-simplifying it. Does that logic seem correct or am I missing something?
Thank you.
Edited to mention independence and correct formulae mistakes.
Comment: Are your two half-normals independent?
Comment: If the random variable X, Y are independent then  $Var\left( \frac{X+Y}{2} \right)=\frac14\cdot \left( Var(X)+Var(Y) \right)=\frac12\cdot Var(X)$ Yes it is right that the variance is less than the variance of the individual distributions.
Comment: But I don´t think that the pdfs are valid since $\int_0^{\infty} f_X(x) \, dx \neq 1$
Comment: If they are not independent then $Var(\frac{X+Y}{2})=\frac{1}{4}(Var(X)+Var(Y)+2Cov(X,Y))$
Answer: Your approach is workable (although the $\tfrac{1}{2\pi\sigma^2}$ should be $\tfrac{2}{\pi\sigma^2}$), but there's a much easier way @callculus pointed out. Since $X,\,Y$ are independent, $\operatorname{Var}(aX+bY)=a^2\operatorname{Var}X+b^2\operatorname{Var}Y=(a^2+b^2)^2\operatorname{Var}X$, so $\operatorname{Var}\tfrac{X+Y}{2}=\tfrac12\operatorname{Var}X=\sigma^2(\tfrac12-\tfrac{1}{\pi})$. (I've used a variance from here.)
Answer: I think you can use moment generating functions to be able to get $E\big(\big(\frac{X+Y}{2}\big)^2\big)$ and $E\big(\frac{X+Y}{2}\big)$ to calculate the variance.
$$M_\frac{X+Y}{2}(t)=  E(e^{t\frac{X+Y}{2}}) = E\big(e^{\frac{t}{2}X + \frac{t}{2}Y}\big) = E\big(e^{\frac{t}{2}X}\big) + E\big(e^{\frac{t}{2}Y}\big)$$
You can calculate both of these independently:
$$E(e^{\frac{t}{2}}X) = \frac{1}{2\sqrt{\pi}}\int_0^\infty e^{\frac{t}{2}x}e^{-\frac{x}{2\sigma^2}}dx = \frac{1}{2\sqrt{\pi}}\int_0^\infty e^{{-\frac{1}{2}}\big(t^2\sigma^2 - tx + \frac{x^2}{\sigma^2}\big) + \frac{t^2\sigma^2}{2}}dx =
e^\frac{t^2\sigma^2}{2}\int_0^\infty\frac{1}{2\sqrt{\pi}}e^{-\frac{(x-t\sigma)^2}{2\sigma^2}} $$
Note that the last integral represents a normal distribution that is centred in $t\sigma$ and since the Normal Distribution is symmetric this is half of the value. Since the integral of the PDF on the entire space is 1, it means that the above mentioned integral will integrate to $\frac{1}{2}$.
$$E(e^{\frac{t}{2}}X) = \frac{1}{2}e^\frac{t^2\sigma^2}{2}$$
In similar manner you can compute $E(e^{\frac{t}{2}}X)$ but in that case the integral would be from $-\infty$ to $0$.
After that you can take the first and second derivative and get the values required to calculate the variance.
Comment: You can't use your integral-is-$\tfrac12$ argument because the $-t\sigma$ breaks the symmetry.
Comment: You're absolutely right. I just noticed my mistake.
Comment: How ? Isn't still centered around the mean, in this case the mean being $t\sigma$ ?
Comment: $\int_{-\infty}^\infty \frac{1}{2\sqrt{\pi}}e^{\frac{-(x-\mu)^2}{2\sigma}}dx = 1 $ right ?
Comment: Let $c\ne0$. For an even function $f$, in general$$\frac12\int_{\Bbb R}f(x-c)dx=\int_c^\infty f(x-c)dx\ne\int_0^\infty f(x-c)dx.$$


Value of rational functions at a point

Question: Q is a rational function with $x \cdot Q(x+2018) = (x-2018)Q(x), \forall x \notin 2018 \text { and } 0$. If $Q(1) = 1$. what is $Q(2017)$?
I tried substituting values in for $Q(x)$ but there is no way to have both $Q(1)$ and $Q(2017)$ in the same equation, perhaps im missing a property of a rational function since i haven't used it yet.
Answer: If $F(x) = xQ(x+2018)$, then $F(x) = F(x-2018)$. Hence $F$ is a periodic rational function and therefore $F$ is constant. If $F(x) = c$, then we have:
$$xQ(x+2018)=c\rightarrow Q(x+2018)=\frac{c}{x}\rightarrow Q(x)=\frac{c}{x-2018}$$
From $Q(1)=1$ we get $c= -2017$, hence $Q(x) = 2017/(2018-x)$; in particular, $Q(2017) = 2017$.
Answer: By cross-dividing, we get:
$$\frac{x}{x-2018}=\frac{Q(x)}{Q(x+2018)}$$
Then, since $Q$ is rational, we say that $Q(x)=\frac{n(x)}{d(x)}$ where $n,d$ are polynomials. Thus, we get:
$$\frac{x}{x-2018}=\frac{\frac{n(x)}{d(x)}}{\frac{n(x+2018)}{d(x+2018)}}=\frac{n(x)d(x+2018)}{n(x+2018)d(x)}$$
Now, just kind of by guessing and checking, I see that if $n(x)=C$, where $C$ is a constant, and $d(x)=x-2018$, then we have a solution to the above equation. Thus, we have:
$$Q(x)=\frac{C}{x-2018} \text{ (maybe)}$$
Now, if $Q(x)=1$, then $\frac{C}{1-2018}=1\rightarrow C=-2017$. Thus:
$$Q(2017)=\frac{-2017}{2017-2018}=2017$$
Now, this does not prove that the only answer is $2017$ since there might be other possible functions for $Q(x)$ which I haven't considered. However, $2017$ is definitely one of the possible values of $Q(2017)$. I hope this helps!

Value of rational functions at a point


Como chamar uma função que imprima o nome da função que a chama?

Question: Tenho a seguinte função:
function imprimir(id, nomeFuncao)
{
  console.log('id: ', id, 'Funcão que chamou: ', nomeFuncao)
}

Quero que a função imprimir() consiga imprimir no console.log as informações dessa chamada de função:
function criarEvento(id, oNomeDessaFuncao)
{
   imprimir(id, oNomeDessaFuncao)
}

Simulando a saída da função criarEvento();
(id: 23, Funcão que chamou: criarEvento)

Comment: Não entendi o que deseja imprimir, dê uma exemplo.
Comment: A dúvida é porque segundo essa descrição isso não faz sentido `'Funcão que chamou: ', nomeFuncao`. Minha resposta inicial interpretou uma coisa (na verdade fiz a outra interpretação possível que parece ser a que você realmente quer).
Comment: @bigown, quero que a função chamada imprima o nome da função que a chama.
Comment: e acertou na mosca.
Answer: Não é uma solução universal nem padronizada, mas alguns browsers aceitam:
function imprimir(id, nomeFuncao, frase)
{
  console.log( imprimir.caller )
}

Veja funcionando no CODEPEN.
Notar que ele retorna a estrutura toda da função. Precisaria de um parse. Tem outros métodos como o arguments.caller, considerado obsoleto pela documentação, mas pode ser interessante depende do contexto.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
Answer: Pode fazer isso:

function imprimir() {
    console.log('Funcão que chamou: ', arguments.callee.caller.name)
}

function criarEvento() {
    imprimir(); //os argumentos são irrelevantes para o problema
}

criarEvento();

Usei o arguments porque apesar de ser obsoleto é aceito em todos navegadores.
A pergunta original não explicava bem o que queria e mesmo agora ainda dá margem para querer outra coisa que eu respondo originalmente:

function oNomeDessaFuncao() {}

function imprimir(nomeFuncao) {
    console.log('Funcão passada: ', nomeFuncao.toString());
}

function criarEvento() {
    imprimir(oNomeDessaFuncao);
}

criarEvento();

Coloquei no GitHub para referência futura.


Usar forEach e useState de forma sequêncial

Question: Estou tentando fazer um dashboard com o número de alunos e posições dos mesmos em uma escolinha de futebol. Meu objetivo é que apareça um card para cada posição e o número de alunos na posição seja incrementado de acordo com as informações do banco de dados, ficando assim:
Porém, ao invés de agrupar os card e incrementar a quantidade, os cards de repetem no primeiro render e só nos próximos eles começam a agrupar, ficando assim:

O bd ainda não foi implementado, então estou usando o json-server e faço um fetch dentro de um useEffect. Informações do bd.json:
{
  "alunos": [
    {
      "id": 1,
      "nome": "João",
      "posicao_campo": "7",
      "posicao_futsal": "5"
    },
    {
      "id": 2,
      "nome": "José",
      "posicao_campo": "7",
      "posicao_futsal": "3"
    },
    {
      "id": 3,
      "nome": "Marcos",
      "posicao_campo": "3",
      "posicao_futsal": "4"
    },
    {
      "id": 4,
      "nome": "Juan",
      "posicao_campo": "4",
      "posicao_futsal": "4"
    }
  ]

Ao fazer o fetch, chamo a seguinte função:
const conferePosicaoAluno = (alunos) => {
  alunos.forEach((aluno) => {
  //Confere a posição no campo
    switch (aluno.posicao_campo) {
      case '1':
        addPosicaoCampo('Goleiro');
        break;
      case '2':
        addPosicaoCampo('Zagueiro');
        break;
      case '3':
        addPosicaoCampo('Lateral Direita');
        break;
      case '4':
        addPosicaoCampo('Lateral Esquerda');
        break;
      case '5':
        addPosicaoCampo('Meia');
        break;
      case '6':
        addPosicaoCampo('Volante');
        break;
      case '7':
        addPosicaoCampo('Atacante');
        break;
    }
    // Confere a posição no futsal
    switch (aluno.posicao_futsal) {
      case '1':
        addPosicaoFutsal('Goleiro');
        break;
      case '2':
        addPosicaoFutsal('Fixo');
        break;
      case '3':
        addPosicaoFutsal('Ala Direita');
        break;
      case '4':
        addPosicaoFutsal('Ala Esquerda');
        break;
      case '5':
        addPosicaoFutsal('Pivô');
        break;
      }
    });
  };

Na parte do front, estou usando React.js com chakra-ui.
Variáveis:
const [alunos, setAlunos] = useState('');
const [posicoesCampo, setPosicoesCampo] = useState([]);
const [posicoesFutsal, setPosicoesFutsal] = useState([]);

Funções para manipular as informações dos cards:
const addPosicaoCampo = (type) => {
  // Verifica se a posição já foi cadastrada no array de posições de campo
  let item = posicoesCampo.find((item) => {
    return item.type == type;
  });

  if (item) {
    // Caso a posição já exista, adiciona 1 ao valor
    let itemIndex = posicoesCampo.indexOf(item);
    posicoesCampo[itemIndex].value += 1;
    setPosicoesCampo(posicoesCampo);

  } else {
    // Se não, adiciona uma nova posição com o valor 1
    setPosicoesCampo((prevPosicoesCampo) => [...prevPosicoesCampo, { type, value: 1 }]);
  }
};

const addPosicaoFutsal = (type) => {
  // Verifica se a posição já foi cadastrada no array de posições de futsal
  let item = posicoesFutsal.find((item) => {
  return item.type == type;
    });

  if (item) {
    // Caso a posição já exista, adiciona 1 ao valor
    let itemIndex = posicoesFutsal.indexOf(item);
    posicoesFutsal[itemIndex].value += 1;
    setPosicoesFutsal(posicoesFutsal);

  } else {
    // Se não, adiciona uma nova posição com o valor 1
    setPosicoesFutsal((prevPosicoesFutsal) => [...prevPosicoesFutsal, { type, value: 1 }]);
  }
};

Código de renderização:
return (
  <>
    <Card icon={FaGraduationCap} title="Alunos Cadastrados" content={alunos.length} />

    {posicoesCampo.map((item, i) => {
      return (
        <Card
          key={i}
          icon={FaFutbol}
          title={`${item.position} (Campo)`}
          content={item.amount}
        />
      );
    })}

    {posicoesFutsal.map((item, i) => {
      return (
        <Card
          key={i}
          icon={FaRegFutbol}
          title={`${item.position} (Futsal)`}
          content={item.amount}
        />
      );
    })}
  </>
);

O component Card é apenas para organizar as informações e estilizar elas.
Estou há alguns dias tentando descobrir o motivo, já tentei realizar esse procedimento com um for...of assíncrono, mas também não deu certo. Caso possam ajudar, ficarei muito grato!
Comment: Já que o cenário é futebol e as posições já são determinadas, recomendo (para facilitar sua lógica) já deixar um array de objetos contendo os atributos `type` e `value` e iterar a lista específica, daria até para deixar agrupar dentro de cada objeto da lista um array contendo os jogadores. Essa simples mudança já deixaria seu código mais limpo e simples. Exemplo: `[{nome: 'Atacante', id: '7', qtd: 0, jogadores: []}]`
Se possível coloque o código da renderização também
Comment: @FelippeTadeu acho que eu entendi. Vou tentar implementar aqui e se der certo, aviso!
Answer: Baseado no comentário do @FelipeTadeu consegui desenvolver uma solução para meu problema.
Criei um objeto chamado positions, o qual dividi em 2 arrays e atribuí as posições de cada modalidade:
const positions: {
  campo: [
  {
    id: 1,
    name: 'Goleiro',
    qtd: 0,
  }
...
],
  futsal: [{
    id: 1,
    name: 'Goleiro',
    qtd: 0,
  }
...
]

Modifiquei por completo as funções addPositionCampo e addPositionFutsal, deixando-as mais simples também:
const addPositionCampo = (positionId) => {
  positions.campo[positionId - 1].qtd += 1;
  setPosicoesCampo(positions.campo);
};

const addPositionFutsal = (positionId) => {
  positions.futsal[positionId - 1].qtd += 1;
  setPosicoesFutsal(positions.futsal);
};

Como sei que o index da posição é sempre o id - 1, não me importei de deixar desta maneira.
No fetch, atribuí o resultado à variável alunos e rodei o forEach nela, chamando as funções addPositionCampo e addPositionFutsal:
useEffect(() => {
  alunos.forEach((aluno) => {
    addPositionCampo(aluno.posicao_campo);
    addPositionFutsal(aluno.posicao_futsal);
  });
}, [alunos]);

Por fim, mudei também a renderização, a qual ficou da seguinte maneira:
return (
  <>
    <Card icon={FaGraduationCap} title="Alunos Cadastrados" content={alunos.length} />

    {posicoesCampo.map(
      (item) =>
        item.qtd > 0 && (
          <Card
            key={item.id}
            icon={FaFutbol}
            title={`${item.name} (Campo)`}
            content={item.qtd}
          />
        )
    )}

    {posicoesFutsal.map(
      (item) =>
        item.qtd > 0 && (
          <Card
            key={item.id}
            icon={FaRegFutbol}
            title={`${item.name} (Futsal)`}
            content={item.qtd}
          />
        )
    )}
  </>
);

Consegui alcançar o objetivo, mostrando apenas 1 card por posição e incrementando o valor.
Resultado obtido:


Change colors of output log text from Django development server

Question: When running the django test server on a local project, can you make 400/500 errors stand out in a different color in output text?
Comment: I have colored output on OSX by default :/  What OS are you using?
Answer: The colors can be controlled using the DJANGO_COLORS environment variable. See the docs on syntax coloring.
This requires a platform which supports colors.
Comment: Where exactly do you put those export commands?  In settings.py?
Comment: They would go in your .bashrc file or in the virtualenv postactivate script if you wanted to configure the colors on a project by project basis.