text:
Q: How do I create another column with value of different elements in a column? I have a DataFrame object like this
ColumnOne |  ColumnTwo
ABCD      |  red
ABCD      |  blue
EFGH      |  green
IJKL      |  white

I want a DataFrame object like this
ColumnOne |  ColumnTwo | ColumnThree
ABCD      |  red       | 0
ABCD      |  blue      | 0
EFGH      |  green     | 1
IJKL      |  white     | 2

based on ColumnOne elements, how do I do this?

A: I think you're looking for pd.factorize(). From the docs:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html
Passing a Series to pd.factorize() returns two arrays: labels and uniques. labels is a numeric encoding of your categories, and uniques is an array of unique values in the Series you just passed in. So you can discard uniques and just assign labels to a new column like so:
import pandas as pd

df = pd.DataFrame({
    'ColumnOne': ['ABCD', 'ABCD', 'EFGH', 'IJKL'],
    'ColumnTwo': ['red', 'blue', 'green', 'white']
})

# factorize returns (labels, uniques) and you just want labels
df['ColumnThree'] = pd.factorize(df['ColumnOne'])[0]

Alternatively, if you convert df['ColumnOne'] to the categorical dtype, you can use any of the answers from this other post:
Get mapping of categorical variables in pandas


text:
Q: How I can replace strings in a memo (FastReport)? I have a memo object in my report, and a need replace "%...%" strings.  For example, in Rave Report:
MemoBuf.ReplaceAll('%my_str%',  "new string", false);

But, don't exists a method (or property) to replace text, in the FastReport.  How I can do this?
I'm using Fast Report 4.9.72 and Delphi 2010.
Thanks!

A: Since there is no StringReplace in FastReport available I would do it from the Delphi code. It is possible to import functions somehow but this seems to me better arranged. Please note, that in this first example I suppose that the Memo1 exists (you would get an access violation otherwise).
procedure TForm1.Button1Click(Sender: TObject);
var
  Memo: TfrxMemoView;
begin
  Memo := frxReport1.FindObject('Memo1') as TfrxMemoView;
  Memo.Text := StringReplace(Memo.Text, '%my_str%', 'new string', [rfReplaceAll]);
  frxReport1.ShowReport;
end;

If you are not sure about component name or type you should use something like this:
procedure TForm1.Button2Click(Sender: TObject);
var
  Memo: TfrxMemoView;
  Component: TfrxComponent;
begin
  Component := frxReport1.FindObject('Memo1');
  if Component is TfrxMemoView then
  begin
    Memo := Component as TfrxMemoView;
    Memo.Text := StringReplace(Memo.Text, '%my_str%', 'new string', [rfReplaceAll]);
    frxReport1.ShowReport;
  end;
end;

A: you can use this code in fast report:
function StringReplace(const S, OldPattern, NewPattern: string;
  iReplaceAll: boolean=true; iIgnoreCase :boolean=true): string;
var
  SearchStr, Patt, NewStr: string;
  Offset: Integer;
begin
  if iIgnoreCase then begin
    SearchStr := UpperCase(S);
    Patt := UpperCase(OldPattern);
  end else begin
    SearchStr := S;
    Patt := OldPattern;
  end;
  NewStr := S;
  Result := '';
  while SearchStr <> '' do begin
    Offset := Pos(Patt, SearchStr);
    if Offset = 0 then begin
      Result := Result + NewStr;
      Break;
    end;
    Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
    NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
    if not iReplaceAll then begin
      Result := Result + NewStr;
      Break;
    end;
    SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);
  end;
end;

A: I do not know what the purpose of that code was in Rave Reports as I never used it, but I can suggest alternatives for FastReport:

*

*In fast report all Memo's support variable substitution. Set up a report variable named "my_str", edit your Memo and include the variable. The text in the memo would look like this: [my_str]. This is probably the best option. The content of those brackets is actually a full blown pascal expression that can make use of dataset fields, report variables, registered functions. You could even write a Delphi function, register it with FastReport and call it from within the [..], passing a field from the dataset as a parameter. The possibilities really are endless.

*FastReport memos can be manipulated from the Delphi side, so you can use whatever function you want to change the Text of the memo.

*Memos can also be manipulated from the project's script (from within the report, not from Delphi), you can also do whatever you need to do.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access Bitcoin Daemon from Another Server I have built Catcoind (a fork of the Bitcoin / project) and I can access the commands in my terminal by doing this from root:
cd catcoin/src
./catcoind -daemon

That will start Catcoind, open the port, and allow me to type commands like './catcoind getdifficulty', but I want to access them from a PHP JSON-RPC client running on another server. The code I currently have there is:
<?php

require_once 'jsonRPCClient.php';

$catcoin = new jsonRPCClient('http://RPCUSER:RPCPASS@IP:PORT');

print_r($catcoin->getinfo());
echo $catcoin->getdifficulty();

My config file for the Catcoind build on Ubuntu is:
server=1

rpcuser=USER

rpcpassword=PASS

rpcssl=0

rpcallowip=*

bind=IP:PORT

externalip=IP

proxy=IP:PORT

port=PORT

rpcconnect=IP

When I run the code, it says that it failed to open the stream / connection refused. The config for Catcoind is at location ~/.catcoin/catcoin.conf. Any ideas? I know this is confusing, but I have really everything done but allowing external IPs to access the API. Thanks! :D

A: You don't need all these things to be written in conf file just use following
server=1
daemon=1
rpcuser=<user_namer>
rpcpassword=<password>
rpctimeout=30

if connecting from remote host do add following line
rpcallowip=<remote_ip_address>

save and exit from conf file and restart daemon by first stopping it catecoind stop and then catcoind start

A: Are external IP allowed? If not make sure that the IP is allowed so that it can call the api. The error failed to open the stream / connection refused usually means that the ip and everything is correct but the server rejected the connection.


text:
Q: Can't Update or Delete Plugins From Wordpress I'm having trouble updating or deleting anything from the plugins folder of my Wordpress install. I've tried manually deleting the plugins via FTP, but get an error message that way. I also get an error via SSH, saying I don't have permission for those files.
The plugins folder is owned and in the group www-data. Everything else is owned by the username bitnami. I'm hosted on Amazon Lightsail.
How can I change the folder ownership of /Plugins/ to bitnami so that I can edit the contents?

A: I would check to see how your WordPress install is managed. Bitnami is a package manager, which means it probably manages updates and adding/removing plugins directly.
Another solution might be running this via SSH:
sudo chown -R bitnami:daemon /opt/bitnami/apps/wordpress/htdocs
sudo chmod -R g+w /opt/bitnami/apps/wordpress/htdocs
sudo chmod 640 /opt/bitnami/apps/wordpress/htdocs/wp-config.php

This was a solution on a Bitnami Forum.


text:
Q: How to distinguish a bool from a z3 expression? I read z3 expressions from an input file in Python. Then later in my code I call __deepcopy__() on them.
The problem is that sometimes the input z3 expression is True or False, then Python gets confused and thinks they are bool and refuses to call __deepcopy__().
The error message is
AttributeError: 'bool' object has no attribute '__deepcopy__'
How can I distinguish between bool and z3 expressions in this case?

A: You could add an explicit test whether your expression is a Z3 expression, using isinstance(e, ExprRef). Note the difference between False as a Python boolean (b > 7) and a Z3 boolean (simplify(And(a > 7, b > 7))).
from z3 import Int, simplify, And, ExprRef

a = Int('a')
b = 3
expr = [a + 3,
        a < 7,
        And(a < 7, a > 2),
        And(a < 7, b > 7),
        simplify(And(a > 7, b > 7)),
        b > 7,
        True]

expr_copy = [e.__deepcopy__() if isinstance(e, ExprRef) else e for e in expr]
print(expr_copy)
for e in expr:
    print(f'Is "{e}" a Z3 expression? {isinstance(e, ExprRef)}')

Output:
[a + 3, a < 7, And(a < 7, a > 2), And(a < 7, False), False, False, True]
Is "a + 3" a Z3 expression? True
Is "a < 7" a Z3 expression? True
Is "And(a < 7, a > 2)" a Z3 expression? True
Is "And(a < 7, False)" a Z3 expression? True
Is "False" a Z3 expression? True
Is "False" a Z3 expression? False
Is "True" a Z3 expression? False


text:
Q: hide button with jquery I want to hide a button on click using jquery and not using inline functions.
I have the HTML:
<button id="mybutton" value="click me">click me</button>

and the JS:
$("#mybutton").on("click", hideelement);

hideelement = function() {
    $(this).hide();
}

the button does not hide on click.  What am I doing wrong?

A: If you'll see the accepted answer for this question you'll know what is the problem
Problem is when you define a function like
var funcName = function(){...}

So in this case you have to call this function after definition. Otherwise it won't be available.
define your function like bellow
function hideelement() {
    $(this).hide();
}

DEMO
OR change the order like this
hideelement = function() {
    $(this).hide();
}

$("#mybutton").on("click", hideelement);

DEMO

A: To add to the already working solutions with a little more detail.

Document Ready

First, make sure your code is either placed at the bottom of your body or inside a document ready, similar to the below, to make sure the element is in the DOM at the time your code executes.:
$(document).ready(function(){
   ... your code here...
});

$("#mybutton") will otherwise not be in the DOM yet when the code executes and no event will be bound.

Variable hoisting

If that is not the issue and the event is bound you may find that the way your code is written causes the error: Uncaught ReferenceError: hideelement is not defined
The reason for that is variable hoisting
$("#mybutton").on("click", hideelement);

hideelement = function(){
    $(this).hide();
}

The above code is actually interpreted by the JavaScript interpreter as follows:
var hideelement; // declaration was hoisted to the top of the scope

$("#mybutton").on("click", hideelement); // at this point hideelement is still 'undefined'

hideelement = function(){ // assignment of the value stays within the lexical scope
    $(this).hide();
}

JavaScript will hoist the declaration to the top of the current scope but will leave the assignment in the lexical scope where it was defined.
However, if you change your declaration to this:
$("#mybutton").on("click", hideelement);

function hideelement(){
    $(this).hide();
}

JavaScript now interprets the above code as follows:
function hideelement(){
    $(this).hide();
}

$("#mybutton").on("click", hideelement); // hideelements is defined

As hideelements is no longer an assignment but only a declaration the complete function will be hoisted and as such is defined at the time it is used by your event binding.

DEMO

Naturally off course the already suggested solution in the other answer of defining your assignment lexically before the use of it will also work. i,e:
hideelement = function() {
    $(this).hide();
}

$("#mybutton").on("click", hideelement);

