Replace cell value in Google Script Apps

Question: I am trying to write a script that, when a cell in a sheet changes "Негатив отсутствует", will replace the value of a cell in another sheet with the value "Нерелевант". Help please, what did I do wrong?
function ChangeTone(event) {
  if (event.source.getActiveRange().getValue()=="Негатив отсутствует" && event.source.getActiveSheet()=="Разметка ТОП100 по суду"){
    var sheet = SpreadsheetApp.getActiveSheet();
    var currRow = sheet.getActiveCell().getRow();
    var value = sheet.getRange(currRow, 1).getDisplayValue();
    var pasteSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Тональность");
    var data = pasteSheet.getDataRange().getValues();
//    if(currRow > 2){
//      sheet.deleteRow(currRow);
//    }
    for(var i = 1; i<data.length;i++){
          if(data[i][1] == value){
            pasteSheet.getRange((i), 2).clear({contentsOnly: true});
            pasteSheet.getRange((i), 2).setValue('Нерелевант');
            break;
          }
  };
//    sheet.getActiveCell().setValue("");

}
}

Answer: Explanation / Issues:
Issue:
There is a clear issue with your code and in particular here:
event.source.getActiveSheet()=="Разметка ТОП100 по суду"
You are comparing a sheet object with a string and this will always return false. The correct way to do it would be:
event.source.getActiveSheet().getName()=="Разметка ТОП100 по суду"
but here I also tried to optimize your code because it is quite inefficient.
Optimization:
You don't take full advantage of the event object.

SpreadsheetApp.getActiveSpreadsheet() can be replaced by e.source.

You also define the same variables multiple times when you only need to do that once:

For event.source.getActiveSheet() and var sheet = SpreadsheetApp.getActiveSheet(); you can define a single variable to store the active sheet object and call it whenever you need it.

Last but not least. I am not quite sure about your logic regarding the for loop since you haven't mentioned it in your question.
But I see you use a for loop, an if statement and a break line to escape the for loop as soon as there is a match between the source value and the value in the paste sheet.

Instead of using a for loop, you can use findIndex to find the value that matches the criterion data[i][1] == value.

Also the full getDataRange() is not needed if you intend to use only one column, therefore I change that part too.

Solution:
function onEdit(e){
 const ss = e.source;
 const ar = e.range;
 const activeSheet = ss.getActiveSheet();
 const pasteSheet = ss.getSheetByName("Тональность");
  if (ar.getValue()=="Негатив отсутствует" && activeSheet.getName()=="Разметка ТОП100 по суду"){
    const value = activeSheet.getRange(ar.getRow(), 1).getValue();
    const data = pasteSheet.getRange('B1:B'+pasteSheet.getLastRow()).getValues().flat();
    const indx = data.findIndex((element) => element == value);
    if (indx>-1){
      const pasteRng = pasteSheet.getRange(indx+1,2);
      pasteRng.clearContent();
      pasteRng.setValue('Нерелевант');
  }
  }
}

Let me know if that worked for you, otherwise I would like to modify it so it does.
Answer: Thank you very much! The script works =)
I also made a working script before. But this is my first script, so it is much slower and not so ... concise. Also it was fired with a trigger, and yours works as a simple event.
My old version:
function ChangeTone(event) {
  if (event.source.getActiveRange().getValue()=="Негатив отсутствует" && event.source.getActiveSheet().getName() == "Разметка ТОП100 СУД"){
    var sheet = SpreadsheetApp.getActiveSheet();
    var currRow = sheet.getActiveCell().getRow();
    sheet.getRange("A"+currRow+":F"+currRow).setBackground('#ff5a5a');
    var value = sheet.getRange(currRow, 1).getDisplayValue();
    var pasteSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Тональность");
    var data = pasteSheet.getDataRange().getValues();
    for(var i = 1; i<data.length;i++){
          if(data[i][0] == value){
           pasteSheet.getRange((i+1), 2).setValue('Нерелевант');
           sheet.getRange("C"+currRow+":F"+currRow).deleteCells(SpreadsheetApp.Dimension.ROWS);
          }
  };
    sheet.getRange("A"+currRow+":B"+currRow).setBackground('#ffffff');
}
}

So took your code and added row deletion after replacing cell value. Final version:
function onEdit(e){
 const ss = e.source;
 const ar = e.range;
 const arRow = ar.getRow();
 const activeSheet = ss.getActiveSheet();
 const pasteSheet = ss.getSheetByName("Тональность");
  if (ar.getValue()=="Негатив отсутствует" && activeSheet.getName()=="Разметка ТОП100 СУД"){
    const value = activeSheet.getRange(arRow, 1).getValue();
    const data = pasteSheet.getRange('A1:A'+pasteSheet.getLastRow()).getValues().flat();
    const indx = data.findIndex((element) => element == value);
    if (indx>-1){
      const pasteRng = pasteSheet.getRange(indx+1,2);
      pasteRng.clearContent();
      pasteRng.setValue('Нерелевант');
      activeSheet.getRange("C"+arRow+":F"+arRow).deleteCells(SpreadsheetApp.Dimension.ROWS);
  }
  }
}

Thanks again for your help =)


Scrapy spider returns different values compared to browser console xpath result

Question: xpath:
//ol[@class="breadcrumb container"]/li[not(contains(@class,"first")) and not(contains(@class,"last"))]/a/span/text()

HTML:

Home

Books

My Vision : Challenges in the Race for Excellence - Mohammed Bin Rashid Al Maktoum

Python code:
categories = ['NO DATA', 'NO DATA', 'NO DATA', 'NO DATA', 'NO DATA', 'NO DATA']
catIndex = 0
for cat in sel.xpath('//ol[@class="breadcrumb container"]/li[not(contains(@class,"first")) and not(contains(@class,"last"))]/a/span/text()').extract():
            categories[catIndex] = cat
            catIndex += 1

Wanted result is "Books" and when I check it on Firebug console with xpath it returns correct result but when I run spider it returns whole 3 Li elements not excluding class="first" and class="last"
I tried command Scrapy View http://example.com to see page how spider sees it but everything looks same and xpath returns correct result

When I tried using xpath in Scrapy Shell it returns incorrect result of all 3 Li elements

What might be the problem?
Comment: actually if u check the page source from ur browser it will show u that the first and last li element have no class attributes so ultimately u will get all three elements in results. That is the problem.
Comment: u need to make changes in ur xpath to get the correct output that u want.
Comment: You are right  doesn't have Class attribute
Answer: Opened Scrapy View http://example.com output in Internet Explorer and saw that Li elements doesn't have Class attribute in there.
It apears that Scrapy View Command opened in Chrome or Firefox doesn't show REALL code which spider sees.


SQL - Count Partition

Question: I have a massive table, a snippet of which goes like this:
ID  | Archive   | Open Account Date
Bob | May 2018  | Jan 2018
Bob | June 2018 | Jan 2018
Bob | June 2018 | Mar 2018
Bob | July 2018 | Jan 2018
Bob | July 2018 | Mar 2018

I'd just like to count the number of different open accounts 'Bob' has at each (archive date) and at each (archive date-1).
So, for June 2018:
   At Archive Date, Bob has 2.
   At Archive Date-1, Bob only has 1.

Here's what I tried:
-- Because there's so much data and it's not just 'Bob', I'm a little confused.
This Makes sense for count of all open Account Dates at a particular Archive Date:
-- COUNT(Open Account Date) OVER (PARTITION BY ID Order by Archive) as CurrentArchive_Counts
But I can't Mix Lag with Count, so I don't think this works:
-- Count(LAG(Open Account Date,1) OVER (Partition BY ID Order by Archive)) as PreviousArchive_Counts ??
Comment: Thanks bud, just using SQL Server
Comment: As you are new, is always good to say, what have you tried. People is not going to answer you the quiz, take  alook at SELECT COUNT(*) FROM TABLE GROUP BY COLUMN
Comment: Thanks, still learning - i updated with what I tried.
Answer: You don't need lag:. Look into "Row/Range" clause of partitioning function. Check out Example D .
You will needed something along these lines:
SELECT *, COUNT() OVER( PARTITION BY ID ORDER BY Archive ROWS BETWEEN CURRENT ROW AND UNBOUNDED PRECEDING ) AS AccountsNum,
COUNT() OVER( PARTITION BY ID ORDER BY Archive ROWS BETWEEN 1 PRECEEDING AND UNBOUNDED PRECEDING ) AS LastArchiveAccountsNum,
FROM [table]

Comment: Thanks Alex, as I don't need the running total and just for the point in time- would just specifying say ROWS BETWEEN CURRENT ROW AND CURRENT ROW)  or ROWS BETWEEN 1 PRECEDING and 1 PRECEDING do the trick?

SQL - Count Partition


Connect ONLY via VPN

Question: How can I create connection via VPN by default when Ubuntu loading? Also I need don't reach Internet if VPN connection not established or disconnected.
In few words, I need connection to Internet ONLY via VPN.
Comment: This is a chicken-egg story. Without internet access on your 'real' connection, you won't be able to reach your VPN access concentrator. Maybe your questions is about limiting the outbound connections on your 'real' connection to VPN-only traffic? How about a firewall only allowing to talk to the VPN server?
Comment: Relevant bug reports at Launchpad: #508063, #666446, #344455, #648212, #402223.
Comment: As gertvdijk said, without the Internet, no VPN. Perhaps you should ask for a way to restrict Internet traffic to only that traffic underlying the VPN connection.
Comment: Can't it then be scripted so that as soon as there's an internet connection the VPN  is automatically connected?
Answer: this is what I have right now, in some time I'll make a script to make all this automatic in the startup, but meanwhile I hope it works for you.
I'm assuming you are using OpenVPN if you are not you'll have to get the idea and then translate it to your VPN program.
First you need to go to /etc/openvpn and make a file called VPNconfig with two lines (with your real values)
VPN_User
VPN_Password

Now for all your .ovpn files in /etc/openvpn you should replace
auth-user-pass

with
auth-user-pass VPNconfig.txt VPNconfig.txt

That will make sure that you don't have to write user and password each time you log in (it's also highly insecure so beware of what password you use for your VPN, make it sure it's not you password for everything else)
Now I'll make an alias in /root/.bashrc
alias vpn='cd /etc/openvpn/ && openvpn /etc/openvpn/Your_VPN_Ovpn_File.ovpn'

So when you startup you just open a terminal and run
sudo su
vpn

To make sure your IP doesn't get revealed when the VPN disconnects you should use an iptables script, you know it follow the steps specified here, specially check the answer of windom at the bottom of the first page. If you use other VPN than PIA you will have to modify the script to fetch your IP ranges.
That script generates the two files specified in the first post iptables-vpn and iptables-novpn.
You would also like to avoid DNS leaks, for that append at the start of each .ovpn
up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf
--script-security 2

and check if it worked here
So as gertvdijk has said you need the connection to access the VPN, so the order would be, connect to VPN, then execute ./iptables-vpn and now you will be secure of VPN disconnections, the problem is that if it disconnects you will have to manually set it up executing ./iptables-novpn , reset the VPN connection, and then turn back on the iptables-vpn.
There is a quicker way with a python script using netifaces but I'm still using this... Hope it helped!
Answer: Connect to VPN by default:
Click on Network Manager icon in the system tray and select "Edit Connections...".
Choose your default connection and click the "Edit" button.
In the General tab there is a setting "Automatically connect to VPN when using this connection", select your VPN.
Connect to internet only via VPN:
This can be achieved using a firewall, for an example using UFW (Uncomplicated Firewall) see UFW for OpenVPN.

Connect ONLY via VPN


Verification of proof that for a,b in ring R, assuming ab is a zero divisor at least one of a and b is zero divisor

