Faster de-merge of all hashtags

Question: I would like to de-merge hastags from a Twitter dataset. For instance: "#sunnyday" would be "sunny day".
I have found the following code:
The code finds the hastags and looks into  a file called "wordlist.txt", which is a huge txt file with a lot of words for some matching words.
The txt. file can be downloaded here:
http://www-personal.umich.edu/~jlawler/wordlist
Source:  Term split by hashtag of multiple words
I modified it a bit to make sure that it works if a sentence is empty: " "
# Returns a list of common english terms (words)
def initialize_words():
    content = None
    with open('wordlist.txt') as f: # A file containing common english words
        content = f.readlines()
    return [word.rstrip('\n') for word in content]

def parse_sentence(sentence, wordlist):
    new_sentence = "" # output
    # MODIFICATION: If the sentence is not empty
    if sentence != '':
        terms = sentence.split(' ')
        for term in terms:
            # MODIFICATION: If the term is not empty
            if term != '':
                if term[0] == '#': # this is a hashtag, parse it
                    new_sentence += parse_tag(term, wordlist)
                else: # Just append the word
                    new_sentence += term
                new_sentence += " "

    return new_sentence

def parse_tag(term, wordlist):
    words = []
    # Remove hashtag, split by dash
    tags = term[1:].split('-')
    for tag in tags:
        word = find_word(tag, wordlist)
        while word != None and len(tag) > 0:
            words.append(word)
            if len(tag) == len(word): # Special case for when eating rest of word
                break
            tag = tag[len(word):]
            word = find_word(tag, wordlist)
    return " ".join(words)

def find_word(token, wordlist):
    i = len(token) + 1
    while i > 1:
        i -= 1
        if token[:i] in wordlist:
            return token[:i]
    return None

The problem is that it takes for ever to run!
How can I make it faster ?
Answer: Use a set instead of a list for your wordlist variable.
This will be a massive performance improvement because with list you need to (potentially) scan the entire word list, so it's O(n). With a set, it's O(1) because membership is checked by calculating a hash of the item and using that as an index into the backing storage.

Faster de-merge of all hashtags


Why did we add 1 to each term?

Question: In how many ways can a manager of a chain of a supermarkets divide between two of its branches 100 units of one product, 200 of another, 150 of a third, and 11 of a fourth? [Notice divide means no branch is left without products]
Solution
(100+1)·(200+1)·(150+1)·(11+1)−2
Of the first product, the manager can assign k = 0, · · · , 100 units to one of the branches, and so for the other products. Since the products must be divided between the two branches, then we should not count the cases where all products are assigned to one branch.However, I don't understand why we added 1 to each term?
Answer:
"Of the first product, the manager can assign $k = 0, \dots , 100$ units to one of the branches"

Indeed. So this is $\lvert \{0,1,2,\dots,100\}\rvert = 101$ options for $k$ (the number of products of the first type put into the first branch can be zero).
Same for the other 3 products. So you get
$$
(100+1)(200+1)(150+1)(11+1)
$$
possible assignments for the first branch (and, obviously, an assignment to the first branch fully determines the assignment to the second branch: the rest of the products).
Now, there is the remaining $-2$. Why? Because

divide means no branch is left without products

so you must remove the two solutions corresponding to $0$, or all, products assigned to the first branch.
Thus, overall, you obtain
$$
(100+1)(200+1)(150+1)(11+1)-2
$$
possible assignments.

Why did we add 1 to each term?


CSS3: Mostrar uma div escondida ao fazer hover sobre outra div

Question: Boa tarde. Neste momento tenho 2 divs, 1 delas visível e a outra oculta, ficando visível quando faço hover sobre a primeira.
Gostava que, ao revelar a div com texto, o fundo desta preenchesse a totalidade da div que contem a imagem.
Desculpem se é uma dúvida básica.
Pretendo fazer isto através do css.
Obrigado

@media only screen and (min-width: 769px) {
  .gridContainer {
    width: 88.2%;
    max-width: 1232px;
    padding-left: 0.9%;
    padding-right: 0.9%;
    margin: auto;
  }

  #mainWrapper{
  width:100%;
}
.contentor{
  display:block;
  width:33.3%;
  height:auto;
  position:relative;
  margin:0;
  float:left;
}
.imagem{
  display:block;
  position:relative;
  width:100%;
  height:auto;
  left:0;
  top:0;
}
.texto{
  display:block;
  z-index:100;
  position:absolute;
  font-size: 3em;
  font-weight:bold;
  left:50%;
  top:35%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
  text-align:center;
  background: rgba(153, 102, 0, 0.6);
  transition: opacity 2s;   /* efeito trans */
  opacity:0;
}

.contentor:hover .texto{
  opacity:1;
}

texto por cima

texto por cima

texto por cima

texto por cima

texto por cima

texto por cima

Comment: Creio que a solução já esteja praticamente pronta aqui: http://pt.stackoverflow.com/q/56996/70
Comment: É isto que pretendes? -> https://jsfiddle.net/4nzpkgu6/
Comment: Sérgio, é isso mas a ocupar a totalidade da div, neste caso só ocupa na horizontal :)
Comment: David, assim -> https://jsfiddle.net/4nzpkgu6/1/ ? Se nõ fôr, explica melhor... Podias juntar uma imagem de como queres?
Comment: Já deu, Obrigado :D
Comment: Relacionado: http://pt.stackoverflow.com/questions/26684/
Answer: Fix um exemplo simples no fiddle de como você pode fazer isso. Veja a baixo o código fonte do exemplo:

figure {
    margin: 0;
}

section {
    position: relative;
    width: 400px;
}

section:hover article {
    visibility: visible;
    display: block;
}

section img {
    max-width: 100%;
}

section article {
    position: absolute;
    bottom: 0;
    margin: 1rem;
    display: none;
    visibility: hidden;
}

Heading

Libero eius molestiae, distinctio facilis eaque odio quam illum amet enim. Consequuntur consequatur nostrum eligendi molestias perspiciatis, consectetur eaque. Nihil, officia, quos.

Answer: Eu recomendaria você usar a imagem como fundo da div .contentor

texto por cima

Outra possível solução seria:
.contentor img{
 z-index: 1;
}
.contentor p{
   margin-left: -Xpx /*X é a largura de img*/;
   margin-top: -Xpx /*X é a altura de img*/;
   z-index: 2;
}

Quanto ao hover é so colocar esses estilos:
.contentor p{
  display: none;
}
.contentor:hover p{
  display: block;
}

Comment: Obrigado Bruno ;)


Python: Comando import fica em cinza no PyCharm

Question: Instalei o Python 3 e o PyCharm e o comando "import" estava funcionando normalmente. De alguns dias pra cá, toda vez que tento importar alguma biblioteca, por exemplo, import datetime, assim que aperto o Enter, o comando fica em cinza.
Será que desabilitei alguma coisa?
Comment: Não, só na primeira linha. Também fiz essa pergunta para um colega e ele me disse que o import vai ficar cinza até que eu utilize uma das funções, aí o comando import volta a ficar colorido. Interessante isso. Apanhando e aprendendo rssss... Obrigada!
Comment: Isso acontece em todas as linhas?
Answer: No Pycharm, quando o import esta cinza, significa que ele nao está sendo utilizado...
Se voce utilizá-lo de qualquer forma, por exemplo:
<code>current_time = datetime.datetime.now()
</code>
ele ficará colorido.
O Pycharm disponibiliza alguns plugins para facilitar sua vida... Um deles, é o SonarLint, que mostra alguns possíves erros, assim como imports não utilizados.


Compactness and Totally Bounded Sets

Question: Suppose that $(K,d)$ is a compact metric space, and $\varepsilon>0$. Prove that there is a finite subset $S⊆K$ so that for every $y∈K$ there is $x∈S$ with $d(x,y)<\varepsilon$, and moreover so that for any distinct $x,w∈S$ we have $d(x,w)>\varepsilon/2$.
I dont know how to approach $d(x,w)>\varepsilon/2$.
So far I have, $d(x_i,w) - d(w,y) \le d(x,w)\ge d(x_i,w) - \varepsilon/2 \le d(x,w)$ but it seems wrong.
Comment: I think you forgot to say that $S$ should be finite. How would you use the definition of compactness in terms of open covers to find a possible $S$?
Comment: sorry, will do next time!
Comment: @EthanBolker: I am sure the problem was meant to say explicitly that $S$ should be finite, However, the second condition on $S$ implies that $S$ must be finite (since an infinite $S$ would have a point of accumulation).
Answer: I assume you have proved that there is a finite set $S$ such that every point of $X$ is within distance $\varepsilon$ of some point of $S$ (cover every point with $\varepsilon$-balls, extract a finite subcover).
For the second part, try induction on the size of the covering. A valid inductive hypothesis might be, "suppose that for any compact metric space admitting a covering of $\leq n$ points, such a configuration with pairs of points distance $\varepsilon/2$ apart exists". The base case of $n = 1$ (or $n=0$ with the empty space) is trivial. If you have a minimal covering with $n+1$ points (i.e. if you remove some $\varepsilon$-ball, you no longer have a cover), then apply the inductive hypothesis to the closure of the subspace $Y$ covered by $n$ points, and judiciously choose the spot for the $(n+1)$-st (e.g. on the boundary of $Y$).
Comment: Now that I think of it, you may need to add multiple points to the boundary of $Y$ to cover $X$, but a similar inductive argument is enough to show that you can choose these to have distance at least $\varepsilon/2$ of one another.

Compactness and Totally Bounded Sets


How to define Views filters and relationships for custom Civicrm contact fields that are indexed via Search API?

Question: I followed the steps on skvare to index CiviCRM contacts via Search API, then to have Views list the contacts with the search box as an exposed filter.
I need to expose a filter that filters results based on what membership type the contact has. That might require a relationship, which is currently not an option in Views for me, so I might have to write a custom relationship handler as well as the custom filter handler. I have been trying to find the code to read to use as a guide but I have been unable to figure out whether these handlers are being defined in CiviCRM, Views, Search API, or the Civicrm Entity module which I'm also using.
How do you define a custom relationship and filter handlers for custom fields on CiviCRM contacts being displayed via Search API, CiviCRM Entity, and Views?
Comment: I would have thought that a View based on Contacts should be able to give you an exposed Filter of membership types, though of course there is the issue that one contact 'could' have multiple memberships. WHen I check on a 'contact' based view, i do have CiviCRM Member fields available as a Filter
Comment: This isn't a view of Civicrm contacts, it's a view of indexed Civicrm contacts. I also can add that filter to the former type but the latter type doesn't have it.
Answer: If this is about getting Membership fields showing in the ADD RELATED FIELDS selector at the bottom of admin/config/search/search_api/index//fields then I expect this is a civicrm entity issue in which case you could check at this chat channel
Otherwise you may be looking for sites/all/modules/civicrm/drupal/modules/views
Comment: I suspect that it does have to do with the related fields. Thanks!
Comment: I also tried the channel you linked but it doesn't seem to have much activity.
Comment: looks to me like you are getting helped there
Comment: Yeah after I commented, I got some advice. However, I tried the suggestion I was given there and it didn't solve the problem because, as mentioned in this answer, it seems like this is an issue in the way Search API is relating to Civi rather than something that can be fixed in Views.
Comment: guess there is a bit more work to do with getting civi working thoroughly with Search API


