Cross intersecting families bound

Question: I have been looking at the following problem
Suppose $k,l \geq 1$, $k+l \leq n$ and consider
$$\mathcal{A} \subseteq \binom {[n]} l, \mathcal{B} \subseteq \binom {[n]} k$$
Which are cross intersecting, that is if $A \in \mathcal{A}, B \in \mathcal{B}$, then $A \cap B \neq \emptyset$.
Then we must have that either $\left| \mathcal{A}\right| \leq \binom {n-1}{l-1}$ or $\left| \mathcal{B}\right| \leq \binom {n-1}{k-1}$.
This look like a simple application of Erdős–Ko–Rado, but so far I am having problems seeing it. Any help is appreciated (hints preferred).
Answer: I don't see how to apply Erdős-Ko-Rado, but you can modify Katona's double-counting proof of EKR to show that, given your hypotheses,
$$|{\cal A}||{\cal B}|\le {n-1\choose l-1}{n-1\choose k-1}.$$
The hint is to count quadruples $(C_A, C_B, S, T)$ where $C_A$ and $C_B$ are cyclic orderings of $[n]$, $S\in\cal A$ is an $l$-interval under $C_A$, and $T\in\cal B$ is a $k$-interval under $C_B$.

Cross intersecting families bound


Has there been a time the 2 NBA or NHL teams in the playoffs final series got there without losing any games?

Question: The Golden State Warriors and Cleveland Cavaliers started the 2016-2017 postseason by winning their first 10 playoff games.
Given their dominance, I'm wondering if there has ever been an NBA or NHL postseason where both teams advanced to the finals with perfect 12-0 record
Comment: I made a [separate question](https://sports.stackexchange.com/q/16180) for the MLB. The history of the MLB postseason format is interesting, compared to the NBA and NHL.
Comment: And mind you, I'd think baseball is just as interesting a field as well for such a run.
Comment: So much for that :-p
Comment: Alas, suppose you're right.  Wasn't all that long ago that baseball mirrored basketball.  Things just keep on a changing.
Comment: I agree, but the playoff format in the MLB is different. Wild cards need to win more games to win the championship. Also not all series are best of 7. The question is as interesting for baseball, but doesn't match NHL and NBA format. So perhaps there can be a separate question for MLB.
Answer: tl;dr: NO
NBA
There has not been a single team in the NBA going 12-0 into the finals. This is also due to the first round being a best of 5 game series until the 2003 playoffs. The 2000-2001 Los Angeles Lakers' actually went 11-0 into the finals before losing game 1 to the Philadelphia 76'ers. They won game 2,3,4 and 5 to win the NBA championship with a playoff record of 15-1. The best in history (so far).
Edit:
The 16-17 Golden State Warriors are the first team to ever reach the NBA Finals with a 12-0 record.
NHL
In the NHL the 1991–92 Chicago Blackhawks, 1991–92 Pittsburgh Penguins, and 1992–93 Montreal Canadiens had eleven game win streaks in the playoffs, but those streaks did not begin until later into the playoffs, such that each team lost opening round games.
Comment: @n_palum The quote "This is also due to the first round being a best of 5 game series until the 2003 playoffs" implicitly points that out, as well.
Comment: Oh yeah, not sure how I missed that.
Comment: Worth pointing out that the 11-0 was because first rounds of playoffs used to be first to 3 wins, not 4 as it is now. So essentially, both the 00'-01' Lakers essentially did the same sweeps as the 16'-17' Warriors.


Counting consecutive values each three times in a data frame in R

Question: I have this
df<-cbind(
t1=c(1,1,1),
t2=c(1,1,1),
t3=c(0,1,1),
t4=c(1,0,1),
t5=c(1,1,1),
t6=c(1,1,1),
t7=c(1,1,0),
t8=c(0,1,1),
t9=c(1,1,1))

> df
     t1 t2 t3 t4 t5 t6 t7 t8 t9
[1,]  1  1  0  1  1  1  1  0  1
[2,]  1  1  1  0  1  1  1  1  1
[3,]  1  1  1  1  1  1  0  1  1

and I need to count the "ones" in each row in t3, t6 and t9.
Every time the counter reach 3 has to go back to zero and start over again.
In this case the results should be:
new_t3 = 0, 3, 3

new_t6 = 3, 2, 3

new_t9= 1, 3, 2

How can I count these consecutive "ones" values at t3, t6 and t9?
I've looked at rle but I'm still having trouble with it!
Many thanks for any help :)
Comment: Why the first value of new_t3 is 0 and not 2 ? isn't t3 preceded by two '1' ? Or am I not getting something ?
Comment: Also, you want to reset to zero every 3 elements, or only when the sum reaches 3 ? Please give more details of your algorithm...at the moment your expected result seems wrong according to your explanation...probably a step by step explanation for the first row could be enough
Comment: Fraid I can't make sense of the results you linked either.
Comment: the first value in t3 is 0 because the counter is empty. Every time gets a 0 at t3, t6 or t9 should start in zero independent of the 1's before. You are right, when sum reaches 3. Thank!
Comment: Ok... then the first value in t9 should be 2 ? because at t3 we have 0, then at t6 we have 3, but then there are two '1's before (and including) t9
Comment: the first value in new_t9 should be 1 because the counter should have it on it. It will be counting only the 1's after zero from t7. I know is very confusing. Thanks any way!
Answer: Something like this could work (edited to fix counts ending with 0):
dat <- as.data.frame(df)
new_t3 <- c()
for(i in 1:3){
    if(dat[i,3] != 0){
        count <- rle(dat[i,1:3])
        new_t3 <- append(new_t3, count$length[count$values == 1])
    } else{
        new_t3 <- append(new_t3, 0)
    }
}

This loops through each row for the column t1 to t3 and uses the rle function to calculate the number of consecutive values. count$length[count$values == 1] accesses the consecutive count where the value equalled 1 in the object returned by rle.  You'd have to do this for each of the column groups you're counting, e.g.:
new_t6 <- c()
for(i in 1:3){
    if(dat[i,6] != 0){
        count <- rle(dat[i,4:6])
        new_t6 <- append(new_t6, count$length[count$values == 1])
    } else{
        new_t6 <- append(new_t6, 0)
    }
}

Or somehow wrap the loop in a function or nested for loop to automate over a table. But it looks like that returns the values in your example. Note that for new_t9 this method returns 1  1 3 2 because there are two single 1 values (1 0 1) in the first row. You might have to do something to the count variable if you need to avoid that type of result (using unique or max perhaps).
Changing df to a dataframe object allowed rle to work, otherwise it couldn't access the values.
Comment: I don't get why in new_t3 you get **2,3,3**, the counter should be empty at that t3. Also, I understand the point at new_t9 and I will take only the right 1 in the df. Thank a lot!
Comment: new_t3 is 2,3,3 because there are two consecutive 1's in the first row (then 3 and 3 in rows 2 and 3). From the comments it looks like other people were expecting 2,3,3 as well -- were you not counting those two consecutive 1's in the first row?
Comment: Yes, I can't count the 1's before zero because the counter is empty in the first row at t3. Different story at t9. I know is kind of confusing (t3, t6 and t9 are my times of counting).
Answer: Here's a possible approach using a good old for-loop combined with apply :
aggregateRow <- function(row){
  result <- rep(NA,length(row) %/% 3)
  cumul <- 0
  for(i in 1:length(row)){
    cumul <- cumul + row[i]
    if(i %% 3 == 0){
      if(row[i] == 0)
        cumul = 0
      if(cumul > 3)
        cumul = cumul - 3
      result[i %/% 3] = cumul
    }
  }
  return(result)
}

res <- t(apply(df,1,aggregateRow))
row.names(res) <- paste0('new_t',c(3,6,9)) # just to give names to the rows
> res
       [,1] [,2] [,3]
new_t3    0    3    2
new_t6    3    2    2
new_t9    3    3    2

Comment: Brillant!!... but in new_t3 (which considered the data from t7 to t9) the results should be 1, 3, 2.  The counter in every row when reaches 3 stops counting and get the maximun which is 3 and when find a zero start in zero.  Perhaps I'm not explaing well this process. Thank a lot any way!


Why Xcode 11 beta can't use C++17's  header?

Question: I need to use C++ 17's filesystem header for my project. As far as I know, Apple finally made it available with Xcode 11 and with macOS Catalina. I'm on the latest (beta 3) Xcode 11 and I use macOS Catalina public beta 2, so in theory it should work. But for some reason it's not, and Xcode gives errors like:
'~path' is unavailable: introduced in macOS 10.15

If I set the C++ standard library in Build Setting to libstdc++ from libc++ these error emssages gone and I got a warning:
include path for stdlibc++ headers not found; pass '-stdlib=libc++' on the command line to use the libc++ standard library instead

and a ton of errors with missing iostream and cstddef in various files. What could I do to make filesystem work?
Edit: a minimal code example
#include <filesystem>
#include <iostream>
#include <string>

bool isPathDir(std::string pathString);

int main(int argc, char *argv[])
{
    std::string pathString = "../test.jpg";
    if (isPathDir(pathString)) {
        std::cout << "This is a directory!" << std::endl;
    } else {
        std::cout << "This is not a directory" << std::endl;
    }
}

bool isPathDir(std::string pathString)
{
    std::filesystem::path path(pathString);
    return std::filesystem::is_directory(path);
}

Comment: Do you happen to have a back-deployment target older than macOS 10.15 specified? This would appear on your command-line as something like `-mmacosx-version-min=`.
Comment: Do you have a [mcve] that's failing and you can show us? How did you set up your project? Perhaps you need to add flags (explicitly or through a toggle) to enable C++17?
Comment: As far as I know, Apple no longer ships libstdc++ with Mac OS; so that really shouldn't be a choice in Xcode. I'll let people at Apple know. But that doesn't answer your question.
Comment: @Someprogrammerdude I added a simple example code snippet. I set up this project as a Command Line application, and added GoogleTest and OpenCV libraries to it with some opencv specific flags.
Comment: @DonátHorváth A "code snippet" is a *far cry* from a [mcve] - which is what was requested.
Comment: @JesperJuhl Fair enough, updated the snippet!
Comment: @MarshallClow Oh, thats answers the "include path for stdlibc++ headers not found" part!
Comment: @LouisDionne Oh yes, that was the problem! As soon as I set the deployment target to 10.15 the code build perfectly! I've never heard of deployment targets before, thank you very much!
Answer: Promoting my comment into an answer:

Do you happen to have a back-deployment target older than macOS 10.15 specified? This would appear on your command-line as something like -mmacosx-version-min=<value>.

@LouisDionne Oh yes, that was the problem! As soon as I set the deployment target to 10.15 the code build perfectly! I've never heard of deployment targets before, thank you very much!

Just to explain what's going on here, the issue is that support for <filesystem> was only introduced in Mac OS 10.15. When you use -mmacosx-version-min=XYZ, you tell the compiler that your program should be able to run on versions of Mac OS all the way until version XYZ. If you use a version older than 10.15, we nicely tell you at compile-time that you can't use <filesystem>, because that would be a runtime error (likely symbol missing from libc++.dylib) if you tried running the program on a version of Mac OS older than 10.15.


approach for arranging songs with two electric guitars

Question: What are some things I should consider when arranging guitar parts in songs with two guitars?  Until now I have just followed my instinct, but it would be nice to have some theory to inform my decisions.
Here is a typical example:

These are all the same chord--a C major barre chord. But there must be differences between them right?  Is the difference a musical one (i.e. making sure the chords sound balanced) or a production one (making sure the guitars sit in the right frequency in an audio mix?
Note:  two similar-sounding guitars (distortion) in rock setting (accompanied by bass, vocals, drums); not too technically proficient, but "figures" like arpeggios and lead riffs are present; no whammy or wah or reverb or chorus or any of that; style is poppy rock (think The Cars)
I don't really know how to ask my question . . . I suppose I am just looking for some things to consider when assignment parts to guitars.
Thank you!
Comment: Here's a bunch of tips and tricks you could do https://music.stackexchange.com/questions/80277/how-to-play-songs-that-contain-one-guitar-when-we-have-two-or-more-guitarists/80278#80278
Comment: @piiperiReinstateMonica this is great--thank you.  Not much theory involved, but certainly helpful
Comment: No problem - the difference between theory and practice is not always clear. If you can _hear_ it, then it's not theory anymore?
Comment: I won't delete my answer, because I think I answered the text of the original question in a way that might be useful to a future searchers, but I can't elaborate on the bounty clarification; you'd probably have more luck attracting answers if you tagged the question [production] and [acoustics].
Comment: We need to know:
Is it just the two electric guitars, or are there other instruments playing?
Are they technically proficient?
What style of music?
Comment: And you should maybe consider:
Should the tone of the instruments be identical or easily distiguishable?
Are they using pedals? What pedals? Have they both got whammy bars?
Is the whole thing chordal or will there be figures, arpeggios etc?
You could give the top note of your C chord only to one of the gtrs. He/she would then be able to play it with real attention to detail: with vibrato for example, or bending up to it. You could give such expressive parts to each of them in turn. And you could pitch them in the tenor range. You could let one player act as the bassist.
Comment: For a big change of texture they could switch abruptly to etouffée. You could share out ten-note, 3-octave broken chords between them. You can do floaty things with up-bends on Gtr1 and down-bends on Gtr2, arranged up down up down... Going back to your chords, yes, they all sound different. #1 is thick, but if the gtrs sound like each other #2 and #3 aren't *very* different. Interlocking notes is another possibility. You could impose a restriction; eg no-one ever plays more than two notes at once. I'd enjoy doing it like that. Lines more than chords. Depends on the style though.
Answer:
What are some things I should consider when arranging guitar parts in songs with two guitars?

Rock guitar arrangement tends to be for "lead" and "rhythm" guitar; this is not universally true, especially if you dig into particular subgenres, but it's a relatively safe way of doing things.
Rhythm guitar forms part of the "rhythm section" with the bass and drums; these instruments provide the most basic elements of the song as a backdrop for everything else. Rhythm guitar plays [rhythmically and/or harmonically] repetitive figures, usually riffs, but sometimes improvised comping over chord progressions.
Lead guitar, confusingly, often plays as part of the rhythm section too, sometimes going as far as to play in unison with the rhythm guitar for entire sections of song; I personally think unison guitars are overused in rock music, but it's a safe genre convention that won't draw too much negative attention. Where rhythm guitar is expected to be predicable and keep to the background, lead guitar might be expected to add fills or harmonies where appropriate, and usually takes the guitar solo if applicable.
Sometimes lead guitar plays a riff that could be a rhythm guitar line because the rhythm guitar is playing something even more basic, e.g., chugging away on power chords.
The distinction between the rhythm and lead part can get a little arbitrary, especially if you have a lead guitarist that plays extremely long unisons with the rhythm guitar and both guitarists divvy soloing duty between them. I would contend that in many cases, this indicates a failure in arrangement.

These are all the same chord--a C major barre chord. But there must be differences between them right?

If it sounds different, then yes; if not, then no; test it and find out. Breaking up solo-guitar voicings across two different guitars like in examples two and three probably isn't making the most of your two guitars; but one obvious reason to try it out would be if you had two guitars with very different tones.
The main reason I would break up a chord between two guitars is to play voicings that are not possible on a single guitar; closed ukulele voicings, huge multi-octave chords, even monstrous polychords and dense walls of muddy noise. In these cases, neither guitar is really acting as rhythm or lead, they're working together to provide a single sound.


error: cannot find symbol FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());

Question: I'm using flutter , and I tried to use Native Ads following this doc
all ads are working fine but Native ad doesn't work and it fails building the app showing this error

error: cannot find symbol     FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());

this is MyActivity.java file :
<code>package tech.devm.movies_torrent;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.firebaseadmob.FirebaseAdMobPlugin;

import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.google.android.gms.ads.formats.UnifiedNativeAdView;
import io.flutter.plugins.firebaseadmob.FirebaseAdMobPlugin.NativeAdFactory;
import java.util.Map;

public class MainActivity extends FlutterActivity {
  @Override
  public void configureFlutterEngine(FlutterEngine flutterEngine) {
    flutterEngine.getPlugins().add(new FirebaseAdMobPlugin());

    FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());
  }

  @Override
  public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
    FirebaseAdMobPlugin.unregisterNativeAdFactory(flutterEngine, "moviesTorrentAdFactory");
  }
}

class NativeAdFactoryExample implements NativeAdFactory {
  @Override
  public UnifiedNativeAdView createNativeAd(
      UnifiedNativeAd nativeAd, Map<String, Object> customOptions) {
    // Create UnifiedNativeAdView
  }
}
</code>
is there should be any changes to Manifest.xml file ? or am I missing something ?
I've cleared the build using (flutter clean ) many times but nothing works
any help would be much appreciated
Comment: @rounpaleum , no bro , I haven't found a solution yet , and I've delayed to work on this to do other things
Comment: same issue. did you solve it?
Answer: I was also having the exact same issue. This is how I fix it!
Seems that this error is related with the NativeAdFactory file (eg: ListTileNativeAdFactory.java) and the layout at app/src/main/res/layout/list_title_native_ad.xml
If you go to the Google Codelabs example at https://github.com/googlecodelabs/admob-inline-ads-in-flutter/tree/main/complete and copy those files exactly like the example you will solve that problem.


emacs elisp send line if no region active python-mode