For the sake of simplicity I intentionally did not go into global
  scope and the differences with using var.

A: $( "#mybutton" ).click(function() {
    $( this ).hide();
});

http://jsfiddle.net/17n2faLo/

A: try this $("#mybutton").click(function(){ $(this).hide() });

A: I had been looking too hard at the screen. After reversing the function definition and setting the on-click behavior, it worked.
hideelement = function() {
    $(this).hide();
}

$("#mybutton").on("click", hideelement);


text:
Q: Firewall config I am trying to see if it's possible and what commands need to be done. I am trying to block all outbound traffic to a specific ip on my local network. The back story is I am using plex and I don't want the plex app on my kodi box connecting to the local server, I am only going to use the plex server for remote viewing. Any help would appriciate do.
Brian

A: I'd use UFW.
sudo apt-get install ufw

and run it like this:
sudo ufw deny from any to 123.123.123.123

Change the IP to what you want to block. Ensure it worked:
sudo ufw status

You can always undo this by putting delete right after ufw, like this:
sudo ufw delete dny from any to 123.123.123.123

Hope this helps!

A: Alternatively, you can use sudo apt install gufw to view the firewall configuration in GUI. GUFW


text:
Q: Supremum over integral of bounded and continuous functions is $+\infty$ Let $X, Y$ be Polish spaces with probability measures $\mu, \nu$, respectively; and let $\gamma$ be a finite measure on the product $X \times Y$. We consider the maximization problem
$$
\sup_{\varphi,\psi} \bigg\{\int_{X} \varphi \ d\mu + \int_{Y} \psi \ d\nu - \int_{X \times Y} \big( \varphi(x) + \psi(y) \big) \ d\gamma\bigg\}
$$
over the set of all bounded and continuous functions $\varphi(x),\psi(y)$.
Why can this maximization problem always attain the value $+\infty$ for every initial choices of $\mu,\nu,\gamma$, if we exclude the case where $\gamma$ has marginals $\mu$ and $\nu$?

A: Let $\mu'$ and $\nu'$ be the margins of $\gamma$.  At least one of $\mu\ne\mu'$ and $\nu\ne\nu'$ must hold.
Your maximization problem becomes: maximize $$\int_X \varphi(d\mu-d\mu') +\int_Y\psi(d\nu-d\nu').$$
Assume without loss of generality that $\mu\ne\mu'$, let the signed measure $\sigma=\mu-\mu'.$  Then your maximization problem is lower bounded by the restricted maximization problem, of determining $$\sup_\varphi \int_{X}\varphi d\sigma.$$ Since $\sigma$ is not the zero measure, there exists a continuous bounded $f$ such that $\int_X f\sigma = 1$.  Now it is clear that by taking $\varphi$ to be large scalar multiples of $f$, you see the supremum is $\infty$.


text:
Q: Are numpy matrix chain multiplication optimized? I used to use the matmul (@) operator all the time in numpy, but I recently found the function numpy.linalg.multi_dot, according to the docs

uses optimal parenthesization of the matrices. Depending on the shapes of the matrices, this can speed up the multiplication a lot.

so given that matmul is a binary operator, I'm assuming it does not perform optimal parenthesization. Is this true? also, would it be possible to implement optimal parenthesization on a binary operator in python?

A: It's probably possible to write an array type that does optimal parenthesize of matrix multiplication. You could write an array that defers the actual multiplication process, returning a proxy object instead of an array containing the results. Only when some non-multiplication operation is attempted on the array, would the proxy do the actual multiplication (using optimal parenthesization). The tedious thing would be setting up the proxy behavior for the custom type, so that you can do the deferred multiplication before any other operation.
For example, here's a class that wraps around an array and queues up matrix multiplications, but only performs them when an indexing or slicing operation is attempted:
class DeferredMultiplicationArray:
    def __init__(self, *arrays):
        self.arrays = arrays

    def __matmul__(self, rhs):
        return DeferredMultiplicationArray(*self.arrays, rhs)

    def __getitem__(self, index):
        if len(self.arrays) > 1:
            self.arrays = [numpy.linalg.multi_dot(self.arrays)]
        return self.arrays[0][index]

This doesn't support lots of other operations that real numpy arrays do, so it's not a full solution, but it demonstrates the general idea of deferring the multiplication until the results are needed, so that you can queue up any further matrix multiplications you get. Here's how it would operate:
>>> a = np.array([[1, 2, 3], [2, 3, 4]])
>>> b = np.array([[3,4, 5, 6], [3, 2, 1, 0], [4, 5, 6, 7]])
>>> c = [[1], [2], [3], [4]]
>>> d = [[1,2,3,4,5,6]]
>>> a @ b @ c @ d        # normal numpy matrix multiplication
array([[ 250,  500,  750, 1000, 1250, 1500],
       [ 370,  740, 1110, 1480, 1850, 2220]])

>>> A = DeferredMultiplicationArray(a) @ b @ c @ d
>>> A.arrays             # no multiplication has been done yet
(array([[1, 2, 3],
        [2, 3, 4]]),
 array([[3, 4, 5, 6],
        [3, 2, 1, 0],
        [4, 5, 6, 7]]),
 [[1], [2], [3], [4]],
 [[1, 2, 3, 4, 5, 6]])

>>> A[:]         # slice the array to make our class do the actual multiplication
array([[ 250,  500,  750, 1000, 1250, 1500],
       [ 370,  740, 1110, 1480, 1850, 2220]])

>>> A.arrays     # the result is now saved, not the inputs any more
[array([[ 250,  500,  750, 1000, 1250, 1500],
        [ 370,  740, 1110, 1480, 1850, 2220]])]


text:
Q: how to use params in the base URL angular 4+? I am working on an app that will have URLs specific to both company and country.

mysite.com/company/country

Is there a way to add the parameters to the base URL rather than adding them to the paths directly?

A: Try like this :
To call router:
this.router.navigate(['/myUrlpath', "company_name", "country_name"]);

In routes.ts:
{ path: 'myUrlpath/:company/:country', component: sampleComponent},


text:
Q: Why compiler throw error CS0165: Use of unassigned local variable? I put the code below, and also uploaded to a online c# compiler:
jdoodle.com/a/1jww
the code can compile and run online, however, it doesn't compile in my local visual studio.
I am using:

Visual Studio 2017 15.9.13,
Console app, .Net Framework 4.7.2
Language version c# 7.3
Microsoft (R) Visual C# Compiler version 2.10.0.0 (b9fb1610)

Below is the code:
class Program
{
    static void Main()
    {
        Dictionary<string,int> myDict = new Dictionary<string,int>();
        myDict.Add("hello", 1);

        if (myDict?.TryGetValue("hello", out var value) == true)
        {
            Console.WriteLine("Hello" + value.ToString());
        }
    }
}

expecting to see Hello1 in Console.Output
Because if the condition is true, the Null-Conditional check must have returned a non-null value, and the key is existing in the dictionary and the value must have been assigned when returning from the TryGetValue method.
Because according to the documentation:

the called method is required to assign a value before the method returns.

update:
This is an open issue in https://github.com/dotnet/roslyn/issues/32572
I think it's an true issue/bug if the requirement for compiler includes not to give false alarm.
My arguments:
Whenever CPU executing to the point inside the if bracket code block, the value must have returned from TryGetValue call and is NOT "unassigned local variable". An easier solution is to give something like "unable to determine assignment status" as warning instead of error, if compiler can't look forward for assignment status when interpreting null conditional operator.

A: It's due to the compiler difference.
In this fiddle, https://dotnetfiddle.net/5GgGNS, you can see the error, which is omitted in the mono compiler.
I think the error is valid due to the fact that this line
if (myDict?.TryGetValue("hello", out var value) == true)

is not guaranteed to initialize the local variable value.
If you would rewrite it to:
if (myDict?.TryGetValue("hello", out var value) == null)

it would try to access value.
Now, the null value, or true in your case, could be a function's return value, which would only be known at run time.
But, since all variables are basically always initialized, it's just a compiler feature.
On the other hand, according to the C#5 specs:

A local variable introduced by a local-variable-declaration is not automatically initialized and thus has no default value. For the purpose of definite assignment checking, a local variable introduced by a local-variable-declaration is considered initially unassigned. A local-variable-declaration may include a local-variable-initializer, in which case the variable is considered definitely assigned only after the initializing expression (§5.3.3.4).

But your code is C# 6.
So my conclusion is that the compilers interpret it differently. The Microsoft compiler takes the ?. operator into account. You should file it as a bug, or finding at least, maybe even at both parties.

Argumentation
Fun fact, if you use this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        //Your code goes here
        Dictionary<string,int> myDict = null;

        if (myDict?.TryGetValue("hello", out var value) == null)
        {
            Console.WriteLine("Hello" + value.ToString());
        }
    }
}

[using https://www.jdoodle.com/compile-c-sharp-online , mono 5.10.1]
You'll see the actual initialization to default(T) at work. The output is Hello0. Nevertheless, it's remarkable because due to the ?, and the fact that myDict is null, TryGetValue shouldn't be called and leaving value "uninitialized".

The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.
source

But..., since there are no uninitialized variables; if it compiles, the compiler will make sure it's behavior is not undefined.

So, since value is initialized, on run-time, the question remains if it's a valid compiler error at build time. Regarding to the run-time intend of the code it is (and that's why the error was there in the first place), but I think it remains a grey area.
Do note that according to this default(T) is not override-able, which would actually lead to no condition where it fails.

By running this little test:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        //Your code goes here
        Dictionary<string,int> myDict = null;

        if (myDict?.Bar(out var test) == null)
        {
            Console.WriteLine("does hit");
        }
    }
}

static class Foo
{
    public static object Bar(this Dictionary<string,int> input, out int test)
    {
        test = 3;
        Console.WriteLine("does not hit");
        return 1;
    }
}

