问:
Installing Apache Spark on Windows 7 | spark-shell not working
I tried installing Apache Spark on my 64 bit Windwos 7 machine.

I used the guides -

Installing Spark on Windows 10

How to run Apache Spark on Windows 7

Installing Apache Spark on Windows 7 environment

This is what I did -

Install Scala
Set environment variable SCALA_HOME and add %SCALA_HOME%\bin to Path
Result: scala command works on command prompt

Unpack pre-built Spark
Set environment variable SPARK_HOME and add %SPARK_HOME%\bin to Path

Download winutils.exe
Place winutils.exe under C:/hadoop/bin
Set environment variable HADOOP_HOME and add %HADOOP_HOME%\bin to Path

I already have JDK 8 installed.

Now, the problem is, when I run spark-shell from C:/spark-2.1.1-bin-hadoop2.7/bin, I get this -

```<code>"C:\Program Files\Java\jdk1.8.0_131\bin\java" -cp "C:\spark-2.1.1-bin-hadoop2.7\conf\;C:\spark-2.1.1-bin-hadoop2.7\jars\*" "-Dscala.usejavacp=true" -Xmx1g org spark.repl.Main --name "Spark shell" spark-shell
</code>```

Is it an error? Am I doing something wrong?

Thanks!

答:
I have the same issue when trying to install Spark local with Windows 7. Please make sure the below paths is correct and I am sure I will work with you.

Create JAVA_HOME variable: C:\Program Files\Java\jdk1.8.0_181\bin

Add the following part to your path: ;%JAVA_HOME%\bin

Create SPARK_HOME variable: C:\spark-2.3.0-bin-hadoop2.7\bin

Add the following part to your path: ;%SPARK_HOME%\bin

The most important part Hadoop path should include bin file before winutils.ee as the following: C:\Hadoop\bin Sure you will locate winutils.exe inside this path.

Create HADOOP_HOME Variable: C:\Hadoop

Add the following part to your path: ;%HADOOP_HOME%\bin

Now you can run the cmd and write spark-shell it will work.

Body:
I tried installing Apache Spark on my 64 bit Windwos 7 machine.

I used the guides -

Installing Spark on Windows 10

How to run Apache Spark on Windows 7

Installing Apache Spark on Windows 7 environment

This is what I did -

Install Scala
Set environment variable SCALA_HOME and add %SCALA_HOME%\bin to Path
Result: scala command works on command prompt

Unpack pre-built Spark
Set environment variable SPARK_HOME and add %SPARK_HOME%\bin to Path

Download winutils.exe
Place winutils.exe under C:/hadoop/bin
Set environment variable HADOOP_HOME and add %HADOOP_HOME%\bin to Path

I already have JDK 8 installed.

Now, the problem is, when I run spark-shell from C:/spark-2.1.1-bin-hadoop2.7/bin, I get this -

"C:\Program Files\Java\jdk1.8.0_131\bin\java" -cp "C:\spark-2.1.1-bin-hadoop2.7\conf\;C:\spark-2.1.1-bin-hadoop2.7\jars\*" "-Dscala.usejavacp=true" -Xmx1g org spark.repl.Main --name "Spark shell" spark-shell

Is it an error? Am I doing something wrong?

Thanks!


来源: stackexchange

问:
HTML meta viewport is cutting my layout. Why is it happening?
I am building a responsive web page. Now I am going to start working with media queries, but when I insert <meta name="viewport" content="width=device-width"> and make the screen get smaller, part of the background of my header, first section and footer is cutted, remaining only a part of them and white space with their text. You can see it in the on the snippet. Why is it happening and what can I do do fix it?

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
body{
    font-family: 'Open Sans', sans-serif;
    margin: 0;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding: 0px 30px;
}
header img{
    width: 45px;
}
header h1{
    font-family: 'Doppio One', cursive;
    margin-left: 10px;
    color: rgb(214, 245, 210);
}
nav ul{
    display: flex;
    list-style: none;
}
nav ul li a{
    margin-left: 55px;
}
nav a{
    color: rgb(230, 245, 229);
    font-size: 17px;
}
nav a:hover{
    background-color: rgb(143, 182, 135);
    padding: 10px 15px;
    margin: 0 -15px 0 40px;
}
#firstsection{
    background-image: url(Images/coffee-3289259_1280.jpg);
    background-size: cover;
    height: 900px;
    position: relative;
}
#firstsection div{
    margin-top: 0;
    position: absolute;
    left: 100px;
    top: 150px;
    color: rgb(47, 119, 27);
    text-align: center;
}
#firstsection h1{
    margin-bottom: 45px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#textboxes{
    display: flex;
    margin-top: 50px;
}
#middlesection div div{
    text-align: center;
    margin: 15px 60px;
    border: 2px solid rgb(93, 158, 76);
    padding: 30px 30px;
}
#middlesection img:first-of-type{
    width: 55px;
}
#middlesection h2{
    text-align: center;
    width: 100%;
}
#lastsection{
    text-align: center;
}
#lastsection img{
    width: 500px;
    margin: 100px auto 0px;
}
#lastsection div{
    position: relative;
    bottom: 450px;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    padding: 15px;
    color: rgb(214, 245, 210);
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
footer img{
    height: 35px;
    width: 35px;
    margin-right: 15px;
}
footer div{
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <link rel="stylesheet" type="text/css" href="https://necolas.github.io/normalize.css/8.0.1/normalize.css">
    </head>
    <body>
        <header>
            <img src="Images/icons8-fund-accounting-80.png">
            <h1>Finances</h1>
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Contact us</li>
                    <li>Register</li>
                    <li>Login</li>
                </ul>
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    Get started
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    Create an account
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html></code>```

答:
Do a simple global reset with:

```<code>html,
body,
*,
*::before,
*::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
</code>```

then set the body to:

```<code>body {
    width: 100vw;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am building a responsive web page. Now I am going to start working with media queries, but when I insert <meta name="viewport" content="width=device-width"> and make the screen get smaller, part of the background of my header, first section and footer is cutted, remaining only a part of them and white space with their text. You can see it in the on the snippet. Why is it happening and what can I do do fix it?

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
body{
    font-family: 'Open Sans', sans-serif;
    margin: 0;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding: 0px 30px;
}
header img{
    width: 45px;
}
header h1{
    font-family: 'Doppio One', cursive;
    margin-left: 10px;
    color: rgb(214, 245, 210);
}
nav ul{
    display: flex;
    list-style: none;
}
nav ul li a{
    margin-left: 55px;
}
nav a{
    color: rgb(230, 245, 229);
    font-size: 17px;
}
nav a:hover{
    background-color: rgb(143, 182, 135);
    padding: 10px 15px;
    margin: 0 -15px 0 40px;
}
#firstsection{
    background-image: url(Images/coffee-3289259_1280.jpg);
    background-size: cover;
    height: 900px;
    position: relative;
}
#firstsection div{
    margin-top: 0;
    position: absolute;
    left: 100px;
    top: 150px;
    color: rgb(47, 119, 27);
    text-align: center;
}
#firstsection h1{
    margin-bottom: 45px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#textboxes{
    display: flex;
    margin-top: 50px;
}
#middlesection div div{
    text-align: center;
    margin: 15px 60px;
    border: 2px solid rgb(93, 158, 76);
    padding: 30px 30px;
}
#middlesection img:first-of-type{
    width: 55px;
}
#middlesection h2{
    text-align: center;
    width: 100%;
}
#lastsection{
    text-align: center;
}
#lastsection img{
    width: 500px;
    margin: 100px auto 0px;
}
#lastsection div{
    position: relative;
    bottom: 450px;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    padding: 15px;
    color: rgb(214, 245, 210);
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
footer img{
    height: 35px;
    width: 35px;
    margin-right: 15px;
}
footer div{
    text-align: center;
}

<!DOCTYPE html>

        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <link rel="stylesheet" type="text/css" href="https://necolas.github.io/normalize.css/8.0.1/normalize.css">

Finances

Home

About

Contact us

Register

Login

Manage your money easily, anywhere, anytime.

                    Get started

Concrete data

Simple but concrete data that are the answer to all the quesions about your current money, spending and.

Easy interface

An interface easy to use, made to you who want to manage your money faster and with no problems.

Fast access

No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.

Register now and enjoy
the best of Finances.

                    Create an account

A work of Bruno Sdoukos.

Body:
Do a simple global reset with:

html,
body,
*,
*::before,
*::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

then set the body to:

body {
    width: 100vw;
}


问:
How to copy specific files from directories, while the directories name was extracted from an excel file using Bash script
I'm new in Bash and I have a list of names of directories stored in an excel file. I'd like to find those directories (they are located in different location at the computer) and to copy from each directory specific files (list of 4 files that ends with specific endings) to a remote computer.

For examples:

For a name of directory at the excel sheet - "NA123", I'd like to find it and copy it's partial content to a remote computer, for example copy the files: samples-sheet.csv, toInfo.xml, newfiles.gz, todo.csv to the remote computer, under a folder name "NA123".

How do I begin to do that?

****Editing to give an example of how it needs to be*****

A short example of the csv is as below:

```<code>         A
1  14RD00129_TS1_01
2  SD-2015-06_01
3  US-005
4  RA99
</code>```

All the names at the csv are directories that can be found under /home/bella/samples under 3 different folders: some will be at /home/bella/samples/gruop_1, some at:/home/bella/samples/gruop_2, and some at:/home/bella/samples/gruop_3

So first I need to iterate through the csv file, to locate the match directory at my computer, then I need to copy 4 specific files to a remote computer with the same name of directory. Hope this is clearer...

答:
Basically, you could do something like:</p>

```<code># create the directory on the remote:
ssh remote-ip 'mkdir -p NA123'
# copy the files to the remote in the directory just created
for f in samples-sheet.csv toInfo.xml newfiles.gz todo.csv; do scp $f remote-ip:NA123/; done
</code>```

