How to create static alpha masks of an image

Question: I have an image of following type-

I want to create mask of the following type where the inside area is white and rest of it is black. How to do it?
Comment: Again - edge detection. Or you can take out all perfectly black pixels and use those as an inverse to the mask (in this specific image it seems like it will work).
Comment: Could you please elaborate more on inversing black pixels?
Comment: Let's assume you create a new image which is black everywhere where the greyvalue (for example `(r+g+b)/3`) is lower than some threshold `T`, and white otherwise. So essentially:
`target(x,y) = dot(source(x,y),vec3(1)) < 3.0*T ? 1 : 0`
Where you loop over all pixels.
Answer: You can either use a threshold, or, since you know the location and size of the 2 circles, simply generate one programatically. In this case, you have a circle that's centered at (279, 283.5) and has a radius of 265. (I haven't calculated the center and radius of the smaller circle, but you should be able to do that fairly easily by looking at the image in any image editor that shows you mouse coordinates.)
Once you have the smaller circle radius, for each pixel in the mask find the distance to the large circle center and if it's less than the large radius, color it white. Otherwise take the distance to the smaller circle and if it's less than the smaller radius, color it white. Otherwise, color it black.


R: split dataframe by multiple answers

Question: So I have a dataframe with results of the survey.
The thing is, I have several questions with multiple answers in cell.
For example:
q1|q2
answer1;answer2;ansert4 |1986

so I need to extract 'tidy' dataset for specific analysis tasks, meaning: split those cells down  in the same column and copy other specified columns so it will be like that:
q1|q2
answer1|1986
answer2|1986
answer4|1986

How can i do this in R?
I am pretty sure it is a simple task, but I don't have any clue...
Answer: Another similar solution would be
library(splitstackshape)
cSplit(df, "q1", sep = ";", direction = "long")
#         q1   q2
# 1: answer1 1986
# 2: answer2 1986
# 3: ansert4 1986

Answer: You can do this with data.table package and strsplit function:
library(data.table)
setDT(df)[,setNames(strsplit(q1, ';'),'q1'),by=q2]
#     q2       q1
#1: 1986  answer1
#2: 1986  answer2
#3: 1986 ansert4

Data:
df = structure(list(q1 = "answer1;answer2;ansert4 ", q2 = 1986L), .Names = c("q1",
"q2"), class = "data.frame", row.names = c(NA, -1L))

Comment: You should probably mention GitHub somewhere here
Comment: I think I really did not get it..! What's the point with Git?
Comment: Oh never mind, I thought you've used the `tstrsplit` function from the devel version. Either way, you can also do this `setDT(df)[, .(q1 = tstrsplit(q1, ';')), by = q2]` using the devel version.

R: split dataframe by multiple answers


Manage GPU settings like turn-off v-sync, antialiasing ant etc?

Question: From the Nvidia X Server settings i have this:
https://copy.com/rB7ho3D0leoa
Not the GPU settings I am looking for.
Answer: You need the proprietary Nvidia drivers.
Go to Software & Update -> Additional Drivers and select the proprietary Nvidia drivers.
Then run sudo nvidia-setings from Terminal crtl+alt+t.
Comment: From where to download it?
Comment: You just need the proprietary Nvidia drivers and everything should be fine. I edited the answer.
Comment: I am using NVIDIA binary driver - version 331.8 from nvidia-331-updates(proprietary) and when type nvidia-settings in the terminal it opens Nvidia X Servers Settings.
Comment: Which version of Ubuntu are you using?
Comment: I am using Xubuntu 14.04
Comment: There should be way more options in the nvidia settings. Try `sudo apt-get install --reinstall nvidia-settings`
Comment: The same thing.


CSS only horizontal scrolling gallery wth images of various dimensions

Question: I'm tring to create a CSS-only horizontal scrolling gallery that contains images of various dimensions. Before you mark this as a dublicate (this question pops up frequently), I did do a lot of research and couldn't find any solution for different image dimensions yet.
My solutions so far have been:

flexbox
inline-block
Peter Biesemans rotation trick

the flexbox approach:

/* setting up the site */
* {
 margin: 0;
 padding: 0;
}
body {
 height: 100vh;
 width: 100vw;
 display: grid;
 grid-template-columns: 1fr 8fr 1fr;
 grid-template-rows: 1fr 8fr 1fr;
 grid-template-areas:
  ".    .    ."
  ".  wrap  ."
  ".    .    .";
}
#wrapper {
 grid-area: wrap;
 overflow-x: auto;
 overflow-y: hidden;
}
#wrapper ul {list-style: none;}

/* try using flexbox */
#wrapper ul {
 display: flex;
    flex-direction: row;
 flex-wrap: nowrap;
 -webkit-overflow-scrolling: touch;
 -ms-overflow-style: -ms-autohiding-scrollbar; /*suggestion from https://iamsteve.me/blog/entry/using-flexbox-for-horizontal-scrolling-navigation*/
 height: 100%;
}
#wrapper ul li {
 height: 100%;
 flex:0 0 auto;
}
#wrapper ul li img {height: 100%;} /*<-- breaks the thing

... but if I set the height of the images to 100%, it breaks my neat gallery by introducing a lot of white space after the images. And because the gallery wrapper is a grid-item itself with no absolute dimensions, the only choice I have is to calculate the resulting height of the images in vh and that defeats the whole purpose of using fr. Am I wrong and is there a easier way?
The older way would be using inline-block, which has basically the same problem:

/* setting site up */
* {
 margin: 0;
 padding: 0;
}

body {
 height: 100vh;
 width: 100vw;
 display: grid;
 grid-template-columns: 1fr 8fr 1fr;
 grid-template-rows: 1fr 8fr 1fr;
 grid-template-areas:
  ".    .    ."
  ".  wrap  ."
  ".    .    .";
}
#wrapper {
 grid-area: wrap;
 overflow-x: auto;
 overflow-y: hidden;
}
#wrapper ul {list-style: none;}

/* trying inline-block */
#wrapper ul {
 height: 100%;
 display: block;
 overflow-x: auto;
 overflow-y: hidden;
 white-space: nowrap;
}
#wrapper ul li {
 display: inline-block;
 height: 100%;
}
#wrapper ul li img {
 height: 100%;
}

The third option is just a bit too much of a hack and not ideal for mobile devices either.
So is there a slution to this?
EDIT: Features/properties the gallery should have:

vertical responsiveness: if the browser height is reduced, the gallery's parent element is also, so it should follow along;
no minium or maximum image heights; if the image is too small, it should be blown up;
horizontal response must be avoided: if the width of the browser is altered, the image width should stay the same (according to the aspect ratio and the height of the image);
Comment: something like [this](https://codepen.io/danield770/pen/QMzBEO)?
Comment: Nope, I want every image to be of the same height, but not the same width, so it should maintain its original aspect ratio.
Answer: You can do it like this:

* {margin:0;padding:0;box-sizing:border-box}
html, body {width:100%}

#wrapper {
  display: flex;
  justify-content: center; /* horizontal alignment / centering of the ul */
  width: 1000px; /* for presentation */
  max-width: 100%; /* responsiveness */
  margin: 0 auto; /* horizontal alignment / centering on the page */
}

#wrapper > ul {
  list-style: none;
  display: flex;
  overflow: auto; /* better this way */
  overflow-y: hidden; /* appears just a little, don't know why (yet), needs to be set to hide it and make it look nicer */
  max-height: 100vh;
}

#wrapper > ul > li {
  height: 150px; /* needs to match the height of the "shortest" img or be less than that but not more */
  flex: 0 0 auto; /* mandatory */
  max-height: 100vh;
}

img { /* responsiveness */
  display: block; /* to remove the bottom margin */
  height: 100vh;
  max-width: 100%;
  max-height: 100%; /* mandatory */
}

Comment: Thank you for your reply! It certainly got me closer to the solution, but it lacks some features I cannot miss this time: if the image height is less than the ``li`` it should be blown up. Furthermore if the browser window is changed in height, it should shrink the gallery too, because it is embedded in a responsive grid item. I'll edit my original post to point out these features, which I failed to express the first time.
Comment: Thank you! I am now trying to understand how the blank space is created, e.g. why and how the ``li`` element gets so wide in my solution, but in yours not. ``width: auto`` doesn't do anything. It' also not the original width of the image, so I don't understand how the engine computes this value.
Comment: Thank you so much, but no this is not what I meant. I am aware of this possible solution (see first paragraph after the flexbox snippet), but it is not as clean as I would like it to be. I was asking if there is a way so that the gallery could inherit its exact size and its items would adapt accordingly. If there is no solution, I would have to calculate the ``vh`` values of several layouts seperately in my project.


Expand card component and center it after hiding other components in Vuetify

Question: I created a button that hides other components on the page except one and then the one that is left is expanded and then it should be moved to the center.
However somehow the component is not aligning itself in the center after clicking on the button.
Here is codepen with the current behaviour.

new Vue({
  el: '#app',
  data: () => ({
    lorem: `Lorem ipsum dolor sit amet, mel at clita quando. Te sit oratio vituperatoribus, nam ad ipsum posidonium mediocritatem, explicari dissentiunt cu mea. Repudiare disputationi vim in, mollis iriure nec cu, alienum argumentum ius ad. Pri eu justo aeque torquatos.`,
    show1: true,
    show2: true,
    show3: true,
    show4: true,
    show5: true,
    expand1:true

  }),
  methods: {
    hideothers() {
        this.show2=!this.show2,
        this.show3=!this.show3,
        this.show4=!this.show4,
        this.show5=!this.show5,
        this.expand1=!this.expand1
                 }
  }
})

  <v-app id="inspire">
    <v-container fluid grid-list-sm>
      <v-layout row wrap>

        <v-flex d-flex xs12 sm4 child-flex>
          <v-card color="orange lighten-2" tile flat v-show="show1">
            <v-card-text>Card 1</v-card-text>
             <v-btn flat  @click="hideothers()">Expand</v-btn>
             <v-card-text>
                  <v-expand-transition>

This is a short paragraph

                  </v-expand-transition>
                  <v-expand-transition>

A looooong

paragraph

                  </v-expand-transition>
                </v-card-text>
          </v-card>
        </v-flex>

         <v-flex d-flex xs12 sm4 child-flex>
           <v-fade-transition>

          <v-card color="orange lighten-2" tile flat v-show="show2">
            <v-card-text>
            <v-layout row wrap>
              <v-flex sm6>
                 Card1
              </v-flex>
              <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
            </v-layout>
            </v-card-text>
          </v-card>
             </v-fade-transition>
        </v-flex>

        <v-flex d-flex xs12 sm4>
          <v-card color="red lighten-2" dark tile flat v-show="show3">
            <v-card-text>{{ lorem.slice(0, 100) }}</v-card-text>
          </v-card>
        </v-flex>

         <v-flex d-flex xs12 sm4 child-flex>
          <v-card color="purple lighten-1" tile flat v-show="show4">
            <v-card-text>{{lorem}}</v-card-text>
          </v-card>
        </v-flex>
        <v-flex xs12 sm4 child-flex v-show="show5">
          <v-card color="green lighten-2" tile flat>
            <v-card-text>{{lorem}}</v-card-text>
          </v-card>
        </v-flex>

      </v-layout>
    </v-container>
  </v-app>