[using https://www.jdoodle.com/compile-c-sharp-online , mono 5.10.1]
The output becomes:
does hit

And you can verify the correct run-time behavior of the ?. operator.

A: The null conditional ?. removes the guarantee that value will be assigned to since TryGetValue will only be called conditionally if myDict is not null.
You enforce the assignment of value inside the if statement afterwards with == true since the left side will return null if TryGetValue is not called due to myDict itself being null.  The compiler, however, cannot make this inference leap in the general case so you have to help it out either by testing myDict for null beforehand (and skipping ?.) or initializing value beforehand.

A: I would suggest initializing the value variable before your "TryGetValue" call.

A: The null-conditional operator introduces a different execution path where it short-circuits TryGetValue. However, the value variable exists anyways since it is scoped outside of the if and TryGetValue statements, which would indicate this flavor of syntactic sugar must result in the good old declaration of the variable prior to its use. For instance:
if (myDict?.TryGetValue("hello", out var value) == true)
{
    Console.WriteLine("Hello" + value.ToString());
}
//Current issue aside, this is legal as the variable exists at a higher scope,
//beyond the if and TryGetValue statements although the brackets give the illusion of scope.
value = 2;

Should be equivalent to:
int value;
if (myDict?.TryGetValue("hello", out value) == true)
{
    Console.WriteLine("Hello" + value.ToString());
}
value = 2;

Which also results in the compilation error.
However, the same error would be issued for myDict if it was null and you didn't use the null-conditional operator:
Dictionary<string, int> myDict; //Not initialized
//You would get the warning for myDict here instead
if (myDict.TryGetValue("hello", out var value) == true)
{
    Console.WriteLine("Hello" + value.ToString());
}

In other words, myDict can never be null and compile without the same error so there is no need to use a null-conditional operator. This is why removing it fixes the issue.
That being said, the documentation states:

No need to assign an initial value. By declaring the out variable
  where it's used in a method call, you can't accidentally use it before
  it is assigned.

So, in theory you are accidentally using the variable before it's assigned because the language constructs allow it. However, the compiler is identifying an issue at a lower level and not letting you go through with it.
In my mind, it's valid compiler verification obscured by syntactic sugar fog.


text:
Q: Liberando memória com PHP usando __destruct É necessário usar o método __destruct e definir as variáveis da classe com null com objetivo de liberar memória de modo mais eficiente?
Por exemplo:
class Teste {
    public $foo;
    public $bar;
    // ...

    public function __construct() {
        // ...
    }

    public function __destruct() {
        $this->foo = null;
        $this->bar = null;
    }

}

A: Creio que não, afinal o __destruct será chamado automaticamente quando as todas as referências são liberadas, ou quando o script termina.
Além disso, se você setar como null não faz liberar memória, por si só, ele só marca como um candidato para a coleta de lixo, que é exatamente o que o _destruct faz.

A: O __destruct é chamado automáticamente ao final do script como dito na própria documentação Destrutores são chamados durante o encerramento do script tendo os cabeçalhos HTTP enviados.
E um adendo: atribuir null a uma variavel ainda consome memória pois ainda existe a referencia a propriedade que tem valor null.


text:
Q: plot selected rows of numpy array Consider a small numpy array:
array([[  0.,   1.,   0.,   1.,   0.,   0.,   0.,   0.,   0.,   1.],
   [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
   [  0.,   0.,   0.,   0.,  18.,  15.,  25.,   0.,   0.,   0.],
   [  0.,   0.,   0.,  23.,  19.,  20.,  20.,   0.,   0.,   0.],
   [  0.,   0.,  20.,  22.,  26.,  23.,  18.,   0.,   0.,   0.],
   [  0.,   0.,   0.,  23.,  16.,  20.,  13.,   0.,   0.,   0.],
   [  0.,   0.,   0.,   0.,  18.,  20.,  18.,   0.,   0.,   0.],
   [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
   [  0.,   1.,   0.,   0.,   1.,   0.,   0.,   0.,   0.,   0.]])

I would like to plot, let say from the row number 3 to the row number 6, i.e. a section of my numpy array(I am coming from matlab backgroud). How could I loop this? or How could I plot multiple rows of my numpy array in the same graph?
So far I have tried; I define an arbitrary x:
x = np.arange(0,10)

then If I use
plt.plot(x,data[3,:])

to plot the third row and It does fine. The problem arises if I try:
plt.plot(x,data[3:4,:])

I get the error "x and y must have same first dimension", which I understand because he stacks row number 3 and row number 4 together, so that x and y do not have the same dimension. How can I overcome that?
Thank you

A: As the error implies, your data.shape = (1,10) is inconsistent with your input x.shape = (10,). To solve this problem you can just transpose your data using .T, i.e.
plt.plot(x, data[3:4,:].T)

Also, keep in mind that data[3:4,:] is the same as data[3,:], you will need to use data[3:5,:] to get the 3rd and 4th rows, for example.

A: You can try:
for i in range(3):
    plt.plot( x , data[ i , : ] )

plt.show()

If you want a range of rows ,for example from 3 to 6 , you can use:
range(3,7,1) , where 1 is the step , 3 is the starting row and 7 is the last row we want to plot (6 ) plus one

A: Just a better application of psuedocubi's answer.
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,10)
y = np.array(YOUR DATA HERE)

plt.plot(x,a[3:4].T,'r--',label="x vs y1") #CONTAINS YOUR 3RD ROW
plt.plot(x,a[4:5].T,'g--',label="x vs y2") #CONTAINS YOUR 4TH ROW
plt.plot(x,a[5:6].T,'b--',label="x vs y3") #CONTAINS YOUR 5TH ROW
plt.legend(loc='best')
plt.xlabel("x")
plt.ylabel("y")
plt.show()

The x here as been plotted with your own data!


text:
Q: Genus of a graph and planarity In 'Introduction to graph theory' by Trudeau it is proved the theorem

Every graph has a genus

by first embedding the graph onto a sphere , and then adding handles, say we use $k$ of them, where the graph has edge-crossing , this is the example used :

Then, he writes that using a continuous deformation of the surface (stretching,shrinking or distorting the surface) it is possible to preserve planarity while deforming the $k$-handles sphere into a $k$-hole torus. So, the genus will be at most $k$.
I'm not able to visualize the bold part, how can I be sure that planarity will be preserved? Should it be obvious? Is there a simple explanation to understand clearly why this happens ? (I'm totally a beginner in algebraic topology, just visualization of trasformations are used in the book).
Another proof of a theorem stated earlier in the book : "every planar graph has genus $0$ (it can be embedded on a sphere)" was obscure to me but then searching online I found the explanation through the stereographic projection and all my doubts were gone , does something similar exist? Or even a good intuition is difficult to set up ?
EDIT :
For clarity I add the definition of genus given in the book :

The genus of a graph, denoted $g$, is the subscript of the first surface among the family $S_0,S_1,S_2,\dots$ on which the graph can be drawn without edge crossing .

I also add the explanation of the author to pass from the $k$-handle sphere to the $k$-hole thorus :

Think of the surface consisting of $S_0$ with $k$ handles as made of extremely pliable rubber which we are free to stretch, shrink or otherwise distort as much as we want , provided that we don't tear it off of fold it back onto itself. With this understanding we see that the surface consisting of $S_0$ with $k$ handles can be 'continuously deformed' into $S_k$ and the vertices and edges of $G$ can be carried along with this continuos deformation. Thus $G$ can be drawn on $S_n$ without edge-crossings.

The bold part is obscure to me in the sense explained above.

A: To be honest, I am not really sure what is your question. What do you mean by "every graph has a genus"? I'll try to answer by the way, since geometrically your question is clear.
For me, the genus is a well defined quantity associated to a (compact) surface. When you have a planar graph, you imagine to fill the faces among the edges and you get a very simple surface, something like a polygon in the plane. If you also fill the exterior " ghost" face you obtain the whole plane. The genus is computed now as $1-\chi/2$, where
$$\chi =  \#\{\text{filled faces}\} - \#\{\text{edges}\} +\#\{\text{vertices}\}$$
And we would be done, but the plane is not a compact surface so we don't know what this should be equal to. To deal with this technical issue, we add a point to infinity and we get a sphere. Now the theory tells us that the genus (which is secretly the number of holes) of the sphere is zero, so that we get for a planar graph
$$\#\{\text{filled faces}\} - \#\{\text{edges}\} +\{\text{vertices}\}= 2$$
You can also reformulate this, recalling that the faces we filled were the internal faces + one ghost face:
$$\#\{\text{ faces}\} = \#\{\text{edges}\} - \{\text{vertices}\}+1$$
Check this on small graphs! That's true for real :)
Some complications arise if there are intersections. The main idea in algebraic topology is that if we cut a topological space in simple bricks - like a surface in triangles - the geometric properties of the space become combinatorial properties of how our bricks are combined. You have just seen this above: the genus of the sphere reflects in an equation for edges, vertices and faces for the graph that "builds up" the sphere.
When you have intersection, the problem is that the graph is apparently not building up anything. The idea of your book is to create small bridges (handles) so that the graph does not intersect himself anymore: you will have a planar graph sitting inside a new surface, no longer a sphere, but who cares! We can carry on our argument above, and we only have to change the genus in the end: for a nice coincidence, it will be the number of bridges we added.
If you are not comfortable with deforming the surface into a k-hole torus while preserving planarity, there is no need to do that: the genus is a homotopy invariant. If you are convinced that - beside the graph story - you can deform a k-handle sphere into a k-hole torus, then you know that the genus of the k handle sphere is the same of the k-hole torus, that is k.
Please ask in the comments if you need further clarifications :)

A: If you have a mug (that has glaze on it) and a whiteboard marker, try drawing $K_5$ on it without any edge crossings.
Once you do that, it's not a far leap to imagine the handle expanding to make the mug more donut-like, and noticing that this deformation does not create any new edge crossings. Then try generalizing this to more holes.

A: Maybe I found a satisfactory not much mathematical way for myself to explain what's going on.
Take a nonplanar graph on a sphere with $1$ unavoidable intersection, then you can add a bridge to delete the intersection, so now if we are able to imagine the trasformation in a torus we are done in the case of one intersection. Take the bridge and make it say an half ring, this is simple enough for me to see that it preserves planarity, now we will have something like a kettlebell, now get bigger the half ring so that it incorporates the sphere, here we have the torus!
Now, say we have a graph with $k$ unavoidable intersections , then we can add $k$ bridges one by one (applying the trasformation above each time) so at most the genus is $k$.


text:
Q: After casting PushPin , get this Possible unitended reference comparison underline message I Have this error message :

Possible unitended reference comparison; to get a value coparison, cast the left hand side to type string

problem :
((Pushpin)p).Tag == "locationPushpin"));

============================

