text:
Q: Bokeh: Display local file in DataTable widget I want for a user to be able to upload a csv file which will then be processed and visualized in Bokeh. The input files have three columns (a, b, and c), and I want to read two of them for display.
I copied something from https://github.com/bokeh/bokeh/issues/6096 to get a Javascript input button.
Now my input file is being displayed in the console, but I can't figure out how to get it into the DataTable widget. Do I need to write an update function or something? Thanks for any help!
import pandas as pd
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import Button, DataTable, TableColumn
from bokeh.io import curdoc
import io
import base64

file_source = ColumnDataSource(data=dict(a=[],b=[],c=[]))
def file_callback(attr,old,new):
    print ('filename:', file_source.data['file_name'])
    raw_contents = file_source.data['file_contents'][0]
    prefix, b64_contents = raw_contents.split(",", 1)
    file_contents = base64.b64decode(b64_contents)
    file_io = io.StringIO(bytes.decode(file_contents))
    df = pd.read_csv(file_io)
    print('file contents:', df)
    return df

file_source.on_change('data', file_callback)

columns = [
    TableColumn(field="a", title="a"),
    TableColumn(field="b", title="b")
]

table = DataTable(source=file_source.data,columns=columns, width=400)

button = Button(label="Upload", button_type="success")
button.callback =     CustomJS(args=dict(file_source=file_source,table=table), code = """
function read_file(filename) {
    var reader = new FileReader();
    reader.onload = load_handler;
    reader.onerror = error_handler;
    // readAsDataURL represents the file's data as a base64 encoded string
    reader.readAsDataURL(filename);
    }

function load_handler(event) {
    var b64string = event.target.result;
    file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]};
    file_source.trigger("change");
    }

function error_handler(evt) {
    if(evt.target.error.name == "NotReadableError") {
        alert("Can't read file!");
    }
}

var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function(){
    if (window.FileReader) {
        read_file(input.files[0]);
    } else {
        alert('FileReader is not supported in this browser');
    }
}
input.click();
""")

curdoc().add_root(row(button,table))

A: This works for me (Python 3.6 and bokeh 0.12.13):
import pandas as pd
from bokeh.layouts import row
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import Button, DataTable, TableColumn
from bokeh.io import curdoc

from io import StringIO
import base64

dict1 = {
    'x':[0]*6,
    'y':[1,1,1,2,2,2]
}

table_source = ColumnDataSource(data=dict1)

columns = [
    TableColumn(field="x", title="x"),
    TableColumn(field="y", title="y")
]

data_table = DataTable(
    source=table_source, columns=columns,
    width=800, editable=True
)

file_source = ColumnDataSource({'file_contents':[], 'file_name':[]})

def file_callback(attr, old, new):
    print('filename:', file_source.data['file_name'])
    raw_contents = file_source.data['file_contents'][0]
    # remove the prefix that JS adds
    prefix, b64_contents = raw_contents.split(",", 1)
    file_contents = base64.b64decode(b64_contents)
    # print("B64 decoded: file_contents : %s" % file_contents)
    # Remove byte order mask and decode to str
    file_contents = file_contents.decode("utf-8-sig")
    # print("Decoded file_contents : %s" % file_contents)
    file_io = StringIO(file_contents)
    # Separator might need to be adjusted
    df = pd.read_csv(file_io, sep=";")
    table_source.data = table_source.from_df(df)
    print("Table source data: %s" % table_source.data)

file_source.on_change('data', file_callback)

button = Button(label="Upload", button_type="success")

button.callback = CustomJS(args=dict(file_source=file_source), code = """
function read_file(filename) {
    var reader = new FileReader();
    reader.onload = load_handler;
    reader.onerror = error_handler;
    // readAsDataURL represents the file's data as a base64 encoded string
    reader.readAsDataURL(filename);
}

function load_handler(event) {
    var b64string = event.target.result;
    file_source.data = {'file_contents' : [b64string], 'file_name':[input.files[0].name]};
    file_source.trigger("change");
}

function error_handler(evt) {
    if(evt.target.error.name == "NotReadableError") {
        alert("Can't read file!");
    }
}

var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function(){
    if (window.FileReader) {
        read_file(input.files[0]);
    } else {
        alert('FileReader is not supported in this browser');
    }
}
input.click();
""")

curdoc().add_root(row(button, data_table))

I have created a .csv file that is ; separated. For it to be loaded as a DataFrame I had to add and adjust your code in file_callback. This was because (at least my .csv) included a Byte Order mark which i remove:
file_contents = file_contents.decode("utf-8-sig")
df = pd.read_csv(file_io, sep=";")

Then, I defined a new table_source for the DataTable widget. This gets updated with the data from the uploaded .csv after it is converted to a DataFrame. This happens within file_callback here:
table_source.data = table_source.from_df(df)

These last parts were the pieces you were missing.
I used this answer to the github issue you mentioned as the basis of my code.


text:
Q: Command history (previous and next command) in ngspice This is driving me nuts. I am using ngspice in interactive mode on Ubuntu. I expected the up and down arrows to scroll through previous commands just like in bash or pretty much any CLI ever. However doing so in ngspice just prints out "^[" or "[A". There is a history command and I am able to use "!" to execute previously executed commands just like in bash but what I want to do is bring up a previous command and edit it (like I can by pressing the up arrow in bash). Is there any way to so this in ngspice or do I really have to keep typing out the command from scratch if I want to change it?

A: I would upgrade to Quantal or later so the editline support be activated without having to compile stuff, but if you feel hacky you can do this easily (you must make sure that you have the sources repositories activated):
sudo apt-get build-dep ngspice
sudo apt-get install dpkg-dev
apt-get source ngspice
cd ngspice*
sed '0,/\.\/configure/{N;N;s/$/\n                --with-editline=yes \\/}' debian/rules
## Add the -i option once you are sure of the changes,
## I recommend using `| grep -A5 -B5 editline` to verify
dpkg-buildpackage
dpkg -i ../ngspice*.deb

Done.

A: The ngspice package in the precise repository was compiled without editline support. This was corrected in a the newer repositories, but not in the precise one. link:

*

*Change configure parameters

So if you install on 12.04 or older you will have this problem, if you install on 12.10 or newer you won't.
To solve this on 12.04 you can try compiling ngspice for yourself or you can try installing the .deb package from a newer repository, e.g quantal, hopefully installing this .deb from the newer repository won't break anything on your system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas join on tuple and frozenset field I want to a do a join on common field Products. But this common field is represented as different schema in both dataframes as depicted below:
df1 [frozensets]
Products    Products1
0   (A, C)  (B)
1   (A, B)  (C)
2   (C, B)  (A)
3   (A)     (C, B)
4   (C)     (A, B)

df2 [tuples]
Region  Products

France  ('A','B')
France  ('C')
France  ('B','D')
France  ('C','A','B')
France  ('A','B')

In df2, Products are represented as tuples but not in df1. Can someone help me to convert df1['Products'] to tuple so that I can do this join
s1 = pd.merge(df1, df2, how='left', left_on='Products',right_on='Products')

A: so as the elements are not in string (which they should've been by logic), we can typecast them and make a new tuple of df1 products.
you can try something like this
df_pros = df1['Products'] # or some another way to select all the products from df_1
df_mod = tuple(map(lambda x: (str(x[0]), str(x[1])) if len(x) == 2 else (str(x[0])), list(map(list, df_pros))))
s1 = pd.merge(df_mod, df2, how='left', left_on='Products',right_on='Products')


text:
Q: component is not being rendered in reactJS i have 3 component, that is App, Greet, and navBar. when i tried to import App, and Greet it was rendered successfully, but the navBar component was not rendered, here is my code
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (

Haloo

        <input type = "text"></input>

  );
}

export class Greet extends React.Component {
  render() {
    return (

Hello World

    );
  }
}

export class navBar extends React.Component {
  render() {
    return (

Navbar

    )
  }
}

export default App;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import navComponent, {navBar} from './App';
import GreetComponent, {Greet} from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <App />,
document.getElementById('root')
);

ReactDOM.render(
    <Greet />,
  document.getElementById('greet')
);

ReactDOM.render(
  <navBar />,
  document.getElementById('nav')
);

what i already tried is, changing the component name but it still the same, thanks for your help, any help will be appreciated, im still learning ReactJS

A: All React component names must start with a capital letter. See if renaming it to "Navbar" works.


text:
Q: addition of one column with certain condition in another colum, like sumifs of excel in matlab
Possible Duplicate:
addition of one column with certain condition in another colum, like sumifs of excel

here i want to count the no of 2nd column, with the same conditions in column 1,
i m dictating here again,
A=[1 2;2 3;3 4;3 2;4 3;5 4;5 2;6 3;7 2;8 3]
now i want to count no of 2, 3 and 4 in column2, condition is that when column 1 ranges from 0 to 3, 3 to 6, 6 to 9, 9 to 12 like that.
answer is like that
ranges no2, no3, no4
0 to 3-- 2-----1-------1
3 to 6---1------2-------1
6 to 9-- --1-----1------0
help me,,,, waiting for your reply..

A: You could potentially do something like this:
for(n=1:size(A,1))
    if(A(n,1) >= 0 && A(n,1) < 3)
        % Do something
    elseif( ) % next test condition
        % Do something there.
    end
end

Another option would be to use the for loop to go through your first column and using a switch statement to pull the appropriate action based on that input.
Update below:
for(n = 1:size(A,1))
    switch(mod(A(n,1),3))
        case 0 % this will be 0, 1, 2 in your column
            % code
        case 1
            etc...
    end
end

Info on modulus in matlab
Info on switch in matlab

A: With MATLAB you can use logical indexing meaning that you can filter a variable with any number of conditions. For example, if vec is any vector and you wish to know how many elements of vec are negative you can do the following,
% save the elements of vec which are negative
ind = vec < 0
% vec is a logical variable. Each element of vec lower that 0 is store as 1.
% to know how many elements of vec are smaller than 0
sum(ind)
% will tell you how many ones are there in ind, meaning the number of elements in vec which
% are smaller than 0

% Of course you can do the same all at once,
sum(vec < 0)
% and you can directly access the elements in the same way
vec(vec < 0)

So returning to your problem, you can use something like,

for i = 1:3:length(A)
    %print how many 2s,3s and 4s
    fprintf('%d to %d: %d, %d, %d\n',i,i+2,sum(A(i:i+2,2)==2),sum(A(i:i+2,2)==3),sum(A(i:i+2,2)==4))
end


text:
Q: Find the residue of ζ(2s) and ζ(6s) I know that the residue of the Riemann zeta function is 1. I'm wondering how one would calculate the residue if you have ζ(2s) and ζ(6s) as the pole has shifted to 1/2 and 1/6 respectively.
Also do the trivial zeros change? So ζ(2s) has trivial zeros at s=-1,-2,-3,...?