Body:
I'm new in Bash and I have a list of names of directories stored in an excel file. I'd like to find those directories (they are located in different location at the computer) and to copy from each directory specific files (list of 4 files that ends with specific endings) to a remote computer.

For examples:

For a name of directory at the excel sheet - "NA123", I'd like to find it and copy it's partial content to a remote computer, for example copy the files: samples-sheet.csv, toInfo.xml, newfiles.gz, todo.csv to the remote computer, under a folder name "NA123".

How do I begin to do that?

****Editing to give an example of how it needs to be*****

A short example of the csv is as below:

         A
1  14RD00129_TS1_01
2  SD-2015-06_01
3  US-005
4  RA99

All the names at the csv are directories that can be found under /home/bella/samples under 3 different folders: some will be at /home/bella/samples/gruop_1, some at:/home/bella/samples/gruop_2, and some at:/home/bella/samples/gruop_3

So first I need to iterate through the csv file, to locate the match directory at my computer, then I need to copy 4 specific files to a remote computer with the same name of directory. Hope this is clearer...

Body:
Basically, you could do something like:

# create the directory on the remote:
ssh remote-ip 'mkdir -p NA123'
# copy the files to the remote in the directory just created
for f in samples-sheet.csv toInfo.xml newfiles.gz todo.csv; do scp $f remote-ip:NA123/; done


问:
What happens if I create two class or id with the same name but different property, which one will execute and why?
What happens if I create two class or id with the same name but different property, which one will execute and why ?

I think in this case the class created first will give priority.

I just want to know.

答:
Here's an example to show you:

html {
  background-color: blue;
}

html {
  background-color: red;
}