double Dlat = Convert.ToDouble(g_strLat);
double Dlon = Convert.ToDouble(g_strLon);

 this.map1.Center = new GeoCoordinate(Dlat, Dlon);

  if (this.map1.Children.Count != 0)
     {
        var pushpin = map1.Children.FirstOrDefault(p => (p.GetType() == typeof(Pushpin) && ((Pushpin)p).Tag == "locationPushpin"));

         if (pushpin != null)
          {
              this.map1.Children.Remove(pushpin);
          }
      }

     Pushpin locationPushpin = new Pushpin();

     //---set the location for the pushpin---

      locationPushpin.Tag = "locationPushpin";
      locationPushpin.Location = new GeoCoordinate(Dlat, Dlon);

     locationPushpin.Content = new Ellipse()
     {
        Fill = new SolidColorBrush(Colors.Orange),
        //Opacity = .8,
        Height = 40,
        Width = 30
      };

      locationPushpin.Width = 60;
      locationPushpin.Height = 100;

      this.map1.Center = new GeoCoordinate(Dlat, Dlon);
      this.map1.Children.Add(locationPushpin);
      this.map1.ZoomLevel = 13;

Would appreciate your help. Thanks

A: Firstly, your query would only find exact objects of type Pushpin. This is cleaner:
var pushpin = map1.Children.OfType<Pushpin>()
                           .FirstOrDefault(p => p.Tag == "locationPushpin");

The next problem is that Tag is of type object. So you really want:
var pushpin = map1.Children.OfType<Pushpin>()
                           .FirstOrDefault(p => "locationPushpin".Equals(p.Tag));

Otherwise you'll be doing a reference comparison between the Tag value and the string. So you could have equal but distinct strings, and the pushpin wouldn't be found.


text:
Q: How can I reach seq tag data via web scraping with BeautifulSoup? I am a newbie to web scraping. I am trying to get FASTA file from here, but somehow I cannot. First of all the problem starting for me span tag, I tried some couple of suggestions but not working for me I am suspecting that maybe there is a privacy problem
The FASTA file in this class, but when I run this code, I just can see FASTA title:
url = "https://www.ncbi.nlm.nih.gov/nuccore/193211599?report=fasta"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
fasta_data = soup.find_all("div")
for link in soup.find_all("div", {"class": "seqrprt seqviewer"}):
    print link.text

url = "https://www.ncbi.nlm.nih.gov/nuccore/193211599?report=fasta"
res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
fasta_data = soup.find_all("div")
for link in soup.find_all("div", {"class": "seqrprt seqviewer"}):
    print link.text

##When I try to reach directly via span, output is empty.
div = soup.find("div", {'id':'viewercontent1'})
spans = div.find_all('span')
for span in spans:
    print span.string

A: Every scraping job involves two phases:

*

*Understand the page that you want to scrape. (How it works? content loaded from Ajax? redirections? POST? GET? iframes? antiscraping stuff?...)

*Emulate the webpage using your favourite framework
Do not write a single line of code before to work on point 1. Google network inspector is your friend, use it!
Regarding your webpage, it seems that the report is loaded into a viewer getting data from this url:
https://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?id=193211599&db=nuccore&report=fasta&extrafeat=0&fmt_mask=0&retmode=html&withmarkup=on&tool=portal&log$=seqview&maxdownloadsize=1000000
Use that url and you will get your report.


text:
Q: Is it possible to execute code after return statement in C++? I am a java programmer, new to C++. In the code below, I know if( condition1 ) is true variable1 is returned. But is there any mechanism by which the second if is also processed after the first if condition evaluates to true? I am asking this because I have seen code like this and I found it while debugging.
if( condition1 )
{
    return variable1;
}

//do some processing here

if( condition2 )
{
    return variable2;
}

A: No.  Once a return is encountered, nothing else in the function is processed.

A: Your function must execute 1 and exactly 1 return statement.
So, either return variable1 gets executed or if(condition2), but never both.

A: Although there is a way to run code after the return statement, there is no way to change the return value after a return statement has been executed.
Here is how you can make some code to run after a return statement:
struct AfterReturn {
    ~AfterReturn() {
        // This code will run when an AfterReturn object goes out of scope
        cout << "after return" << endl;
    }
};

int foo() {
    AfterReturn guard; // This variable goes out of scope on return
    cout << "returning..." << endl;
    return 5;
    // This is when the destructor of "guard" will be executed
}

int main() {
    cout << foo() << endl;
    return 0;
}

The above program prints
returning...
after return
5

A: No, code is never executed after a return statement is reached. If, however, condition1 is false, then the return statement isn't reached, so execution proceeds normally. This is exactly the way Java behaves, too.
There is an argument against early return statements, but personally I find them helpful; trying to avoid them can lead to extraneous cruft, such as temporary variables that don't really do you any good or large if-blocks that are mostly just confusing to read due to their scope.

A: As far as I remember (or at least as my teachers told me) is not quite a good idea to use return before the end of the execution, with the exception of recursive functions.
I suggest you use a variable to store the value you want to return as a result of your function and return it at the end of your function:
if( condition1 )
{
    ans = variable1;
}

/* more code */

if( condition2 )
{
    ans = variable2;
}
return ans;

A: It only is executed if it is called. At which point, you are leaving that function/method.
In your case, if condition1 is false, it will run your extra processing and then proceed to test condition 2.
Now, in your case, your code probably won't compile. (I know it wouldn't in Java)
This is because it is possible to have neither condition be satisfied in which case we get lost. So, you should probably have some return outside of your if statements.
In short, no execution of code happens after a return is called.


text:
Q: How to disable to remove individual count under subtotal in Excel pivot table? I'm quite new to programming, so I don't know if I am using the right words, BUT I'm creating a pivot table for my list of library books, and I want to hide all those 1s.

As you can see, I have those lines of 1s next each of the book titles under the subtotal, and I was wondering if there was a way to disable them because they look quite distracting. Thanks so much!!!

A: Pivot table values will always show. Filtering, as suggested in a comment, is probably not what you want.
You could use conditional formatting to hide the 1's for the individual values. In the screenshot, I'm counting the "Title" column of the data. Select one of the "1" values, then click Home ribbon > Conditional formatting > New Rule

Click the option highlighted with the arrow. It will show your column name instead of "title".
Then click "Use a formula to determine ...." and enter the formula like below:

My selected cell is F6 and whatever cell you have selected needs to go into the formula box WITHOUT the dollar signs!
Next click the Format button and use either white font on white background, or a custom number format ;;;.

Confirm all the dialogs and enjoy the result. Note how the subtotal "1" for 30-Jun did not disappear, because the conditional format acts only on cells showing "Count of title" values for "Title", as ticked in my first screenshot.


text:
Q: How to send arraylsit as request parameter using android? I'm trying to capture signature using GestureOverlayView and send the signature as request. This works fine if there is only one signature to be sent, now I want multiple signatures to be sent, for this I'm trying to store signature in arraylist. Is there any other possibility to send signature instead of using NameValuePair.
This is my code:
public class MainActivity extends Activity {

String response;
WebView webView;
String loanCode;

ArrayList<String> arrayList = new ArrayList<String>();
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = getIntent();
    String url = intent.getExtras().getString("url");
    loanCode = intent.getExtras().getString("loanCode");
    webView = (WebView) findViewById(R.id.pdfDisplay);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.loadUrl("https://docs.google.com/gview?embedded=true&url="+url);
    //webView.loadUrl(url);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    return true;
}

@SuppressLint("ShowToast")
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

    case R.id.save:

        try {

            GestureOverlayView gestureView = (GestureOverlayView) findViewById(R.id.signaturePad);

            Bitmap bm = Bitmap.createBitmap(gestureView.getGesture().toBitmap(100, 100, 10, Color.BLACK));
            ByteArrayOutputStream stream = new ByteArrayOutputStream(2056);
            //FileOutputStream fos = openFileOutput("signature.png", Context.MODE_PRIVATE);
            bm.compress(Bitmap.CompressFormat.PNG, 100, stream);

            byte[] image_byte = stream.toByteArray(); // stream.toString().getBytes();//Base64.encode(fos.toString().getBytes(), 0);

            String strImage = Base64.encodeToString(image_byte, Base64.DEFAULT);

            if(arrayList.size()<3){
            arrayList.add(strImage);
            }
            String serverUrl = "http://192.168.3.139:8001/ql/acceptCustomerSignature.do";
            //String serverUrl = "http://192.168.3.139:8001/APDWebTest/ImageRetrieve";
            String[] signatureImage = {serverUrl,strImage,loanCode};

            ArrayList params = new ArrayList();
            params.add(serverUrl);
            params.add(arrayList);
            params.add(loanCode);
            System.out.println("String is "+strImage);

            stream.flush();
            stream.close();

          APDWebApp apd = new APDWebApp();
          apd.execute(params);

       } catch (Exception e) {

           Log.v("Gestures", e.getMessage());

           e.printStackTrace();

      }
        System.out.println("Size of array list "+arrayList.size());
        break;

    case R.id.logout:
        Intent logout = new Intent(this, LoginActivity.class);
        startActivity(logout);
        finish();
        break;
    }
    return false;
    }

private class APDWebApp extends AsyncTask<ArrayList, Void, String>{

    String response = null;
    @Override
    protected String doInBackground(ArrayList... params) {

        try{
            ArrayList parameters = params[0];

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(parameters.get(0).toString());

            ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

            nameValuePair.add(new BasicNameValuePair("signture", (String)parameters.get(1)));
            nameValuePair.add(new BasicNameValuePair("loanCode", (String) parameters.get(2)));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            //httpPost.setHeader(name, value)
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
            System.out.println("Response is "+response);

        }
        catch(Exception ex){

            ex.printStackTrace();

        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT);
        response = result;
        super.onPostExecute(result);

    }

}

I'm trying to add signature to arraylist at this step arrayList.add(strImage);
Passing this arraylist to AsyncTask class params.add(arrayList);
Adding this to NameValuePair using following steps
ArrayList parameters = params[0];
nameValuePair.add(new BasicNameValuePair("signture", (String)parameters.get(1)));
I'm not sure if this is only way to send arraylist as request parameter. Please let me know if there is any other possibility.

A: NameValuePair is the standard method of creating an HTTP GET request with parameters.
You can change the way you send info to your AsyncTask though, since the parameters for async task are Params... params, you can send two String instead of an ArrayList:
apd.execute(serverUrl, signature, loancode);

and then simply use them in the doInBackground():
HttpPost httpPost = new HttpPost(params.get(0));

ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("signture", params.get(1)));
nameValuePair.add(new BasicNameValuePair("loanCode", params.get(2)));


text:
Q: Algorithm for placing textual/non-textual content in a book layout Hey guys I was looking for different approaches/algorithms for placing textual/non-textual content in a book layout having 2 sides. So essentially it should look like a user is reading a book & content placed in a 2 page layout.
If you guys have any directives or suggestions on how to go about doing this. Way to decide how many content items can fit into 2 pages, no overflow. Suppose a page is 425 px BY 600 px & we have 2 such pages fit side by side (dimensions are flexible).
Any pointers appreciated?
P.S. I know this is not a pure programming question per se but more of an algorithmic question. If so, please direct me where this question can be best asked.
EDIT 1
I want to use this algorithm in a website application & not in a standalone app, so please consider that.
EDIT 2
I would like to mention that the order of the content items is pre-decided.