Question: I want to create a command where the region is sent if active, and if not, the current line/statement is evaluated and point is taken further to the next statement.
I started with This solution.
Now I can't get the (python-shell-send-region) to work though as I don't know how to pass the beginning and end of the region to it.
So far I have this:
 (defun my-python-send-region (&optional beg end)
   (interactive)
    (if (use-region-p)
      (python-shell-send-region)    (let ((beg (cond (beg beg)
                    ((region-active-p)
                     (region-beginning))
                    (t (line-beginning-position))))
         (end (cond (end end)
                    ((region-active-p)
                     (copy-marker (region-end)))
                    (t (line-end-position)))))
     (python-shell-send-region beg end)
     (python-nav-forward-statement))))

 (add-hook 'python-mode-hook
       (lambda ()
     (define-key python-mode-map "\C-cn" 'my-python-send-region)))

UPDATE:
With Andreas' and Legoscia's suggestions I changed the structure a bit.
Now I get an error (Invalid function: (setq beg (point)) for:
 (defun my-python-send-region (&optional beg end)
  (interactive)
  (if (use-region-p)
    (python-shell-send-region (region-beginning) (region-end))
   ((setq beg (point))
    (python-nav-end-of-statement)
    (setq end (point))
    (python-shell-send-region (beg) (end)))
    (python-nav-forward-statement))))

However, this works:
 (defun my-python-send-region (&optional beg end)
 (interactive)
 (setq beg (point))
 (python-nav-end-of-statement)
 (setq end (point))
 (python-shell-send-region beg end))

Comment: Sending a region or line is error-prone due to Pythons sensitiveness WRT whitespaces. Rather use commands adressing Python forms at point - sending block, statement, whatever.
Answer: An alternative approach which might work is to try the whole-line-or-region package from melpa. This package sets up things so that if you call a command which expects a region, but no region is defined, it will basically set a region which is equal to the current line. Essentially, this causes commands which expect a region to work when no region is defined on the current line. I have this in my init.org file

Allow region oriented commands to work on the current line if no
  region is    defined.

   #+BEGIN_SRC emacs-lisp
     (use-package whole-line-or-region
       :ensure t
       :diminish whole-line-or-region-mode
       :config
       (whole-line-or-region-mode t)
       (make-variable-buffer-local 'whole-line-or-region-mode))

Comment: it doesn't move one line ahead, but I can fix it by recording a quick macro when I use it a lot
Answer: In this part:
(if (use-region-p)
  (python-shell-send-region)

you need to pass the beginning and end of the region to python-shell-send-region.  It only gets those values automatically when called interactively.  When you call it from Lisp code, you need to pass the values explicitly:
(python-shell-send-region (region-beginning) (region-end))

Answer: Updated answer: the python-shell-send-defun does not always send the current statement/line (it is not meant to do that), so I replaced it with a function from elpy
(defun python-shell-send-region-or-line nil
  "Sends from python-mode buffer to a python shell, intelligently."
  (interactive)
  (cond ((region-active-p)
     (setq deactivate-mark t)
     (python-shell-send-region (region-beginning) (region-end))
 ) (t (python-shell-send-current-statement))))

(defun python-shell-send-current-statement ()
"Send current statement to Python shell.
Taken from elpy-shell-send-current-statement"
(interactive)
(let ((beg (python-nav-beginning-of-statement))
    (end (python-nav-end-of-statement)))
(python-shell-send-string (buffer-substring beg end)))
(python-nav-forward-statement))

I use cond for if in case I want to add cases. Setting deactivate-mark is to deselect the region if selected. If no region is selected, I also navigate forward a python statement.
Comment: When I use this without an active region, I get error: 'Wrong number of Arguments: (1 . 1), 0
Comment: the "wrong number of arg..." was from a move-end-of-line in the previous answer, which needed an argument nil. The updated answer has that functioned removed anyway.
Comment: This is very nice - the only glitch now is that it jumps ahead one statement even if a region is selected, which might make you miss part of your code if you keep going continuously.
Comment: On my emacs, when a region is selected, it will send the region to the interpreter and unselect the region without moving forward one statement. If a region is not selected, then it will send the current statement AND move one statement forward. If you want to not move a statement forward, then remove (python-nav-forward-statement) from python-shell-send-current-statement. Or you might want to replace (python-nav-forward-statement) with (next-line) (move-end-of-line nil)


Proof the following inequality: $ (x -\frac{x^k-r}{kx^{k-1}})^k \geq r $

Question: Given that $k \geq 2$, $r \geq 1$, $x > 0$ and $x^k \geq r$, I am supposed to proof that
$(x -\frac{x^k-r}{kx^{k-1}})^k \geq r $. It also says, Bernoulli's inequality might me helpful, but so far I had no success.
I only came this far:
$(x -\frac{x^k-r}{kx^{k-1}}) = \frac{kx^{k} - x^k +r}{kx^{k-1}} = \frac{kx^{k} - x^k +r}{kx^{k-1}} = \frac{(k-1)x^{k} +r}{kx^{k-1}}  $
And that if  $(\frac{(k-1)x^{k} +r}{kx^{k-1}})^k \geq (\frac{k-1+r}{k})^k = (1 + \frac{r-1}{k})^k $ was true then I could use Bernoulli, but I have no Idea how to actually show that this ist true. So some help would be appreciated.
Answer: Bernoulli's inequality does help:
$$
\left(x -\frac{x^k-r}{kx^{k-1}}\right)^k =
x^k \left(1 -\frac{x^k-r}{kx^{k}}\right)^k
\ge x^k \left(1-k\frac{x^k-r}{kx^{k}}\right) = r \, .
$$
The inequality can be applied because
$$
 -\frac{x^k-r}{kx^{k}} \ge -\frac 1k > -1 \, .
$$
This works for all positive $x$, not only if $x^k \ge r$. It shows that the Newton iteration for finding solutions of $x^k - r = 0$ produces only values which are all greater than (or equal to) $\sqrt[k]{r}$.
Another way to obtain this result is to use that the function $f(x) =  x^k-1$ is convex:
$$
 x^* = x -\frac{x^k-r}{kx^{k-1}} = x - \frac{f(x)}{f'(x)}
$$
implies that
$$
 f(x^*) \ge f(x) + (x^*-x) f'(x) = 0 \, .
$$


What is the difference between pulsar and kafka in regards to consumption?

Question: In order to consume data from Kafka, we can have multiple consumers on a topic, totally decoupled. Then, what is meant by no shared consumption on the page(https://streaml.io/blog/pulsar-streaming-queuing) which shares differences between kafka and pulsar?
Comment: I feel like that page clearly describes what you're asking... "there can be only one single consumer in a subscription (consumer group) consuming a topic partition at any given time"... I think you are trying to compare **queueing** to Kafka consumers?
Answer: In his blog, Sijie is referring to shared messaging as queuing. With queuing messaging, multiple consumers are created to receive messages from a single topic. Which consumer gets the message is completely random.
The issue with implementing the messaging pattern with Kafka lies in way that Kafka consumers mark that they've consumed a message. Kafka consumers use what's called a high watermark for consumer offsets. That means that a consumer can only say, "I've processed up to this point" rather than, "I've processed this message."
Consider the scenario in which multiple Kafka consumers from the same consumer group were processing from the same topic partition and one of the consumers fails due to an exception while the other succeed. Because Kafka does not a have a built-in way to only acknowledge a single message, and only uses a high-water mark, the failed message would be erronously marked as consumed when in fact it failed and needs to be either reprocessed or published to an error queue, etc.
In order to avoid this situation, you would need to have just a single consumer per partition which limits the comsumption throughput of the topic. Which in turn requires you to increase the number of partitions in order to meet your throughput needs.
There is a detailed explanation in this blog post


Evento onclick em uma lista mostrar uma imagem

Question: Preciso de ajuda em um evento onclick:
Ao clicar em um texto dentro de uma lista

. Gostaria que mostrasse uma imagem em uma div ao lado.
Como faço isso?
Comment: deixa a `div` com a atributo css `display: none` e quando clicar no elemento muda pra `display: block` por exemplo
Comment: Ricardo... teria algum exemplo pra indicar?
Answer: Clicando em um elemento da lista a imagem vai aparecer na div e o texto vai mudar, e ao clicar de novo volta como era. Explicação do código comentado no script com //comentário aqui

function imagem(){
 var img = document.getElementById("img")
 var imagem = document.getElementById("imagem")
 if(img.style.display == "none") { //verifica se a imagem está sendo exibida, se não estiver vai executar os comandos abaixo e se tiver vai executar o else
   img.style.display="block" //exibe a imagem
   imagem.innerHTML = "CLIQUE DE NOVO" //altera o texto
 }
 else { //se a imagem estiver sendo exibida vai executar os comandos abaixo
   img.style.display="none"; //oculta a imagem
   imagem.innerHTML = "CLIQUE AQUI" //altera o texto
 }
}
.div1 {
width:50%;
float:left;
}
.div2 {
float:left;
width:50%;
}

CLIQUE AQUI

Comment: Perfeito...Muito obrigado!!!!
Answer: Ao clicar no texto do
 ele executa a função, que vai mudar o display da imagem para que ela possa aparecer:

function aparecer(){
   imagem = document.getElementById("imagem");
   imagem.style.display = "block";
}
.principal{
   display: flex;
   justify-content: center;
   align-items: center;
}
.principal ul{
  list-style-type: none;
}
#imagem{
   display: none;
   width: 200px;
   height: 60px;
}
#texto{
  cursor: pointer;
}
<!DOCTYPE html>

  <title>teste</title>

Clique Aqui

Comment: Perfeito...Muito obrigado!!!!


Can I re-string my 12 string guitar with strings of different octaves?

Question: I have an Ibanez 12-string guitar. I've been thinking of changing strings, but instead of simply replacing the octave strings, I would like to put on pairs of the same strings. So my question is:
What should I do to prevent my guitar from breaking? (due to the greater tension it will be under)
Should I always de-tune it after I finish playing?
Comment: Do you mean you want all *lower-octave* strings or all *higher-octave* strings?
Answer: I think this project of yours would be entirely feasible and you should try it.
There would be no appreciable difference in overall tension on the neck by replacing the thinner of each pair of strings with a duplicate of its lower-octave pair (or vice-versa) — I've done the maths.
Here is a typical set of strings for an acoustic 12-string guitar, gauge 12 through 52, provided by D'Addario (archived link, updated link). The chart below lists the exact tension of each string when tuned to standard pitch.
EJ39 Tension Chart

Item #
Note
Diameter in
Diameter mm
Tension lbs
Tension  kg

PL012
E
0.012
0.3000
23.36
10.60

PL012
E
0.012
0.3000
23.36
10.60

PL016
B
0.016
0.4060
23.31
10.57

PL016
B
0.016
0.4060
23.31
10.57

PB025
G
0.025
0.6350
32.81
14.88

PL010
G
0.010
0.2500
22.94
10.41

PB032
D
0.320
0.8128
29.93
13.58

PL014
D
0.014
0.3600
25.24
11.45

PB042
A
0.042
1.0668
28.93
13.12

PL020
A
0.020
0.5080
28.91
13.11

PB052
E
0.052
1.3208
24.23
10.99

PB030
E
0.030
0.7620
33.65
15.26

The total tension on the neck for these string gauges at standard pitch adds up to 319.98 lbs or 145.14 kg.
If you were to take each pair of strings, remove the thinner higher octave string, and replace it with a wound lower octave string, the overall tension would only be 325.12 lbs or 147.47 kg. This is only a 1.6% increase in string tension.
You would probably not have to make any adjustment to the truss rod tension on the neck of the guitar to accomplish this.
What you would have to do is to pay a professional guitar repair technician to permanently modify the nut of the guitar to widen the slots that the strings fit into, so that they would sit at the proper height. Furthermore, this would be best attempted on a 12-string guitar that has a wide nut in the first place. Some 12-string guitars have a fingerboard width of 48mm, whereas others (the classic Rickenbacker electric for example) have a tremendously narrow fingerboard width of only 41.5mm.
The problem is that the extra low strings (which are wound and thicker in diameter) would need sufficient extra space between strings so that they could vibrate freely and would not clash into their neighbors while vibrating.
I think this could work if:

You have a guitar with a wide fingerboard

You have a guitar repair technician remove the original nut, set it aside and save it (so you could convert the guitar back to its original state later on)

You have the guitar technician cut an entirely new nut with the correct slot sizes and with a tiny bit of extra width between the string pairs. (You might have to be willing to let the technician try this several times with several blank nuts until he gets it right. Blank nuts are not expensive but the labor to shape and cut them is.)

You are willing to strum the guitar softly so that the strings don't clash into each other and create a lot of glitchy noise.

Overall, I don't think any modifications to the bridge saddle would be necessary, but a guitar technician might say otherwise.

I have a further suggestion, however: Assemble a custom set of individual strings based on the lightest gauge set commonly available for a 12-string acoustic guitar. For instance, D'Addario has a set that goes from 9 to 45-gauge (updated link):
EJ41 Tension Chart

Item #
Note
Diameter in
Diameter mm
Tension lbs
Tension  kg

PL009
E
0.009
0.2280
13.14
5.96

PL009
E
0.009
0.2280
13.14
5.96

PL013
B
0.013
0.3300
15.39
6.98

PL013
B
0.013
0.3300
15.39
6.98

PB021
G
0.021
0.5334
22.95
10.41

PL008
G
0.008
0.2000
14.68
6.66

PB029
D
0.029
0.7366
24.85
11.27

PL011
D
0.011
0.2790
15.58
7.07

PB038
A
0.036
0.9144
21.37
9.69

PL016
A
0.016
0.4060
18.50
8.39

PB045
E
0.045
1.1430
18.39
8.34

PB026
E
0.026
0.6604
24.85
11.27

I would suggest trying this solely to minimize the problem of the pairs of lower-octave strings crashing together when strummed hard. The overall lower neck tension would not be the reason for my suggesting this. But in doing so, you will need a truss rod adjustment in addition to the replacement, custom-shaped-and-cut nut, to account for the much lower overall neck tension of this set.
In either case, this experiment should be entirely reversible by removing the new nut, replacing the original nut, re-stringing with the original gauge strings, and doing a truss-rod adjustment.
I think this would be a worthwhile experiment.

Footnote:
Stringing a 12-string guitar with unison pairs of strings is not a new idea. Many variations on this idea have been tried and are available from the Veillette guitar company in Woodstock, New York. Have a look at their various models (which are hand-built according to a customer's specifications and are very expensive.) If you have any specific questions about modifying your own guitar, I suggest that you contact Veillette and ask them for advice.
Comment: Excellent answer Wheat, it's always good to see hard data combined with experience.
Comment: Okay - Even though your answer leads to  opposite conclusion of mine, I'm upvoting because you took the extra time to validate what I suspected might be true about the relative tension issue.  Also, I suppose if someone has the money to conduct such an experiment - it might be interesting to see what will happen.  It's definitely not for me - I don't think I would like the sound or feel (even if it would play - which I still have my doubts) - but I would love to know the results if anyone wants to do the experiment.  Wheat I think you should try it if OP does not report back in 3 months ;-)
Answer: I personally would not try it.     I think it's a bad idea for several reasons.
Reason One - Doubling the 4 wound (fattest strings) might put  more tension on the neck than the guitar is built to handle.  A Twelve string guitar already has far more tension on the neck than a six string.  The fact that 12 strings add more tension is the reason many folks tune their 12 strings a half or whole step flat.  I would not want to take a chance on increasing the tension.  But this is the least of my concerns actually since the octave strings might add almost as much tension as the extra wound strings (since they will be tuned an octave higher).  I have not done the research to see how much added tension would actually be involved.
EDIT - now that trusted community member Wheat Williams has done the actual research I must say that added tension is NOT in fact a concern (because there won't be any added tension which makes the premise of the question incorrect).
Reason Two - The nut slots will not accommodate two low E strings and two low A strings.  And there may not be enough real estate (space between existing slots) on the nut slot to cut the thin slots wide enough without compromising the strength of the nut.
Reason Three - Even though the nut width and fingerboard are wider to make room for twelve strings, if you double all your bass strings, the space between the pair of low E's and the pair of low A's etc. - will be so smaller and it would be more difficult to isolate the strings. You would have trouble fretting one pair without accidentally touching a string in the adjacent pair because the pairs would end up closer to one another.
Reason Four - Even if the nut could handle all those large slots - note that the pairs are normally closer to each other than to the next string in the adjoining pair.  They are close enough to be treated as one string so you can fret them both with the same fingertip.  Even if your fingertips were wide enough (and strong enough) to fret two wound low E strings simultaneously, they would have to be so close together that they would collide with each other when they vibrated.  Your heavier strings have a much wider oscillation envelope than your unwound treble strings.  They need room.  A pair of wound .047 E strings or .039 A strings close enough together to fret as a single string would not play because they would clang together when they vibrated.
Reason Five - Oh never mind I think we have enough already .......
Finally - musically it would defeat one of the unique properties that make a twelve string sound different than two six strings playing the same thing simultaneously.  Having the octave difference adds a unique flavor and depth to the sound of each note and makes it far more interesting than simply doubling the note.  The only reason your treble strings are doubled is that it would be impossible to make a string gauge thin enough to be an octave higher than the b or high e string - so the compromise is to double those.
Regardless of increased tension which may be less than you think because you would be tuning the extra bass strings in unison vs. octaves, there are too many other reasons that you simply can't do this and would not want to.
But I do admire that you are thinking outside the box.
Comment: your Reason One is incorrect. I have actually calculated the change in tension for a typical set of strings and it is negligible. I will explain in my own answer below.
Comment: **Reason Three** doesn't make much sense to me. Thick strings are actually easier to fret (easier to feel and cut less into the flesh); only if you increase the tension or action then the required force becomes a problem, but that wouldn't apply here. **Reason Four b)** is also only partially correct, because if the strings are tuned in unison they will be able to vibrate in _phase-locked mode_, i.e. each goes out of the other's way at exactly the right time. Not sure how much colliding would happen before they sync; at any rate that might in itself give an interesting sound.
Comment: @WheatWilliams  I'm glad you calculated the tension.  I suspected that might be the case.  That's why I put "might" instead of would.  Also I alluded to the possibility that there would be little increased tension at end of answer and in a comment to the now deleted answer.
Comment: @leftaroundabout  Reason Three is supposed to be about distance between pairs of strings (not how easy to press down).  Notice how on a bass guitar the strings are farther apart than on a regular guitar?  If the nut slots on the bass were as close together as on a 6 string guitar you might accidentally fret two strings when trying for one - no?
Comment: ...no, not really. At most you'd be forced to _damp_ the adjacent strings. The larger spacing between the strings on electric bass at the bridge is mostly to give enough space for plucking / picking, but at the nut, the space could easily be much narrower (many bass necks are in fact more tapered than guitar necks, and could be yet more tapered, except there's no reason why they should be).
Answer: This is extremely common in Mexican music, the artist will use pairs of the same strings and take off the 2nd low E string and play with 11 strings, of course, if you do this you will still need to adjust the gaps in the nuts to fit the strings


On the Limit of Stirling's Approximation

Question: I have recently proven the following curious identity: For real $x \geqslant 1$,
\begin{align}
\lfloor x \rfloor! = x^{\lfloor x \rfloor} e^{1-x} e^{\int_{1}^{x} \text{frac}(t)/t \ dt}
\end{align}
where $\text{frac}(x)$ denotes the fractional part (function) of $x$. A proof follows from an application of Legendre's Theorem on the order of a prime divisor of the factorial function and an identity involving the de Bruijn function.
An asymptotic expansion of the integral as $x \to \infty$ yields Stirling's Approximation, hence the title of the post. Is this exact result known in the literature?
Thanks!
Comment: +1: Very nice! Is the proof too involved to post here?
Comment: The proof of a much more general identity is a bit involved and too long to post here. The identity above is a special case.
Comment: @Aryabhata: See my recent post below.
Comment: Thank you for notifying me. I already did (and voted) :-)
Answer: That works. There are two parts. Write $x = n + \delta,$ with $n \in \mathbb Z$ and $0 \leq \delta < 1.$
Your identity
$$ \lfloor x \rfloor! = x^{\lfloor x \rfloor} e^{1-x} e^{\int_{1}^{x} \text{frac}(t)/t \ dt}.$$
becomes
$$  n! = (n + \delta)^n \; e^{1-n} \; e^{-\delta} \;  e^{\int_{1}^{n} \text{frac}(t)/t \ dt} \;  e^{\int_{n}^{n + \delta} \text{frac}(t)/t \ dt}  $$
As the left hand side $n!$ is independent of $\delta,$ we need the factor that depends on $\delta$ to be a constant (but depending on $n$). Note that
$$  {\int_{n}^{n + \delta} \text{frac}(t)/t \ dt} = \delta + n \log \left( \frac{n}{n+\delta} \right)  $$
So the factor
$$   (n + \delta)^n \;  e^{-\delta}  \;  e^{\int_{n}^{n + \delta} \text{frac}(t)/t \ dt} =  (n + \delta)^n \;  e^{-\delta}  \;  e^{\delta}   \; \left( \frac{n}{n+\delta} \right)^n = n^n $$
is indeed independent of $\delta,$ and your identity is
$$  n! = n^n \; e^{1-n} \;  e^{\int_{1}^{n} \text{frac}(t)/t \ dt}  .$$
This is rather cute. Proof by induction: it is true for $n=1,$ both sides are just $1.$ In the induction step, we get the right hand side with $(n+1)$ as
$$ RHS_{n+1} = (n+1)^{n+1} \; e^{-n} \;   e^{\int_{1}^{n} \text{frac}(t)/t \ dt} \;   e^{\int_{n}^{n+1} \text{frac}(t)/t \ dt}.   $$
The final factor is what we got with $\delta = 1,$ that is
$$  {\int_{n}^{n+1} \text{frac}(t)/t \ dt} = 1 + n \log \left( \frac{n}{n+1} \right)  $$
So
$$  RHS_{n+1} = (n+1) \; (n+1)^n \; e^{-n} \;  e^{\int_{1}^{n} \text{frac}(t)/t \ dt} \; \cdot e \cdot \; \left( \frac{n}{n+1} \right)^n   $$  and
$$  RHS_{n+1} = (n+1) \; n^n \; e^{1-n} \;  e^{\int_{1}^{n} \text{frac}(t)/t \ dt}  $$ and the induction hypothesis says
$$  RHS_{n+1} = (n+1) \; n!  $$
Comment: Hi Will. Thanks for your observation. Once one has the identity, it can be proved by induction, as you've just demonstrated. My question is whether the identity has appeared in the literature.
Comment: @user02138, I really don't now.
Comment: +1.  I'm not terribly interested in whether or not this is a previously published result, I just wanted to see the proof, and this one is so nice!
Comment: @MattCalhoun, thank you.
Answer: Although my question above concerns whether or not the posted identity is a known result, I'll add the following elementary and direct proof (without recourse to Legendre's Theorem or the de Bruijn function needed for a more general version).
Proposition For real $x \geqslant 1$, the following identity holds
\begin{align}
\lfloor x \rfloor! = x^{\lfloor x \rfloor} e^{1-x} e^{\int_1^{x} \frac{\text{frac}(t)}{t} \ dt}.
\end{align}
Proof.
For each positive integer $n$, the function $f(t) = \tfrac{\text{frac}(t)}{t}$ equals $1 - \tfrac{n}{t}$ on $[n,n+1]$. Thus,
\begin{align}
\int_{1}^{n} f(t) \ d t &  = \sum_{k = 1}^{n-1} \int_{k}^{k+1} (1 - \tfrac{k}{t}) \ dt \\ & = n - 1 + \log n! - n \log n.
\end{align}
By splitting the following integral into two pieces, we compute
\begin{align}
\int_{1}^{x} f(t) \ d t & =\int_{1}^{\lfloor x \rfloor} f(t)  \ d t + \int_{\lfloor x \rfloor }^{x} f(t)  \ dt \\ & =  \lfloor x \rfloor - 1 + \log \lfloor x \rfloor! - \lfloor x \rfloor \log \lfloor x \rfloor + \int_{\lfloor x \rfloor}^{x } f(t) \ d t.
\end{align}
We need only to compute the last integral,
\begin{align}
 \int_{\lfloor x \rfloor}^{x } f(t)  \ dt & =  \int_{0}^{\text{frac}(x)  } \frac{\text{frac}(t + \lfloor x \rfloor)}{t + \lfloor x \rfloor} \ d t \\ & =  \int_{0}^{ \text{frac}(x)  } \frac{t}{t + \lfloor x \rfloor } \ d t
  \\ & =\text{frac}(x)  + \lfloor x \rfloor \log \lfloor x \rfloor - \lfloor x \rfloor \log x
\end{align}
by a change of variables from $t$ to $t + \lfloor x \rfloor$. Hence, together these identities yield
\begin{align}
\int_{1}^{x} f(t)  \ dt &  =   x   - 1 + \log \lfloor x \rfloor!      - \lfloor x \rfloor \log x,
\end{align}
which completes the proof of the claim.
Comment: @draks: Thanks. ;)


Email hosting on home's Windows server 2003

Question: I am new to Server management,
I have a static Ip address
and I bought recently a domain name, I configure the domain name to target my Ip address.
I am running windows server 2003 standard.
what are the steps to host my email adresses?
Do I need to buy anything else, or what I have is enough (static ip address, domain name, win server 2003, exchange server 2003) ??
thanks Guys
Answer:
First run a check on your IP to make sure it is not out of a dynamic IP pool. If it is - even if you have it static - there simply is no sense, because basically, every major email server will reject you as spam. Depends on the reverse domain name for the ip address ;) Use http://www.mxtoolbox.com/blacklists.aspx to find out. There is a reverse lookup link at the end after checking your blacklist.
Find out the reverse domain name attached to the ip address. You want to use THAT NAME as server name for email. Yes, may suck, but - a standard check for email servers is to check whether the domain name they have and the one the ip thinks it has match. No match -> spam.
Then you need a server ;) http://www.smartertools.com/ - smartermail, free for 1 domain, 10 email addresses. Open port 25 (SMTP) and route accordingly if you have a hardware firewall. You can also use exchange, but it is really very heavy for a handfull of users. Plus it does antispam pretty badly - smartertools handles that a lot better.
Make sure your domain IN A entry uses the name find out in my second step for MX.

FInished.


Singleton in Interface Builder with ARC

Question: My question is quite similar to this one: Use Singleton In Interface Builder?
The only difference is that I use ARC. So, if simplified, my singleton looks like that:
Manager.m
@implementation Manager

+ (instancetype)sharedManager {
    __strong static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

@end

So the question is if it's possible to adopt it for Interface Builder still being with ARC?
Of course, I understand that it might be simpler just to rewrite that class without ARC so the question is rather academic. :)
Comment: How does Interface Builder come into the picture? How is it related? What's wrong with your current code?
Comment: It's used to bind a control in IB.
Answer: When the nib is unarchived, it'll attempt to either alloc/init or alloc/initWithCoder: a new instance of the class.
So, what you could do is intercept that call and re-route it to return your singleton:
+ (id)sharedInstance {
  static Singleton *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[self actualAlloc] actualInit];
  });
  return sharedInstance;
}