Question: I'm not so sure if this is correct but here's what I have so far:
ab is a zero divisor iff there is a c$\neq$0 s.t. (ab)c=c(ab)=0 given ab$\neq$0 and c$\neq$0.  Then we have (ab)c-c(ab)=0=(ab)c+c-c-c(ab)=0 which breaks down into (ab+1)c-c(1+ab)=0.  We already know c cannot be 0 so for 1+ab=0 ab must equal -1.
Is this what the proof is asking for? If not, how would I correct it?
Answer: No, that is not what the proof is asking for. You seem to have the wrong definition of zero divisor.
Let's assume that the ring $R$ is commutative for simplicity.
$x\in R$ is a zero divisor if there is $y\in R$, $y\ne0$, such that $xy=0$.
Thus, if $ab$ is a zero divisor, then there is $c\in R$, $c\ne0$, such that $(ab)c=0$.
Then, $0=(ab)c=a(bc)$. If $bc=0$, then $b$ is a zero divisor. If $bc\ne0$, then $a$ is a zero divisor.
Comment: But don't you have to incorporate commutativity so that (ab)c=c(ab)=0 here?
Comment: @cambelot, If your ring is not commutative, say it explicitly in the question.
Comment: What I mean is: The definition I have here is that ab in a ring is a zero divisor if ab does not equal to 0 and there is a c not equal to 0 with (ab)c=0 or (ba)c=0.  So shouldn't the last line of your proof be in this format?
Comment: @cambelot, are you sure that's the definition? I mean, what is the definition of "$x$ is zero divisor"? Perhaps you could tell us which book you're using or online notes if any.


How to have only 1 return in render() with React Native?

Question: How to have only 1 return in render() with React Native? See render method in <SampleApp />.
Here's a playground version: https://rnplay.org/apps/t8KFig
The views should be full screen, like in this playground: https://rnplay.org/apps/0GFbHg
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView
} = React;

