Simplifying MYSQL query

Question: Is there a way to simplify the query below? I got what i wanted but i want to  learn how to achieve the result by using a shorter query. As for the result, can i replace the value NULL to 0?

SELECT ad.Staff,
       ad.TYear,
       ad.TWeek,
       b.TMonth
  FROM (SELECT a.Staff,
               a.TYear,
               d.TWeek
          FROM (SELECT t2.creatorfullname AS Staff,
                      count(distinct(t1.ticketmaskid)) AS TYear
                 FROM swtickets t1
                      JOIN swticketauditlogs t2
                           ON t1.ticketid = t2.ticketid
                WHERE (YEAR(from_unixtime(t2.dateline)) = YEAR(CURRENT_TIMESTAMP)
                       AND FIND_IN_SET (t2.creatorfullname,'Andy Murray,Rafael Nadal,Maria Sharapova') > 0
                       AND t2.actionmsg LIKE '%Ticket status changed from: % to: Closed%')
                       AND totalreplies > 0
              GROUP BY t2.creatorfullname) AS a
                LEFT OUTER JOIN (SELECT t2.creatorfullname AS Staff,
                                        count(distinct(t1.ticketmaskid)) AS TWeek
                                   FROM swtickets t1
                                        JOIN swticketauditlogs t2
                                             ON t1.ticketid = t2.ticketid
                                  WHERE (WEEK(from_unixtime(t2.dateline)) = WEEK(CURRENT_TIMESTAMP)
                                         AND FIND_IN_SET (t2.creatorfullname,'Andy Murray,Rafael Nadal,Maria Sharapova') > 0
                                         AND t2.actionmsg LIKE '%Ticket status changed from: % to: Closed%')
                                         AND totalreplies > 0
                                GROUP BY t2.creatorfullname) AS d
                                 ON (a.Staff = d.Staff)) AS ad
                LEFT OUTER JOIN (SELECT t2.creatorfullname AS Staff,
                                        count(distinct(t1.ticketmaskid)) AS TMonth
                                   FROM swtickets t1
                                        JOIN swticketauditlogs t2
                                             ON t1.ticketid = t2.ticketid
                                  WHERE (MONTH(from_unixtime(t2.dateline)) = MONTH(CURRENT_TIMESTAMP)
                                         AND FIND_IN_SET (t2.creatorfullname,'Andy Murray,Rafael Nadal,Maria Sharapova') > 0
                                         AND t2.actionmsg LIKE '%Ticket status changed from: % to: Closed%')
                                         AND totalreplies > 0
                                GROUP BY t2.creatorfullname) AS b
                                 ON (ad.Staff = b.Staff);

+----------------+-------+-------+--------+
| Staff          | TYear | TWeek | TMonth |
+----------------+-------+-------+--------+
| Andy Murray    |   337 |    37 |    142 |
| Rafael Nadal   |    49 |  NULL |     13 |
| Maria Sharapova|    49 |     1 |      4 |
+----------------+-------+-------+--------+
Comment: please provide some sample data with expected output
Comment: Removed sql-server tag because question is explicitly about MySQL.
Comment: Here we go again @Gordon
Comment: You could use coalesce  to show 0 instead of null, like coalesce(ad.TWeek,0)
Comment: coalesce works! Thank @RobertRozas . As for simplifying the query.. any suggestion?
Comment: your column of  "AND totalreplies > 0", there is no alias or table reference to confirm its origin... which table t1 or t2
Comment: Any idea how to integrate a sum value at the bottom of the row? I tried WITH ROLLUP but it doesnt output the correct sum value.
Comment: Anyone knows how to rollup the values?
Comment: i can use "with rollup" only if i requery it.