html {
  background-color: lime;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html></html></code>```

As you can see, the last duplicate rule defined is the one that is applied.

Body:
Here's an example to show you:

html {
  background-color: blue;
}

html {
  background-color: red;
}

html {
  background-color: lime;
}

<html></html>

As you can see, the last duplicate rule defined is the one that is applied.


问:
Get the default height (or maxY) of a NavigationBar on iOS
I would like to know if is there any way for us to obtain the default Navigation Bar height (maxY preferably) of a NavigationController.

Knowing that iOS 11 introduced large titles, is there any way for us then to get the default height (or maxY) of a Navigation Bar with a "small title" and of a Navigation Bar with a "large title"?

The reason I am asking this is because I am making the Navigation Bar's background transparent and introducing my own background to it (which is an Effect View). But the problem I am having is that every time I run the following code

```<code>self.navigationController?.navigationBar.frame.maxY
</code>```

it returns a number ways higher than the expected :/

I tried to run this piece of code on many callbacks -> onViewWillAppear, onViewDidAppear, onViewDidLoad

答:
The best approach I found so far, without having to create a navigation controller instance:

```<code>[self.navigationBar sizeThatFits:CGSizeZero].height;
</code>```

And just to mention, it supports screen orientation change too.

Body:
I would like to know if is there any way for us to obtain the default Navigation Bar height (maxY preferably) of a NavigationController.

Knowing that iOS 11 introduced large titles, is there any way for us then to get the default height (or maxY) of a Navigation Bar with a "small title" and of a Navigation Bar with a "large title"?

The reason I am asking this is because I am making the Navigation Bar's background transparent and introducing my own background to it (which is an Effect View). But the problem I am having is that every time I run the following code

self.navigationController?.navigationBar.frame.maxY

it returns a number ways higher than the expected :/

I tried to run this piece of code on many callbacks -> onViewWillAppear, onViewDidAppear, onViewDidLoad

Body:
The best approach I found so far, without having to create a navigation controller instance:

[self.navigationBar sizeThatFits:CGSizeZero].height;

And just to mention, it supports screen orientation change too.


问:
C Structures Explain push_vlan = (struct vlan_header *)((uint8_t *)new_eth + eth_size);
Can someone explain what is line of code does

```<code>struct name* push_tag = (struct name *)((uint8_t *)name2 + int_size);
</code>```

where name and name2 are different structures .

答: This code puts in the struct variable push_t the value of name2 + int_size, by doing a cast on different variables</p>

Body:
Can someone explain what is line of code does

struct name* push_tag = (struct name *)((uint8_t *)name2 + int_size);

where name and name2 are different structures .


问:
Saving buffer/stream that comes from nodejs server
I am not sure what I am doing wrong.

I have a html content and want to save it as pdf. I use html-pdf (from npm) and a download library http://danml.com/download.html

Actually when I directly save to file or show it as a result I can get the pdf without problem. But I call my webservice method from a js method and I have a stream/buffer as a return value and saving with the 'download' library

Here is my code

```<code>pdf.create(html, options).toFile('./mypdf.pdf', function (err, res) {
    if (err) return console.log(err);
        console.log(res);
  });

pdf.create(html,options).toBuffer(function (err, buffer) {
  if (err) return  reject(err);
      return resolve(buffer);
 });

//res.setHeader('Content-type', 'application/pdf');
pdf.create(html, options).toStream(function (err, stream) {
  if (err) return res.send(err);
     //res.type('pdf');
   return resolve(stream);// .pipe(res);
 });
</code>```

I can save the content as a pdf it works fine. but when I try to send stream or buffer, somehow the page is empty. I opened the both pdf files with notepad. There are some differences. For example, probless one is 44kb the other one 78 kb. and the empty one contains also the following lines

%PDF-1.4 1 0 obj << /Title (��) /Creator (��) /Producer (�� Q t   5 .
  5 . 1) /CreationDate (D:20190524152156)

endobj

I think toBuffer or toStream method has a problem in my case. Because the stream seems not bad. at least I can see that it is a pdf file (no error, just page is empty)

Anyway, here is my API router

```<code>let result = await
routerVoucher.CreatePdfStream(req.query.VoucherCode,req.query.AppName);
res.setHeader('Content-type', 'application/pdf');
res.type('pdf');
//result.pipe(res);
res.end(result, 'binary');
</code>```

and here is my js consumer

```<code>    $.ajax({
            type: "GET",
            url: '/api/vouchers/GetLicensePdf',
            data:data,
            success: function (pdfFile) {

                if (!pdfFile)
                    throw new Error('There is nothing to download');

                    download(pdfFile,voucherCode + '.pdf', 'application/pdf')
</code>```

答:
I've solved the problem.

Firstly I converted buffer to base64

```<code>const base64 = buffer.toString('base64')
</code>```

and then converted base64 to blob by using the following code

```<code>function base64toBlob (base64Data, contentType) {

    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    //var byteCharacters = decodeURIComponent(escape(window.atob(base64Data)))
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}
</code>```

and then

again I've used my download method (from download.js library) as follow

```<code>download(new Blob([base64toBlob(base64PDF,"application/pdf")]),
         voucherCode + '.pdf', "application/pdf");
</code>```

then everything is fine :)

Body:
I am not sure what I am doing wrong.

I have a html content and want to save it as pdf. I use html-pdf (from npm) and a download library http://danml.com/download.html

Actually when I directly save to file or show it as a result I can get the pdf without problem. But I call my webservice method from a js method and I have a stream/buffer as a return value and saving with the 'download' library

Here is my code

pdf.create(html, options).toFile('./mypdf.pdf', function (err, res) {
    if (err) return console.log(err);
        console.log(res);
  });

pdf.create(html,options).toBuffer(function (err, buffer) {
  if (err) return  reject(err);
      return resolve(buffer);
 });

//res.setHeader('Content-type', 'application/pdf');
pdf.create(html, options).toStream(function (err, stream) {
  if (err) return res.send(err);
     //res.type('pdf');
   return resolve(stream);// .pipe(res);
 });

I can save the content as a pdf it works fine. but when I try to send stream or buffer, somehow the page is empty. I opened the both pdf files with notepad. There are some differences. For example, probless one is 44kb the other one 78 kb. and the empty one contains also the following lines

%PDF-1.4 1 0 obj << /Title (��) /Creator (��) /Producer (�� Q t   5 .
  5 . 1) /CreationDate (D:20190524152156)

endobj

I think toBuffer or toStream method has a problem in my case. Because the stream seems not bad. at least I can see that it is a pdf file (no error, just page is empty)

Anyway, here is my API router

let result = await
routerVoucher.CreatePdfStream(req.query.VoucherCode,req.query.AppName);
res.setHeader('Content-type', 'application/pdf');
res.type('pdf');
//result.pipe(res);
res.end(result, 'binary');

and here is my js consumer

    $.ajax({
            type: "GET",
            url: '/api/vouchers/GetLicensePdf',
            data:data,
            success: function (pdfFile) {

                if (!pdfFile)
                    throw new Error('There is nothing to download');

                    download(pdfFile,voucherCode + '.pdf', 'application/pdf')

Body:
I've solved the problem.

Firstly I converted buffer to base64

const base64 = buffer.toString('base64')

and then converted base64 to blob by using the following code

function base64toBlob (base64Data, contentType) {

    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    //var byteCharacters = decodeURIComponent(escape(window.atob(base64Data)))
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

and then

again I've used my download method (from download.js library) as follow

download(new Blob([base64toBlob(base64PDF,"application/pdf")]),
         voucherCode + '.pdf', "application/pdf");

then everything is fine :)


问:
What the Chinese, Japanese, and Korean characters are in Unicode
From what I've gathered:

Hiragana is U+3040 to U+309F

Katakana is U+30A0 to U+30FF.

U+4E00..U+9FFF is part of the complete [Chinese] set, but not all.

The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD].

CJK (for Chinese, Japanese, Korean) encompasses all characters for the Chinese Hànzì, the Japanese Kanji and the Korean Hanja. (So they are all mixed).

The linked answers don't fully explain where everything is. Wondering if there is a clear answer to this so I don't have to go through each character one-by-one.

Body:
so I don't have to go through each character one-by-one.

You're supposed to examine the properties. This is for Unicode 12.1.

Script_Extensions: Han (89513 characters)

U+02E80…U+02E99
U+02E9B…U+02EF3
U+02F00…U+02FD5
U+03001…U+03003
U+03005…U+03011
U+03013…U+0301F
U+03021…U+0302D
U+03030
U+03037…U+0303F
U+030FB
U+03190…U+0319F
U+031C0…U+031E3
U+03220…U+03247
U+03280…U+032B0
U+032C0…U+032CB
U+032FF
U+03358…U+03370
U+0337B…U+0337F
U+033E0…U+033FE
U+03400…U+04DB5
U+04E00…U+09FEF
U+0F900…U+0FA6D
U+0FA70…U+0FAD9
U+0FE45…U+0FE46
U+0FF61…U+0FF65
U+1D360…U+1D371
U+1F250…U+1F251
U+20000…U+2A6D6
U+2A700…U+2B734
U+2B740…U+2B81D
U+2B820…U+2CEA1
U+2CEB0…U+2EBE0
U+2F800…U+2FA1D

Script_Extensions: Hangul (11775 characters)

U+01100…U+011FF
U+03001…U+03003
U+03008…U+03011
U+03013…U+0301F
U+0302E…U+03030
U+03037
U+030FB
U+03131…U+0318E
U+03200…U+0321E
U+03260…U+0327E
U+0A960…U+0A97C
U+0AC00…U+0D7A3
U+0D7B0…U+0D7C6
U+0D7CB…U+0D7FB
U+0FE45…U+0FE46
U+0FF61…U+0FF65
U+0FFA0…U+0FFBE
U+0FFC2…U+0FFC7
U+0FFCA…U+0FFCF
U+0FFD2…U+0FFD7
U+0FFDA…U+0FFDC

Script_Extensions: Hiragana (431 characters)

U+03001…U+03003
U+03008…U+03011
U+03013…U+0301F
U+03030…U+03035
U+03037
U+0303C…U+0303D
U+03041…U+03096
U+03099…U+030A0
U+030FB…U+030FC
U+0FE45…U+0FE46
U+0FF61…U+0FF65
U+0FF70
U+0FF9E…U+0FF9F
U+1B001…U+1B11E
U+1B150…U+1B152
U+1F200

Script_Extensions: Katakana (356 characters)

U+03001…U+03003
U+03008…U+03011
U+03013…U+0301F
U+03030…U+03035
U+03037
U+0303C…U+0303D
U+03099…U+0309C
U+030A0…U+030FF
U+031F0…U+031FF
U+032D0…U+032FE
U+03300…U+03357
U+0FE45…U+0FE46
U+0FF61…U+0FF9F
U+1B000
U+1B164…U+1B167


问:
distinguish between the scanner and the keyboard
hey all.
I have a barcode scanner connected to a PC that working with a c# program.now i want to distinguish between the scanner and the keyboard which one is sending data to my program.
can everyone help me with a code or advise in c#?

somebody said this to me in another topic(but i can't do this yet):
basically you can configure the scanner to send some characters that basically tell the computer "hi, it's me". When you see those characters in your input stream, you know the information is coming from the barcode scanner, not from something the user typed on the keyboard. Did you check the manual that came with your barcode scanner? It should have more information about this.

答: The scan data will typically end with a carriage return or line feed character, called the suffix. You may be able to configure the scanner to include a prefix as well. That is what your friend was trying to tell you.</p>

ContentLicense: CC BY-SA 3.0


问:
Error "could not delete" with Composer on Vagrant
I have a Vagrant running Linux and I'm trying to install Symfony.

After the command composer create-project symfony/framework-standard-edition ./ "2.5.*" I have the error :

```<code>[RuntimeException]
  Could not delete ./.git/objects/pack/tmp_idx_llwUKb:
</code>```

If I try to composer update another project, I always have this kind of error Could not delete

Any ideas?

Edit: For a simple sudo composer update -vvv on another project:

```<code>  - Installing sonata-project/admin-bundle (dev-master 8a022aa)
Failed to download sonata-project/admin-bundle from source: Could not delete /vagrant/crm_neo/vendor/sonata-project/admin-bundle/.git/objects/pack/tmp_idx_hchQhc:
Now trying to download from dist
  - Installing sonata-project/admin-bundle (dev-master 8a022aa)

Failed: [RuntimeException] Could not delete /vagrant/crm_neo/vendor/sonata-project/admin-bundle/.git/objects/pack/tmp_idx_hchQhc:

  [RuntimeException]
  Could not delete /vagrant/crm_neo/vendor/sonata-project/admin-bundle/.git/o
  bjects/pack/tmp_idx_hchQhc:

Exception trace:
 () at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:193
 Composer\Util\Filesystem->unlink() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:151
 Composer\Util\Filesystem->removeDirectoryPhp() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:129
 Composer\Util\Filesystem->removeDirectory() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:35
 Composer\Util\Filesystem->remove() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:80
 Composer\Util\Filesystem->emptyDirectory() at phar:///usr/local/bin/composer/src/Composer/Downloader/FileDownloader.php:108
 Composer\Downloader\FileDownloader->doDownload() at phar:///usr/local/bin/composer/src/Composer/Downloader/FileDownloader.php:89
 Composer\Downloader\FileDownloader->download() at phar:///usr/local/bin/composer/src/Composer/Downloader/ArchiveDownloader.php:35
 Composer\Downloader\ArchiveDownloader->download() at phar:///usr/local/bin/composer/src/Composer/Downloader/DownloadManager.php:201
 Composer\Downloader\DownloadManager->download() at phar:///usr/local/bin/composer/src/Composer/Installer/LibraryInstaller.php:156
 Composer\Installer\LibraryInstaller->installCode() at phar:///usr/local/bin/composer/src/Composer/Installer/LibraryInstaller.php:87
 Composer\Installer\LibraryInstaller->install() at phar:///usr/local/bin/composer/src/Composer/Installer/InstallationManager.php:152
 Composer\Installer\InstallationManager->install() at phar:///usr/local/bin/composer/src/Composer/Installer/InstallationManager.php:139
 Composer\Installer\InstallationManager->execute() at phar:///usr/local/bin/composer/src/Composer/Installer.php:548
 Composer\Installer->doInstall() at phar:///usr/local/bin/composer/src/Composer/Installer.php:217
 Composer\Installer->run() at phar:///usr/local/bin/composer/src/Composer/Command/UpdateCommand.php:128
 Composer\Command\UpdateCommand->execute() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:252
 Symfony\Component\Console\Command\Command->run() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:889
 Symfony\Component\Console\Application->doRunCommand() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:193
 Symfony\Component\Console\Application->doRun() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:135
 Composer\Console\Application->doRun() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:124
 Symfony\Component\Console\Application->run() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:84
 Composer\Console\Application->run() at phar:///usr/local/bin/composer/bin/composer:43
 require() at /usr/local/bin/composer:15
</code>```

答:
To me it helped to install a (new) version via command line from download homepage https://getcomposer.org/download/. I can exclude some file permissions as I was root with chmod +R 0777, though I had virtualbox mounted drive. Anyway since new version worked, would mean it was version, or running a new version via php phar, and the original bin belonged to root</p>

```<code>php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"
</code>```

Body:
I have a Vagrant running Linux and I'm trying to install Symfony.

After the command composer create-project symfony/framework-standard-edition ./ "2.5.*" I have the error :

[RuntimeException]
  Could not delete ./.git/objects/pack/tmp_idx_llwUKb:

If I try to composer update another project, I always have this kind of error Could not delete

Any ideas?

Edit: For a simple sudo composer update -vvv on another project:

  - Installing sonata-project/admin-bundle (dev-master 8a022aa)
Failed to download sonata-project/admin-bundle from source: Could not delete /vagrant/crm_neo/vendor/sonata-project/admin-bundle/.git/objects/pack/tmp_idx_hchQhc:
Now trying to download from dist
  - Installing sonata-project/admin-bundle (dev-master 8a022aa)

Failed: [RuntimeException] Could not delete /vagrant/crm_neo/vendor/sonata-project/admin-bundle/.git/objects/pack/tmp_idx_hchQhc:

  [RuntimeException]
  Could not delete /vagrant/crm_neo/vendor/sonata-project/admin-bundle/.git/o
  bjects/pack/tmp_idx_hchQhc:

Exception trace:
 () at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:193
 Composer\Util\Filesystem->unlink() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:151
 Composer\Util\Filesystem->removeDirectoryPhp() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:129
 Composer\Util\Filesystem->removeDirectory() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:35
 Composer\Util\Filesystem->remove() at phar:///usr/local/bin/composer/src/Composer/Util/Filesystem.php:80
 Composer\Util\Filesystem->emptyDirectory() at phar:///usr/local/bin/composer/src/Composer/Downloader/FileDownloader.php:108
 Composer\Downloader\FileDownloader->doDownload() at phar:///usr/local/bin/composer/src/Composer/Downloader/FileDownloader.php:89
 Composer\Downloader\FileDownloader->download() at phar:///usr/local/bin/composer/src/Composer/Downloader/ArchiveDownloader.php:35
 Composer\Downloader\ArchiveDownloader->download() at phar:///usr/local/bin/composer/src/Composer/Downloader/DownloadManager.php:201
 Composer\Downloader\DownloadManager->download() at phar:///usr/local/bin/composer/src/Composer/Installer/LibraryInstaller.php:156
 Composer\Installer\LibraryInstaller->installCode() at phar:///usr/local/bin/composer/src/Composer/Installer/LibraryInstaller.php:87
 Composer\Installer\LibraryInstaller->install() at phar:///usr/local/bin/composer/src/Composer/Installer/InstallationManager.php:152
 Composer\Installer\InstallationManager->install() at phar:///usr/local/bin/composer/src/Composer/Installer/InstallationManager.php:139
 Composer\Installer\InstallationManager->execute() at phar:///usr/local/bin/composer/src/Composer/Installer.php:548
 Composer\Installer->doInstall() at phar:///usr/local/bin/composer/src/Composer/Installer.php:217
 Composer\Installer->run() at phar:///usr/local/bin/composer/src/Composer/Command/UpdateCommand.php:128
 Composer\Command\UpdateCommand->execute() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:252
 Symfony\Component\Console\Command\Command->run() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:889
 Symfony\Component\Console\Application->doRunCommand() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:193
 Symfony\Component\Console\Application->doRun() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:135
 Composer\Console\Application->doRun() at phar:///usr/local/bin/composer/vendor/symfony/console/Symfony/Component/Console/Application.php:124
 Symfony\Component\Console\Application->run() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:84
 Composer\Console\Application->run() at phar:///usr/local/bin/composer/bin/composer:43
 require() at /usr/local/bin/composer:15

Body:
To me it helped to install a (new) version via command line from download homepage https://getcomposer.org/download/. I can exclude some file permissions as I was root with chmod +R 0777, though I had virtualbox mounted drive. Anyway since new version worked, would mean it was version, or running a new version via php phar, and the original bin belonged to root

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"


问:
find number by given factorial number
I need to find number by given factorial number. I know how to find factorial of a number .But stuck to find number of given factorial..</p>

```<code>class Fact{
 public static void main(String args[]){
  int i,fact=1;
  int number=5;
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  int yo = number(number);
  System.out.println(fact + " " + yo );

 }

  public static int number(int no){
      for(int i = 1 ; i >= no ; i--){
          no = no / i;
      }
      return no;
  }
}
</code>```

答:
This method:

```<code>public static int number(int factorial) {
    if (factorial <= 0) return -1;
    if ((factorial == 1) || (factorial == 2)) return factorial;
    if (factorial % 2 != 0) return -1;

    int i = 1;
    int prod = 1;
    while (prod < factorial) {
        prod *= ++i;
    }
    return (prod == factorial) ? i : -1;
}
</code>```

takes as an argument an integer number factorial and checks if it is the factorial of an integer and returns that integer.

It is limited up to 12! (this is the limit posed by the int data type)

For 1 as the argument it returns 1 and not 0 which is also a solution since 0! = 1.

It returns -1 if it is not the factorial of an integer.

So, this:

```<code>public static void main(String[] args) {
    for (int i = -1; i <= 1_000_000_000; i++) {
        int x = number(i);
        if (x > 0)
            System.out.println("Number = " + i + " is the factorial of " + x);
    }
}
</code>```

will print:

```<code>Number = 1 is the factorial of 1
Number = 2 is the factorial of 2
Number = 6 is the factorial of 3
Number = 24 is the factorial of 4
Number = 120 is the factorial of 5
Number = 720 is the factorial of 6
Number = 5040 is the factorial of 7
Number = 40320 is the factorial of 8
Number = 362880 is the factorial of 9
Number = 3628800 is the factorial of 10
Number = 39916800 is the factorial of 11
Number = 479001600 is the factorial of 12
</code>```

I'm not sure if it's the most efficient way of doing this, but it gives correct results.

Title: find number by given factorial number

Body:
I need to find number by given factorial number. I know how to find factorial of a number .But stuck to find number of given factorial..

class Fact{
 public static void main(String args[]){
  int i,fact=1;
  int number=5;
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  int yo = number(number);
  System.out.println(fact + " " + yo );

 }

  public static int number(int no){
      for(int i = 1 ; i >= no ; i--){
          no = no / i;
      }
      return no;
  }
}

Body:
This method:

public static int number(int factorial) {
    if (factorial <= 0) return -1;
    if ((factorial == 1) || (factorial == 2)) return factorial;
    if (factorial % 2 != 0) return -1;

    int i = 1;
    int prod = 1;
    while (prod < factorial) {
        prod *= ++i;
    }
    return (prod == factorial) ? i : -1;
}

takes as an argument an integer number factorial and checks if it is the factorial of an integer and returns that integer.

It is limited up to 12! (this is the limit posed by the int data type)

For 1 as the argument it returns 1 and not 0 which is also a solution since 0! = 1.

It returns -1 if it is not the factorial of an integer.

So, this:

public static void main(String[] args) {
    for (int i = -1; i <= 1_000_000_000; i++) {
        int x = number(i);
        if (x > 0)
            System.out.println("Number = " + i + " is the factorial of " + x);
    }
}

will print:

Number = 1 is the factorial of 1
Number = 2 is the factorial of 2
Number = 6 is the factorial of 3
Number = 24 is the factorial of 4
Number = 120 is the factorial of 5
Number = 720 is the factorial of 6
Number = 5040 is the factorial of 7
Number = 40320 is the factorial of 8
Number = 362880 is the factorial of 9
Number = 3628800 is the factorial of 10
Number = 39916800 is the factorial of 11
Number = 479001600 is the factorial of 12

I'm not sure if it's the most efficient way of doing this, but it gives correct results.


答:
I think it is more likely to be the second one, because generally computers will go by what value was assigned to a class or variable last. For example:

var num = 1;
var num = 2;
alert(num);
//will alert “2”
```

Title: What happens if I create two class or id with the same name but different property, which one will execute and why?

Body:
What happens if I create two class or id with the same name but different property, which one will execute and why ?

I think in this case the class created first will give priority.

I just want to know.


问:
developin web app using .net need Info about Local System
we are devoloping a web application using c#.net,ASP.Net 3.5,in that we need to know the infomation  of local system  like what are the  installed printers? is there any way to get the data using any scripting Languages? Plz let me know if any body knows the answer.

Thanks in advance
Prasad

答:
I guess that will help:

How To Get Hardware Information (CPU ID, MainBoard Info, Hard Disk Serial, System Information , ...)


问:
spark-shell throws error in Apache spark
I have installed hadoop on ubuntu on virtual box(host os Windows 7).I have also installed Apache spark, configured SPARK_HOME in .bashrc and added HADOOP_CONF_DIR to spark-env.sh. Now when I start the spark-shell it throws error and do not initialize spark context, sql context. Am I missing something in installation and also I would want to run it on a cluster (hadoop 3 node cluster is set up).

答:
I have the same issue when trying to install Spark local with Windows 7. Please make sure the below paths is correct and I am sure I will work with you. I answer same question in this link So, you can follow the below and it will work.

Create JAVA_HOME variable: C:\Program Files\Java\jdk1.8.0_181\bin

Add the following part to your path: ;%JAVA_HOME%\bin

Create SPARK_HOME variable: C:\spark-2.3.0-bin-hadoop2.7\bin

Add the following part to your path: ;%SPARK_HOME%\bin

The most important part Hadoop path should include bin file before winutils.ee as the following: C:\Hadoop\bin Sure you will locate winutils.exe inside this path.

Create HADOOP_HOME Variable: C:\Hadoop

Add the following part to your path: ;%HADOOP_HOME%\bin

Now you can run the cmd and write spark-shell it will work.


问:
Convert array of indices to one-hot encoded array in NumPy
Given a 1D array of indices:

```<code>a = array([1, 0, 3])
</code>```

I want to one-hot encode this as a 2D array:

```<code>b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])
</code>```

答:
You can use the following code for converting into a one-hot vector:

let x is the normal class vector having a single column with classes 0 to some number:

```<code>import numpy as np
np.eye(x.max()+1)[x]
</code>```

if 0 is not a class; then remove +1.

Body:
Given a 1D array of indices:

a = array([1, 0, 3])

I want to one-hot encode this as a 2D array:

b = array([[0,1,0,0], [1,0,0,0], [0,0,0,1]])

Body:
You can use the following code for converting into a one-hot vector:

let x is the normal class vector having a single column with classes 0 to some number:

import numpy as np
np.eye(x.max()+1)[x]

if 0 is not a class; then remove +1.


问:
How can I access label.Text from my User Control
I want to access labelNummer.Text from my User Control in my form.

Form

```<code>if (idPartijen.Contains(labelNummer.Text))
        {
            con.SqlQuery("SELECT * FROM `kandidaat` where `partijnummer` =@nummer ");
            con.Cmd.Parameters.Add("@nummer", MySql.Data.MySqlClient.MySqlDbType.VarString).Value = labelNummer.Text;
</code>```

User Control

```<code>  public string KandidaatNummer
    {
        set
        {
            Nummer = value;
            labelNummer.Text = Nummer;
        }
    }
</code>```

答:
Your UserControl

```<code>public partial class MyUserControl : UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
    }

    private void MyUserControl_Load(object sender, EventArgs e)
    {

    }

    public string KandidaatNummer
    {
        get
        {
            return labelNummer.Text;
        }

        set
        {
            labelNummer.Text = value;
        }
    }
}
</code>```

Let's say that your user control has a name called: MyUserControl1

```<code> if (idPartijen.Contains(myUserControl1.KandidaatNummer)) { ... }
</code>```

Body:
I want to access labelNummer.Text from my User Control in my form.

Form

if (idPartijen.Contains(labelNummer.Text))
        {
            con.SqlQuery("SELECT * FROM `kandidaat` where `partijnummer` =@nummer ");
            con.Cmd.Parameters.Add("@nummer", MySql.Data.MySqlClient.MySqlDbType.VarString).Value = labelNummer.Text;

User Control

  public string KandidaatNummer
    {
        set
        {
            Nummer = value;
            labelNummer.Text = Nummer;
        }
    }

Body:
Your UserControl

public partial class MyUserControl : UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
    }

    private void MyUserControl_Load(object sender, EventArgs e)
    {

    }

    public string KandidaatNummer
    {
        get
        {
            return labelNummer.Text;
        }

        set
        {
            labelNummer.Text = value;
        }
    }
}

Let's say that your user control has a name called: MyUserControl1

 if (idPartijen.Contains(myUserControl1.KandidaatNummer)) { ... }


问:
TextView inside Fragment in ViewPager is null on orientation change
I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.

MyFragment

public class MyFragment extends Fragment {

    private TextView textView;
    private String info;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.item_weather, container, false);
        textView = view.findViewById(R.id.text_view);
        Bundle bundle = getArguments();
        info = bundle.getString("info");
        setInfo(info);
        return view;

    }

    public void setInfo(String info) {
        this.info = info;
        textView.setText(info); //here is the error
    }
}
```

<p>In <code>MainActivity.java</code> in <code>OnCreate</code></p>

<pre class="lang-java prettyprint-override"><code>myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);

List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);

pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);
</code>```

MyPagerAdapter looks like this:

public class MyPageAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> fragments;

    public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}