A: You are correct about the placement of the trivial zeros of $\zeta(2s).$ This could be seen, for example, from the functional equation (i.e. reflection formula) of $\zeta(2s)$:
$$\zeta(2s)=\zeta(1-2s)\Gamma(1-2s)\sin(πs)π^{2(s-1)}4^s$$ which follows from the functional equation of $\zeta$ after some algebraic massage. This thing goes to 0 precisely when $s=-n\quad\land\quad 1\le n\in\mathbb{N}.$ So yes, they do in fact change values.
The poles of $\zeta(2s)$ and $\zeta(6s)$ are, in fact, simple, and as you have stated are $\frac{1}{2}$ and $\frac{1}{6}$ respectively, so we have the residue of $f$ at a simple pole $x_0$: $\lim_{z\to x_0}(z-x_0)f(z)$ and as to your question, the residues could be found by:
$\lim_{z\to\frac{1}{2}}(z-\frac{1}{2})\zeta(2z)$
$\lim_{z\to\frac{1}{6}}(z-\frac{1}{6})\zeta(6z)$
respectively.


text:
Q: is it mandatory to have a link function in angularjs directives? When building our own directives in angularjs 1.5.x+, is it mandatory to have a link function? If not, how will angular deal with it? Will it use its own default implementation of the link function?
I explored a lot about this. However little information is available in the search engines in this regard.

A:
No.

You do not have to use the link function. It's typically used if your directive wants to modify the DOM or needs to hook into events on the component related to the directive. Some directives might not need this, and even if you just want to work with a template and a scope, you still don't need to use the link function.
It's all very well explained here: https://docs.angularjs.org/guide/directive
You can use the controller function instead of the link in many cases. Taken directly from the docs:

The basic difference is that controller can expose an API, and link
  functions can interact with controllers using require.


text:
Q: How to get the difference between two dates (informix)? How to get the difference between two dates (informix) in integer format  like that

day = 15
mon = 2
year = 1

A: There are two sets of date/time values in Informix: DATE and DATETIME.
The DATE type is oldest (it was in the precursor to the SQL-based Informix), and represents the integer number of days since a reference date (where day 0 is 1899-12-31, so day 1 was 1900-01-01).
You get the difference between two DATE values in days by subtracting one from the other.
The DATETIME system is newer (but still old — circa 1990).  You can take the difference between two DATETIME YEAR TO DAY values and get a result that is an INTERVAL DAY TO DAY (essentially the number of days).
You could also take the difference between two DATETIME YEAR TO MONTH values and get a result that is an INTERVAL YEAR TO MONTH.
However, there is no way to get a difference in years, months and days because there is no simple way to deduce that value.  In fact, ISO SQL recognizes two classes of INTERVAL: those in the YEAR-MONTH group, and those in the DAY-SECOND group.  You can't have an INTERVAL that crosses the MONTH/DAY barrier.

A: Use the MDY function :
select mdy(2,15,2014) - mdy(1,15,2014) from sysmaster:sysdual


text:
Q: Как сделать, чтобы у объектов grid сохранялся display: inline-block? Недавно начал делать надписи у слайдшоу, и пришел к тому, что при большой ширине экрана заголовок и текст сливаются в один ряд (при маленькой ширине все нормально). Но когда я попытался исправить проблему с помощью grid, то bgcolor распространился на всю сетку. Как это исправить ?
P.S. Также пробовал ограничивать ширину текстового блока, но тогда при уменьшении ширины терялся нужный вид.

.ss-item-text {
  /* display: grid;
 grid-template-columns: 1fr;*/
  position: absolute;
  top: 60%;
  left: 5%;
  /*width: 60%;*/
}

.h1-ss-item {
  background: var(--dark-blue);
  color: var(--green);
  display: inline-block;
  margin: 0;
  padding: 10px;
}

.p-ss-item {
  width: 80%;
  background: var(--dark-blue);
  color: var(--green);
  display: inline-block;
  margin: 0;
  padding: 10px;
}

.ss-item {
  width: 100%;
  height: 60vh;
  margin-right: 0;
  background: #8C8;
  font-size: 1.25em;
}

Комфорт

      Велсофт создан для домашнего комфорта и уюта. Её пушистый, мягкий ворс напоминает велюр, но отличается особой шелковистостью и нежностью. Изделия из этого материала дарят и взрослым, и детям ощущения особого домашнего тепла и покоя

.ss-item-text {
 display: grid;
 grid-template-columns: 1fr;
 position: absolute;
 top: 60%;
 left: 5%;
 /*width: 60%;*/
}

.ss-item-text {
 /*display: grid;
 grid-template-columns: 1fr;*/
 position: absolute;
 top: 60%;
 left: 5%;
 width: 30%;
}

A: .h1-ss-item {
    background: var(--dark-blue);
    color: var(--green);
    display: inline-block;
    margin: 0;
    padding: 10px;
    float: left;
}

.p-ss-item {
    width: 80%;
    background: var(--dark-blue);
    color: var(--green);
    display: inline-block;
    margin: 0;
    padding: 10px;
    float: left;
    clear: left;
}


text:
Q: How to stay logged into Magento 2.0 longer Magento 2.0.2 seems to log me out after 5 or so minutes of inactivity.
Is there a setting to keep me logged into the Admin backend longer? If so, where and how?

A: Go to Stores > Config > Advanced > Admin > Security and edit the Admin Session Lifetime field. This is in seconds, for development purposes I usually go for 28800 which is 8 hours.


text:
Q: 3.3 V switching off 3.3 V or 5 V I'm hacking a device that uses USB 2.0 for another purpose - the USB 2.0 was for a communications card, and I'm changing it for flash USB storage.
I have the device working (it uses the USB storage) but when the device is off, the USB storage drains the battery.
The devices 4 pins are 3.3 V, D+, D-, and Gnd.  Since most USB are 5 V, I have a boost module installed to 5v - and that read 5v even when the device is shut off.
The D+ and D- pins are low when the device is off and high 3.3 V when on.
The 3.3 V (boosted to 5 V) is always on.
I'm looking for a way to turn the 5 V off (or 3 V before the boost) when the data channels are low.
Is a MOSFET a good solution?  Collecting the 3.3 V to open a 5 V or 3.3 V?  Will it turn off with the device?  Would an npn transistor as a switch work better?  Some other switch solution?
Any other suggestions would be super helpful.


text:
Q: Getting Byte[] from Decoded base64 MIME Part We receive files from various entities that can contain MIME parts (which are PDFs) in them that are base64 encoded. We extract it out and store it to open later. This has worked fine for all but from one of the entities. Their files will save, but have not been able to open them.
Here is the code:
        public byte[] GetAttachmentByName(string name)
    {
        foreach (var attachment in _mimeMessage.BodyParts.OfType<MimePart>())
        {
            if (attachment.ContentId != name)
                continue;

            using (var stream = new System.IO.MemoryStream())
            {
                using (var filtered = new FilteredStream(stream))
                {
                    filtered.Add(DecoderFilter.Create("base64"));
                    attachment.ContentObject.DecodeTo(filtered);

                    return stream.ToArray();
                }
            }
        }

        return null;}

Here is what part of the MIME looks like:
MIME-Version: 1.0
Content-Type: multipart/related; boundary="=-antAW7IrKfe1DvH3559M9g=="
…
--=-antAW7IrKfe1DvH3559M9g==
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Description:
Content-Id: "AC13127925.pdf"
…
bGVyDTw8IA0vU2l6ZSAxODkgDS9Sb290IDE4OCAwIFIgDS9JbmZvIDEgMCBSIA0+PiANc3Rh
cnR4cmVmDTU3MzU3MiANJSVFT0YN
--=-antAW7IrKfe1DvH3559M9g==--
(I included the start, middle, and end of the MIME part. There is also XML in another part of the file, but that is processing just fine. The problem we are having is with the MIME/PDF.)
Any guidance at all is appreciated.

A: The MimeContent.DecodeTo() method already decodes the base64 for you, so you need to change your code to this:
public byte[] GetAttachmentByName(string name)
{
    foreach (var attachment in _mimeMessage.BodyParts.OfType<MimePart>())
    {
        if (attachment.ContentId != name)
            continue;

        using (var stream = new System.IO.MemoryStream())
        {
            attachment.ContentObject.DecodeTo(filtered);

            return stream.ToArray();
        }
    }

    return null;
}


text:
Q: SOS: file recover Hallo all,
I made some revisions on a c sharp file in visual studio 2008 express, and committed the following actions:
1. open this c sharp file thru notepad,
2. tried to save some modifications in this file while it was opened by the notepad,
3. Ctrl+C and Ctrl+V to make a copy to this file
4. closed visual studio 2008 and notepad
Then this c sharp file dissappears! Please help!
John

A: It's gone forever.  The only thing you can really hope for is to pair the situation with the appropriate whiskey.
If it was months of work down the drain, I would choose Ancient Age out of the plastic bottle.

A: if you right click in your project and then goto add existing you should be able to re-add it.
As to why it disapears i am not sure ... i guess it may be a file handle problem.

A: Is there a repository, a version control system, or something like that? Otherwise, let your code RIP.

A: Sounds like it has probably gone forever, but you should be able to recover it from your daily backups. You do take daily backups don't you....?


text:
Q: Convert integer to hex with padding in Python I have an integer (67) that needs to be converted to hex and stored as a string like:
"\x00\x00\x00\x43"
How can I do this in Python?

A: Updated due to ambiguity in OP.
Try...
def convert(i):
    result = ''
    for c in struct.pack('>i', 67):
        c = hex(ord(c))[2:]
        if len(c) < 2:
            c = '0%s' % c
        result += '\\x%s' % c
    return result

>>> print convert(67)
\x00\x00\x00\x43


text:
Q: Finding an expression for the CDF of sum of two random variables $X, Y$ conditioned on the value of one variable $Y$: find $P(X + Y < c | Y = b)$ This is related to my other question on renewal processes https://math.stackexchange.com/questions/3947852/renewal-theory-probability-of-residual-lifetime-gamma-t-x-conditioned-on-c
$X, Y$ are continuous random variables, possibly not independent, and we know the $CDF$ of $X + Y$ which is given by $F(c)$. What is $P(X + Y < c | Y = b)$ in terms of $F(c)$?
Attempt:
$P(X + Y < c | Y = b) = \frac{P(X + Y < c)}{P(Y = b)}$. The numerator is just $F(c)$, but how do I find the denominator in terms of the given $CDF$? Another confusion I have is why is the denominator not just $0$ since $Y$ is a continuous random variable?


text:
Q: Is $\Bbb Q$ disconnected under general topology from $\Bbb R$? I just completed the proof of that fact that $\Bbb Q$ is disconnected. My question is how to find a separation of $\Bbb Q$.
Let $X$ be a topological space. We say $A$ and $B$ forms a separation of $X$ if $A\cap \bar{B}$ and $\bar{A}\cap B$ are empty and $A\cup B=X$.
Here $\Bbb Q$ denotes the set of rational numbers.
Can someone please help with hints.
Thanks.

A: $U= (-\infty, \sqrt{2}) \cap \mathbb{Q}$, is open in $\mathbb{Q}$ as the intersection of an open subset of $\mathbb{R}$ with $\mathbb{Q}$ (definition of subspace topology) and similarly $V=(\sqrt{2}, +\infty) \cap \mathbb{Q}$ is also open in $\mathbb{Q}$.
As $\sqrt{2} \notin \mathbb{Q}$ we have $\mathbb{Q} = U \cup V$ and $\overline{U} = U$ (closure in $\mathbb{Q}$) and $\overline{V}=V$ and clearly $U \cap V=\emptyset$, so $\{U,V\}$ forms a separation of $\mathbb{Q}$.