select Staff, Sum(TYear) as TYear, Sum(TWeek as TWeek, Sum(TMonth) as TMonth FROM (SELECT
Answer: Try:
 SELECT t2.creatorfullname AS Staff,
        count(distinct case when YEAR(from_unixtime(t2.dateline)) = YEAR(CURRENT_TIMESTAMP)
                       then t1.ticketmaskid end) AS TYear,
        count(distinct case when WEEK(from_unixtime(t2.dateline)) = WEEK(CURRENT_TIMESTAMP)
                       then t1.ticketmaskid end) AS TWeek,
        count(distinct case when MONTH(from_unixtime(t2.dateline)) = MONTH(CURRENT_TIMESTAMP)
                       then t1.ticketmaskid end) AS TMonth
 FROM swtickets t1
 JOIN swticketauditlogs t2
      ON t1.ticketid = t2.ticketid
 WHERE FIND_IN_SET (t2.creatorfullname,'Andy Murray,Rafael Nadal,Maria Sharapova') > 0
   AND t2.actionmsg LIKE '%Ticket status changed from: % to: Closed%'
   AND totalreplies > 0
 GROUP BY t2.creatorfullname

-- edit --
This approach can be used when we need to count records that meet many conditions.
In this approach we use the simplest form of a case expression:
CASE WHEN condition THEN expression1 [ ELSE expression2 ] END
The case expression works like IF statement - it evaluates a condition, and when the condition is true, then returns a result of first expression, otherwise a result of second expression, or - when the second expression is not given (else part is skipped) - it returns NULL.
MySql has an IF function: IF(expr1,expr2,expr3) that works in the same way as case expressions, however case expressions are part of ANSII SQL Standard and are implemented by most databases, while IF function is MySql's proprietary extension.
Please take a look at this link for details: https://dev.mysql.com/doc/refman/5.6/en/control-flow-functions.html

The query to count records may look for example like:
SELECT count(*),
       count( some_column ),
       count( CASE WHEN condition1 THEN 1 END ),
       count( IF( condition2, 1, null ) ),
       sum( CASE WHEN condition3 THEN 1 ELSE 0 END ),
       count( DISTINCT CASE WHEN condition4 THEN some_column END ),
       count( DISTINCT IF( condition2, 1, some_column ) )
FROM sometable

COUNT(*) - counts a total number of rows
COUNT( expression ) - counts a number of rows when expression is not null (it skips null values)
COUNT( DISTINCT expression ) - same as above, but takes into account only distinct values

count( DISTINCT CASE WHEN condition THEN some_column END ) -for each row it evaluates condition and returns a value of some_column when the condition is true, else returns null. Since nulls are skipped, it counts only distinct values for rows that meet the condition.
Comment: exactly where I was going, but pending on where "totalreplies" table basis was as it was not qualfied.
Comment: Its from the table t1.
Comment: It works. awesome!So i dont need to use LEFT OUTER JOIN as well as coalesce. Can you explain a bit
Comment: Also can u help me out with "last week", "last month" and "today"? Abit struggle playing with the dates
Comment: @user1204671 i've appended an explanation. If you want a previous year/month/week, just append `-1` to the condition, for example: `YEAR(from_unixtime(t2.dateline)) = YEAR(CURRENT_TIMESTAMP) - 1`
Comment: Nice one @kordirko what about just today and yesterday?
Comment: Any idea how to integrate a sum value at the bottom of the row? I tried WITH ROLLUP but it doesnt output the correct sum value.
Comment: i can use "with rollup" accurately only if i requery it.

select Staff, Sum(TYear) as TYear, Sum(TWeek as TWeek, Sum(TMonth) as TMonth FROM (SELECT

Simplifying MYSQL query


How to set dynamic default textarea data in a Django template?

Question: I'm designing a contact form and I'd like in some case (not always) pre-fill the subject and content field with data in the URLs.
That's why my view look like this:
def contact(request):
    if request.method == 'POST':
        contact_form = ContactForm(request.POST)
        # Some more logic here

    else: # GET request
        contact_form = ContactForm()
        subject = request.GET.get('subject') or ""
        content = request.GET.get('content') or ""

    return render(request, 'contact.html', locals())

I created an addattrs custom filter that allow me to inject HTML attributes in HTML elements.
So, for pre-filling the subject (a classic text input), I do it like this, and it works:
{% with "value="|add:subject as attrs %}
    {{ contact_form.subject|addattrs:attrs }}
{% endwith %}

Now, I'd like to do the same thing with a textarea.
But textarea default values are not set by filling the HTML value attribute, they're filled that way:
<textarea>default texte here</textarea>

How could I do?
Thanks!
Comment: Related: https://github.com/kmike/django-widget-tweaks/issues/7
Answer: You don't need to manipulate with HTML. Use initial argument of the form constructor:
subject = request.GET.get('subject', '')
content = request.GET.get('content', '')
contact_form = ContactForm(initial={'subject': subject, 'content': content})


CSS :before/:after selectors are suddenly being positioned separately of parent div

Question: I switched to a new computer, and all of a sudden the CSS :after and :before selectors no longer work.
What's truly bizarre is that the :before/:after selectors I added before, on my other computer, display completely normally on my new computer. But any new ones I add now simply don't show up, even if I copy-and-paste the old code onto a new div.
For example, this one:
html

css
#wtf {
    width: 10px;
    height: 20px;
    background: red;
}
#wtf:after {
    content: "";
    position: absolute;
    left: 100px;
    top: 10px;
    width: 20px;
    height: 20px;
    background: blue;
}

This code works when copied and pasted directly into a fiddle: ( http://jsfiddle.net/rLnrtu0x/ ) but only the red box displays on my local browser. No matter what I do, the blue box won't show. All other CSS behaves normally.
Does anyone know what I might be doing wrong?
Tested on Mozilla 35.0.1 and Chrome 42.0.2311.152 (64-bit) on Ubuntu 14.04. I can't retest it on my old computer because it broke, but I never had problems with :before/:after selectors before.
UPDATE
I just found the selectors with my inspector. They actually display normally, but they are being positioned relative to html, not their parent div. Here again, with the code that I added before the computer change, the :before/:after selectors are positioned relative to the parent div. But the new code, even though it's copy-and-pasted, positions the selectors relative to the html. Why would this be?
Comment: You need to do what is called "troubleshooting". That means to systematically develop hypotheses about the possible problem, and test them one by one. For instance, in this case, copy the edited file back to the previous computer and see if it works. Try different browsers and versions on the two machines. View the console. Run a CSS linter.
Comment: You might be doing something wrong. Because this is unlikely to happen to you only.
Comment: What version of "Mozilla"?
Comment: @Mr_Green That's the question. But I don't see what I could possibly be doing wrong, because the code from the fiddle is literally copy and pasted.
Comment: @misterManSam I added mozilla and chrome versions above.
Comment: @torazaburo My previous computer broke, so I can't retest it on that. I tried it on chrome and the same problem is manifested. The web console displays no errors.
Comment: Continue troubleshooting. Open devtools, select the `#wtf` element, and view styles to see if the `:after` rule is present and being applied.
Comment: @torazaburo I actually found the selectors with my inspector. They are displaying normally, but they are now positioned relative to the html, where before they were positioned relative to the parent div.
Answer: The parent container needs to have position
Absolutely positioned elements are positioned "at a specified position relative to its closest positioned ancestor or to the containing block." (src: MDN)
So, your :after pseudo-element is not contained by its parent because the parent isn't "positioned" or its position is set to static.
The only explanation is that there must have been something in your previous setup that was applying position to #wtf, which allowed its child to be positioned absolutely within it.
You can "fix" the issue by applying position to #wtf like so:

#wtf {
    width: 10px;
    height: 20px;
    background: red;
    position: relative;
}
#wtf:after {
    content: "";
    position: absolute;
    left: 100px;
    top: 10px;
    width: 20px;
    height: 20px;
    background: blue;
}

Answer: It turns out that it's unrelated to the computer change. The :before/:after selectors are in fact displaying, but they are being positioned relative to the html, not the parent div, because the parent divs are absolutely positioned.
Comment: If the parent `div` has `position: absolute` set, then the `:after` pseudo-element would be positioned relative to it. The problem appears to be that there is no position applied to the parent container. See my answer above.


How soon can we stain a freshly-sanded deck after it got drenched in the rain?

Question: My family and I are refinishing our deck.  We live in area with wild weather so, even though it called for a week of sun, immediately after finishing sanding our deck (to a very beautiful  underneath) it got drenched from rain.  It took 5 people 3 days of sanding to finish it.  Please, please don't tell me we have to do it again.  I have read many things about wood pores and finish that won't stick.
Is this rain going to affect anything? Or can we let it dry for a day or so and proceed with staining?
Comment: How'd it turn out if you didn't re-sand? I keep reading this advice to re-sand after rain, but it doesn't make sense to me.
Answer: Prep is always the most important step. Make sure the wood is dry. It shouldn't make too much of a difference that it rained after you sanded it down as long as it still has pores to absorb the stain.
I always recommend placing a large tarp over the area so that if it does rain, you don't have to worry too much about your work.
Answer: Old decks get slippery when from organic material and worse with wax based sealers.  Then there is the cosmetic blemish of aging with black stains from slow drying areas.  Stain looks great but slows down the drying out process which aggravates spots where water collects whereas as unfinished dries the quickest but turns grey from UV.
Appearance will vary greatly with porosity and density of wood.  I find staining  to be a short term solution with accumulating stain over the years required due to UV effects. Pressurized water removal is slow but regarding your question ... adhesion after a  days of sun drying is not a problem.   Pigment fading under UV is a problem as is black fungal growth, which I presume took many man-days of sanding.
Stain beefs.
Stain also makes the surface hotter for bare feet.  My preference is unfinished which turns stays grey and can be restored every few years by bleach or better pool chlorine dissolved in water applied with a roller on a broom stock then a stiff floor brush and rinse with a hose. Chlorine will evaporate in a day or so and wood will look as good as new with very little surface wood removed. This removes any black, green or other stains and makes sanding unnecessary unless you have slivers. It is also 5x faster than sanding. It will turn grey quickly and stay that way, dry faster and be cool under the hot sun.
Answer: I doubt this will help you now seeing as its been over a year but I would say that every product I've ever used says "apply to clean dry surface" or something to that effect, even water borne stuff. Which is to say that you'll get the best penetration and adhesion with wood that's perfectly dry.
If you're using a product that has a staining effect you'll get areas that repel the stain more than others and it will look blotchy. To be safe I would suggest letting it dry as thoroughly as you can (tarp it, put heaters/fans to it, whatever you can manage) then lightly sand again as the moisture will have raised the grain. Once you've prepped, apply your finish and keep it dry for as long as the manufacturer recommends you stay of it, usually 24 hours.
Good luck!
Answer: yes.  if a water based stain or an aniline dye, let the wood dry for a couple of days and stain as you wish.  if its an oil based stain, let it dry for four days or so before you apply the stain.  then apply your topcoat after the stain manufacturers indicated drying time.
FYI, the rain will have opened up more of the pores in the wood once it dries out, so you will actually get a better depth of penetration than you otherwise would have.


Is it possible to replace 32 bit hash function with 64 bit in this case?

Question: I've found https://github.com/cespare/mph as a minimal perfect hash, but it seems that it uses 32 bit function (I want 64 one). Is there a way to replace the function and make it work along with the rest part of the code?
Answer: Yes. The steps are:

Read the paper and understand it.
Read the code and understand it.
Make the necessary changes.

There's nothing in the algorithm that depends on a specific hash output size, so you can change it to anything you want, as long as the hash family you supply meets the requirements of section 1.3.
Probably it just requires changing all of the uint32 to uint64 in mph.go, and replacing all of murmur.go with a new 64-bit implementation; you just have to make sure that that new 64-bit hash is good.
Comment: Thank you, I'll try my best then!


Pandas apply on a column returning values for two columns on a portion of df

Question: I have a dataframe df and I want to apply a function to a column of the dataframe (c3) such that it returns values for two other columns (c1 and c2), and this should be done only on a portion of the df rows.
I would have expected this to work:
df.loc[0:20, ['c1','c2']] = df.loc[0:20, 'c3'].apply(my_f)
where my_f is the function to be applied, returning a Series with the two values for c1 and c2,
but it doesn't, the values for c1 and c2 remains NaN in df after executing this, despite no error or warning is raised.
What is the correct way to do this? It should be trivial, but I'm struggling to find it
For instance with the following code:
df_test = pd.DataFrame([{'C3':1}, {'C3': 2}, {'C3': 3}, {'C3': 4}, {'C3': 5}, {'C3': 6}])

def my_f(s):
  return pd.Series(['V1', 'V2'])

df_test.loc[0:1, ['C1', 'C2']] = df_test.loc[0:1, 'C3'].apply(my_f)
df_test.loc[3:4, ['C1', 'C2']] = df_test.loc[3:4, 'C3'].apply(my_f)

the result is the following:
    C3  C1  C2
0   1   NaN NaN
1   2   NaN NaN
2   3   NaN NaN
3   4   NaN NaN
4   5   NaN NaN
5   6   NaN NaN

while I expect the following:
    C3  C1  C2
0   1   'V1' 'V2'
1   2   'V1' 'V2'
2   3   NaN NaN
3   4   'V1' 'V2'
4   5   'V1' 'V2'
5   6   NaN NaN

NB: it is important taht I can do the assignments in separate instructions, as in the example above, since trying to do them all together makes me consume too much ram, crashing, due to the large size of my dataframe
Comment: Please add a reproducible code example, with your attempt along with the data and your expected result, this makes it easier to see the potential error.
Comment: @DigitalFarmer now it should be more clear, evenf if it's a very minimal example
Comment: @DigitalFarmer I think it's already pretty clear, but I will try to improve it with a specific example
Comment: Without seeing the data model you're working with (a basic DataFrame example would be enough), it's a little tricky to be sure of the right approach to help.
Comment: What is a `progress_apply`?
Comment: @BeRT2me just the apply of tqdm, showing a progress bar, in effect it is not relevant for this question, I will replace it with `apply` in the code
Answer: Try without .loc at the left assingment:
df_test = pd.DataFrame([{'C3':1}, {'C3': 2}, {'C3': 3}, {'C3': 4}, {'C3': 5}, {'C3': 6}])

def my_f(s):
    return pd.Series(['V1', 'V2'])

idxs = [0,1, 3, 4]
# Or if you want to use different ranges
# idxs = list(range(2)) + list(range(3,5))

df_test[['C1', 'C2']] = df_test.loc[idxs, 'C3'].apply(my_f)
print(df_test)

   C3   C1   C2
0   1   V1   V2
1   2   V1   V2
2   3  NaN  NaN
3   4   V1   V2
4   5   V1   V2
5   6  NaN  NaN

Comment: It works, but I don't get why. Or better, I suppose it is able to deal with the two different dimensions of the return from the right hand side and the df on the left, but still I don't get why it does not work with .loc, which typically is the right way to effectively change the df
Comment: @Vitto, in your assigments in `.loc`, you pass indexs to `.loc` but you can not pass `index` you can pass a boolean list to `.loc`. you can read [here](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html) : A boolean array of the same length as the axis being sliced, e.g. [True, False, True].
Comment: I've just realized that your solution is still now working in they way I need it, since it puts to nan everything that is outside [0:2], but I would like to keep it as it was, in the way that I can repeat the assignment on different subsets of df with different instructions and have all the values of c2 and c1 that I've inserted at the end
Comment: @Vitto, edited the answer, Is this what you want?
Comment: The problem is that I would like to be able to do it in separate instructions, for a very trivial reason: since my data frame is really big, colab crashes going out of ram if I provide it with all the indexes together, so I am doing it in a sort of batched way, one chunk of indexes after the other
Answer: I think you're over-complicating things, or not explaining enough of what you're actually trying to do:
df_test.loc[(0, 1, 3, 4), ('C1', 'C2')] = ['V1', 'V2']

Output:
   C3   C1   C2
0   1   V1   V2
1   2   V1   V2
2   3  NaN  NaN
3   4   V1   V2
4   5   V1   V2
5   6  NaN  NaN

Comment: Thanks for your answer, but doing in this way, while theoretically working, makes me crash due to the large size of the dataframe. (And obviously `my_f` is not really returning constant values in my real code). The solution I have found for other operations is to work on the dataframe chunk by chunk, where a chunk is a portion of the rows which is not too large, so to avoid crashes


Best strategy for pausing apt updates

Question: I'm running a Postfix/Dovecot stack and I absolutely do not want unattended upgrades (tends to break things). However, I do want to update at some point. I'm thinking of adding packages to /etc/apt/apt.conf.d/50unattended-upgrades. My concern is their dependencies updating, which may break them.
If I blacklist the main packages, their dependencies won't update right?
Comment: Sounds like a great plan for killing the whole system.
Comment: Care to elaborate?
Answer: I presume your are using ubuntu.
You can mark the package on hold which will stop updates to these packages.
To hold back updates e.g. google-chrome
sudo apt-mark hold google-chrome-stable

To re-eanble updates use
sudo apt-mark unhold google-chrome-stable

Comment: And again, this will hold any dependencies related to that package?

Best strategy for pausing apt updates


iptables block port from local network

Question: I have a problem inside my infrastructure.
chat.example.com port 8185 is reachable outside my infrastructure with a port fowarding to the right box.
But inside my infrastructure, i'm not able to reach it.
root@node1:/etc/iptables# telnet chat.example.com 8185
Trying 91.x.x.x...
telnet: Unable to connect to remote host: Connection refused

and outside my infrastructure :
guilhem@guilhem-Lenovo-B50-30:~$ telnet chat.example.com 8185
Trying 91.x.x.x...
Connected to chat.example.com.
Escape character is '^]'.

I don't understand why i can't reach it from my infra...
Here is my iptables rules :
root@node1:/etc/iptables# cat rules.v4
# Generated by iptables-save v1.4.21 on Thu Nov 26 13:51:03 2015
*nat
:PREROUTING ACCEPT [1577:148565]
:INPUT ACCEPT [484:29040]
:OUTPUT ACCEPT [403:31487]
:POSTROUTING ACCEPT [47:2820]
-A PREROUTING -d 91.x.x.x/32 -i eth0 -p tcp -m tcp --dport 8185 -j DNAT --to-destination 10.0.100.30:8185
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
# Completed on Thu Nov 26 13:51:03 2015
# Generated by iptables-save v1.4.21 on Thu Nov 26 13:51:03 2015
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [4:407]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i eth1 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 8185 -j ACCEPT
-A INPUT -j DROP
-A FORWARD -i eth1 -j ACCEPT
-A FORWARD -d 10.0.100.30/32 -i eth0 -p tcp -m tcp --dport 8185 -j ACCEPT
-A OUTPUT -p icmp -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -o eth1 -j ACCEPT
-A OUTPUT -o eth0 -j ACCEPT
COMMIT
# Completed on Thu Nov 26 13:51:03 2015

If you have any idea... Thank you !
Answer: Sounds like a DNS issue. You most likely setup your external DNS to point to your firewall/router (external IP). Your firewall then does an IP/Port forward to the correct IP on your network.
For this to work on your internal network, you will need to do a similar DNS setup. But you need to point the address to your internal IP address.
You can do it for your whole network via a DNS server you setup.
Or if you only need this done for one computer then you can just make an entry into the HOST file of the computer:

sudo nano /etc/hosts

Then type: (according to this format IP HOSTNAME.DOMAIN ALIAS)

LIP.###.###.### chat.example.com example

LIP = the local ip address of the server you are trying to access
Then try to ping 'chat.example.com' and see if it points to the right IP.

ping chat.example.com

Be mindful that if you use the host file that this will only work on that computer. Any other computer on the network will have to have a similar entry on their host file. If you have many computers trying to access that, then it would be worth considering setting up a DNS server.

iptables block port from local network


What is best way to attach deck balusters?

Question: I am going to build a railing around my wall.
One of my friend hired a contractor who installed balusters between two 2x4s. But now those spindles coming out. They first drilled a hole of 3/4" in every 4" in both top and bottom 2x4 wood. Then installed spindles in those holes. We see the top 2x4 crowned little bit over time that's why spindles coming out from those places.
Now I am going to build railing around my wall too, what is the best way?
Drill hole with 1" deeper
Or use connectors( showing in image)
Another way
Please advise.
Comment: This is a matter of opinion (about the procedure, cost, and appearance). Both systems are viable. I have lots of experience with each. Warped lumber is the actual problem in the scenario you described, and is a problem with either mounting strategy.
Answer: Unfortunately, this is a "preference" thing: both of these solutions will work if properly installed. The holes drilled for baluster install in the top and bottom rails should be deep enough that the balusters cannot flex out with normal slight movement of the wood. This indicates your previous install was improperly done.
The install in your second picture with connectors works well, it limits the movement (even rotation) of the balusters. This is my preference, my deck is built this way now. This can help on the stair railing where the holes method would require even deeper holes due to the diagonal, to keep the balusters from falling out the shallow side.
Ultimately, this comes down to preference and cost tolerance.
Comment: I agree. I've done both numerous times, and a crowned rail is more a problem with the rail than the baluster attachment mechanism. The rail should be replaced, I suppose.
Comment: @fredric, one of friend said  drill deep hole and use Sikaflex which prevent rail in any movement. Will this work ?
Comment: Probably; I haven't used it but in reading, it's a "professional-grade" sealant/adhesive. Whether you water-seal or not, you might have issues with water getting in the hole beside the baluster and causing damage over time as it gets wet and dries. Sikaflex could help prevent much of that water from getting in the hole, but on the other hand would keep it from drying out as quickly/effectively.


When should I use Shared Locking (Read Locking)

Question: Can someone explain when shared locks should be used. If I understand correctly, shared locks are used when reading and exclusive locks are used while writing.
But why can't I just wait while a mutex is locked when doing a read.
Comment: The pattern you describe is the most *common* use for shared and exclusive locks, but not the *only* sensible strategy. Another I've seen several times when there is some sort of partitioning of data (and that entire data set is protected by a single lock) with each partition having an owner, is that the owner can both read and write data in its own partition with a shared lock, but must acquire an exclusive lock for accessing other partitions for any access, read or write. This works well when a very high percentage of access is within the owner's partition.
Answer: It is for improving performance. Multiple concurrent reads then won't have to happen sequentially, which may be a great bonus if the structure is read frequently. (But still the data read will be consistent and up to date.)
Answer:
But why can't I just wait while a mutex is locked when doing a read.

Usually for speed. Shared locks allow multiple readers, as the content is not changing. Exclusive lock allows only a single (typically) write operation as you want all the writes to be atomic.
More technical definitions from here.

Exclusive locks protect updates to file resources, both recoverable
  and non-recoverable. They can be owned by only one transaction at a
  time. Any transaction that requires an exclusive lock must wait if
  another task currently owns an exclusive lock or a shared lock against
  the requested resource. Shared locks
Shared locks support read integrity. They ensure that a record is not
  in the process of being updated during a read-only request. Shared
  locks can also be used to prevent updates of a record between the time
  that a record is read and the next syncpoint.
Answer: A shared locks (also known as read locks) prohibits any other process from requesting a write lock on the specified part of the file. However, other processes can request read locks and keep reading from the resource.
An exclusive lock (also known as write lock) gives a process an exclusive access for writing to the specified part of the file and will prevent any other process to acquire any kind of locking to the resource until the exclusive lock is released.
So a read lock says "you can read now but if you want to write you'll have to wait" whereas a write lock says "you'll have to wait".
For an official description, check out the official locks documentation of GNU C library.
In addition, in many cases, the context of shared/exclusive locking is pessimistic/optimistic locking which is a methodology used to handle multi-users read/write to the same resource. Here is an explanation of the methodology.
Answer:
But why can't I just wait while a mutex is locked when doing a read.

Because that would be inefficient in certain scenarios, specifically those where a lot of threads are reading a data structure often, but very few are writing and not very often. Since multiple concurrent reads are thread-safe if no one is writing, it would be a waste to have mutual exclusion for the readers.
Imagine a server and multiple clients doing various transactions on some shared data. If most of these clients are simply asking for information, but not changing anything, the server would have horrible performance if it only allowed one client to read at a time.


What is the Flux State?

Question: Simply as that... What is Flux State? I am in the middle of the game, now, and I can guess a little. But Internet has no clear explanation of the thing. Is this a place, or ideology? Or maybe a place when certain ideology has been applied? Is the word used only around Berlin? The more information the better. Thank you.
Answer: The Flux State refers to the period when the anarchists ruled Berlin.

In 2039, after a small-scale civil war that had started with the Night of Rage an organization called "Anarchist Movement Berlin" (AMB) gained control of the city and declared Berlin the "Greatest Experiment in Anarchist History".

You can read a little more about it here:

In the wake of the anarchist revolution of 2039, the city seceded from the German state and created the Flux State. This grand experiment in social order is anarchy in practice, where the power structure constantly evolves and the crafty shadowrunner will always find ways to survive - and even thrive. Corporations thread carefully in the Free City - and even the great dragon Lofwyr only has so much influence here.

What is the Flux State?


Order of a field

Question: If $F$ is a finite field, show that $|F|=p^r$, for $p$ prime and $r>0$ integer.
I know that $p$ is zero in this field since $p$ is characteristic. So the kernel of this will be any multiple of of $p$. But am confused how to go from here. Don't fields have the requirement that they need to be prime. So wouldn't $p$ divide $p^r$ so it could not be a field?? Any help would be appreciated. Thank you
Comment: The ideal $\langle x^2 + x + 1 \rangle \leq \Bbb F_2[x]$ is maximal, so the quotient $\Bbb F_2[x] / \langle x^2 + x + 1 \rangle$ is a field of order $4$.
Answer: If $F$ is a finite field, then there is a prime $p$ such that $F$ contains $\mathbb{F}_p$. Since $F$ is finite, the dimension of $F$ as an $\mathbb{F}_p$-vector space must be finite, so there are elements $x_1,\dots,x_r\in F$ which form a basis for $F$ as an $\mathbb{F}_p$-vector space.
Then every element of $F$ can be written uniquely in the form $n_1x_1+\dots+n_rx_r$ with $n_i\in \{0,1,\dots,p-1\}$, hence $|F|=p^r$.

Order of a field


Looking for a updateable & secure WebBrowser-Framework

Question: I would like to implement a web browser in my c#-program. The browser should cover some requirements:

It should be updateable
I'm not sure if this is possible, but it would be great if the implementet web-browser would alwasy be using the latest version of the based browser which is installed on the system.
Easy implementation
Of course, the easier to use, the better!
Security
And the used browser should be as secure as possible. The safest i could think of, was running the browser in sandboxed mode. Are there other possibilities to achieve a maxiumum of security?

Untill now i have found some wrappers for different Browser-Engines, but none of hem seems to match my requirements:

Awesomium: Is very easy to use! But is still based on an old Version of Chrome (12.0.702.0)
Berkelium: Same as Awesomium, i think.
CefSharp:
GeckoFX: Needs FireFox 1.5 installed
MozNet: Based on FireFox 3.6
WebKit.NET: I'm not sure about that...
the native WebBrowser Class: I think this is the best i could get - because it always uses the latest installed version of IE.
Answer: After doing some more research, i think i'll stick with the WebBrowser Control. It's not perfect and the posibilities to use own settings are not as good as i hoped, but i think since there seems no better solution, it will have to work...


Is it me or i can't sum these?

Question: Good morning / Afternoon / evening :).
i have two integers that i want to turn them floats, with 4 decimal numbers to use them on GPS coordinates:
var z = y.toFixed(4);
var p = x.toFixed(4);