Comment: as I shown in my answer below you cannot center element in flex container if other elements'childs just hidden. You have to replace v-show with v-if and place them into v-flex. Also to center content in the flex container you need to turn on justify-center prop of the v-layout
Comment: If you expand card component then you don't need to center it horizontally. Either you wish to expand it or to center it with 1/3 width of its container
Answer: Basically change the following line
<v-flex xs12 sm4 child-flex v-show="show2" :class="{ 'd-flex': show2 }">

Apply d-flex class only when its shown and also hide this div when the parameter is false
Also add justify-content: center CSS to the wrapper of all the 5 divs
See the updated codepen

new Vue({
  el: '#app',
  data: () => ({
    lorem: `Lorem ipsum dolor sit amet, mel at clita quando. Te sit oratio vituperatoribus, nam ad ipsum posidonium mediocritatem, explicari dissentiunt cu mea. Repudiare disputationi vim in, mollis iriure nec cu, alienum argumentum ius ad. Pri eu justo aeque torquatos.`,
    show1: true,
    show2: true,
    show3: true,
    show4: true,
    show5: true,
    expand1: true

  }),
  methods: {
    hideothers() {
      this.show2 = !this.show2,
        this.show3 = !this.show3,
        this.show4 = !this.show4,
        this.show5 = !this.show5,
        this.expand1 = !this.expand1
    }
  }
})
.custom-class {
  justify-content: center;
}

<link rel="stylesheet" href="https://firstname.lastname@example.com/dist/vuetify.min.css">

  <v-app id="inspire">
    <v-container fluid grid-list-sm>
      <v-layout row wrap :class="{ 'custom-class': !show2 }">

        <v-flex d-flex xs12 sm4 child-flex v-show="show1">
          <v-card color="orange lighten-2" tile flat >
            <v-card-text>Card 1</v-card-text>
             <v-btn flat  @click="hideothers()">Expand</v-btn>
             <v-card-text>
                  <v-expand-transition>

This is a short paragraph

                  </v-expand-transition>
                  <v-expand-transition>

A looooong

paragraph

                  </v-expand-transition>
                </v-card-text>
          </v-card>
        </v-flex>

         <v-flex xs12 sm4 child-flex v-show="show2" :class="{ 'd-flex': show2 }">
           <v-fade-transition>

          <v-card color="orange lighten-2" tile flat  v-show="show2">
            <v-card-text>
            <v-layout row wrap>
              <v-flex sm6>
                 Card1
              </v-flex>
              <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
            </v-layout>
            </v-card-text>
          </v-card>
             </v-fade-transition>
        </v-flex>

        <v-flex xs12 sm4 v-show="show3" :class="{ 'd-flex': show3 }">
          <v-card color="red lighten-2" dark tile flat  v-show="show3">
            <v-card-text>{{ lorem.slice(0, 100) }}</v-card-text>
          </v-card>
        </v-flex>

         <v-flex xs12 sm4 child-flex v-show="show4" :class="{ 'd-flex': show4 }">
          <v-card color="purple lighten-1" tile flat v-show="show4">
            <v-card-text>{{lorem}}</v-card-text>
          </v-card>
        </v-flex>
        <v-flex xs12 sm4 child-flex v-show="show5"  :class="{ 'd-flex': show2 }">
          <v-card color="green lighten-2" tile flat>
            <v-card-text>{{lorem}}</v-card-text>
          </v-card>
        </v-flex>

      </v-layout>
    </v-container>
  </v-app>

Comment: Perfect, exactly what I tried to do. I wonder if the transition can be also applied to the justify-content
Answer: Try ou this :

  <v-app id="inspire">
    <v-container fluid grid-list-sm>
      <v-layout row wrap :justify-center="!expand1">

        <v-flex d-flex xs12 sm4 child-flex>
          <v-card color="orange lighten-2" tile flat v-show="show1">
            <v-card-text>Card 1</v-card-text>
             <v-btn flat  @click="hideothers()">Expand</v-btn>
             <v-card-text>
                  <v-expand-transition>

This is a short paragraph

                  </v-expand-transition>
                  <v-expand-transition>

A looooong

paragraph

                  </v-expand-transition>
                </v-card-text>
          </v-card>
        </v-flex>

         <v-flex d-flex xs12 sm4 child-flex v-if="show2">
           <v-fade-transition>

          <v-card color="orange lighten-2" tile flat>
            <v-card-text>
            <v-layout row wrap>
              <v-flex sm6>
                 Card1
              </v-flex>
              <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
               <v-flex sm6>
                 Card1
              </v-flex>
            </v-layout>
            </v-card-text>
          </v-card>
             </v-fade-transition>
        </v-flex>

        <v-flex d-flex xs12 sm4 v-if="show3">
          <v-card color="red lighten-2" dark tile flat>
            <v-card-text>{{ lorem.slice(0, 100) }}</v-card-text>
          </v-card>
        </v-flex>

         <v-flex d-flex xs12 sm4 child-flex v-if="show4">
          <v-card color="purple lighten-1" tile flat>
            <v-card-text>{{lorem}}</v-card-text>
          </v-card>
        </v-flex>
        <v-flex xs12 sm4 child-flex v-show="show5">
          <v-card color="green lighten-2" tile flat>
            <v-card-text>{{lorem}}</v-card-text>
          </v-card>
        </v-flex>

      </v-layout>
    </v-container>
  </v-app>

Answer: You can bind the required widths md4 and md12 to whether it is expanded or not.
Like this: <v-flex d-flex xs12 :sm4="expand1" :sm12="!expand1" child-flex>
see the pen
Comment: Well the thing is that it will take whole width of the container and that is not what I want


Multiplication table with rows and columns

Question: How can I make multiplication table to look like this: http://i.imgur.com/rR6JSua.png ?
With my code it only has one column.
<code>#include<stdio.h>

int main()
{
    int i, j;

    for(i = 1;i <= 9;i++)
    {
        for(j = 1;j <= 9;j++)
        {
            printf("%d * %d  = %d\n",i , j,i*j);
        }
        printf("%d * %d = %d\n",i , 10,i*10);
        printf("\n");
    }

    return 0;
}
</code>
Comment: The image link is broken, please update with a new image.
Answer: Try This:
<code>#include<stdio.h>

int main()
{
    int i, j;

for(i = 1;i <= 9;i+=3)
{

  for(j = 1;j <= 10;j++)
  {

       printf("%2d * %2d = %2d ",i , j,(i)*j);
       printf("%2d * %2d = %2d ",i+1 , j,(i+1)*j);
       printf("%2d * %2d = %d\n",i+2, j,(i+2)*j);
  }
  printf("\n");
}
return 0;
</code>
}
Comment: @AndriusK I might be too picky, and maybe for you it is perfect, but your teacher might have different opinion. Look at alignment of columns. You were given that exercise for a reason. Match it to look **exactly** the same(every space, every character, then it will be perfect).
Answer: You have to print your table line by line, not column by columne.
So you have to
<code>printf("%d*%d=%d %d*%d=%d %d*%d=%d\n",...);
</code>
Rest figure out yourself, if you have problems, write and I'll help you further.
Comment: What's the point in giving him/her complete code to something that's definetely for educational purpose( homework, I mean).
Answer: This will work perfectly:
<code>#include<stdio.h>

int main(){
int i, j=1;

while(j<=9){
      for(i=1;i<=9;i++){
          printf("%d * %d = %3d    ",i , j,i*j);
      }
      printf("\n");
      j++;
}

return 0;
}
</code>


Betting game with numbers

Question: Someone is challenged to play the following game: there are 36 marbles in an urn. 21 of them are red, 9 are blue and 6 are green. Each red is worth 0 rupees, each blue 100 rupees and each green 1000 rupees. By betting 1000 rupees only once, you must pick as many marbles as you want (obviously without seeing its color), one by one (you draw each marble, look at its color and either stop or continue) and without replacement and you can stop at any time, and you earn the product of the values of the marbles you have picked so far.
Assuming that the player plays optimally, what is the average percentage of the average percentage of profit for the game?
My understanding is that we must calculate the probability (not) to draw a 0 in a series of consecutive draws from 1 to 36.
For the 1st draw, the probability to get a 0 is $P_1 = \frac {21}{36}$ and the game ends, so with probability $P'_1 = \frac {15}{36}$ the player continues ("optimal" playing refers to this, otherwise if he continues, he will get 0 anyway).
Up to now, the player has earned 100 rupees with probability $Pw'_1 = \frac {15*9}{36*15}$ and 1000 rupees with probability $Pww'_1 = \frac {15*6}{36*15}$.
For the 2nd draw, the probability not to get a 0 is $P'_2 = \frac {14}{35}$ and so on.
The player will earn again the product of either 100 or 1000 of the first earning, with probability equal to the product of $P'_2$ by $\frac {8}{14}$ or $\frac {5}{14}$.
Can you please help me continue? It is getting really confusing from this point forward!
Thank you very much!
Comment: This question requires some clarification. The answer posted seems correct to me, and it's not clear whether you disagree with it because it misinterprets the question or because you don't understand it. To me, "you can stop at any time, and you earn the product of the values of the marbles you have picked so far" sounds as if you only get a payout once, when you stop. But later you write "The player will earn again the product of either $100$ or $1000$ of the first earning". Does that mean that you get a payout after every draw, even if you then continue drawing?
Answer: As long as there is at least one blue or green marble in the urn, it makes sense to keep playing, since you have a better than 1 in 36 chance of multiplying your winnings by at least 100. So the optimal strategy is to draw 15 marbles. Your expected earnings will be the product of: (1) the probability that every one of the first 15 marbles drawn is non-red, times (2) the number of rupees you will earn if you draw all 15 non-red marbles and no red marbles. Can you compute these two quantities? The result is kind of funny, in that you wind up with a minuscule probability of winning an astronomically large amount of money.
Edit: There are
$$
{36\choose 15}=\frac{36!}{15!\, 21!}=5567902560
$$
possible sets of 15 marbles you could draw. Exactly one of them has no red marbles, so using the optimal strategy, the probability you win money is $1/5567902560$. In the event you draw 15 non-red marbles, the amount of money you win is $100^9\cdot 1000^6 = 10^{36}$. Your expected winnings are then
$$
\frac{10^{36}}{5567902560}\approx 1.796\cdot 10^{26},
$$
and your expected percent profit is
$$
\frac{\frac{10^{36}}{5567902560}-1000}{1000}\cdot 100\%\approx 17960084416419816082413526\%.
$$
Comment: Julian, thank you for your answer. Just to clarify: You don't draw all the marbles at once, but one by one: You see them first and then decide if you will continue and so on. Obviously if you draw a zero, you must stop, because whatever you draw afterwards, you will earn the product, which will be zero.
Comment: This is not optimal playing. According to the OP, you must play optimally. Plus, this is an one-off case. You must get the average earning of all possible cases.
Comment: Well, once you draw a red marble, it doesn't matter what you do, so you don't *have* to stop. My argument is that whatever happens on the draws, it is optimal always to continue drawing until you have drawn 15 marbles.
Comment: I did some calculations with Excel and got an average of ~22% - does this seem reasonable?
Comment: I got an expected profit much larger than that
Comment: Can you please share some calculations? I am not sure my method is correct. Thank you.
Comment: To me, optimal playing means you continue drawing as long as you don't get a red and until you get a green. Of course, after this, you can continue playing, to maximise your earnings. In all other cases, you are losing money. Therefore, this is what you need to calculate.
Comment: Hmm, I do not understand the comments here. If there is objection to continuing to draw after a red marble, the player could continue to draw until you getting a red or reaching 15 marbles, which has the same payout as always drawing 15 marbles. I interpret "optimal strategy" to mean one that maximizes expected payout. Using the strategy I propose, the player earns 0 rupees with probability $5567902559/5567902560$, and earns $10^{36}$ rupees with probability $1/5567902560$. Did I make a mistake in this calculation? Or is there a strategy with higher expected payout?
Comment: The question is not about the optimal strategy or the highest payout, but about the average payout, based on all possible outcomes. Maybe I haven't explained it correctly. If you get a red on any draw, there is no point to continue. Whatever you get after this point, it doesn't matter, because you will get 0 anyway! So let's say, for example, you want to spend 100.000 rp (in total): You start with your first "game": You bet 1000 rp, you draw a red, and you stop. Then you bet another 1000, you draw a blue, then a green and you continue. To secure your earning so far, you stop, and start a new.
Comment: I think I am still missing something. The average payout depends on what strategy you use. The strategy I propose have an average payout of $\approx 1.8\cdot 10^{26}$, and I am claiming that no strategy does better.
Comment: Are you saying you play multiple games without replacing the marbles between games?