```

<p>As I said everything works, but after orientation chage if I use Button I got an error:</p>

```java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
```

<p>Any ideas how to solve this?</p>

<p>edit:
full error</p>

```E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app.myapp, PID: 15400
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
        at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
        at android.app.Activity.onMenuItemSelected(Activity.java:3543)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
        at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
        at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
        at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
        at android.widget.AdapterView.performItemClick(AdapterView.java:318)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
        at android.widget.AbsListView$3.run(AbsListView.java:4052)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
```

答:
Into the fragment try to initialize the textView in the on  the onViewCreated method:

@Override
public View onViewCreated(view: View, savedInstanceState: Bundle) {

   // Your initialization code here

}
```

Body:
I have a MainActivity inside I create ViewPager withFragments. I am using savedInstanceState to store values to set TextView after orientation changed. I also want to change value e.g. using button in MainActivity. Button works properly, but if I change the orientation then Button cannot set TextView in Fragment because TextView is now null.

MyFragment

public class MyFragment extends Fragment {

    private TextView textView;
    private String info;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.item_weather, container, false);
        textView = view.findViewById(R.id.text_view);
        Bundle bundle = getArguments();
        info = bundle.getString("info");
        setInfo(info);
        return view;

    }

    public void setInfo(String info) {
        this.info = info;
        textView.setText(info); //here is the error
    }
}