text:
Q: What Does a double assignment in a VB.NET assignment accomplish? I (new to VB.NET) am doing some code maintenance on a function that sometimes throws an exception "error converting string "False" (or "True") to type Integer."  What I found was something equivalent to this
someVal is a string, someFun1 returns an Integer and someFun2 takes an Integer as a parameter
...
someVal = someVal = someFun1()
...
someFun2(someVal)
...

What I think might be happening is that it is trying to assign     someFun1's return value into someVal, then perform a bool check as to whether someVal has changed - but I don't think that is what needs to be done.
My question is - does this double assignment (someVal = someVal = someFun1()) accomplish anything that I don't know about in VB.NET?
another note: I realize there are implicit casts of integer to string and back to integer, but that shouldn't be causing any problems, because the values should always hold a numerical value (which can be implicitly cast back and forth from Integer and String, right?) not True or False - as far as I can tell

A: The confusion here is that the equals operator = is the same as the assignment operator = in VB.NET. In C#, the code above would be equivalent to
someVal = someVal == someFun1();

where the boolean equals operator == is carried out first, and the result is inserted into someVal. This fails, because someVal is int, not bool.
In other words, the runtime is comparing someVal with the return value of someFun1(), returning True or False, and failing to cast that to an integer. This isn't a "double assignment" - it's just an inline representation of
If someVal = someFun1() Then
    someVal = True
Else
    someVal = False
End If

where it is much more obvious that we're trying to give an Integer variable a value of type Boolean.


text:
Q: how to unerstand finite dimensional vector spaces
A vector space $V$ is called finite-dimensional if there is a finite subset of $V$ that is a basis for $V$. If there is no such finite subset of $V$, then $V$ is called infinite-dimensional.

We now establish some results about finite-dimensional vector spaces that will tell about the number of vectors in a basis, compare two different bases, and give properties of bases. First, we observe that if $\{\mathbf{v}_1, \mathbf v_2,\dotsc, \mathbf v_k\}$ is a basis for a vector space $V$, then $\{c\mathbf v_1, \mathbf v_2, \dotsc, \mathbf v_k\}$ is also a basis when $c\neq 0$ (Exercise 35). Thus a basis for a nonzero vector space is never unique.
Image.

I am confused if $\mathbb R^2$ is a finite dimensional vector space. $[1 \ 0],[0 \  1]$ will be the standard basis of $\mathbb R^2$. However, there are also $[2 \ 0],[0 \ 1]$ and I can find infinite many to be the basis of $\mathbb R^2$. So, $\mathbb R^2$ is an infinite dimensional vector space?

A: I don't understand why this question was downvoted since it is an honest one. For a vector space $V$, the existence of a finite basis is all you need to determine the dimension (which is unique). This is because you can show that if $A$ is a basis for $V$ and $|A| = n$ then any other basis $B$ for $V$ also have to have cardinality $n$.

A: I suppose you are mixing the terms "finite subset" and "finite number of subset".
The first one corresponds to the fact that in the subset there are only finitely many ${\it elements}$; the second one corresponds to the fact that there are finitely many ${\it subsets}$.
Hope I helped. I also mixed these two concepts at the start of learning linear algebra, so I think you met the same problem.

A: For each $n$, the following is a basis for $\mathbb{R}^2$, ${\cal B}_n = \{ (0,1), (n,1) \}$.
So, each ${\cal B}_n$ has exactly two elements, but there is an infinite number of bases.


text:
Q: how to capture image in android phone using application I have to automate the script where i will click on the camera icon in my application which will open the camera but am not able to capture the image and attach the image.
I am using Appium and i tried these two possibilities:
1)oBrowser.pressKeyCode(AndroidKeyCode.KEYCODE_CAMERA);
2)oBrowser.pressKeyCode(27);
But none of them works.
Can any one help me to solve the issue?

A: Have you tried?
Runtime.getRuntime().exec("cmd /C adb shell input keyevent " + eventNumber);


text:
Q: AngularJS with loading external page with controller I have a quick question on loading external page with route. I am quite new to AngularJS.
var app = angular.module('app', []);
$routeProvider.when('/list', {
    templateUrl: '/list.html'
})

Load up the page, but within the list.html there is controller defined.
list.html:

The above code will throw me an error as test is undefined function, unless if i place the app.controller('test') to the parent page.
So i can't place controller on external .html files?
Updated link below:
http://plnkr.co/edit/YC6P9W1VfzX8XOyrynCP?p=preview

A: You have to create a separate script.js and should load in main html page during execution of main page or during click of the link
    index.html

    <!DOCTYPE html>

        <link rel="stylesheet" href="style.css">

Hello Plunker! {{change}}

        Test
        <ng-view></ng-view>

    testscript.js

    function test2($scope){
          console.log('succeed');
    };

    script.js

    // Code goes here
    var app = angular.module('app', ['ngRoute']);

    app.controller('home', function($scope){
      $scope.change = "change";

      $scope.test = function(){
        console.log('clicked');
      }
    });

    app.config(function($routeProvider){
      $routeProvider.when('/test', {
          templateUrl: 'test.html',
          controller: function(){
            console.log('here');
          }
      })
    });


text:
Q: How to convert array in a df cell to individual column names? I am not able to convert below DF:
 | A | B |     C   |
 | 1 | 2 | t1,t2,t3|
 | 1 | 3 | t4,t5   |
 | 2 | 2 | t1,t5   |

to below DF:
| A | B | t1 | t2 | t3 | t4 | t5 |
| 1 | 2 | 1  | 1  | 1  | 0  | 0  |
| 1 | 3 | 0  | 0  | 0  | 1  | 1  |
| 2 | 2 | 1  | 0  | 0  | 0  | 1  |

in scala spark.
Values in column C are comma separated and I want it to make them into separate columns. Once that is done I want to mark 0 and 1 in that particular row if t1, t2, etc. exists or not.
Please help here. Would really appreciate.

A: This can be done by using pivot. However, first split the the data on "," and explode the C column.
df.withColumn("C", explode(split($"C", ",")))
  .groupBy("A", "B")
  .pivot("C")
  .count()
  .na.fill(0)

Result:
+---+---+---+---+---+---+---+
|  A|  B| t1| t2| t3| t4| t5|
+---+---+---+---+---+---+---+
|  2|  2|  1|  0|  0|  0|  1|
|  1|  2|  1|  1|  1|  0|  0|
|  1|  3|  0|  0|  0|  1|  1|
+---+---+---+---+---+---+---+

The above solution assumes that all rows have unique combinations of values in A and B (due to the use of groupBy). If this is not the case an additional step is necessary:
Add a new column with a unique id that can be used together with A and B in the groupBy, e.g.:
df.withColumn("D", monotonically_increasing_id)

This column can be deleted after the pivot.

A: First you need to get all values from column C and then create a Set of that columns C as value which will use as columns name, check below process

*

*Create Data Frame:
val df = spark.sparkContext.parallelize(Seq((1, 2, "t1,t2,t3"), (1, 3, "t4,t5"), (2,2,"t1,t5"))).toDF("A","B","C")
+---+---+--------+
|  A|  B|       C|
+---+---+--------+
|  1|  2|t1,t2,t3|
|  1|  3|   t4,t5|
|  2|  2|   t1,t5|
+---+---+--------+

*Read Column value which require for header for Data frame :
val cols = df.select($"C")
val colnameAsHeader = cols.map(x=>x.getString(0).split(",")).collect.flatten.toSet

*Create UDF for check criteria:
def checkCriteria(inputString: String) = {udf((inputColumn: String) => { if(inputColumn.split(",").contains(inputString)){1}else{0} })}

*Use foldLeft to set header :
colnameAsHeader.foldLeft(df)((df, name) => df.withColumn(name , lit(checkCriteria(name)($"C")))).drop("C").show

+---+---+---+---+---+---+---+
|  A|  B| t4| t5| t3| t2| t1|
+---+---+---+---+---+---+---+
|  1|  2|  0|  0|  1|  1|  1|
|  1|  3|  1|  1|  0|  0|  0|
|  2|  2|  0|  1|  0|  0|  1|
+---+---+---+---+---+---+---+

A: Another possible is to make use of spark sql functions of Spark 2.4 instead of udf asthe following:
Collect all values in values List then test foreach value in your list if it exists in your array column by using the array_contains method
val df1  = Seq(
  ("1", Array("t1", "t2")),
  ("2", Array("t1", "t3", "t5"))
).toDF("id", "arr")
import org.apache.spark.sql.functions.{col, lit, array_contains, when}
val values = df1.select("arr").collect().map(x => x.getList[Array[String]](0).toArray)
  .flatMap(x => x)
  .distinct
  .map(_.toString)
val df2 = df1
  .select(df1.columns.map(col(_)) ++
    values.map(x => when(array_contains(col("arr"), x), 1).otherwise(0).alias(x)):_*)
df2.show()

+---+------------+---+---+---+---+
| id|         arr| t1| t2| t3| t5|
+---+------------+---+---+---+---+
|  1|    [t1, t2]|  1|  1|  0|  0|
|  2|[t1, t3, t5]|  1|  0|  1|  1|
+---+------------+---+---+---+---+


text:
Q: Magento 2: What is the best way to observe cart change to modify cart item in magento 2? I'm using Magento v2.3.4 and i want to modify the cart item, if there is an update on the cart (add to cart, update cart item, and remove cart item). Currently I'm using plugin for quote collectTotals() function.
Is this the correct way to do it, or is there any other method that i can use ?
etc/di.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Quote\Model\Quote">
        <plugin disabled="false" name="Vendor_Module_Plugin_Magento_Quote_Model_Quote" sortOrder="10" type="Vendor\Module\Plugin\Magento\Quote\Model\Quote"/>
    </type>
</config>

Vendor/Module/Plugin/Magento/Quote/Model/Quote.php
public function beforeCollectTotals(\Magento\Quote\Model\Quote $subject)
{
    $quote = $this->getQuote();
    foreach($quote->getAllItems() as $item){
       $price = $this->getCustomPrice($item->getProductId());
       if($price){
          $item->setCustomPrice($price);
          $item->setOriginalCustomPrice($price);
       }
    }
    return [];
}

the problem with this plugin is, i got this error after i placed an order:

Please check the billing address information. "firstname" is required.
Enter and try again. "lastname" is required. Enter and try again.
"street" is required. Enter and try again. "city" is required. Enter
and try again. "telephone" is required. Enter and try again.
"postcode" is required. Enter and try again. "countryId" is required.
Enter and try again.

i check the quote address in the database and those field column is empty

A: As far I know
1: If you need to override a single method first priority will be plugin and in plugin the  first will be before plugin and then after and if both are not possible then use around
2: If plugin is not working then we can override whole class but this is the least thing if other solution are not working
while overriding whole class if possible override the only method that you want to override and if not possible with the specific method that you want then override the whole class with all methods

A: have you used the below two events observer ?
checkout_cart_product_add_after and checkout_cart_product_update_after from this events you can from this observer you can get the $item = $observer->getQuoteItem(); and then you can use below code to add your custom price you can use the same observer file for both events
$item = ($item->getParentItem() ? $item->getParentItem() : $item);
$orignalprice = $product->getFinalPrice();
$customPrice = 10; // your price
$price = $orignalprice + $customPrice;
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);

A: Use checkout_cart_product_add_after event.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="customprice" instance="Dolphin\Hello\Observer\CustomPrice" />
    </event>