But there are a situation that is bugging me, that is the sum between these 'z' and 'p':
var t = z + p;

After this instruction, i want to print the result on the screen with some common functions like:
document.write(z);  document.write("
");
document.write(t);
document.write("
");
document.write("
");

The result that i get is:
0.0000
0.0000300.0000

1.0000
1.0000300.0000

2.0000
2.0000300.0000

But what i really want is:
300.0000
301.0000
302.0000

How can i sum 'z' and 'p', after all? :S
Noob question, i know :S.
Kind regards,
Sam
Comment: toFixed converts a number into a string. so at the end you're adding two strings !
Comment: tried to int /float/double z and p and sum them then?
Comment: Thank you both for the fast response.

I already checked that situation of the strings, and it's so true :).

Already fixed the bug :).
T
Comment: Thank you both for the fast responses.

That string situation is the problem of this bug.

Already fixed my problem.

Thanks once again :)
Answer: That's because .toFixed() returns a String object rather than a Number, so the + operator performs concatenation.
Instead you should perform the addition of the actual numbers first and then perform .toFixed() to "round" the result for display.
var t = (x + y).toFixed(4);
document.write(t);

Comment: This worked fine for me.

Thank you very much for the fast response Jack! :)

Kind Regards!
Answer: I think what you want is :
var t = x + y;
var p = t.toFixed(4);
document.write(p);