A: If your goal is to display data in a book like format, then the easiest method would be to reuse an already existing toolkit for doing text layout.  I think the best tool for this purpose would be LaTeX, which is an evolution of the original digital typesetting program.
In order to use it you will have to convert your data into the LaTeX format, which is relatively painless (I have done it several times with several types of data).  In this document you can specify that you want a book format, how large the pages are, and much more.  You can then render the text to pdf/ps and then display the two pages of a "book" side by side.
If what you are looking for is the actual algorithms to do it yourself, you might search around the TeX/LaTeX community for information.


text:
Q: NSXMLElement walk through I have an element of a NSXMLDocument (a FCPX exported .fcpxml) which I'd like to walk-through, as opposed to getting the children and then the nested children, etc:

    <spine>
     <clip name="Referee" offset="0s" duration="5s" format="r2" tcFormat="NDF">
      <video offset="0s" ref="r3" duration="418132800/90000s">
       <audio lane="-2" offset="0s" ref="r3" srcID="2" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>
       <audio lane="-1" offset="0s" ref="r3" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>
      </video>
      <spine lane="1" offset="119/25s" format="r1">
       <clip name="Referee" offset="0s" duration="403200/90000s" start="1300/2500s" format="r2" tcFormat="NDF">
        <adjust-volume amount="-96dB"/>
        <video offset="0s" ref="r3" duration="418132800/90000s">
         <audio lane="-2" offset="0s" ref="r3" srcID="2" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>
         <audio lane="-1" offset="0s" ref="r3" duration="3345062400/720000s" role="dialogue" srcCh="1, 2"/>
        </video>
       </clip>
       <transition name="Cross Dissolve" offset="313200/90000s" duration="1s">
        <filter-video ref="r4" name="Cross Dissolve">
         <param name="Look" key="1" value="11 (Video)"/>
         <param name="Amount" key="2" value="50"/>
         <param name="Ease" key="50" value="2 (In & Out)"/>
         <param name="Ease Amount" key="51" value="0"/>
        </filter-video>
        <filter-audio ref="r5" name="Audio Crossfade"/>
       </transition>
      </spine>
     </clip>
     <transition name="Cross Dissolve" offset="4s" duration="1s">
      <filter-video ref="r4" name="Cross Dissolve">
       <param name="Look" key="1" value="11 (Video)"/>
       <param name="Amount" key="2" value="50"/>
       <param name="Ease" key="50" value="2 (In & Out)"/>
       <param name="Ease Amount" key="51" value="0"/>
      </filter-video>
      <filter-audio ref="r5" name="Audio Crossfade"/>
     </transition>
    </spine>

I'm thinking that using NSXMLParser would be the best bet, so I've one up like this:

NSXMLParser *new_parser = [[NSXMLParser alloc] initWithData:[NSData dataWithBytes:[[theXMLElement stringValue] UTF8String] length:[theXMLElement stringValue].length]];
[new_parser setDelegate:self];
BOOL parse_success = [new_parser parse];

But it fails as the -stringValue of the element returns a zero-length string (checked with a NSLog output). So how should I setup to parse just the above element (or similar) of a larger NSXMLDocument?

A: I should have used -XMLString to get a valid string for the parser. I'd seen -stringValue somewhere and it had become stuck in my head.


text:
Q: How do I erase lines with different words at a time in Notepad++? I have a big txt file and I need to erase each line that contains specific 15-20 different words.
I could bookmark the lines using the specific words one by one and then delete the lines, but this would take me a while and unfortunately I need to do this process with other lists too.
What i want is to delete all the lines from a single move :)
Also Notepad++ regex doesn't support the | alternation operator.
So i can't use Find/Replace or Bookmark for smt like :\b(word1|word2|word3|word4).*\s+
Any suggestions in how may delete all the lines containing my words from a single move?

A: Yes, I agree with Marco Amans
Notepad++ recent versions support the alternation operator.
You can use it like this:
     [word1|word2|word3]

Reference

http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Regular_Expressions

A: Recent versions of Notepad++ do support the | alternation operator. Update and try it.


text:
Q: My sql query not returns null value rows with not in condition My query is:
SELECT (SUM(credit)-SUM(debit)) AS balance
FROM member_transaction
WHERE member_id=" + mId + " AND reference_id NOT IN (
    SELECT user_reference_id FROM r_request WHERE status=7)

But it's not returning rows which has NULL in reference_id column.
Is there anything wrong in my query?

A: If you want to include the null rows, it's best to be explicit:
SELECT (SUM(credit)-SUM(debit))AS balance
FROM member_transaction
WHERE member_id=" + mId + " AND
      (
         reference_id NOT IN(
            SELECT user_reference_id FROM r_request WHERE status=7)
         OR reference_id IS NULL
      )

SQL uses a three-valued logic where comparisons with NULL generally produce the third logic value, UNKNOWN, rather than TRUE or FALSE.

A: Try to this
SELECT (SUM(credit) - SUM(debit)) AS balance
FROM member_transaction
WHERE member_id = " + mId + "
    AND isnull(reference_id, 0) NOT IN (
        SELECT user_reference_id
        FROM r_request
        WHERE STATUS = 7
        )

A: Also return referece_id null rows
SELECT (SUM(credit)-SUM(debit))AS balance FROM member_transaction
WHERE
    member_id=" + mId + "
    AND ( (referece_id is null) or
          (reference_id NOT IN
              (SELECT user_reference_id FROM r_request WHERE status=7))

A: NULL values are automatically eliminated from main query if sub-query returns some result. However if sub-query does not have a record to return, then only NULL values will be returned.
So you can use
SELECT (SUM(credit)-SUM(debit))AS balance
FROM member_transaction
WHERE member_id=" + mId + "
AND (reference_id NOT IN
(SELECT user_reference_id FROM r_request WHERE status=7) OR reference_id  IS NULL)

A: Actually yes, you are not considering NULLs in column reference_id. In order to consider NULLs you should explicitly define an OR condition.
Make the following query. It will be sargable and will use potential indexes on column reference_id:
"SELECT (SUM(credit)-SUM(debit)) AS balance
 FROM member_transaction
 WHERE member_id=" + mId + " AND (reference_id IS NULL OR reference_id NOT IN (
    SELECT user_reference_id FROM r_request WHERE status=7))"

A: I would suggest the usage of an left join instead of an not in, as it could be quite slow on a huge r_request table.
SELECT (SUM(credit) - SUM(debit)) AS balance
    FROM member_transaction mt
    LEFT JOIN r_request r
            ON mt_dat.reference_id = r.user_reference_id
    WHERE member_id = " + mId + "
        AND r.user_reference_id is null

This should exactly do what you want.
Best regards,
Ionic


text:
Q: Vertically align two horizontally-parallel equations I am attempting to vertically align two equations at multiple points and I have come up with the following:
\begin{array}{rlclcl}
\eta(n)&\equiv&\frac{\Lambda(n)}{\log n}&\equiv&\sum_{d\mid n}&\mu\left(\frac nd\right)\log_nd\\
\eta(p(x))&\equiv&\frac{\Lambda(p(x))}{\log p(x)}&\equiv&\sum_{c(x)\mid p(x)}&\mu\left(\frac {p(x)}{c(x)}\right)\log_{p(x)}c(x)
\end{array}

The problem I'm encountering is that there is too much space between the right-most \sum and the following \mu, but if I remove the alignment markers then the \sum symbols do not align.  Is there a simple way to fix this?  I arrived at this point while trying to get the \sum parts to be vertically aligned, and this part of the alignment is what I most want to keep, followed immediately by the \equivs and the \eths (with right-alignment for the \eths).
Is there a simple way to resolve this?

A: I don't think that aligning the \equiv and \sum signs adds to readability; to the contrary, I believe that it hinders it.
Anyway, with some more work one can get the required alignments.
I made also some improvements, defining a \moebius command that uses \DeclarePairedDelimiter, so you can say
\moebius{x}        % normal size
\moebius[\big]{x}  % big size
\moebius[\Big]{x}  % Big size
\moebius[\bigg]{x} % bigg size
\moebius[\Bigg]{x} % Bigg size
\moebius*{x}       % automatic sizing, use sparingly

The package array and \newcolumntype are necessary only for the second way of typesetting the formulas.
\documentclass{article}
\usepackage{mathtools,array}
\DeclarePairedDelimiter\moebiusdel{(}{)}
\newcommand{\moebius}{\mu\moebiusdel}

\newcolumntype{M}[1]{>{\displaystyle{}}#1<{{}}}

\begin{document}

My proposal
\begin{gather*}
\partial(n)\equiv\frac{\Lambda(n)}{\log n}\equiv\sum_{d\mid n}\moebius*{\frac{n}{d}}\log_nd\\
\partial(p(x))\equiv\frac{\Lambda(p(x))}{\log p(x)}\equiv\sum_{c(x)\mid p(x)}
  \moebius*{\frac{p(x)}{c(x)}}\log_{p(x)}c(x)
\end{gather*}
With multiple alignments
\[
\setlength{\arraycolsep}{0pt}
\begin{array}{Mr Mc Mc Mc Ml}
\partial(n) &
  \equiv &
  \frac{\Lambda(n)}{\log n} &
  \equiv &
  \sum_{\mathmakebox[\widthof{$\scriptstyle c(x)\mid p(x)$}]{d\mid n}}
    \moebius*{\frac{n}{d}}\log_nd
\\
\partial(p(x)) &
  \equiv &
  \frac{\Lambda(p(x))}{\log p(x)} &
  \equiv &
  \sum_{c(x)\mid p(x)}\moebius*{\frac{p(x)}{c(x)}}\log_{p(x)}c(x)
\end{array}
\]
\end{document}


text:
Q: How to connect mongodb using Springboot through mongoose? I have already done connect MongoDB using application.properties. But I want to connect MongoDB through mongoose.
This is my current configuration
This is DB Connection url setting in application.properties;
    spring.data.mongodb.uri =mongodb+srv://hans123:Hans123@cluster0.avxi858.mongodb.net/?retryWrites=true&w=majority

spring.data.mongodb.database=test

spring.data.mongodb.port=27017

spring.data.mongodb.host=localhost

A: Model Class
@Document
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
    @Id
    @Indexed
    private String id;
    @Indexed
    private String address;
    @Indexed
    private String name;
    @Indexed
    private String email;
    @Indexed
    private String password;
    @Indexed
    private String role;
}

Repository Class
public interface userReporsitory extends MongoRepository<User,String> {
    Optional<User> findByEmail(String email);
    List<User> findAllByRole(String role);
}

Service Class
@AllArgsConstructor
@Service
public class userService {
    private userReporsitory userReporsitory;
    public User saveUser(User user){
        return userReporsitory.save(user);
    }
    public User login(User user){
          User response = userReporsitory.findByEmail(user.getEmail()).orElseThrow(()->new RuntimeException("User Not Found"));

          if(!response.getPassword().equals(user.getPassword())){
            throw new RuntimeException("Bad Credincials");
          }

          return response;
    }

    public List<User> findAllUsers(){
      return userReporsitory.findAllByRole("user");
    }
}

Controller Class
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("api/v1/user")
public class userController {
   private userService userService;

    @PostMapping("/create")
    public ResponseEntity<User> save(@RequestBody User user){
        HttpStatus status = HttpStatus.EXPECTATION_FAILED;
        User response = userService.saveUser(user);

        if(response != null){
           status = HttpStatus.CREATED;
        }

        return new ResponseEntity<>(response, status);

    }
    @PostMapping("/login")
    public ResponseEntity<User> login(@RequestBody User user){
        return new ResponseEntity<>(userService.login(user),HttpStatus.ACCEPTED);

    }
    @GetMapping("/userList")
    public ResponseEntity<List<User>> userList(){
        return new ResponseEntity<>(userService.findAllUsers(),HttpStatus.ACCEPTED);
    }

}

A: In above answer you can encrypt the password as well (Additional Thing)
AuthRequest Class:
@Data
@AllArgsConstructor
public class AuthRequestDto {
    private String userName;
    private String password;
}

RegisterRequest Class:
@Data
@AllArgsConstructor
public class RegisterRequestDto {

    private String userName;
    private String password;
    private String firstName;
    private String email;
    private String phone;
    private String address;

}

UserService Class:
@AllArgsConstructor
@Service
public class UserService implements UserDetailsService {
    private final UserRepository userRepository;
    private final JWTUtility jwtUtility;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserEntity userEntity = userRepository.findByUsername(username).orElseThrow(()-> new UsernameNotFoundException("user name not found"));
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userEntity.getRole());
        return new User(userEntity.getUsername() , userEntity.getPassword() , new ArrayList<>(Arrays.asList(authority)));
    }

    public UserEntity registerUser(RegisterRequestDto request){

        //check user is already in
        if(userRepository.existsByUsernameIgnoreCase(request.getUserName())){
            throw new FieldValidationFaild("user name already exist in the system");
        }

        if(userRepository.existsByEmailIgnoreCase(request.getEmail())){
            throw new FieldValidationFaild("email already exist in the system");
        }

        UserEntity saveToBe = UserEntity.builder()
                                        .username(request.getUserName())
                                        .password(new BCryptPasswordEncoder().encode(request.getPassword()))
                                        .firstName(request.getFirstName())
                                        .email(request.getEmail())
                                        .phone((request.getPhone()))
                                        .address(request.getAddress())
                                        .role(Role.BUYER)
                                        .build();

        return userRepository.save(saveToBe);
    }

    public AuthRespondDto loginUser(AuthRequestDto authRequestDto){

        final UserDetails userDetails = loadUserByUsername(authRequestDto.getUserName());
        final String token = jwtUtility.generateToken(userDetails);
        return new AuthRespondDto(token , authRequestDto.getUserName() , userDetails.getAuthorities().stream().findFirst().get().getAuthority());
    }

    public long getAuthUserId(String username){
        UserEntity userEntity = userRepository.findByUsername(username).get();
        return userEntity.getId();
    }

    public String getUserAddressByName(String username){
        UserEntity userEntity = userRepository.findByUsername(username).get();
        return userEntity.getAddress();
    }

    public String getUserPhoneByName(String username){
        UserEntity userEntity = userRepository.findByUsername(username).get();
        return userEntity.getPhone();
    }

    public String getUserEmailByName(String username){
        UserEntity userEntity = userRepository.findByUsername(username).get();
        return userEntity.getEmail();
    }

    public UserEntity getUserById(long id){
        return userRepository.findById(id).orElseThrow(()-> new NotFoundException("user not found"));
    }
}