var SampleApp = React.createClass({

  getInitialState: function() {
    return {
      whichView: 'two'
    };
  },

  _renderViewOne: function() {
    return (
      <View style={[styles.tabContent, {backgroundColor: 'orange'}]}>
        <Text style={styles.tabText}>I like funny cake.</Text>
      </View>
    );
  },

  _renderViewTwo: function() {
    return (
      <View style={[styles.tabContent, {backgroundColor: 'blue'}]}>
        <Text style={styles.tabText}>
            Justin Beiber should sing Thrash Metal.
        </Text>
      </View>
    );
  },

  render: function() {
    var showJSX = '';

    if ( this.state.whichView === 'one' ) {
        showJSX = (this._renderViewOne());
    }
    else {
      showJSX = (this._renderViewTwo());
    }

    return (
      <ScrollView>
          {showJSX}
        </ScrollView>
    );
    }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  tabContent: {
    flex: 1,
    alignItems: 'center',
  },
  tabText: {
    color: 'white',
    margin: 50,
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

Answer: I've extracted the showJSX var business to another method so it's cleaner.
render: function() {
  return (
    <ScrollView style={styles.bigContainer}>
      {this.viewPicker()}
    </ScrollView>
  );
},

viewPicker: function() {
  if ( this.state.whichView === 'one' ) {
    var showJSX = (this._renderViewOne());
  }
  else {
    var showJSX = (this._renderViewTwo());
  }

  return showJSX;
}

And you were missing flex: 1 and backgroundColor: 'blue' on the ScrollView.
Here is a link to the updated playground
Comment: Thanks. I realized my main View was collapsed just before I fell asleep. Wasn't sure if it was legit to have a View wrapping another View. Thanks for the clean code.


What are the eigenvectors of a linear map in a 1 dimensional inner product space?

Question: I was thinking in this way,
Let V be a real inner product space of dimension 1 and T is a linear map on this space i.e. $T\in\mathcal L(V)$.
If $\lambda$ is an (real) eigenvalue and $v$ is corresponding non-zero eigenvector, then, $$ T(v) = \lambda v\\$$
Let $(v_1)$ is a basis for $V$ vector space.
Then $$v=av_1$$ for some $a\in R$
$a\neq 0$ because $v$ is non-zero.
Therefore,
\begin{aligned}
T(av_1)&=\lambda av_1\\
aT(v_1)&=a\lambda v_1\\
T(v_1)&=\lambda v_1\\
||T(v_1)||&=\lambda||v_1||\\
\lambda &=\frac{||T(v_1)||}{||v_1||}
\end{aligned}
That means any non-zero vector is an eigenvector for 1 dimensional inner product space with eigenvalue equal to $\frac{||T(v_1)||}{||v_1||}$.
Is there anything wrong in this approach?
Comment: You don't use the inner product! You just need a normed linear space.
Comment: @sujoy Your reasoning is correct.
Comment: It is not correct ! Look at $T(v)=-v$
Comment: Your formula would induce that you can only have **positive** eigenvalues...
Answer: If $V$ is a normed space, then you only can conclude: $|\lambda |=\frac{||T(v_1)||}{||v_1||}$
With your notation: there is a scalar $t_0$ such that $T(v_1)=t_0v_1$. If $v \in V$, then $v=sv_1$ with some scalar $s$, hence
$T(v)=T(sv_1)=sT(v_1)=st_0v_1=t_0v$. Thus $T$ has the form
$T(v)=t_0v$.
Consequence: the only eigenvalue of $T$ is $t_0$ and each nonzero $v \in V$ is eigenvector.


Addressing a shower pan that was not sloped properly

Question: My tile contractor did not properly slope my shower floor and left a lot of 2"X2" shower floor tiles with numerous lippage spots. I took out all the tile but still have some thinset stuck to the floor.
If I am able to remove all the thinset with out tearing out all the deck mud, do you think it would be alright to just patch and fill areas in the deck mud?
Or should I take out all the deck mud and start all over?
I also had to dig down to the vinyl liner around the drain because my tile contractor installed the vinyl liner over the drain flange and the locking coupling.  I was able to remove the locking coupling and install it over the vinyl liner. I think I can back fill this area with gravel and deck mud, but not sure if this is a good idea.
Comment: "*If I am able to remove all the thinset with out tearing out all the deck mud, do you think it would be alright to just patch and fill areas in the deck mud?*"  That does not address the fact that the pan does not have the proper slope.  Perhaps When you say properly sloped   you mean   **not flat**.  Is it sloped so water flows to the drain?
Answer: It sounds as if you practically have all the concrete removed. It may be wise to bite the bullet and start anew. For the sake of consistency it's better to have a floor pan from one single installation.
It certainly is possible to install patched areas in concrete and have them function as expected. Shallow chisel divots can be filled and if the area is solid without cracks and hasn't been jolted-loose from the demolition the odds are good for a repair.
Comment: I agree with having a solid pan or later when someone rocks back on a heel (small contact area with full weight)  the bottom breaks. If there was a solid structure below this I would say ok but gravel, no it needs to be redone with the correct slope to start with.
Comment: I agree with this, so won't bother with a separate answer. I'll add, though, that the materials at this stage (deck mud/sand mix) are cheap compared to everything else in the shower. If you have to have a do-over, this is the place you want to have it. Also, unless you are the "tile contractor," you should never let that tile contractor in your house again.
Comment: Thank you all for your advice.  Looks like I will replace all the deck mud.  Will give it try by myself. Tough to find a reasonable tile contractor.


Crawlspace Post to beam lumber grade

Question: Recently we replaced some of the rotten and cracked true size 4 in x 6 in. posts under the house in crawlspace. The old posts were resting on concrete pads 24 in. x 24 in. and supporting a true size beam 4 in x 8 in.
The lumber we used is 4 in. x 6 in. x 8 ft. Pressure-Treated Landscape Timber , since we couldn't find any true size to match the old one. This lumber is rated as #3 grade but does not have any knots or cracks and labeled as not being used for structural purposes.
Should I be concerned about its strengths? I presume that is Douglas Fir.
Comment: Hmmm...let's see...it's, "labeled as not being used for structural purposes," and you chose to use it for structural purposes....hmmm. Well let's see, if it's pressure treated lumber, I doubt if it's Douglas Fir...probably spruce. Spruce 1) has a significant lower bending stress values than Douglas Fir, 2) #3 grade is significantly less bending stress value than standard framing lumber (no. 2 and better), 3) stress values are less because it's been injected with water treatment. Having said all that, residential construction is grossly over designed. If we knew the span of the beams,
Comment: If we knew the span of the beams, contributing load on the beam, etc. we could make an educated guess as to its strength, durability, etc.
Comment: Dimension ( eg. 2 X 4 ) and treated wood in the US is mostly southern pine ( loblolly , short leaf or long leaf) . It is relatively strong. Critical engineering wood construction  is commonly "stress grade spruce" ( in the US).
Comment: @Lee the distance between beams is 5ft, and distance between posts is 8.3 ft. I just had an answered question from the Home Depot about the type of the lumber I purchased, it is "either Hem-Fir or Doug Fir".
Answer: Not using graded lumber can get you in trouble. Or what I mean is using a lower grade than allowed for a residence. If you ever have an earthquake this could be an area that the insurance company says they won't cover your loss. And you want to use material that is below grade 2 and specifically listed as not for structural.
I would not have this prior to my loss, don't give them any reason for denying your claim.
Answer: I would be heeding the warning. Did you try a real lumber yard or just your home store for the replacement lumber? At least replace the wood with some rated for structural use.
Comment: Probably not, but they could cut it for you and they used to do that. That was the one great reason for going to the lumber yard.
Comment: Did you intend to post this as an answer? Seems more like a comment. Home stores often sell better grades than lumber yards because their customers consider appearance a more important factor than builders do. I have lots of experience with both. Let's not big-box-bash without cause.
Comment: I'm not bashing big box... have a lot of stock in them. It was mentioned he couldn't find the true size he needed so I was just asking the question. I have found true sizes in lumber yards that the home stores didn't carry.
Comment: no lumber yard has a 4x6 real size
Answer: Why wouldn't you just use 6x6 treated #2 SYP posts? You must have a reason why you felt that getting a 4x6 was more important.
Otherwise 4x6 treated is available as curb blocking at lumber yards. Typically it's #2 if I remember correctly.
Comment: The 4x6 it is not a real size. It is 3.5x5.5 which is lower than the size I have.

Crawlspace Post to beam lumber grade


retain array class when operation results in 2-dimensional matrix

Question: I have an array that can have one or more pages or sheets (my names for the third dimension).  I am attempting to perform operations on the array.  When there is only one sheet or page the result of the operation is a matrix.  I would like the result to be an array.  Is there a way to retain the class array even when the result of the operation has only 1 sheet or page?
Here is an example.  I would like my.var.2 and my.var.3 to be arrays.  The variable my.pages is set to 1 here, which seems to be causing the problem.  However, my.pages can be >1.  If my.pages <- 2 then my.var.2 and my.var.3 are arrays.
set.seed(1234)

my.rows    <- 10
my.columns <- 4
my.pages   <- 1

my.var.1 <- array( rnorm((my.rows*my.columns*my.pages), 10, 2),
                        c(my.rows,my.columns,my.pages))
my.var.1

my.var.2 <-  2 * my.var.1[,-my.columns,]
my.var.3 <- 10 * my.var.1[,-1,]

class(my.var.2)
class(my.var.3)

my.var.2 <- as.array(my.var.2)
my.var.3 <- as.array(my.var.3)

class(my.var.2)
class(my.var.3)

my.var.2 <- as.array( 2 * my.var.1[,-my.columns,])
my.var.3 <- as.array(10 * my.var.1[,-1,]         )

class(my.var.2)
class(my.var.3)

The switch to matrix causes problems when I try to use my.var.1 and my.var.2 in nested for-loops.
The following if statement seems to solve the problem, but also seems a little clunky.  Is there a more elegant solution?
if(my.pages == 1) {my.var.2 <- array(my.var.2, c(my.rows,(my.columns-1),my.pages))}

Answer: From help([):
Usage:
     x[i, j, ... , drop = TRUE]
...
drop: For matrices and arrays.  If 'TRUE' the result is coerced to
      the lowest possible dimension (see the examples).  This only
      works for extracting elements, not for the replacement.  See
      'drop' for further details.

Your code, revisited:
set.seed(1234)

my.rows    <- 10
my.columns <- 4
my.pages   <- 1

my.var.1 <- array( rnorm((my.rows*my.columns*my.pages), 10, 2),
                        c(my.rows,my.columns,my.pages))
my.var.2 <-  2 * my.var.1[,-my.columns,,drop=FALSE]
my.var.3 <- 10 * my.var.1[,-1,,drop=FALSE]

class(my.var.2)
## [1] "array"
class(my.var.3)
## [1] "array"


Two light switches and three black wires

Question: I've never seen this setup before and was wondering if others had. One of the switches powers a ceiling light in the foyer and the other powers two outside lights on the front porch. Right now neither work and I thought maybe replacing the switches would work but I'm perplexed on how to wire this up properly.
Basically I have three black wires coming from the wall. All of the white wires are twisted together. The switch on the left has two black wires and the switch on the right has one wire running to both posts...
Any help would be much appreciated!
Comment: Hello, and welcome to Home Improvement. What changed between when this worked and when it didn't? (A switch with one wire going to both terminals isn't going to do anything for you...) And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Answer: The wire nut in the middle has three black wires going to it, so it's likely the feed in, that then gets daisy-chained out to other fixtures. Looks like all 4 neutrals (one in, one out to other fixtures, and the two to the fixtures switched here) are commoned in the wire nut at the back of the box.
From that live junction, it then feeds the switch on the right, and then the loop going to the other terminal of the same switch is clearly in the wrong place.
I'd guess that the two wires to the left switch are the two switched feeds out to your two loads, so you need to swap one (back) with the loop wire on the right switch, such that the feed goes to both switches, and the switched sides are one to each switch.
How exactly did these wires get swapped? It clearly has not been like this from the beginning.
Comment: I think this is exactly it. Check to see if the right switch is hot. If it is, you have power to the box. Check to see if the left switch has nothing hot. If not, those are your switch legs.
Answer: That didn't get that way by itself.
In multiple-switch situations, it is quite common for both switched devices to be powered from the same circuit.  Hot wires are switched (neutrals aren't), so we are working with "hots".
A switch connects supply hot to a switched-hot wire (that is only energized when the switch is on).
Since both switches use the same supply, the supply wire must be "split" to both switches.  There are several ways to do that.
This particular way involves the wire looping around one terminal of switch 1, and then going to one terminal of switch 2.
The remaining two wires, each a switched-hot, go to the remaining switch terminals.


proving that $\sin\beta \cos(\beta+\theta)=-\sin\theta$ implies $\tan\theta=-\tan\beta$

Question:
Show that $\sin\beta \cos(\beta+\theta)=-\sin\theta$ implies $\tan\theta=-\tan\beta$

I expand the cosinus:
$$\cos(\beta+\theta)=\left(1-\frac{\theta^2}{2}\right)\left(1-\frac{\beta^2}{2}\right)-\beta\theta$$
but I can't get any tan.
Comment: I get $\cos(\beta + \theta) = \cos\beta\cos\theta - \sin\beta\sin\theta$. Your expansion is new to me, and frankly doesn't look right. Is it just the first terms of the Taylor expansion or something?
Comment: It's false that $\cos(\beta+\theta)$ equals the expression on the right hand side. You can use Taylor expansion up to some degree for computing limits and other tasks, but generally not for showing equalities.
Comment: Write RHS as $\cos (\beta + \theta - \beta)$
Comment: Where did you get that expansion formula for cosine I never see that in m life
Comment: Please, if you are ok, you can accept the answer and set it as solved. Thanks!
Answer: Separating out $\sin\theta,\cos\theta$ after using $$\cos(A+B)$$ formula
$$\sin\theta(\sin^2\beta-1)=\sin\beta\cos\beta\cos\theta$$
$$\iff\dfrac{\sin\theta}{\cos\theta}=\dfrac{\sin\beta\cos\beta}{\sin^2\beta-1}=?$$
Answer:
Indeed,
since $\cos(\beta + \theta) = \cos\beta\cos\theta - \sin\beta\sin\theta$
your equation becomes
 $$
\sin\beta( \cos\beta\cos\theta - \sin\beta\sin\theta) =\sin\theta $$
Dividing by $\cos\theta$ $$
\sin\beta( \cos\beta - \sin\beta\tan\theta) =-\tan\theta \implies
\sin\beta \cos\beta - \sin^2\beta\tan\theta =-\tan\theta $$
Dividing by $\cos^2\beta = \frac{1}{1+\tan^2\beta}$
$$
\tan\beta - \tan^2\beta\tan\theta =-\tan\theta(1+\tan^2\beta) \implies
\tan\beta =-\tan\theta $$
Answer: Note that
$$\cos(\beta+\theta)=\cos\beta \cos\theta-\sin\beta \sin\theta $$
thus step by step
$$\sin\beta \cos(\beta+\theta)=\sin\beta \cos\beta \cos\theta-\sin^2\beta \sin\theta=-\sin \theta$$
$$\sin\beta \cos\beta \cos\theta-\sin^2\beta \sin\theta=-\sin \theta$$
$$\sin\beta \cos\beta \cos\theta=-\sin \theta+\sin^2\beta \sin\theta$$
$$\sin\beta \cos\beta \cos\theta=-\sin \theta(1-\sin^2\beta)$$
$$\sin\beta \cos\beta \cos\theta=-\sin \theta \cos^2\beta$$
$$\sin\beta \cos\theta=-\sin \theta \cos\beta$$
$$\frac{\sin\beta} {\cos\beta}=-\frac{\sin \theta} {\cos\theta}\iff\tan\theta=-\tan \beta$$


JWT access token security considerations

Question: For my project, I'm implementing OAuth2 authentication framework that uses Bearer tokens.
From a quick search, it looks like JWT tokens are the mainstream choice for Bearer tokens today.
If I would use a "dumb" token that doesn't encode any information, I would be storing this token in a database, alongside all the related parameters (token's user, issue date, expiration date, etc.).
From JWT's documentation I understood that I can avoid this overhead by implementing this flow:

User authenticates with one of the supported methods
Authentication service generates JWT token and encodes the following parameters into it: user id, authentication method used, issue date, expiration date
Authentication service encrypts and then signs the token
The token is sent to the user for subsequent usage

The encryption step is desirable because I wouldn't like to advertise user IDs.
My understanding is that if I use the above method, I can avoid storing the mapping between access tokens and users, and rely entirely on the user ID information provided with the token.
What disturbs me with this approach, is that it looks like I won't have the option to "revoke" access tokens.
In other words - even if access token will become compromised, I won't be able to disable it (unless I know the exact compromised token, which is not the case).
Is this a real concern, or I'm just missing somethig? If this concern is real, how can I work around it?
Comment: You're right, a JWT is valid until expires and you shouldn't store it. You can build a revocation list but the usual thing is to let the token expire and adjust the expiration period to your needs. See https://stackoverflow.com/questions/37507714/invalidating-client-side-jwt-session
Answer: Access tokens self-contained and are valid as long as the expiration time is valid. There is no specification around invalidating them in the actual spec. Depending on the level of security you need you can adjust the validation time of the tokens, from fewer minutes to hours. Typically the validation time is set for an hour.
If you require higher level of security, you can use Reference tokens. Reference tokens doesn't carry any information, they are plain strings. But, the server (or whoever is consuming these tokens) has to contact the Token Provider to exchange the reference tokens for actual response content. But, these tokens can be revoked if they are compromised.
Please refer to this link for more information and some suggestions on how to overcome some of the downsides of Reference tokens (like back channel communication/ extra round trip to Token Provider). Please let me know if you have any questions.
-Soma.


Laplace Inversion using the Residue Theorem

Question: UPDATE: I've attempted to answer this question
I'm trying to invert a Laplace Transform using Cauchy's Residue Theorem. The transform is
$$\Theta(s)=\frac{F(s)}{G(s)}$$
where
$$
F(s)=[1+\gamma P(s)] [As^{-1}+\theta(0)]
$$
and
$$
G(s)=[1+\gamma P(s)] (s+A) + \gamma BP(s)
$$
in which $\theta(0)$ is the initial condition of the inverse transform function in the time domain, $\gamma$, $A$, and $B$ are real constants, and $P(s)$ is given by the series
$$
P(s)=s\sum_{k=1}^{k=N} \frac{C_k}{s+\lambda_k^2}
$$
where $N \ge 50$. The  terms $C_k$ and $\lambda_k$ are the real Fourier-Bessel coefficients and real eigenvalues that are the outcome of another coupled problem.
Here is the approach that I used:
There is one pole at $s=0$ and the remaining $N$ poles $z_k, k=1\cdots N$ are the zeroes of $G(s)$, all of which lie on the negative Real Axis, and each of which I have calculated with residuals pretty close to machine roundoff. Following the Residue Theorem, the Inverse Laplace Transform can be written as
$$
\theta(t)=1+\sum_{k=1}^{k=N}e^{z_k t}F(z_k) \lim_{s\to z_k}\frac{s-z_k}{G(s)}
$$
whereupon the indeterminate limit can be resolved with L'Hôpital's Rule yielding
$$
\theta(t)=1+\sum_{k=1}^{k=N} e^{z_k t}\frac{F(z_k)}{G'(s)}
$$
where $G'(s)$ is the derivative w.r.t. $s$ of $G(s)$
$$
G'(s)=[1+\gamma P(s)] +\gamma (s+A+B)P'(s)
$$
and $P'(s)$ is the derivative w.r.t. $s$ of $P(s)$
$$
P'(s)=\sum_{k=1}^{k=N} \frac{C_k}{s+\lambda_k^2}-s\sum_{k=1}^{k=N} \frac{C_k}{(s+\lambda_k^2)^2}
$$
Issues:
I've observed that the evaluation of $\theta(t)$ doesn't seem quite right especially for small times and in particular for larger values of $\gamma$. Moreover, it demonstrates a sensitivity to the eigenvalues and Coefficients $C_k$ that is not consistent with expected observations. Rather than inundate the reader with more details at this stage, I'll be glad to update the question with more relevant information following any comments.
My specific questions:
Is the approach that I've used with the Residue Theorem fundamentally correct?   Is there anything else that I should be aware of when solving problems of the type above?
Many thanks, as always.
Answer: Maybe incorporating a pre-processing to reduce the transfer function to its simplest expression, make the inversion process more accurate. For  $N = 2$, the final transfer function is presented, adequate to apply the method
$$
\Theta(s) = \frac{A \left(C_1 \gamma  s \left(\lambda _2^2+s\right)+\left(\lambda _1^2+s\right) \left(C_2 \gamma  s+\lambda _2^2+s\right)\right)}{s \left(C_1
   \gamma  s \left(\lambda _2^2+s\right) (A+B+s)+\left(\lambda _1^2+s\right) \left(C_2 \gamma  s (A+B+s)+(A+s) \left(\lambda
   _2^2+s\right)\right)\right)}
$$
with denominator coeficients
$$
\left\{
\begin{array}{c}
 0 \\
 A \lambda _1^2 \lambda _2^2 \\
 \left(\lambda _2^2+A+(A+B) \gamma  C_2\right) \lambda _1^2+\left(A+(A+B) \gamma  C_1\right) \lambda _2^2 \\
 \lambda _1^2+\lambda _2^2+A+\gamma  C_2 \left(\lambda _1^2+A+B\right)+\gamma  C_1 \left(\lambda _2^2+A+B\right) \\
 \gamma  \left(C_1+C_2\right)+1 \\
\end{array}
\right.
$$
Follow a symbolic processing script in MATHEMATICA to implement this simplification
P[s_, n_] := s Sum[Subscript[C, k]/(s + Subscript[lambda, k]^2), {k, 1, n}]
F[s_, n_] := (1 + gamma P[s, n]) A/s
G[s_, n_] := (1 + gamma P[s, n]) (s + A) + gamma B P[s, n]
Phi[s_, n_] := F[s, n]/G[s, n]

n = 2;
Phisn = Phi[s, n] // Together
num = Phisn // Numerator;
den = Phisn // Denominator;
Phis0 = num/den // FullSimplify
den0 = Phis0 // Denominator

Attached a python script to obtain the inverse Laplace transform from a transfer function $G(s) = \frac{N(s)}{D(s)}$ with the $N(s) = a_n s^n + \cdots + a_0$ and $D(s) = b_m s^m+\cdots b_0$ The $N$ coefficients are given in num and the $D$ coefficients in den both in power decreasing style. $G(s)$ is assumed strictly proper. The script gives a sequence of response terms which should be added to compound the time inversion.
import scipy.signal as R

num = [6.92462, 73.8839, 400.845, 1455.68, 3946.03, 8455.99, \
       14824.9, 21736.1, 27038.6, 28803.0, 26421.5, 20924.8, \
       14306.8, 8423.79, 4249.23, 1821.19, 655.104, 194.266, \
       46.253, 8.49133, 1.12494, 0.0951142, 0.00380817]
den = [1, 10.9544, 61.0185, 227.587, 634.139, 1398.5, 2527.38,\
       3827.46, 4929.55, 5452.66, 5212.0, 4320.11, 3108.84, 1940.74,\
       1048.1, 487.221, 193.437, 64.822, 18.0145, 4.04279, 0.702988, \
       0.0884995, 0.00711991, 0.000271338, 0]

#num = [3, 2, 2]
#den = [5, 2, 2, 1]

(r,p,k) = R.residue(num,den,tol=1e-5)

toler1 = 1e-5
toler2 = 1e-15
i      = 0
j      = 1

while i < len(r):
    alphai = real(r[i])
    betai  = imag(r[i])
    gammai = real(p[i])
    deltai = imag(p[i])

    if abs(betai) > toler1:
        if abs(alphai) < toler2:
            alphai = 0
        print("{4} >>> 2*exp({0}*t)*({1}*cos({2}*t) + {3}*sin({2}*t))".format(gammai,alphai,deltai,-betai,j))
        i += 2
    else:
        if abs(gammai) > toler2:
            print("{2} >>> {0}*exp({1}*t)".format(1*alphai,1*gammai,j))
        else:
            print("{1} >>> {0}".format(1*alphai,j))
        i += 1
    j += 1

The inversion problem gives as result
1 >>> 14.0347831855
2 >>> -0.483039070616*exp(-0.187218948148*t)
3 >>> 2*exp(-0.309980077984*t)*(-1.97460596883*cos(-0.0673684262979*t)+0.0408608048522*sin(-0.0673684262979*t))
4 >>> 2*exp(-0.317487772418*t)*(-0.853151294864*cos(-0.193564461065*t)+0.11474944314*sin(-0.193564461065*t))
5 >>> 2*exp(-0.262710062176*t)*(-0.192942085124*cos(-0.380624549122*t)+-0.196136519663*sin(-0.380624549122*t))
6 >>> 2*exp(-0.0566781486718*t)*(-2.04346564851*cos(-0.473314360884*t)+-0.784055678847*sin(-0.473314360884*t))
7 >>> 2*exp(-0.253402873944*t)*(-0.224610305483*cos(-0.602941037526*t)+0.573864761592*sin(-0.602941037526*t))
8 >>> 2*exp(-0.18001778095*t)*(-0.214405624466*cos(-0.953393232567*t)+-0.105678203189*sin(-0.953393232567*t))
9 >>> 2*exp(-0.25943110475*t)*(-0.377299755441*cos(-1.02160634165*t)+-0.266212072126*sin(-1.02160634165*t))
10 >>> 2*exp(-1.07768853278*t)*(0.0995875511961*cos(-0.120122202754*t)+-0.456124154697*sin(-0.120122202754*t))
11 >>> 2*exp(-0.674142284507*t)*(-0.207698716256*cos(-1.01903055486*t)+-0.0654651577739*sin(-1.01903055486*t))
12 >>> 2*exp(-1.08508395079*t)*(-0.222022363057*cos(-0.651792664191*t)+-0.740528774445*sin(-0.651792664191*t))
13 >>> 2*exp(-0.906967936955*t)*(-0.565257846658*cos(-0.938474102998*t)+-0.35832504633*sin(-0.938474102998*t))

That should be added to give the response to an impulse. In the figure are shown two curves. One the assumed exact and the other, the computed by the script.
Comment: Thanks @Cesareo. My problem is that I have at minimum $N=50$. Moreover, I need an Excel implementation and don't have access to Mathematica. However, your answer gave me an idea as to whether I could look into some sort of factorisation. It doesn't seem obvious, but perhaps worth a look. Thanks again.
Comment: ANother question: Is the Method of Residues known to cause numerical artifacts due to poor factorisation or the lack thereof altogether?
Comment: With polynomials of such a high degree, I think that it would be more appropriate to use an inversion method that approximates the transfer function globally, such as those inversion methods using the orthogonal polynomials of Laguerre.
Comment: Do the Laguerre polynomials offer a specific advantage over, say - a Laurent Series expansion?
Comment: @SharatVChandrasekhar As long as you use the Excel for  calculations, I offer a python script to do the same. I hope it helps.
Comment: Awesome! The parameters that I used are A=200, B=10, $\gamma$=0.1, $N=50$. The Eigenvalues are strictly increasing and the Fourier-Bessel coefficients are strictly decreasing. Both are functions of a parameter called the *Drainage Radius*. I can send you the values in a spreadsheet, if you would like to indulge me by cross-checking the solution that I have. Also, what did you think of my answer (which raises another question!)
Comment: Please. Send me the spreadsheet containing the parameter values. I will send you my results after calculation. I saw your answer and I celebrated that the question was resolved.
Comment: Thanks again @Cesareo. I didn't see a contact link in your profile? Is there another way or a repository for sharing information on Stack Exchange? Btw, I added a graphic showing the transient response of $\theta$ compared to a function-sampling algorithm.
Answer: I've figured out the cause of the discrepancy. The solution of the underlying problem in the time domain is
$$
\theta(t)=1+\sum_{k=1}^{k=N} e^{z_k t}\frac{F(z_k)}{G'(s)}
$$
as written above. The problem is that at time $0$, the initial condition $\theta(0))$ must be  honoured. This requires that
$$
\theta(0)=1+\sum_{k=1}^{k=N} \frac{F(z_k)}{G'(s)}
$$
which is violated by a small amount whose precise magnitude depends on how large the values of the first few poles are. I found that if I added this difference to the solution, everything works perfectly. See the figure below. The Gaver-Stehfest approach uses a function sampling algorithm and is well suited for diffusion problems.

What I still don't get is even though I've actually included $\theta(0)$ in the expression for $F(s)$, this isn't satisfied in what is I believe a definite integral evaluation in the Method of residues. What gives?!


How do I fill this very challenging table?

Question: I am practicing for a very hard logic competition in Lebanon and I was asked two questions.

Complete the following table:

Who am I?

Can anyone give me a hint? I really have no idea how to start! I tried to fill in blanks by using the sum, like 0+0.01 = 0.01, then 1.99 + 0.01 = 2 and etc...
I'm stuck.
Answer: It's pretty hard to know what's going on from just this, but assuming that the first table is supposed to mean "find two numbers whose sum is given in the right-hand column" and the second table is supposed to mean "find two numbers whose difference is given in the right-hand column" AND the two tables are expecting the same two values for each row (and this is a lot of assumptions...) you have simple simultaneous equations.
The first row becomes:
$$ a + b = 230 \quad \mbox{and} \quad a - b = 50 $$
for which the solutions are $a=140$ and $b=90$ (add the two equations to get $2a = 280$, solve for $a$ and substitute back into either equation to solve for $b$).
The last row becomes:
$$ a + b = 0.01 \quad \mbox{and} \quad a - b = 0 $$
for which the solutions are $a = 0.005$ and $b=0.005$.
Everything in between you should be able to complete now.


libusb cross compiling for raspberry pi3 on ubuntu

Question: Steps I followed to cross compile the libusb-1.0.9 to use with already cross compiled QT5 for raspberry pi3.
I have the libusb1.0.9 folder located at   /home/yasir/Development/crosscompile/libususb-1.0.9
mounted image of raspberry pi3 at
    /mnt/rasp-pi-rootfs/
STEPS
step 1.
At   /home/yasir/Development/crosscompile
 I run this
./fixQualifiedLibraryPaths /mnt/rasp-pi-rootfs/ /home/yasir/Development/crosscompile/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc

step 2.
Then I go to  /home/yasir/Development/crosscompile/libususb-1.0.9
 I run this
./configure --host=arm-linux --prefix=/usr/local/libusb-rpi  -disable-udev --with-sysroot=/mnt/rasp-pi-rootfs/  CROSS_COMPILE=/home/yasir/Development/crosscompile/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf- CFLAGS=-I/mnt/rasp-pi-rootfs/usr/include/ /mnt/rasp-pi-rootfs/usr/local/include/ LIBS=-L/mnt/rasp-pi-rootfs/usr/lib

please note this in the mean of terminal output:

step 3
sudo make

step 4
sudo make install

step no 5
make install does copy files to /usr/local/libusb-rpi on the PC, but not to the image mounted. So I did this
sudo mkdir -p /mnt/rasp-pi-rootfs/usr/local/libusb-rpi
sudo rsync -avh /usr/local/libusb-rpi/  /mnt/rasp-pi-rootfs/usr/local/libusb-rpi/

but QT5  compiler claims that the libusb-1.0.so  has wrong format when I did this
object dump  -f libusb-1.0.so

which clearly shows that the libusb -1.0.so file is generated but not for the raspberry pi arm architecture its for the host system.
Please tell me where I am wrong. Why libusb-1.0.so file is not cross compiled for the arm architecture(raspberry pi3), while I have use all the correct tools for the cross compilation.
please advice so I can generate .so file for the rapberry pi3 through cross compilation, though I also investigated the generated libusb.so file at the raspberry pi3 itself ,it was found to small size and its architecture was also arm.
Comment: Seriously, don't use screenshots, just copy and paste the text!
Answer: I used below script for configure and then a correct libusb-1.0.so  file is generated whose architecture was for arm(raspberry pi3).
./configure CC=/home/yasir/Development/crosscompile/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc  --host=arm-linux --enable-udev=no --enable-shared  --prefix=/usr/local/libusb-rpi


Querying value of xml file using xmlstarlet with namspace

Question: using this xml:
<application xmlns="http://ns.adobe.com/air/application/14.0">
    <id>5555</id>
    <filename>product2</filename>
    <name>prodigy</name>
    <versionNumber>6.5.511</versionNumber>
    <versionLabel>6.5.5110</versionLabel>
</application>

this command does not work, returns nothing:
xml sel -t -c "/application/versionLabel" application.xml

however, removing the xmlns attribute from application does work.   why?
Answer: Try this :
 xmlstarlet sel -N x="http://ns.adobe.com/air/application/14.0" -t -m "/x:application/x:versionLabel" -c . -n file

or (using default namespace) :
xmlstarlet sel -t -v "/_:application/_:versionLabel" file

OUTPUT:
<versionLabel xmlns="http://ns.adobe.com/air/application/14.0">6.5.5110</versionLabel>


How to get the total count of occurence of a word in a sentence

Question: I am trying to find the total count of occurrence of word in a sentence.
I tried the following code:
String str = "This is stackoverflow and you will find great solutions  here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";

    String findStr = "hello World";
    String[] split=findStr.split(" ");

    for(int i=0;i<split.length;i++){
        System.out.println(split[i]);
        String indexWord=split[i];
        int lastIndex = 0;
        int count = 0;
        while(lastIndex != -1){

            lastIndex = str.indexOf(indexWord,lastIndex);
            System.out.println(lastIndex);

            if(lastIndex != -1){
                count ++;
                lastIndex += findStr.length();
            }

        }
        System.out.println("Count for word "+indexWord+" is : "+count);
    }

If I am passing string like "stack solution" ,the string should be split into two(space split) and need to find the no of occurrence of each string in the sentence.The count is perfect if I pass only one word.The code has to match even substrings containing the searched string.
Eg:-In the sentence "stack" apperars three times,but the count is only 2.
Thanks.
Comment: Replace `lastIndex += findStr.length();` with `lastIndex += indexWord.length();`?
Comment: great.its working fine now.Thanks for saving my time.
Comment: I'll add an answer so this question can be marked as resolved
Answer: When you increment lastIndex after a match, you mean to increment it by the length of the match (indexWord), not the length of the string of input words (findStr). Just replace the line
lastIndex += findStr.length();

with
lastIndex += indexWord.length();

Answer: try this code
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

lastIndex = str.indexOf(findStr,lastIndex);

 if(lastIndex != -1){
    count ++;
    lastIndex += findStr.length();
 }
}
System.out.println(count);

Answer: You can use map for this as well.
public static void main(String[] args) {

        String value = "This is simple sting with simple have two occurence";

        Map<String, Integer> map = new HashMap<>();
        for (String w : value.split(" ")) {
            if (!w.equals("")) {

                Integer n = map.get(w);
                n = (n == null) ? 1 : ++n;
                map.put(w, n);
            }
        }
        System.out.println("map" + map);
    }

Answer: Is there any reason of not using the readymade API solution in place.
This can be achieved by using the StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.
E.g.
String input = "This is stackoverflow and you will find great solutions  here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";
String findStr = "stackoverflow is";
for (String s : Arrays.asList(findStr.split(" "))) {
         int occurance = StringUtils.countMatches(input, s);
         System.out.println(occurance);
}


AzureDevOps | GitHub, required status check

Question: I have setup AzureDevOps to build Xamarin mobile application, using GitHub (not Azure Repos yet).
In image below, Merge button is still clickable. I would like to disble it until build is completed successfully. I can not see any option to add WebHook for AzureDevOps to restrict branch protection rules via GitHub, all is managed via pipeline triggers from azure console
Answer: Fixed by adding pipeline name in branch rules.


Why do we have non-free software in the official repositories?

Question: The Ubuntu wiki describes the "sections" of the official Ubuntu repositories as follows:

Main - Officially supported software.
Restricted - Supported software that
  is not available under a completely
  free license.
Universe - Community maintained
  software, i.e. not officially
  supported software.
Multiverse - Software that is not
  free.

I thought that software in the Ubuntu repositories had to be open source, however doesn't the description of the Multiverse directly contradicts this?
Comment: There are different reasons, most of them subjective and argumentative.
Answer: The software in Multiverse is "gratis", but not free. These are some examples of cases in which software would be appropriate in Multiverse:

The Software is not legal in every jurisdiction (DVD Decryption, ...)
It's software-patent encumbered (MP3 Codecs, ...)
It doesn't provide the user with all of the four essential Freedoms:

Run the program for any purpose.
Study how the program works, and change it to make it do what you want.
Redistribute copies at will.
Modify the program, and release modified versions.

Note that those do not include a requirement that modified version be released with a license that grants the same freedom. This is called copyleft, and it's seperate from pure free software.
There are issues with the licensing (like missing, unclear or invalid copyright notices)
Any of the above is disputed or unclear

As htorque quotes, "The onus is on you to verify your rights to use this software ".
Note also: much of the software in Ubuntu enters the repositories through being in Debian first, so the Debian Social Contract & The Debian Free Software Guidelines are of some relevance.
Comment: Great info, but as far as I can see this doesn't answer the question. It talks about what is the situation, but not why. I believe that you can expand a little bit the answer with that info.
Comment: very good point. But I'm very hesitant to explain why, because there isn't really a well documented, factual answer. It's going to be subjective. I don't want to get into a holy-war argument. But I'll think about it, and see if I can't find a few documented reasons. Maybe @MarkShuttleworth should answer the question. (he is [around](http://askubuntu.com/users/5287/mark-shuttleworth)) ;-)
Answer: I'm not Shuttleworth, but the Ubuntu objective is not to ship a Pure Free Distro, but to solve Bug number 1. In order to be able to solve it, it needs to supply non-free software that users demands. Specially closed software firmware that is needed by lots of drivers to work.
If you are interested in a totally free system you can select "Only install free software" while installing Ubuntu.
Summarizing the answer in just one word: Pragmatism.
Comment: Gobuntu is no more; it's been merged into mainline Ubuntu, you can now get the same effect by selecting "Only install free software" on the Live CD boot-screen.
Answer: My answer is no
Now we should make it clear first as to what "free" means here. Are you talking about free of charge or free of use?
I believe open source concept is free of use, but it doesn't necessarily have to be free of charge as well.
Comment: That's not what he meant. There is non-free software in main because it's necessary in order for people to use Ubuntu. Drivers, etc.


Why nm libc.so reports no symbols?

Question: I've built a simple program like this:
g++ application.cpp -o application.exe
and then executed the command;
ldd application.exe
...
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
...

I want to list all the symbols of the libc library:
nm /lib/x86_64-linux-gnu/libc.so.6
nm: /lib/x86_64-linux-gnu/libc.so.6: no symbols

nm --defined-only /lib/x86_64-linux-gnu/libc.so.6
nm: /lib/x86_64-linux-gnu/libc.so.6: no symbols

Why nm reports no symbols? If libc.so.6 is not a library, but a some kind of a link to the actual library, then how can I find the actual library?
Comment: Is `/lib/x86_64-linux-gnu/libc.so.6` stripped? What is the output of `file /lib/x86_64-linux-gnu/libc.so.6`?
Comment: You can try `readelf -s libc.so.6`, also see [Why nm shows no symbols for /lib/i386-linux-gnu/libc.so.6?](https://unix.stackexchange.com/questions/282616/why-nm-shows-no-symbols-for-lib-i386-linux-gnu-libc-so-6) .
Answer: By default, nm reads the .symtab section in ELF objects, which is optional in non-relocatable objects.  With the -D/--dynamic option, you can instruct nm to read the dynamic symbol table (which are the symbols actually used at run time).  You may also want to use --with-symbol-versions because glibc uses symbol versioning extensively.
Alternatively, you can use eu-readelf --symbols=.dynsym or objdump -Tw.  (readelf -sDW does not include symbol versioning information.)
Comment: Thanks! Why --dynamic isn't a default option then??
Comment: @FlorianWeimer: Curiously, the commentary I remember from 1998 already regarded it as a bug that `nm` doesn't list exported symbols from stripped `.so` files by default.
Comment: The `nm` command is very old and dynamic linking did not exist back then (and some binutils targets still do not support it). Changing the data source based on object type would likely be too confusing.
Comment: OK, maybe there exist more modern and convenient tools for analysing library symbols then?
Comment: `--with-symbol-versions` appears to be the default with `nm`, so only the `-D/--dynamic` is required for to read the dynamic symbol table.

Why nm libc.so reports no symbols?


PHP CSV Column Headings

Question: I'm exporting a some data from a survey to CSV for use by another team with PHP. I have outputted my first row of data as all of the headings. But I need some of the headings to span 2 columns is the at all possible.
The headings are all in correctly, but I need to add two cells of data underneath some of the headings.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=lite-survey-data_'.time().'.csv');

require_once ( dirname(dirname(dirname(dirname(__FILE__)))).'/wp-load.php' );

$content =build_csv_download();
$headings = convert_to_csv($content[0]);
$csv_content = convert_to_csv($content[1]);
$output = fopen('php://output', 'w');
fwrite($output, $headings);
fwrite($output, $csv_content);

Any ideas?
Answer: It's not possible to have headings that span two columns as CSV is such a basic format it doesn't allow you to represent merged cells. However if the second of the two columns has no header (so heading,,nextheading) then when you open it in Excel the heading will spread across into the empty cell.
Comment: This could be the answer i'm looking for. I forget how primitive .csv can be at times. Just trying it now. Cheers for the suggestion though.
Answer: CSV doesn't support column-spanning, so you'd just have to put the same field header on top of two columns.  It's not the prettiest thing in the world, but then CSV isn't the most flexible format in the world either.
Answer: CSV does not support column spanning. Some programs like Excel might try to make sense out of missing headings or other such tricks, but that doesn't leave you with a valid CSV file. See https://www.rfc-editor.org/rfc/rfc4180
Concatenate the data with a non-significant string (like a space or a hyphen) before making the CSV data. Basically, you're just taking the two data columns and making them in to one.
The easiest way to do this is to use CONCAT (docs) to combine the stings right out of the database:
    SELECT
        id,
        CONCAT(first_name, " " last_name) AS name,
        email
    FROM
        users

 /*   Gives these results:
    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => Bob Someuser
                [email] => email@example.com
            )

        [1] => Array
            (
                [id] => 2
                [name] => George Anotheruser
                [email] => email@example.com
            )

    )
*/

If you can't do that in the database query, you can use array_walk (docs) to do it after the fact:
$headings = array(
    'First heading',
    'Second heading',
    'Third heading'
);

$one_data = array(
    'First data',
    'Second',
    'data',
    'Third data'
);
$data = array();
for ($x=0;$x<10;$x++)
    $data[] = $one_data;

print 'Before fix:';
print_r($data);

function prepare_array (&$item) {
    $item[1] = $item[1].' '.$item[2];
    unset($item[3]);
}
array_walk($data, "prepare_array");

print '

After fix:';
print_r($data);

function csv_array (&$item) {
    $item = implode(',', $item);
}
$csv = implode(',', $headings)."\n";
array_walk($data, "csv_array");
$csv .= implode("\n", $data);

print '

CSV:
'.$csv;

PHP CSV Column Headings


Trying to solve this triple integral: $\iiint (x-1)(y-1) \,dx\,dy\,dz$

Question: Here's the question
$$\iiint (x-1)(y-1) \,dx\,dy\,dz.$$
I am asked to evaluate this integral over the region $$D:=\left \{ (x,y,z) \in\mathbb{R}^3 :x^2+y^2 \leq z \leq 2x+2y+2 \right \}.$$
There are the bounds of integration in set D (the variable $z$ is isolated) and well I tried to find the solution of this integral :
\begin{align*}
&\iint_{Pr_{(y,x)}(D)}\int_{x^2+y^2}^{2x+2y+2}(x-1)(y-1) \,dx\, dy\, dz \\
=&\iint_{Pr_{(y,x)}(D)}\int_{x^2+y^2}^{2x+2y+2}(xy-x-y+1) \,dx\, dy\, dz,
\end{align*}
and integrate only with respect to $z.$ I have that:
\begin{align*}
\int_{x^2+y^2}^{2x+2y+2}(xy-x-y+1) \,dz&=(xy-x-y+1)*(2x+2y+2-(x^2+y^2)) \\
&=3x^2y+3xy^2-2x^3y-2xy^3-3x^2+x^3-2xy-3y^2+y^3+2.
\end{align*}
It looks like this way is too long. The second thing that came to mind when I saw the set $D$ was to apply cylindrical coordinates, but this doesn't make easier the left member of the set $D.$
What can I do or what have I done wrong up until now?
Any support for this question would be appreciated.
Answer: Hint. Note that the intersection of paraboloid $z=x^2+y^2$ and the plane $z=2x+2y+2$ projected onto $xy$-plane is given by the circle $x^2+y^2=2x+2y+2$ that is
$$(x-1)^2+(y-1)^2=2^2.$$
Hence the given triple integral becomes
$$\iint_{(x-1)^2+(y-1)^2\leq 2^2}\int_{x^2+y^2}^{2x+2y+2}(x-1)(y-1) dx dy dz,$$
and after integrating with respect to $z$ we get
$$\iint_{(x-1)^2+(y-1)^2\leq 2^2}(x-1)(y-1)(4-(x-1)^2-(y-1)^2) dx dy.$$
Now use the polar coordinates centered at $(1,1)$. Can you take it from here?
Comment: @andrew OK. BTW I am happy that you appreciated my previous comment.
Comment: Yes i understood


Is waiting for Baron Nashor's buff on enemies to dissipate still viable?

Question: When the buff still applies to the champions, it is okay to pass some time and face enemies without the additional stats.
But now, since the buff affects the minions, is it still advisable to wait for the buff to disappear if :

the enemy has the buff.
the scores are even.
both teams still have 3rd tower on all lanes.
considering that they're most likely to go all in 1 lane.

I mean should we defend and wait for the end of the buff or make some isolated kills to remove their buff?
Comment: Do you mean the team with or without the buff?
Comment: I am not sure what you are asking. Are you asking if it is a good strategy for the team without baron-buff to wait for the buff to wear off before team team fighting?
Comment: @Randomizer Is there any particular reason why you rejected my edit? As it stands, there is a lot of confusion around what you mean.
Comment: Clarify what you want to know.
Comment: Sorry for confusing. Question edited.
Answer: It highly depends on the game, but in most cases you were ahead and that fact got you the baron buff.
Baron buff currently gives you increased Attack Damage and Ability Power (which scales over time)
That leads to the fact that you will probably will lose every teamfight. If there are a lot of minions around, you should definitly avoid to fight a team that has the baron buff.
Just try to play defensive and make picks when an enemy is out of position.
Answer: It really comes down to a game to game basis. Most games, at least in my experience, one team clearly has the advantage by the time nashor is killed. Because of that, I would say it is almost always a good idea to use it to push. If you are ahead by a ton, you usually just want to end it. If you are down by a lot, this is usually your last ditch effort. On the off chance you have a game where either side could win, it can be useful to sit on it and use it as a deterrent to stop your opponents from farming and possibly giving you that small edge you need.
Answer: Depends on both compositions, and the current state of the game.
In short, you should just avoid them sieging you at the turrets, because not only they can dive easily and take the turret, but the minions will also hit you hard.
If you have mobility and good waveclear, it's a good idea to have one person roaming and killing minion waves that aren't affected by the buff.
If you're able to pick people then you should do it (eg: Blitzcrank, Thresh, Amumu, etc) so that if they do siege they will be 4v5.
If you're really ahead and you're able to 5v5, DO IT ASAP. The more you stall, the more they can catch up, you should just take them out.
However, if you see them taking the baron.  preferably you should kill them before they get a chance to recall, so that they lose the buff.
Answer: There are several other factors in play on how to do this, but OP is asking "given x, should I do y or z?"
The answer here will almost always be: try to fight them, or at least try to discourage them from pushing on you (poke or get another lane autopushing).
Reasoning:
Given the circumstances, it is likely that a fair teamfight should end in a slight favor to the team with the baron buff. This would, in a fair-case-scenario end with one player (lets hope its not Jinx) on the other team surviving. Most of the time, teamfights are also slightly spaced out in time, which means they will have to choose between overextending or not getting an objective. Either way, you win.
Lets consider the other scenario; stay and defend as 5. Considering equal compositions, you will almost always lose at least half your turret for free, and at the same time give up control of your own jungle and sidelanes. Yes, your risk is probably lower while the baron buff is live, but you will certainly always lose something.
There are pros and cons and you can discuss the weighing of arguments here, but in the end, I will always choose an option that gives me a chance to gain an advtange.


Why is my WSL Ubuntu 22.04 saying "Failed to configure: Unsupported session typer" when I ran gnome-shell?

Question: Why is my gnome-shell saying "Failed to configure: Unsupported session typer" in WSL Ubuntu 22.04?
When I ran

gnome-shell

in my WSL Ubuntu 22.04 terminal, it said "Failed to configure: Unsupported session typer".
Is there anyways to fix this issue? I have been having this issue for a long time. I have tried upgrading and updating both WSL and Ubuntu 22.04 but still it doesn't work. I have installed gnome-shell too.
If someone knows the solution it would be a life saver.
EDIT:
It is not really similar to the following question.
Run ubuntu-desktop on WSL (Ubuntu 18.04 LTS)
Also, I'm a beginner programmer so I'm sorry if I had done mistakes.
EDIT 2:
It has been solved.
Thanks.
Comment: Does this answer your question? [Run ubuntu-desktop on WSL (Ubuntu 18.04 LTS)](https://askubuntu.com/questions/1162808/run-ubuntu-desktop-on-wsl-ubuntu-18-04-lts)
Comment: Thanks for the link but It doesn't answer my question.
Comment: Basically, the point is that you don't need to run the command `gnome-shell` in WSL. Running GNOME shell in WSL will just graphically overlap with your Windows taskbar, and it might confuse you. The correct way to run graphical applications on WSL is to set up WSLg, and then directly run the app you want (firefox, nautilus, etc.), without starting `gnome-shell`.
Comment: Oh, thanks a lot.
Comment: I thought it was some kind of a shell or something.
Comment: There are two definitions of "shell" here. 1. A https://en.wikipedia.org/wiki/Shell_(computing)#Command-line_shells is like bash, dash, csh, zsh, and runs inside your terminal. 2. A https://en.wikipedia.org/wiki/Shell_(computing)#Graphical_shells is either the Windows taskbar, or `gnome-shell`. You already have one of each type of shell running, and you don't need to start another one.
Comment: Oh I get, thanks.
Comment: Please add an answer, and mark is as solution.
Answer: You don't need to, and shouldn't run gnome-shell in WSL. Copied from my comments on @davidbaumann's request.
On WSL, you need a X Or Wayland server running on the Windows 11 host's side to show graphical applications. Older answers here might suggest third-party X servers. In modern times, Microsoft has released a more integrated solution, WSLg. According to https://learn.microsoft.com/en-us/windows/wsl/tutorials/gui-apps , it is enabled by default on new installs with wsl --install. To enable it for existing installations, there are further details at https://github.com/microsoft/wslg .
Is gnome-shell some kind of a shell or something?
There are two definitions of "shell" here. 1. A https://en.wikipedia.org/wiki/Shell_(computing)#Command-line_shells is like bash, dash, csh, zsh, and runs inside your terminal. 2. A https://en.wikipedia.org/wiki/Shell_(computing)#Graphical_shells is either the Windows taskbar, or gnome-shell. You already have one of each type of shell running, and you don't need to start another one.
If you open two terminal windows, you have two command-line shells. If you run another bash inside one of the bashes (perfectly safe), you would have 3 command-line shells.
However, you do not want to run two graphical shells. A graphical shell is usually the taskbar plus some other things. You do not want two taskbars on screen! One might overlap the other, and confuse you when you try and click but the wrong taskbar gets clicked. Furthermore, gnome-shell says it manages window switching, which Windows 11 itself wants to manage. When you log into Windows, you have the perfectly functional graphical shell (one of the functions of explorer.exe) that comes with Windows. The only reason a bare-metal Ubuntu installation needs to start gnome-shell is because nothing else is providing a taskbar.
So basically, you want to skip trying to start gnome-shell and jump to trying to run the application you are trying to use. After WSLg is set up, just running firefox or nautilus in terminal should open the corresponding application window.


systemd-networkd - No networking in recovery mode

Question: Running UbuntuGnome 17.04 I am not enable to start networking in recovery mode, because there is an unknown group "power" in message bus configuration file error when NetworkManager is trying to connect. NetworkManager won't connect.
I am using a Wireless Lan Adapter:
Bus 003 Device 004: ID 0bda:8172 Realtek Semiconductor Corp. RTL8191SU 802.11n WLAN Adapter.
 In an older Version of Ubuntu Gnome it was possible to enable networking using this adapter.
EDIT:
I could solve the 'unknown group "power" in message bus configuration file' error due to cd /etc/dbus-1/system.d and find . | xargs grep 'power'. It showed up that thermald seems to not work properly. Purging it temporarily the error was not shown up. But NetworkManager didn't connect as well. Running root from recovery it tells me that nmcli can not be found. But it is installed and works properly running the system in graphic mode as user. Any ideas how to solve this?
EDIT:
I decided to use systemd-networkd for running as root in recovery. I disabled Network-Manager and enabled systemd-networkd as well as systemd-resolved. I could start systemd-networkd. But I don't know how to scan for wifi and connect to it. Or maybe just connect to it with typing in the needed informations... Any ideas?
Thanks a lot
Comment: Is a wired network connection an option in recovery mode? If not you need to create a systemd service for your wlan interface, referring to a /etc/wpa_supplicant/wpa_supplicant.conf specifying ssid and psk key to use. (Sorry I realize the last piece is not very concrete, hence asking if wired is an option.)
Comment: Any details to the error? What if you execute the piece after 'ExecStart' directly? (So something along the lines of: /sbin/wpa_supplicant -i%i -c/etc/wpa_supplicant/wpa_supplicant.conf
Comment: the %i needs to be replaced with the actual interface. looking at your other logfiles it seems this is 'wlx24050f7cdde7'. so please post output of  `/sbin/wpa_supplicant -iwlx24050f7cdde7 -c/etc/wpa_supplicant/wpa_supplicant.conf`.
Answer: 1: Boot to recovery mode
2: Drop to a root shell prompt (read only)
3: Remount file system to read and write:
mount --options remount,rw /
mount --all

4: Add dns server just to be safe that DNS will work:
vi /etc/resolv.conf

add
nameserver 22.214.171.124

(188.8.131.52 is the Google DNS server)
5: Reboot and get into a root shell again with read/write access
Remount to read and write:
mount --options remount,rw /
mount --all

6: Stop networking:
systemctl stop network-manager

7: Setup wireless connection and scan:
ifconfig wlan_name up

iwlist wlan_name scan

8: Create wpa configuration file and connect:
wpa_passphrase NETWORK_ID WIRELESS_KEY > /home/(username)/wpa.conf

wpa_supplicant -B -i wlan_name -c /home/(username)/wpa.conf

Ignore any IOCSIWENCODEEXT and SIOCSIWGENIE errors, and finally run:
dhclient wlan_name

If you don't want to create a file to save your config, use these commands instead:
iwconfig wlan_name essid NETWORK_ID key s:WIRELESS_KEY

dhclient wlan_name

Source:
https://ubuntuforums.org/showthread.php?t=2164398
Answer: First find out the name of your wirless interface using ifconfig. Then run:
ifconfig wlan_name up

where wlan_name is the name of your wireless interface.
This will enable your wireless interface. There won't be an output. Next thing you have to do is to search for the wireless networks near you.
iwlist wlan_name scan

You will see a list of wireless networks in your area. Find out the wireless network you want to connect to and run the following:
iwconfig wlan0 essid NETWORK_ID key s:PASSWORD

where NETWORK_ID with the name (SSID) of the network and PASSWORD is the network passphrase.


Whats means the : operator in str.format()?

Question: Take {:.2f}.format(x) for example. This gives me the as output a fixed-point number with precision 2 as output. What does the : means?
I also have another question:
Why does the upper function doesn't work when i give as input x = 7.5643915285818e+210+4.6951592215e+280j?
Answer: Colon (:) is used instead of % in formatting.
Refer this link


I want to know if my ram is ok for Ubuntu

Question: Hi i have a amd64 2800mz procresor with 256MiB RAM, what Ubuntu can install to run smoothly?.
Answer: Unfortunately its not enough RAM, it doesn't even meet the minimum required (512MiB RAM) to run Ubuntu (11.XX and higher versions).
You can go ahead and try to install Xubuntu instead which its been said to run on a 256MiB minimum but i doubt it would run at all and if it does it wont be even near to "smooth".


How to use /scoreboard to have a list of names on the sidebar

Question: I have a prison and 3 levels: Guards, prisoners and Receptionist. I want to display a list of everyone in those groups and add different colours them. How would I achieve this?
Example...
<code>Guards:
teddy9264
diamond_knight1

Prisoners:
Minecraft_Player77
A_Prisoner

Receptionist:
Minecraft_Player99999
</code>
Thank you in advance,
Comment: What have you tried to acomplish this on your own? It is easier to answer your question if we know what you tried so far.
Comment: Is this text static or do you want to dynamically create the list?
Comment: Have you made any attempt to solve this yourself? Arqade works better when askers show effort to solve their own problems; we see that you have a problem you've worked on, and answerers respond to that. You also get a more specific answer that's tailored exactly to the part you're stuck, and Arqade gets a very specific question. Everybody wins!
Comment: Sorry everyone, been away but back now... it is static. Thanks for your response
Comment: I have made teams, made an adjective then added the players to the list then I made it go on the side. but it only comes up with the team name not the people in the team
Answer: Unfortunately, this isn't possible using Vanilla Minecraft, although you could do something like it:
/scoreboard objectives add playerlist dummy Players
/scoreboard objectives setdisplay sidebar Players
Then, on a clock:
/scoreboard players set @a playerlist 1
This won't be perfect, but it should be enough for what you want to do, and if you have colored names for players on teams, it will display the colors as well.


Advanced Filtering in Data Table

Question: The Problem
I have a data table, that's on slide-over, fixed to its bottom.
I need do advanced filtering of data.
For example:
<code> 1. I want only the drug with exact name "Aspirin"
 2. I want drugs, that contain name "Aspirin" (e. g. "Aspirin for Kids")
 3. I want drugs, both "Lisoprophil" and "Aspirin"
 4. I want drugs, with exact name "Lisoprophil" and all that contain name "Aspirin"
</code>
Also, I want easily back to defaults (or clear selected) or deselect some of the criteriums.
There is a technical restriction - it should be pop-up or dialog window or something not full-screen.

So, here I've done some work. But, of course, it doesn't seem perfect solution.

I can only add drugs one by one (I should exit pop-up, and then click on filter icon again)
Pop-up look and options ("Clear All") varies.

Sorry for grammar mistakes, if any
Comment: So, as example, the result of filtering will be 1. Data row, that has drug "Aspirin". 2. Two different data rows - one has drug "Aspirin", another - "Aspirin for Kids". 3. - 4. The same as 2 - two different data rows, each with its unique drug name.
Comment: Are you having issues in the filter selection or in the filter results?
Comment: @Alvaro I have several issues in filter selection. For example, I don't know how to add several drug names (some can be exact names, and some "contains") at the same time without closing pop-up. I don't know is it ok to show "Clear All" function when he opens filter pop-up and only then.
Comment: Some questions: **1**. When you say exact name "Lisoprophil" and "Aspirin", do you mean both names in the title or only one at least?   **2**. Do you need to differentiate if "contains" refers to one of the specific "exact names". For example in this search query: exact name="Lisoprophil" and "Aspirin" ; contains="for adults" needs to be refered to "Lisoprophil" **or** "Aspirin", or to any of them?
Comment: @Alvaro 1. I mean only the one name in the title. For example that data row will be like: #Patients - 2, Drug Name - "Aspirin". Not "Aspirin","Lisoprophil". Not "Aspirin for kids".
Comment: 2. To any of them, if it's only not the exact drug name :)
Answer: If I understood the case correctly, I suggest:

Keep the filter edit (add, remove, etc.) in a dialog.
Differentiate clearly between "exact name " and "might contain".

For example:
Comment: Thank you, it's sounds reasonable. But I am looking for the compact solution. I already have slide over with overlay. So, I am doubtful about modal dialog
Answer: For the filter menu content, I agree with @Alvaro 's solution.
However, if you find that the current layout is your main problem, I suggest you to use accordion-like menu like the one used on Gmail filter. It is much tidier in my opinion, because the position only expanded from the parent layout (in your case, table header) so it looks more like it only belongs to that column.

Advanced Filtering in Data Table


Linear gradient causes banding in chrome

Question: I am facing issue with linear gradient in chrome. Here is my code

div{
  background: linear-gradient(20deg, rgb(213, 213, 55), rgb(158, 158, 33));
    background: -webkit-linear-gradient(20deg, rgb(213, 213, 55), rgb(158, 158, 33));
    background: -moz-linear-gradient(20deg, rgb(213, 213, 55), rgb(158, 158, 33));
    background: -o-linear-gradient(20deg, rgb(213, 213, 55), rgb(158, 158, 33));
  width:400px;
  height:400px;
}

While using gradient some banding occuring in chrome. Gradient not look smooth on chrome. Here is screenshot for same.

Please help.
Comment: The gradient looks perfectly smooth for me. What version of Chrome do you use? Can you maybe capture a screenshot of the banding?
Comment: what you mean by banding? the output and screenshot seems normal! May be you have some problem with your Display! (check it in another pc/smartphone/display)
Comment: I have added image above. I am using chrome 54.0.2840.59
Comment: I don't see a noteworthy banding on the screenshot as well, looks like in Firefox ¯\\_(ツ)_/¯ However, the latest Version of Chrome is 61.0.3163.100, you may want to upgrade and take a look again.
Comment: I have tested on onther machine. I can see the banding in screenshot and in html also. Anyone have any idea what could I do?
Comment: No apparent banding - Chrome Version 62.0.3202.29 (Official Build) beta (64-bit)
Comment: Silly question...this isn't a question of the *angle* is it?
Comment: I facing problem with my chrome version that's why I asked this question.
Answer: You can try to use 2 layers. From color to transparent, and superimpose them on each other:

div {
  position: relative;
  background: linear-gradient(20deg, rgb(213, 213, 55), transparent);
  width: 400px;
  height: 400px;
}

div:before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: linear-gradient(20deg, transparent, rgb(158, 158, 33));
}


IntentHandler can't read UserDefaults but Timeline can

Question: I want to read UserDefaults when a user changes the configuration for a widget, so I created an app group and added the capabilty to my main app, the widget extension and the Intent extension.
I can read and write fine between my app and the widget extension, however the UserDefaults always return nil in IntentHandler.swift, what could cause this?
// called from TimelineProvider
func example() -> String {

let sharedDefaults = UserDefaults.init(suiteName: "group.myname")
  let value = sharedDefaults!.value(forKey: "myKey") as! String
// value == "Hi this works!"
}

But when I call example() from my IntentHandler value is nil. (It crashes)
Comment: Double check the intent capability, or remove it and add it again.
Comment: @EmilioPelaez ... Such a stupid mistake . It was only enabled for release mode, not debug. I need to take a break from this lol.
Answer: As EmilioPelaez commented, double check the capabilities (even if you've already done so, I didn't notice this either). My app group was only enabled for release mode, not debug. Should have noticed this sooner...

IntentHandler can’t read UserDefaults but Timeline can


Will ubuntu support subversion1.7 and when will it be?

Question: Since svn is the most widely used centralized source collaboration repository: are there plans for supporting the current version (1.7) out of the box in the near future?
Comment: For the current 12.04 LTS you can get it installed following the answers in http://askubuntu.com/questions/65468/where-can-i-find-a-subversion-1-7-binary. There's one mentioning the "Subversion team" PPA, which, IMHO, is your best bet.
Answer: <code>$ rmadison -u ubuntu -s quantal subversion
subversion | 1.7.5-1ubuntu2 |       quantal | source, amd64, armel, armhf, i386, powerpc
</code>
Looks like 12.10 has version 1.7.5 of Subversion in the repository already.

Now, if you are asking whether 12.04 and the older versions would have the latest version, I would say no.
See also:

Why don't the Ubuntu repositories have the latest versions of software?
Why can't I update applications without upgrading the whole OS?
Where can I find a Subversion 1.7 binary?
Comment: I can verify on http://packages.ubuntu.com/quantal/subversion.


Question about Event firing in reflex-frp

Question: This is the first Haskell and reflex-frp project I'm working on and I've put together what I have from a bunch of examples and projects I found on github. I am basically trying to log three events to the console, but only two seem to be firing and I don't understand why.
I have a route function (this function is really longer with a bunch of other definitions for other routes, but focusing on this one).
route :: R FrontendRoute -> State -> FTNet t m (Event t State)
route (FrontendRoute_Logout :/ ()) (StateLoggedIn _) = do
    pb <- getPostBuild
    el "h1" $ text "logging out..."
    setRoute $ FrontendRoute_Login :/ () <$ traceEvent "logA" pb
    setRoute $ FrontendRoute_Main :/ () <$ traceEvent "logB" pb
    pure $ StateLoggedOut <$ traceEvent "logC" pb

and some other things that may be relevant
data State = StateLoggedOut | StateLoggedIn User deriving stock (Eq, Show)

type FTNet t m = RequesterT t AuthApi (Either Text) m

data AuthApi a where
   …

I get this output in the console
logB: ()
logA: ()

I'm confused why logC isn't printed, also confused how the order of output gets decided, why does logB get printed before logA?
Answer: Through help on https://web.libera.chat/#reflex-frp this can be marked solved.
I was using the result of the route function in a switchHold like this
    initState :: FTNet t m ()
    initState = do
      rec dyState <- holdDyn StateLoggedOut stateUpdatedEv
          dyRoute <- lift askRoute
          el "div" $ dynText (T.pack . show <$> dyState) -- temporary for debugging
          stateUpdatedEv <- switchHold never =<< dyn (routeWithMenu <$> dyRoute <*> dyState)
      pure ()
    routeWithMenu :: R FrontendRoute -> State -> FTNet t m (Event t State)
    routeWithMenu r s = do
      lift $ el "div" $ menu r s
      route r s

but I needed to be using switchHoldPromptly instead


Dominant and Injective Morphisms

Question: As mentioned before, I am self-studying some commutative algebra out of "A Course in Commutative Algebra" by Kemper. In the text, Kemper has the following problem:
Let $X$ and $Y$ be affine varieties over a field $ K$, and let $f: X → Y$ be a morphism with induced
homomorphism $ϕ: K[Y ] → K[X].$ We say that $f$ is dominant if the image
$f(X)$ is dense in $Y$ , i.e., $f(X) = Y$ .
Show that $f$ is dominant if and only if ϕ is injective.
He provides a proof of the forward implication namely,
Assume that $f$ is dominant, and let $ϕ(g) = 0$ with $g ∈ K[Y]$. Viewing $g$
as a regular function $Y → K,$ we have $g\circ f = 0,$ so the restriction of $g $ to
$f(X)$ is zero. Since $g$ is continuous and $f(X)$ is dense, this implies $g = 0$.
I am trying to understand the overall structure of this proof however I had 3 questions regarding some details.

In viewing $g: Y \rightarrow K$ as a regular function, how comes he can conclude that  $g\circ f = 0,$?

Having  $g \circ f = 0,$, how does this imply that restriction of $g $ to
$f(X)$ is zero?

I see why $g$ is continuous ( I believe here he means continuous in the Zariski Topology), but how does the continuity of $g$ and the fact by the hypothesis $f(X)$ is dense imply that $g = 0$.

Once we have the result that $g = 0$, the injectivity follows immediately. Any help in coming to terms with my 3 questions would be highly appreciated.
Answer: Let me try to answer your questions:

This is just the definition of the morphism $\phi$. Under the assumption that $g\in\ker(\phi)$ this means $g\circ f=0$.
$g\circ f=0$ means that for any point $x\in X$, $g(f(x))=0$, so the restriction of $g$ to $f(X)$ is zero.
There is the following theorem: Let $T$ be a reduced scheme and $S$ a separated scheme, $U\subset T$ dense open set. Then two morphisms $f,g \colon T\rightarrow S$ that agree on $U$ must be equal. As you are working with affine varieties all of these properties are satisfied, so $g=0$.

Hope that helps!
Comment: To question 3: Suppose $f,g\colon X\rightarrow Y$ agree on a dense open set $U$. One can show that $\mathrm{Eq}(f,g)$, the set where $f$ and $g$ agree, is closed. As $U\subset \mathrm{Eq}(f,g)$ it follows that the underlying topological spaces of $\mathrm{Eq}(f,g)$ and $X$ agree.
Comment: Regular functions are always continuous.
Comment: Thank you very much for the explanation! iI have not run into the last theorem yet but it definitely does the trick.
Comment: Just one more question, i thought i resolved the issue as to why $g$ is continuous, but that turned out to be wrong What is the reasoning there?
Comment: Also, I am not too familiar with scheme's. Is this theorem the only lense in which my question to 3 makes sense?

Dominant and Injective Morphisms


json ajax animation prevents sending data through php

Question: I am building a form to submit email messages. When I add the ajax animation, the data can't be pass to php. Not sure why. Please help, thanks a lot.
Here is the js
    //contact form
var form = $('.contact-form');
form.submit(function () {
    $this = $(this);
    $.post($(this).attr('action'), function(data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    },'json');
    return false;
});

Here is the php
<?php
header('Content-type: application/json');
$status = array(
    'type'=>'success',
    'message'=>'Thank you for contacting us, we will get you back soon!'
);

$firstname = @trim(stripslashes($_POST['firstname']));
$email = @trim(stripslashes($_POST['email2']));
$lastname = @trim(stripslashes($_POST['lastname']));
$message = @trim(stripslashes($_POST['message']));

$email_from = $email;
$email_to = 'firstname.lastname@example.com';

$body = 'First Name: ' . $firstname . "\n\n" . 'Last Name: ' . $lastname . "\n\n" . 'Email: ' . $email . "\n\n" . 'Message: ' . $message;

$success = @mail($email_to, 'Mortise Message' , $body, 'From: <'.$email_from.'>');

echo json_encode($status);
die;

?>
Here is the HTML
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
    <input name="firstname" id="firstname" type="text" placeholder="First Name">
    <input name="lastname" id="lastname" type="text" placeholder="Last Name">
     <input name="email2" id="email2" type="text" placeholder="Email address">
     <textarea name="message" id="message" rows="8" placeholder="Message"></textarea>
     <button type="submit" class="btn btn-primary btn-lg">Send Message</button>
</form>

Comment: Try this `$.post($(this).attr('action'),{form_val: val,...}, function(data) {
        $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
    },'json');`
Comment: @ChristopherDíaz, this method also works. Thank you very much.
Answer: I recommend using "ajax" instead "post"

  $.ajax({
      type: 'POST',
      url: 'http://www.yoururl.com',
      data: {key:'data'},
      success: function(data){
          alert(data);
      }
  });

And ensure that you are passing the right parameters to your php.
According to this example:
$.post( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
});

The first post parameter is the url, so be sure that "$(this).attr('action')" is correct.
Answer: First things first.... You are not posting any data to the PHP File that processes the AJAX... you may want to try something along these lines:
JAVASCRIPT: UPDATED TO ALERT SOME MESSAGES...

PHP
    <?php

        // IF THIS DOESN'T WORK, TRY REMOVING THE HEADER PART TEMPORARILY
        // TO SEE HOW THINGS PLAY OUT, THOUGH IT SHOULD NOT BE A CAUSE FOR
        //  ALARM... (ACTUALLY THE OPPOSITE).
        header('Content-type: application/json');

        $status = array(
            'type'      =>'success',
            'message'   =>'Thank you for contacting us, we will get you back soon!'
        );

        $firstname  = @trim(stripslashes($_POST['firstname']));
        $email      = @trim(stripslashes($_POST['email2']));
        $lastname   = @trim(stripslashes($_POST['lastname']));
        $message    = @trim(stripslashes($_POST['message']));

        $email_from = $email;
        $email_to   = 'email@example.com';
        $body       = 'First Name: ' . $firstname . "\n\n" . 'Last Name: ' . $lastname . "\n\n" . 'Email: ' . $email . "\n\n" . 'Message: ' . $message;
        $success    = @mail($email_to, 'Mortise Message' , $body, 'From: <'.$email_from.'>');

        die( json_encode($status) );
    ?>

HTML
    <form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
        <input name="firstname"     id="firstname"      type="text" placeholder="First Name">
        <input name="lastname"      id="lastname"       type="text" placeholder="Last Name">
        <input name="email2"        id="email2"         type="text" placeholder="Email address">
        <textarea name="message"    id="message"        rows="8"    placeholder="Message"></textarea>
        <button type="submit"       id="submit-btn"     class="btn btn-primary btn-lg">Send Message</button>
    </form>

Comment: Thanks for helping, but it's still not working... The animation is going as well. And no data has passed. I also tried took off the header, but nothing changes... Any idea why?
Comment: @ChenyuLin     Did you check the Networks Tab in your Web-Inspector? Check the Console as well... You should be able to see some output. Let me know what you find.... ***I actually updated the Success Handler in the Javascript Section to Alert something so that you can see if anything happened.***


Best practices to display a promotion code area

Question: Promotion code can lead some traffic, and increase revenues.
At the same time, if a user is ready to buy without a promotion code, you shouldn't distract him with a too much visible promotion code area.
Do you have any recommandation on how to display a promotion code area?
For instance, here are 2 options, maybe there are other options you can suggest:
Comment: You need to provide more information. I can't figure out why anyone would want to buy without a promotion code.
Comment: Are you talking about individual codes like `AS4NF2GE` or semi-public ones like `FALLDOWN` or both?
Comment: @StudentX so you always have a promotion code when you buy on Amazon?
Comment: @Crissov it can be both.
Comment: In my case promotion code is applied in the cart, right before I pay. Not on the product page.
Comment: @StudentX I've written "Buy (or any CTA)" to not be explicit about the page. So you can imagine that you are "in the cart".
Comment: Buy in the cart doesn't make sense to me, but anyway that's not the question here so let's move on.. have a look at my two cents in the answers below
Comment: "or any CTA", for instance "Add to cart".
Answer: It depends on how the company wants to brand itself to it's audience. is it as a discount site or something more exclusive? If you choose to be the latter then option 2 is better.
Answer: Users that see an empty text field will be more likely to want to fill that field with something. By hiding the field and only revealing it when the link or expand icon is clicked you are making it more optional, and reducing the amount of visual attention that it demands.
Answer:
The first option, I feel, implies that all users have one or the other promo code. If this is not the case then user will feel annoyed.
The most elegant way I feel is second one, when you are comparing the two.
Moreover, many sellers are now putting all promo codes in their blog posts or offer pages or in Facebook posts etc (this also leads to more marketing and awareness) or in other channels like coupon stores.

Said that, all depends on your actual need and target customers that you have not clearly mentioned!
Answer: My two cents : The first approach seems better, as it will prompt buyer to search for if the promotion code is available or not, and in the process they may find a promotion code for a different product and will be tempted to buy more.
Answer: I feel like having a simple text link that, when clicked, expands a input works best for a lot of cases. If the user already has a discount code then they'll look for a link to apply it so a big call to action isn't needed.


Show that $\lim_{n\rightarrow \infty} \left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}=\max\{a_1,\ldots,a_p\}$

Question: For $a_1,\ldots,a_p$ positive numbers. Show  that $\lim_{n\rightarrow \infty} \left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}=\max\{a_1,\ldots,a_p\}$.
My attempt was: for $p=1$ i have that $\left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}=a_1$ then $\lim a_1=a_1=\max \{a_1\}$. For $p=2$ we have that $\left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}=(a_1^n+a_2^n)^{\frac{1}{n}}\leq 2^{\frac{1}{n}}\max\{a_1,a_2\}$ therefore $\lim_{n\rightarrow \infty} \left(\sum_{j=1}^{2}a_j^n\right)^{\frac{1}{n}}\leq\max\{a_1,a_2\}$. I guess that the same argument works taking all the numbers $a_j$ but i do not how to prove the equality. The definition have to be, for all $\epsilon>0$ i need to find some $N_{\epsilon}$ integer such that
$$|\left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}-\max\{a_1,\ldots,a_p\}|<\epsilon$$.
I will appreciate any hint please!! Thank you
Comment: Divide the numbers by the max , then the Summation will tend to 1.
Comment: This is probably a duplicate question; but briefly, show that if $M = \max\{a_1, \ldots, a_p\}$, then $M^n \le \sum_{j=1}^p a_j^n \le p \cdot M^n$; then take both sides to the $1/n$ power and apply the squeeze theorem.
Comment: thank you for you hints, Prem and Daniel!!
Answer: Since
$$ \left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}=\exp \left ( \frac{1}{n}\log \left (\sum_{j=1}^{p}a_j^n  \right )   \right ) $$
we shall evaluate $\lim_{n \to \infty} \frac{1}{n}\log \left (\sum_{j=1}^{p}a_j^n  \right )$. Without loss of generality, suppose that $a_1$ is the largest one among all $a_i$'s, then
$$\begin{align}
\lim_{n \to \infty} \frac{1}{n}\log \left (\sum_{j  = 1}^{p}a_j^n  \right ) & = \lim_{n \to \infty} \frac{1}{n}\log \left (a_1^n\sum_{j  = 1}^{p}\left ( \frac{a_j}{a_1}  \right ) ^n  \right )\\
&=\log a_1+\lim_{n \to \infty}\frac{1}{n}\log \left (\sum_{j  = 1}^{p}\left ( \frac{a_j}{a_1}  \right ) ^n  \right )
\end{align}$$
Since $\sum_{j  = 1}^{p}\left ( \frac{a_j}{a_1}  \right ) ^n$ is bounded by $p$, $\lim_{n \to \infty} \frac{1}{n}\log \left (\sum_{j=1}^{p}a_j^n  \right )=\log a_1$ and hence
$$\lim_{n\rightarrow \infty} \left(\sum_{j=1}^{p}a_j^n\right)^{\frac{1}{n}}=a_1$$
Comment: @weymar andres Every $a_j$ is not larger than $a_1$, hence $\left ( \frac{a_j}{a_1}  \right ) ^n\leqslant 1$ and hence the sum is bounded by $p$.
Comment: Why is bounded by $p$, sorry i do not get it.


PCIe Bus Error, Physical Layer

Question: When I run the command dmesg it shows 3 times the following error:
[    2.725876] pcieport 0000:00:1c.5: AER: PCIe Bus Error: severity=Corrected, type=Physical Layer, (Receiver ID)
[    2.725879] pcieport 0000:00:1c.5: AER:   device [8086:9d15] error status/mask=00000001/00002000
[    2.725880] pcieport 0000:00:1c.5: AER:    [ 0] RxErr

Is this a hardware error? how do i fix it? How to know what device is?
Comment: Does this answer your question? [PCIe Bus Error: severity=Corrected, type=Physical Layer, id=00e5(Receiver ID)](https://askubuntu.com/questions/863150/pcie-bus-error-severity-corrected-type-physical-layer-id-00e5receiver-id)
Answer: You can see the device by
lspci -nn

Find the device with [8086:9d15].

PCIe Bus Error, Physical Layer