</config>

have to create CustomPrice.php file that override your price in the Observer Folder.
<?php
        namespace Dolphin\Hello\Observer;

        use Magento\Framework\Event\ObserverInterface;
        use Magento\Framework\App\RequestInterface;

        class CustomPrice implements ObserverInterface
        {
            public function execute(\Magento\Framework\Event\Observer $observer) {
                $item = $observer->getEvent()->getData('quote_item');
                $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
                $price = 100; //set your price here
                $item->setCustomPrice($price);
                $item->setOriginalCustomPrice($price);
                $item->getProduct()->setIsSuperMode(true);
            }

        }


text:
Q: Android: does flight mode turn off radio completely or just transmission portion? I have an Android application that uses both ble and wifi.  Periodically ble locks up and no longer detects devices.  while fault-finding the lock up, I noticed that I can reestablish normal operation by switching flight/airplane mode on an off.  BUT if I turn bluetooth on/off or wifi on/off, or both wifi and bluetooth on/off, I cannot replicate the results I get by turning flight mode on/off.  This tells me that flight mode is doing something different.  So:
what is the difference between flight mode and the separate functions for turning bluetooth and/or wifi on and off?

A: What we know
Airplane mode disables all radios, cellular, bluetooth, GPS, NFC, wimax, and any other radios declared in Settings.Global.AIRPLANE_MODE_RADIOS you can check the list in your particular device by executing adb shell settings get global airplane_mode_radios.
What we don't know
As to why it's different from simply disabling a certain radios by itself, I also experienced something similar with WIFI not connecting anymore and working once again after ON/OFF of airplane mode.
You can follow the source code of what APM does but in the end it broadcasts as user the intent Intent.ACTION_AIRPLANE_MODE_CHANGED and this intent is handled by all the broadcast receivers of the radios individually. How they handle this differently from a simple toggle of the radios in settings makes the difference between it coming back to life or not.
Digging deeper
For example, in the BluetoothManagerService, when we enable Airplane mode, we trigger status 2 for the radio, instead of 0 which would be disabled. So there clearly is a differentiation between disabled and airplane mode disabled, this is interesting.
// Bluetooth persisted setting is off
private static final int BLUETOOTH_OFF=0;
// Bluetooth persisted setting is on
// and Airplane mode won't affect Bluetooth state at start up
private static final int BLUETOOTH_ON_BLUETOOTH=1;
// Bluetooth persisted setting is on
// but Airplane mode will affect Bluetooth state at start up
// and Airplane mode will have higher priority.
private static final int BLUETOOTH_ON_AIRPLANE=2;

As you can see, in the very source code of the Manager, it's noted that the Airplane mode will affect the startup. So perhaps this is what you're after. When we enable the radio after airplane mode, this is the code that's run:
sendEnableMsg(mQuietEnableExternal);

However, simply enabling the radio runs this one:
    sendEnableMsg(false);
Conclussion
Maybe it has something to do with the quiet mode? It's rather fascinating, and I'm sorry I can't provide a better answer but hopefully it's a good starting point if you care to dig even deeper.


text:
Q: Why wrong spelling in str.length doesn't show an error in JS I'm a beginner javascript dev, I wrote this code:
var foo = "sunny";
var longitudInt = foo.length;
console.log("The length of " + foo + " is " + longitudInt);

But when I wrote foo.length, I made a spelling mistake and wrote foo.lenght, but it didn't show an error in the console, Why?
It doesn't show an error

A: The value of "something".lenght (or anything really, "something".foobar) will be "undefined" (roughly equivalent to null).
It doesn't throw an exception as it would with some other languages

A: foo.lenght will not raise an error but it will return undefined. The reason for this is that foo is a String type variable and when it try to call the property lenght (which is invalid), it does not get that in its prototype. Thus, it returns with undefined instead of error.

var foo = 'str';
console.log(foo.lenght);

However, if you try to access other properties in foo.lenght say, foo.lenght.len then this will give you error because at this time foo.lenght is undefined and it tries to read a property of a undefined type.

var foo = 'str';
console.log(foo.lenght.len);


text:
Q: How to make a GUI that plots user-entered function(x)? I'm developing a program that takes a function of x from the user, also it takes the min and max values of x, then the program have to plot this function.
for example:
user-entered function(x) is: x^2+2x-1
Max value of x is : 3
Min value of x is : -3
now the GUI have to display (if the entered function is free of errors otherwise the error will be displayed to the user) something similar to this image:

The entered function also maybe a little bit complex E.g.(sin(x), cos(2*x+1), etc..)
I'm trying to make this job with C++ and QT, so any advice how to make the plotting part of the program using QT, or if anyone knows better recommendation instead of QT that works with C++ and can do this job.
Thanks in advance.

A: You are going to need a library that interprets mathematical expressions (i.e: muparser). In the code i did my own math, but you will be doing that using a library. Considering you managed all those; with QCustomPlot you can draw your graphs.
Here's a sample to give an idea how you can use QCustomPlot:
/** I copy pasted the code from one of my projects, please ignore function & class namings
 */
/** somewhere in your window constructor, create a QCustomPlot
 * widget and add graphs to your QCustomPlot widget.
 * example: ui->plt_freq_domain->addGraph();
 */

void ControllerMain::plot_frequency_domain()
{
    QVector <double> vec_keys(1024), vec_values(1024);
    //fill x axis values with incrementing numbers from 0 to 1024 (or any other number you want)
    // let's say your function is y = x^2 and calculate all y values and store them in vec_values
    for(int i = 0; i < vec_keys.size(); i++)
    {
        vec_values[i] = std::pow(vec_keys[i], 2);
    }

    // we fill keys with continuous integers [0,1023] so our graph spans along x-axis
    std::iota(vec_keys.begin(), vec_keys.end(), 0);

    ui->plt_freq_domain->graph(0)->setData(vec_keys, vec_values, true);
    ui->plt_freq_domain->graph(0)->setPen(QPen(QColor(245, 197, 66)));

    ui->plt_freq_domain->yAxis->setLabel("A/m"); // change it with your unit or just keep empty
    ui->plt_freq_domain->yAxis->setRange(*std::min_element(vec_values.begin(), vec_values.end()),
                                                            *std::max_element(vec_values.begin(), vec_values.end()));

    ui->plt_freq_domain->xAxis->setLabel("f"); // change it with your unit or just keep empty
    ui->plt_freq_domain->xAxis->setRange(vec_keys.constFirst(), vec_keys.constLast());

    ui->plt_freq_domain->replot();
}


text:
Q: avoid enumerating group names in d3.layout.stack()["group 1", "group 2"] I am having a really hard time understanding d3.layout.stack() when groups are not listed manually. In the below example, similar to what I've found in other questions, groups are listed in [] as "Apple", etc., but as far as I understand this has to be inputted manually. I am seeking a way to not have to manually input "Apple", "Blueberry", etc.
var dataset = d3.layout.stack()(["Apple", "Blueberry", "Lettuce", "Orange"].map(function(fruit) {
      return data.map(function(d) {
        return {x: d.orchard, y: +d[fruit]};
      });
    }));

I've tried inserting a line in my data object as below, called 'names':
[{names='Apple','Blueberry','Lettuce','Orange'}, {Apple=1.0, Orange=2.0, Lettuce=1.0, orchard=小明, Blueberry=1.0}, {Apple=1.0, Orange=1.0, Lettuce=1.0, orchard=小陈, Blueberry=1.0}, {Apple=1.0, Orange=1.0, Lettuce=1.0, orchard=小虎, Blueberry=1.0}, {Orange=1.0, Lettuce=1.0, orchard=小桃, Blueberry=1.0, Apple=1.0}]