AuthController Class (Controller Class):
public class AuthController {

    private final AuthenticationManager authenticationManager;
    private final UserService userService;

    @PostMapping("/signin")
    public ResponseEntity<AuthRespondDto> login(@RequestBody AuthRequestDto authRequestDto) throws BadCredentialsException {

        try {
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            authRequestDto.getUserName(),
                            authRequestDto.getPassword()
                    )
            );
        }catch (BadCredentialsException e){
            //TODO add proper exception
            throw new BadCredentialsException("INVALID_USERNAME_OR_PASSWORD" , e);
        }

        return new ResponseEntity<>(userService.loginUser(authRequestDto) , HttpStatus.ACCEPTED);
    }

    @PostMapping("/signup")
    public ResponseEntity<UserEntity> register(@RequestBody RegisterRequestDto request){
        // basic controller level validations
        if(request.getUserName().isEmpty()){
            throw new FieldValidationFaild("user name is required");
        }
        if(request.getPassword().isEmpty()){
            throw new FieldValidationFaild("password is required");
        }
        if(request.getFirstName().isEmpty()){
            throw new FieldValidationFaild("first name is required");
        }
        if(request.getEmail().isEmpty()){
            throw new FieldValidationFaild("email is required");
        }
        if(request.getPhone().isEmpty()){
            throw new FieldValidationFaild("phone is required");
        }
        if(request.getPhone().length() != 10){
            throw new FieldValidationFaild("phone number length must be 10");
        }
        if(request.getAddress().isEmpty()){
            throw new FieldValidationFaild("address is required");
        }

        return new ResponseEntity<>(userService.registerUser(request) , HttpStatus.CREATED);

    }

}


text:
Q: XSLT grouping data from 2 different tags and removing duplicates I have this XML:
<CombinedResults>
    <Results>
        <Results>
                   <AccountNumber>5678</AccountNumber>
                   <Accounts>
                      <DomainAccount>
                         <AccountNumber>1234</AccountNumber>
                      </DomainAccount>
                      <DomainAccount>
                         <AccountNumber>9999</AccountNumber>
                      </DomainAccount>
                      <DomainAccount>
                        <AccountNumber>8888</AccountNumber>
                      </DomainAccount>
                    </Accounts>
       </Results>
       <Results>
             <AccountNumber>0427</AccountNumber>
       </Results>
       <Results>
               <AccountNumber>1234</AccountNumber>
               <Accounts>
                  <DomainAccount>
                    <AccountNumber>5678</AccountNumber>
                  </DomainAccount>
                  <DomainAccount>
                    <AccountNumber>9999</AccountNumber>
                  </DomainAccount>
                  <DomainAccount>
                    <AccountNumber>8888</AccountNumber>
                  </DomainAccount>
              </Accounts>
       </Results>
</Results>
</CombinedResults>

I need to create a table where each row has the AccountNumber value. The table must contains both the values from the Results/AccountNumber tag and the values from Results/Accounts/DomainAccount/AccountNumber tag and also no duplicates.
I managed to do it, but I was not able to remove the duplicates.
My code was:
<xsl:for-each select="CombinedResults/Results/Results">

 <xsl:value-of select="AccountNumber"/>

</xsl:for-each>

<xsl:for-each select="CombinedResults/Results/Results/Accounts/DomainAccount">

<xsl:value-of select="AccountNumber"/>

</xsl:for-each>

I need to get the values from the Results tag first, and then the ones from DomainAccount, with no duplicates.
This is the output I need to get:

   5678

  0427

  1234

  9999

  8888

A: To get the output you want in XSLT-1.0, you have to use a technique called Muenchian Grouping. So create an xsl:key with all of your values and then select only the first item in an xsl:for-each.
An XSLT-1.0 stylesheet realizing that is the following:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    <xsl:key name="items" match="Results/Results/AccountNumber | Results/Results/Accounts/DomainAccount/AccountNumber" use="text()" />

    <xsl:template match="/CombinedResults">
        <xsl:for-each select="//AccountNumber[generate-id() = generate-id(key('items',text())[1])]">

                    <xsl:choose>
                        <xsl:when test="key('items',text())[parent::Results]">
                            <xsl:copy-of select="key('items',text())[parent::Results]"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:copy-of select="key('items',text())[not(parent::Results)]"/>
                        </xsl:otherwise>
                    </xsl:choose>

        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

Its output is:

    5678

    1234

    9999

    8888

    0427

The order is not as you mentioned, but I cannot infer any ordering system from your desired output. Use an xsl:sort in the xsl:for-each loop if you need another order.

In XSLT-2.0 this is easier. You would just use the xsl:for-each-group function:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="/CombinedResults">
        <xsl:for-each-group select="Results/Results/AccountNumber | Results/Results/Accounts/DomainAccount/AccountNumber" group-by="text()">

                    <xsl:value-of select="if (current-group()[name(..) = 'Results']) then current-group()[name(..) = 'Results'][1] else current-group()[name(..) != 'Results'][1]"/>

        </xsl:for-each-group>
    </xsl:template>

</xsl:stylesheet>

The result is the same.


text:
Q: How to add a colored background which looks like an underline BENEATH the text in a sentence in Flutter? The first word is underlined but if you look closely, the text overlaps a part of the colored shape/part. It is not just under the text.
Here is what I am trying to achieve:

Here's my current code:
                text: TextSpan(children: <TextSpan>[
                  TextSpan(
                    text: "Welcome",
                    style: TextStyle(
                        color: HSColors.darkBlue,
                        decoration: TextDecoration.underline,
                        decorationColor: HSColors.cream,
                        decorationThickness: 5.h,
                        fontSize: 30.sp,
                        fontWeight: FontWeight.w700,
                        height: 1.1,
                        letterSpacing: -0.03),
                  ),
                  TextSpan(
                    text: " to Veritas Monitoring Services",
                    style: TextStyle(
                        color: HSColors.darkBlue,
                        fontSize: 30.sp,
                        fontWeight: FontWeight.w700,
                        height: 1.1,
                        letterSpacing: -0.03),
                  )
                ]),
              ),

Here is what it currently looks like:

Moreover, if I use other text, it overlaps and looks like this:

A: You need to work with decorationThickness value.
decorationThickness: 5.h,

I have lower the decorationThickness value to
decorationThickness: 0.2.h,

Here's the result on iPhone 12 simulator

A: You can acheive this using Stack as shown below. Set the behind container's height and width as per your need. Thanks
Stack(
    alignment: Alignment.bottomLeft,
    children: [
        Container(
            height: 15,
            width: 130,
            color: Colors.amber,
        ),
        Text("Welcome",
            style: TextStyle(
                color: Colors.black,
                fontSize: 30,
                fontWeight: FontWeight.w700,
                height: 1.1,
                letterSpacing: -0.03),
        ),
    ],
),


text:
Q: Battery Indicator shows wrong percentage Anyone have any idea what's going on with the percentage? (I wish my laptop was that awesome...)

A: Try sudo powertop and see what that says...
Also, try letting the computer die while it is on battery power. That always updates my percentage.

A: The problem is that it shows the battery charge when full is much higher than the design charge. That cannot be. Hence the denominator increases and the percent becomes low.


text:
Q: 127.0.0.1:9051 doesnt work after apache, mysql, php installation? I have installed apache2, mysql, and php and now it doesn't let Vidalia run on localhost. I tried to change the TCP connection (controlport) to any other ip 192.168.0.40 and tried to change the default port 9051 to any other but that doesn't work. I thought apache is running so I used this command sudo service apache2 stop but that still doesn't work. So now when I type 127.0.0.1:9051 in browser it says

and if I type only type 127.0.0.1 after stopping the apapche2 service with the command mentioned above it says unable to connect
I am not sure what to do now.

A: Tor is neither HTTP proxy nor a web server, and under no motive it will run in port 80. The port 9051 is a control port which Vidalia uses to talk with Tor, while port 9050 is the SOCKS port where you should point your browser. I installed Apache, Tor and Vidalia and no problem arrises.
Vidalia and Tor should always communicate using localhost or 127.0.0.1. If localhost doesn't work, is probably because is preferring ipv6 and apache has nothing to do with it. In the control port type 127.0.0.1:9051 and restart the system. Don't autostart Tor yourself, Vidalia should bring Tor up when Vidalia starts. If you start Tor before Vidalia it will fail.

A: I found this article https://tor.stackexchange.com/questions/20906/why-cant-i-access-localhost-from-tor-browser
"
Cause localhost is local to your computer, Tor is a public network that routes your traffic around the world. The network connections Tor browser makes are not local. Tor will not attempt any connections to private networks, or localhost. The browser connection leaves your computer and goes through 3 Tor relays and finally to the destination. That exit node (which can be anywhere in the world) cannot access "localhost" on your computer since it has zero knowledge about the request, only the destination and the relay it needs to send the response back to. – drew010 -Feb 13, 2020 at 16:13"
And this one which explained why trying to re-configure tor is not recommended.
Exclude IP addresses - where has it gone?
https://tor.stackexchange.com/questions/20854/exclude-ip-addresses-where-has-it-gone/20868#20868
Bottom line for me is use firefox for localhost on a seperate computer to my tor research machine.
Hope this helps


text:
Q: Разрешение robot.createScreenCapture не соответствует кнопке PrintScreen Необходимо делать скриншот и сверять его с сохраненным на диске, который делали кнопкой PrintScreen. Для того чтобы сделать скрин средствами Java я использую класс Robot:
BufferedImage image = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

Однако скриншоты не совпадают разрешением 1536-864 - java скрин, 1920-1080 - принт скрин.
Если задать разрешение вручную:
robot.createScreenCapture(new Rectangle(0,0,1920,1080));

То получим тот же скрин с разрешением 1536-864 но с черной рамкой. Я немного в замешательстве.
Как делать скриншот с помощью Java аналогичный нажатию принт скрин ? Эмуляция нажатия на кнопку через robot.keyPress не вариант, т.к. у многих установлено по , типа Яндекс диск, который открывает поверх свое приложение.

A: Люди минусят, но ничего не предлагают... Не смог разобраться почему robot.createScreenCapture делает скрин 1536-864 при разрешении экрана 1920-1080.
Решение нашлось следующее:
        MultiResolutionImage multiResolutionImage = robot.createMultiResolutionScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        GraphicsDevice graphicsDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        Image screen = multiResolutionImage.getResolutionVariant(
                graphicsDevice.getDisplayMode().getWidth(), graphicsDevice.getDisplayMode().getHeight());
        ImageIO.write((BufferedImage) screen, "png", new File("test.png"));


text:
Q: python converting any datetime string to UTC I have a tedious function that does something like this:
...
if ('PDT' in stringVal) or ('PST' in stringVal):
    utcdateTime = convert(stringVal)+(hardcode the offset)
elif('EDT' in stringVal)...
...

I looked at several posts including this but couldn't find anything that fits my purpose. I also looked at datetime.datetime and the whole datetime module in general but it has things like .now(); .utcnow(); datetime.now(tz.pytz.utc) etc etc. Basically if I have something like:
2014-05-01 01:02:03 PDT
2014-05-01 01:02:03 PST
2014-05-01 01:02:03 EDT
2014-05-01 01:02:03 EST
2014-05-01 01:02:03 MDT
2014-05-01 01:02:03 MST

Is there a python module that has some method I can use to convert those above datetime strings to UTC? If there is none, I will just stick with the hard-coded way I have.

A: You'll need to translate the timezone strings, but otherwise you can use the datetime and pytz libraries.
import datetime
import pytz

s = '2014-05-01 01:02:03 PST'
ds, tzs = s.rsplit(' ', 1)

tz_map = {
    'PST': 'US/Pacific',
    'EST': 'US/Eastern'
}
tz = pytz.timezone(tz_map[tzs])

dt = datetime.datetime.strptime(ds, '%Y-%m-%d %H:%M:%S').replace(tzinfo=tz)
dt_utc = dt.astimezone(pytz.utc)


text:
Q: Probability of raining in the weekend Just trying to see if my reasoning is correct....
If the probability that next saturday will rain is 0.25 and the probability that next sunday will rain is 0.25, what is the probability that during the weekend will rain?
Assuming that A and B are independent events,
P(A∪B)=P(A)+P(B)-P(A∩B)
and
P(A∩B)=P(A)*P(B)
therefore the probability that during the weekend will rain is:
P(A∪B)=0.25+0.25*0.25*0.25=0.265625
It this reasoning correct?
Thanks,
Luca

A: Almost. For $P(A\cup B)$, you ended up calculating $0.25 + 0.25^3$, not what you actually wanted to calculate. So double-check your last step.
Another way to think about this: What is the probability that it will not rain on Saturday? 0.75. And what is the probability that it will not rain on Sunday? 0.75. So what is the probability that it will rain neither on Saturday nor on Sunday? Assuming independence, it is $0.75^2$. So what is then the probability that it will rain on at least one of those two days? Well, that's just the complement of it not raining on either day, so $1 - 0.75^2$.

A: You are correct, but you made a typo - you wrote:
0.25+0.25*0.25*0.25 = 0.265625

instead of
0.25+0.25-0.25*0.25 = 0.4375

But note that this assumes independence, which is not likely the case of weather.
Relaxing the independence
(This is just an extension of the answer, you don't need to read it :-)
In most general case, you would need this model:
pSat = P(rains on saturday)
pSun = P(rains on sunday)
pSat0_Sun1 = P(rains on sunday | not rained on saturday)
pSat1_Sun1 = P(rains on sunday | rained on saturday)
pSun1_Sat1 = P(rains on saturday | rains on sunday) = pSat1_Sun1 * pSat / pSun
    //  Bayess rule
...

To be realistic, you probably want to simplify the model by assuming pSat = pSun = p and then pSun1_Sat1 = pSat1_Sun1, pSun1_Sat0 = pSat0_Sun1 etc. so the realistic model would be:
p = P(rains on saturday) = P(rains on sunday)
pRainChange = P(rains one day | not rains the other day) = pSat0_Sun1 = pSun0_Sat1

From these 2 parameters you can also derive:
pRainPersist = P(rains one day | rains the other day) = pSat1_Sun1 = pSun1_Sat1 =
    = 1 - pRainChange * (1/p - 1)

From this you can derive:
P(no rain over weekend) = (1 - p) * (1 - pRainChange)
P(rain on sunday only) = (1 - p) * pRainChange
P(rain on saturday only) = p * (1 - pRainPersist)
P(rain both days) = p * pRainPersist

So then your desired
P(rain on saturday or sunday) = (1 - p) * pRainChange + p * (1 - pRainPersist) +
    + p * pRainPersist = (1 - p) * pRainChange + p

When independence, as you assumed, then pRainPersist = pRainChange, which implies both must be equal to p, and then:
P(rain on saturday or sunday) = (1 - p) * p + p = p + p - p * p

But in reality, I'd expect pRainPersist > p > pRainChange.


text:
Q: Transposing a matrix represented as a string? I have a 25 character long string where every subsequent 5 characters represent a row in the matrix.
String matrix="qwsedrhendtedksiehwnehsbt";

I am trying to transpose it using a function
public String transpose(String str) {

    if (str == null || str.length() == 1 || str.length() == 2) {
        return str;
    } else {
        return str.substring(0, 1) + str.substring(str.length() -1, str.length()) + transpose(str.substring(1, str.length() -1) );
    }
}

produces
result="qtwbssehdernhwehneditsekd"

this isnt the expected result.
the result must be
expectedResult="qrtiewheehsedhsenkwbddsnt"

I am not able to understand where I am going wrong

A: This method works for strings representing square matrices.
static String transpose(String s) {
    int n = s.length();
    int m = (int) Math.sqrt(n);
    if (m * m != n)
        throw new IllegalArgumentException();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n - 1; i++)
        sb.append(s.charAt(i * m % (n - 1)));
    sb.append(s.charAt(n - 1));
    return sb.toString();
}

This more general version works for strings representing rectangular matrices.
static String transpose(String s, int rows, int columns) {
    int n = s.length();
    if (rows * columns != n)
        throw new IllegalArgumentException();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n - 1; i++)
        sb.append(s.charAt(i * columns % (n - 1)));
    sb.append(s.charAt(n - 1));
    return sb.toString();
}

A: This transposes a nxn char matrix stored in a string of length n².
static String transpose( String s ){
    char[] c = s.toCharArray();
    int n = (int)Math.sqrt(s.length());
    for( int i = 0; i < n; ++i ){
        for( int j = i+1; j < n; ++j ){
            char h = c[i*n+j];
            c[i*n+j] = c[j*n+i];
            c[j*n+i] = h;
        }
    }
    return new String( c );
}