Fitting gamma distribution - loc parameter relation to alpha and beta

Question: I am trying to fit some data using python scipy.fit with the gamma distribution.
This returns three parameters (alpha, loc, beta). I would like to use these parameters to generate some data in excel, but the gamma function in excel only take values of alpha and beta.
Could someone explain how the "loc" parameter is related to the gamma distribution and how I can alter alpha and beta to be correct?
Comment: Possible duplicate of https://stats.stackexchange.com/questions/73175/three-parameter-gamma-distribution?rq=1
Answer: Gamma function has three parametrizations:

With a shape parameter k and a scale parameter θ.
With a shape parameter α = k and an inverse scale parameter β = 1/θ, called a rate parameter.
With a shape parameter k and a mean parameter μ = k/β.

In Excel, the second, "standradized", form is used. But it's possible to shift and/or scale the distribution using the loc and scale parameters. Specifically, gamma.pdf(x, alfa, loc, scale) is identically equivalent to gamma.pdf(y, alfa) / scale with y = (x - loc) / scale.
Hence to generate data in Excel just apply loc as above and then use Excel function as usual with parameters, returned from scipy.fit


How do I replace MPMoviePlayer notifications?

Question: In iOS 9 MPMoviePlayer and all his components are deprecated.
We used MPMoviePlayerController notifications, like MPMoviePlayerLoadStateDidChangeNotification, MPMovieDurationAvailableNotification, MPMoviePlayerPlaybackStateDidChangeNotification, MPMoviePlayerReadyForDisplayDidChangeNotification, to track video service quality. But now with AVPlayerViewController I can't find properly replacement for these notifications.
How do I replace these notifications now?
Answer: AVPlayerViewController is a lot different in its usage from the MPMoviePlayerViewController. Instead of using notifications you use Key Value Observing to determine the current characteristics of the AVPlayer object associated with the AVPlayerViewController. According to the docs:

You can observe the status of a player using key-value observing. So
  that you can add and remove observers safely, AVPlayer serializes
  notifications of changes that occur dynamically during playback on a
  dispatch queue. By default, this queue is the main queue (see
  dispatch_get_main_queue). To ensure safe access to a player's
  nonatomic properties while dynamic changes in playback state may be
  reported, you must serialize access with the receiver's notification
  queue. In the common case, such serialization is naturally achieved by
  invoking AVPlayer's various methods on the main thread or queue.

For instance, if you want to know when your player has been paused add an observer on the rate property of the AVPlayer object:
[self.player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: &PlayerRateContext];

Then in the observe method check if the new value is equal to zero:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (context == &PlayerRateContext) {
        if ([[change valueForKey:@"new"] integerValue] == 0) {
            // summon Sauron here (or whatever you want to do)
        }
        return;
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    return;
}

A lot of properties on the AVPlayer are observable. Go through the Class reference.
Also apart from this there are several Notifications available for the AVPlayerItem object which are limited but still helpful.

Notifications
AVPlayerItemDidPlayToEndTimeNotification
AVPlayerItemFailedToPlayToEndTimeNotification
AVPlayerItemTimeJumpedNotification
AVPlayerItemPlaybackStalledNotification
AVPlayerItemNewAccessLogEntryNotification
AVPlayerItemNewErrorLogEntryNotification

I find AVPlayerItemDidPlayToEndTimeNotification particularly useful to seek the Item to the start once playback has finished.
Using these two options together you should be able to replace most if not all notifications for the MPMoviePlayerController
Comment: Can you also provide a list of JWPlayer notifications? Unable to find a concise list on the net.
Comment: How do I convert MPMoviePlayerPlaybackStateDidChangeNotification in AVPlayer?
Answer: I looked at the documentation for both MPMoviePlayerNotifications and AVPlayerItemNotifications and I notice two things.

MPMoviePlayerNotifications don't show they were deprecated:

AVPlayerItemNotifications don't have any replacements that I could see:

So, I am confused that you are saying MPMoviePlayerNotifications are deprecated, because the docs are saying they are available. Also, I don't think AVPlayerItemNotifications has a replacement for MPMoviePlayerNotifications.
Comment: From documentation: `The MPMoviePlayerViewController class is formally deprecated in iOS 9. (The MPMoviePlayerController class is also formally deprecated.) To play video content in iOS 9 and later, instead use the AVPictureInPictureController or AVPlayerViewController class from the AVKit framework, or the WKWebView class from WebKit`. I guess, that means no `MPMoviePlayerNotifications` notifications in future.


Is this an F below middle C? (check my relative pitch estimation plus my math)

Question: I'm listening to a "tone" and estimating its frequency and need some help checking both my relative pitch estimation and my math.
In this noisy part of this video the Mars helicopter Ingenuity is taking off and then hovers in a Mars atmosphere simulation chamber. The air pressure is roughly 1% of Earth's standard atmosphere but the microphone still picks up the sound nicely.
I've played A440 from another video and from that I estimate that the frequency once it reaches a stable hover is an octave plus a major third below it, or "F below middle C".
That frequency would then be 440 / 2 / 2^(1/3) or about 174.6 Hz.
Have I done this correctly?
Comment: In the clip, there are two different shots fairly close after one another. In the first shot, which corresponds to the image you've posted, the tone I'm hearing is an Eb, and yes, I'd say the fundamental is the Eb below middle C – though I'm sure people who are posting full answers will consider the physics involved in this in much more detail. In the second shot shortly after that I also hear the tone as an F, and I'm willing to suppose the fundamental is the F below middle C.
Comment: Is the tone strong enough (SNR) that a typical smartphone tuner app could tell you the frequency?  Or maybe try running an FFT on the source?
Comment: @CarlWitthoft That's a great idea! I used o be able to download YouTubes with [Python](https://stackoverflow.com/q/43159565/3904031) and then extract the audio with [Blender](https://blender.stackexchange.com/q/62163/5334) or [ffmpeg](https://apple.stackexchange.com/q/327177/143729) but they've changed the way that YouTube videos download and so my script no longer works. If you know a way to get the audio as a .wav or similar file then the FFT is easy in Python. I don't use apps on my phone or download third party programs if I can help it (ffmpeg was an exception).
Comment: @uhoh  possibly   https://ytmp3.cc/en13/   or  https://x2convert.com/en20/download-youtube-to-mp3-music .  I haven't tried those; used to use some similar service successfully.
Answer: It is actually an octave below where you say, it starts off in the first shot at about an Eb and then in the second shot when it lifts off it goes up to about an F an octave and a 5th below middle C. That would put the frequencies at approximately 78 hz and 87 hz respectively. Your math seems right but you are an octave high on the pitch, 174/2=87.
Comment: Thanks for your answer! I wonder if there is a strong first harmonic and I'm listening on a laptop with a poor low frequency response, so I missed the fundamental.  The rotor is *nominally* 2400 RPM or ~40 per second, and so for each blade the tips pass ~80 times a second, but there are two blades at 90 degrees which are not necessarily identical in all parameters (and sound reflections may be different for each) so there can be strength at both ~80 and ~160 Hz. This is why I asked here where people with better ears than mine can help sort it out.
Comment: @uhoh I compared the sounds to notes on my electric bass and the fundamentals are low frequencies, approximately Eb and F on the 1st and 3rd frets of the D string. As with most sounds and recordings there are also a lot of overtones mixed in.


Restrict classes with same method names to be used interchangeably

Question: Lets say we have Shape class like this:
export default class Shape {
  public render(): void {
    console.log("Render Shape");
  }
}

and Group class like this:
import Shape from "./Shape";

export default class Group {
  private shapes: Shape[] = [];

  public add(shape: Shape): void {
    this.shapes.push(shape);
  }

  public render(): void {
    for (const shape of this.shapes) {
      shape.render();
    }
  }
}

as you can see in Group class, we have method called add that accept 1 parameters with type Shape class. I want to pass only objects with type Shape to this method, but i can pass Group type as well.
import Group from "./Group";
import Shape from "./Shape";

const group1 = new Group();
group1.add(new Shape()); // this is ok

const group2 = new Group();
group2.add(group1); // this is ok in typescript view but i don't like it

Is there any solution to prevent this behaviour?
Answer: I found a solution for this problem, but i like to know another solutions too.
import Shape from "./Shape";

type ValidateStructure<T, Struct> = T extends Struct
  ? Exclude<keyof T, keyof Struct> extends never
    ? T
    : never
  : never;

export default class Group {
  private shapes: Shape[] = [];

  public add<T>(shape: ValidateStructure<T, Shape>): void {
    this.shapes.push(shape);
  }

  public render(): void {
    for (const shape of this.shapes) {
      shape.render();
    }
  }
}

and now magic happens:
Answer: I never experienced this problem but I think this happens because typescript uses structural typing. For example C# or Java use nominal typing and don't allow this.
So, we need to make structure of the two classes different. For that I would add some random named field to the Shape class. Not sure if it should be public or private is enough.


Pyrocms, stream on where clause

Question: I use pyrocms to develop a site. I need to use stream for a view. I would like only the entries corresponding to the current user to be displayed.
I use the following query (user_id is name of the field on my database)
{{ streams:cycle stream="{{ stream }}"  where="`user_id`='{{user:id}}'" order_by="nom" sort="asc"}}

Pyrocms works like if my request stop before the where clause. and it show me this on the page :

1 '" order_by="nom" sort="asc"}}

and I view all results on the page (all entries for all users).
If I'm using this request it works :
{{ streams:cycle stream="{{ stream }}" where="`user_id`=1" order_by="nom" sort="asc"}}