Betting game with numbers


Custom URI regular expression

Question: I would like to restrict access to my site using a custom URI regular expression.
I would like to allow access for such URIs:
https://example.com/item/page/2/?wpv_view_count=258
https://example.com/item/page/3/?wpv_view_count=258

and restrict content for such URIs:
https://example.com/item/snv00001-indice-di-documenti/
https://example.com/item/sa00068-libro/
https://example.com/item/aud00068-audio/

I need to provide the restrict content URI regex
Comment: I added more examples. I need to restrict for /item/snv etc..not for pages
Comment: I am using memberpress on wordpress to restrict content to subscribers. Some pages ex: /snv00001-indice-di-documenti/ should not be available if not subscribed
Answer: Based on the info in the question you want to match everything except requests which start with /item/page/ so:
/item/(?!page/).+

That is:
/item/  # literal string
(?!     # Begin negative lookahead
  page/ # literal string
)       # End negative lookahead
.+      # 1 or more characters

A negative lookahead is a zero-length match - so the next bit of the regex .+ continues right after /item/.
Here's a demonstration: https://regex101.com/r/8T2ytg/1

Custom URI regular expression


Why are some Bestiary entries yellow?

Question: See this screenshot of the Bestiary:

Why are Skeleton, Lionhead, Milk Elemental and Dragon Shrimp written in yellow font? There are more entries like, but I think they are less than 10% of all.
Answer: Yellow entry enemies are the ones you need to kill to unlock new characters or achievements.
Also confirmed in this Steam thread by one of the developers who confirmed a similar answer.
Comment: Oh, I see, looks like they are also stay yellow even when you completed related achievements

Why are some Bestiary entries yellow?


Downloads from Chrome or any shortcut from Places menu opens with Evince

Question: When I try to open a file that has been downloaded from Chrome, or any folder in the menu bar "Places", evince opens with an error.
The error does not occur when I open a file with a particular program from the command line (ie: gnumeric myfile.xls) or if I open and navigate from Places>Computer, although it does occur with Places>Home Folder, Places>Desktop, etc.
For example, this is the result of clicking on Places>Desktop:

I have tried the following:

Checking the settings for a given filetype to see if preferred
application is 'evince', but it is not. I have followed this
guide.
Checking the settings on Chrome, but I can not find anything related to it.
removing evince: received 'Failed to execute default File Manager'...
Comment: Might be an ugly hack, but try uninstalling evince.
Comment: @Capt.Nemo it might have been an ugly hack that didn't work, but it pointed me to the answer posted below. Thanks. I'll give the bounty to you if you write it up.
Answer: Need to change your default file manager. Either follow the steps at help.ubuntu.com, or simply type
 exo-preferred-applications

at the command line, select the 'utilities tab' and switch to your favorite file manager (e.g. Nautilus, Thunar).
Answer: Try uninstalling evince
sudo apt-get remove evince

With evince no longer on the machine, check what response chrome gives to opening files, and it might point you in the right direction.


Change in textfield and "save before quit"