Comment: This was, like Jack's solution, the best way to fix the bug.

I apprecitate the fast response pktangyue! :)

Kind regards!
Answer: try this
var t = (x + y).toFixed(4);

fiddle here
Comment: Thank you for the fast response bipen! :).

The solution is already taken and the bug is fixed! :).

Kind regards! :)
Answer: The JavaScript method toFixed converts your number into a string. Thus, when you perform operation z + p it actually is string concantenation and not addition of numbers. You may first add your numbers and afterwards apply toFixed.
Comment: This is an important description to fix the bug!

Thanks once again for the fast response! :)

Kind regards!
Answer: toFixed() returns a string, which means you are concating string when you use var t = z + p. You need to first sum your coordinates and then call toFixed().
Comment: Thanks for your fast response w4rumy! :)

My problem is solved! :)

Kind regards!
Answer: How much is p? Are you concatenating strings?
Try with var t = parseFloat(z) + parseFloat(p);
Comment: I think this should be a comment and not an answer.
Comment: -2? Are you joking? I was the first to find the problem and provide a working solution
Comment: I didn't dv you, but doing `parseFloat(x.toFixed(4))` is redundant, because it's the same as `x` (more or less).
Comment: Well, if `x.toFixed(4)` returns a String, then I don't think this is redundant, right?
Comment: Vault, i was working with GPS coordinates, and their format are double/float.

But i want to sum more values to each coordinate with some other values.

I appreciate your given solution , but i already fixed the bug. Check the previous responses so that you can learn too :).

Thank you once again for your fast response! :)

Kind Regards!

Is it me or i can't sum these?


Code::Blocks 16.01 Build Failed

Question: I am using 18.04.4 lts version of Ubuntu. I downloaded Code::Blocks from "Ubuntu Software" and didn't install any other package. I do not know if the packages required for development are installed.
This error:
||=== Build: Debug in Hello (compiler: GNU GCC Compiler) ===|
 obj/Debug/main.o||No such file or directory|
||error: no input files|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Comment: Please provide more information about you build environment: Which version of Ubuntu, died you install all required development packages for that build. Die you configure the project?
Comment: I am using 18.04 lts version of Ubuntu. I downloaded Code::Blocks from "Ubuntu Software" and didn't install any other package. I do not know what packages are required for development, I am an amateur user yet. "Die you configure the project?" > sorry, i didn't understand what you mean by that.
Comment: Ubuntu version was 18.04.4 lts
Comment: Please edit your question and add the new information in the question.
Comment: The file path references, such as: obj\Debug\main.o are giving an absolute path. What you probably want is: `.\obj\Debug\main.o` so you get a relative path based on the current directory. Your Code::Blocks and gcc installations in Ubuntu 18.04 seem to be OK for C programming language, but please note that for C++ you also need to install g++ package with `sudo apt install g++`
Comment: Thank you, i will check after that.
Answer: There is a long an details description on the code blocks wiki: Install Code Blocks from source on Linux
The process is not trivial and requires several steps before building the project with:

Read the wiki entry and follow the steps carefully
Download or checkout the source code
Bootstrap, configure, and make code blocks
$  ./bootstrap
$ ./configure
$ make

Use checkinstall, to generate and install a Debian package.
$ sudo checkinstall

Comment: Thanks for your answer, but I couldn't follow your suggestions. As I said, I'm new and the steps look complicated so I deleted Ubuntu and installed it again. This time there was no problem when I downloaded Code::Blocks from Ubuntu Software.
Answer: The file path references, such as: obj\Debug\main.o are giving an absolute path. What you probably want is: .\obj\Debug\main.o so you get a relative path based on the current directory. Your Code::Blocks and gcc installations in Ubuntu 18.04 seem to be OK for C programming language, but please note that for C++ you also need to install g++ package with sudo apt install g++

Code::Blocks 16.01 Build Failed


Compound mortise and tenon joints on corners (ie. legs of a table)

Question: I am playing around with the idea of doing a workbench that can be disassembled, using pinned mortise and tenon joints. I haven't found anything that could be used where two spans meet at a corner (leg) and be able to pin each one with a removeable pin.
I had a bit of a play around in Sketchup today and below is what I came up with - but I really want to know if this method would weaken the joins to the point where it's not worth doing?
The idea is that the pin on the end of the component on the right would pin the component on the left, therefore to assemble you would first slide the tenon on the left in, then the tenon on the right, then the pin through the tenon on the right to hold it all in place. Disassembly would be in the exact reverse.
Note that the pin to go through the hole on the component on the right is missing, but would have to be something that was either wedged or other to ensure it didn't move.
Also note that these will be 2x4 hardwood, for strength considerations.
Comment: Nuts and bolts make a strong, disassemblable joint. If your corner posts were 4x4, this *might* work. 2x4 are only 1.5" wide, which doesn't allow much material to work with.
Comment: I love the drawing, it shows a great concept. As already mentioned, it will split as soon as the legs are put under the stress that a bench would have under use. The sideways stresses would be its undoing. Metal to hold the assembly together is the way to go in theses types of situations.
Answer: I'd be worried about the wood splitting, especially in the beam on the right. That's only an inch or so of material to hold it firm.
If you disassemble the workbench then the largest piece will be the surface so you only need to keep the rest smaller than that. So I suggest assembling the short side permanently.
Then you can use a dado joint to attach the long beams and use a through dowel to be able to put a wedge in.
Comment: Sorry but I can't visualise that. Assemble the short side permanently how? Which do you envision is the short side? (should have specified, in mine the left is the short side, right goes across the front)

Any hint on your through dowel?