What do I do wrong?
Can I use variable on the where clause ?
Thanks
Matthieu
Answer: To start, try {{ streams:cycle stream="stream_name".... without the curly braces and the stream name is enclosed in back-ticks, second, is the user_id a field in the stream you are accessing?
The following is an extract from the Streams Plug In documentation:
Note: The where clause is directly mapped to the where clause in MySQL, so you are limited in the values that you can restrict by. For instance, if you have a Choice dropdown field with a key and value, the key is stored in the database. So, if you want to restrict by that field, you need to restrict by the choice key and not the value.
You may need to have a stream for the users and use the Relationship field type. For example:
{{ streams:users where="active='1'"... }}
 {{ streams:stream_name where="`user`='{{ id }}'"... }}

       .........................

 {{ /streams:stream_name }}

{{ /streams:users }}
note that {{ id }} is the id of the entry in the users stream. Note again the requirement for back ticks - but it looks like you have that under control based on your code samples
Hope this helps.

Pyrocms, stream on where clause


FileNotFoundException when reading file - No such file or directory

Question: I was wondering if anyone to help me catch what is wrong with my code?
Path:
src/dictionary.txt
Code:
BufferedReader reader = new BufferedReader(new FileReader("src\\dictionary.txt"));`

Error:
Exception in thread "main" java.io.FileNotFoundException: src\dictionary (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at java.io.FileInputStream.<init>(FileInputStream.java:79)
    at java.io.FileReader.<init>(FileReader.java:41)
    at p26.WordReconstruction.generateDictionary(WordReconstruction.java:13)
    at p26.WordReconstruction.main(WordReconstruction.java:24)

Comment: @AustinTruong no, you didn't. `"/src/dictionary.txt"` != ``"\src\dictionary.txt"``
Comment: I tested your code and it works fine, are you sure that your java class file is in a directory which contains src directory which contains dictionary.txt?
Comment: I got a syntax error when I tried that `Invalid escape sequence`
Comment: I'm using the same thing and it seems to work. Are you sure there's no other place where there might be some error? What's line 120?
Comment: Have you tried to use an absolute pass?
Comment: Ah I tried `Exception in thread "main" java.io.FileNotFoundException: /src/dictionary.txt (No such file or directory)` Still getting the error. Yeah I am pretty sure it is in the src folder.
Comment: try ".\\src\\dictionary.txt", be sure that it's dictionary.txt, not dictionary.TXT nor dictionary.tXt
Comment: what operating system are you on?
Answer: /src/dictionary.txt is not the same as src/dictionary.txt. The first is in the ROOT the second is RELATIVE to the current directory.
Comment: yeah but you can do ./src/dictionary.txt
Answer:
Check character case is correct, the file has to be named "dictionary.txt" with correct cases
Check where you placed the file in relative to where you run your java code. By default if you specify relative path such as "src/dictionary.txt", java will look it up from System.getProperty("user.dir")


how to wrap around a list with a max-width container

Question: I have a list with a maximum size of 176px. If items overflow, i want them to wrap around the ul container. If they don't overflow, i want the ul to adjust to the width.
In my example, the first list overflows, and wraps around the max container size. Just what i want!
The second list doesn't overflow. So the container needs to be more smaller, needs to adjust to the size of the list. I've added a max-width, with no success.
How do i make my second list container to be as width as the list is ?

ul {
  padding: 0;
  margin: 0;
}

.flagMenu {
  border: 1px solid red;
  max-width: 176px;
  white-space: wrap;
}

.flagMenu li {
  display: inline-block;
}

Answer: Add display: inline-block to your ul element.
Unorderded List elements are block level elements by default, so naturally they will always appear on a new line, and take up the full available width.  By changing that display property to inline-block, you can override that default behavior..

ul {
  padding: 0;
  margin: 0;
  width: auto;
  display: inline-block
}

.flagMenu {
  border: 1px solid red;
  max-width: 176px;
  width: auto;
  white-space: wrap;
}

.flagMenu li {
  display: inline-block;
}


How to export a large table (100M+ rows) to a text file?

Question: I have a database with a large table containing more that a hundred million rows. I want to export this data (after some transformation, like joining this table with a few others, cleaning some fields, etc.) and store it int a big text file, for later processing with Hadoop.
So far, I tried two things:

Using Python, I browse the table by chunks (typically 10'000 records at a time) using this subquery trick, perform the transformation on each row and write directly to a text file. The trick helps, but the LIMIT becomes slower and slower as the export progresses. I have not been able to export the full table with this.
Using the mysql command-line tool, I tried to output the result of my query in CSV form to a text file directly. Because of the size, it ran out of memory and crashed.

I am currently investigating Sqoop as a tool to import the data directly to HDFS, but I was wondering how other people handle such large-scale exports?
Comment: [`SELECT ... INTO OUTFILE`](http://dev.mysql.com/doc/en/select-into.html).
Comment: possible duplicate of http://stackoverflow.com/questions/10890163/exporting-large-mysql-table
Answer: Memory issues point towards using the wrong database query machanism.
Normally, it is advisable to use mysql_store_result() on C level, which corresponds to having a Cursor or DictCursor on Python level. This ensures that the database is free again as soon as possible and the client can do with thedata whatever he wants.
But it is not suitable for large amounts of data, as the data is cached in the client process. This can be very memory consuming.
In this case, it may be better to use mysql_use_result() (C) resp. SSCursor / SSDictCursor (Python). This limits you to have to take the whole result set and doing nothing else with the database connection in the meanwhile. But it saves your client process a lot of memory. With the mysql CLI, you would achieve this with the -q argument.
Comment: The sscursor lets you fetch one GOW at a time if I'm correct. But there's also a fetch many approach in some python packages which is a good trade off between getting the whole result set and just a single record
Answer: I don't know what query exactly you have used because you have not given it here, but I suppose you're specifying the limit and offset. This are quite quick queries at begin of data, but are going very slow.
If you have unique column such as ID, you can fetch only the first N row, but modify the query clause:
WHERE ID > (last_id)

This would use index and would be acceptably fast.
However, it should be generally faster to do simply
SELECT * FROM table

and open cursor for such query, with reasonable big fetch size.


How to deny access to disabled AD accounts via kerberos in pam_krb5?

Question: I have a working AD/Linux/LDAP/KRB5 directory and authentication setup, with one small problem. When an account is disabled, SSH publickey authentication still allows user login.
It's clear that kerberos clients can identify a disabled account, as kinit and kpasswd return "Clients credentials have been revoked" with no further password / interaction.
Can PAM be configured (with "UsePAM yes" in sshd_config) to disallow logins for disabled accounts, where authentication is done by publickey? This doesn't seem to work:
account     [default=bad success=ok user_unknown=ignore] pam_krb5.so

Please don't introduce winbind in your answer - we don't use it.
Answer: I have read elsewhere other people asking for SSH to be "fixed" so that locked accounts can't be logged into via SSH. (see Debian bug 219377)
This request got rejected as a patch "because it breaks some expectations from users [who were] used to passwd -l only locking the passwd." (see Debian bug 389183)
e.g. some people WANTED to be able to lock accounts from password logins, but still allow SSH key access.
PAM will not deny SSH key authentication to accounts which have just been locked (e.g. due to invalid password attempts, because SSH key authentication is designed to not pay any attention to the password field, which is where accounts are usually locked from.)
I understand that the password hash entry is implicitly checked at pam_authenicate() time, not at pam_acct_mgmt() time. pam_unix.so pam_sm_acct_mgmt() doesn't check the password hash at all, and pam_authenticate() is not called during public key authentication.
If your intention is to be able to centrally disable accounts from logging in, there are other possible workarounds, including:
Changing the login shell.
(re)moving their authorized_keys file.
Another option for denying access could be some use of DenyGroups or AllowGroups in the sshd_config.
(then adding the user to a "sshdeny" group, or removing them from an "sshlogin" group to disable them from logging in.)
( read here: https://help.ubuntu.com/8.04/serverguide/user-management.html )
From http://web.archiveorange.com/archive/v/67CtqEoe5MhDqkDmUMuL
I read: "The problem is pam_unix checks just the expiration dates of the shadow entry, not the password hash field contents."
If this is true, would expiring the account rather than locking it do what you need?
The answer to your question is possibly "yes, if you're disabling them somewhere other than the password field"
Answer: Did some more homework, and am answering my own question.
In RedHat's pam_krb5 (pam_krb5-2.3.14-1/src/acct.c), unless the module participated in the authentication stage, the pam_sm_acct_mgmt() function returns either PAM_IGNORE or PAM_USER_UNKNOWN depending on the module config. It would therefore require changes to the pam_krb5 code to do what I want.
JohnGH's answer is a good workaround; using "proxy" attributes to convey the same meaning, such as breaking the shell or adding to a "disabled-users" group.
Another workaround (partially tested) is to set an account expiry date in the past, and use a module such as pam_unix to fail the account checks. This uses LDAP, rather than KRB5, but queries against the same centrally-managed user directory.
Answer: SSH key based authentication is independent of PAM. You have the following solutions:

disable keybased authentication in sshd_config
change and recompile sshd and add a hook so that keybased auth will check also if the account is valid via pam.

If you want to use passwordless login via kerberos, you must make sure that:

you are not using pam for sshd
you have kerberos properly configured. E.g. you can do kinit -k host/server1.example.com@DOMAIN
you sshd is configured to use gssapi:
KerberosAuthentication yes
GSSAPIAuthentication yes
GSSAPICleanupCredentials yes
UsePAM no
you use a kerberized ssh client like PuTTY v0.61 or newer.
Comment: I disagree that SSH public key auth is independent of PAM. Adding `account optional pam_echo.so file=/etc/redhat-release` to /etc/pam.d/sshd causes the file contents to be printed while using key-based auth logins (try it).
Comment: I think that pam is used only for account (e.g. to create the home folder) and not for auth. I am checking this case now.


roots of polynomial equation

Question: How to find the roots of $x^5-2^5$ by hand. I see that we get a root of $x=2$ and 4 complex roots (should come in pairs). Not sure how to work out the complex roots. Do we need to convert to polar? Would that make it easier to see the other roots?
Comment: @Amzoti: Which fifth root?
Comment: What if you write $x^5 = 2^5$ and take the fifth root of each side? Clear
Comment: For this kind of polynomial, the roots are indeed easier to see in polar form.
Comment: They are $2$ and the fifth roots of unity.
Answer: Yes, polar form would make it easier to see the other roots. Write $x=re^{i\theta},$ so that you're solving $$r^5e^{5i\theta}=2^5.$$ It's easy enough to find $r$ simply by taking the modulus, and if you know a few basic properties of the complex exponential function, you can find values of $\theta$ that give you all five solutions.
Answer: Write as $x^5 - 2^5e^{2\pi ik} = 0$
So your solutions are $x = 2{e^{2\pi ik/5}}$ for $k=-2,-1,0,1,2$

roots of polynomial equation


Type 1 error Bayesian Stats

Question: Is there anybody who can tell me or explain to me about finding the Type 1 error for a Bayesian clinical trial.
Of a 100 patients I need 59 successful patients to exceed my posterior threshold.
I have been able to work this through R but now am stuck trying to find the probability Type 1 error for these 59 successes. I know the value should be ~ 0.044, but has to how to find this value I am unsure.
Any help please.
Comment: @January, "not compatible" is too strong. [Bayesian Adaptive Methods for Clinical Trials](http://www.amazon.com/Bayesian-Adaptive-Methods-Clinical-Biostatistics/dp/1439825483) has a lot of information about computing Type I errors under Bayesian adaptive designs.
Comment: On a more philosophical note -- formally, type I errors are defined within the Pearson-Neyman decision / hypothesis testing framework, which is not compatible with the Bayesian approach.
Comment: To compute type I error you need to fully describe the sample space, including the schedule of intended looks at the data even if these looks are never taken, and including any indeterminism in the sample size.
Answer: Formulate a sampling model (or preferably, a bunch) in which the null hypothesis is true. Try the model used in the Bayesian adaptive part, plus different dependence structures, missing covariates, anything that breaks model assumptions in plausible ways  -- especially ways that might inflate the "success" rate under the Bayesian model.
Simulate the trial under each of these different models a large number of times, say 10,000 or 100,000. The relative frequency with which the trial gets >59 successful patients is a Monte Carlo estimate of the Type I error rate under the assumed model.

Type 1 error Bayesian Stats


Como gerar um serial key que contenha um prefixo nos primeiros 5 caracteres?

Question: Eu tenho um script em PHP que gera um "serial key", mas preciso que esse script gere esse "serial key" com um padrão no inicio, como se fosse um prefixo.
O código que já tenho é:
<?php
$chars = array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$serial = '';
$max = count($chars)-1;
for($i=0;$i<20;$i++){
    $serial .= (!($i % 5) && $i ? '-' : '').$chars[rand(0, $max)];
}
echo $serial;
?>

Que gera um serial assim:

"HJMW0-5RRXT-CS853-BD888"

Quero que os 5 primeiros caracteres (o primeiro conjunto antes do " - ") de todos os seriais gerados sejam iguais e os outros sejam apenas números, sem letras, dessa maneira:

"XYAMN-97354-81037-01936"
"XYAMN-75903-81938-01936"
Answer: Separe em duas funções como no código abaixo:

function prefixo(){
    $chars = array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $prefixo = '';
    $max = count($chars)-1;
    for($i=0;$i&lt5$i++){
        $prefixo .= (!($i % 5) && $i ? '-' : '').$chars[rand(0, $max)];
    }
    return $prefixo;
}

function serial(){
    $chars = array(0,1,2,3,4,5,6,7,8,9);
    $serial = '';
    $max = count($chars)-1;
    for($i=0;$i&lt15$i++){
        $serial .= (!($i % 5) && $i ? '-' : '').$chars[rand(0, $max)];
    }
    return $serial;
}
echo prefixo()."-".serial();

Answer: Não sei se entendi direito, mas o prefixo do seu serial, será um texto fixo que você mesmo irá escolher?? Se for você pode fazer uma alteração bem simples no seu código, que é tirar todas as letras do array, e diminuir a contagem do for de 20 para 15 digitos, e colocar o seu texto de prefixo manualmente, dessa forma:
$chars = array(0,1,2,3,4,5,6,7,8,9);
$serial = '';
$max = count($chars)-1;
for($i=0;$i<15;$i++){
    $serial .= (!($i % 5) && $i ? '-' : '').$chars[rand(0, $max)];
}
echo 'XYAMN-'.$serial;

Agora se você quer que o prefixo seja de letras aleatórias, você pode separar em 2 array, um para números e outro para letras, e criar 2 for. Mas eu sugeria uma forma simplificada sem arrays utilizando a função chr do php, dessa forma:
for($i=0; $i<5; $i++){
    $prefixo .= strtoupper(chr(rand(97, 122))); //97 é o codigo ascii para 'a' e 122 para z
}

for($i=0; $i<15; $i++){
    $serial .= (!($i % 5) && $i ? '-' : '').rand(0, 9);
}
echo $prefixo.'-'.$serial;

E se você criar funções e classes para deixar seu gerador de serial muito mais dinâmico. Como por exemplo fazer um modificador para o separador de dígitos, utilizar um único for para as duas situações, e etc. Por exemplo:
function Serial($tipo = '', $qtdigitos = 5, $qtdbaterias = 4, $separador = '-') {
    $qtdtotal = $qtdbaterias * $qtdigitos;
    $letrasnumeros = array_merge(range(0,9), range('A', 'Z')); // Cria um array de letras e numeros de forma simplificada

    for($i=0; $i < $qtdtotal; $i++){

        if ($tipo == 'numeros') { $digito = rand(0, 9); }
        else if($tipo == 'letras') { $digito = chr(rand(65, 90)); }   //65 é o codigo ascii para 'A' e 90 para 'Z'
        else { $digito = $letrasnumeros[rand(0, count($letrasnumeros) - 1)]; }

        $serial .= (!($i % $qtdigitos) && $i ? $separador : '').$digito;
    }
  return $serial;
}

E ai você pode utilizar a função de várias formas:
// Retorna serial com letras e numeros,
// Ex: RQ4BD-1NSBA-PXUD9-DOKS6
echo Serial();

// Retorna serial só com números,
// Ex: 07295-31860-33824-63832
echo Serial('numeros');

// Retorna serial só com letras,
// Ex: CDMIC-AXLET-BRMGW-QUVWL
echo Serial('letras');

// Retorna serial só com números mas quantidade diferente de caracteres,
// Ex: 339-671-633-081-731-120
echo Serial('numeros', 3, 6);

// Utilizar separadores diferentes,
// Ex: 2CQHJ.SF1E6.D5SOG.UA10K
echo Serial('aleatorio', 5, 4, '.');

// Juntar formas e quantidades diferentes,
// Ex: AMQGUUY-82468-32482-84190
echo Serial('letras', 7, 1).'-'.Serial('numeros', 5, 3);

// Juntar texto fixo com serial
// Ex: XYAMN-16697-17479-56095
echo 'XYAMN-'.Serial('numeros', 5, 3);

Espero ter ajudado
Answer: Acredito que você deva utilizar random_bytes ou random_int ao invés do rand(). A diferença é que o random_* vai utilizar o CSRPNG presente no sistema operacional, que é mais seguro do que LGC ou Mersenne Twister.
Você pode utilizar o random_int com o pack, da seguinte maneira:
function letra(int $limite) : string {
    $b = '';

    while(strlen($b) < $limite){
        $b .= pack('C', random_int(65, 90));
    }

    return $b;
}

function numero(int $limite) : string{
    return str_pad(
        random_int(0, str_repeat(9, $limite)),
        $limite, '0', STR_PAD_LEFT);
}

echo letra(5) . '-' . numero(5) . '-' . numero(5) . '-' . numero(5);

Answer: Você pode criar uma classe, exemplo:

Classe serial.class.php

class Serial
{
  private $prefixo = "";
  public $letras = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
  public $numeros = array(0,1,2,3,4,5,6,7,8,9);

  /*
   * Método construtor
   * Cria um prefixo para cada objeto criado
   */
  public function __construct() {
    $max = count($this->letras)-1;
    for($a=0;$a<5;$a++) {
      $this->prefixo .= $this->letras[rand(0, $max)];
    }
    return $this;
  }

  /*
   * Método get
   * Gera um serial de 15 digitos toda vez que o método for chamado
   */
  public function get() {
    $serial = '';
    $max = count($this->numeros)-1;
    for($b=0;$b<15;$b++){
      $serial .= (!($b % 5) && $b ? '-' : ''). $this->numeros[rand(0, $max)];
    }
    echo $this->prefixo."-".$serial."\n";
    return $this;
  }

}

Como usar:

require_once('serial.class.php');

$serial_A = new Serial();
$serial_A->get()->get()->get()
         ->get()->get()->get()
         ->get()->get()->get()
         ->get()->get()->get()
         ->get()->get()->get()
         ->get()->get()->get();

Exemplo de saída

MPRDM-68308-47678-09412
MPRDM-34567-47698-43685
MPRDM-79111-86573-68267
MPRDM-78570-58526-57259
MPRDM-89941-85110-50824
MPRDM-41477-69233-60018
MPRDM-76481-63231-98672
MPRDM-14028-03542-56162
MPRDM-41338-20932-00450
MPRDM-72468-49538-39004
MPRDM-82852-74510-92625
MPRDM-34866-98635-93850
MPRDM-42227-33041-72832
MPRDM-15014-94731-68651
MPRDM-12007-58515-50146
MPRDM-27148-78106-34490
MPRDM-99967-35102-51586
MPRDM-47226-20839-60614

Podes ver funcionando no repl.it


How do I programmatically delete an order?

Question: My head is about to pop. I'm trying to figure out how to delete commerce orders programmatically. I created a rest export with the order IDs I want to delete. I've parsed that and put the IDs into an array. Now I want to loop through that array and delete the orders.
json parsing, and retrieving order_id work fine.
I'm so close but I can't figure out how to properly reference commerce_order_delete or commerce_cart_commerce_order_delete?
function afc_custom_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
          if ($entity->id() == 803) {
            $url = 'my url';
            $jsonString = file_get_contents($url);
            $jsonDecoded = json_decode($jsonString, true);
            $object = new stdClass();
            foreach($jsonDecoded as $row){
            if ($row['order_id'] == 121) {
                $object->order_id = $row['order_id'];
                // $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row['order_id']);
                commerce_cart_commerce_order_delete($object);
            }

            }
          }
    }

Error:
TypeError: Argument 1 passed to commerce_cart_commerce_order_delete() must be an instance of Drupal\commerce_order\Entity\OrderInterface, instance of stdClass given,

UPDATE #2
New Code
use Drupal\commerce_order\Entity\OrderInterface;

  if ($entity->id() == 803) {
    $url = 'https://myurl.com/pull-ghosts';
    $jsonString = file_get_contents($url);
    $jsonDecoded = json_decode($jsonString, true);

    $object = new OrderInterface;

    foreach($jsonDecoded as $row){
      if ($row['order_id'] == 121) {
        $object->setOrderNumber($row['order_id']);
        commerce_cart_commerce_order_delete($object);
        print 'deleted';
      }
    }
  }

SAME ERROR:
error: Cannot instantiate interface Drupal\commerce_order\Entity\OrderInterface in afc_custom_node_view()

Comment: There is no such thing as commerce_order_delete(). commerce_cart_commerce_order_delete() is a hook implementation and should never be invoked manually.

Commerce entities are deleted like any other Drupal entity. $order->delete(); or $order_storage->delete([$order]);
Comment: Also, you don't use `new` with a PHP interface. `new OrderInterface` is going to give you an error message.
Comment: You have the order id, so why not load the order object with that?
Something like Order::load($id); Actually dunno the base class of the Interface.
Answer: Loading it like a normal entity did the trick.
How to load and delete commerce order programmatically
$ord_id=121;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);
$order->delete();

Here is the entire snippet on my ultimate goal which was deleting abandoned orders in the cart.
How to remove commerce orders automatically
How to delete ghost commerce registrations in cart
Custom cron to delete commerce orders programmatically
Load a view programmatically loop through values and delete orders
/**
 * Implements hook_cron().
 */
 function my_module_cron() {
   //load a view showing orders still in cart
   $view = \Drupal\views\Views::getView('commerce_carts');
   //the name of your display, i chose a simple rest display with the order_id field
   $view->setDisplay('rest_export_1');
   $view->execute();

   foreach($view->result as $row){
     //load the order
     $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row->order_id);
     $oid = $order->id();
     //delete the order
     $order->delete();
     //log to dblog
     \Drupal::logger('afc_commerce_registration')->notice('Clearing ghost registration, deleted: @oid.',
       array(
           '@oid' => $oid,
       ));
   }
 }

You can add the Created date field to the view, and test time values before deleting. In my case, it doesn't matter.
Thanks for the help everyone
Answer: For one, in your updated code, you cannot instantiate an Interface in PHP. This is throwing the error. If you were to need a new instance, you would instead use the Order class which implements the OrderInterface Interface.
As Orders are Entities, you should be able to simply load the Order and delete it.
Example:
use Drupal\commerce_order\Entity\Order;

$my_order = Order::load(122); // Or, your Order ID
$my_order->delete();

This should delete the Entity, which is your Order in this case.
Answer: You need your object to be of the class Drupal\commerce_order\Entity\OrderInterface instead of an empty class.
Use this instead: (Update)
use Drupal\commerce_order\Entity\OrderInterface;

$object = new OrderInterface;

foreach($jsonDecoded as $row){
  if ($row['order_id'] == 121) {
    $object->setOrderNumber($row['order_id']);
    commerce_cart_commerce_order_delete($object);
    print 'deleted';
  }
}

Comment: This seems like exactly the right path, but getting an error. Update on original post: error: Cannot instantiate interface Drupal\commerce_order\Entity\OrderInterface in afc_custom_node_view()
Comment: Same Error: Cannot instantiate interface Drupal\commerce_order\Entity\OrderInterface in


How can I disable a specific date in daterangepicker?

Question: I want disable the date 9th of September 2017 in my daterangepicker:

var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('input[name="daterange"]').daterangepicker({
    minDate: new Date(currentYear, currentMonth, currentDate)
    , dateFormat: 'yy-mm-dd'
    , startDate: moment(date).add(1,'days')
    , endDate: moment(date).add(2,'days')
    , datesDisabled:["17-09-09"]
    , locale: {
        format: 'DD.MM.YYYY'
    }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<input type="text" name="daterange" value="01/01/2015 - 01/31/2015" />

But the date is not disabled in my calender
Answer: bootstrap-daterangepicker doesn't have datesDisabled option. Instead this option belongs to Bootstrap 3 Datepicker.
With daterangepicker you can use the isInvalidDate option:
isInvalidDate: function(ele) {
    var currDate = moment(ele._d).format('YY-MM-DD');
    return ["17-09-09"].indexOf(currDate) != -1;
}

The snippet:

var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('input[name="daterange"]').daterangepicker({
    minDate: new Date(currentYear, currentMonth, currentDate)
    , dateFormat: 'yy-mm-dd'
    , startDate: moment(date).add(1,'days')
    , endDate: moment(date).add(2,'days')
    , isInvalidDate: function(ele) {
        var currDate = moment(ele._d).format('YY-MM-DD');
        return ["17-09-09"].indexOf(currDate) != -1;
    }
    , locale: {
        format: 'DD.MM.YYYY'
    }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<input type="text" name="daterange" value="01/01/2015 - 01/31/2015" />
Comment: These two are others points. Give me time and I'll add these other features. Thanks
Comment: Ok, no problem. Thank you very much
Comment: It is working. The problem is, that I am still able to write the 09.09.2017 into the input field
Comment: And I can also can select a range from 07.09.2017 to 12.09.2017. This should actually not be possible, because there is a disabled day in that range
Comment: @gaetanoM I know, pretty old, but do you know which are those options? I'm using react-bootstrap-daterangepicker which is a wrapper of daterangepicker but I cannot figure how not to let the user wrap invalid dates. Any idea to share?


SOA domain records cannot be retrieved

Question: I'm still having trouble setting up my nameservers. DNS check says the following about my nameserver address:

Checking SOA records for domain. Domain server is not answering to UDP requests on port 53. Possible problems: A firewall is blocking port 53, server is down, server is not running software for handling dns requests.

I've run netstat -anp and found out that named is listening on tcp port 53, and it has udp port 53 on all IPs listed among active connections, though I'm unsure if that also means the port is actually active.
edit:
This problem is now solved. Everything was configured correctly, the problem was in zone files which didn't have appropriate permissions, so named couldn't read them.
Comment: Have you tried using `nslookup` from a remote computer to test your DNS server?
Comment: My registrar hasn't written the new nameservers into the DNS zone, because my server is not behaving like one (not answering the requests on UDP port 53).
If I run nslookup on my IP (the one that should act as ns1) I get a Non-Authoritative answer. There are however authoritative answers from two IP addresses that are close in range to mine, but I don't see how this could help me.
Comment: I'm thinking. Should I create a reverse lookup zone for my server's IP? The external one I mean, the one for localhost is already set up.
Comment: Since you found your own answer, you should post that as an answer and then mark it as accepted please.
Comment: I'd rather he accepted mine - it was the one that told him to go look in the BIND log file for the answer ... ;-)
Answer: I found what was wrong.
The zone files had read permissions set only for root, so named couldn't open them.
Answer: From here, I get answers from your servers for the two .arpa zones, but SERVFAIL for the .si domain.  Hence it's clearly not an IP stack or firewall problem.
Your BIND log file should tell you why that particular zone isn't working.  FWIW, I ran your drustvo.zone file against the named-checkzone program and it said there were no errors.
Comment: Thanks for your effort, I found out what was the problem checking the logs when I restarted BIND. The zone files had read permissions set only for root, so named couldn't open them. Quite stupid, and to think I wasted a day o this...

SOA domain records cannot be retrieved


Criar rotas usando o Route do React

Question: Seguinte estou utilizando o react-router-dom enquanto estou servindo a pasta do projeto como se fosse raiz funciona, as rotas vão para os componentes específicos meu problema é quando eu coloco em um servidor:
a parte do front onde está o react eu coloco dentro da pasta /app e meus scripts php que interagem com o front em /server.
diferente quando eu coloco o react na raiz / que funciona perfeitamente.
<Router>

      inicio
      maps
      cadastro

      <Route path={"/app/maps"} component={TelaMaps} />
      <Route path={"/app/cadastro"} component={TelaCadastro} />

  </Router>

Answer: O seu problema é a rota que você faz no seu servidor para os arquivos do React.
Se você está usando webpack e express basta você fazer uma combinação dos dois para servir seus arquivos no lugar desejado.
Um exemplo:
Webpack output:
output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },

Express configuração:
const app = express();
app.use(express.static('dist'));

Comment: Infelizmente eu não estou utilizando o node, meu projeto é com o PHP usando o stack com APACHE.
Comment: Coloca as configurações que você tem

Criar rotas usando o Route do React


Access console logs from VS Code extension

Question: I'm working on a VS code extension which needs to access console.log() output, written into the user's active terminal.
I'm aware of the vscode.window.activeTerminal API which returns a Terminal. However, according to the docs I can only sendText() to the terminal.
Is it possible to read the terminal's content from within my extension?
Answer: It cannot do in stable version of VSCode. Try window.onDidWriteTerminalData API only in Insider version.
For your information, there are several options, not official supported by VSCode.

Use node-pty to create and manage the process and then hook it up using ExtensionTerminalOptions.
Create a process/script that wraps the terminal shell.

reference:
https://github.com/microsoft/vscode/issues/83224
https://github.com/microsoft/vscode/commit/dc6b475be75999e78233f9f6951ef66f18f768ea#r53974957


Is there a way to exclude a network interface from being bound via INADDR_ANY?

Question: In network programming, it's common to pass INADDR_ANY (or IN6ADDR_ANY) as part of the second argument to bind(), telling the networking stack that you want the socket to receive connections/traffic from any network interface that the machine happens to have.  Many programs do this, as it is often the most useful behavior.  The other common option is to specify a single network interface to bind to, instead.
However, I have a use-case where I'd like one particular network interface on my Linux machine be "reserved", in the sense that it is not included in the set of network interfaces used by sockets bound to INADDR_ANY.  In particular, I'd like this network interface to be usable only by sockets that have bound themselves to its IP address explicitly (or perhaps have performed some other explicit step to indicate that they are aware of this network interface's special status and wish to use it anyway) -- sort of a "socket whitelist", if you will, to guarantee that only a few hand-picked apps can send/receive traffic over this network interface.  (These apps will likely be ones I wrote and personally control, if that matters)
Is there any mechanism to accomplish this in Linux?
Some approaches that I have considered but am not entirely satisfied with:

Modifying all apps to bind explicitly to the network interfaces they want to use, instead of binding to INADDR_ANY, and not including this network interface in the set.   (too much work, and I probably don't have access to modify all such apps anyway)
Setting up a firewall on the network interface such that only traffic on certain ports is accepted.  (this might sort-of work, but it means I have to specify in advance all ports that I will use on the interface, which precludes software that required dynamic port allocation... and of course there would still be the chance that some unexpected app gets "lucky" and happens to bind to one of the whitelisted ports, which would be undesirable)
Switch to SELinux or similar security-oriented distribution that has fine-grained ACLs (not a realistic option here, for various reasons I won't get into)
Comment: This kind of requirement is traditionally solved with firewall rules, i.e. everything is blocked except this kind of service. An alternative or addition would be to expose the network card directly to the specific container or VM where the customer facing application is running,  and not have it usable (no address assigned) for the rest of the system.
Comment: *" I have a use-case where I'd like one particular network interface on my Linux machine be "reserved""* - please be more clear about this use case. Currently it looks like an [XY problem](https://en.wikipedia.org/wiki/XY_problem) to me where you want an unspecified problem (X) with a specific approach (Y) and thus ask on how to do Y. Maybe one can up with a better idea once X is known too.
Comment: @SteffenUllrich the Y is that a customer wants to attach our headless server device to a network where only 'highly secured' devices are permitted, which is to say that the only traffic they want our device to respond to on that network is the customer-facing service that customer explicitly wants to use; all the other services on the device should be verifiably unable to communicate over that network interface.  (The other services still need to run and communicate via the other/non-secure-network interfaces though, as these servers can be clustered together and need to talk to each other)
Answer: Have you tried or considered iptables (I know its hard to specify precisely the requirements, but it is probably worth trying and trying until success ):
To allow traffic only from IP address 10.0.0.1 and port 80 to be forwarded to the reserved network interface
iptables -A FORWARD -i <reserved_interface> -s 10.0.0.1 -p tcp --dport 80 -j ACCEPT

And then block all other
iptables -A FORWARD -i <reserved_interface> -j DROP

Or to use the network-manager to create a virtual network interface and move the IP address you want to reserve to the virtual interface, this way the applications will not be able to bind to it by default, you can also use firewall rules on the virtual interface. I will watch this article to see what will the final result.


Finding $\frac{1}{2\pi}\int_{0}^{2\pi} \cos^{2n} x dx$

Question: I have a question that asks me to find the value of $\displaystyle\frac{1}{2\pi}\int_{0}^{2\pi} \cos^{2n} x dx$  $\ $ by considering the integral $$ \displaystyle \oint_{\gamma} \frac{1}{z}\left ( z+\frac{1}{z} \right ) ^{2n}dz$$ where $\gamma$ is the circle of radius 1 centered at the origin.
So I expanded the integrand out using the binomial theorem to get the following:
$$\displaystyle \frac{1}{z}\left ( z+\frac{1}{z} \right ) ^{2n}=\sum \binom{2n}{k} z^{2n-2k-1}$$ so the integral of each of these terms is 0 apart from when $k=n$ and we get $\int_{\gamma}z^{-1} dz=2\pi{i}$ and so we have that:
$$ \displaystyle \oint_{\gamma} \frac{1}{z}\left ( z+\frac{1}{z} \right ) ^{2n}dz=\binom{2n}{n} 2\pi{i}$$
If we now let $z=e^{it}$ on $\gamma$ then the integral becomes:
$$\displaystyle \int_{0}^{2\pi} \frac{ie^{it}}{e^{it}} \left ( e^{it}+e^{-it} \right )^{2n}dt=  {i}\int_{0}^{2\pi} \left ( e^{it}+e^{-it} \right )^{2n}dt={i}\int_{0}^{2\pi} \left ( 2{\cos(t)} \right ) ^{2n}dt=\binom{2n}{n} 2\pi{i}$$
and finally:
$$\displaystyle\int_{0}^{2\pi} \left ( \cos(t) \right ) ^{2n}dt=\binom{2n}{n} \frac{2\pi}{2^{2n}}$$
However I checked the answers that I have and it is the same apart from on the right hand side there is no $\dfrac{1}{2^{2n}}$, I was wondering what I had done wrong?
Thanks very much for any help
Comment: You mean $\left ( e^{it}+e^{-it} \right )=2\cos(t)$?
Comment: Yeah, don't know why I have done that there, it's correct on the RHS, sorry about that i'll edit
Answer: As you can see in this answer (where $n$ is your $2n$), your result is correct; so if you interpreted the answers your were given correctly, they must be wrong.
Answer: I think that your binomial expansion should be:
summation k goes from 0 to n {(2n n) z^(2k-2n-1) instead of summation (2n n) z^(2n-2k-1)}
Also, I think you are missing 2^(2n) because cos x = 1/2(z + 1/z) while you forgot to put 1/2 before paranthesis.
Comment: Please use [**MathJax**](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for formatting questions and answers as it great improves readability and thus understanding. Also, what do you mean by $(2n n)$? Regards.


Separando páginas por categorias (incluindo permalinks)

Question: Estou trabalhando num projeto em que é necessário que exista uma separação por tipos de páginas. Funciona assim:
Ao acessar o website, o visitante deve escolher se é Empresa ou Candidato, e eu gostaria que a URL separasse empresa de candidato, como:
nomedosite.com/empresa/
nomedosite.com/candidato/
Existem várias páginas diferentes no grupo empresa e também várias páginas diferentes no grupo candidato. Preciso que a URL final seja: http://nomedosite.com/candidato/contato, por exemplo.
Dentro do site também existem diversas postagens no blog da empresa e no blog do candidato, e necessito que fiquem assim, por exemplo:
http://nomedosite.com/candidato/blog/postagem-do-blog-candidato.
Já pesquisei muito mas não encontrei nada que me ajudasse a separar as páginas... Somente os posts.
Answer: Você pode adicionar as páginas da URL que vem antes da página final como Página mãe. vlw
Comment: Deu certo cara!!


Ideas for defining a "size" which informally measures subsets of rationals to eachother?

Question: EDIT: I posted an answer to this question. Can somone check?
Consider set $T_1,T_2,...T_p$ which are subsets of $\mathbb{Q}$
I want to create a new definition of "size" that distinguishes between subsets of $\mathbb{Q}$ that have "significantly" more elements inside of $\mathbb{Q}$ than other subsets. (Note that I want this size to apply to countably dense and countably finite subsets of $\mathbb{Q}$) .
For example, if we compared rational numbers to integers, we know there are significantly more rationals in rationals than integers in rationals. Morover,  there are infinite rationals between every integer, further proving the previous statment.
Unfortunately, formal measures, which assigns a weight for each singleton $\left\{x\right\}$ in $T_p$,
$$\mu(T_p)=\sum_{x \in T_p}\mu(\left\{x\right\})$$
would not be meaningful since assigning zero or positive weight would give subsets of $\mathbb{Q}$ zero or infinite measure. This does not distinguish which of those subsets could have significantly more or less elements inside of $\mathbb{Q}$.
Cardinality is also a problem, since it counts the number of elements, rather than determine which subsets $\mathbb{Q}$ have more elements in $\mathbb{Q}$. Morover, the cardinality of any countably infinite set is infinity.
However, informal measures can be used. For example, the asymptotic density of a subset of $\mathbb{N}$ is the number elements the subset "fills" of natural numbers between $[0,b]$ as $b\to\infty$.
How can we create a new definition of "size" that constructs an informal measure of the subsets of $\mathbb{Q}$ and meets the following requirments?
-If $T_1=T_2$ and $\mu(T_1)=\mu(T_2)$
-If $T_1\subseteq T_2$ then $\mu(T_1) \le \mu(T_2)$
Comment: This sounds like a problem that might be an application of *numerosity*, a concept that extends cardinality but retains the archimedian properties you seek. See http://www.sciencedirect.com/science/article/pii/S0001870802000129 or https://arxiv.org/pdf/1212.6201.pdf
Comment: Sorry I don't know that. Numerosity is something I came across by accident since I dealt with some other work of one of the authors; but I hadn't really looked at it in detail. All I know is that it is based on an ultrafilter construction and claims to achieve some of the properties you seek.
Comment: If anyone has ideas let me know.
Comment: Does the post make sense?
Comment: @Hyperplane I know this too much to ask of you but is numerosity the same as the extending asymptotic density to rationals as mentioned in mine and RossMillikan's answer.
Comment: why the downvote?
Comment: Maybe you'd want to look at field extensions, depending on context. Or take equivalence classes to compare them.
Comment: Perhaps somone can vote for what they think is the best answer.
Comment: @AspiringMathematician Can you check my answer?
Comment: @Hyperplane If you have time, check my answer.
Answer: There is a "natural" extension of the natural density to the rationals, but I am not sure how useful it is.  The set of rationals in $[-b,b]$ with denominator less than $b$ is finite, so we can compute the fraction of these rationals that are in $T$ and ask if there is a limit as $b \to \infty$.  We want to consider the rationals when expressed in lowest terms.  This clearly meets your request that the density of a superset is at least as great as that of a subset and that sets which are negatives of each other get the same density.
There are $\phi(k)$ fractions with  denominator $k$ in each unit interval.  Wikipedia states that $\sum\limits_{i=1}^b \phi(k) \approx \frac 3{\pi^2}b^2$ so we have about $\frac 6{\pi^2}b^3$ rationals in $[-b,b]$ with denominator $b$ or less.
${}{}{}{}$
It seems one density that would be interesting would be the density of rationals with odd numerators.  This is all the ones with even denominators and half of the ones with odd denominators.  We need the sum of the totient function over the even numbers to get this, but I haven't found one.
Comment: The extension does not satisfy the property $\mu(A)\le\mu(B)$ if $A\subset B$. The simplest counterexample is $A=\left\{\frac{m}{2n+1}\right\}$ and $B=\left\{\frac{m}{4n+2}\right\}$. You would find that the density of $A$ is greater than the density of $B$.
Comment: The density of $A$ can be found using $\frac{\sum\limits_{i=1}^{\left\lfloor{\frac{b-1}{2}}\right\rfloor}\phi(2i+1)}{\sum\limits_{i=1}^{b}\phi(i)}\approx\frac{\frac{2}{\pi}b^3}{\frac{3}{\pi}b^3}=2/3$ and the density of $B$ can be found using  $\frac{\sum\limits_{i=1}^{\left\lfloor{\frac{b-2}{4}}\right\rfloor}\phi(4i+2)}{\sum\limits_{i=1}^{b}\phi(i)}\approx\frac{\frac{1}{2\pi}b^3}{\frac{3}{\pi}b^3}=1/6$. Hence $\mu(A)>\mu(B)$ disproving one of my requirments.
Comment: The only solution I found was to separate the denominator by divisor 2 to get $2^k(2n+1)$, where $k<r$ and $2n+1<b$, and take the rationals in $[-b,b]$. The number of rationals is $\sum\limits_{k=1}^{r}\sum\limits_{n=1}^{\left\lfloor\frac{b-1}{2}\right\rfloor}\phi(2^k n)\approx\frac{4}{\pi^3}b^3(2^r)$ (using $\phi(cd)=\phi(c)\phi(d)$). We then compute the fractions that are in $T$ as $(r,b)\to\infty$
Answer: I strongly recommend that you read Mancosu's article on counting principles, as he reviews the interesting literature that has emerged out of this question. In particular, following the work of Benci and Di Nasso (which is the most promising line of attack), he analyzes the question as being equivalent to the existence of a "numerosity" function $v$ from $S$ (the set of sets to be counted) to $N$ (the set which will be used for counting, typically, in the case of countable sets, $\mathbb{N}$) such that:
(1) If $A, B \in S$ are such that $A \subset B$, then $v(A) < v(B)$;
(2) If $v(A) = v(A')$ and $v(B) = v(B')$, then $v(A \sqcup B) = v(A' \sqcup B')$ and $v(A \times B) = v(A' \times B')$ (it preserves disjoint unions and products).
Ideally, we would want it to preserve bijections, but we know that is not compatible with (1) for infinite sets. Nevertheless, there may happen that we are able to impose some other restriction on the bijections to make it work, i.e. something like
(3)  If $A \simeq B$ (an isomorphism under an appropriate relation), then $v(A) = v(B)$.
In the second article mentioned above, the authors show that the existence of (an interesting example of) such a function is equivalent to the existence of a certain type of ultrafilter on the natural numbers (Ramsey or selective ultrafilters), which incidentally shows that this question is independent of $\mathsf{ZFC}$. If you're familiar with ultrafilters, their appearance in this context is not very surprising, since they typically give rise to a measure. There are also interesting connections to non-standard analysis which are explored in the article.
Comment: I will read into this in more detail but I am unsure how effective this will be on subsets of rational number. Anyways, if you have time can you check my answer.
Comment: Hopefully, Numerosity is a generalization of [asymptotic density](https://en.wikipedia.org/wiki/Natural_density) and the answer I found. Otherwise, there will be conflict between both ideas.
Answer: How about $\mu: \mathcal{P}(\mathbb{Q})\to \mathbb{N}\cup \{\infty\}$ defined by $\mu(T)=\limsup_{a<b\in \mathbb{Q}} |T\cap (a,b)|$. It measures the asymptotic behavior of local density and incorporates your requirement.
Comment: What does $\mathbb{N}\cup{\left\{\infty\right\}}$ mean?
Comment: $\infty$ here is just reserved for the cardinality of any countably infinite object, as made clear from the definition of $\mu$.
Comment: So if we set $T=\left\{\left.\frac{m}{2n+1}\right|m,n\in\mathbb{Z}\right\}$ what would $\mu(T)$ be?
Comment: Can you elaborate in more detail with how you got this equation?
Comment: $\mu(T)$ will be infinity, since between any rationals $a<b$, there are infinitely many $m,n\in \mathbb{Z}$ such that $a<\frac{m}{2n+1}<b$. In some sense this measure is really silly.
Comment: I mentioned that I wanted to avoid measures that are infinite for countably infinite sets. I don't feel this answer is relevant. It is best to put it in the comment section or delete it.
Answer: The theory of sets asserts that sets of integers and rational numbers are countable sets, that is, they have the same cardinality.
At the same time, our experience suggests the opposite:

For example, if we compared rational numbers to integers, we know there are significantly more rationals in rationals than integers in rationals. Moreover,  there are infinite rationals between every integer, further proving the previous statement.>

To reconcile the theory with common sense helps the particular case of lemma to the theorem of Matiyasevich on the existence of a one-to-one correspondence
$$ \left(\mathbb Z^+\right)^2\leftrightarrow \mathbb Z^+,$$
using the functions
$$\begin{cases}
z(x,y) = \dfrac12\left((x+y)^2 - x - 3y +2\right)\\
x(z) = z-\dfrac12(s(z)-1)(s(z)-2)\\
y(z) = s(z)-x(z),
\end{cases}\tag1$$
where
$$s(z) = \left[\sqrt{2z-{7\over4}}-{1\over2}\right] + 2\tag2$$
The functions $(1-2)$ realize the Cantor ordering of the set - by increasing the sum $s=x + y$, and if the sums are equal, by increasing $x$ (see also Wolfram Alfa). Therefore, the Cantor's consequence is
$$q_i = \left\{ {1\over1}, {1\over2}, {2\over1}, {1\over3}, {2\over2}, {3\over1}, {1\over4}, {2\over3}, {3\over2}, {4\over1}, {1\over5}, {2\over4}, {3\over3}, {4\over2}, {5\over1}, {1\over6}, {2\over5}, {3\over4}, {4\over3}, {5\over2}, {5\over2},\dots \right\}$$
In my opinion, this order can be used as the "natural" order of positive rational numbers.
For example, natural series displayed in consequence of Cantors indexes
$$N_n = {1\over2}\left((n+1)^2 - n - 3 +2\right) = {n(n+1)/2},$$
fractions with odd numerator and even denominator - in consequence
$$H_n = \left\{2, 7, 9, 16, 18, 20,\dots \right\} .$$
Thus, each infinite subset of rational numbers can be displayed as the increasing sequence of Cantor indexes, allowing to form representative samples of a given volume. Reciprocal to the selective expectancy of $x\over y$, or its limit (when it converges), or some another selective statistics can be used as the required measure of subsets.
At the same time, more informative (and therefore more promising) direction is the construction of empirical probability distributions.
Comment: I'm glad you gave me other possible methods but can you check my answer. My username is Arbuja.
Comment: I can't find an article on cantor indexes and how does this lead to $N_n$ and $H_n$? I apolgize for my ignorance.
Comment: Try it [there](https://www.google.com.ua/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwjAvNT1xYjUAhWCZpoKHQyuDTsQFggxMAI&url=https%3A%2F%2Fwww-fourier.ujf-grenoble.fr%2F~panchish%2FGDL16%2FManin_Panchishkin_Introduction%2520to%2520modern%2520number%2520theory.pdf&usg=AFQjCNFXHh3T7hFVr-jn_EV263a3MCrAQg&sig2=HcApvYHyWx3uYXINbMf5yQ), page 110
Answer: Here is another definition my professor offered.
However, I believe it does not follow my second requirement for an appropriate measure/density.
Requirement 1: If $T_1$ and $T_2$ are subset of $\mathbb{Q}$ and $T_1=T_2$, then $D(T_1)=D(T_2)$
Requirement 2: If $T_1$ and $T_2$ are subset of $\mathbb{Q}$ and $T_1\subset{T_2}$, then $D(T_1)<D(T_2)$
We can turn $\mathbb{Q}$ into a finite set by restricting its numerator and denominator.
$$V(r)=\left\{\left.\frac{m}{n}\right|1<m<r,1<n<r,\gcd(m,n)=1\right\}$$
$$\lim_{r\to\infty}V(r)=\mathbb{Q}$$
We then take the number of elements in $V(r)$ that $T$ intersects with.
$$\frac{\left|T\bigcap{V(r)}\right|}{|V(r)|}$$
As $r$ becomes larger
$$D(T)=\lim_{r\to\infty}\frac{\left|T\bigcap{V(r)}\right|}{|V(r)|}$$


How to have multiple users in a user reference field

Question: I'm using Drupal 8.
Can I have multiple users by comma separating each users? When I was doing by this way, after I input a comma, I can choose another user again. But after I submit it. Only the last user I have chose that had been saved (only 1 value).
If I set the field as "Allowed number of values to Unlimit or a number". There will be many user reference text box. I only want one user reference text box and have multiple users with comma separating. How to do it?
Answer: Yes, you can do that.
You need to select "Autocomplete (Tags style)" as the widget you use in the Form display.

After you have done that, you can use commas to add multiple users in the same widget (provided you have set cardinality to > 1).
Comment: It works very well for me! Thanks so much for your help!


A question about approximating a continuous function with a $G$-invariant polynomial.

Question: Given $f:\mathbb{R}^n \rightarrow \mathbb{R}$, a finite group $G$ and a compact set $K \subseteq \mathbb{R}^n$, I want to prove that I can approximate $f$ with a $G$-invariant polynomial on $K$.
I think this is trivial, but I'm not 100% sure.
What I would do is the following, by Stone-Weierstrass theorem we can say that there exists a polynomial $p$ such that
$$|f(\textbf{x}) - p(\textbf{x})| < \varepsilon \, \, , \, \forall \textbf{x} \in K .$$
Then I consider the set $K_{sym} = \bigcup_{g \in G} g \cdot K$ and define $q(\textbf{x}) = \frac{1}{|G|}\sum_gp(g \cdot \textbf{x})$. Of course $q$ is $G$-invariant.
Can I conlcude from here, that
$$|f(\textbf{x}) - q(\textbf{x})|<\varepsilon \, \, \forall \textbf{x} \in K \, \, \, \, ?$$
EDIT:
First we consider a symmetrized domain $K_{sym} := \bigcup_{g \in G}g \cdot K$ which is still compact because is the image of the continuous map $(g,\textbf{x}) \mapsto g \cdot \textbf{x}$. So ther exists a polynomial $p$ such that
$$|f(\tilde{x})-p(\tilde{x})| < \varepsilon \, \, , \, \forall \tilde{x} \in K_{sym}.$$
But if $\tilde{x} \in K_{sym} \Rightarrow \exists g \in G$ such that $\tilde{x} = g \cdot \textbf{x}$ for some $\textbf{x} \in K$.
Then we define $q(\textbf{x}):= \frac{1}{|G|}\sum_{g \in G}p(g \cdot \textbf{x})$ and then
$$|f(\textbf{x})-q(\textbf{x})| = |f(g \cdot \textbf{x}) - \frac{1}{|G|}\sum_g p(g \cdot \textbf{x})| \le \frac{1}{|G|}\sum_g|p(g \cdot \textbf{x}) - f(g \cdot \textbf{x})| < \varepsilon.$$
I'm trying to follow the lines explained in this work https://arxiv.org/pdf/1901.09342.pdf (right under Definition 4)
Comment: How (and on what) is the action of $G$ defined? Add details to your reasoning and see if it still holds…
Comment: $G$ is a general group acting on the coordinates $\textbf{x} \in \mathbb{R}^n$
Answer: I am in doubt. Consider $f:\mathbb{R}^2  \to\mathbb{R}$, $f(x,y)=x$, $K=[0,1]^2$ and $G=\{I, (x,y) \mapsto (y,x)\}$. If $p$ is any polynomial, then
$$
q(x,y)=\frac{1}{2}(p(x,y)+p(y,x)).
$$
Let $\varepsilon = 1/3$. Assume that $|f(x,y)-q(x,y)| < \varepsilon$ on $K$.
Then on $K$
$$
|x-q(x,y)| < 1/3, ~ |y-q(y,x)|=|y-q(x,y)|<1/3.
$$
For $x=0,y=1$ we get $|q(0,1)|< 1/3$ and $|1-q(0,1)|<1/3$, not possible.
I think this approximation is only possible if $f$ is $G$-invariant
on $K':= \cup_{g\in G} gK$, that is $f(x)=f(gx)$ $(x \in K',g \in G)$. Then your argument works.
Comment: I'm actually looking at the proof given in this work (Proposition 2.1) https://arxiv.org/pdf/1804.10306.pdf and trying to figure out what is the difference...
Comment: I don't understand the details, but the author of this Proposition is talking about approximating "group invariant" functions by (simpler) group invariant functions. That's in accordance with what I meant with the last sentence of my answer.
Comment: Actually, there is another work related to the first one https://arxiv.org/pdf/1901.09342.pdf where it is stated exactly $G$-invariant polynomials can approximate an arbitrary continuous function on a compact domain .(Right under Definition 4)
Comment: I think the assertion in the second paper is wrong, as stated. If a sequence of polynomials $(q_k)$ is uniformly convergent to a function $f:\mathbb{R}^n \to \mathbb{R}$ on a compact set $K'$ containing $K$ where $K'$ is $G$-invariant and each $q_k$ is $G$-invariant then $f(x)-f(gx) = f(x)-q_k(x)+q_k(gx)-f(gx) \to 0$ for each $x \in K'$ and each $g \in G$. Thus $f$ has to be $G$-invariant on $K'$.
Comment: So even if we consider $f$ on the symmetrized domain $K'$ it doesn't mean that the function is invariant on this domain, i.e. $f(g \cdot x) = f(x)$ for $x \in K_{sym}$. Maybe I was a bit confused about this. Actually if the map $f$ is $G$-invariant it makes sense then to write $|q(x)-f(x)| = |p(g \cdot x) - f( g \cdot x)|\dots$ like they actually start to do in the paper. It's this equality that I didn't indeed understand.
Comment: but in your statement, if $x \in K'$ then shouldn't it be $f(gx) = f(x)$?
Comment: Yes, that's correct. I will edit it.
Answer: No such approximation is possible. Here is a counterexample. Let $\mathbb{Z}_2$ act on $\mathbb{R}$ by negation. The functions invariant under this $\mathbb{Z}^2$ action are the even functions. So, for instance, on $[-1,1]$, no approximation of $f(x) = x$ to within $1$ in $\sup$ norm is possible.


How do you troubleshoot a website javascript popup that should be showing up on a dnn in order to get things connected from an external popup builder?

Question: I'm currently working with a website created in DNN and I am trying to get a popup onto the home page---I am currently using Popupsmart for ease of use, but I have tried to install the javascript code and popupsmart is not recognizing that it is installed. I've tried two different ways of installing---via google tag manager and a content injection module.
It is a custom-designed popup to collect lead info on potential new customers (pretty standard).
I am attaching some images to go along with this post and would love any help in troubleshooting the issue. Thank you in advance!
I tried GTM and a content injection module and thought that this would fix the issue. Not sure where I'm going wrong.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: You have several possibilities.
If you use a Text/HTML module, you can add the script to the header or the footer, but if you do that often it can get a bit hard to maintain. And you don't have much control of where the script will appear in the rendered page.
I would suggest to use Will Strohl's Content Injection Module, that let's you inject anything on the page with much more control over it.
But if you want this on every page of your site adding it to the theme would be the best choice.
Comment: Michael, thank you so much! I really appreciate the insights. I will try this out and let you know if I can see any changes on my end!
Comment: Michael, I've been trying to figure this out with no luck. I recorded a short screen recording explaining the problem in more detail, so that you guys get a better understanding. If you could send over a quick screen recording of how you would potentially troubleshoot/solve it yourself that would be awesome!

Here's the link of me explaining things in more detail: https://share.vidyard.com/watch/qmdrJF11WAEFEsn6pqYzaW?

Or could you hop on a quick call? I am more than willing to pay to get this resolved asap!
Comment: Did you check if your browser is not blocking popups?
Answer: Per page, header tip:
In the page settings for your home page, go to the Advanced tab > SEO > Page Header Tags. This section will inject HTML into the HEAD of that specific page. Since it is HTML for this input, be sure to wrap and javascript in  tags.


Degree of a formal power series involving Mobius function

Question: I am reading Enumerative Combinatorics by Richard Stanley, and I came across the following expression: $(1-x^n)^{\frac{-\mu(n)}{n}}$, where $\mu(n)$ is the usual Mobius function from number theory.
This expression can also be written as:
$(1-x^n)^{\frac{-\mu(n)}{n}}=\sum_{i \ge 0} \binom{-\mu(n)/n}{i}(-1)^ix^{in}$
This part is clear. But then the author claims that the expansion above shows that $(1-x^n)^{\frac{-\mu(n)}{n}}=1+H(x)$, where $H(x)$ is a formal power series of degree $n$. Why is that?
(Also: the degree of a formal power series is defined here as the smallest integer for which the corresponding coefficient is nonzero.
$\binom{-\mu(n)/n}{i}$ is defined in the usual way, as $\frac{(-\mu(n)-i+1)\dots (-\mu(n))}{i!}$)
Answer: As $\mu(n)\in\{0,1,-1\}$ we have one of three cases.
If $\mu(n)=0$ then
$$(1-x^n)^{\mu(n)/n}=1$$
so that $H(x)=0$.
If $\mu(n)=1$ then
$$(1-x^n)^{\mu(n)/n}=(1-x^n)^{1/n}=1-\frac{x^n}{n}-(n-1)\frac{x^{2n}}{2n^2}
-\cdots$$
so that
$$H(x)=-\frac{x^n}{n}+\text{higher terms}.$$
If $\mu(n)=-1$ then
$$(1-x^n)^{\mu(n)/n}=(1-x^n)^{-1/n}=1+\frac{x^n}{n}+(n+1)\frac{x^{2n}}{2n^2}
-\cdots$$
so that
$$H(x)=\frac{x^n}{n}+\text{higher terms}.$$
Comment: Thanks. Taylor series, right?


How do I add link to Edit and Delete in a column in a view table item list?

Question: I've trying to add a link to Edit and Delete column to perform desirable actions. I need help in implementing it. I've tried several suggested methods on the internet, but none did the job for me. Maybe I am doing something wrong.
Here is my Controller.php
<code>public function getAdList(){
            $limit = 3;
            $query = \Drupal::database();
            $result = $query->select('ad_form_submissions','u')
                    ->fields('u',['id','name','crop_category','crop_type','quantity','price'])
                    ->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit($limit)
                    ->execute()->fetchAll(\PDO::FETCH_OBJ);

            $data = [];
            $count = 1;

            $params = \Drupal::request()->query->all();

            if(empty($params) || $params['page'] == 0){
                $count=1;
            }else if($params['page'] == 1){
                $count = $params['page'] + $limit;
            }else{
                $count = $params['page'] * limit;
                $count++;
            }

            foreach($result as $row){
                $data[] = [
                    'S_no'=> $count.".",
                    'ID'=> $row->id,
                    'Name'=> $row->name,
                    'Crop Category'=> $row->crop_category,
                    'Crop Type'=> $row->crop_type,
                    'Quantity'=> $row->quantity,
                    'Price'=> $row->price,
                    'Edit' => 'Edit',
                    'Delete'=>'Delete'
                ];
                $count++;
            }

            $header = array('S_no','ID','Name','Crop Category','Crop Type','Quantity','Price','Edit','Delete');

            $build['table'] = [
                '#type'=>'table',
                '#header'=>$header,
                '#rows'=>$data,
                '#empty' => t('No users found'),
            ];

            $build['parger'] = [
                '#type'=>'pager'
            ];

            return [
                $build,
                '#title'=> 'Submit Ad List'
            ];

        }
</code>
Clarification: I want to perform the Edit and Delete Task on the selected row.
Answer: I believe you are looking for Entity Operations. Soul you'd have to load the enity by ID, and then use the getoperations methods. Looking at your code though, I would suggest you use EntityTypeManager to instead load your entities with a EntityListController or something equivalent, it's all baked into core.


Little-Oh notation with index

Question: Currently I'm reading a paper in probability theory. Often, the author uses the little-oh-symbol, that I am not really familiar with, for example
$$
o_\varepsilon(n) \text{ for some } \varepsilon > 0 \text{ and } n\in\mathbb N.
$$
My intuition tells me that this means for a function $f_\varepsilon(n)\in o_\varepsilon(n)$ that
$$
\lim_{\varepsilon\to0} \frac{|f_\varepsilon(n)|}{n} = 0
$$
or something related.
Could you maybe tell me what you believe this means? I am especially uncertain with the index $\varepsilon$. For example with my "definition" that means for $f_\varepsilon(n) = \varepsilon$ and $g(n)=n$ that
$$
\frac{|f_\varepsilon(n)|}{g(n)} = \frac{\varepsilon}{n} \to 0
$$
for $\varepsilon \to 0$ (or should it be $n\to\infty$)?
Here is the link to the paper.
Comment: This may differ substantially author-to-author. One common meaning is that the rate of decay depends on $\epsilon$. If you give a reference to the paper it may be possible to help more.
Comment: @SeanEberhard I'm talking about this [paper](https://arxiv.org/abs/1805.09744) for example p. 9, equation (52).
Answer: Typically this means that the unsubscripted version is true for any fixed value(s) of the subscripted variable(s). See, for example, p13 of these notes (this is for big-Oh, but the same concept applies).
Here $f_\epsilon(n)=o_\epsilon(n)$ would mean that if $\epsilon>0$ is kept fixed but $n\to \infty$ then $\frac{f_\epsilon(n)}{n}\to 0$. For example, $f_\epsilon(n)=\epsilon^{-1}\sqrt n$ satisfies this definition, but $f_\epsilon(n)=o(1)$ is not necessarily true if $\epsilon$ is allowed to depend on $n$.

Little-Oh notation with index