Question: i'm trying to add a "save before quit" alert on my app to avoid data loss if the user want to go back without saving on the previous view.
I know there's a lot of method, but why this doesn't seems to work?
1) declare this two variables:
<code>@property (nonatomic, assign) BOOL isChanged;
</code>
2)
<code>@property (nonatomic, assign) NSString *modifiedText;
</code>
3) set to false "isChanged" at the init
4)
<code>  (void)textFieldDidBeginEditing:(UITextField *)textField {
  self.modifiedText = textField.text;
</code>
5)
<code> - (void)textFieldDidEndEditing:(UITextField *)textField {

 if(![self.modifiedText isEqualToString:textField.text]){
        self.isChanged = YES;
 }
 else{
        self.isChanged = NO;
  }
</code>
But i've a exc_bad_access on modified text on 5. Why?
Answer: Try to declare modifiedText property this way:
<code>@property (copy) NSString *modifiedText;
</code>
See this question for more information.
Answer: Try this
<code>@property (nonatomic,retain) NSString *modifiedText;
</code>
or
<code>@property (nonatomic,copy) NSString *modifiedText;
</code>
Instead of assign.
Answer: Try this,
Change your property
<code>@property (nonatomic, assign) NSString *modifiedText;
</code>
to
<code>@property (nonatomic, strong) NSString *modifiedText;
</code>
more details


Why IE document mode is Edge in one environment and IE5 in another

Question: I have a web page that renders correctly when document mode is Edge, but have some issues when document mode is IE5. This page is part of a web application that is deployed on a tomcat server (if that is a relevant info).
When I test this on my development environment the doc mode is Edge. I can see this when I click on Emulation Tab in F12 Developer Tools. See Screen Capture. This is when my web application is deployed on my local tomcat server. But when I deploy the same web application on another test environment with same version of tomcat server and access the page doc mode is IE5. Please note that I am using the same browser i.e IE11 to access page on both environments.
Now I understand that the way to force browser to load web page in Edge mode is to add following
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

I have not included the above in my html. But why does my browser load the page from my dev env in Edge mode while from the test env in IE5 mode. What is the difference? The code is same, tomcat server is same. How is browser interpreting diff env differently.
Answer: Internet Explorer defaults to showing intranet documents in "compatibility" (read: broken) mode, and has various lists of sites that you can add to to say "no, no, work correctly with this site/URL/etc. please." It also has a "service" it will use if you let it that tells it which intranet sites to use in "compatibility" mode.
It would appear that you've at some point told IE not to hobble itself in your dev environment, but not told it not to hobble itself in your test environment.
Add the meta tag you've quoted to the top of the head of the document to make this not an environment-specific thing.
Comment: Thank you. This makes sense.


How can I catch a keybind like F6 no matter what is in focus with c++?

Question: Preferably with <windows.h>, but if it's not possible I am open to other solutions.
I've seen RegisterHotKey(), but it requires Ctrl, Shift, Alt, or Win to be pressed.
I would also like to be able to know when the key has been let go (is not being pressed anymore).
Comment: @DaveS the `SetWindowsHookEx()` low-level hooks (`WH_MOUSE_LL` and `WH_KEYBOARD_LL`) do not require a DLL, as they are not injected into other processes, they always run in the thread that installs them.
Comment: To snoop on keyboard messages across all processes you need a low-level keyboard hook in a DLL.  Your app might also need to run with admin rights to see presses in other apps running as admin.
Comment: For you application or the whole system ? Have you considered an accelerator table (if for your application only) ?
Comment: RegisterHotKey doesn't require a modifier key, you can pass 0 for the `fsModifiers` arg.
Comment: Interpret them in *LowLevelKeyboardProc* hook procedure, for example https://stackoverflow.com/questions/75061028/windows-low-level-keyboard-hook-allow-win-h-not-other-win-hotkeys.
Answer: To monitor the keyboard globally, you can either:

use a WH_KEYBOARD_LL hook via SetWindowsHookEx().

use the Raw Input API to receive WM_INPUT messages.
Comment: @DaveS the `LL` hooks can be used only globally, yes. But [they don't require a DLL](https://stackoverflow.com/a/24276756/65863), unlike the other global hooks, which do.
Comment: @DaveS In fairness, this can be inferred from the [documentation](https://learn.microsoft.com/en-us/windows/win32/winmsg/lowlevelkeyboardproc): *"This hook is called in the context of the thread that installed it."* This is also why low-level hooks are extremely disruptive. For every input event, the system walks the entire hook chain, switching to the thread that installed the hook, runs the callback, and moves to the next callback only after the previous has returned. Unless you must *filter* input, use Raw Input. It's far less intrusive.
Comment: Regarding the need for a DLL, Doesn't the table at the bottom of your link say "WH_KEYBOARD_LL Global only", "WH_MOUSE_LL Global only" or am I misreading what that means?
Comment: Thanks, I trusted the MS docs too much.


Ati Radeon Xpress 1100/1150 Driver? Which one and how to install? Ubuntu 14.04

Question: h@h:~$ lspci -nn | grep VGA
01:05.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] RS482/RS485 [Radeon Xpress 1100/1150] [1002:5974]

Thats my Graphics card. And all I need is a stable driver for this. Im running ubuntu 14.04, I tried installing fglrx but it didn't work I could not log in to ubuntu anymore.
I need to run 2 displays that are both 24", side by side so I can get larger workspace and run windows on vmware on other screen and main os, ubuntu on other. I hate windows but i need it too much to throw it away.
I just need someone to tell me how to install good graphics card. It can be fglrx but how do I avoid the login bug in that?
h@h:~$ dpkg -l | grep xserver-xorg-core

ii  xserver-xorg-core-lts-utopic                          2:1.16.0-1ubuntu1.2~trusty2                         amd64        Xorg X server - core server
Comment: Please [edit] your question and add output of `dpkg -l | grep xserver-xorg-core` terminal command there.
Comment: And what is your "login bug"?
Comment: Login bug is that I cant log in normally. I had to delete fglrx with ctrl+alt+f1
Answer: There is no proprietary standalone driver for this video adapter in linux.
Open source driver is already installed.
The only thing you can do is to upgrade graphical stack for the latest available version for Ubuntu 14.04. In your case you have it already.
You can upgrade to 3.19 kernel. It has a built in radeon module, which may be better. It can be done by
sudo apt-get install linux-generic-lts-vivid

New graphical stack must appear soon too in repositories.
Comment: I added it. How do I do that?
Comment: You have the latest possible graphical stack. But you can upgrade kernel with a newer `radeon` driver. I will add to the answer.
Comment: Thanks, it works faster now. But I still cant get my displays side by side. I get this error when I try to do it: Requested size (3840, 1080) exceeds 3D hardware limit (2048, 2048).
You must either rearrange the displays so that they fit within a (2048, 2048) square.   You know how to bypass this error?
Comment: This old adapter may not have enough RAM to support two big displays. Or other hardware limitations.


Is there a better way to write this repetitive event-declaration code in C# when implementing an interface explicitly?

Question: I have a lot of code like the following, where I explicitly implement some events required by an interface.
public class IMicrowaveNotifier {
  event EventHandler<EventArgs> DoorClosed;
  event EventHandler<EventArgs> LightbulbOn;
  // ...
}

public class Microwave : IMicrowaveNotifier {
  private EventHandler<EventArgs> _doorClosed;
  event EventHandler<EventArgs> IMicrowaveNotifier.DoorClosed {
    add { lock (this) _doorClosed += value; }
    remove { lock (this) _doorClosed -= value; }
  }

  private EventHandler<EventArgs> _lightbulbOn;
  event EventHandler<EventArgs> IMicrowaveNotifier.LightbulbOn {
    add { lock (this) _lightbulbOn += value; }
    remove { lock (this) _lightbulbOn -= value; }
  }

  // ...
}

You can see that much of this is boilerplate. In Ruby I'd be able to do something like this:
class Microwave
  has_events :door_closed, :lightbulb_on, ...
end

Is there a similar shorter way of removing this boilerplate in C#?

Update: I left a very important part out of my example: namely, the events getting implemented are part of an interface, and I want to implement it explicitly. Sorry for not mentioning this earlier!
Comment: Offtopic, but generally using lock(this) is bad. Refer the remarks here for reference: http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
Comment: @dcp - While I agree that `lock(this)` is a bad practice, it interesting to note that the C# compiler emits this very instruction for field-like events in versions 1, 2, and 3.
Answer: Try this:
public class Microwave {
    public event EventHandler<EventArgs> DoorClosed;
    public event EventHandler<EventArgs> LightbulbOn;
}

This code leverages C#'s field-like event syntax:

When compiling a field-like event, the
  compiler automatically creates storage
  to hold the delegate, and creates
  accessors for the event that add or
  remove event handlers to the delegate
  field.

In C# 1, 2, and 3 this code will compile down to just what you have above.  In C# 4 you will get functionally equivalent code that doesn't use explicit locks.  Either way you can use this shortcut without changing the consumers of this type.
Update:  Unfortunately, the C# compiler does not allow you to use field-like events for explicit interface implementation.  If you try you will get this compilation error:

An explicit interface implementation of an event must use event accessor syntax

Update: It's too bad that an explicit interface implementation requires the use of event accessor syntax.  It would be kind of cool if C# added the ability to create automatically implemented field-like events like this:
event EventHandler<EventArgs> IAppliance.DoorClosed { add; remove; }

But this syntax is already wordier than the existing field-like event syntax and would only be applicable in cases where an interface member was being explicitly implemented.  The best thing I think would be if the compiler would simply allow us to do this:
event EventHandler<EventArgs> IAppliance.DoorClosed;

Comment: @Andrew: Very sorry, but I left an important piece of the puzzle out of my question. Specifically, I'm using explicit interface implementation for the events. This seems to require using `add`/`remove` directly. I made the update above.
Comment: @Andrew: Thanks for the update. That's pretty much the same conclusion I reached. Bummer! Is there any way that extension methods would help here?
Comment: So it seems the answer to your question is no: C# will not allow you to avoid the repetition.
Comment: @Damien - Sorry dude!  I think your only option is to manually create the backing fields and the `add` and `remove` accessors. It's too bad really - perhaps C# 5 will give us something like this:  `event EventHandler IAppliance.DoorClosed { add; remove; }`
Comment: A very strange restriction, IMO, as you can implement properties in interfaces by meant of automatic properties. I'd say open a Connect suggestion for this.
Answer: I am not sure what Lock does as I am kind of new, but you can connect all of the controls or whatever is calling those events to only one event. In that event just do a if statement to check who is sending it.
It would look much neater I would think, but still require a some amount of work I guess.
Comment: His question was poorly titled. His issue is with the verbosity of the code, not the events firing frequently. FWIW, I had expected to see a question to which this would have been an answer.
Comment: @Adam, @Dinoo: I've edited the title. Hopefully this is less confusing now. Thanks for the heads up.
Answer: Write a code snippet for it and use a shortcut.  Just like when you use if, for, foreach{tab}{tab}.
Answer: Code snippets as suggested by gbogumil will save some time. Alternately, if there's a specific interface you find yourself implementing regularly that requires this, is it possible for you to create an abstract base class?


Common terminal question on old furnace and air conditioner with new smart thermostat

Question: Trying to solve an odd problem with my T5 Lyric smart thermostat and an old furnace/AC.
I'll try and be concise.  The model of furnace is: Goodman, GMP075-4 Rev B
Details, and photos below for help:

Wiring from thermostat has 5 wires, normal.  The blue wire was not used, was tucked behind the thermostat.
The blue wire up at the furnace was not connected to anything.
The furnace is quite old, and formally only has a 3 wires on the control board: W, G, and R.
There is a blue wire that runs to the AC wiring, very likely a common for the AC (I think it's a common, insight would be good here.)
There is a transformer with 24 V lines coming off.

To try and get things running, I wire nutted the blue line from the thermostat wiring into the Blue line with the AC.  This got the thermostat running, and the system ran the heat just fine, but the AC would not power up at all, so I'm not sure what's happening.
I tried to put the blue line from the thermostat onto a grounded screw on the furnace that has a s, but that didn't do anything.
I tried to connect a separate 24V power source to the thermostat (kept original wiring at the furnace), and it got the system running with functional heat, but AC would not stay on.  Honeywell indicated a separate 24 V power source can't be used for the AC.
So... I'm stuck. I will likely try the Honeywell C-adapter: https://www.amazon.com/dp/B07VMV2BJ7?psc=1&ref=ppx_yo2ov_dt_b_product_details, but I'm afraid this won't work either.
It should seem that I should be able to find a common without the C-adapter, but I figured I'd ask y'all!  Just use Honeywell C-adapter?  If so, I'd still need to find a true common I think?
Pics below for what I got for wiring, etc.  Any thoughts/help would be appreciated!
https://photos.app.goo.gl/niT63t326s1betg76
https://photos.app.goo.gl/jgsAzZHgPNYHFByS7
https://photos.app.goo.gl/2exQXjJfGX8pu1jD8
https://photos.app.goo.gl/4LZAWaq78oGpBMto7
Answer: That light blue wire from the furnace is your C wire connection
Simply connect the blue wire from your thermostat cable in with the light blue wire from the furnace and the wire going to it from the condensing unit cable.    We know this is C because in order for your air conditioner to work, the 24V from R that your thermostat puts on Y needs to have a return path from going off to energize the compressor contactor coil, and that means the wire in the condensing unit cable that is not connected to Y must be connected to C.
Comment: That was the first thing I tried, but the AC would not turn on.  The thermostat turned on, it ran the heat just fine, but the AC would not kick on.
Comment: @thegreataus it sounds like you removed the C wire to the condensing unit from the splice when you made the connection -- all three C wires need to be in that splice for everything to work the way you want


Mysql update from a join query

Question: I have a table user_settings which references the user table to save some settings. But I decided to use the settings in a column in the user table.. All good, but now all my settings are in a separate table, and I'm trying to find a query to "import" the user_settings fields into the "setting" column in the user table.
Something like this:
UPDATE USER
SET setting=settings.value
JOIN USER_SETTINGS
  ON USER_SETTINGS.USER_ID = USER.ID

Having a hard time figuring this out, could someone give me a hand?
Comment: Provide sample input data and desired results.  "Some settings" suggests that your code is not representative, because it only sets one value.
Answer: You're almost there, you just have your join and set clauses in the wrong order:
UPDATE USER
JOIN   USER_SETTINGS
ON     USER_SETTINGS.USER_ID = USER.ID
SET    setting=settings.value

Mysql update from a join query


Php send mail with gmail and SPF record handling

Question: I use the Swiftmailer lib to send mail in php, such as:
$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
->setAuthMode('login')
->setUsername('firstname.lastname@example.com')
->setPassword('password');

$mailer = Swift_Mailer::newInstance($transporter);

I use Gmail Workplace and am trying to understand and setup SPF at my webb host (not Google). Should I setup a gmail SPF or an SPF for my own IP adress to avoid having mails sent via php on my server, but with gmail SMTP, marked as spam?
Answer: You're already authenticating with credentials against smtp.gmail.com, so your own IP address is irrelevant for SPF configuration. SPF is checked by receiving servers, where the IP address of the connecting server (Google) is checked against the SPF list in the domain found in the Return-Path header.
Google is then relaying your message to it's destination recipient(s) on your behalf. Thus Google's IP should be in the SPF record for the domain you use in the Return-Path header (a.k.a. bounce address or smtp.mailfrom).
So, to answer your question: For the domain you use to send email from (as the Return-Path address), you should include the gmail servers as authorized hosts. Assuming you don't use any other services, that SPF record would look like:
"v=spf1 include:_spf.google.com ~all", as described in this Google support article.
And as per Jake's comment, indeed you should consider implementing DKIM and DMARC as well, because relying on SPF alone for protection against spoofing is not sufficient and is not resilient against email forwarding. The same documentation, a few levels up, lists all required actions to accomplish that.
Comment: In addition to what Reintro said, you will also want to setup DKIM and DMARC records to complete the set. This will insure that your emails have the best chance of being delivered.


how to set the index as character for pandas

Question: I am trying to create a pandas df like this post.

df = pd.DataFrame(np.arange(9).reshape(3,3) , columns=list('123'))
df

this piece of code gives

describe() gives

is there is way to set the name of each row (i.e. the index) in df as 'A', 'B', 'C' instead of '0', '1', '2' ?
Answer: Use df.index:
df.index=['A', 'B', 'C']

print(df)
   1  2  3
A  0  1  2
B  3  4  5
C  6  7  8

A more scalable and general solution would be using list-comprehension
df.index = [chr(ord('a') + x).upper() for x in df.index]

print(df)
   1  2  3
A  0  1  2
B  3  4  5
C  6  7  8

Answer: Add index parameter in DataFrame constructor:
df = pd.DataFrame(np.arange(9).reshape(3,3) ,
                  index=list('ABC'),
                  columns=list('123'))
print (df)
   1  2  3
A  0  1  2
B  3  4  5
C  6  7  8


Deploying a cluster of containers in Azure

Question: I have a Docker application that works fine in my laptop on Windows using compose and starting multiple instances of a container as a Dask cluster.
The name of the service is "worker" and I start two container instances like so:
docker compose up --scale worker=2

I deployed the image on Azure and when I run docker compose (using the same command I used in Windows) only one container is started.
How to deploy a cluster of containers in Azure? Can I use docker compose or I need to have a different approach, such as deploying with templates or Kubernetes?
This is the docker-compose.yml file:
version: "3.0"
services:

  web:
    image: sofacr.azurecr.io/pablo:job2_v1
    volumes:
      - daskvol:/code/defaults_prediction
    ports:
      - "5000:5000"
    environment:
      - SCHEDULER_ADDRESS=scheduler
      - SCHEDULER_PORT=8786
    working_dir: /code
    entrypoint:
      - /opt/conda/bin/waitress-serve
    command:
      - --port=5000
      - defaults_prediction:app

  scheduler:
    image: sofacr.azurecr.io/pablo:job2_v1
    ports:
      - "8787:8787"
    entrypoint:
      - /opt/conda/bin/dask-scheduler

  worker:
    image: sofacr.azurecr.io/pablo:job2_v1
    depends_on:
      - scheduler
    environment:
      - PYTHONPATH=/code
      - SCHEDULER_ADDRESS=scheduler
      - SCHEDULER_PORT=8786
    volumes:
      - daskvol:/code/defaults_prediction
      - daskdatavol:/data
      - daskmodelvol:/model
    entrypoint:
      - /opt/conda/bin/dask-worker
    command:
      - scheduler:8786

volumes:
  daskvol:
    driver: azure_file
    driver_opts:
     share_name: daskvol-0003
     storage_account_name: sofstoraccount
  daskdatavol:
    driver: azure_file
    driver_opts:
     share_name: daskdatavol-0003
     storage_account_name: sofstoraccount
  daskmodelvol:
    driver: azure_file
    driver_opts:
     share_name: daskmodelvol-0003
     storage_account_name: sofstoraccount

Comment: What specific azure service are you using? Does docker report any errors?
Comment: I'm using the container registry and instances, deploy with `docker compose up --scale worker=2` connected to the Azure context from Windows. There are no errors, a single container is deployed and it works fine
Comment: Azure Container instances with the docker CLI, as documented at https://learn.microsoft.com/en-ca/azure/container-instances/quickstart-docker-cli ?
Comment: [This is the tutorial I followed](https://learn.microsoft.com/en-us/azure/container-instances/tutorial-docker-compose)
Comment: Any update on this question? Does it solve your problem?
Answer: What you need here is Azure Kubernetes Service or Azure Webapps for Containers. Both will take care of taking Docker images from ACR and distributing then across a fleet of machines.
Here is a decision tree to choose your compute service
Container Instances - small, fast, serverless container hosting service - usually nice for small container deployments, I tend to use it to spawn adhoc background jobs
AKS - large scale container deployment, big part here is the multi-container orchestration platform . Have a look at this example
Answer: I am also new to docker . But as far I read to orchestrate the containers or to scaleup the container generally use
the docker swarm or kubernetes. In Azure kuberenetes cluster is AKS.
docker compose up --scale worker=2

I have come across this issue of scaling container in this link
https://github.com/docker/compose/issues/3722
How to simply scale a docker-compose service and pass the index and count to each?
hope this might help.
Answer: Now ACI supports deploying from the docker-compose.yaml file, but it doesn't support scaling up to multiple replicas for the same container. Because ACI does not support port mapping and one port can only expose once and for one container. So you only can create multiple containers in a container group through the docker-compose. yaml file and each container have one replica.
If you want to have multiple replicas of one container, then I recommend you use the AKS, it's more suitable for your purpose.
Comment: The workers are not set to expose ports, though. Are you saying this restriction applies because you *might* want to expose ports?
Comment: @mdurant Yes, it's a possible reason. But I'm not pretty sure.


How to determine encoding format of string and then decode it

Question: I have captured request content of a mobile app (iphone) through a proxy (Charles Proxy), but the content seems to be encoded which I want to decode into human-readable format. As the source of the encoding format is not known, I cannot decode it, I have tried several online tools with different source formats but none of it decode it properly. How to decode such content properly?

pv8WkNKPolGj6EgiYKNXzlGAOjGku5ewenklAlyQ58wpWcLBH7y4S0ZZ12JODvWSLpvoJbeffKgDxvaTMTt17qLUNKsiTroaldStWO5n+H1BdI+IXLFusgipOtpUUvnvbA52x0Gwi349bfXNCD9EamQBEPD8J+zreVtYwvgL9b7ohgvnoq2WXpOeHs9hTJnWEwAiLzPTocVDzr3kzLsMsB6N10X+pnJ/QODY3RDklqQeb5o6vzvTapgs5G/R2ZjsvzBTJ/u+DuLxulVfNUAKXGjh4CVAWjWzsymuxo1CaI7s3nPW17Kx9BNYxw37r4TKAqTMA+A0uP+NPi17KsC9ag==

UPDATE:
Comment: How did you capture the content? Was it HTTP content? If so, you should know what the source is. If you are sniffing on encrypted data, then you may have to spend more years than you'll be alive to decrypt it and it is not a simple case of decoding it.
Comment: I mentioned above that I have captured it with an http proxy (Charles Proxy) which is running on my computer whereas app is running on my mobile, both computer and mobile are in the same WiFi network, I just added a screenshot of content captured in proxy above,  it is a REST call and the content is a JSON payload. It's not an encrypted data instead it's an encoded data where request/response content is encoded with some algorithm(base64, utf-8..etc) and being sent over the network instead of a raw content. So, unless I look into the app code or server code,I do not know what algorithm is used
Comment: Is it BASE64? Which BTW it is just an intermediate encoder.
Comment: It seems that the content captured here is SSL encrypted, this app is doing something different before sending payload to the server (programmatically encrypted??), for all other apps (which are also using 128-bit SSL encryption) I am able to capture raw content within my network by trusting and handshaking the proxy's SSL certificates in my mobile device, but only for this app the content is not shown in plain text
Comment: In both screenshots, the HTTP body content has clearly been encoded in base64 (which is very unusual for HTTP/S or REST to do - are you sure it is not your capture tool doing that for display purposes?). In the case of the HTTP response, the body content has been compressed in gzip format before encoded in base64
Comment: No, my capturing tool is not doing anything, I can say this because when I capture the requests for other apps I am able to see the content in normal text, only for this app, it is showing like that. If the content is encoded in base64 as stated by you then I must be able to decode it with some online base64 decoder right? It's not happening, so this is not base64 encoded format for sure, it seems something encrypted by SSL certificate programatically.
Answer: The request/response content is encrypted by java cryptography before sending it in the network using the AES cipher algorithm and cipher transformation is done with AES/CBC/PKCS5Padding. I am able to decrypt it by debugging APK code and finding the secret key used to encrypt the content. It's really another level of encryption before sending it in the network.


Proof that range of projection matrix equals eigenspace corresponding to eigenvalue of 1

Question: Theorem
Let $A$ be an idempotent, diagonalizable, $n \times n$ matrix. Then the range of $A$, $R(A)$, equals $E(A)_{\lambda = 1}$, the eigenspace of A corresponding to the eigenvalue 1.
Attempted proof
Let $v \in R(A)$. Then $Ax = v$ for some vector $x$. Now,
$E(A)_{\lambda = 1}$ = $\{z \mid Az = z\}$, so if we can show that $x = v$, then $Av = v$, so $v \in E(A)_{\lambda = 1}$.
$$
Ax = v \\
AAx = Av \\
Ax = Av \\
Ax - Av = 0 \\
A(x - v) = 0
$$
Since A is diagonalizable, $A \neq 0$, so $x - v = 0$ and hence $x = v$. So $v \in E(A)_{\lambda = 1}$ and hence $R(A) \subseteq E(A)_{\lambda = 1}$
Conversely, let $z \in E(A)_{\lambda = 1}$. Then $Az = z$, so $z \in R(A)$ and hence $E(A)_{\lambda = 1} \subseteq R(A)$.
Thus, $R(A) = E(A)_{\lambda = 1}$.
$\blacksquare$
Source
Anthony, Harvey, Linear Algebra, 2012, Exercise 12.4.
There's a full proof in the back of the book, but it seemed very unintuitive to me, so I'm wondering if my proof above is also correct.
Comment: The zero matrix is diagonalisable, so you can't conclude that $A \neq 0$. Notice that $0$ is in fact an idempotent matrix, it just has a $1$-eigenspace of dimension 0.
Comment: Ah, of course! Is there an easy way to salvage the proof as it stands? Otherwise I'll accept your answer if you submit it as such.
Answer: Let $E:V\to V$ such that $E^2=E$.
If $Ey=y$ then clearly $y\in E(V)$.
If $y\in E(V)$ then $y=Ex$ for some $x$, and so $Ey=EEx=Ex=y$ and $y$ is in the $1$-eigenspace.
(Daigonalisability is free and irrelevant).
Comment: Ah, yes, from $Ax = Av$ I could've just concluded that $v = Av$ and hence $v$ in the 1-eigenspace.


Old computer Intel Sound Card cannot work with Ubuntu

Question: I tried everything.
My sound card is
00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 04)

I tried commands and rebooting and everything, it just DOES NOT WORK.
Just no sound, at all.
What to do?
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.4 LTS
Release:    20.04
Codename:   focal

00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)
00:14.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI (rev 04)
00:16.0 Communication controller: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 (rev 04)
00:19.0 Ethernet controller: Intel Corporation Ethernet Connection I217-V (rev 04)
00:1a.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 (rev 04)
00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 04)

No questions on the forum could answer this, I tried the solutions of downgrading, everything, how do I fix the sound?
Comment: Welcome to AskUbuntu. Unfortunately there is not enough information here to offer any suggestions. Could you [edit] your question to include: (0) the version of Ubuntu you're using (1) the complete Terminal output of `sudo lspci` (2) more details about what you've tried (so that the same suggestions are not made). With this, it *might* be possible for someone to offer an answer
Answer: it might be possible that you need to install pavucontrol and check if thr device is configured properly and detected in pavucontrol.
Run sudo apt install pavucontrol
Then open it and check the output and configuration tab. (I had to reconnect my sound output device to a new jack, you might have to unmute the sound output as well)
Comment: I just did what you said. No sound unfortunately.
Comment: WTF should I do to get sound from this system?!


UserListError.ADVERTISER_NOT_WHITELISTED_FOR_USING_UPLOADED_DATA @ operations

Question: When executing https://github.com/googleads/googleads-php-lib/blob/master/examples/AdWords/v201809/Remarketing/AddCrmBasedUserList.php file which throws UserListError.ADVERTISER_NOT_WHITELISTED_FOR_USING_UPLOADED_DATA @ operations error
Answer: Could you confirm if the account you're trying to use is already
whitelisted? To clarify, you would need to whitelist the account when
creating a CrmBasedUserList through AdWordsUserListService. You may refer
to this blog
https://ads-developers.googleblog.com/2018/11/update-to-customer-match-requirements.html
You can also contact your Google representative and have it whitelisted.


Use string interpolation and custom URL scheme

Question: I'm trying to display a Text with different URLs in swiftUI but face an issue with string interpolation.
I used the instruction here to add a custom URL scheme to my test app and when I use a basic test URL it works:
Text("[\(text)](urlschemetest://action)")
.onOpenURL { link in
   print("LINK: \(link)")
}

When I create the the same with a string interpolation within the URL part though the link doesn't work anymore.
Text("[\(text)](urlschemetest://\(actionVariable))")
.onOpenURL { link in
   print("LINK: \(link)")
}

Is there a way to have string interpolation to work or to populate the URL dynamically from a variable?
I assume I'm missing something simple but could not find anything related to this issue with my searches.
The goal is to use an array of words and connect each to its own URL. I currently use reduce on the array to build the string:
arrayObj.reduce(Text(""), {
    $0 + Text("[\($1.word)](baps://action/\($1.urlAction!)) ") + Text(" ")
} )

Comment: you could try using AttributedString: `Text(try! AttributedString(markdown: "[\(text)](urlschemetest://\(actionVariable))"))`.  See also this link:  https://stackoverflow.com/questions/57744392/how-to-make-hyperlinks-in-swiftui
Answer: Use this example code (using AttributedString or Link) to ...have string interpolation to work or to populate the URL dynamically from a variable..
struct ContentView: View {
    @Environment(\.openURL) var openURL

    let query = "?q=swiftui&atb=v201-4__&hps=1&ia=web"
    let prompt = "Search for SwiftUI"

    var body: some View {
        VStack (spacing: 55) {
            // using AttributedString
            if let txt = try? AttributedString(markdown: "[\(prompt)](https://duckduckgo.com/\(query))") {
                Text(txt)
                    .environment(\.openURL, OpenURLAction { url in
                        print("\n---> Text: \(url)")
                        return .systemAction
                    })
            }
            // alternative, using Link
            if let linkUrl = URL(string: "https://duckduckgo.com/\(query)") {
                Link(prompt, destination: linkUrl)
                    .environment(\.openURL, OpenURLAction { url in
                        print("\n---> Link: \(url)")
                        return .systemAction
                    })
                    .foregroundColor(.red)
            }
        }
    }
}

EDIT-1:
Your question was: Is there a way to have string interpolation to work or to populate the URL dynamically from a variable?, now you are saying Is there a way to have that without a variable?.
What variable are you referring to?
With your .reduce, I suggest you use String, and then after getting the results use the AttributedString, such as:
     let results = arrayObj.reduce("", {
          $0 + "[\($1.word)](baps://action/\($1.urlAction)) " + " "
      } )

     if let txt = try? AttributedString(markdown: results) {
         Text(txt)
     }

Note, do not use forced unwrapping ! in your code, it is a recipe for a crash.
Comment: Thank you for answering. Is there a way to have that without a variable? I have a ForEach loop and use .reduce so I'm not sure it would work or be efficient to use :S
Comment: updated my answer with your new question using the `.reduce` scheme.
Comment: "AttributedString(markdown: results)" works ! Thank you for that. Checking a little further I realised I could call a function of my own too and create a proper AttributedString with all the required properties.


What's the worst space complexity of a loop which create an arrayat each iteration

Question: I am struggling to find a proper definition of worst space complexity whether it is the sum of the total amount of the algorithm used or if it is only the space consumed by the algorithm at a critical time, the worst one.
As an example:
void myFunc(n) {
  for(int j = 0; j < n ; ++j) {
     int* myTab = malloc(n*sizeof(int));
     for(int i = 0; i < n; ++i) {
        myTab[i] = 1;
     }
      free(myTab);
   }
}

For the first definition it is roughly O(N²) and for the second one O(N).
Comment: The same space can be reused. You need to know the inner workings of `malloc()` (and the load on the system, and the day of the week, ...) to be sure ... but I say you can safely assume `O(n)` space.
Answer: It would be O(n). You are explicitly freeing up the memory after the assignment is done. I agree the inner workings of the malloc would be useful but assuming a normal implementation which doesn't use memory enough to change the space complexity ( For tracking O(n) memory allocation it keeps O(n^2) amounts of metadata - just a weird example).
An interesting point, to clear up your idea. If you comment out this free(..) line, then the space complexity would be O(n^2).  This is what is known as memory leakage.


Post-commit hook failed (exit code 255) with no output

Question: So I'm trying to make a pre-commit hook for svn but the error Post-commit hook failed (exit code 255) with no output keeps coming out. I have browse the other question but don't really understand as I am new to svn.
#!/bin/sh
# POST-COMMIT HOOK

REPOS=$1
REV=$2
UUID=`svnlook uuid $REPOS`
URL=http://XXXXXXXXXXX:8080/subversion/${UUID}/notifyCommit?rev=$REV
echo $URL

/usr/bin/curl \
 -v \
 --connect-timeout 5\
 --header "Content-Type:text/plain;charset=UTF-8" \
 --data "`svnlook changed --revision $REV $REPOS`" \
$URL

Comment: Start by specifying the full path to `svnlook` when you execute it. How scripts run in an empty environment, so there's no `$PATH` for it to look in.
Answer: I solved it by chmod my post commit file. Turns out it didn't have permission to execute


Use nmap scan specific ports to see which IP addresses are running any of those

Question: I have a question to write a script using nmap to look at TCP ports across the entire network to identify which IP addresses are running any of those services.
Sorry my english is not good.
Comment: Read `man nmap`. That kind of thing is what `nmap` was designed for. Warning: Depending on what you mean by "across the entire network", you could be on the edge of illegal behaviour. Ensure the the network manager is aware, and approves. A Port Scan is often a precursor to an attack. Don't trigger a response - get approval first.
Comment: Which services are you referring to ?
Comment: it's just a normal scan, because I'm new to nmap and I heard it can do lot of things, so I just want to give it a try. *waltinator
Comment: tcp ports 53 and 123 services =) *George
Answer: What you want to do is this:
nmap -p 53,123 192.168.0.0/24