A: I have an c++ implementation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* transpose (const char* matString, unsigned int col, unsigned int row)
{
    char *answer = (char*)calloc(strlen(matString), sizeof(char));

    unsigned int index = 0;

    for(unsigned int i=0;i<col;i++)
   {
        for(unsigned int j=0;j<row;j++)
    {
        answer[index++] = matString[j * col + i];
    }
 }

    return answer;
}

int main(int argc, char **argv)
{
printf("%s", transpose("ABCDEF", 3, 2));

    return 0;
}

It gives output ADBECF
for the program the input matrix was
A-B-C
D-E-F

After transposition,.it's row will be column & columns will be row
A-D
B-E
C-F

& the string representation will look like ADBECF. For a quick explanation of the matrix transposition can have a look inside Matrix transposition
this is more generalized implementation of your problem specifies. It takes an row & col input for further generalization. Hope it helps you.


text:
Q: Custom Controls not displaying I'm trying to learn how to design a Wpf .NET Core custom control. I've been following a YouTube video to the letter but when it comes to running the solution, the control isn't showing on the main window. Can anybody see what I'm doing wrong?
MainWindow.xaml
<Window x:Class="AnalogClock.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AnalogClock"
        xmlns:custom="clr-namespace:AnalogClock.CustomControls"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Label Content="Test"/>
        <StackPanel>
            <custom:AnalogClock/>
        </StackPanel>
    </Grid>
</Window>

/Themes/Generic.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:AnalogClock.Themes">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/CustomControls/AnalogClockStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

/CustomControls/AnalogClock.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace AnalogClock.CustomControls
{
    class AnalogClock : Control
    {
        static AnalogClock()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(AnalogClock), new FrameworkPropertyMetadata(typeof(AnalogClock)));
        }
    }
}

/CustomControls/AnalogClockStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:AnalogClock.CustomControls">
    <Style TargetType="local:AnalogClock">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:AnalogClock">
                    <Grid>
                        <Line x:Name="PART_HourHand"
                              Stroke="Black"
                              StrokeThickness="2"
                              VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              X1="0"
                              X2="-75"/>
                        <Line x:Name="PART_MinuteHand"
                              Stroke="Black"
                              StrokeThickness="2"
                              VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              X1="0"
                              X2="-100"/>
                        <Line x:Name="PART_SecondHand"
                              Stroke="Red"
                              StrokeThickness="2"
                              VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              X1="0"
                              X2="-100"/>
                        <Ellipse x:Name="PART_Border"
                                 Stroke="Black"
                                 Fill="Black"
                                 StrokeThickness="2"
                                 Width="210"
                                 Height="210"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

A: Add the following attribute to any class file in your project, for example to the file where the AnalogClock class is defined:
[assembly: System.Windows.ThemeInfo(
    System.Windows.ResourceDictionaryLocation.None,
    System.Windows.ResourceDictionaryLocation.SourceAssembly
)]

Unlike .NET Framework projects, .NET Core projects don't include an AssemblyInfo.cs file that contains this attribute by default. It's required for the generic resource dictionary to be found.


text:
Q: Return ids after upsert Slick I have a query that upserts the data to the database via Slick. I'd like to return the ids of the entities that were inserted. How can I do this using Slick in Scala.
Here's a current query and entity defined:
def upsertEntitiesReturn(models: Seq[Entity]): Future[Unit] =
    dbRun((models map (entities returning entities).insertOrUpdate),
      Seq("entities"))

  val entities = TableQuery[Entities]

  class Entities(tag: Tag)
    extends Table[Entity](tag, Some("service"), "entities") {

      private def id = column[String]("id", O.PrimaryKey)
      private def name = column[String]("name")
      private def description = column[Option[String]]("description")

     def `*`: ProvenShape[Entity] =
      (id,
       name,
       description
      ) <> (
        {case (
         id,
         name,
         description
         ) => Entity(
           id,
           name,
           description
         )
       }, (a: Entity) =>
         Some((
           a.Id,
           a.Name,
           a.Description
         ))
     )
  }


text:
Q: Issue when installing sqlite3 in node.js Does anyone know how to fix this issue when running the command "npm install -g triplie"? I also get the same error when installing sqlite3 only.
This is node.js compiled manually, as I can't find a version in apt-get to install.
   gyp ERR! stack     at ChildProcess.emit (events.js:110:17)
gyp ERR! stack     at maybeClose (child_process.js:999:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:1071:5)
gyp ERR! System Linux 3.15.3-x86_64-linode44
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--name=sqlite3" "--configuration=Release" "--module_name=node_sqlite3" "--version=2.2.4" "--major=2" "--minor=2" "--patch=4" "--runtime=node" "--node_abi=node-v14" "--platform=linux" "--target_platform=linux" "--arch=x64" "--target_arch=x64" "--module_main=./lib/sqlite3" "--host=https://node-sqlite3.s3.amazonaws.com/" "--module_path=/usr/local/lib/node_modules/triplie/node_modules/sqlite3/lib/binding/node-v14-linux-x64" "--remote_path=./Release/" "--package_name=node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz" "--staged_tarball=build/stage/Release/node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz" "--hosted_path=https://node-sqlite3.s3.amazonaws.com/Release/" "--hosted_tarball=https://node-sqlite3.s3.amazonaws.com/Release/node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz"
gyp ERR! cwd /usr/local/lib/node_modules/triplie/node_modules/sqlite3
gyp ERR! node -v v0.11.14-pre
gyp ERR! node-gyp -v v0.13.1
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node rebuild --name=sqlite3 --configuration=Release --module_name=node_sqlite3 --version=2.2.4 --major=2 --minor=2 --patch=4 --runtime=node --node_abi=node-v14 --platform=linux --target_platform=linux --arch=x64 --target_arch=x64 --module_main=./lib/sqlite3 --host=https://node-sqlite3.s3.amazonaws.com/ --module_path=/usr/local/lib/node_modules/triplie/node_modules/sqlite3/lib/binding/node-v14-linux-x64 --remote_path=./Release/ --package_name=node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz --staged_tarball=build/stage/Release/node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz --hosted_path=https://node-sqlite3.s3.amazonaws.com/Release/ --hosted_tarball=https://node-sqlite3.s3.amazonaws.com/Release/node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/triplie/node_modules/sqlite3/node_modules/node-pre-gyp/lib/util/compile.js:76:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:110:17)
node-pre-gyp ERR! stack     at maybeClose (child_process.js:999:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:1071:5)
node-pre-gyp ERR! System Linux 3.15.3-x86_64-linode44
node-pre-gyp ERR! command "node" "/usr/local/lib/node_modules/triplie/node_modules/sqlite3/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /usr/local/lib/node_modules/triplie/node_modules/sqlite3
node-pre-gyp ERR! node -v v0.11.14-pre
node-pre-gyp ERR! node-pre-gyp -v v0.5.19
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node rebuild --name=sqlite3 --configuration=Release --module_name=node_sqlite3 --version=2.2.4 --major=2 --minor=2 --patch=4 --runtime=node --node_abi=node-v14 --platform=linux --target_platform=linux --arch=x64 --target_arch=x64 --module_main=./lib/sqlite3 --host=https://node-sqlite3.s3.amazonaws.com/ --module_path=/usr/local/lib/node_modules/triplie/node_modules/sqlite3/lib/binding/node-v14-linux-x64 --remote_path=./Release/ --package_name=node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz --staged_tarball=build/stage/Release/node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz --hosted_path=https://node-sqlite3.s3.amazonaws.com/Release/ --hosted_tarball=https://node-sqlite3.s3.amazonaws.com/Release/node_sqlite3-v2.2.4-node-v14-linux-x64.tar.gz' (1)
npm ERR! sqlite3@2.2.4 install: `node-pre-gyp install --fallback-to-build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sqlite3@2.2.4 install script.
npm ERR! This is most likely a problem with the sqlite3 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-pre-gyp install --fallback-to-build
npm ERR! You can get their info via:
npm ERR!     npm owner ls sqlite3
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.15.3-x86_64-linode44
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "triplie"
npm ERR! cwd /root/node
npm ERR! node -v v0.11.14-pre
npm ERR! npm -v 1.4.14
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /root/node/npm-debug.log
npm ERR! not ok code 0

A: I got the same error trying to install sqlite through npm for etherpad-lite. I checked out the 0.12 branch and rebuilt, and npm install sqlite3 ran with no errors. My etherpad is now using an sqlite database, hooray!


text:
Q: Yii2 delete ActiveRecord error message sometimes array, sometimes not? I have this in Controller, generated with giiant (I assume it's correct):
public function actionDelete($id) {
    try {
        $this->findModel($id)->delete();
    } catch (\Exception $e) {
        $msg = (isset($e->errorInfo[2])) ? $e->errorInfo[2] : $e->getMessage();
        \Yii::$app->getSession()->addFlash('deleteError', $msg);
        return $this->redirect(Url::previous());
    }

    $isPivot = strstr('$id', ',');
    if ($isPivot == true) {
        return $this->redirect(Url::previous());
    } elseif (isset(\Yii::$app->session['__crudReturnUrl']) && \Yii::$app->session['__crudReturnUrl'] != '/') {
        Url::remember(null);
        $url = \Yii::$app->session['__crudReturnUrl'];
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->redirect($url);
    } else {
        return $this->redirect(['index']);
    }
}

Now my problem is, that it throws sometimes $msg as array and I have no clue why.
View/index:
if (\Yii::$app->session->getFlash('deleteError') !== null) {
    echo Alert::widget([
        'options' => ['class' => 'alert-danger'],
        'body' => \Yii::$app->session->getFlash('deleteError'),
    ])
;}

The error message:

PHP Notice – yii\base\ErrorException
Array to string conversion

I have no clue why is it sometimes array and sometimes not. All controllers are the same, but for some Models it's working, for some not. I can implement a workaround that if is_array then ...[0] otherwise ... but I feel it's not the right way to solve the problem. How can a Model change the data type of this error message? Can you please point me to the right direction? Many thanks.

A: First, you're actually never using model validation here, so it has nothing to do with model. Second, $msg is probably OK, the problem is how you're using getFlash(). This method may return array, this is expected and documented:

The flash message or an array of messages if addFlash was used.

You should either iterate trough getFlash() result to get actual message as string, or use widget which will handle this and generate multiple alerts from getFlash() result.
You may also use setFlash() instead of addFlash(). But I would not recommend this - it is easy override some previous flashes and you should not blindly assume that  getFlash() result will be a string.