In MainActivity.java in OnCreate

myFragment = new MyFragment();
viewPager = findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(10);

List<Fragment> fragments = new ArrayList<>();
fragments.add(myFragment);

pagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(pagerAdapter);

MyPagerAdapter looks like this:

public class MyPageAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> fragments;

    public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

As I said everything works, but after orientation chage if I use Button I got an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

Any ideas how to solve this?

edit:
full error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app.myapp, PID: 15400
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.app.myapp.fragments.myFragment.setInfo(myFragment.java:53)
        at com.example.app.myapp.MainActivity.onOptionsItemSelected(MainActivity.java:195)
        at android.app.Activity.onMenuItemSelected(Activity.java:3543)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
        at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:63)
        at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:203)
        at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
        at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
        at android.widget.AdapterView.performItemClick(AdapterView.java:318)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1159)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3136)
        at android.widget.AbsListView$3.run(AbsListView.java:4052)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)


问:
How to return Flask-SqlAlchemy error details
I'm using Flask 1.0, Flask-SqlAlchemy 2 and Angular 7.

When SqlAlchemy throws an error I want to show a tailored error message in the frontend.

There is a section in the official Flask documentation about how to handle errors and also a similar question here on SO, that is related to Flask-Restless though. And yet I'm not able to connect the dots.

When SqlAlchemy throws an error, it looks something like this:

```<code>DETAIL:  Key (id)=(123) is not present in table "foo".
</code>```

I'm returning the error to the route:

```<code>try:
    db.session.commit()
except Exception as error:
    db.session.flush()
    db.session.rollback()
    return error
</code>```

In the route I'm checking if it is an error:

```<code>if status == True:
    return jsonify( { "success": True } ), 201
else:
    return error_response(500, str(status))
</code>```

And my error_response class looks like this:

```<code>def error_response(status_code, message=None):
    payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
    if message:
        payload["message"] = message
        response = jsonify(payload)
        response.status_code = status_code
    return response
</code>```

But the response json just contains a generic error message:

```<code>"message": "Http failure response for http://127.0.0.1:5000/database/add_foo: 0 Unknown Error"
</code>```

答:
You can read the error object and create your own custom message out of it. for all details try printing error.\__dict__ in console.

for example:

```<code>from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import Column
from sqlalchemy import Integer, String

db_uri = 'sqlite:///'
engine = create_engine(db_uri)
conn = engine.connect()

# Create a metadata instance
meta = MetaData(engine)
table = Table('user', meta,
   Column('id', Integer, primary_key=True),
   Column('l_name', String),
   Column('f_name', String))
meta.create_all()
# Insert Data
conn.execute(table.insert(),[
   {'id':1,'l_name':'Hi','f_name':'bob'},
   {'id':2,'l_name':'Hello','f_name':'john'},
   {'id':3,'l_name':'yo','f_name':'bob-john'}])

result =conn.execute("SELECT * FROM user")
for res in result:
  print(res)
# Intensionally violating unique constraint
try:
  ins = table.insert().values(
      id=3,
      l_name='Hello',
      f_name='World')
# conn = engine.connect()
  conn.execute(ins)
except Exception as error:
  print(str(error.orig) + " for parameters" + str(error.params))
</code>```

output will be :-

Body:
I'm using Flask 1.0, Flask-SqlAlchemy 2 and Angular 7.

When SqlAlchemy throws an error I want to show a tailored error message in the frontend.

There is a section in the official Flask documentation about how to handle errors and also a similar question here on SO, that is related to Flask-Restless though. And yet I'm not able to connect the dots.

When SqlAlchemy throws an error, it looks something like this:

DETAIL:  Key (id)=(123) is not present in table "foo".

I'm returning the error to the route:

try:
    db.session.commit()
except Exception as error:
    db.session.flush()
    db.session.rollback()
    return error

In the route I'm checking if it is an error:

if status == True:
    return jsonify( { "success": True } ), 201
else:
    return error_response(500, str(status))

And my error_response class looks like this:

def error_response(status_code, message=None):
    payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
    if message:
        payload["message"] = message
        response = jsonify(payload)
        response.status_code = status_code
    return response

But the response json just contains a generic error message:

"message": "Http failure response for http://127.0.0.1:5000/database/add_foo: 0 Unknown Error"

Body:
You can read the error object and create your own custom message out of it. for all details try printing error.\__dict__ in console.

for example:

from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import Column
from sqlalchemy import Integer, String

db_uri = 'sqlite:///'
engine = create_engine(db_uri)
conn = engine.connect()

# Create a metadata instance
meta = MetaData(engine)
table = Table('user', meta,
   Column('id', Integer, primary_key=True),
   Column('l_name', String),
   Column('f_name', String))
meta.create_all()
# Insert Data
conn.execute(table.insert(),[
   {'id':1,'l_name':'Hi','f_name':'bob'},
   {'id':2,'l_name':'Hello','f_name':'john'},
   {'id':3,'l_name':'yo','f_name':'bob-john'}])

result =conn.execute("SELECT * FROM user")
for res in result:
  print(res)
# Intensionally violating unique constraint
try:
  ins = table.insert().values(
      id=3,
      l_name='Hello',
      f_name='World')
# conn = engine.connect()
  conn.execute(ins)
except Exception as error:
  print(str(error.orig) + " for parameters" + str(error.params))

output will be :-


问:
Plot point patterns on original images
I have a histopatholgy images and I use developed algorithms extracted interested cells as point patters.

Now I want to plot point patterns on the original images, my expectation should be like this:

At first I try to use R to load original image, however, the loaded image are displayed together with axes, and no grid lines as the figure shows. So I was wondering how could I replicate the format as the figure shows exactly.
Thanks!

Information about the 'fig' variable for plot:

答:
Here's a suggested solution with R, using the EBImage package. I like this because of the ease of interacting with the image.

```<code># EBImage is required
  if (!require(EBImage)) {
    source("https://bioconductor.org/biocLite.R")
    biocLite("EBImage")
    library(EBImage)
  }

# Read the image and plot it with no borders, 300 ppi
  fn <- file.choose() # select saved image
  img <- readImage(fn)
  img <- channel(img, "gray") # gray scale for simplicity
  dev.new(width = dim(img)[1]/300, height = dim(img)[2]/300)
  plot(img)
</code>```

This step takes advantage of the ease of interacting with graphic elements in R. Here, locator is used to place a mark at the intersection of grid lines and to record the x, y coordinates. Grid lines are then added to the image under the assumption that the image is oriented with the grid lines running vertically and horizontally.

```<code># Use locator() to interactively identify convenient intersections
  pp <- locator(type = "p", pch = 3, col = 2) # end with ctrl-click
</code>```

The following code is not necessary if only intersections along the diagonal were chosen. This extra code accomodates an arbitrary number of selections to determine the unique grid lines (as long as choices include one of each grid line). The average value will be determined from multiple choices.

```<code># Little more coding to extract and plot unique grid lines
  breaks <- lapply(pp, function(v) hist(v, plot = FALSE)$breaks)
  groups <- Map(cut, pp, breaks)
  pp <- Map(function(v, g) tapply(v, g, mean), pp, groups)
  pp <- lapply(pp, function(x) x[!is.na(x)]) # to re-use if needed

# Place grid lines on new image
  plot(img)
  abline(v = pp$x, h = pp$y, col = 2)
</code>```

Grid lines were added with the simplest base function. More sophisticated lines could be added if desired. To illustrate other possibilities, the coordinates (in pixels) of each grid line is placed here.

```<code>  text(min(pp$x), pp$y, round(pp$y), col = 2, adj = c(1, -0.2))
  text(pp$x, max(pp$y), round(pp$x), col = 2, adj = c(0, 1.2))
</code>```