-p  specifies list of comma-separated ports.
192.168.0.0/24 tells to scan local network in CIDR notation. Please note that if you are scanning a local network, you need to know what type it is; for example /24 means there are 2^(32-24) - 1 = 255 possible host addresses ( and if you exclude  router, broadcast, and network ID there are 3 less addresses ). Use ip addr -o to find on what network you are on.

Of course, you can use other options in combination with this to perform various types of scans.


require_once of certain file works on local windows, not on dev linux machine

Question: I'm trying to integrate Goutte http://github.com/fabpot/Goutte into my existing symfony 1.4 project and am running into a problem.
I have everything working on my local wamp server, here are the two lines in question:
<code>require_once('path_to_goutte.phar');
$client = new Goutte\Client();
</code>
Now to debug I've put a print statement before and after the require_once statement and the second print statement doesn't get fired off. No error logs are generated - the error is silent and very frustrating.
Any ideas as to why this might be happening?
Answer: "No error logs" is something that should be fixed! Check your php configuration (the php;ini file). Is the log_errors setting set to on?
Comment: Thanks for the heads up! It actually wasn't on. I've turned it on and checked out the logs but there is nothing there other than some missing images. Any ideas?
Comment: Check your error_reporting setting is set to -1 . Explanation here : http://fr.php.net/manual/fr/function.error-reporting.php
Comment: I set it, and output the setting right before just to make sure it's -1, and there are still no errors reported in the log for it. If I take out the require_once, the second print will print. This is very bizarre.
Comment: Use the trigger_error() with different levels as second argument and make sure every error message is logged... and check whether your error_log setting, it should tell to which file PHP errors are logged (missing images are perhaps only apache 404 errors, no php involved)
Comment: Hi there, thanks for working with me. I just tested E_USER_NOTICE, E_USER_WARNING, and E_USER_WARNING. Any other ideas? It's very strange that the .phar file would be included on my windows machine but not on my linux and not throw an error. BTW my windows machine is running php 5.3, my linux 5.3.2 - not that it should make a difference though...
Comment: Hi, I tried this piece of code on my server `<?php require_once('nonexistant_file.php');` , and I get a warning and a fatal error. Check you get the same thing in your log file. BTW, you said you tested some levels, but you did not specify the results, are they positive? I mean, do you get error messages in your log file? Also, check you get "Syntax Ok" when running the command `apache2ctl -t`
Comment: Hi Greg, I did see the errors in my log file. I ended up uninstalling apache, php, mysql, memcache, and apc - then reinstalling and rewriting the configuration files - and then cloning everything to my production. That has solved the problem. However, I still don't know why I was getting the error I did. I changed things around a bit with regards to my hosts file and how I'm serving up the content - perhaps that's what did it. Thanks so much for trying to help me though.
Comment: Glad you finally got your problem solved! Please upvote my answer it you found it useful :)