+ (id)actualAlloc {
  return [super alloc];
}

+ (id)alloc {
  return [Singleton sharedInstance];
}

- (id)actualInit {
  self = [super init];
  if (self) {
    // singleton setup...
  }
  return self;
}

- (id)init {
  return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
  return self;
}

This allows -init and -initWithCoder: to be safely called multiple times on the same object.  It's generally not recommended to allow this, but given that singletons are already cases of "a place where things can get really wonky", this isn't the worst you could do.
Comment: My Xcode complained that I cannot assign self outside of a init method. I worked around this by renaming `actualInit` to `- (id)initWithNil: (id) theNil`. Works very well then.
Comment: That's correct. But I was talking about ARC. Which doesn't allow that trick `[[Singleton sharedInstance] retain]`
Comment: @codingFriend1 yes, that's a recent development in Clang.  You could solve this by changing the name of the `actualInit` method to begin with `init` (as you correctly discovered).
Comment: @Eugene so then take out the call to `retain`.
Comment: I still don't follow. If I take out `retain` – my singleton will be released when IB would be done with it.
Comment: @Eugene, using ARC, objects are automatically retained or released, you do not need to (and actually cannot) do it. The only think that you can do is set the receiving property to be strong or weak. Strong properties will keep (sort of retain) the object. Weak references will be dropped if only weak references to the object remains.
Comment: Well... I still don't fully understand why it works but it works. Please correct me if I'm wrong because I see the next flow:

IB object lifecycle:
`[[alloc] init]` (in our case it would be `[Singleton instance]`)
And for the balance, that object should be released by the environment after usage. So, internally, it would get `objc_release`.
Why it's still alive? L)
Answer: Just to be complete, here's an implementation of Singleton which might be used from Interface Builder. The difference is in actualAlloc method. As [super alloc] would still call [self allocWithZone:] – it wouldn't allocate the object.
Singleton.h
@interface Singleton : NSObject

+ (instancetype)sharedInstance;

@end

Singleton.m
@implementation Singleton

+ (instancetype)sharedInstance {
    __strong static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self _alloc] _init];
    });
    return _sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone {
    return [self sharedInstance];
}

+ (id)alloc {
    return [self sharedInstance];
}

- (id)init {
    return self;
}

+ (id)_alloc {
    return [super allocWithZone:NULL]; //this is important, because otherwise the object wouldn't be allocated
}

- (id)_init {
    return [super init];
}

@end

Comment: For everyone's (mostly mine) benefit... I [created an only-slightly modified Gist](https://gist.github.com/mralexgray/6891945) of this.  Why?  Because it is the ONLY thing that works.
Answer: @Eugene, from iOS doc set, "For historical reasons, alloc invokes allocWithZone:.", so, there is no need to reimplement the alloc method.

Singleton in Interface Builder with ARC


how to select within last 30 days from date in postgresql?

Question: sql table has data on taxi drivers, columns are :
id  integer
client_id   integer (Foreign keyed to events.rider_id)
driver_id   integer
city_id integer (Foreign keyed to cities.city_id)
client_rating   integer
driver_rating   integer
predicted_eta   integer
actual_eta  integer
first_completed_date Timestamp ,
status  Enum('completed', 'cancelled_by_driver', 'cancelled_by_client')

how to calculate 90 th percentile difference between Actual and Predicted ETA for all completed trips within the last 30 days?
select

  percentile_cont(0.90) within group (order by actual_eta-predicted_eta) as percentile_90_diff

from trips t where status='completed'

and first_completed_date > (first_completed_date - INTERVAL '30 DAY')::DATE

i m concerned with the last part - first_completed_date > - within last 30 days.
is it correct way to calculate last 30 days from first_completed_date?
Comment: There's no `first_completed_date` in the schema you provided. And `d > (d - '30 days')` will always be true, did you mean `d > (CURRENT_DATE - '30 days')`?
Comment: @Marth, sorry edited it. i dont know how the way postgre calculates last 30 days from specific date column.
Answer: You compared the "first_completed_date" to itself, however, need to compare it to the current date minus 30 days
first_completed_date > NOW() - INTERVAL '30 DAY';


numerical values of points in cantor set

Question: Let $C$ be the standard middle thirds Cantor set in the interval $[0,1]$. The "endpoints" of $C$ have very simple numerical values that can be listed off: $$0,1,1/3,2/3,1/9,2/9,6/9,7/9,1/27,2/27,7/27,8/27,... $$
What I am looking for is some numerical values of the "nonendpoints" of $C$. Specifically, is there a dense subset of the nonendpoints which has some nice pattern to its values? Can you list off some of these for me?
Comment: There's a pretty simple characterisation of the Cantor set in terms of base-$3$ expansions. $x\in C$ if and only of $x$ has a base-$3$ expansion in which no $1$ occurs.
Comment: @DanielFischer ok, but could you list a dense set of these for me? I need to make a table
Comment: Cantor set has empty interior, so it has no "non-endpoints".
Answer: For example,
$$\frac 14 = \frac{0}{3} + \frac{2}{3^2} + \frac{0}{3^3} + \frac{2}{3^4} + \frac{0}{3^5} + \frac{2}{3^6} + \cdots$$
is in the Cantor Set.
Edit: Actually, elements of the Cantor Set are of the form
$$\sum_{n=1}^\infty \frac{a_n}{3^n}$$
where $a_n$ is any sequence consisting of only $0$ and $2$'s.
So, when $a_n$ is not almost constant (an almost constant sequence is a sequence which is constant from some point on) then the corresponding number is a non-endpoint.
Edit2:
$$\frac{2}{25} = \frac{0}{3} + \frac{0}{3^2} + \frac{2}{3^3} + \frac{0}{3^4} + \frac{0}{3^5} + \frac{2}{3^6} + \cdots$$
$$\frac{11}{12} = \frac{2}{3} + \frac{2}{3^2} + \frac{0}{3^3} + \frac{2}{3^4} + \frac{0}{3^5} + \frac{2}{3^6} + \cdots$$
For further examples, you can take:
$a_n = 0,0,0,2,0,2,0,2,0,2,0,2,0, \dots$
$a_n = 2,0,2,0,2,2,0,2,0,2,0,2,0, \dots$
$a_n = 0,2,2,0,0,2,2,0,0,2,2,0,0, \dots$
$a_n = 0,0,0,0,2,2,2,2,0,0,0,0,2,2,2,2, \dots$
$a_n = 0,0,0,2,2,0,0,0,2,2,0,0,0,2,2, \dots$
etc.
Comment: interesting.  so I'm thinking we could we just change finite numbers of terms at the beginning and somehow end up with a dense set of nonendpoints...
Comment: i understand what you are saying in your edit, but I really want numerical values!
Comment: Truncate the series above for some sequences of 2's and 0's.


Specialisations in use case diagrams

Question: I am working on a use case diagram and I was wondering if this is a correct use of a Specialized use case. Here I have Create which has 3 different specialisations. What I am trying to demonstrate here is that the user can create a Team, Project or a Board. I feel this might not be the correct use of specialisation. Would it make more sense to split these into "Create Team", "Create project" etc...?
Answer: In UML a use case is a classifier and can be specialized.  From a notation point of view this is correct.  However, you shoud reconsider the wording of the names, since the specialized use case may be used or reused independently of their generalization.
What about: Create item, Create project, Create team, Create board ?
Comment: Thanks for the reply. This implementation with some word changing would be okay? Would a use case with extension points make more sense or is the way that I have done it good to demonstrate the action being carried out which is "Create". I was also looking to implement "Edit" & "Delete". Would it be better to use case with extension points or would you recommend using specialisations for Create, Edit, Delete?
Comment: @Krellex I'd tend to prefer specialization in your example: extension is for adding possibly optional sub-goals, but here the main use case (delete item) would not make any sense without the subgoals.

Specialisations in use case diagrams


Existence of model implies consistency in Cohen's book

Question: On page $13$ of his book Set Theory and the Continuum Hypothesis Paul Cohen writes:

The point of these definitions is the following obvious fact:
THEOREM $1$. ... If a set of statements $S$ has a model then it is consistent.