Otherwise I'm kind of leaning towards your idea of assembling the short side permanently - it makes sense, as the top is 1800x750 anyway, the short side will be as wide but shorter :)
Answer: One approach to take-down tusk-tenon (PDF)  (not what you are using, but look them up - much easier to actually get apart, yet very solid when set) wooden workbench design is to offset the rails vertically, so each has full bearing in the post. For a table, you could just offset the tenons (one is in the top half of its beam, the other is in the bottom half of its beam, and the tenons pass over/under each other) - that's probably too weak for a workbench.
If you want full support, you can offset by 4 or 5 inches for the part you tenon through, and then add the same amount on top. For better rigidity, cut a shallow groove or pocket (1/4" or so) in the face of the post that receives the full end-face of the beam. A workbench top that won't support itself between posts (especially the short direction) is perhaps a bit too thin.
I'm assuming you want to stay with all-wood - otherwise bed-bolts are very nice for take-down furniture, without too much hardware showing.


Should we decide on a general formatting style for references?

Question: There are already a couple of great suggestions on how you should reference articles. These have been summarized by Ben in one all encompassing answer.
From this another question arose how to properly format these references, particularly how to format the reference list at then end of an answer.
I suggest the following approach:

Up/down vote this question in order to reflect your opinion on whether we need a formatting style.
Post suggested formatting styles as an answer, using the actual content of the following answer, applying the formatting of your preference.
Up/down vote the answers which represent the formatting you like.

From wikipedia:
Maslow's hierarchy of needs is a theory in psychology, proposed by Abraham Maslow in his 1943 paper A Theory of Human Motivation. [ 2]
Neher (1991, FREE PDF) summarises and critically evaluates the theory.
  From the abstract:
This critique of Maslow's theory of motivation examines all of its
  major components. The theory is summarized and its basic propositions
  are analyzed in the light of internal logic, other relevant theories,
  and related research. This examination points up many deficiencies in
  Maslow's theory, which enjoys wide acceptance, especially among
  humanistic psychologists. Suggestions are made regarding modifications
  to the theory that would remedy many of its more serious problems but
  at the same time preserve its perceptive insights.
The lack of empirical evidence was already discussed in an older article by Wahba et al. (1976).
The uncritical acceptance of Maslow's need hierarchy theory despite
  the lack of empirical evidence is discussed and the need for a review
  of recent empirical evidence is emphasized. A review of ten
  factor-analytic and three ranking studies testing Maslow's theory
  showed only partial support for the concept of need hierarchy. A large
  number of cross-sectional studies showed no clear evidence for
  Maslow's deprivation/domination proposition except with regard to
  self-actualization. Longitudinal studies testing Maslow's
  gratification/activation proposition showed no support, and the
  limited support received from cross-sectional studies is questionable
  due to numerous measurement problems. The difficulties with testing
  the theory are discussed and the conceptual, methodological, and
  measurement problems of the studies reviewed are detailed. The
  implications of the findings and future directions for research are
  outlined.
References
Neher, A. (1991). Maslow's theory of motivation: A
  critique. Journal of Humanistic Psycholgoy, 31, 3. FREE PDF
Mahmoud A. Wahba, Lawrence G. Bridwell, Maslow reconsidered: A review of research on the need hierarchy theory (1976), or a free pdf scan here

The content of this example answer was shamelessly copied from two answers to a real CogSci question.
Comment: @ArtemKaznatcheev I think for a site attempting to court academics (and in general) it makes much more sense to specify and maintain a specific structure for references (which will be in the majority of answers)
Comment: we should ask people to format references clearly (I suspect most will use something resembling APA because they are familiar with it), but having an official policy will cause needless editing of decent questions and answers.
Comment: @BenBrocka cstheory has successfully courted academics and it does not enforce a citation style. I don't think academics care all that much about a consistent citation style (I know I don't) but they care about the quality of questions and answers.
Comment: Also, it's currently framed as an encouraged style; if anyone is willing to take the time  to edit other people's questions or answers to improve the referencing, that sounds great to me. If people don't provide thorough references, the answer can still be good.
Comment: Another way to move forward on this is to also discuss particular issues related to referencing and then absorb these decisions into Ben's overall answer.
Comment: @JeromyAnglim: I agree we should first wait a while until we have reached a consensus (as far is possible on meta) on [Ben's answer](http://meta.cogsci.stackexchange.com/a/168/21) before starting to edit answers to reflect this post. This question is meant **solely** to address the _formatting_ issues.
Comment: Furthermore, because we establish a _preferred_ style, doesn't mean you are supposed to go through our history of posts and start editing all of them. We inherit standard editing guidelines from the SE network. I'll clarify this in this question and start a new post related to editing guidelines specific to our site.
Answer: The issue of style for the references section has come up. I still find the  subscript method to be superior to the blockquote or References header as it deemphasizes the reference section rather than emphasizing it. The reference section should be easy to locate and read but should not catch the eye like bold and blockquotes do.
References
 Neher, A. (1991). Maslow's theory of motivation: A critique. Journal of Humanistic Psycholgoy, 31, 3. FREE PDF
Mahmoud A. Wahba, Lawrence G. Bridwell, Maslow reconsidered: A review of research on the need hierarchy theory (1976), or a free pdf scan here
Best I can tell, blockquote was preferred because someone thought each reference would have to be wrapped in  tags but this is not the case; as you can see from the source of this post, only one set of tags is needed, but lines need to be broken by two spaces and a return at the end of a line, not two returns.
Comment: As I mentioned in chat though, I'm not sure why the double return paragraph break messes this up, I'm not sure it should.
Comment: _" someone thought each reference would have to be wrapped in  tags"_ ... that would have been me. :) Thanks for pointing out a way around this.
Comment: I asked about it [on meta](http://meta.stackexchange.com/q/123097/157047).
Comment: This [meta answer](http://meta.stackexchange.com/a/123100/157047) makes it clear this is by design.


Key based SSH login that requires both key AND password

Question: My problem is :
I developed successfully RSA Key based ssh login on board from system.
When a client logs in for the first time, ask about private key and passphrase also which works fine.
In second time login, ssh doesn't ask private key or password, directly login on board.
Client side use Ubuntu 16.04 and on board customizes Ubuntu.
First time login with below command:
ssh -i ~/.ssh/id_rsa user@board_ip   //works fine
Second time:
ssh user@board_ip  //never ask password and public key - problem
First time:
ssh user@board_ip  //not able to login without key - works fine
As per my understanding, I made a mistake in the sshd_config file on the board.
I played with below settings but failed it all the time.
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
#PasswordAuthentication yes
PermitEmptyPasswords no

Project requirement is secure login, mainly on ssh.
To achive more security SSH password based login, we shifted to key based login.
As explain above after change all configuration.
SSH login require private key and password also.
After logout and after sometime login again, ssh doesn't require key or password, project requirement need key and password each and everytime.
Comment: It sounds more like the credentials are being cached by your ssh agent than a mistake in the configuration
Comment: The "problem" you are having is that ssh-agent is storing the key and password. see https://askubuntu.com/questions/737251/ssh-agent-what-does-this-process-do/737255 and similar. ssh and ssh-server are functioning normal this is not a configuration problem.
Comment: @steeldriver post that as an answer
Comment: @user68186 : As per requirement of project for more security, need key and password in every ssh attempt. first time for any reason user login and logout then some one use this system and try to login at that time for security password and key must require.
Comment: Disable ssh-agent from running at startup on client system. Then probably you will have to retype the passphrase every time you attempt a ssh connection. The default in Ubuntu is to have the ssh-agent enabled and the function of ssh-agent is **exactly** to remember the passphrase typed on first ssh connection attempt, so you don't have to retype it every time.
Answer: There are two ways to configure ssh to require both a public key and a password or passphrase.
The difference between the password and the passphrase:
The password in this context is the password assigned to the user in the server computer (the board). If the board has only one user account, then it will have only one password. If the board has multiple user accounts, they should have their unique passwords.
The passphrase is linked to the private key in the client (local) computer, not to the remote server (board) computer. Thus, if you use two different client computers of devices to ssh from, then you will have to create a passphrases for the private keys stored in each local computer. Similarly, if two different users need to ssh to the server (board) from their own respective local computers, they will need their own private-public key pairs and own passphrase to unlock their respective private keys.
For example, say you and I need to ssh to the same server computer (the board) from our own laptops. You will have your own private key and a passphrase for that private key. I will have my own private key and its passphrase. The upshot of this arrangement is, I can change the passphrase of my private key any time without telling you, or changing anything to the server computer (the board). I can even remove the passphrase from my private key without telling you.
The other scenario is, if I have multiple servers to ssh to and if I use the same private key to authenticate myself to all the servers, I will need to use the same passphrase to access ssh in all the servers I work with, not just your board.
Method 1. Public Key with passphrase
Reference: https://help.ubuntu.com/community/SSH/OpenSSH/Keys
Step 1. Add a passphrase to the existing public-private keyfor each client and user combinations
For each user on each client computer or device use the following command to generate a passphrase for the exiting public-private key pair:
ssh-keygen -p

You wil be prompted for the the location where to keep the files. Hit enter to accept the default location.
If you already have a passphrase set, you will be asked to enter the existing passphrase. In that case you have already done this step. Press Ctrl+C to stop the process.
Next you will be prompted to enter a new passphrase. Do not hit Enter! Enter a long and difficult to guess passphrase that is easy to remember. You will be asked to re-enter the passphrase.
If you don't have an existing public-private key pair, use the following command to generate it. You will be prompted to add a passphrase if you need one:
ssh-keygen -t rsa

Every time you try to login to the ssh server, you will be asked to enter this passphrase. This can be different for the user password of the ssh server. Each user can have their own passphrase. If an user needs to login from different clients  (laptop, phone, etc.) she will need to repeat this process for each client. She can choose different passphrase for different clients.
Step 2. Copy the public key to the server only if the key is new
In your client computer enter:
ssh-copy-id -i ~/.ssh/id_rsa.pub user@board_ip

It will ask for the password of the user in the remote server. Remember, password based login must be enabled for this to work.
Repeat for all the users and all client devices.
Step 3. Test if it works
Try to login to the server by entering:
ssh user@board_ip

If all goes well, you will be prompted to enter the passphrase you created in step 2. This is not the user password you were asked in step 3.
If you see the prompt to enter the user password, then something is not right.  Do not proceed to the next step, until you get this working.
Step 4. Disable password based login
Once each user and their respective client devices have their own public-private key pairs and respective passphrases of their choice, you won't need the password based login. It is best to disable this method. Keeping it enabled will allow anyone without the public-private key pair to try to guess the password of the user@board-ip.
In the ssh server, the board, edit the file /etc/ssh/sshd_config and change:
#PasswordAuthentication yes

to read:
PasswordAuthentication no

Note, the # is not there in the second line and the yes is now no.
Restart the ssh service in the server by:
sudo service ssh restart

If this does not work, reboot the board.
It is done. The passphrase is cached in the client probably by Gnome-Keyring until the user logs out of the local computer. Thus, the phass-phrase is asked only once per session.
What comes next is another alternative. You need to do either 1 or 2.
Method 2. Public key and user password both required
Reference: https://security.stackexchange.com/questions/17931/possible-to-use-both-private-key-and-password-authentication-for-ssh-login
Step 1. Remove passphrase from Private key if present, for each client and user combinations
For each user on each client computer or device use the following command to remove the existing passphrase for each public-private key pair:
ssh-keygen -p

You will be prompted for the the location where to keep the files. Hit enter to accept the default location.
If you have an existing passphrase you will be asked to enter it. If you don't get prompted for existing passphrase, you are done. Press Ctrl+C to stop the process.
Otherwise enter the existing passphrase and continue.
Next you will be prompted to enter a passphrase. Hit Enter twice to remove the existing passphrase from the private key.
If you don't have an existing public-private key pair, use the following command to generate it. You will be prompted to add a passphrase if you need one:
ssh-keygen -t rsa

If an user needs to login from different clients  (laptop, phone, etc.) she will need to repeat this process for each client.
Step 2. Copy the public key to the server only if the key is new
In your client computer enter:
ssh-copy-id -i ~/.ssh/id_rsa.pub user@board_ip

It will ask for the password of the user in the remote server. Remember, password based login must be enabled for this to work.
Repeat for all the users and all client devices.
Step 3. Test if public keys are being used
Try to login to the server by entering:
ssh user@board_ip

If all goes well, you will not be prompted to enter any password or passphrase.  This is normal. This shows that the public key is properly installed in the ssh server (the board) and it is working. We will change the setting so that it asks for the password again in the next step.
Step 4. Setup for both public key and password
Login to the ssh server (the board) and edit the /etc/ssh/sshd_config file. Add the following line in the file:
AuthenticationMethods "publickey,password"

Warning: Make sure the the PasswordAuthentication looks like:
#PasswordAuthentication yes

This is the default behavior. You may choose to keep or remove the # in the beginning. However, if this setting is set to no along with the line you just added, then nobody will be able to login to the server using ssh. If you get locked out, you will have to physically go to the remote server, hook it up to keyboard, monitor, etc. and login locally and edit this file to fix the problem.
End Warning
Restart the ssh service in the server by:
sudo service ssh restart

If this does not work, reboot the board.
Step 5. Test breaking in
Find a new computer or login to the client computer using a new username, say user2. This user should not have any public-private key pairs in his /home/$USER/.ssh/ folder. We will pretend that user2 is the hacker who has somehow found out the password of user@board_ip and try to ssh into that system.
Enter as user2, from the client computer:
ssh user@board_ip

If you can login with just the password, then it did not work. Anyone who has the password or can guess it, can login to the board. They do not need the key.
If you get a permission denied and login fails, then the double authentication of public key and password works.
Hope this helps
Comment: No need to remove passphrase from private key, so you have the opportunity to be protected by 2 passwords at the same time: for key and for user.
Answer: The issue is that ~/.ssh/id_rsa is the default home for an SSH public key in Ubuntu. Therefore you don't have to include -i ~/.ssh/id_rsa in your SSH command after the key exchange has happened, to use the id_rsa keypair.
To avoid this behaviour create the SSH keypair with a different name, then it will only be used when you specify it with the -i option.
Example:
If you create the key with the name user_ssh_rsa in user's home directory:
ssh-keygen -t rsa -f ~/.ssh/user_ssh_rsa

Then exchange the key with the remote server, entering the password for the user on the remote system when prompted:
ssh-copy-id -i ~/.ssh/user_ssh_rsa user@board_ip

Logging in with:
ssh -i ~/.ssh/user_ssh_rsa user@board_ip

Will login without prompting for password, as it's using the newly created key.
Using:
ssh -user@board_ip

Will prompt for the password, as the keypair is not found automatically.
This does depend on having removed the already shared key at ~/.ssh/id_rsa
Comment: Did you remove id_rsa and id_rsa.pub? Otherwise it must be an ssh-agent caching issue.
Comment: I tried with both options, first I rename id_rsa and second rename and change location of id_rsa and also delete permanently id_rsa from ~/.ssh/ location, but same result. ssh allow access without key and password.
I want security in every ssh login attempt.
Comment: I removed private key but didn't touch public key.
Comment: I think you'd need to remove both.


Panel labeling conventions

Question: I'm in WA state. PoCo is Mason PUD #1. AHJ is WA L&I. I recently had my first inspection after replacing meter box, breaker panel, lots of house wiring. Only flunked for 7 things. One of them was "label panel circuits and mount cover with 2 screws for next inspection". I left the cover off so they could see inside. I didn't label the circuits in case they told me I needed to change any. Go figure.
I want the labels on the panel to be meaningful to me, to the inspector, and to the next poor person who has to figure out what they mean. I'm looking for any/all suggestions for what you all use. E.g., What abbreviations would be easily understood? What details are important to list? Most circuits are straightforward (e.g., just refrigerator, just microwave). A few are more complex (e.g., living room receptacles and lights, dining room ceiling fan). Once I get some suggestions, I'll use them to describe the complex ones - perhaps then I can get feedback on them (hopefully not feedback saying just don't do that, but if so, I'd rather know now than at the next inspection).
And to answer questions that may come up on the complex ones, this was a remodel. Some walls had drywall, some had T&G wood, some had tile. As much as possible, I didn't want to have to open walls. I straightened things out as much as I could without going to excessive lengths. So, somethings may be a bit strange, but if they are just plain wrong (i.e., not code compliant), I'd love to know.
Answer: Rooms without a clear, unlikely to change, definable purpose (i.e kitchen, bathrooms, etc) are better referred to by compass direction than current function (2nd Fl NW rather than christy's bedroom or guest room or office...) and likewise if there are multiple bathrooms per floor, say.
Or, go commercial, print out a floorplan, assign numbers to rooms, and use that. If doing that, convention is 3 digits and the first is the floor, even if there are not more than 9 rooms per floor.
(not that it helps with inspection, but it can help YOU or future owner if you also label each outlet/switch with a breaker number - under the faceplate if you don't want to see it normally.)
Comment: I like the breaker label idea. I can put it on the inside of the face plate. For GFCI/AFCI controlled receptacles (which are almost all these days), I can also list the location of the reset. I've wasted so much time trying to find those. The house is only 1026 ft^2, so I think I'll skip the floorplan :). Looks like I need to find my compass :)
Answer: You don't need to name every single outlet. Just a descriptor that covers most of the outlets.
You also must use labels that make sense to people not your family: so "Angie's Room" is Right Out.
Comment: It doesn't have to be perfect @TomGetzinger, Code is just looking for more than nothing.  If you want to deep-drill, feel free to expand into a second sheet.
Comment: Unless there is a nameplate saying "Angie's Room" outside the area right?
Comment: @Harper, I agree I wouldn't use people names. It's pretty obvious which is main vs. guest bedroom - baths are a little more vague, so I kinda like the compass direction idea above. As for covering most outlets... I have one circuit that covers all (2) receptacles in the dining room and all lights in both bedrooms. More lights that receptacles, so I could say "Bedroom lites", but then someone looking for which breaker covers the dining room receptacles would be at a loss. For this, I thinking "DR rec., Bdrm lites" (I'll be wordier if space allows, maybe "Din Rm rec., Bdrm lites" or more).
Comment: Most complex case is living room lights and receptacles, dining room ceiling fan, deck (exterior) light. Shortest I'm thinking is "LR, DR Fan, Deck Lite", then getting more verbose on rooms, space permitting, in case LR and DR are not commonly understood.

Panel labeling conventions


Are the following const function equivalent?

Question: My question is simple. I was programing a getter when I noticed that I forgot the last const in my expression. But while I was writing it, I doubted: I know that in const function you can't change the returned element, so in the second one the is const std::vector implicit?
const std::vector<int> foo() const{}
std::vector<int> foo() const{}

Comment: you can return whatever you like from a const function, you just cant change the object its invoked on
Comment: Since the returned `vector` is a value, a copy, you can fold it, spindle it, and mutilate it without affecting the instance you got the copy from. The trailing `const` is satisfied.
Comment: the fact that you did not change this inside foo.  https://stackoverflow.com/questions/751681/meaning-of-const-last-in-a-function-declaration-of-a-class
Comment: It will be returning a copy by the way and that's missing from the body also there shouldn't be semicolons at the ends there.
Comment: That's true, I'm going to edit the question @pm100
Comment: I seem to remember returning a `const` value prevents Return Value Optimization, but I'm not sure if that's still true.
Comment: no the const is not implicit, you are returning a writable vector
Comment: the compiler will tell you if you try to do something invalid when you declare a function const
Comment: so if I'm returning a writable vector, what guarentee the const at the finish of the function? @pm100
Answer: You can return non-const values. You cannot return a non-const reference. Both of these functions return a copy, thus the const for the return type is not required.
If you were to return
std::vector<int> &

Then you would need the const.
Answer: Your concern is that if you are rturning a reference to data from within the object does that have to be const. Yes. This
class Test {
    int m_num;
public:
    int& getNum()   const { return m_num; }
};

does not compile. You need
class Test {
    int m_num;
public:
    const int& getNum()   const { return m_num; }
};

your case with a vector
class Test {
    int m_num;
    std::vector<int> m_vec;
public:
    const int& getNum()   const { return m_num; }
    std::vector<int> getVec()   const { return m_vec; }
};

works fine because you are returning a copy
but this is not ok
class Test {
    int m_num;
    std::vector<int> m_vec;
public:
    const int& getNum()   const { return m_num; }
    std::vector<int> & getVec()   const { return m_vec; }
};

has to be
class Test {
    int m_num;
    std::vector<int> m_vec;
public:
    const int& getNum()   const { return m_num; }
    const std::vector<int> & getVec()   const { return m_vec; }
};


javascript with textarea input correspondingly text area output - no button clicks

Question: I have seen some pages in which we can input in textarea and correspondingly an output gets displayed for it
no button clicks in between , see an example here http://ntools.infoexpo.in/p/html-to-xml-encoder_4042.html
how to apply this type in the below code
html:
<textarea  id="source"  placeholder="Text Entry."></textarea>

js
function myFunction()
{
var str = document.getElementById('source').value;

var len = str.length;
    document.getElementById("result").innerHTML="<textarea>"+len+"</textarea>";

}

Comment: So what you want actually?
Answer: Try this code

<textarea id="one" onKeyUp="showtext(this)"></textarea>
<textarea id="two"></textarea>

Comment: Include an entire library to select an element? What's wrong with `getElementById()`?
Comment: Just thought this would be helpful in case of any extended requirement.  Otherwise, getElementById will suffice :)
Answer: It is pure javascript,I think you should learn a bit of javascript,but i will show you the sample
<textarea id="t1" onkeyup="document.getElementById('t2').value=this.value" ></textarea>
<textarea rows="4" cols="50" id="t2" ></textarea>

DEMO
Comment: so for example in first textarea i take userinput and in second textarea want to show result - the length of text -- what should i do?
Comment: @Sreeraj: that is what is in the DEMO,did you check the demo ?
Comment: how to apply it on this        html-
                        js-  function myFunction()

{
var str = document.getElementById('source').value;

var len = str.length;
    document.getElementById("result").innerHTML=""+len+"";

}


Swift TabBarController not correctly deallocate?

Question: I create a custom TabBarController and add a few buttons with images on them.
But i found that every time i load the TabBarController without doing anything and immediately dismiss it, the memory is increased permanently. I couldn't find any problems in my code. Please help. Thanks in advance!
<code>    class CustomTabBarController: UITabBarController {

    var menuButton: UIButton!
    var announcementButton : UIButton!
    var broadcastButton: UIButton!
    var toDoListButton: UIButton!
    var plusMenuBool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        let newInfo = UIImage(named: "info")!.imageResize(sizeChange: CGSize(width: 30, height: 30))
        self.viewControllers![0].tabBarItem.image = newInfo

        let newChat = UIImage(named: "chat")!.imageResize(sizeChange: CGSize(width: 30, height: 30))
        self.viewControllers![1].tabBarItem.image = newChat

        self.setupMiddleButton()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setupMiddleButton() {
        // menuButton
        menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
        var menuButtonFrame = menuButton.frame
        menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height
        menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2
        menuButton.frame = menuButtonFrame

        // announcementButton
        announcementButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        var announcementButtonFrame = announcementButton.frame
        announcementButtonFrame.origin.y = self.view.bounds.height - announcementButtonFrame.height
        announcementButtonFrame.origin.x = self.view.bounds.width/2 - announcementButtonFrame.size.width/2
        announcementButton.frame = announcementButtonFrame

        self.announcementButton.layer.anchorPoint = CGPoint(x: 0.5, y: 3.5)
        announcementButton.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI*3/4))

        // broadcastButton
        broadcastButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        var broadcastButtonFrame = broadcastButton.frame
        broadcastButtonFrame.origin.y = self.view.bounds.height - broadcastButtonFrame.height
        broadcastButtonFrame.origin.x = self.view.bounds.width/2 - broadcastButtonFrame.size.width/2
        broadcastButton.frame = broadcastButtonFrame

        self.broadcastButton.layer.anchorPoint = CGPoint(x: 0.5, y: 3.5)
        broadcastButton.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))

        // toDoListButton
        toDoListButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        var toDoListButtonFrame = toDoListButton.frame
        toDoListButtonFrame.origin.y = self.view.bounds.height - toDoListButtonFrame.height
        toDoListButtonFrame.origin.x = self.view.bounds.width/2 - toDoListButtonFrame.size.width/2
        toDoListButton.frame = toDoListButtonFrame

        self.toDoListButton.layer.anchorPoint = CGPoint(x: 0.5, y: 3.5)
        toDoListButton.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI+M_PI/4))

        // addSubView
        menuButton.layer.cornerRadius = menuButtonFrame.height/2
        announcementButton.layer.cornerRadius = announcementButtonFrame.height/2
        broadcastButton.layer.cornerRadius = announcementButtonFrame.height/2
        toDoListButton.layer.cornerRadius = announcementButtonFrame.height/2
        self.view.addSubview(menuButton)
        self.view.addSubview(announcementButton)
        self.view.addSubview(broadcastButton)
        self.view.addSubview(toDoListButton)

        menuButton.setImage(UIImage(named: "plus"), for: UIControlState.normal)
        menuButton.addTarget(self, action: #selector(self.menuButtonAction(sender:)), for: UIControlEvents.touchUpInside)
        announcementButton.setImage(UIImage(named: "announcement"), for: .normal)
        announcementButton.addTarget(self, action: #selector(self.announcementButtonAction(sender:)), for: UIControlEvents.touchUpInside)
        broadcastButton.setImage(UIImage(named: "broadcast"), for: .normal)
        broadcastButton.addTarget(self, action: #selector(self.broadcastButtonAction(sender:)), for: UIControlEvents.touchUpInside)
        toDoListButton.setImage(UIImage(named: "toDoList"), for: .normal)
        toDoListButton.addTarget(self, action: #selector(self.toDoListButtonAction(sender:)), for: UIControlEvents.touchUpInside)

        self.view.layoutIfNeeded()
    }
}
</code>
Answer: Check out memory management in swift.

To make sure that instances don't disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

In short you can do one of the below things:

Check if the tabBar is getting deallocated. Simply dismissing does not guarantee that.
Even if the tabBar is deallocated, you will not see the memory decrease immediately.
Check if some other object is referencing the tabBar. This might cause the tabBar to hang around since ARC would think that you might need the reference.
Comment: I indeed have its child holding strong reference to it self! Changing it to weak solves the issue.
Comment: Can you mark my answer as correct if that solves your issue?
Answer: I figured out that the tabBarController's child viewController has a "strong" reference to its parent tabBarController. After I changed it to weak, the tabBarController is deallocated correctly!


Why can't I suppress Android lint via comment

Question: For some lint checks I can suppress them with a comment or a method annotation. ConstantConditions is a good example:

However for other checks I can only suppress via a method annotation. CheckResult is an example.

Is there any reason for this difference? Is it just that Android tools team hasn't added a comment-based suppression check?
Comment: Just making sure you are aware of this page: https://developer.android.com/studio/write/lint
Comment: @MorrisonChang yep. I'm familiar with the lint docs. What specifically on that page do you think answers my question?
Answer: Basically, Android Studio comes with a two sets of inspections:

inspections from Intellij IDEA
inspections from Android Lint

So, ConstantConditions is an Intellij IDEA inspection, and CheckResult is coming from Android Lint.
I think the reason that Android Lint checks usually disabled with @SuppressLint annotation is just that it's technically easier to understand that check is suppressed or not for a particular source code element.
Actually, you can suppress a check will comment like this:
//noinspection CheckResult

But it only works when running lint from the command line, but not in Android Studio.


Web Based Monitoring App for Simple Java Application

Question: I have created a small java application(myapp.jar). This is a multi threaded application and We are going to run it on multiple machines(Separate instance for each machine). Now I want to create a remote interface so I can start, stop, monitor this application from a remote machine (most probably using Web Console). By monitoring I mean
   1. Whether this application is running on that machine or not?
   2. If its not running that Web console should provide capabilities to Start it.
   3. If its running then

--Web console should provide capabilities to stop execution
   --System should tell me value of different parameter like how many threads are running, value of some local parameter of my execution.
In which technology I should design this monitoring application. If there is any open source available to do this then please let me know. I heard about JAMon api but dont know how it can be useful.
Answer: So you'd want a server machine that had this web interface to manage all the clients.  The clients would talk to this server through a web service, say polling it every 10 minutes or something.  You could then turn off and on these clients and when they poll the server, they'd know whether to start/stop etc.
Rather than going for some framework to setup the communications like JMS, I'd just say a HTTP web service over REST/SOAP should work fine for the clients to poll the server.
There's a question though on what should the clients do if they can't send to the server, maybe some local in memory DB like Derby would make sense for them to collect the messages.


I am having this " throw new RangeError('BITFIELD_INVALID', bit);" error; and i just can not find the solution

Question: I keep getting this error:
        throw new RangeError('BITFIELD_INVALID', bit);
    ^

RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number: undefined.
    at Function.resolve (I:\DiscordManagment\ReactionRolesAnimeHub\node_modules\←[4mdiscord.js←[24m\src\util\BitField.js:152:11)
    at I:\DiscordManagment\ReactionRolesAnimeHub\node_modules\←[4mdiscord.js←[24m\src\util\BitField.js:147:54
    at Array.map (<anonymous>)
    at Function.resolve (I:\DiscordManagment\ReactionRolesAnimeHub\node_modules\←[4mdiscord.js←[24m\src\util\BitField.js:147:40)
    at Client._validateOptions (I:\DiscordManagment\ReactionRolesAnimeHub\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:546:33)
    at new Client (I:\DiscordManagment\ReactionRolesAnimeHub\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:73:10)
    at Object.<anonymous> (I:\DiscordManagment\ReactionRolesAnimeHub\main.js:5:16)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1072:14)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:937:32)←[39m {
  [←[32mSymbol(code)←[39m]: ←[32m'BITFIELD_INVALID'←[39m
}
_____

I have been searching for the messed up and outdated variable but i can not seem to find nor find a solution to this issue. Can someone help me please> This bot's function is to auto add roles to someone when they react to an emoji below the message. For a self role system. I have been at this for a while trying to weed out the bugs. However this is a bug that i can not find the solution for in my code.

const Discord = require('discord.js');

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.message, Intents.channel, Intents.reaction] });
const prefix = '-';

const fs = require('fs');

client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);

    client.commands.set(command.name, command);
}

client.on('ready', () => {
    console.log('bot is online!');
});

client.on('message', message => {

    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();
    if (command === 'ping') {
        client.commands.get('ping').excecute(message, args);
    }
    if (command === 'reactionrole') {
        client.commands.get('reactionrole').execute(message, args, Discord, client);
    }

});

client.login('');

module.exports = {
    name: 'reactionrole',
    description: "Sets up a reaction role message!",
    async execute(message, args, Discord, client) {
        const channel = '876575997338742786';
        const extrovertRole = message.guild.roles.cache.find(role => role.name === "Extrovert");
        const introvertRole = message.guild.roles.cache.find(role => role.name === "Introvert");

        const hotFaceEmoji = ':hot_face:';
        const coldFaceEmoji = ':cold_face:';

        let embed = new Discord.MessageEmbed()
            .setColor('#e42643')
            .setTitle('What kind of personality do you havc?')
            .setDescription('Choosing a personality allows people to know how to approach you/n/n'
                + `${hotFaceEmoji} for Extrovert \n`
                + `${coldFaceEmoji} for Introvert`);

        let messageEmbed = await message.channel.send(embed);
        messageEmbed.react(hotFaceEmoji);
        messageEmbed.react(coldFaceEmoji);

        client.on('messageReactionAdd', async (reaction, user) => {
            if (reaction.message.partial) await reaction.message.fetch();
            if (reaction.partial) await reaction.fetch();
            if (user.bot) return;
            if (!reaction.message.guild) return;

            if (reaction.message.channel.id == channel) {
                if (reaction.emoji.name === hotFaceEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(extrovertRole);
                }
                if (reaction.emoji.name === coldFaceEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.add(introvertRole);
                }
            } else {
                return;
            }

        });

        client.on('messageReactionRemove', async (reaction, user) => {

            if (reaction.message.partial) await reaction.message.fetch();
            if (reaction.partial) await reaction.fetch();
            if (user.bot) return;
            if (!reaction.message.guild) return;

            if (reaction.message.channel.id == channel) {
                if (reaction.emoji.name === hotFaceEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(extrovertRole);
                }
                if (reaction.emoji.name === coldFaceEmoji) {
                    await reaction.message.guild.members.cache.get(user.id).roles.remove(introvertRole);
                }
            } else {
                return;
            }
        });
    }

}

Comment: Look at the error stack `at Object. (I:\DiscordManagment\ReactionRolesAnimeHub\main.js:5:16)`. It looks like the error is in line `const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.message, Intents.channel, Intents.reaction] });`
Answer: Try replacing the following and see if it works.

Replace Intents.message with Intents.FLAGS.GUILD_MESSAGES
Replace Intents.channel with Intents.FLAGS.GUILDS
Replace Intents.reaction with Intents.FLAGS.GUILD_MESSAGE_REACTIONS

Refer this in the Discord Documentation for more info. Perhaps, it may help you in finding something else as well.
Answer: I had the same problem, but I used this format, and it worked for me:
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });


Discrete Math Strings

Question: Question: 7. A string that is obtained by rearranging the letters of the word
BOOGER is called awesome, if the string does not contain the substring OO. Thus, GEOROB is awesome, whereas GREOOB is not awesome. What is the number of awesome strings?
Answer: (6 * 5C2 * 3 * 2 * 1)
Attempt: What I did was calculate the number of ways the string contains the substring OO, which I found to be 5!, I treated OO as one letter. Then I subtracted it from the total number of possible substrings 6!.I'm not sure where I went wrong, would appreciate any help.
Comment: Are you saying you obtained $600$ and the book's answer is $360$?
Comment: I don't think either you or the book is right. I think the answer is $240$. If I understand the problem correctly, which is hardly a foregone conclusion. Maybe I can ask a clarifying question: What do you think the answer would be if I asked how many awesome permutations there are of BOO? Of BOOR?
Comment: Yes. The answer is 360, but I'm getting 600.
Comment: Sorry, I just checked again and I confused it with another answer. It is 240. To answer your question, would that be 2!.
Comment: No, it isn't $2$. Try listing out the awesome permutations of BOO and of BOOR. There are not that many. In fact, while you're at it, list *all* the permutations of BOO and of BOOR. That may help you see why your approach, even though it is sound in principle, isn't yielding the right answer. ¶ By the way, if you suddenly get it, please resist the urge to delete the question. It can be useful for future readers.
Comment: Can't you have RBOO and BOOR?
Comment: Aren't those both non-awesome? I thought the awesome ones were the ones without consecutive O's. I'll post an answer; you can check to see if it answers the question the way you want.
Comment: Oh sorry. I was thinking you were asking a different type of question. I wrote it out so ROBO, OROB, OBOR, BORO,
Comment: You're missing ORBO and OBRO, so a total of $6$. My answer shows how to get this as either $4!/2-3! = 12-6 = 6$ (which is your approach, only suitably fixed) or $3 \times 2 = 6$.
Comment: Oh, I see it now. Thank You Very Much!
Comment: Incidentally, a minor language issue that may confuse some readers: We would typically say "I subtracted it *from* the total number..." rather than "I subtracted it by the total number..."
Answer: The answer is $240$, which (as the comments indicate) is actually the result the OP's book provides. Here are two ways to obtain that answer:
First, to apply the method the OP uses, we need only fix one minor error—there are not $6! = 720$ different permutations of BOOGER, but only $6!/2 = 360$. The reason is that the two O's are not distinguishable. If we permute BO$_1\!$O$_2\!$GER, there are $720$ different sequences, but in ordinary text, there is no difference between BO$_1\!$O$_2\!$GER and BO$_2\!$O$_1\!$GER, and in general, each permutation of BO$_1\!$O$_2\!$GER has an indistinguishable "twin". Therefore, the correct answer is $6!/2 - 5! = 360-120 = 240$.
A second approach is to first decide where to put the two O's. There are ten possibilities: OXOXXX, OXXOXX, OXXXOX, OXXXXO, XOXOXX, XOXXOX, XOXXXO, XXOXOX, XXOXXO, and XXXOXO. The remaining four spots (marked by X's above) can be replaced by the four remaining letters B, G, E, and R in $4! = 24$ different ways. So the number of awesome permutations is $10 \times 24 = 240$.
Answer: Permute $BGER$ in $4!$ ways and punch holes at two of the five uparrows $\uparrow B \uparrow G \uparrow E \uparrow R \uparrow$  for the two $O's$ to get the corrected answer of $4!\binom 52 =240$

Discrete Math Strings


GKE Clusters no indication within metrics or logs after failure

Question: We are using Google Cloud Platform and our GKE clusters has had multiple "node auto repair" events occur within the last 48 hours, and we can find no indication within the metrics, nor in the logs, that might explain why the control plane required it to do so.
How can I debug this ?
No support from Google team
Comment: Do you have master logs enabled for your cluster?
Answer: It may be worth to check out this answer
Also, by any chance if you have enabled master logs for your cluster check with NodeNotReady keyword or track node's different metrics in metric explorer.
I have came across many situations where users fail to apply resources limit and that results in such node behaviour
Comment: We are already checking the logs and are not able to find out why the node repair was required.
Comment: Regular logs will not be of much use, but the kube-controller-manager logs will provide a clearer picture. I would recommend contacting GCP support, as they likely have more visibility into this issue.
Answer: Try to run the gcloud command below to see the repair events
gcloud container operations list


Typescript Metronome

Question: I'm trying to build a metronome with Typescript (and Angular 2).
Thanks, to @Nitzan-Tomer (Typescript Loop with Delay), who helped me with the basics.
Now I'm facing the issue, that after I started the metronome, I'm not able to change the interval. Imagine a slider, changing the speed between the sounds (=> interval).
let theLoop: (i: number) => void = (i: number) => {
    setTimeout(() => {
        metronome.play();
        if (--i) {
            theLoop(i);
        }
    }, 3000);
};

theLoop(10);

The interval here is 3000. And I want to be able to change it, after the function was triggered. (Maybe also get rid of the i: number? Because it shouldn't just play the metronome-sound 10 times...
I thought of a class? But I'm not sure how to build it...
Comment: Possible duplicate of [Changing the interval of SetInterval while it's running](http://stackoverflow.com/questions/1280263/changing-the-interval-of-setinterval-while-its-running)
Comment: Not specifically about the question but I suggest you use more descriptive function names. `theLoop` doesn't tell the reader what your function does. Something like `startMetronomeCycle()` might be better.
Comment: Unfortunately they're using SetInterval and the DOM... I try to build a plain javascript/typescript/angular2 metronome.
Answer: Here's a simple class to do it:
class Metronome {
    private interval: number;
    private timer: number;

    constructor(interval = 3000) {
        this.interval = interval;
    }

    start(): void {
        this.tick();
    }

    stop() {
        clearTimeout(this.timer);
    }

    setInterval(interval: number) {
        this.interval = interval;
    }

    private tick() {
        // do something here
        this.timer = setTimeout(this.tick.bind(this), this.interval);
    }
}

(code in playground)
Comment: I think it's wise to separate the two. The `tick` method is being called repeatedly, and the `start` method is the symmetric counterpart of `stop`. Also, you might want to do more things in `start` which you won't want to repeat.
Comment: Why don't you implement the `setInterval(interval: number)` directly into `start(interval: number)`?

Typescript Metronome


Catching User Input in discord.js for a Rock, Paper, Scissors Application

Question: I am trying to create a discord.js bot that has a Rock, Paper, Scissors command. The code below is my last attempt at catching a user response.
The response after the command does not have a prefix and I have been trying to get it to work without one.
var rps = ["rock", "paper", "scissors"];
var rpsChoice = rps[Math.floor(Math.random() * rps.length)];

message.channel.send("Let us play Rock, Paper, Scissors. Please type in the corresponding responses.").then(() => {
    message.channel.awaitMessages(response => response.content === "rock" || response.content === "paper" || response.content === "scissors", {
        max: 1,
        time: 45000,
        errors: ['time'],
    }).then((collected) => {
        if (user == "rock" && rpsChoice == "scissors") {
            message.channel.send(`I chose ${rpsChoice} and you chose ${collected}`);
            message.channel.send("You win! Congrats!");
        } else if (collected == "paper" && rpsChoice == "rock") {
            message.channel.send(`I chose ${rpsChoice} and you chose ${collected}`);
            message.channel.send("You win! Congrats!");
        } else if (collected == "scissors" && rpsChoice == "paper") {
            message.channel.send(`I chose ${rpsChoice} and you chose ${collected}`);
            message.channel.send("You win! Congrats");
        } else if (collected == rpsChoice) {
            message.channel.send(`I chose ${rpsChoice} and you chose ${collected}`);
            message.channel.send("No one wins, we tied!");
        } else {
            message.channel.send("I'm sorry, you lost!");
        }

    }).catch(() => {
        message.channel.send("You didn't respond with anything!");
    });
});

Comment: Some clarity please? What is your problem? Based on this line: `The response after the command does not have a prefix and I have been trying to get it to work without one.` You've been trying to get it to work **without** a prefix? Yet you say the command *does not have* one.
Comment: @Frustratedprogrammer Sorry, the command in order to run the command has a prefix but typing in "rock", "paper", and "scissors" does not. Does that clarify it?
Comment: Well I figured that, but do you want the *response* to have a prefix or not? Cuz atm it looks like the code accepts answers without prefixes.
Comment: @Frustratedprogrammer No, I want the prefix to not have a prefix.
Comment: Um then just remove the prefix I guess? I still don't understand... do you want the user to send smt like `>rps` then `>rock`? Your code appears to accept `>rps` then `rock`
Comment: I want it it like the second thing you did
Comment: So then whats the problem? What is it *currently* doing? Your code looks correct based on what you described... I am not sure what you're doing to run the `rps` command. If you don't know how to run it try this `if( message.content.toLowerCase() === ">rps"){ your code thats you got right now }`
Comment: So, my command is ".rps"

When I type "rock", "paper", "scissors", the bot automatically sends the "You didn't send anything" message
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/212216/discussion-between-frustrated-programmer-and-jiangxi123).
Answer: First off you have a few issues:
here: if (user == "rock" && rpsChoice == "scissors") { it looks like user isn't defined.
Secondly collected is a collection of messages. NOT the message's content. So doing collected == "paper" is similar to comparing an Object to a String.
Third using two equals == can generally cause issues when comparing things and is highly recommended against using it. It's fine to use, but only when you know what your doing.
So to fix all three issues use this inside the .then() function:
let response = collection.first().content.toLowerCase();
if (response === "rock" && rpsChoice == "scissors") {
    message.channel.send(`I chose ${rpsChoice} and you chose ${collected}`);
    message.channel.send("You win! Congrats!");
} else if (response === "paper" && rpsChoice == "rock") {
    message.channel.send(`I chose ${rpsChoice} and you chose ${response}`);
    message.channel.send("You win! Congrats!");
} else if (response === "scissors" && rpsChoice == "paper") {
    message.channel.send(`I chose ${rpsChoice} and you chose ${response}`);
    message.channel.send("You win! Congrats");
} else if (response  === rpsChoice) {
    message.channel.send(`I chose ${rpsChoice} and you chose ${response}`);
    message.channel.send("No one wins, we tied!");
} else {
    //Hey did ya realize you don't tell the user what the bot's choice was when they lost?
    message.channel.send("I'm sorry, you lost!");
}

And just a tip, to reduce code, remove all the
message.channel.send(`I chose ${rpsChoice} and you chose ${response}`);

and put it right after the definition of response