What is the difference between halfdelay() and cbreak() + timeout() when getting input?

Question: I'm writing a typing game with ncurses in C++, and I noticed there are cbreak() and halfdelay() functions to switch modes for text input in ncurses.
I know cbreak() is used to disable line buffering when reading characters, and the difference between cbreak() and halfdelay() is halfdelay() take a parameter to blocking for X tenths.
And I was curious what if I use cbreak() with timeout(), does it works like halfdelay() ?
I made an experiment to see their difference:
Use halfdelay():
#include <ncurses.h>
int main()
{
    initscr();
    halfdelay(10); // blocking for 1s
    getch();
    endwin();
}

Use cbreak() and timeout():
#include <ncurses.h>
int main()
{
    initscr();
    cbreak();
    timeout(1000); // blocking for 1s
    getch();
    endwin();
}

I found both of behavior are waiting for a char and exit the programs immediately until exceed 1s, so I would like to ask if they have difference in ncurses?
Answer: The halfdelay routine is used for half-delay mode. It's very similar to cbreak, but after blocking for tenths tenths of seconds, ERR (Error stream) is returned if nothing  has  been  typed.
You can find more informations about it here : Link


how to add lxc containers to host's DNS so that getaddrinfo() can resolve them?

Question: I'm running LXC containers on Ubuntu 12.04 with a 3.8 kernel.  The containers are on a host-only network, so their addresses are managed by dnsmasq.  Is there a way to configure the host so that getaddrinfo() (on the host) can resolve container names?  (I know there ways to resolve container names from the shell, but I'm specifically looking for something that works with getaddrinfo()).
Answer: The following works on 12.04 with the 3.11 kernel.  On the host, add this to /etc/resolvconf/resolv.conf.d/head:
nameserver 10.0.3.1
and then run this on the host to update your /etc/resolv.conf:
sudo resolvconf -u
After that, remove this from the container's /etc/resolvconf/resolv.conf.d/original:
nameserver 127.0.0.1
and then run this in the container to update its /etc/resolv.conf:
sudo resolvconf -u


Shutdown  does not depower

Question: When shutting down in 12.04, either in terminal or GUI, the result is a laptop (dell inspiron M4300) which is still powered. I then have to hold the power button for 5 seconds to depower. It's just an annoyance, but an annoyance i wouldn't mind getting to the bottom of. Any thoughts?
Comment: Please try the boot parameters `noacpi` OR `acpi=force`. It's usually an ACPI incompatibility of some sort.
Answer: Try the following:
Modify /etc/modules and add:
 apm power_off=1