Sadly, I'm unable to prove this obvious fact... Thank you very much in advance for your help!
Comment: @Chantry: That's the other direction.
Comment: I am not familiar with this area, but is [this](http://math.stackexchange.com/questions/513812/showing-the-every-consistent-set-of-sentences-has-a-model) what you are looking for?
Answer: Suppose that $S$ was not consistent, let $\psi$ a statement which is both provable and refutable from $S$. And let $M$ be a model of $S$.
By the definition of the satisfaction relation, $M\models\varphi$, we know that if $S$ proves $\varphi$, then $M\models\varphi$. In particular $M\models\psi$ and $M\models\lnot\psi$. But this is a contradiction to the definition of the truth.
What have we used here? We used the fact that $M\models\varphi$ is defined in a certain way, and that $M$ cannot satisfy both a statement and its negation, which follows from the definition by induction.
Comment: @Pierre: The consistency of ZF _in particular_ is not an automatic assumption, but like any other mathematician Cohen implicitly assumes that _mathematical reasoning is possible at all_, and then offers an informal argument in the hope that the reader will consider it valid. Some readers will base their validity judgment on whether Cohen's argument can be formalized in their foundational system of choice, for others it will be a more intuitive matter. (After all, mathematicians made decisions about whether they found arguments valid for many centuries before Cantor and Zermelo ... _(contd)_
Comment: _(contd)_ ... came along, so having a formal system in mind is clearly not a prerequisite for this). In any case, which foundational system the reader prefers is not something Cohen decides. If someone reads his book with a narrow conception of what's a valid mathematical argument, and therefore rejects it, that's just too bad.
Comment: Slight correction to the above: Cohen does pledge (on p. 54) to stick to reasoning that can be expressed in ZF unless otherwise noted, but that's more of a convenient shorthand for which demands on the reader's credulity he's going to make. It still makes sense to distinguish between where he's assuming Consis(ZF) as a _technical_ statement and where he's just implicitly depending on his own mathematical reasoning being possible.
Comment: @Pierre-YvesGaillard: _By definition_, $M\vDash \neg\varphi$ exactly when $M\vDash\varphi$ is _not_ true. So we cant have $M\vDash\neg\varphi$ at the same time as $M\vDash\varphi$, because that would mean that $M\vDash\varphi$ is both true and not-true _at the metalevel_. Of course we're assuming that whatever reasoning we're using at the metalevel (which need not be ZF) is sound.
Comment: @Pierre: Can you make sense in the fact that some people believe in one god, and other people believe in another, and some people deny the existence of any deity whatsoever?
Comment: @Pierre: Um, Cohen and Nelson were different persons. They had different opinions about whether or not PA is obviously true. What is there to understand about that? -- And kindly stop "dear"ing me.
Comment: Dear Asaf: Thanks! I don't understand why "$M$ cannot satisfy both a statement and its negation", and why this "follows from the definition by induction". For instance, in Part $1$ of Cohen's Definition p. $12$, why can't we have $\overline x_i=\overline x_j$ *and* $\overline x_i\neq\overline x_j$?
Comment: Pierre, I don't have Cohen's book, so I can't quite help you by looking at it. But I can tell you that you have to assume at least that the logic you are working with is sound, and that no object is both equal and different from itself. You know, the little stuff.
Comment: If you want to work in a logic where $x_i=x_j\land x_i\neq x_j$, then perhaps classical first-order logic is not the right choice.
Comment: Dear Asaf: Thanks for your comments! Do you think it might be possible that Cohen assumes implicitly the consistency of Zermelo-Fraenkel Set Theory?
Comment: @Henning - Thank you dear Henning! It is also my understanding of Cohen's wording that ZF is not the only option, but since it *is* an option I'd rather stick to it. (Do you use the word *sound* as a synonym for *consistent*?) On p. 71 Cohen writes: "THEOREM. If ZF is consistent, so is ZF + Axiom of Regularity." Can't this suggest that, in his mind, the consistency of ZF is not always viewed as an automatic assumption?
Comment: @Pierre: Since the axiom of regularity is part of $\sf ZF$, I'm not quite sure what you mean by that. In either case, the consistency of set theory is not automatically assumed when working in set theory, since if $\sf ZFC$ is consistent then there are models of $\sf ZFC+\lnot\operatorname{Con}(ZFC)$, and inside those models $\sf ZFC$ is not consistent (although the universe of sets, and this model will disagree on what exactly constitute as the axioms of $\sf ZFC$).
Comment: Dear Asaf - Sorry if my comment wasn't clear. I'm happy that you wrote "the consistency of set theory is not automatically assumed when working in set theory". I was under the (false) impression that you were making an implicit consistency assumption in your answer. Again, I'm most grateful for your answer, I don't doubt that it is outstanding, but I'm afraid I'm not clever enough to understand it...
Comment: @Asaf: Cohen's formulation of ZF does include Regularity, but on p. 70 he temporarily excludes it: "By ZF we shall now mean ZF without Regularity and either with or withour the Axiom of Choice since this does not affect the discussion".
Comment: @Pierre: By "sound" I mean that we can trust the result of the reasoning -- say, if our reasoning proves a statement about the integers, then it will also be Platonically true. Being _consistent_ is a necessary but not sufficient condition for this.
Comment: @Henning: Thanks, and thanks for all the great comments!
Comment: @Henning - Dear Henning: Thank you very much for your comments. I'll think quietly about them. For no good reason, here is one more quotation (p. 41): "Now a statement which is provable in $Z_1$ is of course *true* in the model of integers. Also since $Z_1$ is consistent not both $A$ and $\sim A$ are provable."
Comment: @Henning - Dear Henning: The above quotation suggests that Cohen viewed Peano arithmetic as obviously consistent. But (as I'm sure you know) [Edward Nelson](http://en.wikipedia.org/wiki/Edward_Nelson) tried (in 2011) to prove the inconsistency of Peano arithmetic. I have some trouble understanding how these two facts can be compatible.


Como sair de um loop dentro de outro através de uma função no python?

Question: Oi, estou confuso e não estou conseguindo deixar meu código do jeito ideal.
O que preciso, é de sair de todos os loops através da função ask_continue()
depois de o usuário responder n no input sem sair do programa, temporariamente, coloquei exit() só pra no mínimo rodar.
aqui está o código:
print('Olá, seja bem vindo!')
programa = 0
while programa == 0:

def ask_continue():
    ask = str(input("Deseja repetir a operação? (Y/N): "))
    if ask.lower() == 'y':
        program = 0
    elif ask.lower() == 'n':
        programa =+ 1
        exit()

x = 0
while x == 0:
    try:
        a = float(input("Informe a variável 'a': "))
        b = float(input("Informe a variável 'b': "))
        campo_de_saída = a*b-a+b
        print("O campo de saída é {}".format(campo_de_saída))
        ask_continue()
    except:
        print("Valor inválido, tente novamente.")
        x = 0

Answer: Isso de sair de loops aninhados realmente é um problema de programação que dura gerações.
O comando break, como você deve saber, sai de um único for ou while, e tem que estar diretamente dentro desse for ou while- não poderia estar dentro de uma função chamada para esse fim.
Então, se o break fosse a única coisa existente, a única forma de resolver seria essa:
def funcao_que_resolve_se_sai():
    ...
    return sair_ou_nao

def funcao_principal():
    sair = False
    for laco1 in coisas1:
       for laco2 in coisas2:
           ...
           sair = funcao_que_resolve_se_sai()
           if sair:
                break
       if sair:
           break

Ou seja: você teria que guardar a decisão de sair dentro de uma variável,
e ter um if com um  break em cada laço.
Em Python, e outras linguagens de alto-nível que tem o recurso de "exceções", isso se resolve com o uso das mesmas.
Mas "exceção não é só quando acontece um erro?" - não necessariamente -
uma exceççao pode ser causada deliberadamente, com o comando raise,
justamente com o intuíto de mandar um sinal
que consiga escapar da ordem normal de execução.
O ideal é criar uma exceção personalizada, para diferencia-la,
mesmo que só de forma semântica, de uma exceção real, causada por um
problema na execução. Mas para manter o exemplo simples, vou usar
o RuntimeError mesmo:
def funcao_que_resolve_se_sai():
    ...
    if sair_ou_nao:
        raise RuntimeError()

def funcao_principal():
    try:
       for laco1 in coisas1:
          for laco2 in coisas2:
           ...
           funcao_que_resolve_se_sai()
     except RuntimeError:
         pass

funcao_principal()

Então veja como ficou- quando a exceção "RuntimeError" é causada pelo comando raise dentro da função chamada, o programa vai pular direto para
a próxima cláusula except que pegar essa exceção. Se a claúsula estiver depois dos loops que queremos deixar, ele sai de todos os loops.
Agora note uma cois a importante: eu coloco o nome da função específica no except. No seu código, você coloca except sem nada, dentro do seus laços - isso é uma prática muito ruim, já que o except sem nada pega todos os tipos de erro - inclusive erros que vocẽ não está esperando, e mais ainda, inclusive qualquer erro personalizado que você queria usar para o controle do fluxo do programa.
Por isso é muito, muito mesmo  importante sempre colocar exceções específicas quando usar o Excecept. No caso do seu código, você usa o except para tratar valores não numéricos que o usuário digita. O erro lançado nesse caso é o ValueError. Então seu programa, na parte interna dos laços, tem que capturar só o ValueError!
Essa técnica de exceções personalizadas é interessnte, por que não importa quantos loops, e quantas funções são chamadas uma dentro da outra (isso é - vamos dizer que a funcao_que_resolve_se_sai chamasse ainda uma outra função) - quando a exceção é lançada, o programa sai das funções e dos laços todos, até o Except.
Isso dá um controle muito maior do que chamar exit, porque depois do Except, você continua executando o programa na próxima linha, normalmente. (o comando pass dentro do Except não faz nada, só deixa o bloco com a sintaxe válida, por que ele não pode ser vazio)
Isso é usado em qualquer sistema grande em Python - por exemplo, em sistemas Web, os frameworks sempre chamam as funções do seu sistema dentro de uma cláusula "try--except" apropriada - se o seu código gerar qualquer erro, o except para todo o seu código, e gera uma página HTML com o código de erro apropriado - e, o servidor continua rodando normalmente, esperando outras requisições.
Por fim, a forma de personalizar uma exceção também é bem simples - é só criar uma subclasse, que pode ser vazia, de Exception:
class SairDosLacos(Exception):
    pass

def funcao_que_resolve_se_sai():
    ...
    if sair_ou_nao:
        raise SairDosLacos()

def funcao_principal():
    try:
       for laco1 in coisas1:
           for laco2 in coisas2:
              numero_ok = False
              while not numero_ok:
                  try:
                      a  = int(input("digite um número"))
                  except ValueError:
                      print("número inválido, tente de novo - ")
                  else:
                      numero_ok = True
               # codigo usando o número digitado:
               ...
               funcao_que_resolve_se_sai()
     except SairDosLacos:
         pass
funcao_principal()

(note aqui o uso  do else para o  try/except/else - o bloco else do comando try só é executado se não aconteceu nenhuma exceção - nesse caso, se o número for válido)

Há um outra forma sem uso de exceções, que não dá pra usar no seu caso, por que você não colocou seus laços principais do programa dentro de uma função - acostume-se a sempre fazer isso.
Mas além de uma exceção com o comando raise, um outro comando que sai de qualquer número de loops é o return - ele encerra a função atual imediatamente, e o controle volta para a função que chamou a atual.
Se dentro da função você não vai fazer mais nada depois dos laços (e está dentro de uma função), é só por um return.
O seu código ficaria assim:
print('Olá, seja bem vindo!')
programa = 0
while programa == 0:

def ask_continue():
    ask = str(input("Deseja repetir a operação? (Y/N): "))
    if ask.lower() == 'y':
        program = 0
        return True
    elif ask.lower() == 'n':
        programa =+ 1
        return False

def principal():
    x = 0
    while x == 0:
        try:
            a = float(input("Informe a variável 'a': "))
            b = float(input("Informe a variável 'b': "))
            campo_de_saída = a*b-a+b
            print("O campo de saída é {}".format(campo_de_saída))
            if not ask_continue():
                 return
        except:
            print("Valor inválido, tente novamente.")
            x = 0

Linguagens que não tem o mecanismo de exceções, como o C, para sair de vários laços as vezes tem o comando goto - ele pode fazer a execução do programa saltar incondicionalmente para uma linha específica dentro da mesma função.
A literatura de programação execra o goto de forma que sua menção causa "medo" em muitos profissionais experientes - por que era a única forma de modelar laços e funções antes de linguagens que tinham funções como as conhecemos hoje - só que por conta de sua flexibilidade extra, um programa poderia ficar realmente difícil de se acompanhar ou entender.
Bem usado, no entanto, ele é a forma convencional de sair de laços - um if no laço mais interno pode conter um goto para um ponto fora de todos os laços.
Reitero que goto não existe em Python - existe em C, e é a forma recomendada, por exemplo, de codificar o tratamento de erros se vocẽ está criando uma função em C que vai interagir, e ser chamada a partir de código Python.
Answer: Não entendi o que você quer fazer realmente, pois pelo que vi vc fez uma função que simplesmente ela não sai do loop...
mas vou tentar resolver veja abaixo se é isso que você quer, eu tirei estas condicionais que deixavam o loop infinito, pois para continuar o programa basta satisfazer a pergunta com y, mas fica claro que com o exit() o programa sai por completo, segue:
class Program():
def __init__(self):
    self.ask_continue()

def ask_continue(self):

    ask = 'y'
    while ask.lower() == 'y':

        a = float(input("Informe a variável 'a': "))
        b = float(input("Informe a variável 'b': "))
        campo_de_saída = a*b-a+b
        print("O campo de saída é {}".format(campo_de_saída))
        ask = str(input("Deseja repetir a operação? (Y/N): "))
        if ask.lower() == 'n':
            programa =+ 1
            exit()

if __name__ == "__main__":
     Program()


Which rows contain the specified element, using R

Question: Here's a list, each row represents an random event
      [,1]        [,2]    [,3]
 [1,] "Zebra"     "bat"   "lion"
 [2,] "crocodile" "lion"  "bat"
 [3,] "dog"       "fish"  "snake"
 [4,] "bat"       "zebra" "snake"
 [5,] "dog"       "Bear"  "bat"
 [6,] "dog"       "Zebra" "lion"
 [7,] "Bear"      "dog"   "Zebra"
 [8,] "pig"       "dog"   "snake"
 [9,] "zebra"     "lion"  "fish"
[10,] "Bear"      "dog"   "Zebra"

I'm trying to use %in% command to check which of the events have a dog in them.
Comment: `which(m == "dog", arr.ind = TRUE)`.
Answer: For basic equality, use which(., arr.ind=TRUE):
m <- matrix(1:25, nr=5)
m
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    6   11   16   21
# [2,]    2    7   12   17   22
# [3,]    3    8   13   18   23
# [4,]    4    9   14   19   24
# [5,]    5   10   15   20   25

which(m == 5L, arr.ind = TRUE)
#      row col
# [1,]   5   1

If you need set membership with %in%, it doesn't work just to replace == with %in%, unfortunately,
which(m %in% c(5L, 9L, 12L), arr.ind=TRUE)
# [1]  5  9 12

this is because m == . returns a matrix but m %in% . returns a vector (I don't recall why atm):
m == 5L
#       [,1]  [,2]  [,3]  [,4]  [,5]
# [1,] FALSE FALSE FALSE FALSE FALSE
# [2,] FALSE FALSE FALSE FALSE FALSE
# [3,] FALSE FALSE FALSE FALSE FALSE
# [4,] FALSE FALSE FALSE FALSE FALSE
# [5,]  TRUE FALSE FALSE FALSE FALSE

m %in% c(5L,9L,12L)
#  [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# [20] FALSE FALSE FALSE FALSE FALSE FALSE

We can get around this by forcing the return to be a matrix:
which(matrix(m %in% c(5L,9L,12L), nrow=nrow(m)), arr.ind = TRUE)
#      row col
# [1,]   5   1
# [2,]   4   2
# [3,]   2   3

Comment: Thanks about this info, could I only return the index of row? which means I only need return which row contain the element?
Comment: Did you try it? The return is a matrix, so if you just want rows your can use `which(.)[,1]`.
Answer: To get the row index which has the word 'dog' in it you can use rowSums as -
which(rowSums(mat == 'dog') > 0)
#[1]  3  5  6  7  8 10

data
mat <- structure(c("Zebra", "crocodile", "dog", "bat", "dog", "dog",
"Bear", "pig", "zebra", "Bear", "bat", "lion", "fish", "zebra",
"Bear", "Zebra", "dog", "dog", "lion", "dog", "lion", "bat",
"snake", "snake", "bat", "lion", "Zebra", "snake", "fish", "Zebra"
), .Dim = c(10L, 3L), .Dimnames = list(NULL, NULL))


Is there any way of proving two spaces have the same homotopy class without using directly the definition of homotopy equivalence?

Question: Given two spaces $X,Y$ homotopically equivalent sometimes it is not easy to find eplicit maps $f:X\to Y$ and $g:Y:\to X$ satisfying the definition of homotopic equivalence. I want to know if there are other ways of proving they are equivalent, probably adding some conditions on $X$ and $Y$ (like having CW-complex structure). For example, is there any situation in which having isomorphic fundamental group implies having same homotopy type?
Comment: One example is if you have a CW pair $(X,A)$ and A is contractible then $X \simeq X/A$.
Answer: There is a concept called "weak homotopy equivalence" which is defined in terms of algebraic invariants: two spaces $X$ and $Y$ are weakly homotopy equivalent if there is a map $X \to Y$ inducing isomorphisms on all higher homotopy groups.
It is known for certain classes of spaces—most notably CW complexes—that two spaces are weakly homotopy equivalent iff they are homotopy equivalent (Whitehead's Theorem). However, I can't think of a practical example where it is easier to apply Whitehead's theorem than to construct a homotopy equivalence. I've mostly seen it used to prove other things.
Comment: Especially since WT requires all the isos in all degrees to come from the *same* map.


Local Outlook 2019 JavaScript Add-In

Question: I want to create my own Outlook add-in using JavaScript.
As a first step I want to load the xml file as an add-in.
I am running a local installation of Office 2019.
So far I tried:

Outlook

adding "add Add-ins" to the quick bar (resulting in a disabled button)

Word - Downloading the Style Checker demo (https://github.com/OfficeDev/Word-Add-in-Angular2-StyleChecker)

running a localhost:1800/demo/ with the xml-file
adding to Word "Trusted Add-ins Catalogs Url"
the result is, that it is not showing up in word

My Question is, how can I add the xml file to my local Outlook 2019 installation, so that I can start working on the JS part? It is fine for me to run this from a localhost url.
Answer: It sounds like the question you're asking should be answered by this article: https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/sideload-outlook-add-ins-for-testing?tabs=windows

Local Outlook 2019 JavaScript Add-In


How to get and code for API in PayPal in HTML through jQuery or Javascript

Question: I am a web developer. I am working on PayPal. I did the code for PayPal transaction through 'Bay Now' button using script
, but I and user, both not getting any Email from PayPal after payment. Is there any other process through which user get email automatically after PayPal payment.
I also want to code for 'Check Out with PayPal' button in HTML through javascript or jquery and how to get API and code for API in HTML through javascript or jquery.
Comment: Ask PayPal tech. support. They know the answer to this question
Answer: Have you setup your IPN script yet @ your server?

Have you enabled IPN's and set the address to your IPN script @ PayPal?
To check IPN Settings go to..

Profile > My Selling Tools > Instant payment notifications (update)
PayPal IPN Docs

PayPal IPN PHP Class

PayPal IPN Example
Hope this helps...
Comment: Ah, that's your problem... PayPal's IPN services operates on the back-end or server-side. Javascript is a front-end or client-side language. You'll need to utilize php, python, ruby, or a similar language to utilize the IPN system.
Comment: Yes I have set the IPN (notificatin URL)
Comment: but its not getting any response
Comment: Is the URL pointing to a .php file that contains something similar to what the example in the response I posted above has? Also you can view your IPN history, the link is @ the IPN edit page. This may provide some helpful info as well. Also here is the [PayPal IPN Testing Docs](https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNTesting/)
Comment: I am not working in PHP. I need in Jquery or JS and I also read all the process of link 1st that you send me. I getting problem in how to call the method DoExpressCheckoutPayment and other methods in HTML in JS or jquery
Comment: I am using the BB code to process the data. Is it possible to do it in  this code.
Comment: You're referring to bulletin board code right? That's not a programming language, just a markup language to format posts in a forum. Your best bet will be to check out the examples posted above, work your way through that in PHP and post questions as needed.


When this map $f(x)=x^2$ will be a automorphism on $G$, where $G$ is a commutative group.

Question: I know that for a commutative group $G$ the map $f(x)=x^2$ is a homomorphism from $G$ to $G$.
My question : When this map $f$ will be a automorphism on $G$, where $G$ is a commutative group.
In other words, when the map $f:G\rightarrow G$ defined by $f(x)=x^2$ is an onto map for a commutative group $G$?
Comment: Do you want to restrict attention to finite or finitely generated abelian (commutative) groups?
Answer: If $G$ is finite it is equivalent to say that $f$ is injective, i.e. there are no elements of order $2$.
If $G$ is finitely generated abelian then it must be finite (bt the structure theorem on these groups) and the previous statement applies.
In general I don't know of any characterization. For example, take a field $K$ (here the group is $K$ with addition). The situation depends a lot on $K$ (consider $K=\mathbb{Q},\mathbb{F}_p,\mathbb{R},\mathbb{C}$).
Comment: To be precise, you want $K$ not to have characteristic $2$.
Comment: No, for example if you take $\mathbb{F}_2(t)$, where $t$ is a variable, then $t$ is not the square of anything (i.e. $x^2-t$ is irreducible).


$15a ≡ ca \pmod{25}$, then $15 ≡ c \pmod{25}$

Question: For which numbers $a$ is it true that if $15a ≡ ca \pmod{25}$, then $15 ≡ c \pmod{25}$?
I know that this means that $a\frac{15-c}{25}=k_1\in \mathbb{Z}$ and $\frac{15-c}{25}=k_2\in \mathbb{Z}$, but what must I show?
Comment: I changed (\text{mod}~25) to \pmod{25}.  That is standard.  It automatically generated proper spacing before and after "mod" and puts the parentheses where they should be.
Answer: HINT
Recall that if $x \mid yz$ and $\text{gcd}(x,y)=1$, i.e., $x$ and $y$ are relatively prime, then $x \mid z$.
Comment: To be "relatively prime" is to be what?
Comment: @Pinsgrair $\gcd(x,y) = 1$.
Comment: @Pinsgrair: "relatively prime" means "$\gcd(x, y) = 1$". "$(x, y)$" above is another notation for the gcd.
Comment: You mean "coprime," yes?
Comment: @user17762 What are your $x$ and $y$ here?
Comment: @user17762 $y=a,~z=15-c,~x=25$, yes? How do you know that $\text{gcd}(x,y)=\text{gcd}(25,a)=1$?
Comment: @Pinsgrair Yes. Relatively prime is another word for co-prime which is another word to mean $\gcd$ is $1$.
Comment: So the answer here is all $a$ which are coprime to $25$, yes?
Comment: @mike4ty4 Don't you mean $\text{gcd}(25,a)$?
Comment: Never mind it is a commutative function.
Comment: @Pinsgrair Yes. The answer here is all $a$'s that are coprime to $25$.


Expectation of sum of absolute values for correlated normal random variables

Question: Let $x_1, x_2, \dots, x_{N}$ i.i.d. random variables $\sim \mathcal{N}\left(0,\sigma^2_x\right)$. Further, let $z\sim \mathcal{N}\left(0,\sigma^2_z\right)$, $z$ is independent from all $x_i$.
We build random variables $y_i=x_i+\gamma z$. By construction, $y_i \sim \mathcal{N}\left(0, \sigma^2_x +\gamma^2 \sigma^2_z\right)$ -- But, $y_i$ are not independent anymore.
What is the following expectation:
$$ \mathbb{E} \sum_i \left| y_i\right|, $$
where $\left| a\right|$ is the absolute value of $a$?
Answer: Expectation operator distributes over the sum, so correlation amongst $y_i$ is not important in the calculation:
$$\mathbb E\left[\sum_{i=1}^N|y_i|\right]=N\mathbb E[|y_1|]$$
$y_1\sim\mathcal N(0, \sigma_y^2)$ where $\sigma_y^2=\sigma_x^2+\gamma^2\sigma_z^2$. You can calculate the  expected value using the mean entry of Folded Normal distribution by letting $\mu=0, \sigma^2=\sigma_y^2$. You can choose to calculate it by yourself as well, since the integral will be trivial.


Method to solve for a number in modulus equation.

Question: If you had an equation of 12 = (8000 + B) mod 13
You could guess and check a little and arrive at B = 7.
My question is what is the best way to solve these? Is there a defined method to get B?
Answer: You can reduce  $8000 \equiv 5\pmod{13}$ and get $12 \equiv (5 + B) \pmod{13}$ then subtract $5$ from each side.
Added: You can use long division to find the remainder of $8000$ divided by $13$ is $5$.  In other words, $8000 = 615 * 13 + 5$, so $8000 \equiv 5 \pmod{13}$
Comment: Can you explain the reduction to 8000≡5(mod13)  ? That's the only part I'm not following.
Comment: So will this method work for all forms of this type?
Comment: Not sure what you mean exactly.  If you divide $a$ by $b$ and get a remainder of $R$, then it is always true that $a \equiv R \pmod{b}$


Change values in XML python

Question: I have an XML file that looks like this:
<StationConfig
StationId="1"
SportType="null"
StationType="null"
UseMetricSystem="US"
LocalTempStorageDrive="C:\"
LocalStorageDrive="C:\">
<ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable>
</StationConfig>

I'm trying to change the value of StationID through python and can't find a way.
I've tried using Etree but cant figure out how to access the value in StationID and change it.
Sorry for the noob question, any help would be appreciated
Answer: You can use the .set('attrname', 'value') method.
import xml.etree.ElementTree as ET

xml_tree = ET.parse("xml_doc.xml")
root = xml_tree.getroot()

root.set("StationId", "123")
xml_tree.write("xml_doc_updated.xml")

Comment: @AvivKaplan: you are moving the goalposts by adding more requirements that are not in the original question. Please ask about one issue at a time. If you have problems with formatting for example, please ask a separate question (but first you should search for similar questions).
Comment: Thank you,
How can I save this to a new file?
Comment: Thanks for you answer mate.
The thing is the file is already spaced out and has comments and I would rather to keep it in this format.
If I'm not saving it to a new file the values won't change.
If I'm saving it to a new file the new file is unformatted with the changed value
Comment: Please mark it as the accepted answer if it helped you.
Comment: Any idea why the value wont change in the original file but they do change if i save to another file?
Comment: It is as it is now an xml object stored in a variable. And we are changing the attribute only to that variable.
Comment: Is there any way to overwrite the original file?
Answer: In your case the root is also the 'StationConfig' tag. Once you select it like this (or the find, findall functions), you can use the '.set' command to change its attributes.
from xml.etree.ElementTree import fromstring, ElementTree
xml_string = '<StationConfig StationId="1" SportType="null" StationType="null" UseMetricSystem="US" LocalTempStorageDrive="C:\" LocalStorageDrive="C:\"> <ClubManagementEnable ClubManagementStaticHours="">false</ClubManagementEnable> </StationConfig>'

tree = ElementTree(fromstring(xml_string))
root = tree.getroot()

root.set('StationId', 'the-new-value-you-want')

Change values in XML python


How to test an unmounted React component's method that relies on setState?

Question: I have implemented a component (for a typing training app) which tracks key presses on global scope like this:
class TrainerApp extends React.Component {
    constructor() {
        // ...
        this.handlePress = this.handlePress.bind(this);
    }
    handlePress(event) {
        const pressedKey = event.key;
        const task = this.state.task;
        const expectedKey = task.line[task.position];

        const pressedCorrectly = pressedKey == expectedKey;
        this.setState(prevState => {
            const newPosition = prevState.task.position +
                (pressedCorrectly ? 1 : 0);
            return {
                // ...prevState, not needed: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-are-merged
                task: {
                    ...prevState.task,
                    position: newPosition,
                    mistakeAtCurrentPosition: !pressedCorrectly
                }
            }
        })
    }
    componentDidMount() {
        document.addEventListener(this.keyEventTypeToHandle,this.handlePress);
    }
    componentWillUnmount () {
        document.removeEventListener(this.keyEventTypeToHandle,this.handlePress);
    }
    ...
}

and I'd like to write some unit-tests using Jest. My initial idea was:
describe('TrainerApp.handlePress should',() => {
    test('move to the next char on correct press',() => {

        const app = new TrainerApp();
        app.state.task.line = 'abc';
        app.state.task.position = 0;
        const fakeEvent = { key: 'a' };

        app.handlePress(fakeEvent);

        expect(app.state.task.position).toBe(1);
    });
    ...
});

but the problem is app.handlePress relies on usage of this.setState which is not defined when the component is not mounted yet. Of'course I can modify the app like this:
test('move to the next char on correct press',() => {

    const app = new TrainerApp();
    app.setState = jest.fn(function(handler) {
        this.state = handler(this.state);
    });
    app.state.task.line = 'abc';
    app.state.task.position = 0;
    const fakeEvent = { key: 'a' };

    app.handlePress(fakeEvent);

    expect(app.state.task.position).toBe(1);
});

or even like this:
class ExplorableTrainerApp extends TrainerApp {
    setState(handler) {
        this.state = handler(this.state);
    }
}
test('move to the next char on correct press',() => {

    const app = new ExplorableTrainerApp();
    app.state.task.line = 'abc';
    app.state.task.position = 0;
    const fakeEvent = { key: 'a' };

    app.handlePress(fakeEvent);

    expect(app.state.task.position).toBe(1);
});

but this seems a very fragile approach (here I rely on the fact that .setState is called with the function argument while it can be called with just newState argument and hence I'm testing implementation details, instead of just the behaviour. Is there a more robust way to test this?
Comment: You'll need to actually mount your components to access the methods. 'Enzyme' from airbnb works nicely with React for this https://airbnb.io/enzyme/docs/guides/jest.html
Answer: There are a few frameworks for testing React components, Enzyme and react-testing-library are both popular and well supported.
Comment: So basically we need to use tools to mount the component to get `setState` to work; and react does not provide a handy methods to mount them only for testing so it's better to use testing frameworks, right?
Comment: You _could_ just mount the component in the DOM: `const app = ReactDOM.render(, document.querySelector('.main');`, but the testing frameworks provide methods that allow you to conveniently do things like find components deeper in the tree.


Hide void option from menu in DocuSign envelope view from c# for all users

Question: Hide void option from menu in DocuSign envelope view.
Can I do this using C# DocuSign SDK?
To hide Void option for user usingfor all the users whether user is participant or not.
Envelope is being accessed using CreateRecipientView end point of docusign.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Use Focused View with a bit of JS/HTML to do that.
Recommend you download the full (right most) quickstart for C# and then search for "Focued View" to see how it works.
Here is what the HTML/JS looks like:
    <!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Signing</title>

@Html.Raw(ViewBag.SupportingTexts.ContinueButton)

@Html.Raw("")

@{

  [1]: https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-focused-view/


Validate the switch statement with an if statement

Question:
Use a switch statement to implement a menu. Allow the user to enter correct upper/lowercase letters (i.e. AIR or air or Air or aiR etc ). If the user enters an invalid selection your program should tell them and then exit.
The answers for air, water and steel must use printf. Display air to 3 decimal places, water to 4 decimal places and steel to 5 decimal places.
After the user enters the distance the sound wave must travel but before using the number in a calculation, validate it. If the distance is less than zero or greater than 10000, display an error message and do no further processing ie exit. Nest the switch statement (menu – see above) within this if statement.

import java.util.Scanner;

   public class SpeedSound
   {
     public static void main(String[] args)
     {
        String input;
        double distance;
        double time;
        final double AIR   = 1/1100;
        final double WATER = 1/4900;
        final double STEEL = 1/16400;

        Scanner kyb = new Scanner(System.in);

        System.out.print("Enter the corresponding medium:\n ");
        System.out.println("Air\n ");
        System.out.println("Water\n ");
        System.out.println("Steel\n ");
        input = kyb.nextLine();

        System.out.print("Enter the distance: ");
        distance = kyb.nextDouble();

       if (distance < 0 || distance > 10000)
             System.out.print("Error: ");

           switch (input)
            {
                case "Air":
                case "AIR":
                time = (distance / 1100);
           System.out.println("The total time traveled is " + time + "seconds.");
        break;

        case "Water":
        case "WATER":
        time = (distance / 4900);
        System.out.println("The total time traveled is " + time + "seconds.");
        break;

        case "Steel":
        case "STEEL":
        time = (distance / 16400);
        System.out.println("The total time traveled is " + time + "seconds.");
        break;

        }
     }
   }

Answer: Indentation doesn't matter for java, use a block by using {} braces, otherwise it will only execute the next statement.
if (condition) {
// .. lots of
// .. lines of
// .. code

}

Comment: i also tried that before but it is not working that way it suppose to.
Answer:
Allow the user to enter correct upper/lowercase letters (i.e. AIR or air or Air or aiR etc )

As you need to handle all the lower/upper case version of the input. Just convert the string into lower casebefore passing to switch case, then define there only lowercase case statements instead of multiple statements.
intput = input.toLowerCase();   // this is not require if you have converted it earlier
switch (input) {
case "air":

If the user enters an invalid selection your program should tell them and then exit.

You can use the if condition and exit the user:
input = kyb.nextLine().toLowerCase();

if (! (input.equals("air") || input.equals("water") || input.equals("steel")) ) {
  System.out.println("Invalid input. Exit");
  return;
}

If the distance is less than zero or greater than 10000, display an error message and do no further processing ie exit.

   if (distance < 0 || distance > 10000) {
         System.out.print("Error: ");
         return;
   }

Comment: Thank you, i understand what you mean but the if statement should be validating the distance i entered if my distance is <0 or >10000 it should display an error message any number inside 0 to 10000 should calculate depending on the input i pick. the switch statement supposed to have the input (air, water, and steel) calculation. my code compiles but when i try to enter the distance it stops compiling.
Comment: Also I'm only allowed to use one if statement and a switch statement nested inside it. Thank you in advance
Comment: `If the user enters an invalid selection your program should tell them and then exit.` you will need one if for this and another for `distance` input.
Comment: just wondering if i could do this:                                                                      input = kyb.nextLine().equalsIgnoreCase();
Comment: No. This is a comparison. As you are using switch case so use cannot use it, otherwise this can be used in if condition.
Comment: yeah my bad i realized it after i sent the msg. just one last question if i already have System.out.println("The total time traveled is " + time + "seconds."); how am i going to display the time in printf? The answers for air, water and steel must use printf. Display air to 3 decimal places, water to 4 decimal places and steel to 5 decimal places. i edited my code trying to use printf but its not working.
Comment: check it [Formatting Numeric Print Output](https://docs.oracle.com/javase/tutorial/java/data/numberformat.html). You will find all the information with example


Good metric / method to evaluate balanced multiclass classification when some classes are more similar than others?

Question: Surely I'm not the first person trying to do this, but can't find a good answer (probably because I'm not searching with the right terms).
I have a problem with 10 balanced classes (0-9) where the error is less important the closer the predicted class is to the actual class (e.g. if true class is 2, I'd rather classify it as 3 than as 8). Essentially, I'd like the confussion matrix to be as centered on the diagonal as possible.

Is there a specific metric/technique that is used in these cases? If so, is it implemented in sklearn or similar?
Thanks!
Comment: Is your variable ordinal like low/medium/high? (A movie-style "star rating" counts as ordinal.)
Comment: Yes it is. It's a product quality index (0 would be worst quality, 9 would be best quality).
Comment: There are specific methods for doing ordinal regression, since, as you've noticed, ordinal variables are kind of a hybrid of numerical and categorical.
Answer: Would the root mean squared error work? You give more penalty to classes predicted far from the truth. E.g.
<code>rmse <- function(predicted, true) {
    sqrt(sum((predicted - true)^2) / length(predicted))
}

rmse(c(1,1,2,2,3,3), c(1,1,2,2,4,4))
[1] 0.577

rmse(c(1,1,2,2,4,5), c(1,1,2,2,4,4))
[1] 0.408
</code>


How to check if a Vocabulary is translatable?

Question: In Drupal Core, I found the following code:
$entity instanceof TranslatableDataInterface && $entity->isTranslatable()

But it looks like it is not working for the Taxonomy vocabularies
Answer: This information is stored in configuration and you can retrieve it by using this service:
\Drupal::service('content_translation.manager')->isEnabled('taxonomy_term', 'my_vocab')

More info Where do I fetch myself complete definition for a bundle?
Comment: Many thanks for this nice code.
Answer: $entity instanceof TranslatableDataInterface && $entity->isTranslatable() doesn't work because the first part is checking for the wrong interface. The correct code is the following one.
$entity instanceof TranslatableInterface && $entity->isTranslatable()

It's TranslatableInterface that defines isTranslatable(). TranslatableDataInterface is not an interface defined from Drupal core.
The documentation page for the Term class has a list of its methods. You can also see which class implements them, and which method they override. In the case of isTranslatable() the page reports the following data.
ContentEntityBase::isTranslatable    public    function    Returns the translation support status.
                                                           Overrides TranslatableInterface::isTranslatable

The Vocabulary class, which is the class for the configuration entity used to define the bundles of the Taxonomy term entity (a content entity), doesn't have any isTranslatable() method.
Comment: Thank you for the detailed information however, I will accept the 4k4 answer as it is solving my issue: How to know if a vocabulary is translatable.