And the result of this (having interacted through locator().

Title: Plot point patterns on original images

Body:
Here's a suggested solution with R, using the EBImage package. I like this because of the ease of interacting with the image.

# EBImage is required
  if (!require(EBImage)) {
    source("https://bioconductor.org/biocLite.R")
    biocLite("EBImage")
    library(EBImage)
  }

# Read the image and plot it with no borders, 300 ppi
  fn <- file.choose() # select saved image
  img <- readImage(fn)
  img <- channel(img, "gray") # gray scale for simplicity
  dev.new(width = dim(img)[1]/300, height = dim(img)[2]/300)
  plot(img)

This step takes advantage of the ease of interacting with graphic elements in R. Here, locator is used to place a mark at the intersection of grid lines and to record the x, y coordinates. Grid lines are then added to the image under the assumption that the image is oriented with the grid lines running vertically and horizontally.

# Use locator() to interactively identify convenient intersections
  pp <- locator(type = "p", pch = 3, col = 2) # end with ctrl-click

The following code is not necessary if only intersections along the diagonal were chosen. This extra code accomodates an arbitrary number of selections to determine the unique grid lines (as long as choices include one of each grid line). The average value will be determined from multiple choices.

# Little more coding to extract and plot unique grid lines
  breaks <- lapply(pp, function(v) hist(v, plot = FALSE)$breaks)
  groups <- Map(cut, pp, breaks)
  pp <- Map(function(v, g) tapply(v, g, mean), pp, groups)
  pp <- lapply(pp, function(x) x[!is.na(x)]) # to re-use if needed

# Place grid lines on new image
  plot(img)
  abline(v = pp$x, h = pp$y, col = 2)

Grid lines were added with the simplest base function. More sophisticated lines could be added if desired. To illustrate other possibilities, the coordinates (in pixels) of each grid line is placed here.

  text(min(pp$x), pp$y, round(pp$y), col = 2, adj = c(1, -0.2))
  text(pp$x, max(pp$y), round(pp$x), col = 2, adj = c(0, 1.2))

And the result of this (having interacted through locator().


问:
Ansible yum disablerepo does not work if repo is not installed
I have a number of different Centos7 servers running. I like to use ansible to update them all at once.

As one of my servers has an additional repository enabled, which I do not want to update. I've added to the playbook the option to disable this repo. This works as expected.

However, on my other servers, I did not install and enable this repo. When using the disablerepo in my ansible playbook, I get an error: repository not found.

How do I solve this in the ansible-playbook? Is it possible to add an condition like, if repo installed; then disablerepo; else do nothing?

Is it possible to ignore these errors?

ansible-playbook:

```<code>---
- hosts: [all]
  tasks:
- name: update all packages to lastest version
  yum:
    name: '*'
    state: latest
    disablerepo: sernet-samba-4.2
</code>```

答:
you can put ignore_errors: yes as in the link from the comment, or you can put when, only if certain package is installed, sure you have to register them to variables first, I'm thinking something like:

```<code>- name: check if installed
  shell: rpm -qa sernet-samba-4.2
  register: is_installed

- name: update all packages to lastest version
  yum:
    name: '*'
    state: latest
    disablerepo: sernet-samba-4.2
  when: is_installed.rc == 1
</code>```

Warning: Untested.

Body:
I have a number of different Centos7 servers running. I like to use ansible to update them all at once.

As one of my servers has an additional repository enabled, which I do not want to update. I've added to the playbook the option to disable this repo. This works as expected.

However, on my other servers, I did not install and enable this repo. When using the disablerepo in my ansible playbook, I get an error: repository not found.

How do I solve this in the ansible-playbook? Is it possible to add an condition like, if repo installed; then disablerepo; else do nothing?

Is it possible to ignore these errors?

ansible-playbook:

---
- hosts: [all]
  tasks:
- name: update all packages to lastest version
  yum:
    name: '*'
    state: latest
    disablerepo: sernet-samba-4.2

Body:
you can put ignore_errors: yes as in the link from the comment, or you can put when, only if certain package is installed, sure you have to register them to variables first, I'm thinking something like:

- name: check if installed
  shell: rpm -qa sernet-samba-4.2
  register: is_installed

- name: update all packages to lastest version
  yum:
    name: '*'
    state: latest
    disablerepo: sernet-samba-4.2
  when: is_installed.rc == 1

Warning: Untested.


问:
Shapes not appearing on html canvas
I am trying to make a game on an html canvas, however nothing is appearing on the canvas. I am not sure what I am doing wrong. This is the code where I attempt to draw the shapes and start the game:

```<code>function startGame() {
    myGamePiece = new component(50, 10, "grey", 240, 20);
    myAponent = new component(50, 10, "grey", 240, 460);
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}
</code>```

If you wish to see all of my code, it is available here: https://js.do/nioiluc/320839

答:
You arent properly defining ctx, as myGameArea.context returns undefined.

Try this for defining:

var ctx = myGameArea.canvas.getContext('2d');

and make the needed adjustments. Example: https://jsfiddle.net/ztnr1gqd/

Title: Shapes not appearing on html canvas

Body:
I am trying to make a game on an html canvas, however nothing is appearing on the canvas. I am not sure what I am doing wrong. This is the code where I attempt to draw the shapes and start the game:

function startGame() {
    myGamePiece = new component(50, 10, "grey", 240, 20);
    myAponent = new component(50, 10, "grey", 240, 460);
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

If you wish to see all of my code, it is available here: https://js.do/nioiluc/320839


问:
What options do I have to make my ORDER BY faster?
I have the following query:

```<code>SELECT DISTINCT c.id
FROM clients AS c
LEFT JOIN client_project AS cp ON (cp.client_id = c.id)
WHERE cp.project_id = 1
    AND c.active_flag = 1
ORDER BY c.client_name
</code>```

If I remove the order by, the query takes 0.005 seconds. With the order by, the query takes 1.8-1.9 seconds. I have an index on client_name.

What else would improve the speed?

Edit: c.id is primary key, but there could be multiple records for it in client_project and therefore it may result in more than one record for each id. Also, removing the distinct makes 0.1 second difference in the query.

Addition: Here is my clients table:

```<code>CREATE TABLE IF NOT EXISTS `clients` (
  `id` int(11) NOT NULL auto_increment,
...
  `organization` varchar(255) character set utf8 collate utf8_bin NOT NULL,
  `client_name` varchar(255) character set utf8 collate utf8_bin NOT NULL,
  `active_flag` tinyint(1) NOT NULL,
...
  PRIMARY KEY  (`id`),
  KEY `active_flag` (`active_flag`),
...
  KEY `organization` (`organization`),
  KEY `client_name` (`client_name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
</code>```

Using MySQL 5.0

答:
I don't have a solution for you, but I do have an explanation.

MySQL only uses a single index per table. You have two tables, and the indexes used in those are the Primary Key of one (WHERE cp.project_id = 1) and the join is forcing the use of the second table index to efficiently join.

Using ORDER BY after that it therefore becomes impossible for MySQL to use an index to order. Adding more indexes will not help. EXPLAIN will show you which indexes MySQL has chosen to use for each table. Forcing an index will cause the other parts of the query to slow down.

OwnerDisplayName: Darryl Hein

ContentLicense: CC BY-SA 2.5

Body:
I have the following query:

SELECT DISTINCT c.id
FROM clients AS c
LEFT JOIN client_project AS cp ON (cp.client_id = c.id)
WHERE cp.project_id = 1
    AND c.active_flag = 1
ORDER BY c.client_name

If I remove the order by, the query takes 0.005 seconds. With the order by, the query takes 1.8-1.9 seconds. I have an index on client_name.

What else would improve the speed?

Edit: c.id is primary key, but there could be multiple records for it in client_project and therefore it may result in more than one record for each id. Also, removing the distinct makes 0.1 second difference in the query.

Addition: Here is my clients table:

CREATE TABLE IF NOT EXISTS `clients` (
  `id` int(11) NOT NULL auto_increment,
...
  `organization` varchar(255) character set utf8 collate utf8_bin NOT NULL,
  `client_name` varchar(255) character set utf8 collate utf8_bin NOT NULL,
  `active_flag` tinyint(1) NOT NULL,
...
  PRIMARY KEY  (`id`),
  KEY `active_flag` (`active_flag`),
...
  KEY `organization` (`organization`),
  KEY `client_name` (`client_name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Using MySQL 5.0

LastEditorDisplayName: Darryl Hein

OwnerDisplayName: mluebke


问:
Selenium Basic VBA focus on new tab that is opened by Click
I'm working on the Selenium Basic Wrapper for Excel VBA, but upon clicking  a button that opens a new tab, I am unable to get the selenium web-driver to switch focus onto the new tab that is opened, and to close the original tab.. Believe this should be achievable using the Java Selenium, but is there any way to do it through the Selenium Basic wrapper on excel VBA?

Have tried using bot.switchtopreviouswindow/nextwindow to no avail, Selenium does not even seem to detect the new tab/window opened as an existing window, also tried using switchwindow using title to no avail...

```<code>Private Sub CommandButton1_Click()

    Dim bot As New ChromeDriver
    Dim merchant As String
    Dim promocode As Object
    Dim number As Long
    Dim test As Object
    Dim testnumber As Integer

    lastColumn = Sheets("Merchants").Range("B" & Rows.Count).End(xlUp).Row

    For i = 2 To lastColumn

        bot.Get (Sheets("Merchants").Range("B" & i).Value)
        merchant = Sheets("Merchants").Range("A" & i).Value

        For Each promocode In bot.FindElementByClass("main_vouchers").FindElementsByClass("c")

            number = Right(promocode.Attribute("id"), 6)

            If IsEmpty(promocode) = True Then Exit For

            promocode.FindElementByClass("go").Click

            #This is the part I have problems with as after click, original page re-directs to another page, and new tab opens (which is the place  I want focus on). Also, I need the original tab closed so that Chrome doesn't end up opening too many tabs due to the loop running. Appreciate the help!

        Next promocode

    Next i

End Sub
</code>```

Just need Selenium to switch focus onto newly opened tab and for old/original tab to be closed..

答:
The following works for me where you use switchToNextWindow and then you take 1 off the current window count (you might want to check more .windows.count > 1 first), and close that item in windows collection.

You can also .SwitchToWindowByName  and .SwitchToWindowByTitle if either of those are known in advance | can be extracted from the current page.

```<code>'Ensure latest applicable driver e.g. ChromeDriver.exe in Selenium folder
'VBE > Tools > References > Add reference to selenium type library
Public Sub Example()
    Dim d As WebDriver
    Set d = New ChromeDriver
    Const URL = "https://www.cuponation.com.sg/agoda-discount-code"

    With d
        .get URL
        Debug.Print .Window.Title
        .FindElementByCss(".go").Click
        .SwitchToNextWindow
        Debug.Print .URL   '<= includes voucher code
        'do something with new window
        Debug.Print .Window.Title
        .Windows.item(.Windows.Count - 1).Close 'close prior window
        Debug.Print .Window.Title
        Stop
        .Quit
    End With
End Sub
</code>```

Body:
I'm working on the Selenium Basic Wrapper for Excel VBA, but upon clicking  a button that opens a new tab, I am unable to get the selenium web-driver to switch focus onto the new tab that is opened, and to close the original tab.. Believe this should be achievable using the Java Selenium, but is there any way to do it through the Selenium Basic wrapper on excel VBA?

Have tried using bot.switchtopreviouswindow/nextwindow to no avail, Selenium does not even seem to detect the new tab/window opened as an existing window, also tried using switchwindow using title to no avail...

Private Sub CommandButton1_Click()

    Dim bot As New ChromeDriver
    Dim merchant As String
    Dim promocode As Object
    Dim number As Long
    Dim test As Object
    Dim testnumber As Integer

    lastColumn = Sheets("Merchants").Range("B" & Rows.Count).End(xlUp).Row

    For i = 2 To lastColumn

        bot.Get (Sheets("Merchants").Range("B" & i).Value)
        merchant = Sheets("Merchants").Range("A" & i).Value

        For Each promocode In bot.FindElementByClass("main_vouchers").FindElementsByClass("c")

            number = Right(promocode.Attribute("id"), 6)

            If IsEmpty(promocode) = True Then Exit For

            promocode.FindElementByClass("go").Click

            #This is the part I have problems with as after click, original page re-directs to another page, and new tab opens (which is the place  I want focus on). Also, I need the original tab closed so that Chrome doesn't end up opening too many tabs due to the loop running. Appreciate the help!

        Next promocode

    Next i

End Sub

Just need Selenium to switch focus onto newly opened tab and for old/original tab to be closed..

Body:
The following works for me where you use switchToNextWindow and then you take 1 off the current window count (you might want to check more .windows.count > 1 first), and close that item in windows collection.

You can also .SwitchToWindowByName  and .SwitchToWindowByTitle if either of those are known in advance | can be extracted from the current page.

'Ensure latest applicable driver e.g. ChromeDriver.exe in Selenium folder
'VBE > Tools > References > Add reference to selenium type library
Public Sub Example()
    Dim d As WebDriver
    Set d = New ChromeDriver
    Const URL = "https://www.cuponation.com.sg/agoda-discount-code"

    With d
        .get URL
        Debug.Print .Window.Title
        .FindElementByCss(".go").Click
        .SwitchToNextWindow
        Debug.Print .URL   '<= includes voucher code
        'do something with new window
        Debug.Print .Window.Title
        .Windows.item(.Windows.Count - 1).Close 'close prior window
        Debug.Print .Window.Title
        Stop
        .Quit
    End With
End Sub


问:
Gather result from different block of threads
I just started learning CUDA and I am really so confused about how to use GPU memory , the problem is that
I need to make each block (groupe of thread in the same block ) return his own result and copy it to CPU memory.

My question is :
Can I store result of each block in the shared memeory and then copy it to global memory ?
How can I gather the result of each one ?

I will be grateful if someone can help !

答:
Shared memory is per block, each block has a different instance of the shared buffer, and only the threads in that block have access to it.

If there is one value per block that needs to be copied to global memory, one thread in the block has to do the copy to global memory.

For example:

```<code>__global__ void gather(int* output) {
    __shared__ int shared_buffer[128];
    .... // threads in block work in shared_buffer
         // store output value for block in shared_buffer[0]

    __syncthreads();
    if(threadIdx.x == 0) output[blockIdx.x] = shared_buffer[0];
}
</code>```

Body:
Shared memory is per block, each block has a different instance of the shared buffer, and only the threads in that block have access to it.

If there is one value per block that needs to be copied to global memory, one thread in the block has to do the copy to global memory.

For example:

__global__ void gather(int* output) {
    __shared__ int shared_buffer[128];
    .... // threads in block work in shared_buffer
         // store output value for block in shared_buffer[0]

    __syncthreads();
    if(threadIdx.x == 0) output[blockIdx.x] = shared_buffer[0];
}


问:
How do I position different elements that are part of the same div element on the same line horizontally?
How do I position different elements that are part of the same div element on the same line horizontally? I want to create a navigation bar at the top of my website that contains the logo at the left, the search bar with the search button at the center and the login dropdown menu at the right but I'm not able to align the three elements, please help.

答:
Add this code the styles of your div:</p>

```<code>display: -webkit-box
display: flex
width: 100%
margin-right: auto
margin-left: auto
-webkit-box-pack: start
-webkit-justify-content: flex-start
-ms-flex-pack: start
justify-content: flex-start
-webkit-box-align: center
-webkit-align-items: center
-ms-flex-align: center
align-items: center
</code>```

Body:
Add this code the styles of your div:

display: -webkit-box
display: flex
width: 100%
margin-right: auto
margin-left: auto
-webkit-box-pack: start
-webkit-justify-content: flex-start
-ms-flex-pack: start
justify-content: flex-start
-webkit-box-align: center
-webkit-align-items: center
-ms-flex-align: center
align-items: center


问:
Keyboard disappears when you submit a form
I am making real time chat app and when user types something in an input and submits a form(clicks a send button) a keyboard (virtual keyboard on mobile devices) disappear.

I want to keep the keyboard opened.

<form class="panel" action="">
  <input type="text" class="message" id="message" autocomplete="off" spellcheck="false">

  <button type="submit" class="send" id="send"></button>
</form>
```

答:
let form = document.getElementById("form");
let input = form.children["input"];
let send = form.children["send"];

form.addEventListener("submit", (e) =>
{
    // Use Ajax to send the message to php page.
    if (input.value.length !== 0)
    {
        console.log(input.value);
    }

    // Reset the input:
    input.value = "";

    // Disable the submit:
    e.preventDefault();
});

send.addEventListener("focus", (e) =>
{
    input.focus();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="panel" id="form">
  <input name="input" type="text" class="message" autocomplete="off" spellcheck="false"/>
  <button name="send" class="send">S</button>
</form></code>```

Body:
let form = document.getElementById("form");
let input = form.children["input"];
let send = form.children["send"];

form.addEventListener("submit", (e) =>
{
    // Use Ajax to send the message to php page.
    if (input.value.length !== 0)
    {
        console.log(input.value);
    }

    // Reset the input:
    input.value = "";

    // Disable the submit:
    e.preventDefault();
});

send.addEventListener("focus", (e) =>
{
    input.focus();
});

<form class="panel" id="form">
  <input name="input" type="text" class="message" autocomplete="off" spellcheck="false"/>
  <button name="send" class="send">S</button>
</form>


问:
How can I add a border to an image that has padding?
I have an image on my webpage that I added padding to so it wouldn't be in the corner. I also wanted to give it a border but the border is showing up around the empty space instead of just the image... What am I doing wrong?

The image also has a float attribute.

```<code>img {
  float: right;
  width: 300px;
  padding: 25px;
  border-style: solid;
  border-color: #fdb924;
}
</code>```

答:
Give the image a margin instead of padding:

img {
  float: right;
  width: 300px;
  margin: 25px;
  border-style: solid;
  border-color: #fdb924;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://via.placeholder.com/250"></code>```

Body:
I have an image on my webpage that I added padding to so it wouldn't be in the corner. I also wanted to give it a border but the border is showing up around the empty space instead of just the image... What am I doing wrong?

The image also has a float attribute.

img {
  float: right;
  width: 300px;
  padding: 25px;
  border-style: solid;
  border-color: #fdb924;
}

Body:
Give the image a margin instead of padding:

img {
  float: right;
  width: 300px;
  margin: 25px;
  border-style: solid;
  border-color: #fdb924;
}

<img src="https://via.placeholder.com/250">


问:
How can I partition a RDD respecting order?
I would like to divide a RDD in a number of partitions corresponding to the number of different keys I found (3 in this case):

RDD: [(1,a), (1,b), (1,c), (2,d), (3,e), (3,f), (3,g), (3,h), (3,i)]

What I do now is that elements with the same key will fall into the same partition:

```<code>[(1,a), (1,b), (1,c)]
[(2,d)]
[(3,e), (3,f), (3,g), (3,h), (3,i)]
</code>```

This is how I partition

```<code>val partitionedRDD = rdd.partitionBy(new PointPartitioner(
     rdd.keys.distinct().count().asInstanceOf[Int]))
</code>```

This is PoinPartitioner class

```<code>class PointPartitioner(numParts: Int) extends org.apache.spark.Partitioner{

import org.apache.spark.Partitioner
  override def numPartitions: Int = numParts

  override def getPartition(key: Any): Int = {
    key.hashCode % numPartitions
  }

  override def equals(other: Any): Boolean = other match
  {
    case dnp: PointPartitioner =>
      dnp.numPartitions == numPartitions
    case _ =>
      false
  }
}
</code>```

However, elements are unbalanced across partitions. What I would like to obtain is a RDD partitioned like this, where all the partitions contain roughly the same number of elements, respecting the order of the keys:

```<code>[(1,a), (1,b), (1,c)]
[(2,d), (3,e), (3,f)]
[(3,g), (3,h), (3,i)]
</code>```

What could I try?

答:
Assigning your partitions like this

```<code>p1 [(1,a), (1,b), (1,c)]
p2 [(2,d), (3,e), (3,f)]
p3 [(3,g), (3,h), (3,i)]
</code>```

would mean that you would like to assign the same partition key to different partitions (for 3 it's p2 or p3). Just like for mathematical functions it cannot have many values for the same argument (what does the value depend on then?).

What you could do instead is adding something to your partition key which would result in having more buckets (effectively splitting one set into smaller sets). But you have no control (virtually) over how Spark places your partitions onto the nodes so the data which you wanted to be on the same node can span across multiple nodes.

That really boils down to what job you would like to perform. I would recommend considering what is the outcome you want to get and see if you can come up with some smart partition key with a reasonable tradeoff (if really necessary). Maybe you could hold values by the letter and then use operations like reduceByKey rather than the groupByKey to get your final results?

Body:
I would like to divide a RDD in a number of partitions corresponding to the number of different keys I found (3 in this case):

RDD: [(1,a), (1,b), (1,c), (2,d), (3,e), (3,f), (3,g), (3,h), (3,i)]

What I do now is that elements with the same key will fall into the same partition:

[(1,a), (1,b), (1,c)]
[(2,d)]
[(3,e), (3,f), (3,g), (3,h), (3,i)]

This is how I partition

val partitionedRDD = rdd.partitionBy(new PointPartitioner(
     rdd.keys.distinct().count().asInstanceOf[Int]))

This is PoinPartitioner class

class PointPartitioner(numParts: Int) extends org.apache.spark.Partitioner{

import org.apache.spark.Partitioner
  override def numPartitions: Int = numParts

  override def getPartition(key: Any): Int = {
    key.hashCode % numPartitions
  }

  override def equals(other: Any): Boolean = other match
  {
    case dnp: PointPartitioner =>
      dnp.numPartitions == numPartitions
    case _ =>
      false
  }
}

However, elements are unbalanced across partitions. What I would like to obtain is a RDD partitioned like this, where all the partitions contain roughly the same number of elements, respecting the order of the keys:

[(1,a), (1,b), (1,c)]
[(2,d), (3,e), (3,f)]
[(3,g), (3,h), (3,i)]

What could I try?

Body:
Assigning your partitions like this

p1 [(1,a), (1,b), (1,c)]
p2 [(2,d), (3,e), (3,f)]
p3 [(3,g), (3,h), (3,i)]

would mean that you would like to assign the same partition key to different partitions (for 3 it's p2 or p3). Just like for mathematical functions it cannot have many values for the same argument (what does the value depend on then?).

What you could do instead is adding something to your partition key which would result in having more buckets (effectively splitting one set into smaller sets). But you have no control (virtually) over how Spark places your partitions onto the nodes so the data which you wanted to be on the same node can span across multiple nodes.

That really boils down to what job you would like to perform. I would recommend considering what is the outcome you want to get and see if you can come up with some smart partition key with a reasonable tradeoff (if really necessary). Maybe you could hold values by the letter and then use operations like reduceByKey rather than the groupByKey to get your final results?


问:
Add strong typing for react navigation props
I'm using typescript in my react-native project(expo).

The project uses react-navigation, so on my screens I can set navigationOptions and I have access to the prop navigation.

Now I'm trying to strongly type these so I get hints for what properties are available to set.

```<code>interface NavStateParams {
    someValue: string
}

interface Props extends NavigationScreenProps<NavStateParams> {
   color: string
}

class Screen extends React.Component<Props, any> {
    // This works fine
    static navigationOptions: NavigationStackScreenOptions = {
        title: 'ScreenTitle'
    }
    // Does not work
    static navigationOptions: NavigationStackScreenOptions = ({navigation, screenProps }) => ({
        title: navigation.state.params.someValue
    })
}
</code>```

What would be the best way to handle react-navigation as props for components.

答:
Rather than describing manually all your navigation functions (e.g: navigate), in your Props' interface, you can directly extends NavigationScreenProps.

In my case it was mandatory to stop eslint from yielding an error.

```<code>import { StackNavigator, NavigationScreenProps } from 'react-navigation';

export interface HomeScreenProps extends NavigationScreenProps {
/* your custom props here */
};

export class HomeScreen extends React.Component<HomeScreenProps, object> {

  render() {
    return (
      <View style={styles.container}>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}
</code>```

Body:
I'm using typescript in my react-native project(expo).

The project uses react-navigation, so on my screens I can set navigationOptions and I have access to the prop navigation.

Now I'm trying to strongly type these so I get hints for what properties are available to set.

interface NavStateParams {
    someValue: string
}

interface Props extends NavigationScreenProps<NavStateParams> {
   color: string
}

class Screen extends React.Component<Props, any> {
    // This works fine
    static navigationOptions: NavigationStackScreenOptions = {
        title: 'ScreenTitle'
    }
    // Does not work
    static navigationOptions: NavigationStackScreenOptions = ({navigation, screenProps }) => ({
        title: navigation.state.params.someValue
    })
}

What would be the best way to handle react-navigation as props for components.

Body:
Rather than describing manually all your navigation functions (e.g: navigate), in your Props' interface, you can directly extends NavigationScreenProps.

In my case it was mandatory to stop eslint from yielding an error.

import { StackNavigator, NavigationScreenProps } from 'react-navigation';

export interface HomeScreenProps extends NavigationScreenProps {
/* your custom props here */
};

export class HomeScreen extends React.Component<HomeScreenProps, object> {

  render() {
    return (
      <View style={styles.container}>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}


问:
Nested query to unknown level GraphQL
I have a tree structure. Let's say Folder for example.

How do I query nested queries to N level using GraphQL.

Let's take an example as I have following properties in class.

```<code>public class DocumentField
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public List<DocumentField> Children { get; set; }
    }
</code>```

Server side is designed in a way that if children are there then it will include as children. But graphql layer is restricting it because my query which is following.

Following query will not bring result of children.

```<code>query ($folderId: Int!) {
                              folder(folderId: $folderId) {
                                id,
                                name
                              }
                            }
</code>```

Following query gives error as: nested query Field children of type DocumentFieldICollection must have a sub selection

```<code>query ($folderId: Int!) {
                          folder(folderId: $folderId) {
                            id,
                            name,
                            children
                          }
                        }
</code>```

答:
GraphQL does not allow to query such recursive structure down to all levels dynamically. You have to explicitly specify how many levels that you want to query. For example , to query to down 4 levels , the query looks liked :

```<code>query ($folderId: Int!) {
  folder(folderId: $folderId) {
    id
    name
    children {
       id
       name
       children{
          id
          name
          children{
            id
            name
          }
       }
    }
  }
 }
</code>```

You can use fragment to reduce some duplication in this query. For details , please see this.

Title: Nested query to unknown level GraphQL

Body:
I have a tree structure. Let's say Folder for example.

How do I query nested queries to N level using GraphQL.

Let's take an example as I have following properties in class.

public class DocumentField
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public List<DocumentField> Children { get; set; }
    }

Server side is designed in a way that if children are there then it will include as children. But graphql layer is restricting it because my query which is following.

Following query will not bring result of children.

query ($folderId: Int!) {
                              folder(folderId: $folderId) {
                                id,
                                name
                              }
                            }

Following query gives error as: nested query Field children of type DocumentFieldICollection must have a sub selection

query ($folderId: Int!) {
                          folder(folderId: $folderId) {
                            id,
                            name,
                            children
                          }
                        }

Body:
GraphQL does not allow to query such recursive structure down to all levels dynamically. You have to explicitly specify how many levels that you want to query. For example , to query to down 4 levels , the query looks liked :

query ($folderId: Int!) {
  folder(folderId: $folderId) {
    id
    name
    children {
       id
       name
       children{
          id
          name
          children{
            id
            name
          }
       }
    }
  }
 }

You can use fragment to reduce some duplication in this query. For details , please see this.


问:
Clipping UIImageView if is moved out of CGRect
I want to clip an UIImageView if it moves out of given rect.

The image is moving across the screen by setting the frame, but I need to clip it when it moves out of a given fixed rect (say (0,0,650,650)).

答:
If you only want to show the center of the image an a UIImageView set the content mode to "Aspect Fill" via IB. That will center it and crop off anything extra.

Or in code

```<code>myImageView.contentMode = UIViewContentModeScaleAspectFill;
</code>```

or

Subclass UIView and in the drawRect method, adjust the rect and draw out the clipped image using CGContextDrawImage (context, rect, sourceImage.CGImage).

or

Use CALayers. You can adjust the 'contentsRect' of the imageView's layer:

```<code>CALayer* imageLayer = imageView.layer;
imageLayer.masksToBounds = YES;
CGRect rect;
if (inPortrait)
  rect = CGRectMake(0.0, 0.0, 0.5, 1.0); // half size
else
  rect = CGRectMake(0.0, 0.0, 1.0, 1.0); // full size
imageLayer.contentsRect = rect;
</code>```

Body:
If you only want to show the center of the image an a UIImageView set the content mode to "Aspect Fill" via IB. That will center it and crop off anything extra.

Or in code

myImageView.contentMode = UIViewContentModeScaleAspectFill;

or

Subclass UIView and in the drawRect method, adjust the rect and draw out the clipped image using CGContextDrawImage (context, rect, sourceImage.CGImage).

or

Use CALayers. You can adjust the 'contentsRect' of the imageView's layer:

CALayer* imageLayer = imageView.layer;
imageLayer.masksToBounds = YES;
CGRect rect;
if (inPortrait)
  rect = CGRectMake(0.0, 0.0, 0.5, 1.0); // half size
else
  rect = CGRectMake(0.0, 0.0, 1.0, 1.0); // full size
imageLayer.contentsRect = rect;