Edit /etc/default/grub and add this after quiet splash:
acpi=force apm=power_off

Finally update grub:
sudo update-grub

Shutdown  does not depower


Get copy to sender with correct email adress / phpmailer

Question: i using a very simple phpmailer script for a contact page.
<?php
if( isset($_POST['name']) )
{
    $to = 'email@example.com'; // Replace with your email

    $subject = $_POST['subject'];
    $message = $_POST['message'] . "\n\n" . 'Regards, ' . $_POST['name'] . '.';
    $headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'] . "\r\n" . 'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);

    if( $_POST['copy'] == 'on' )
    {
        mail($_POST['email'], $subject, $message, $headers2);
    }
}
?>

but the issue is, that if copy is send, it has wrong "from" header details...so in example:

From: firstname.lastname@example.com
Reply to: firstname.lastname@example.com
To: firstname.lastname@example.com

but i need
From: email@example.com
reply to: email@example.com
to: firstname.lastname@example.com

Comment: Does this answer your question? [How to change envelope sender address using phpmailer?](https://stackoverflow.com/questions/13918999/how-to-change-envelope-sender-address-using-phpmailer)
Answer: This will usually not work because it's forgery, and most hosting providers will not allow it, for example gmail does not.
The right way to do this is to put your own email address in both from and to headers, and the submitter's address in a reply-to.
Though your code is short, it is a spam gateway that attackers could exploit to send unlimited amounts of email through your contact form. I suggest you start again with some better-protected code, such as the contact form example provided with PHPMailer that you tagged this question with.


Kafka on Kubernetes multi-node

Question: So my objective here is to set up a cluster of several kafka-brokers in a distributed fashion. But I can't see the way to make the brokers aware of each other.
As far as i understand, every broker needs a separate ID in their config, which I cannot guarantee or configure if I launch the containers from kubernetes?
They also need to have the same advertised_host?
Are there any parameters I'm missing that would need to be changed for the nodes to discover each other?
Would it be viable to do such a configuration at the end of the Dockerfile with a script? And/or a shared volume?
I'm currently trying to do this with the spotify/kafka-image which has a preconfigured zookeeper+kafka combination, on vanilla Kubernetes.
Answer: My solution for this has been to use the IP as the ID: trim the dots and you get a unique ID that is also available outside of the container to other containers.
With a Service you can get access to the multiple containers's IPs (see my answer here on how to do this:
what's the best way to let kubenetes pods communicate with each other?
so you can get their IDs too if you use IPs as the unique ID.
The only issue is that IDs are not continuous or start at 0, but zookeeper / kafka don't seem to mind.
EDIT 1:
The follow up concerns configuring Zookeeper:
Each ZK node needs to know of the other nodes. The Kubernetes discovery service knowns of nodes that are within a Service so the idea is to start a Service with the ZK nodes.
This Service needs to be started BEFORE creating the ReplicationController (RC) of the Zookeeper pods.
The start-up script of the ZK container will then need to:

wait for the discovery service to populate the ZK Service with its nodes (that takes a few seconds, for now I just add a sleep 10 at the beginning of my startup script but more reliably you should look for the service to have at least 3 nodes in it.)
look up the containers forming the Service in the discovery service:
this is done by querying the API.
the KUBERNETES_SERVICE_HOST environment variable is available in each container.
The endpoint to find service description is then

URL="http(s)://$USERNAME:$PASSWORD@${KUBERNETES_SERVICE_HOST/api/v1/namespaces/${NAMESPACE}/endpoints/${SERVICE_NAME}"
where NAMESPACE is default unless you changed it, and SERVICE_NAME would be zookeeper if you named your service zookeeper.
there you get the description of the containers forming the Service, with their ip in a "ip" field.
You can do:
curl -s $URL | grep '\"ip\"' | awk '{print $2}' | awk -F\" '{print $2}'

to get the list of IPs in the Service.
With that, populate the zoo.cfg on the node using the ID defined above
You might need the USERNAME and PASSWORD to reach the endpoint on services like google container engine. These need to be put in a Secret volume (see doc here: http://kubernetes.io/v1.0/docs/user-guide/secrets.html )
You would also need to use curl -s --insecure on Google Container Engine unless you go through the trouble of adding the CA cert to your pods
Basically add the volume to the container, and look up the values from file. (contrary to what the doc says, DO NOT put the \n at the end of the username or password when base64 encoding: it just make your life more complicated when reading those)
EDIT 2:
Another thing you'll need to do on the Kafka nodes is get the IP and hostnames, and put them in the /etc/hosts file.
Kafka seems to need to know the nodes by hostnames, and these are not set within service nodes by default
EDIT 3:
After much trial and thoughts using IP as an ID may not be so great: it depends on how you configure storage.
for any kind of distributed service like zookeeper, kafka, mongo, hdfs, you might want to use the emptyDir type of storage, so it is just on that node (mounting a remote storage kind of defeats the purpose of distributing these services!)
emptyDir will relaod with the data on the same node, so it seems more logical to use the NODE ID (node IP) as the ID, because then a pod that restarts on the same node will have the data.
That avoid potential corruption of the data (if a new node starts writing in the same dir that is not actually empty, who knows what can happen) and also with Kafka, the topics being assigned a broker.id, if the broker id changes, zookeeper does not update the topic broker.id and the topic looks like it is available BUT points to the wrong broker.id and it's a mess.
So far I have yet to find how to get the node IP though, but I think it's possible to lookup in the API by looking up the service pods names and then the node they are deployed on.
EDIT 4
To get the node IP, you can get the pod hostname == name from the endpoints API
/api/v1/namespaces/default/endpoints/
as explained above.
then you can get the node IP from the pod name with
/api/v1/namespaces/default/pods/
PS: this is inspired by the example in the Kubernetes repo (example for rethinkdb here: https://github.com/kubernetes/kubernetes/tree/master/examples/rethinkdb
Comment: Good idea! This seems like a doable solution! I managed to give all my brokers IDs now, through a startup-script doing: BROKER_ID=$(ip addr | awk '/inet/ && /eth0/{sub(/\/.*$/,"",$2); print $2}' | sed -r 's/\.//g') and : sed -r -i "s/(broker.id)=(.*)/\1=$BROKER_ID/g" $KAFKA_HOME/config/server.properties
Comment: I used ip=$(hostname -i) Then id=${ip//./}
Comment: Can I also ask how you add the servers to /conf/zoo.cfg? A shared volume that's interacts with the Kafka-Service of Kubernetes?
Comment: So the idea is this, and i will edit the answer with more details: start a Service with the zk nodes, and a service with the kafka nodes. then start the replication controller for zookeeper. at that point the service will register the zk containers... but it takes a few seconds. so meanwhile your container needs to wait for the discovery service to populate the zk container nodes. I put a 10sec pause in my script starting zookeeper to account for that, but it it not ideal. then look up the IPs and populate the zoo.cfg before running zk.
Comment: Thank you for the thorough walkthrough! Which Username and Password are you referring to? The API-server itself I assume? I auth to the server with a cert atm. I should lookup how to curl with a cert then?
Comment: Yes username and password for the API server. that can be found by describing the cluster in gke:
gcloud beta container clusters describe
If you got that working with a certificate, I'd be interested to know how you set that up.
Comment: Kelsey Hightower has written a [Intro to Kubernetes](https://github.com/kelseyhightower/intro-to-kubernetes-workshop) where installing certs is covered in the sub-topics "PKI infrastructure" and "Provision the Controller Node". Later those certs are [added to Kubectl](https://github.com/kelseyhightower/intro-to-kubernetes-workshop/blob/master/labs/install-and-configure-kubectl.md) The guide is focused on CoreOS, but I see no reason it shouldn't work on other distros. :)

Thanks again for the help. It's not up and running yet, but with this guide I have only myself to blame!
Comment: This fails miserably when I am trying to deploy Kafka on multiple kubernetes clusters. I have 3 GKE clusters in different regions and trying to keep one Kafka broker per cluster for High Availability. But because Statefulsets start with `0` on every cluster (e.g `statefulset-name-0`) all my brokers are getting the ID `0` and only one of them is able to connect with the Zookeeper (running separately).
Comment: Nowadays, use StatefullSets to handle statefull applications like Kafka. This post was a work around when these didn't exists in Kubernetes
Answer: Look at
https://github.com/CloudTrackInc/kubernetes-kafka
It allows to start Kafka in kubernetes and support scaling it and auto extanding.
Comment: That link is fairly outdated. Probably better to find Strimzi or Confluent Helm Charts now.
Answer: This shows up prominently in my searches but contains pretty outdated information. To update this with a more modern solution, you should use a StatefulSet deployment, which will generate pods that have an integer counter instead of a hash in their name, eg. kafka-controller-0.
This is of course the hostname, so from there it's a simple matter to extract a fixed, invariant broker ID using awk:
hostname | awk -F'-' '{print $3}'

The most popular containers available for Kafka these days have a broker ID command.
Answer: I did this using docker-compose (The difference for Kubernetes would be that you would pass the ID via your service.yaml and have 2 services):
kafka1:
  build: kafka-0.8.1/
  ports:
  - 9092
  links:
  - zookeeper
  environment:
  - ID=1
kafka2:
  build: kafka-0.8.1/
  ports:
  - 9092
  links:
  - zookeeper
  environment:
  - ID=2

Config:
broker.id=${ID}
port=9092
advertised.host.name=${HOST}
advertised.port=9092
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
log.dirs=/kafka/kafka-logs-${ID}
num.partitions=200
num.recovery.threads.per.data.dir=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
log.cleaner.enable=false
zookeeper.connect=${DOCKER_ZOOKEEPER_1_PORT_2181_TCP_ADDR}:${DOCKER_ZOOKEEPER_1_PORT_2181_TCP_PORT}
zookeeper.connection.timeout.ms=6000

sh:
#!/bin/bash
echo "Running config"
export HOST=`grep $HOSTNAME /etc/hosts | awk '{print $1}'`
export ID=${ID:?}
perl -p -i -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : $&/eg' < /broker.template > $KAFKA_HOME/config/server.properties
echo "Done"
echo "starting kafka with:"
echo "$KAFKA_HOME/config/server.properties"
echo ""
cat $KAFKA_HOME/config/server.properties
$KAFKA_HOME/bin/kafka-server-start.sh $KAFKA_HOME/config/server.properties

Comment: Are you sure it's possible to pass environment-variables through a kubernetes-service? because other than that I can see this as a solution.
Comment: This talks about passing environment-variables in Pods or ReplicationControllers? I am aware this is possible, but does this also imply that it can be done in a Service?

Kafka on Kubernetes multi-node


writing to a .php file?

Question: Hey i'm trying to write to my "config.php" file but it just won't work. I am using the code below. using this code it doesn't come up with any errors it just doesn't write the string.
<code> $myFile = "config.php";
      $fh = fopen($myFile, 'w') or die("can't open file");
      $stringData = "<?php\n";
      fwrite($fh, $stringData);
      $stringData = "$db_user = '{$dbuser}';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_pass = '{$dbpass}';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_name = '{$dbname}';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'localhost';\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'mysql_connect($db_host, $db_user, $db_pass) or die(mysq_error());\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'mysql_select_db($db_name) or die(mysql_error());\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = 'function protect($str) {\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = '   return mysql_real_escape_string(urldecode($str));\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = '}\n";
      fwrite($fh, $stringData);
      $stringData = "$db_host = '?>\n";
      fwrite($fh, $stringData);
      fclose($fh);
</code>
What am i doing wrong?
Comment: Are the permissions correct? Do you get any errors? What actually happens?
Comment: Please take this to heart: You should never post that "you're getting an error" or "it doesn't work" without telling us *what* error, or *how* it doesn't work. We can't help you otherwise.
Comment: @Duncan: as explained in my answer below, you are not properly escaping your variables. When confronted with a problem like this, try to get the smallest piece of code that works, then build from there. In this instance, comment all lines except the first one, then uncomment the second, then test, etc.
Answer: You need to properly escape the $ characters when you want them to be output, like so:
<code>$stringData = "\$db_user = '{$dbuser}';\n";
</code>
Comment: @Duncan Specifically, you seem to think you need to use `"{$variable}"` to substitute the value into the string. You don't. Both `"$db_user"` and `"{$db_user}"` will cause the value of `$db_user` to be interpolated into the string.
Comment: @Duncan I mean, you're using strings like this: `"$db_user = '{$dbuser}';\n";` which seems to imply you don't realize this is identical to `"{$db_user} = '{$dbuser}'"` or `"$db_user = '$dbuser'"`. You don't need the `{}`. It looks like you're intending to write the literal string `"$db_user"` to the file, but this isn't what you're doing. If `$db_user` isn't set, you're going to write something like `" = 'username'"` to the file.
Answer: look! if you want to write something to file like:
<code>$stringData = "$db_host = 'localhost';\n";
</code>

you should escape it!
<code>$stringData = "\$db_host = 'localhost';\n";
</code>
and
<code>  $stringData = "$db_host = 'mysql_connect($db_host, $db_user, $db_pass) or die(mysq_error());\n";
</code>
why you quoted mysql function????
Answer:
What am i doing wrong?

The big thing you are doing wrong is confusing code and data. Having self-modifying code on a webserver is a recipe for disaster.
But assuming you actually want your application to be hacked and destroyed...You need to escape references to variables to avoid them being interpolated. i.e.
<code>fwrite($fh, '$db_user = ' . "'{$dbuser}';\n");
</code>
You should also provide meaningful explanations of why your code is not behaving as you expect (a bit more information than "it just won't work"). Assuming the file is not being written / amended and the script is bombing out with "can't open file", it's probably a permissions problem - but since you've provided no details of which OS this is, we can't tell you how to fix that.
Also you're quoting function names - does that mean you are using eval to ivoke the self-modified coe at runtime? OMG!
Comment: if you're not seeing the die() message then it's not dying - so it's writing the file - just not the file you expect / in the location you expect.
Comment: i'm new to php :S but the problem is that it just doesn't write to the file. No errors come up at all.

writing to a .php file?


How can I find a tag in html site that I know it matches a certain pattern in python?

Question: I want to get the width percentage from the winter/spring/summer etc charts in this site:
https://www.fragrantica.com/perfume/Christian-Dior/Sauvage-Eau-de-Parfum-48100.html
For example, for the winter season, I want to find this row in the page elements:

I have tried the following
res = requests.get("https://www.fragrantica.com/perfume/Christian-Dior/Sauvage-Eau-de-Parfum-
                    48100.html", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)
                                           AppleWebKit/537.36 (KHTML, like Gecko),
                                           Chrome/88.0.4324.150 Safari/537.36'}
soup = BeautifulSoup(res.content, 'html.parser')
winter_row = soup.select('div[style="rgb(120, 214, 240)"]')
print(winter_row)

I wanted to find that certain html row using the RGB that is unique for each season. The problem is I get an empty list as the output. I want my code to extract the width for each season, day and night from the charts so I know exactly what percentage the votes are.
Do you guys have any idea what should I do?
PS:
I also got the name of the perfume from the site and it works, so I know I get a response.
name_row = soup.select('#toptop')[0]
name = name_row.getText().replace('\n', '')

Answer: You get an empty list because you use:
soup.select('div[style="rgb(120, 214, 240)"]')
But this expression is looking for an exact match.
But in fact you want to find div elements having a style attribute, and this attribute must contain a background CSS property with a specific value (rgb(120, 214, 240) in your example).
So you have to use this CSS attribute selector syntax:
soup.select("[style*='background: rgb(120, 214, 240)']")

Example:
htmlpage = """<!doctype html>

    <title>Title</title>

"""

soup = BeautifulSoup(htmlpage, 'html.parser')
extracted = soup.select("[style*='background: rgb(120, 214, 240)']")

print(extracted)

Output:
[

]

And you should use res.text instead of res.content which gives you the content of the response in bytes, not as text that can be parsed.
Comment: I still get an empty list :(


Delete / Un-assign Group numbers to units in Supreme Commander 2

Question: While I love the fact that I can assign more than one group # (using CTRL + *number *to a particular unit or combination of units), I can't, for the life of me, figure out how to un-assign, or delete that group designation, from a unit.  And it drives me crazy.
Also, on the flip side, if anyone knows what secret combination of actions will let me change the group designation number without adding an additional group designation, that would be pretty cool as well.  Say if I wanted to change my WASPS from group 1 to group 3.
I couldn't find anything in the settings on how to do this, any help would be appreciated.
Answer: To change the group designation for a unit, assign the units to the new group, deselect all units, then press Ctrl + the old group number (this assigns the group to nothing).
The only way to remove units from a group is to select the group, deselect the specific units, then re-assign those units to the same group.
Comment: This is standard for pretty much every RTS game.
Comment: @StrixVaria: actually, Starcraft has the annoying problem of not really benig able to empty your selection, so it's basically impossible to do the first items.


Does attack speed modify the animation speed for priests on TERA?

Question: Good Day,
I am figuring out how to build my priest on TERA. I have recently seen a video of a sorcerer with 24% attack speed landing his attacks faster than when he had 0% attack speed. I wondered if the same goes for healers? Would attack speed affect the animation speed of which your character gets heals off? (I am not talking about cast times - but I do notice that you cannot act while your character is animating on his attack or heal)
Answer: According to this guy's guide, about half way down in Gear Stats, attack speed is indeed a critical stat, as it does increase your healing animations' speed according to this line:

This bonus is quite noticeable and important for priests. It increases
  all our healing animations, including circles and even target heals.
  This is a must and you should aim to have two of these rolled on your
  enigmatic staff. At the example above, the staff has "double" attack
  speed stats rolled.

This guide also states that attack speed is a useful stat when it goes over all of the stats.

Which of these affect a Healer's raw healing power?
None of them! Pretty cool, huh? Our heals cannot crit and Power/Attack
  only affect damage dealers. The only combat stat or stat modifier
  that's of benefit to a healer is Attack Speed. That allows us to get
  off our healing and buff abilities faster, so it's something to look
  out for.

Finally, someone on these forums says that you heal faster with it. That topic is from 2012, and it says that there can be disadvantages to attack speed. This mostly seems to be the ranges of melee attacks. These range changes could have changed since this post.
Overall, I've seen several places say that it increases your healing speed, so at the very least, it shouldn't hurt it.
Comment: Finally. a solid answer. I read the links you gave me.
Comment: I will award bounty in 23 hours from now
Comment: Awarded! wasn't exactly 23 hours, but I'm drunk. whatcanyado


How to grid columns in tkinter?

Question: I'm making a project using tkinter but am having some trouble with using the grid method
i'm trying to place all the pictures on the right side of the screen,but its just not working
here is the code i've written:
window = Tk()

window.geometry("500x400")

lemon_pic = PhotoImage(file="lemon.png")
melon_pic = PhotoImage(file="melon.png")
dragonFruit_pic = PhotoImage(file="DragonFruit.png")

lemon_picture = Label(window,image=lemon_pic,bg="white")
melon_picture = Label(window,image=melon_pic,bg="white")
DragonFruit_picture = Label(window,image=dragonFruit_pic,bg="white")

lemon_picture.grid(row=4,column=10,sticky=E)
melon_picture.grid(row=0,column=10,sticky=E)
DragonFruit_picture.grid(row=3,column=10,sticky=E)

window.mainloop()

And here's the output i get:
https://i.stack.imgur.com/GV1kn.png
Comment: It may be because there is nothing in the columns before column 10, so their widths are all zero.
Comment: I did my research and a lot of what i've found say the same as you did, but how can i fix it? how can i make the images visible in column 10.
Comment: Use `win.columnconfigure(10, weight=1)` (assume `win` is the container of the widgets holding the images) and set `sticky=E` on the `.grid(...)`.
Comment: i just tried it, It works! but only on column 10..so if i were to put column 9 or 8 it wouldn't work
Comment: Then change 10 to the column in `.columnconfigure(...)`.
Comment: thanks, That works well!

i have another question, Can we separate each picture by half a row only?

if i tried to do something like `lemon_picture.grid(row=0.5,column=10,sticky=E)`

it would give me an error saying that i should provide a non-negative integer
`bad row value "0.5": must be a non-negative integer`
Comment: You  can add `pady` option to `.grid(...)` to add some margins.
Comment: okay! Thanks a lot for answering my question,Sorry if it was a silly one

so how do i mark this question as solved?
Comment: you should vote on it and/or accept it, also if you have something else to ask, create a new question.
Answer: if the images are inside a frame that is sticky to the left like frame.pack(side='left'): then change that to 'right'. otherwise:
try using E (east) instead of W (west) for the images
lemon_picture.grid(row=0,column=10,sticky=E)
melon_picture.grid(row=1,column=10,sticky=E)
DragonFruit_picture.grid(row=2,column=10,sticky=E)

Comment: I tried doing so and it still doesn't work
Comment: i don't use frame.pack() at all and i don't know how to use it...is it gonna help me with fixing this if i use it?
Comment: it may be esier to fix the problem if you edit your question to include all your code
Comment: @acw1668 answered my question, Thank you a lot for helping me.

How to grid columns in tkinter?


Well pump isn't functioning after chlorination shutdown

Question: We had to bleach our well, and we turned off the the power to the pump overnight. After letting the chlorinated lines set for about 12 hours, I flipped the breaker to the pump to drain the lines. Unfortunately, nothing drained from the lines and I realized something was not working.
I checked the pressure in the well tank, it is fine. I checked the pressure gauge on the pressure switch. It reads 0. I tested the pressure switch circuit and power is hot on both the source and load side. Does this mean the pump is receiving power but not working?
Answer: When I have had submersible pumps fail they have always tripped the overload or breaker. If you have a pump controller the start capacitors may be bad but this usually blows a fuse in the controller and you would not have power on both legs if 240V. Try turning the pump power off for 30 minutes if it is over heated it may reset if it has a thermal overload on the pump. Then try toggling the power on and off several times to get the pump to try and start. If it starts you should be prepared to replace the pump because once they start failing to start with good capacitors (if it has them) it wont last long.