Is there a way to code something similar to below?
var dataset = d3.layout.stack()([d3.keys(names)].map(function(fruit) {

Should I be focused more on inserting a unique list of names into my data object, or do so by parsing my data in my d3 code itself to accumulate a list of unique group names?
I am wondering, if the d3.keys logic makes sense, if it can be applied to the below context too, instead of enumerating each case:
legend.append("text")
         .attr("x", width + 5)
          .attr("y", 9)
          .attr("dy", ".35em")
          .style("text-anchor", "start")
              .text(function(d, i) {
                for(var j =0; j<4; j++){
                   switch (i) {

                      case j: return d3.keys[j]

//                switch (i) {
//
//                  case 0: return "orange"
//                  case 1: return "apple"
//                  case 2: return "blueberry"
//                  case 3: return "lettuce"

              }
              }
            });

A: I ended up just converting the entire graph to d3 v5. Below is some notes based off a lot of sources I looked at mixed with my own work:
Better practice for stacked bar is to use
  .data(d3.stack().keys(keys)(data))

where
 var keys = d3.keys(data[0]).filter(function(d){
          return d != "orchard";
        });

or in other words:
   var keys = d3.keys(data[0]).filter(d => d != "orchard")

This is useful for data that is pre-parsed in javascript. Say you have just columns in a csv:
var keys = csv.columns.slice(0);

is useful, but same philosophy for stacking applies.
Slight issue: if you have new categories arising later on in the data, i.e. a new fruit pineapple is part of data[1] but not data[0], key will not identify pineapple. It only responds to the data object of the first entry.
To not rely on data[1], data[0], etc., and "accumulate" keys for data[0], data[1], etc. while maintaining the same filter:
  var key = [];
  for(var i =0; i < d3.keys(data).length; i++){
     var joinin = d3.keys(data[i]).filter(d => d != "orchard")
     var key = key.concat(joinin)
//     console.log(key)
 }

There's most likely a better way of writing that code, but the explanation is:
If you wrote something like this you'd get keys for only one set of data:
  var key = d3.keys(data[2]).filter(function(d){
          return d != "orchard";
        });

If you wrote this you get the keys for each iteration of data:
  var key = [];
  for(var i =0; i < d3.keys(data).length; i++){
     var key = d3.keys(data[i]).filter(d => d != "orchard")
     console.log(key)
     key.push(key);
  }

So the trick is to use a for loop to get each iteration of data but concat that into one singular list, which has no repeats.
[EDIT] What if you wanted the value given to each key? Again, this is for a data structure like this, which is a little unconventional:
  data = [
              {0:
                {"Apple": 1}
                {"orchard": xx}
              }
              {1:
                {"Apple": 2}
                {"orchard": xx}
              }
           ]

You can use the below, where key will return ["Apple"], and key_values will return [1, 2]. Basically the filter d > 0 prevents any strings, so like names of orchards "xx". Does the same as filtering out orchards.
  var key = [];
  var key_values = [];
  for(var i =0; i < d3.keys(data).length; i++){
     var key_value = d3.entries(data[i]).map(d => d.value).filter(d => d > 0)
     var key_values = key_values.concat(key_value)
     var joinin = d3.keys(data[i]).filter(d => d != "orchard")
     var key = key.concat(joinin)
 }

(EDIT2) About the legend..
I just replaced my code with, and I know d3v5 can simplify the below(?),
 var legend = svg.selectAll(".legend")
  .data(color.domain())
  .enter()
  .append("g")
  .attr("class","legend")
  .attr("transform",function(d,i) {
    return "translate(1300," + i * 15 + ")";
  });

In my case input variables are discrete, like "Apple" etc., not  integers, so we use scaleOrdinal and just use "keys" for the domain. You don't really need to write that though, I think it defaults to the input list of discrete variables? Not sure why it works.
  var color =  d3.scaleOrdinal()
       .domain(keys)
    // .range (whatever you want)


text:
Q: How do I get a discriminated union case from a string? I have a discriminated union and I want to select a case based on a string (which is read from a JSON file). This is easy to do:
type MyDU = A | B
let str = "B"
let myDU : MyDU =
    match str with
    | "A" -> MyDU.A
    | "B" -> MyDU.B
    | _ -> failwith "whatever"
// val myDU : MyDU = B

However, sometimes there are many cases, which would require a lot of typing.
The Microsoft.FSharp.Reflection library allows me to get a UnionCaseInfo
 object:
open Microsoft.FSharp.Reflection
let myDUInfo : UnionCaseInfo =
    FSharpType.GetUnionCases(typeof<MyDU>)
    |> Array.find (fun x -> x.Name = str)
// val myDUInfo : UnionCaseInfo = MyDU.B

I would like to convert myDUInfo into a union case so as to get the same result as the code above relying on match, but without having to type the strings corresponding to all the cases.
Is this possible?

A: To instantiate a union case, use the FSharpValue.MakeUnion method. Here is a function that will instantiate a union case given its name:
let instantiate<'t> name =
    Reflection.FSharpType.GetUnionCases( typeof<'t> )
    |> Seq.tryFind (fun uc -> uc.Name = name)
    |> Option.map (fun uc -> Reflection.FSharpValue.MakeUnion( uc, [||] ) :?> 't)

Usage:
> type T = A | B | C
> instantiate<T> "A"

val it : T option = Some A

NOTE: this function assumes, but does not make sure, that the union case has no arguments. If you give it a case with arguments, it will crash:
> type T = A of int | B | C
> instantiate<T> "A"

System.Reflection.TargetParameterCountException: Parameter count mismatch.
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at FSI_0002.instantiate@5.Invoke(UnionCaseInfo uc) in c:\o\a.fsx:line 5
   at Microsoft.FSharp.Core.OptionModule.Map[T,TResult](FSharpFunc`2 mapping, FSharpOption`1 option)
   at <StartupCode$FSI_0006>.$FSI_0006.main@()
Stopped due to error

I leave resolution of this problem as an exercise for the reader (hint: use the UnionCase.GetFields method).


text:
Q: Why is my  link not working inside this floating ? I can't for the life of me figure out why a float:right  I have isn't showing hyperlinks properly. I was initially thinking it wasn't on the right z-index, but now I'm just confused. Is there a  that's blocking it somewhere?
The website address is www.oakland-rotary.org
I am referring to the purple vertical block at the top right of the website that starts off with "YOU ARE INVITED TO THE MAIN EVENT...". The text that is supposed to be hyperlinked is "CLICK HERE FOR INFO & TICKETS"
Here is the HTML code for that entire block area:

            YOU ARE INVITED TO

            THE MAIN EVENT

            [ OUR ANNUAL FUNDRAISER ]

            A MARDI GRAS PAR-TAY

            AT ROCKWELL WINERY

            IN ALAMEDA, CA

            March 1 from 6pm-10pm

            CLICK HERE FOR INFO & TICKETS

And here is the CSS for that area:
#rightcallout {
float:right;
display:block;
z-index:9999;
height:100%;
width:200px;
padding:25px;
color:#fff;
font-family:League Gothic;
font-size:24px;
text-align:center;
background: #552baa; /* Old browsers */
background: -moz-linear-gradient(top,  #552baa 0%, #5c2cb4 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#552baa), color-stop(100%,#5c2cb4)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #552baa 0%,#5c2cb4 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #552baa 0%,#5c2cb4 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #552baa 0%,#5c2cb4 100%); /* IE10+ */
background: linear-gradient(to bottom,  #552baa 0%,#5c2cb4 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#552baa', endColorstr='#5c2cb4',GradientType=0 ); /* IE6-9 */
border-left:1px dashed #fff;
}

Any help would be greatly appreciated! Thank you so much!!!

A: A this moment #rightcallout height it's bigger than available space.
I've change the font-size to auto... and content fits correctly.
#rightcallout {
float:right;
display:block;
z-index:9999;
height:100%;
width:200px;
padding:25px;
color:#fff;
font-family:League Gothic;
font-size:auto;  /* <<<-------- Modified*/
text-align:center;
background: #552baa; /* Old browsers */
background: -moz-linear-gradient(top,  #552baa 0%, #5c2cb4 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#552baa), color-stop(100%,#5c2cb4)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  #552baa 0%,#5c2cb4 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  #552baa 0%,#5c2cb4 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  #552baa 0%,#5c2cb4 100%); /* IE10+ */
background: linear-gradient(to bottom,  #552baa 0%,#5c2cb4 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#552baa', endColorstr='#5c2cb4',GradientType=0 ); /* IE6-9 */
border-left:1px dashed #fff;
}

For that link I made this:

CLICK HERE FOR INFO & TICKETS

I've tested in Chrome and works fine... hope this helps you.


text:
Q: WIN32 API PostMessage synchronization I am trying to remote control an application.
In particular I Try to send the function key F5 to notepad.exe.
notepad.exe on F5 usually reacts by pasting the actual time/date in it's edit area.
The code I have figure out so far:
/********************************************************************/

org = GetActiveWindow(); // get current active window

ShowWindow(w, SW_RESTORE); // do the switch to the notepad window

PostMessage(w, WM_KEYDOWN, VK_F5, 0); // send/post F5

Sleep(100); // need this to wait for the notepad action to complete

ShowWindow(org, SW_SHOW); // restore org window

/********************************************************************/

So far the code works more or less.
The problem that remains is how long will I have wait using Sleep(), how many milliseconds will be sufficient?
Waiting to short will switch back to the original window before notepad.exe has completed the F5 task.
notepad.exe will loose focus and the F5 command will get lost because only an focused notepad will process it.
It would be much nicer to use SendMessage() as this waits for completion
/********************************************************************/

SendMessage(w, WM_KEYDOWN, VK_F5, 0); // should sync on the completion of F5

/********************************************************************/

Unfortunately notepad.exe does not react on F5 when using SendMessage instead of PostMessage.
Is there a clean way to synchronize the desired task?
Note actually notepad.exe is just an example for a more complex remote control task.

A: In my experience, an app can choose to respond to WM_KEYUP only on some keys (WM_KEYDOWN may be too early,) so you should try SendMessage(w, WM_KEYUP...) after WM_KEYDOWN.


text:
Q: Apply EventListener to table instead of each cell. How? In the code below it works fine but i apply EventListener to each Cell in table in for loop instead i would like to apply just one EventListener to the table itself to change the background-color for selected Cell. How i can do that ?
let height, width, color, reset;
const error = document.querySelector('#error');
function makeGrid(event) {
    event.preventDefault();
    clrGrid();
    height = document.querySelector("#inputHeight").value;
    width = document.querySelector("#inputWidth").value;
    if (height > 50 || width > 50 || height < 1 || width < 1) {
        if (!error.classList.contains("error")) {
            error.classList.toggle("error");
            error.innerText = "the dimension has to be smaller than 50 and bigger than 0";
        }
    } else {
        error.innerText = "";
        error.classList.remove("error");
        for (let x = 0; x < height; x++) {
            const tRow = document.querySelector("#pixelCanvas").insertRow(x);

            for (let y = 0; y < width; y++) {
                const tCell = tRow.insertCell(y);
                tCell.addEventListener("click", fillSquare);
            }
        }
    }
}

// Apply Color to Cells
color = document.querySelector('#colorPicker');
function fillSquare () {
    this.setAttribute("style", `background-color: ${color.value}`);
}

// Clear Canvas Grid
canvas = document.querySelector("#pixelCanvas");
function clrGrid() {
    error.innerText = "";
    error.classList.remove("error");
    while (canvas.firstChild){
        canvas.removeChild(canvas.firstChild);
   }
}

A: You can attach the click listener on the table and access the cell using event.target.
Bellow you can find little demonstration on how to use it.

document.getElementById('table').addEventListener('click', function(event) {
  const target = event.target;

  if (target.tagName.toLowerCase() === 'td') {
    target.style.background = 'blue';
  }
});

    Content
    Content

    Content
    Content

A: Use event delegation. Set the event listener on the table and then ask whether the event target (element that was the source of the event) is cell td element. If it is, then use event target again to modify the cell as you want (in such case event.target will be the corresponding cell element).
You can see it here.

const table = document.querySelector('table');
table.addEventListener('click', event => {
  if (event.target.nodeName === 'TD') {
    event.target.style.background = 'red';
  }
});

    cell1
    cell2

When you click on a cell, its background color will change to red even though there is only on listener assigned to its parent table.
In your case you should remove line
tCell.addEventListener("click", fillSquare);

change the fillSquare function so that it takes argument (element target)
function fillSquare (element) {
  element.setAttribute("style", `background-color: ${color.value}`);
}

and add event listener to the table like this
const table = document.querySelector('select-parent-table');
table.addEventListener('click', event => {
  if (event.target.nodeName === 'TD') {
    fillSquare(event.target);
  }
});

A: When you click on the table, first check if it's a td then change the background color to whatever you wish.

const table = document.getElementById("table");

table.addEventListener("click", (e)=>{
 const element = e.target;
 if(element.tagName === "TD"){
  element.style.backgroundColor = "red"
 }
});

      1
      2

      3
      4


text:
Q: How to read response or output from a UIWebView in swift 4.0? And how many different ways are there for stringByEvaluatingJavaScript(from:) I'm opening an URL in UIWbView, where user can enter OTP and after submitting it'll provide following response:
{"success":true,""message":payment success"}
I want that if the value of success is true, I'll remove UIWebView from superview.
I don't know how to read the response from UIWebView.

A: I tried number of strings as parameter in stringByEvaluatingJavaScript(from:) but finally I figure it out by passing "document.body.innerHTML".
You can use "document.getElementById('someElement').innerText", if you want to read data from HTML elements/components like text fields, etc.
func webViewDidFinishLoad(_ webView: UIWebView) {
        print("WebView did finish load...")
        if !webView.isLoading {
            Loader.hideLoading()
        }
        let str = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML")
        if (str?.contains("\"success\":true"))! {
            print("Success is true")
            self.viewForWebView.removeFromSuperview()
        }else {
            print("Success is false or not found")
        }
    }


text:
Q: Displaying Dynamic placeholder content on Textbox in ReactJS I wanted to place a dynamic content in placeholder inside my textbox component in React. I have declared a function which returns the placeholder, passing the value as argument. I am hardcoding the args here in the below code for clarity perspective.
I am always getting an empty parameter in my function. If someone could let me know what i am doing wrong here.
Here is my Input Component
<SocialInput
   value={data.name}
   onChange={onChangeInput}
   error={validationError}
   placeholder={ () => { CustomPlaceholder("facebook") }}
/>

Function which return placeholder.
const CustomPlaceholder = (name) => {
        let placeholderContent;
        switch(name) {
            case "facebook":
                placeholderContent = "https://www.facebook.com/your-username";
                return placeholderContent;
            case "email":
                placeholderContent = "example@domain.com";
                return placeholderContent;
            case "instagram":
                placeholderContent = "https://www.instagram.com/your-username"
                return placeholderContent;
            case "linkedin":
                placeholderContent = "https://www.linkedin.com/your-username";
                return placeholderContent;
            case "pinterest":
                placeholderContent = "https://www.pinterest.com/your-username";
                return placeholderContent;
            case "skype":
                placeholderContent = "https://skype/your-username";
                return placeholderContent;
            case "twitter":
                placeholderContent = "https://twitter.com/your-username";
                return placeholderContent;
            case "whatsapp":
                placeholderContent = "(Country-code)-Mobile number";
                return placeholderContent;
            case "youtube":
                placeholderContent = "https://www.youtube.com/channel/Channel link";
                return placeholderContent;
            case "blog":
                placeholderContent = "domain.com";
                return placeholderContent;
            case "other":
                placeholderContent = "Social URL";
                return placeholderContent;
                default: "Social URL";
        }
    }

And finally my input textbox. Here i am getting function as placeholder props:
<input
   type="text"
   onChange={onChange}
   value={value}
   className="social-input"
   placeholder={placeholder}
   onBlur={(e) => e.target.placeholder = placeholder}
   onFocus={(e) => e.target.placeholder = ""}
 />

A: Here placeholder={ () => { CustomPlaceholder("facebook") }} it call the function but returns undefined, make it return the value:placeholder={() => CustomPlaceholder("facebook")},
and in your component call the received function: placeholder={placeholder()} because it's a function

or you can leave your component as it is and pass the generated placeholder string instead:
placeholder={CustomPlaceholder("facebook")}


text:
Q: New Review Task - Find posts that might need editing I have an idea that I wanted to run past you guys.
What do you think to a new Review task or similar tool be added to SO, that identifies posts that might need editing?
Something like this could be implemented fairly easily, e.g. by checking for the existence of things like lots of  i 's (for example).
I see a lot of posts like i am struggling with... i have tried... i think it might be.
Of course, this is just a simple example, but such a tool could also check for other common things that might signal a potential edit requirement.
What do you guys think? Is this something that might be useful?
It would certainly increase the overall quality of posts on the site anyway.
Also, people would be incentivised by a) the +2, b) progress towards Copy Editor, and c) the additional Custodian, Reviewer and Steward badges.

A: You've suggested a queue for posts that fail a heuristic test designed to predict quality. While the Low Quality Posts review queue is not quite the same as what you've suggested--in particular, it generally does not contain longer posts where most of the post is good quality--there's enough overlap that a "needs editing" queue is likely not necessary.
You need 2000 reputation to review Low Quality Posts. For answers, this review queue offers Looks Good, Recommend Deletion (or Delete if you have enough reputation), Edit, and Skip options. For questions, it offers Looks Good, Close (and I think Recommend Closing if you don't have 3k rep to close), Edit, and Skip.
The heuristics the system uses to identify posts as likely being of low quality aren't necessarily the same as the ones you'd use to identify a post as needing editing. A post that is good quality overall but has little pockets of low quality is probably one of the few kinds of posts the system could automatically identifcy as likely needing editing, and these would usually not be "low quality" enough to enter the Low Quality Posts review queue. Therefore, there may be some merit to this feature request.
However, unless the heuristics would have to be highly sophisticated, it's probably possible to use the Data Explorer to find posts that need editing. And this is something anyone (who can write or find an appropriate SQL query) can do, with any amount of reputation (or even without an account). This is not perfect, of course, as the data are not updated immediately upon creation.


text:
Q: Time coordinate inside black hole horizon I am new to physics and was trying to learn more especially about general relativity.
The Schwarzschild metric, changes the sign of the time and radial parts of the metric once we cross the event horizon. Someone on stack exchange had noted that as a result inside the horizon the decrease in radius is the direction of increasing time.
My question is if radius (i.e space) becomes timelike due to change in metric sign, then does time also become spacelike. I mean can then inside the horizon one move freely in time?
NOTE: As far as my understanding of the linked question goes, that question is about cosmology of interiro of ablack hole (it asks about a spacetime originating form blackhole horizon). My question i think is different, its really more on the lines of time-travel.Since the signature of the time corrdinate is spacelike, it should behave like space and we should be able to move in it in the backward direction as we can in space.
Some say that it is a coordinate artifact, but I think the other coordinates dont tend to have the physical interpretation of time.(I may have understood it incorrectly)

A: Yes, the "time" coordinate of Schwarzschild coordinates is spacelike inside the horizon (meaning a path of constant radial coordinate and varying time coordinate is a spacelike curve). But this is just an artifact of the coordinate system chosen, with no particular physical significance; in special relativity one could likewise design a non-inertial coordinate system where some coordinate switched from being timelike to being spacelike past some arbitrarily-chosen boundary. And if you use a coordinate system called Kruskal-Szekeres coordinates on the Schwarzschild black hole spacetime, rather than Schwarzschild coordinates, then the radial coordinate is spacelike both inside and outside the horizon, and the time coordinate is timelike both inside and outside (another nice feature of these coordinates is that all light rays moving in a radial direction are represented as straight lines 45 degrees from the vertical, just as in inertial frames in SR, so the light cone structure is obvious).


text:
Q: symfony 2 security redirect after login I have the next security.yml:
security:
    encoders:
        Test\BackEndBundle\Entity\User:
            algorithm: sha512
            encode-as-base64: true
            iterations: 10

    providers:
        main:
            entity: { class: TestBackEndBundle:User, property: username }

    firewalls:
        main:
            pattern: /.*
            form_login:
                check_path: _security_check
                login_path: _security_login
                default_target_path: homepage
            logout: true
            security: true
            anonymous: true

    access_control:
        - { path: ^/service, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: /.*, roles: {ROLE_PARTNER, ROLE_ADMIN} }

And the next routing:
homepage:
    pattern:  /
    defaults: { _controller: TestBackEndBundle:Default:index }

_security_login:
    pattern:  /login
    defaults: { _controller: TestBackEndBundle:Security:login }

_security_check:
    pattern:  /login_check

_security_logout:
    pattern:  /logout

Authentication works well, instead of redirection after login. Application redirects to /_wdt/5044c6f2a329c. How can I make redirect to the home page? Thanks.

A: *

*You have to create a success_handler implementing the AuthenticationSuccessHandlerInterface

*Then you have to declare it as a service (in services.xml or services.yml)

*And add it to your security configuration.

A: The solution is to unprotect your _wdt route.
You get this behaviour because your _wdt route is protected.
When a page loads the toolbar from the _wdt route, it triggers the login. Your login form will try to redirect back to the route that triggered the login: In this case _wdt.
Add this to your access_control in security.yml
 - { path: ^/_wdt, roles: 'IS_AUTHENTICATED_ANONYMOUSLY' }

This will let the toolbar work in both protected and unprotected pages, and if the page is protected, it will be the page the one who triggers the login form = it will work as expected.

A: Also, you can set always_use_default_target_path: true and then your default_target_path will work as you expect. See details.


text:
Q: Elm 0.19: How to obtain request body when receiving BadStatus with elm/http 2.0.0 elm/http 1.0.0 defined Http.Error as
type Error
    = BadUrl String
    | Timeout
    | NetworkError
    | BadStatus (Response String)
    | BadPayload String (Response String)

but 2.0.0 changed it to
type Error
    = BadUrl String
    | Timeout
    | NetworkError
    | BadStatus Int
    | BadBody String

When receiving BadStatus I cannot obtain the body of the request, only the status code. In the docs Evan suggests a solution for this, but I don't understand how to make it work.
If we defined our own expectJson similar to
expectJson : (Result Http.Error a -> msg) -> D.Decoder a -> Expect msg
expectJson toMsg decoder =
  expectStringResponse toMsg <|
    \response ->
      case response of
        Http.BadStatus_ metadata body ->
          Err (Http.BadStatus metadata.statusCode)
        ...

Then we have access to the metadata and body, but how do I use them? Should I define my own myBadStatus and return that instead?
Http.BadStatus_ metadata body ->
  Err (myBadStatus metadata.statusCode body)

Would this work?
What I need is to convert the following code:
myErrorMessage : Http.Error -> String
myErrorMessage error =
    case error of
        Http.BadStatus response ->
            case Decode.decodeString myErrorDecoder response.body of
                Ok err ->
                    err.message
                Err e ->
                    "Failed to parse JSON response."
        ...

Thank you.

A: Edit 22/4/2019: I updated this answer for version 2.0+ of http-extras which has some API changes. Thanks to Berend de Boer for pointing this out!
The answer below gives a solution using a package I wrote (as per request), but you don't have to use the package! I wrote an entire article on how to extract detailed information from an HTTP response, it includes multiple Ellie examples that don't require the package, as well as an example that uses the package.

As Francesco mentioned, I created a package for exactly this purpose, using a similar approach described in the question: https://package.elm-lang.org/packages/jzxhuang/http-extras/latest/.
Specifically, the module to use Http.Detailed. It defines an Error type that keeps the original body around on error:
type Error body
    = BadUrl String
    | Timeout
    | NetworkError
    | BadStatus Metadata body Int
    | BadBody Metadata body String

Make a request like so:
type Msg
    = MyAPIResponse (Result (Http.Detailed.Error String) ( Http.Metadata, String ))

sendRequest : Cmd Msg
sendRequest =
    Http.get
        { url = "/myapi"
        , expect = Http.Detailed.expectString MyAPIResponse

In your update, handle the result including decoding the body when it is BadStatus:
update msg model =
    case msg of
        MyAPIResponse httpResponse ->
            case httpResponse of
                Ok ( metadata, respBody ) ->
                    -- Do something with the metadata if you need! i.e. access a header

                Err error ->
                    case error of
                        Http.Detailed.BadStatus metadata body statusCode ->
                            -- Try to decode the body the body here...

                        ...

        ...

Thanks the Francisco for reaching out to me about this, hopefully this answer helps anyone who faces the same problem as OP.


text:
Q: I would like to get clarified between below two constructs? loop do
  token = Devise.friendly_token
  break token unless User.where(authentication_token: token).first
end

loop do
  token = Devise.friendly_token
  break token unless self.class.unscoped.where(authentication_token: token).first
end

I'm a newbie to ruby and it's rails so, hoping you guys will not downvote my question, since I google around but could not understand between differences.

A: The difference is User.where vs self.class.unscoped. They do the same thing essentially.
In the first construct the class name User is hardcoded into the expression. So the construct will only call where on the User class. And the User class has to respond to the where message; it must have a class method called where.
In the second construct the class name is derived. In Ruby, self refers to the instance you are currently working within. If you call self.class inside an instance, you get the class name of the instance. For example:
apple = Apple.new
puts apple.class.name
# => "Apple"

So the second construct can be used inside any class.
The last difference is the unscoped call. This is an ActiveRecord method that removes any defined scopes on a class. Think of it like "remove any filters" before finding records where authentication_token equals token.
I believe unscoped was deprecated.

A: Given you are in the class User e.g. in user.rb self.class maps to User. So the difference is actually another scope added to the where clause:
class User
  def some_method_to_find_token
    loop do
      token = Devise.friendly_token
      break token unless User.where(authentication_token: token).first
    end
  end

  def some_other_method_to_find_token
    loop do
      token = Devise.friendly_token
      break token unless User.unscoped.where(authentication_token: token).first
    end
  end
end

I guess the intention is to create a new token if no token exists. And there probably is a default scope in place which probably filters out deleted_users. Not a really good coding example actually. The first loop is unnecessary as you always have to check if this token is set to a deleted user anyways.
class User
  def new_untaken_token
    loop do
      token = Devise.friendly_token
      break token unless User.unscoped.exists?(authentication_token: token)
    end
  end
end

This could also be written recursivly:
class User
  def new_untaken_token
    token = Devise.friendly_token                         # Create a new token
    if User.unscoped.exists?(authentication_token: token) # check if it exists
      new_untaken_token                                   # find another one
    else
      token                                               # use token
    end
  end
end


text:
Q: Show that a path lies on a quadric surface We have the path of a particle determined as $\vec{x}(t)=(a\cos(t), b\sin(t), ct)$, $a, b, c > 0$, $t$ is time. If I want to show that the path lies on a quadric surface, do I have to derive a definite equation of the quadric surface? Or can I go about it implicitly?
I can show that the path is an oval: $(\frac{x}{a})^2 + (\frac{y}{b})^2 = 1$; and that $z=ct$, which implies that the particle "draws" a spiral oval as time goes.
I'm, however, wondering if we can show by an explicit formula that the oval spiral lies on an oval surface. My guess is no.

A: The parametrization is sufficient to say that you are extruding an ellipse and on that prism you are going up a helical a path. The surface is an elliptic cylinder as distinguished from the circular cylinder.
It need not lie on a quadric surfaces alone. A rigid helix can be drawn on an infinite set of blown in or blown out surfaces.
Mathematical formulation may be possible, but involved. I for one like to avoid math if a physical situation can be imagined.
If a wire-frame model of the helix is made and somehow made to enclose space,  dipped in a soap solution it spans a minimal surface. By putting in or taking our air into the inner space several surfaces of positive and negative Gauss curvature can be created as grooves or humps..
Unless a property of the surface is mentioned, a curve  cannot determine a surface on which it mounts.


text:
Q: Splitting BigIntegers digits I am trying to split a big integer's digits. Let me be a bit more specific. I am using the Fibonacci sequence to generate a big integer, now using this algorithm I need to loop until I find a BigInteger where the first 9 digits and the last 9 digits are pandigital. Only problem is the amount I have to loop is 300K (now that BigInteger is going to be so huge).
I have tried converting the BigInteger into a string, and then using "substring(begin, end)." But, that is so slow, it took nearly 28 minutes just to do 100K indexes.
There is a mathematical solution for this, but I am not completely sure what it is, if someone could lead me within the right direction much would be appreciated. Note: I am not asking for the answer directly, just a step towards finding the right answer.
Here is my code just in case you're wondering:
import java.math.BigInteger;

public class Main {

    public static void main(String...strings)
    {
        long timeStart = System.currentTimeMillis();
        fib(300_000);
        long timeEnd = System.currentTimeMillis();
        System.out.println("Finished processing, time: " + (timeEnd - timeStart) + " milliseconds.");
    }

    public static BigInteger fib(int n)
    {
        BigInteger prev1 = BigInteger.valueOf(0), prev2 = BigInteger.valueOf(1);
        for (int i = 0; i < n; i++)
        {
            BigInteger savePrev1 = prev1;
            prev1 = prev2;
            prev2 = savePrev1.add(prev2);
        }
        return prev1;
    }

    static BigInteger[] pows = new BigInteger[16];

    static {
        for (int i = 0; i < 16; i++) {
            pows[i] = BigInteger.TEN.pow(i);
        }
    }

    static boolean isPanDigital(BigInteger n) {
         if (!n.remainder(BigInteger.valueOf(9)).equals(BigInteger.ZERO)) {
           return false;
        }
        boolean[] foundDigits = new boolean[9];

        boolean isPanDigital = true;
        for (int i = 1; i <= 9; i++) {
            BigInteger digit = n.remainder(pows[i]).divide(pows[i - 1]);
            for (int j = 0; j < foundDigits.length; j++) {
                if (digit.equals(BigInteger.valueOf(j + 1)) && !foundDigits[j]) {
                    foundDigits[j] = true;
                }
            }
        }

        for (int i = 0; i < 9; i++) {
            isPanDigital = isPanDigital && foundDigits[i];
        }

        return isPanDigital;
    }
}

Updated, managed to figure out how to generate the first 9 digits (and it doesn't seem to be too slow). But, I am having an issue generating the last 9 digits.
import java.math.BigInteger;

public class Main {

    public static void main(String...strings)
    {
        long timeStart = System.currentTimeMillis();
        fib(300_000);
        long timeEnd = System.currentTimeMillis();
        System.out.println("Finished processing, time: " + (timeEnd - timeStart) + " milliseconds.");
    }

    public static BigInteger fib(int n)
    {
        BigInteger prev1 = BigInteger.valueOf(0), prev2 = BigInteger.valueOf(1);
        for (int i = 0; i < n; i++)
        {
            if (prev1.toString().length() > 19)
            {
                String leading9Digits = leading9Digits(prev1);
                if (isPanDigital(BigInteger.valueOf(Integer.valueOf(leading9Digits))))
                {
                    System.out.println("Solved at index: " + i);
                    break;
                }
            }
            BigInteger savePrev1 = prev1;
            prev1 = prev2;
            prev2 = savePrev1.add(prev2);
        }
        return prev1;
    }

    public static String leading9Digits(BigInteger x) {
        int log10 = (x.bitLength() - 1) * 3 / 10;
        x = x.divide(BigInteger.TEN.pow(Math.max(log10 + 1 - 9, 0)));
        return x.toString().substring(0, 9);
    }

    static BigInteger[] pows = new BigInteger[16];

    static {
        for (int i = 0; i < 16; i++) {
            pows[i] = BigInteger.TEN.pow(i);
        }
    }

    static boolean isPanDigital(BigInteger n) {
         if (!n.remainder(BigInteger.valueOf(9)).equals(BigInteger.ZERO)) {
           return false;
        }
        boolean[] foundDigits = new boolean[9];

        boolean isPanDigital = true;
        for (int i = 1; i <= 9; i++) {
            BigInteger digit = n.remainder(pows[i]).divide(pows[i - 1]);
            for (int j = 0; j < foundDigits.length; j++) {
                if (digit.equals(BigInteger.valueOf(j + 1)) && !foundDigits[j]) {
                    foundDigits[j] = true;
                }
            }
        }

        for (int i = 0; i < 9; i++) {
            isPanDigital = isPanDigital && foundDigits[i];
        }

        return isPanDigital;
    }
}

A: Okay, I made a number of optimizations to your code.

*

*Your leading9Digits method should not return a String, it should return a number. Allow other parts of your code to turn it into a string if they prefer.

*Calling BigInteger.pow() every time the code loops is a waste. You can precalculate all these powers of 10 and store them in an array.

*You don't have to use an inner loop to check for pandigitalness. If you ever have to increment a cell in your boolean array twice, then it's not pandigital. Additionally, you can early exit on a 0.

*Calculating trailing9digits is easy using mod 1000000000

*You can pre-create your constants and store them rather than creating them each time. Your way is fine for primitives but not objects.

Note, I tried using a String instead of remainders, they worked out to be about the same. I included both in your code.
And, finally, the correct answer is not in the first 300,000; it's about 329,000. And it takes about 29 seconds to run on my machine.
import java.math.BigInteger;

public class Main {
    private static final BigInteger NINE = BigInteger.valueOf(9);
    private static final BigInteger BILLION = BigInteger.valueOf(1000000000);
    private static final double log10_2 = Math.log10(2);
    private static final double CORRECTION = 9d;
    private static final int ARRAY_SIZE = 131072;

    static BigInteger[] pows = new BigInteger[ARRAY_SIZE];

    static {
        pows[0] = BigInteger.ONE;
        for (int i = 1; i < ARRAY_SIZE; i++) {
            pows[i] = pows[i - 1].multiply(BigInteger.TEN);
        }
    }

    public static void main(String... strings) {
        long timeStart = System.currentTimeMillis();
        fib(500_000);
        long timeEnd = System.currentTimeMillis();
        System.out.println("Finished processing, time: "
                + (timeEnd - timeStart) + " milliseconds.");
    }

    public static BigInteger fib(int n) {
        BigInteger prev1 = BigInteger.valueOf(0), prev2 = BigInteger.valueOf(1);
        for (int i = 0; i < n; i++) {
            if (prev1.bitLength() > 30) {
                if (isDualPanDigital(prev1)) {
                    System.out.println("Solved at index: " + i);
                    break;
                }
            }
            BigInteger savePrev1 = prev1;
            prev1 = prev2;
            prev2 = savePrev1.add(prev2);
        }
        return prev1;
    }

    public static BigInteger leading9Digits(BigInteger x) {
        int dividePower = (int) (x.bitLength() * log10_2 - CORRECTION);
        BigInteger y = x.divide(pows[dividePower]);
        if (y.compareTo(BILLION) != -1) y = y.divide(BigInteger.TEN);
        return y;
    }

    public static BigInteger trailing9Digits(BigInteger x) {
        return x.mod(BILLION);
    }

    static boolean isDualPanDigital(BigInteger n) {
        boolean leading = isPanDigital(leading9Digits(n));
        boolean trailing = isPanDigital(trailing9Digits(n));

        if (leading && trailing) {
            System.out.format("leadingDigits: %s, trailingDigits: %s%n",
                    leading9Digits(n), trailing9Digits(n));
        }
        return leading && trailing;
    }

    static boolean isPanDigital(BigInteger n) {
        if (!n.remainder(NINE).equals(BigInteger.ZERO)) {
            return false;
        }

        return isPanDigitalString(n);
    }

    private static boolean isPanDigitalMath(BigInteger n) {
        boolean[] foundDigits = new boolean[10];

        for (int i = 1; i <= 9; i++) {
            int digit = n.remainder(pows[i]).divide(pows[i - 1]).intValue();
            if (digit == 0)
                return false;
            if (foundDigits[digit - 1])
                return false;
            else
                foundDigits[digit - 1] = true;
        }

        return true;
    }

    private static boolean isPanDigitalString(BigInteger n) {
        boolean[] foundDigits = new boolean[9];

        String s = n.toString();
        if (s.length() < 9) {
            return false;
        }

        for (int i = 0; i < 9; i++) {
            int digit = s.charAt(i) - '1';
            if (digit == -1 || foundDigits[digit])
                return false;
            foundDigits[digit] = true;
        }

        return true;
    }
}


text:
Q: Mingw produces x86 program which only successfully runs as Administrator- x64 and VS(x86 and x64) versions fine I was taking a look at this Github project: https://github.com/LloydLabs/delete-self-poc
This project uses the SetFileInformationByHandle API (https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileinformationbyhandle) in a somewhat creative way to allow the deletion from disk of a locked file.  I am attempting to implement this as part of a larger program, however I have ran into an issue when compiling for x86.  I use mingw-w64 on a debian machine to compile my program and when doing compatibility checks for x86, I found a very strange issue.
#include "main.h"

static
HANDLE
ds_open_handle(
    PWCHAR pwPath
)
{
    return CreateFileW(pwPath, DELETE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
}

static
BOOL
ds_rename_handle(
    HANDLE hHandle
)
{
    FILE_RENAME_INFO fRename;
    RtlSecureZeroMemory(&fRename, sizeof(fRename));

    // set our FileNameLength and FileName to DS_STREAM_RENAME
    LPWSTR lpwStream = DS_STREAM_RENAME;
    fRename.FileNameLength = sizeof(lpwStream);
    RtlCopyMemory(fRename.FileName, lpwStream, sizeof(lpwStream));

    return SetFileInformationByHandle(hHandle, FileRenameInfo, &fRename, sizeof(fRename) + sizeof(lpwStream));
}

static
BOOL
ds_deposite_handle(
    HANDLE hHandle
)
{
    // set FILE_DISPOSITION_INFO::DeleteFile to TRUE
    FILE_DISPOSITION_INFO fDelete;
    RtlSecureZeroMemory(&fDelete, sizeof(fDelete));

    fDelete.DeleteFile = TRUE;

    return SetFileInformationByHandle(hHandle, FileDispositionInfo, &fDelete, sizeof(fDelete));
}

int
main(
    int argc,
    char** argv
)
{
    WCHAR wcPath[MAX_PATH + 1];
    RtlSecureZeroMemory(wcPath, sizeof(wcPath));

    // get the path to the current running process ctx
    if (GetModuleFileNameW(NULL, wcPath, MAX_PATH) == 0)
    {
        DS_DEBUG_LOG(L"failed to get the current module handle");
        return 0;
    }

    HANDLE hCurrent = ds_open_handle(wcPath);
    if (hCurrent == INVALID_HANDLE_VALUE)
    {
        DS_DEBUG_LOG(L"failed to acquire handle to current running process");
        return 0;
    }

    // rename the associated HANDLE's file name
    DS_DEBUG_LOG(L"attempting to rename file name");
    if (!ds_rename_handle(hCurrent))
    {
        DS_DEBUG_LOG(L"failed to rename to stream");
        return 0;
    }

    DS_DEBUG_LOG(L"successfully renamed file primary :$DATA ADS to specified stream, closing initial handle");
    CloseHandle(hCurrent);

    // open another handle, trigger deletion on close
    hCurrent = ds_open_handle(wcPath);
    if (hCurrent == INVALID_HANDLE_VALUE)
    {
        DS_DEBUG_LOG(L"failed to reopen current module");
        return 0;
    }

    if (!ds_deposite_handle(hCurrent))
    {
        DS_DEBUG_LOG(L"failed to set delete deposition");
        return 0;
    }

    // trigger the deletion deposition on hCurrent
    DS_DEBUG_LOG(L"closing handle to trigger deletion deposition");
    CloseHandle(hCurrent);

    // verify we've been deleted
    if (PathFileExistsW(wcPath))
    {
        DS_DEBUG_LOG(L"failed to delete copy, file still exists");
        return 0;
    }

    DS_DEBUG_LOG(L"successfully deleted self from disk");
    return 1;
}

When compiling the base code found in the linked repository (and shown above) as x86, attempting to run the program fails at the SetFileInformationByHandle call in the ds_rename_handle function. Calling GetLastError() returns 123:
ERROR_INVALID_NAME

123 (0x7B)

The filename, directory name, or volume label syntax is incorrect.

The very bizarre part is that the program succeeds when ran from an Administrator prompt.  Even stranger, compiling the same code for x64 works both in a normal and an Administrator prompt.
As a sanity check I copied the code verbatim over to VS2019 and compiled there, and the resulting x86 program was able to run without Administrator privileges.
The only changes to the source code made on the debian system were made in the header file:
#pragma once

#pragma comment(lib, "Shlwapi.lib")

#include <Windows.h>
#include <shlwapi.h>
#include <stdio.h>
#include <stdlib.h>

#define DS_STREAM_RENAME L":wtfbbq"
#define DS_DEBUG_LOG(msg) wprintf(L"[LOG] - %s\n", msg)

Where <Windows.h> was changed to <windows.h> and the DS_DEBUG_LOG line changed to %ls so that the entire log message would print.
The GCC command used to compile for x86 was:
i686-w64-mingw32-gcc main.c -o delete32.exe -s -DUNICODE -Os -lshlwapi

I have tried removing all switches and compiling and it still fails.
As a note, the shlwapi library is only required for the very last call in main(), PathFileExistsW.  I have commented out that portion and removed shlwapi from imports and from the gcc command to no effect.
The x64 gcc command which succeeded was:
x86_64-w64-mingw32-gcc main.c -o delete32.exe -s -DUNICODE -Os -lshlwapi

In the issues tab of the github repo there are some mentions of errors in the code which I have looked at separately.  However I would desperately like to know why mingw is causing an issue with the 32 bit version of this program.  Unfortunately "just compile with VS" isn't an option, as I use a program to generate and compile the program that this bit of code will be part of on my linux machine.
Thanks for any insight.

A: RtlCopyMemory(fRename.FileName, lpwStream, sizeof(lpwStream)); writes 4 or 8 bytes into a 2 byte buffer! Who knows where the remaining bytes are going, the program behavior is probably undefined.
The concept of deleting a running exe like this might work but the code indicates that the author does not have a full understanding of Windows and C. You are better off rewriting it from scratch...
Edit:
After playing with your uploaded files I can with confidence say that it is the lack of a application manifest that causes it to fail when it is not elevated. Your vc file has a requestedExecutionLevel element which gives it Vista operating system context. If you remove the manifest resource in the vc exe it stops working. If you add a manifest to the mingw exe it starts working.

A: the ds_rename_handle function is wrong implemented.
the FILE_RENAME_INFO is variable size structure.
as result declaration
FILE_RENAME_INFO fRename;

almost always wrong (it will ok only if FileName containing 1 or 2 symbols)
really we need first calculate FileNameLength and then allocate PFILE_RENAME_INFO  based on this
as example:
ULONG FileNameLength = (ULONG)wcslen(DS_STREAM_RENAME) * sizeof(WCHAR);

ULONG dwBufferSize = FIELD_OFFSET(FILE_RENAME_INFO, FileName) + FileNameLength;

PFILE_RENAME_INFORMATION fRename = (PFILE_RENAME_INFORMATION)alloca(dwBufferSize);

so complete code for ds_rename_handle can be next:
ULONG ds_rename_handle(HANDLE hHandle, PCWSTR DS_STREAM_RENAME)
{
    ULONG FileNameLength = (ULONG)wcslen(DS_STREAM_RENAME) * sizeof(WCHAR);

    ULONG dwBufferSize = FIELD_OFFSET(FILE_RENAME_INFO, FileName) + FileNameLength;

    PFILE_RENAME_INFO fRename = (PFILE_RENAME_INFO)alloca(dwBufferSize);

    fRename->ReplaceIfExists = TRUE;
    fRename->RootDirectory = 0;
    fRename->FileNameLength = FileNameLength;
    memcpy(fRename->FileName, DS_STREAM_RENAME, FileNameLength);

    return SetFileInformationByHandle(hHandle, FileRenameInfo,
        fRename, dwBufferSize) ? NOERROR : GetLastError();
}

but documentation of FILE_RENAME_INFO is very bad. unclear - in what form - full pathname, file name or a relative pathname - must be FileName ?!
from my research - it must be full pathname only (not  file name) or begin with a colon : ( The new name for the stream )
much more better use NtSetInformationFile with FileRenameInformation
compare description of FILE_RENAME_INFORMATION structure with FILE_RENAME_INFO !
here exist detailed description - in what form FileName it should be.
so i always use
NTSTATUS ds_rename_handle_nt(HANDLE hHandle, PCWSTR DS_STREAM_RENAME)
{
    ULONG FileNameLength = (ULONG)wcslen(DS_STREAM_RENAME) * sizeof(WCHAR);

    ULONG dwBufferSize = FIELD_OFFSET(FILE_RENAME_INFO, FileName) + FileNameLength;

    PFILE_RENAME_INFORMATION fRename = (PFILE_RENAME_INFORMATION)alloca(dwBufferSize);

    fRename->ReplaceIfExists = TRUE;
    fRename->RootDirectory = 0;
    fRename->FileNameLength = FileNameLength;
    memcpy(fRename->FileName, DS_STREAM_RENAME, FileNameLength);

    IO_STATUS_BLOCK iosb;
    return NtSetInformationFile(
        hHandle, &iosb, fRename, dwBufferSize, FileRenameInformation);
}


text:
Q: PCI Express - Clarification about BAR, Memory addressing and physical memory I'm an absolute beginner starting to understand the PCI Express protocol and I need some clarifications about its mechanics.
I understood that a PCI Express endpoint device may have some memory BAR mapped in the system memory (is it always RAM the system memory we are talking about?). I need to understand what happens when I send from the CPU to the device (A) a memory read request, addressing a certain memory address (first memory BAR, offset 0).
Let's assume that my device doesn't have any in-device memory.
The root complex on behalf of CPU creates the TLP and forwards it to device (A) because the memory address of destination is assigned to (A).
A receives the TLP, unpacks it, and creates a completion TLP containing data coming from its internal application logic.
Now the TLP travels backwards to the Root Complex that unpacks it, gathers the interesting data and gives it back to the the CPU.
What is the system memory role during this communication? None?
Does the root complex communicate (in this case) with the physical memory of the system, other than sending and receiving packets to/from the endpoint?
To some people it may seem a silly question but for me this is crucial to understand the connection between the physical memory and the memory address BARs assigned to each PCI Express device.

A: When a CPU talks to a memory address, it isn't RAM that has to respond.  It can be an I/O device.  You can actually think of RAM as a "specialized memory-mapped I/O device" whose job is just to save and give back data, although with today's modern CPUs that have caching and such, it's not physically straightforward.
I am not too keen in the low level details of PCIe, but you seem to be wondering how the PCIe bus itself communicates with the CPU.  It does so like anything else that communicates with the CPU:

*

*Memory mapping - i.e. a device is "mapped" where reads and writes to a range of addresses don't go to RAM, but a device or controller.

*DMA - an external device or controller reads/writes a section of RAM, without the CPU being involved at all.

*I/O ports - this is just another address space (a feature of the Intel x86 family of CPUs) that has historically been dedicated to I/O devices.  You'll never find RAM here, but it works like memory mapping.  The main difference between I/O ports and memory mapping is that I/O port instructions always work serially, no "out of order" or "reordering" of operations will happen here as opposed to the CPU attempting to do that with accesses to main memory.

*IRQs - an external device sends an interrupt to the CPU

The BARs and such are "mapped" into memory, and take the place of any RAM that may be "under" it.  With the MMU I believe it's possible to "remap" the RAM beneath it to a different physical address.


text:
Q: req object in passport.authenticate I am using passportjs for authentication on my server. I am using the following code:
exports.auth = function(req, res, next){
  passport.authenticate('bearer', { session: false })(req, res, next);
};

passport.use(new BearerStrategy(
  function(token, done) {
    User.findOne({ token: token }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false);
      }
      return done(null, user, { scope: 'read' });
    });
  }
));

Is there a way to access the req object in passport.use? This was I can get the user ip address and check for eventual attacks.

A: The comments in the example suggest that you can pass an object { "passReqToCallback": true } to make the req callback available in the callback function. Which can be accessed as
function(req, token, done){//rest of the function body}
So initialize passport.use as
passport.use(new BearerStrategy({ "passReqToCallback": true },

 function(req, token, done) {
  });

and you should have req in the callback.