问:
How to load CSS files and javascript files in Django?
When I am trying to extend the header and footer of base.html to index.html and about.html, I am unable to load CSS and javascript files.

Here is my code.

I have Included django.contrib.staticfiles in INSTALLED_APPS. Also, I have defined STATIC_URL

setting.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'gadget/static')
]
</code>```

I am trying to extend the header and footer to index.html and about.html

base.html

```<code>{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link href="https://fonts.googleapis.com/css?family=Muli:300,400,500,600,700,800,900&display=swap" rel="stylesheet">

<!--     Css Styles-->
     <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/themify-icons.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/elegant-icons.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/owl.carousel.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/nice-select.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/slicknav.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/style.css'%}" />

    <title>e-Gadget</title>
</head>
<body>
<!-- Header Section Begin -->
    <header class="header-section">

        <div class="container">
            <div class="inner-header">
                <div class="row">
                    <div class="col-lg-2 col-md-2">
                        <div class="logo">
                            <a href="./index.html">
                                <img src="img/logo.png" alt="">
                            </a>
                        </div>
                    </div>
                    <div class="col-lg-7 col-md-7">
                        <div class="advanced-search">
                            <button type="button" class="category-btn">All Categories</button>
                            <div class="input-group">
                                <input type="text" placeholder="Search here">
                                <button type="button"><i class="ti-search"></i></button>
                            </div>
                        </div>
                    </div>

                <!--
                    <div class="col-lg-3 text-right col-md-3">
                        <ul class="nav-right">
                            <li class="cart-icon">
                                <a href="#">
                                    <i class="icon_bag_alt"></i>
                                    <span>3</span>
                                </a>
                                <div class="cart-hover">
                                    <div class="select-items">
                                        <table>
                                        </table>
                                    </div>
                                    <div class="select-button">
                                        <a href="./shopping-cart.html" class="primary-btn view-card">VIEW CARD</a>
                                        <a href="./check-out.html" class="primary-btn checkout-btn">CHECK OUT</a>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                     -->

                </div>
            </div>
        </div>
        <div class="nav-item">
            <div class="container">
                <nav class="nav-menu mobile-menu">
                    <ul>
                        <li class="active"><a href="./index.html">Home</a></li>
                        <li><a href="./shop.html">Shop</a></li>
                        <li><a href="./contact.html">Contact</a></li>
                        <li><a href="./login.html">Login</a></li>
                        <li><a href="./register.html">Register</a></li>
                    </ul>
                </nav>
                <div id="mobile-menu-wrap"></div>
            </div>
        </div>
    </header>

 {% block content %}  {% endblock %}

 <!-- Footer Section Begin -->
    <footer class="footer-section">
        <div class="container">
            <div class="row">
                <div class="col-lg-3">
                    <div class="footer-left">
                        <div class="footer-logo">
                            <a href="#"><img src="img/footer-logo.png" alt=""></a>
                        </div>
                        <ul>
                            <li>Address: 44600 Kathmandu, Nepal</li>
                            <li>Phone: +977 9876543210</li>
                            <li>Email: electronicgadget@gmail.com</li>
                        </ul>
                        <div class="footer-social">
                            <a href="#"><i class="fa fa-facebook"></i></a>
                            <a href="#"><i class="fa fa-instagram"></i></a>
                            <a href="#"><i class="fa fa-twitter"></i></a>
                            <a href="#"><i class="fa fa-pinterest"></i></a>
                        </div>
                    </div>
                </div>
                <div class="col-lg-2 offset-lg-1">
                    <div class="footer-widget">
                        <h5>Information</h5>
                        <ul>
                            <li><a href="./contact.html">About Us</a></li>
                            <li><a href="./contact.html">Contact</a></li>
                        </ul>
                    </div>
                </div>

            </div>
        </div>
        <div class="copyright-reserved">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <script src="{% static 'js/jquery-3.3.1.min.js'%}"></script>
    <script src="{% static 'js/bootstrap.min.js'%}"></script>
    <script src="{% static 'js/jquery-ui.min.js'%}"></script>
    <script src="{% static 'js/jquery.countdown.min.js'%}"></script>
    <script src="{% static 'js/jquery.nice-select.min.js'%}"></script>
    <script src="{% static 'js/jquery.zoom.min.js'%}"></script>
    <script src="{% static 'js/jquery.dd.min.js'%}"></script>
    <script src="{% static 'js/jquery.slicknav.js'%}"></script>
    <script src="{% static 'js/owl.carousel.min.js'%}"></script>
    <script src="{% static 'js/main.js'%}"></script>
    <script src="{% static 'js/imagesloaded.pkgd.min.js'%}"></script>
</body>
</html>
</code>```

index.html

```<code>{% extends 'base.html' %}

{% block content %}
<h1> hello</h1>
{% endblock %}
</code>```

Here is my project hierarchy

答:
You've specified that your static files are under your apps directory in your settings.py file.

Make sure you have stored your static files in your app folder.

You will have a hierarchy like this:

```<code>-Project root folder

    -App folder
               -static (keep your static files in here)

    -Project folder
                   - __init__.py
                   - decorators.py
                   - settings.py
                   - urls.py
                   - wsgi.py
</code>```

I would remove staticfiles_dirs or comment out to test.

Body:
When I am trying to extend the header and footer of base.html to index.html and about.html, I am unable to load CSS and javascript files.

Here is my code.

I have Included django.contrib.staticfiles in INSTALLED_APPS. Also, I have defined STATIC_URL

setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'gadget/static')
]

I am trying to extend the header and footer to index.html and about.html

base.html

{% load static %}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link href="https://fonts.googleapis.com/css?family=Muli:300,400,500,600,700,800,900&display=swap" rel="stylesheet">

     <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/font-awesome.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/themify-icons.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/elegant-icons.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/owl.carousel.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/nice-select.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/slicknav.min.css'%}" />
     <link rel="stylesheet" type="text/css" href="{% static 'css/style.css'%}" />

    <title>e-Gadget</title>

                            <button type="button" class="category-btn">All Categories</button>

                                <input type="text" placeholder="Search here">
                                <button type="button"></button>

Home

Shop

Contact

Login

Register

 {% block content %}  {% endblock %}

Address: 44600 Kathmandu, Nepal

Phone: +977 9876543210

Email: electronicgadget@gmail.com

Information

About Us

Contact

index.html

{% extends 'base.html' %}

{% block content %}

 hello

{% endblock %}

Here is my project hierarchy

Body:
You've specified that your static files are under your apps directory in your settings.py file.

Make sure you have stored your static files in your app folder.

You will have a hierarchy like this:

-Project root folder

    -App folder
               -static (keep your static files in here)

    -Project folder
                   - __init__.py
                   - decorators.py
                   - settings.py
                   - urls.py
                   - wsgi.py

I would remove staticfiles_dirs or comment out to test.


来源: stackexchange

问:
WildFly 10 do deploy bug
I am using the latest version of WildFly, which is WildFly 10.0.0 final, and I am encountring a problem in deployment a folder which I am not facing when using WildFly 8.

My problem is that I have a web application folder and when I try to deploy it I get this error message:

Deployment of '***.war' requested, but the deployment is not present.

I am sure that I am following the right instructions to deploy my application as it was deployed using WildFly 8 but not WildFly 9 and 10.

These are the instructions that I'm following to deploy my application:

Copy the web application folder to the standalone/deploymentsfolder,

rename my folder to XXX.war.dodeploy,

then go back to bin folder and run the standalone.bat file.

But I get either nothing or a message saying Deployment of '***.war' requested, but the deployment is not present.

答:
I had the same issue and the actual problem was that the name of the folder didn't match the name of dedeploy file.  If you're deploying an ear, or war, etc make sure the dodeploy files have the same exact name (except the dodeploy extension).  For example, assume we're deploying

default_blah_1.0.ear           <--- This is your folder

default_blah_1.0.ear.dodeploy  <-- this is your flag file (make sure the .ear is in there)

ContentLicense: CC BY-SA 3.0

Title: WildFly 10 do deploy bug

ContentLicense: CC BY-SA 4.0


问:
In C++ what is the point of std::array if the size has to be determined at compile time?
Pardon my ignorance, it appears to me that std::array is meant to be an STL replacement for your regular arrays. But because the array size has to be passed as a template parameter, it prevents us from creating std::array with a size known only at runtime.

```<code>std::array<char,3> nums {1,2,3}; // Works.

constexpr size_t size = 3;
std::array<char,size> nums {1,2,3}; // Works.

const buf_size = GetSize();
std::array<char, buf_size> nums; // Doesn't work.
</code>```

I would assume that one very important use case for an array in C++ is to create a fixed size data structure based on runtime inputs (say allocating buffer for reading files).

The workarounds I use for this are:

```<code>// Create a array pointer for on-the-spot usecases like reading from a file.
char *data = new char[size];
...
delete[] data;
</code>```

or:

```<code>// Use unique_ptr as a class member and I don't want to manage the memory myself.
std::unique_ptr<char[]> myarr_ = std::unique_ptr<char[]>(new char[size]);
</code>```

If I don't care about fixed size, I am aware that I can use std::vector<char> with the size pre-defined as follows:

```<code>std::vector<char> my_buf (buf_size);
</code>```

Why did the designers of std::array choose to ignore this use case? Perhaps I don't understand the real usecase for std::array.

EDIT: I guess another way to phrase my question could also be - Why did the designers choose to have the size passed as a template param and not as a constructor param? Would opting for the latter have made it difficult to provide the functionality that std::array currently has? To me it seems like a deliberate design choice and I don't understand why.

答:
The two main reasons I understand are:

std::array implements STL's interfaces for collection-types, allowing an std::array to be passed as-is to functions and methods that accept any STL iterator.

To prevent array pointer decay... (below)

...this is the preservation of type information across function/method boundaries because it prevents Array Pointer Decay.

Given a naked C/C++ array, you can pass it to another function as a parameter argument by 4 ways:

```<code>void by_value1   ( const T* array )
void by_value2   ( const T array[] )
void by_pointer  ( const T (*array)[U] )
void by_reference( const T (&array)[U] )
</code>```

by_value1 and by_value2 are both semantically identical and cause pointer decay because the receiving function does not know the sizeof the array.

by_pointer and by_reference both requires that U by a known compile-time constant, but preserve sizeof information.

So if you avoid array decay by using by_pointer or by_reference you now have a maintenance problem every time you change the size of the array you have to manually update all of the call-sites that have that size in U.

By using std::array it's taken care of for you by making those functions template functions where U is a parameter (granted, you could still use the by_pointer and by_reference techniques but with messier syntax).

...so std::array adds a 5th way:

```<code>template<typename T, size_t N>
void by_stdarray( const std::array<T,N>& array )
</code>```

Body:
Pardon my ignorance, it appears to me that std::array is meant to be an STL replacement for your regular arrays. But because the array size has to be passed as a template parameter, it prevents us from creating std::array with a size known only at runtime.

std::array<char,3> nums {1,2,3}; // Works.

constexpr size_t size = 3;
std::array<char,size> nums {1,2,3}; // Works.

const buf_size = GetSize();
std::array<char, buf_size> nums; // Doesn't work.

I would assume that one very important use case for an array in C++ is to create a fixed size data structure based on runtime inputs (say allocating buffer for reading files).

The workarounds I use for this are:

// Create a array pointer for on-the-spot usecases like reading from a file.
char *data = new char[size];
...
delete[] data;

or:

// Use unique_ptr as a class member and I don't want to manage the memory myself.
std::unique_ptr<char[]> myarr_ = std::unique_ptr<char[]>(new char[size]);

If I don't care about fixed size, I am aware that I can use std::vector<char> with the size pre-defined as follows:

std::vector<char> my_buf (buf_size);

Why did the designers of std::array choose to ignore this use case? Perhaps I don't understand the real usecase for std::array.

EDIT: I guess another way to phrase my question could also be - Why did the designers choose to have the size passed as a template param and not as a constructor param? Would opting for the latter have made it difficult to provide the functionality that std::array currently has? To me it seems like a deliberate design choice and I don't understand why.

Body:
The two main reasons I understand are:

std::array implements STL's interfaces for collection-types, allowing an std::array to be passed as-is to functions and methods that accept any STL iterator.

To prevent array pointer decay... (below)

...this is the preservation of type information across function/method boundaries because it prevents Array Pointer Decay.

Given a naked C/C++ array, you can pass it to another function as a parameter argument by 4 ways:

void by_value1   ( const T* array )
void by_value2   ( const T array[] )
void by_pointer  ( const T (*array)[U] )
void by_reference( const T (&array)[U] )

by_value1 and by_value2 are both semantically identical and cause pointer decay because the receiving function does not know the sizeof the array.

by_pointer and by_reference both requires that U by a known compile-time constant, but preserve sizeof information.

So if you avoid array decay by using by_pointer or by_reference you now have a maintenance problem every time you change the size of the array you have to manually update all of the call-sites that have that size in U.

By using std::array it's taken care of for you by making those functions template functions where U is a parameter (granted, you could still use the by_pointer and by_reference techniques but with messier syntax).

...so std::array adds a 5th way:

template<typename T, size_t N>
void by_stdarray( const std::array<T,N>& array )


问:
Invalid Resource and malformed policy errors - aws cloudformation YAML
Addig bucketpolicy for a s3 Bucket. But am running into multiple problems defining it in YAML. Here is the sample -

```<code> S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest]]
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest
</code>```

S3BucketTest is the resource name of s3 bucket I defined in the same cft

```<code>S3BucketTest:
  Type: AWS::S3::Bucket
</code>```

I was able to create s3 bucket without any issues, but the bucketpolicy giving errors.

For the above yaml, it says that resource name is invalid.

If I have multiple Actions and I mention them in [], it throws invalid Acttions and malformed policy error.

I alo want to mention multiple resources.

I am essentially looking to replicatee this in YAML -

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "stmt_cross_acct_rs_Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": ["arn:aws:iam::12345678:role/role_rs_1", "arn:aws:iam::12345678:root"]
            },
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<demo-bucket>",
                "arn:aws:s3:::<demo-bucket>/*"
            ]
        }
    ]
}
</code>```

答:
This works for me. I was able to create the stack. I only had to change join to sub.

```<code>AWSTemplateFormatVersion: '2010-09-09'
Resources:
  S3BucketTest:
    Type: AWS::S3::Bucket
  S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource:
              - !Sub 'arn:aws:s3:::${S3BucketTest}'
              - !Sub 'arn:aws:s3:::${S3BucketTest}/*'
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest
</code>```

Hope this helps.

Body:
Addig bucketpolicy for a s3 Bucket. But am running into multiple problems defining it in YAML. Here is the sample -

 S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest]]
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest

S3BucketTest is the resource name of s3 bucket I defined in the same cft

S3BucketTest:
  Type: AWS::S3::Bucket

I was able to create s3 bucket without any issues, but the bucketpolicy giving errors.

For the above yaml, it says that resource name is invalid.

If I have multiple Actions and I mention them in [], it throws invalid Acttions and malformed policy error.

I alo want to mention multiple resources.

I am essentially looking to replicatee this in YAML -

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "stmt_cross_acct_rs_Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": ["arn:aws:iam::12345678:role/role_rs_1", "arn:aws:iam::12345678:root"]
            },
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListBucketMultipartUploads",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::<demo-bucket>",
                "arn:aws:s3:::<demo-bucket>/*"
            ]
        }
    ]
}

Body:
This works for me. I was able to create the stack. I only had to change join to sub.

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  S3BucketTest:
    Type: AWS::S3::Bucket
  S3CURBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 's3:ListBucket'
            Resource:
              - !Sub 'arn:aws:s3:::${S3BucketTest}'
              - !Sub 'arn:aws:s3:::${S3BucketTest}/*'
            Effect: Allow
            Condition:
              StringEquals:
                'AWS:SourceAccount':
                  - 12334456676
            Principal: '*'
      Bucket: !Ref S3BucketTest

Hope this helps.


问:
How to deploy a Java Japplet in iWeb developed on my Macbook?
I am building a website using iWeb on my Mac (latest versions of everything)
I am using the Html Snippet Widget to embed the applet tag.

Since iWeb does not seem to have any specific support for Java applets, my plan was to just publish the tag and then send over the required Jar file afterward.

However I can't get past the "apply" - because after I press apply, iWeb just hangs indefinitely.

Here is the tag...

<applet code="myApplet.class" codebase="java/" width="1000" height="700"  archive="myArchive.jar"

  <parameter name="example" value="morestuff">

  <parameter name="title" value="some text">

</applet>

I am seeing some interesting messages in the console about MalformedUrLException - unsupported protocol iweb-widget

Has anyone had any luck deploying applets using iWeb?

Any guidance would be greatly appreciated

Thanks, Victor

答:
I was trying to put applets generated from my (very noob) "Processing" code into an iWeb site on MobileMe.

The Processing environment produces the .jar file and some applet tag in an index.htm file. In iWeb, I copied the applet tag stuff from the index.htm file and pasted it into the HTML Snippet widget.

The problem was where to put the .jar file. Putting it anywhere in the MobileMe storage space didn't work, no matter what I typed into the applet tag, so I dropped it into a dropbox (dropbox.com, free), copied the public link from the dropbox and replaced all instances of 'filename.jar' in the html in the snippet widget with the public link to the file in my dropbox.

Probably a proper shoddy way to do it, but it works.

It's here, if it helps...

ContentLicense: CC BY-SA 2.5


问:
How to send image from back-end in your web push notifications?
I am using web-push library to send push notification using node server. For now, I am only able to send title from the back-end. Is there any way to send image from the back end?</p>

答:
This is example function that send a notification with image:

```<code>function sendPushNotification(req, res) {
  const subscriptionId = req.params.id;
  const pushSubscription = subscriptions[subscriptionId];
  webpush
    .sendNotification(
      pushSubscription,
      JSON.stringify({
        title: "your title",
        text: "your text",
        image: "path/to/image.jpg",
        tag: "new...",
        url: "/your-url.html"
      })
    )
    .catch(err => {
      console.log(err);
    });

  res.status(202).json({});
}
</code>```

this is from Lorenzo Spyna that explains how do it in this tutorial and you can see all code in this project of github

Body:
This is example function that send a notification with image:

function sendPushNotification(req, res) {
  const subscriptionId = req.params.id;
  const pushSubscription = subscriptions[subscriptionId];
  webpush
    .sendNotification(
      pushSubscription,
      JSON.stringify({
        title: "your title",
        text: "your text",
        image: "path/to/image.jpg",
        tag: "new...",
        url: "/your-url.html"
      })
    )
    .catch(err => {
      console.log(err);
    });

  res.status(202).json({});
}

this is from Lorenzo Spyna that explains how do it in this tutorial and you can see all code in this project of github


问:
What is "runtime compilation" in Javascript?
I'm reading this article on regular expressions, and it says "Using the constructor function provides runtime compilation of the regular expression". It then says "Use the constructor function when you know the regular expression pattern will be changing". What I want to know is, what exactly is runtime compilation in Javascript?</p>

答:
It means that when you use the /ab+c/; the regexp es compiled when the script is loaded and before it's used but if you use the constructor it is compiled just before that line is executed.

Using the constructor is useful, for example, when you want to build the regexp using a variable: new  RegExp('ab+' + value);


问:
RSSI Smoothing using LQI in Android
I am making an application that centers around an easily readable RSSI value. Currently the RSSI jumps around too much for my use case (i.e. being able to tell if the signal is getting stronger or weaker as I walk around) I have built a sample application using Kalman filters, but would also like to test the Improved Fusion Filter found in section 3.6 of this paper https://journals.sagepub.com/doi/full/10.1155/2015/195297.

Unfortunately this requires LQI measurements from the beacon. I believe this is sent in byte offset 16 of the eddystone encrypted TLM frame but I am not sure. Is there another way to calculate or read LQI on android?

答:
From your linked paper:

Given that LQI is a superior metric, it should not be forgotten that it is only made available by 802.15.4 compliant devices. It therefore makes sense to use RSSI as much as possible.

No where in the current Android Compatibility Definition Document for Android 10 - Bluetooth section does it state compatibility with that standard. If any Android device does so, it would be have to be specifically setup by manufacturer.

Title: RSSI Smoothing using LQI in Android


问:
java http request Required String parameter 'Username' is not present
I have a spring boot server running that accepts http request.
I have tested it extensively with curl and it works perfectly.
However when I try to send a request and receive a response in a java client I get:

java.io.IOException: Server returned HTTP response code: 400 for URL:

and on the server side I get:

[org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'Username' is not present]

Here is the spring boot method I am trying to use:

```<code>@PostMapping(path="/CreateAccount") // Map ONLY POST Requests
  public @ResponseBody String CreateUser (@RequestParam String Username
                                        , @RequestParam String Password) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request
    //make sure the username and password is valid input
      if (!validateInput(Username) || !validateInput(Password))
      {
          return "Username and Password cannot be blank";
      }
    //make sure the username is unique
      //check if Username is equal to any other User's username
      User u = findByUsername(Username);
      //if a user was found in the table
      if ( !(u == null) )
      {
          return "Username already taken\nPlease choose another";
      }

      //if we are here we are clear to make a new user
    User n = new User();
    n.setUsername(Username);
    n.setPassword(Password);
    n.setRole("Player");
    userRepository.save(n);

    //THIS CAUSES AN ERROR
    //create a stat object to be added to the table
    Stats s = new Stats();
    s.setUsername(Username);
    statRepository.save(s);

    //create a token for the user
    String usrToken = createToken(tokenSize);
    //add the username and token to hashmap
    userTokens.put(Username, usrToken);

    //return this user's token
    return usrToken;
  }
</code>```

And here is my client:

```<code>public static void CreateAccount(String username, String password)
    {
        try
        {
            String s = serverURL + "/CreateAccount";
            URL url = new URL(s);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setDoOutput(true);

            String json = "[{\n\"Username\"=\"Jake\",\"Password\"=\"123\"\n}]";
            System.out.println(json);

            OutputStream os = connection.getOutputStream();
            DataOutputStream out = new DataOutputStream( os );
            byte[] input = json.getBytes("utf-8");

            out.writeUTF(json);

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = br.readLine();
            System.out.println(response);

        }
        catch (Exception e)
        {
            System.out.println("#");
            System.out.println(e);
        }
    }
</code>```

I thought it had to do with my json formatting but I've tried over and over and no matter how I format it I get the same error.

答:
If you want send json object, use this code for example:</p>

```<code>@PostMapping(path="/CreateAccount")
public @ResponseBody String CreateUser (@RequestBody User user) {

    if (user == null)
    {
        return "User cannot be blank";
    }

    User u = findByUsername(user.Username);

    // your code...

    return usrToken;
}
</code>```

Body:
I have a spring boot server running that accepts http request.
I have tested it extensively with curl and it works perfectly.
However when I try to send a request and receive a response in a java client I get:

java.io.IOException: Server returned HTTP response code: 400 for URL:

and on the server side I get:

[org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'Username' is not present]

Here is the spring boot method I am trying to use:

@PostMapping(path="/CreateAccount") // Map ONLY POST Requests
  public @ResponseBody String CreateUser (@RequestParam String Username
                                        , @RequestParam String Password) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request
    //make sure the username and password is valid input
      if (!validateInput(Username) || !validateInput(Password))
      {
          return "Username and Password cannot be blank";
      }
    //make sure the username is unique
      //check if Username is equal to any other User's username
      User u = findByUsername(Username);
      //if a user was found in the table
      if ( !(u == null) )
      {
          return "Username already taken\nPlease choose another";
      }

      //if we are here we are clear to make a new user
    User n = new User();
    n.setUsername(Username);
    n.setPassword(Password);
    n.setRole("Player");
    userRepository.save(n);

    //THIS CAUSES AN ERROR
    //create a stat object to be added to the table
    Stats s = new Stats();
    s.setUsername(Username);
    statRepository.save(s);

    //create a token for the user
    String usrToken = createToken(tokenSize);
    //add the username and token to hashmap
    userTokens.put(Username, usrToken);

    //return this user's token
    return usrToken;
  }

And here is my client:

public static void CreateAccount(String username, String password)
    {
        try
        {
            String s = serverURL + "/CreateAccount";
            URL url = new URL(s);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setDoOutput(true);

            String json = "[{\n\"Username\"=\"Jake\",\"Password\"=\"123\"\n}]";
            System.out.println(json);

            OutputStream os = connection.getOutputStream();
            DataOutputStream out = new DataOutputStream( os );
            byte[] input = json.getBytes("utf-8");

            out.writeUTF(json);

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String response = br.readLine();
            System.out.println(response);

        }
        catch (Exception e)
        {
            System.out.println("#");
            System.out.println(e);
        }
    }

I thought it had to do with my json formatting but I've tried over and over and no matter how I format it I get the same error.

Body:
If you want send json object, use this code for example:

@PostMapping(path="/CreateAccount")
public @ResponseBody String CreateUser (@RequestBody User user) {

    if (user == null)
    {
        return "User cannot be blank";
    }

    User u = findByUsername(user.Username);

    // your code...

    return usrToken;
}


问:
Code::Blocks, and C++ Compiler problem. cant compile a header
im having problem when compiling C++ source code. that code is a keylogger. at first, i save with .cpp, and try to compile it from terminal using this command

```<code>g++ test.cpp
</code>```

and then the terminal showed me this messages

```<code>test.cpp:1:10: fatal error: conio.h: No such file or directory
#include <conio.h>
         ^~~~~~~~~
compilation terminated.
</code>```

and this message

```<code>test.cpp:2:10: fatal error: windows.h: No such file or directory
#include <windows.h>
         ^~~~~~~~~~~
compilation terminated.
</code>```

to fix this, i tried to use a C++ IDE, code::blocks. installed from terminal, and the copy that keylogger source code to code:::blocks. but the IDE shows this message

```<code>||=== Build file: Debug in Belajar CPP (compiler: GNU GCC Compiler) ===|
/home/lucky/test.cpp|1|fatal error: conio.h: No such file or directory|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
</code>```

I just don't know how to fix this and how to search the solutions online. because I'm new in using Linux-Mint. Can someone help me to fix this?

答:
First of all, conio.h and windows.h these headers are not supported on linux console.

Alternative is to use NCurses library. It does all the Console realted stuff you could want and is part of the Linux Standard Base ( i.e. available in every distro ).

Include 'ncurses.h' instead.

I hope this will resolve your issue.

Body:
im having problem when compiling C++ source code. that code is a keylogger. at first, i save with .cpp, and try to compile it from terminal using this command

g++ test.cpp

and then the terminal showed me this messages

test.cpp:1:10: fatal error: conio.h: No such file or directory
#include <conio.h>
         ^~~~~~~~~
compilation terminated.

and this message

test.cpp:2:10: fatal error: windows.h: No such file or directory
#include <windows.h>
         ^~~~~~~~~~~
compilation terminated.

to fix this, i tried to use a C++ IDE, code::blocks. installed from terminal, and the copy that keylogger source code to code:::blocks. but the IDE shows this message

||=== Build file: Debug in Belajar CPP (compiler: GNU GCC Compiler) ===|
/home/lucky/test.cpp|1|fatal error: conio.h: No such file or directory|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I just don't know how to fix this and how to search the solutions online. because I'm new in using Linux-Mint. Can someone help me to fix this?


问:
Map as.numeric to only specific columns of a dataframe
I have some data in the format below, where all columns are of type chr.

```<code>#> # A tibble: 3 x 4
#>   id    age   name  income
#>   <chr> <chr> <chr> <chr>
#> 1 1     18    jim   100
#> 2 2     21    bob   200
#> 3 3     16    alice 300
</code>```

I'd like to use as.numeric() on only some columns. Preferably, I'd like to define a vector of column names and then use purrr:map to map as.numeric() to only those columns:

```<code>numeric_variables <- c("id", "age", "income")
</code>```

How can I map that?

My desired output would look like:

df
#> # A tibble: 3 x 4
#>      id   age name  income
#>   <dbl> <dbl> <chr>  <dbl>
#> 1     1    18 jim      100
#> 2     2    21 bob      200
#> 3     3    16 alice    300
```

<p>Code for data entry below. </p>

<pre class="lang-r prettyprint-override"><code>library(purrr)
df <- data.frame(stringsAsFactors=FALSE,
          id = c(1, 2, 3),
         age = c(18, 21, 16),
        name = c("jim", "bob", "alice"),
      income = c(100, 200, 300)
)
df <- map_df(df, as.character)
df

</code>```

Created on 2020-02-15 by the reprex package (v0.3.0)

答:
We can use mutate_at

```<code>library(dplyr)
df %>%
  mutate_at(vars(numeric_variables), as.numeric) %>%
  as_tibble
# A tibble: 3 x 4
#     id   age name  income
#  <dbl> <dbl> <chr>  <dbl>
#1     1    18 jim      100
#2     2    21 bob      200
#3     3    16 alice    300
</code>```

Or more easily

```<code>df %>%
    type.convert(as.is = TRUE)
</code>```

Or with map

```<code>library(purrr)
df %>%
   map_if(names(.) %in% numeric_variables, as.numeric) %>%
   bind_cols
# A tibble: 3 x 4
#     id   age name  income
#  <dbl> <dbl> <chr>  <dbl>
#1     1    18 jim      100
#2     2    21 bob      200
#3     3    16 alice    300
</code>```

Or if we use the compound assignment operator (%<>%), this can be assigned in place

```<code>library(magrittr)
df %<>%
   map_if(names(.) %in% numeric_variables, as.numeric) %<>%
   bind_cols
str(df)
#tibble [3 × 4] (S3: tbl_df/tbl/data.frame)
# $ id    : num [1:3] 1 2 3
# $ age   : num [1:3] 18 21 16
# $ name  : chr [1:3] "jim" "bob" "alice"
#  $ income: num [1:3] 100 200 300
</code>```

Body:
I have some data in the format below, where all columns are of type chr.

#> # A tibble: 3 x 4
#>   id    age   name  income
#>   <chr> <chr> <chr> <chr>
#> 1 1     18    jim   100
#> 2 2     21    bob   200
#> 3 3     16    alice 300

I'd like to use as.numeric() on only some columns. Preferably, I'd like to define a vector of column names and then use purrr:map to map as.numeric() to only those columns:

numeric_variables <- c("id", "age", "income")

How can I map that?

My desired output would look like:

df
#> # A tibble: 3 x 4
#>      id   age name  income
#>   <dbl> <dbl> <chr>  <dbl>
#> 1     1    18 jim      100
#> 2     2    21 bob      200
#> 3     3    16 alice    300

Code for data entry below.

library(purrr)
df <- data.frame(stringsAsFactors=FALSE,
          id = c(1, 2, 3),
         age = c(18, 21, 16),
        name = c("jim", "bob", "alice"),
      income = c(100, 200, 300)
)
df <- map_df(df, as.character)
df

Created on 2020-02-15 by the reprex package (v0.3.0)

Body:
We can use mutate_at

library(dplyr)
df %>%
  mutate_at(vars(numeric_variables), as.numeric) %>%
  as_tibble
# A tibble: 3 x 4
#     id   age name  income
#  <dbl> <dbl> <chr>  <dbl>
#1     1    18 jim      100
#2     2    21 bob      200
#3     3    16 alice    300

Or more easily

df %>%
    type.convert(as.is = TRUE)

Or with map

library(purrr)
df %>%
   map_if(names(.) %in% numeric_variables, as.numeric) %>%
   bind_cols
# A tibble: 3 x 4
#     id   age name  income
#  <dbl> <dbl> <chr>  <dbl>
#1     1    18 jim      100
#2     2    21 bob      200
#3     3    16 alice    300

Or if we use the compound assignment operator (%<>%), this can be assigned in place

library(magrittr)
df %<>%
   map_if(names(.) %in% numeric_variables, as.numeric) %<>%
   bind_cols
str(df)
#tibble [3 × 4] (S3: tbl_df/tbl/data.frame)
# $ id    : num [1:3] 1 2 3
# $ age   : num [1:3] 18 21 16
# $ name  : chr [1:3] "jim" "bob" "alice"
#  $ income: num [1:3] 100 200 300


答:
You can use map_at

```<code>df[] <- purrr::map_at(df, numeric_variables, as.numeric)
df
# A tibble: 3 x 4
#     id   age name  income
#  <dbl> <dbl> <chr>  <dbl>
#1     1    18 jim      100
#2     2    21 bob      200
#3     3    16 alice    300
</code>```

Title: Map as.numeric to only specific columns of a dataframe

Body:
You can use map_at

df[] <- purrr::map_at(df, numeric_variables, as.numeric)
df
# A tibble: 3 x 4
#     id   age name  income
#  <dbl> <dbl> <chr>  <dbl>
#1     1    18 jim      100
#2     2    21 bob      200
#3     3    16 alice    300


问:
swift - Dismiss presenting view controller without dismissing navigation controller?
I am trying to dismiss a modal and push a new view controller from the navigation controller, but the code bellow dismisses the navigation controller as well, so there is nothing to push to and the window collapses. This code is inside my routing class:

```<code>    func navigateToVC() {
        self.navigationController.presentingViewController.dismiss(animated: false, completion: nil)
        self.navigationController.pushViewController(newVC, animated: false)
    }
</code>```

So is there a way to dismiss the presenting view controllers while keeping the navigation controller?

答:
Use this to dismiss presented ViewController,

```<code>self.dismiss(animated: true)
</code>```

Once you dismiss it , that's where you should push ViewController. You can't push after you dismiss your viewController because it's deallocated already.

I recommend creating a delegate and call it from your HomeViewController

Body:
I am trying to dismiss a modal and push a new view controller from the navigation controller, but the code bellow dismisses the navigation controller as well, so there is nothing to push to and the window collapses. This code is inside my routing class:

    func navigateToVC() {
        self.navigationController.presentingViewController.dismiss(animated: false, completion: nil)
        self.navigationController.pushViewController(newVC, animated: false)
    }

So is there a way to dismiss the presenting view controllers while keeping the navigation controller?

Body:
Use this to dismiss presented ViewController,

self.dismiss(animated: true)

Once you dismiss it , that's where you should push ViewController. You can't push after you dismiss your viewController because it's deallocated already.

I recommend creating a delegate and call it from your HomeViewController


问:
Delete row based on id from another row in another table postgresql
In my test.users table, I have

```<code>id | email         | first_name
1  | john@site.com | John
2  | bob@site.com  | Bob
</code>```

In my test.questions table, I have

```<code>id  | user_id | answer
10  | 1       | true
11  | 2       | false
</code>```

I want to delete the row in test.questions where the user_id matches the id in test.users for one specific user only.

For example, if I want to delete the row with id 10 from test.questions (since that row corresponds to john@site.com in test.users), I can do

```<code>DELETE FROM test.questions WHERE answer = true AND user_id = 1
</code>```

This will delete only the row with id = 10 from test.questions, which is what I want.

The problem is that I don't want to hardcode the id.  I want to hardcode just the user's email in the query, and get the id dynamically.  Something like

```<code>DELETE FROM test.questions WHERE answer = true AND user_id = [the id of john@site.com from test.users, which is 1]
</code>```

答:
use subquery:</p>

```<code>    DELETE FROM test.questions WHERE answer = true AND user_id =
(SELECT id FROM test.users WHERE email = 'john@site.com' );
</code>```

Body:
In my test.users table, I have

id | email         | first_name
1  | john@site.com | John
2  | bob@site.com  | Bob

In my test.questions table, I have

id  | user_id | answer
10  | 1       | true
11  | 2       | false

I want to delete the row in test.questions where the user_id matches the id in test.users for one specific user only.

For example, if I want to delete the row with id 10 from test.questions (since that row corresponds to john@site.com in test.users), I can do

DELETE FROM test.questions WHERE answer = true AND user_id = 1

This will delete only the row with id = 10 from test.questions, which is what I want.

The problem is that I don't want to hardcode the id.  I want to hardcode just the user's email in the query, and get the id dynamically.  Something like

DELETE FROM test.questions WHERE answer = true AND user_id = [the id of john@site.com from test.users, which is 1]

Body:
use subquery:

    DELETE FROM test.questions WHERE answer = true AND user_id =
(SELECT id FROM test.users WHERE email = 'john@site.com' );


问:
How to use JSON_VALUE with a variable
I have a statement I'm trying to construct in Oracle 18c.  The following line works fine:

```<code>Select JSON_VALUE(l_resp, '$.items[0].volumeInfo.industryIdentifiers[1].type')
  into l_temp_var
  from dual;
</code>```

However, I have to vary the second index by a variable.  The second index currently contains [1].  I  tried using [i] defined as a numeric or varchar, but that doesn't work.  How can I construct a Select JSON_VALUE statement so that it uses a variable?
Thanks for looking at this.

答:
Use string concatination to build your index string. For example:</p>

```<code>BEGIN
  FOR i IN 1..10 LOOP
    Select JSON_VALUE(l_resp, '$.items[0].volumeInfo.industryIdentifiers[' || i || '].type')
      into l_temp_var
      from dual;

    -- Do something with the value in l_temp_var here

  END LOOP;
END:
</code>```

Title: How to use JSON_VALUE with a variable

Body:
I have a statement I'm trying to construct in Oracle 18c.  The following line works fine:

Select JSON_VALUE(l_resp, '$.items[0].volumeInfo.industryIdentifiers[1].type')
  into l_temp_var
  from dual;

However, I have to vary the second index by a variable.  The second index currently contains [1].  I  tried using [i] defined as a numeric or varchar, but that doesn't work.  How can I construct a Select JSON_VALUE statement so that it uses a variable?
Thanks for looking at this.

Body:
Use string concatination to build your index string. For example:

BEGIN
  FOR i IN 1..10 LOOP
    Select JSON_VALUE(l_resp, '$.items[0].volumeInfo.industryIdentifiers[' || i || '].type')
      into l_temp_var
      from dual;

    -- Do something with the value in l_temp_var here

  END LOOP;
END:


问:
What's the simplest way to schedule a function to be called at midnight everyday with Clojure?
While one can use threads and set a timeout to run a function at set intervals from the time a new Thread has been started, how to make it so that the function runs at 00:00:00 starting from the next midnight? </p>

答:
You could also take a look at chime library.

I did not test this code, but something like this.

(ns my.example
  (:require [chime :refer [chime-at]])
  (:import  [java.time Instant LocalTime ZonedDateTime ZoneId Period]))

(defn my-task []
  (println "Executing a task"))

(defn periodic-seq [^Instant start duration-or-period]
  (iterate #(.addTo duration-or-period %) start)) ;; produces a lazy-seq of Instants

;; generates infinite sequence of days. Change the time zone to the one you need.
(def days
  (periodic-seq (-> (LocalTime/of 23 0 0)
                    (.adjustInto (ZonedDateTime/now (ZoneId/of "America/New_York")))
                    .toInstant)
                (Period/ofDays 1)))

(chime-at days (fn [time] (my-task)))
```

<p>chime-at returns a zero arg function, that you can call to cancel the schedule. So you need to
start the schedule like this. </p>

<pre class="lang-clj prettyprint-override"><code>(def cancel (chime-at days (fn [time] my-task)))
(cancel)
</code>```

Again, I haven't tested this code.

Body:
You could also take a look at chime library.

I did not test this code, but something like this.

(ns my.example
  (:require [chime :refer [chime-at]])
  (:import  [java.time Instant LocalTime ZonedDateTime ZoneId Period]))

(defn my-task []
  (println "Executing a task"))

(defn periodic-seq [^Instant start duration-or-period]
  (iterate #(.addTo duration-or-period %) start)) ;; produces a lazy-seq of Instants

;; generates infinite sequence of days. Change the time zone to the one you need.
(def days
  (periodic-seq (-> (LocalTime/of 23 0 0)
                    (.adjustInto (ZonedDateTime/now (ZoneId/of "America/New_York")))
                    .toInstant)
                (Period/ofDays 1)))

(chime-at days (fn [time] (my-task)))

chime-at returns a zero arg function, that you can call to cancel the schedule. So you need to
start the schedule like this.

(def cancel (chime-at days (fn [time] my-task)))
(cancel)

Again, I haven't tested this code.


问:
How to fix component display overlap
I am aiming to display the component "SignIn" when I select the sign in button in the landing page. However, the component in the landing page is still displayed after selecting the button. Here are some images illustrating this problem.

Before Click: enter image description here

After Click: enter image description here

The issue is the second image. What could be the biggest cause of it?

Input is greatly appreciated.

Code - Home Page (LandingPage):

```<code>import React from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { Link } from 'react-router-dom';
import * as ROUTES from '../../routes.jsx';
import './LandingPage.css'

export default class LandingPage extends React.Component {
    render() {
        return(
            <div>
            <Button className="signInButton" variant="light"><Link to={ROUTES.SIGN_IN}>Sign In</Link></Button>
            <h1 className="landingBanner" >Streamosphere</h1>
            <SignUpFormBase/>
        </div>
    );
  }
}

const INITIAL_STATE = {
  email: '',
  password: '',
  error: null,
};

export default class SignUpFormBase extends React.Component {
   constructor(props) {
       super(props);

    this.state = { ...INITIAL_STATE };
  }
onSubmit = event => {
    console.log("Props");
    console.log(this.props);
    const { history } = this.props;
    const { email, password } = this.state;
    this.props.firebase
        .doCreateUserWithEmailAndPassword(email, password)
        .then(authUser => {
          this.setState({ ...INITIAL_STATE });
        })
        .catch(error => {
          this.setState({ error });
        });

    event.preventDefault();
};

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

render() {
  const {
        email,
        password,
        error,
    } = this.state;
    const isInvalid = password === '' || email === '';

    return (

      <Form className="signUpForm"
            onSubmit={this.onSubmit}>
        <h1 className="signUpBanner">Sign Up </h1>

        <Form.Group controlId="formSignUpEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control name="email"
                        value={email}
                        onChange={this.onChange}
                        type="email"
                        placeholder="Enter email" />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
          </Form.Text>
        </Form.Group>

        <Form.Group controlId="formSignUpPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control name="password"
                        value={password}
                        onChange={this.onChange}
                        type="password"
                        placeholder="Password" />
        </Form.Group>
        <Button type="submit"
                disabled={isInvalid}
                className="signUpButton"
                variant="light" >
          Sign Up
        </Button>
        {error && <p>{error.message}</p>}
    </Form>
    );
  }
}

const SignUpLink = () => (
    <p>
      Already have an account? <Link to={ROUTES.SIGN_IN}>Sign In</Link>
    </p>
);
</code>```

Sign In (file w/ SignIn Component):

```<code> import React, { Component } from 'react';
 import SignUpLink from './LandingPage.jsx'
 import * as ROUTES from '../../routes.jsx';
 import Form from 'react-bootstrap/Form';
 import Button from 'react-bootstrap/Button';
 import './LandingPage.css'

export default class SignInPage extends Component {
    render() {
        return(
            <div>
                <h1 className="landingBanner" >Streamosphere</h1>
                <SignInFormBase/>
                <SignUpLink />
            </div>
        );
    }
}

const INITIAL_STATE = {
    email: '',
    password: '',
    error: null,
};

export default class SignInFormBase extends Component {
    constructor(props) {
        super(props);

        this.state = { ...INITIAL_STATE };
    }

    onSubmit = event => {
        const { email, password } = this.state;

        this.props.firebase
            .doSignInWithEmailAndPassword(email, password)
            .then(() => {
                this.setState({ ...INITIAL_STATE });
                this.props.history.push(ROUTES.HOME);
            })
            .catch(error => {
                this.setState({ error });
            });

        event.preventDefault();
    };

    onChange = event => {
        this.setState({ [event.target.name]: event.target.value });
    };

    render() {
        const { email, password, error } = this.state;

        const isInvalid = password === '' || email === '';

        return (
            <Form className="signUpForm"
                  onSubmit={this.onSubmit}>
            <h1 className="signUpBanner"> Sign In </h1>
            <Form.Group controlId="formSignInEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control name="email"
                              value={email}
                              onChange={this.onChange}
                              type="email"
                              placeholder="Enter email" />
                <Form.Text className="text-muted">
                    We'll never share your email with anyone else.
                </Form.Text>
            </Form.Group>
            <Form.Group controlId="formSignInPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control name="password"
                              value={password}
                              onChange={this.onChange}
                              type="password"
                              placeholder="Password" />
            </Form.Group>
            <Button type="submit"
                    disabled={isInvalid}
                    className="signUpButton"
                    variant="light" >
                Sign In
            </Button>
            {error && <p>{error.message}</p>}
        </Form>
      );
  }
</code>```

}
URL Routes (routes.jsx):

```<code>export const LANDING = '/';
export const SIGN_IN = '/signin';
export const HOME = '/home';
export const ACCOUNT = '/account';
</code>```

App.jsx (entry point, where LandingPage is the 1st page rendered):

```<code>import { Route } from 'react-router'
import React from 'react';
import LandingPage from './components/containers/LandingPage'
import SignInPage from './components/containers/SignIn'
import HomePage from './components/containers/HomePage'
import * as ROUTES from './routes.jsx';

class App extends React.Component {
    render() {
        return (
            <div>
                <Route exact path={ROUTES.LANDING} component={LandingPage} />
                <Route path={ROUTES.HOME} component={HomePage} />
                <Route path={ROUTES.SIGN_IN} component={SignInPage} />
            </div>
        );
    }
}

export default App;
</code>```

答:
It is because of the Link from react-router-dom.
You could circumvent it by reloading the whole page.
For example, use  instead.

Title: How to fix component display overlap

Body:
I am aiming to display the component "SignIn" when I select the sign in button in the landing page. However, the component in the landing page is still displayed after selecting the button. Here are some images illustrating this problem.

Before Click: enter image description here

After Click: enter image description here

The issue is the second image. What could be the biggest cause of it?

Input is greatly appreciated.

Code - Home Page (LandingPage):

import React from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { Link } from 'react-router-dom';
import * as ROUTES from '../../routes.jsx';
import './LandingPage.css'

export default class LandingPage extends React.Component {
    render() {
        return(

            <Button className="signInButton" variant="light"><Link to={ROUTES.SIGN_IN}>Sign In</Link></Button>

Streamosphere

            <SignUpFormBase/>

    );
  }
}

const INITIAL_STATE = {
  email: '',
  password: '',
  error: null,
};

export default class SignUpFormBase extends React.Component {
   constructor(props) {
       super(props);

    this.state = { ...INITIAL_STATE };
  }
onSubmit = event => {
    console.log("Props");
    console.log(this.props);
    const { history } = this.props;
    const { email, password } = this.state;
    this.props.firebase
        .doCreateUserWithEmailAndPassword(email, password)
        .then(authUser => {
          this.setState({ ...INITIAL_STATE });
        })
        .catch(error => {
          this.setState({ error });
        });

    event.preventDefault();
};

  onChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

render() {
  const {
        email,
        password,
        error,
    } = this.state;
    const isInvalid = password === '' || email === '';

    return (

      <Form className="signUpForm"
            onSubmit={this.onSubmit}>

Sign Up

        <Form.Group controlId="formSignUpEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control name="email"
                        value={email}
                        onChange={this.onChange}
                        type="email"
                        placeholder="Enter email" />
          <Form.Text className="text-muted">
            We'll never share your email with anyone else.
          </Form.Text>
        </Form.Group>

        <Form.Group controlId="formSignUpPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control name="password"
                        value={password}
                        onChange={this.onChange}
                        type="password"
                        placeholder="Password" />
        </Form.Group>
        <Button type="submit"
                disabled={isInvalid}
                className="signUpButton"
                variant="light" >
          Sign Up
        </Button>
        {error &&
{error.message}
}
    </Form>
    );
  }
}

const SignUpLink = () => (

      Already have an account? <Link to={ROUTES.SIGN_IN}>Sign In</Link>

);

Sign In (file w/ SignIn Component):

 import React, { Component } from 'react';
 import SignUpLink from './LandingPage.jsx'
 import * as ROUTES from '../../routes.jsx';
 import Form from 'react-bootstrap/Form';
 import Button from 'react-bootstrap/Button';
 import './LandingPage.css'

export default class SignInPage extends Component {
    render() {
        return(

Streamosphere

                <SignInFormBase/>
                <SignUpLink />

        );
    }
}

const INITIAL_STATE = {
    email: '',
    password: '',
    error: null,
};

export default class SignInFormBase extends Component {
    constructor(props) {
        super(props);

        this.state = { ...INITIAL_STATE };
    }

    onSubmit = event => {
        const { email, password } = this.state;

        this.props.firebase
            .doSignInWithEmailAndPassword(email, password)
            .then(() => {
                this.setState({ ...INITIAL_STATE });
                this.props.history.push(ROUTES.HOME);
            })
            .catch(error => {
                this.setState({ error });
            });

        event.preventDefault();
    };

    onChange = event => {
        this.setState({ [event.target.name]: event.target.value });
    };

    render() {
        const { email, password, error } = this.state;

        const isInvalid = password === '' || email === '';

        return (
            <Form className="signUpForm"
                  onSubmit={this.onSubmit}>

 Sign In

            <Form.Group controlId="formSignInEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control name="email"
                              value={email}
                              onChange={this.onChange}
                              type="email"
                              placeholder="Enter email" />
                <Form.Text className="text-muted">
                    We'll never share your email with anyone else.
                </Form.Text>
            </Form.Group>
            <Form.Group controlId="formSignInPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control name="password"
                              value={password}
                              onChange={this.onChange}
                              type="password"
                              placeholder="Password" />
            </Form.Group>
            <Button type="submit"
                    disabled={isInvalid}
                    className="signUpButton"
                    variant="light" >
                Sign In
            </Button>
            {error &&
{error.message}
}
        </Form>
      );
  }

}
URL Routes (routes.jsx):

export const LANDING = '/';
export const SIGN_IN = '/signin';
export const HOME = '/home';
export const ACCOUNT = '/account';

App.jsx (entry point, where LandingPage is the 1st page rendered):

import { Route } from 'react-router'
import React from 'react';
import LandingPage from './components/containers/LandingPage'
import SignInPage from './components/containers/SignIn'
import HomePage from './components/containers/HomePage'
import * as ROUTES from './routes.jsx';

class App extends React.Component {
    render() {
        return (

                <Route exact path={ROUTES.LANDING} component={LandingPage} />
                <Route path={ROUTES.HOME} component={HomePage} />
                <Route path={ROUTES.SIGN_IN} component={SignInPage} />

        );
    }
}

export default App;

Body:
It is because of the Link from react-router-dom.
You could circumvent it by reloading the whole page.
For example, use <a href="/sign-in></a> instead.


问:
How to print the sum of the number of times a certain integer returns?
Heres the code:
I want to be able to print something like "Buy! = ???" or "Sell! = ???" or "Hold! = ???".

```<code>list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1
        cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    elif list_A[x] < list_B[x]:
        num_sells += 1
        cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    else:
        num_holds += 1
        cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

</code>```

Recommendations are greatly appreciated.

答:
Well then just print the answer outside the loop. If I'm getting your doubt correctly.

```<code>list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1

    elif list_A[x] < list_B[x]:
        num_sells += 1

    else:
        num_holds += 1

cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)
</code>```

Like the above.

Body:
Heres the code:
I want to be able to print something like "Buy! = ???" or "Sell! = ???" or "Hold! = ???".

list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1
        cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    elif list_A[x] < list_B[x]:
        num_sells += 1
        cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    else:
        num_holds += 1
        cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

Recommendations are greatly appreciated.

Body:
Well then just print the answer outside the loop. If I'm getting your doubt correctly.

list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1

    elif list_A[x] < list_B[x]:
        num_sells += 1

    else:
        num_holds += 1

cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

Like the above.


问:
Are ruby strings that return true for #ascii_only? a subset of strings that return true for Activesupport's #is_utf8?
I have a requirement to determine if a very large number of characters of unknown encoding are utf8. I'm using ActiveSupport #is_utf8?, however it is quite slow because it duplicates the string. I am wondering if I can put a guard clause using #ascii_only. My testing show that this will improve the performance of my utf8? method.

Original method:

```<code>def utf8? character
  character.is_utf8?
end
</code>```

Faster method:

```<code>def utf8? character
  return true if character.ascii_only?
  character.is_utf8?
end
</code>```

Is there a character that will return false for ActiveSupport's String#is_utf8? that will return true for String#ascii_only?

答:
Is there a character that will return false for ActiveSupport's String#is_utf8?
  [and] true for String#ascii_only?

According to the definition of UTF-8, there is no such character.

The first 128 characters of Unicode .. correspond one-to-one with ASCII
  (https://en.m.wikipedia.org/wiki/UTF-8)

But, do these functions respect this definition? Yes, they do. :)

ascii_only? returns true only for characters 0..127, regardless of which encoding we specify.

```<code>127.chr(Encoding::ASCII_8BIT).ascii_only? #=> true
128.chr(Encoding::ASCII_8BIT).ascii_only? #=> false
127.chr(Encoding::UTF_8).ascii_only? #=> true
128.chr(Encoding::UTF_8).ascii_only? #=> false
</code>```

Now let's look at is_utf8?. To answer our question, we only need to consider characters 0..127.

```<code>(0..127).any? { |i| !i.chr(Encoding::ASCII_8BIT).is_utf8? }
#=> false
</code>```

In the range 0..127, there are no characters for which is_utf8? returns false.

Body:
I have a requirement to determine if a very large number of characters of unknown encoding are utf8. I'm using ActiveSupport #is_utf8?, however it is quite slow because it duplicates the string. I am wondering if I can put a guard clause using #ascii_only. My testing show that this will improve the performance of my utf8? method.

Original method:

def utf8? character
  character.is_utf8?
end

Faster method:

def utf8? character
  return true if character.ascii_only?
  character.is_utf8?
end

Is there a character that will return false for ActiveSupport's String#is_utf8? that will return true for String#ascii_only?

Body:
Is there a character that will return false for ActiveSupport's String#is_utf8?
  [and] true for String#ascii_only?

According to the definition of UTF-8, there is no such character.

The first 128 characters of Unicode .. correspond one-to-one with ASCII
  (https://en.m.wikipedia.org/wiki/UTF-8)

But, do these functions respect this definition? Yes, they do. :)

ascii_only? returns true only for characters 0..127, regardless of which encoding we specify.

127.chr(Encoding::ASCII_8BIT).ascii_only? #=> true
128.chr(Encoding::ASCII_8BIT).ascii_only? #=> false
127.chr(Encoding::UTF_8).ascii_only? #=> true
128.chr(Encoding::UTF_8).ascii_only? #=> false

Now let's look at is_utf8?. To answer our question, we only need to consider characters 0..127.

(0..127).any? { |i| !i.chr(Encoding::ASCII_8BIT).is_utf8? }
#=> false

In the range 0..127, there are no characters for which is_utf8? returns false.


问:
Pandas Swap values of 3 columns with next row
I'm using a pandas dataframe and want to swap the values of 3 columns [EndLocation, EndDevice, EndPort] in a row with the next row, the next row then becomes the first row.

```<code>  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P1      NaN
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P3      NaN
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4      NaN
</code>```

expected output:

```<code>    StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AJ11   RU25        P1      MTP
1          AB11        RU15        P1         AD1    Switch2     P2      NaN
2           DD2     Switch2        P3         AB11    RU35       P3      MTP
3          AB12        RU18        P2        AD2    Switch3     P2      NaN
4           DD3     Switch3        P5        AB11    RU40        P4      MTP
5          AB13        RU19        P3        AD3   Switch4      P6      NaN
</code>```

shift() and np.roll() don't fit my use case as this is port mapping and need preserve the start point. Is looping through a dataframe a bad idea?

Edited for more clarity

答:
This works:

```<code>(
    df.iloc[0::2, 3:6],
    df.iloc[1::2, 3:6],
) = (
    df.shift(-1).iloc[:, 3:6],
    df.shift(1).iloc[:, 3:6],
)
</code>```

It uses Python's tuple assignment to assign both even and odd rows at the same time.

df.iloc[0::2, 3:6] will assign to columns 3, 4 and 5 (EndLocation, EndDevice and EndPort) of the even rows (0, 2 and 4), while df.iloc[1::2, 3:6] will assign to the same columns on odd rows (1, 3 and 5.) If you have more than 6 rows, these expressions will keep working.

For the values to assign, we use two shift expressions, one shifting up, for the even rows (1 -> 0, 3 -> 2, 5 -> 4) and the other shifting down for the odd rows (0 -> 1, 2 -> 3 and 4 -> 5), again selecting only columns 3, 4 and 5.

Since Pandas will align the index in an assignment, it will only consider the even or odd rows depending on which expression it's looking at.

Body:
I'm using a pandas dataframe and want to swap the values of 3 columns [EndLocation, EndDevice, EndPort] in a row with the next row, the next row then becomes the first row.

  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P1      NaN
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P3      NaN
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4      NaN

expected output:

    StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AJ11   RU25        P1      MTP
1          AB11        RU15        P1         AD1    Switch2     P2      NaN
2           DD2     Switch2        P3         AB11    RU35       P3      MTP
3          AB12        RU18        P2        AD2    Switch3     P2      NaN
4           DD3     Switch3        P5        AB11    RU40        P4      MTP
5          AB13        RU19        P3        AD3   Switch4      P6      NaN

shift() and np.roll() don't fit my use case as this is port mapping and need preserve the start point. Is looping through a dataframe a bad idea?

Edited for more clarity

Body:
This works:

(
    df.iloc[0::2, 3:6],
    df.iloc[1::2, 3:6],
) = (
    df.shift(-1).iloc[:, 3:6],
    df.shift(1).iloc[:, 3:6],
)

It uses Python's tuple assignment to assign both even and odd rows at the same time.

df.iloc[0::2, 3:6] will assign to columns 3, 4 and 5 (EndLocation, EndDevice and EndPort) of the even rows (0, 2 and 4), while df.iloc[1::2, 3:6] will assign to the same columns on odd rows (1, 3 and 5.) If you have more than 6 rows, these expressions will keep working.

For the values to assign, we use two shift expressions, one shifting up, for the even rows (1 -> 0, 3 -> 2, 5 -> 4) and the other shifting down for the odd rows (0 -> 1, 2 -> 3 and 4 -> 5), again selecting only columns 3, 4 and 5.

Since Pandas will align the index in an assignment, it will only consider the even or odd rows depending on which expression it's looking at.


问:
Global Variable Bug in Google Apps Script Server Side
I am trying to create global variables in Apps Script and avoid built-in functions such as UserProperties. The reason for avoiding UserProperties is because all of my web app users will share the same variables which will result in their accounts being mixed together. I want to create global variables that have a lifetime until you close the tab/window. I can't use user properties because I need to run the script as myself as I am searching within a spreadsheet under my account in this web app.

```<code>function extractData(row){
  extractEmail(row);
  extractPoints(row);
  extractUsername(row);
  extractName(row);
  extractType(row);
  extractFamily(row);
  return "success";
}

function extractEmail(row){
  try{
    var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
    var sheet = SpreadsheetApp.openByUrl(url);
    var subsheet = sheet.getSheetByName("Accounts");
    var col = 2
    Gemail = String(subsheet.getRange(Number(row), col).getValue());
  }
  catch(error){
    Logger.log(error.message);
    }
}

function extractPoints(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 6;
  Gpoints = Number(subsheet.getRange(Number(row), col).getValue());
}

function extractUsername(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 4;
  Gusername = String(subsheet.getRange(row, col).getValue());
}

function extractName(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 3;
  Gname = String(subsheet.getRange(row, col).getValue());
}

function extractType(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 7;
  Gtype = String(subsheet.getRange(row, col).getValue());
}

function extractFamily(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 12;
  Gfamily = String(subsheet.getRange(row, col).getValue());
  Logger.log(Gfamily);
}

function definer(){
  try{
  Utilities.sleep(5000);
  Logger.log(Gfamily);
  var data = [Gemail, Gname, Gusername, Gpoints, Gtype, Gfamily];
  return data;
  }
  catch(error){
    Logger.log(error.message);
  }
}
</code>```

The code above is the server-side. Each function is called by the client-side along with the row already defined. The first function called by the client-side is extractData. When the global variable Gfamily is logged, it comes out correctly as testers. After the next function: definer is called from the client-side, Gfamily is logged as null. Please tell me how I can improve this question if I was unclear about anything. Below is a screenshot of the logs:
Screenshot: Stackdriver logs showing how Gfamily suddenly becomes undefined

答:
Your frontend (browser) session is separate from your backend (server) session. Google's server isn't really tracking whether a user closes the tab/window, so you're going to have to manage the session from the frontend and then write your own server functions to correctly identify sessions.

To share a value across multiple users, I recommend using the Script Properties or Script Cache. Values stored in the script properties/cache will be available to all users of your web app. If one user updates the value, the new value will be immediately available to all other users. I recommend using this with Window.sessionStorage, which will clear automatically when the page session ends. So you could pass session data to the server and then manually track when a session is ended.

However, I don't really understand how you intend to use a shared value dependent on multiple user sessions. If one of the users ends their session, what happens to the shared value?

That makes me think there may be some misinterpretation, particularly due to your sentence

The reason for avoiding UserProperties is because all of my web app users will share the same variables which will result in their accounts being mixed together.

User properties are not shared, unless you deployed the app to "Execute the app as me". If you did that, then the script would always be executing under the same (your) user account and all user properties would be shared. But if you were to simply set "Execute the app as user accessing the web app", then you could safely use User properties/cache without any worries about mixed accounts. (The intention of User properties/cache is to avoid scope issues like mixing across accounts – take a look at this comparison table.)

Body:
I am trying to create global variables in Apps Script and avoid built-in functions such as UserProperties. The reason for avoiding UserProperties is because all of my web app users will share the same variables which will result in their accounts being mixed together. I want to create global variables that have a lifetime until you close the tab/window. I can't use user properties because I need to run the script as myself as I am searching within a spreadsheet under my account in this web app.

function extractData(row){
  extractEmail(row);
  extractPoints(row);
  extractUsername(row);
  extractName(row);
  extractType(row);
  extractFamily(row);
  return "success";
}

function extractEmail(row){
  try{
    var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
    var sheet = SpreadsheetApp.openByUrl(url);
    var subsheet = sheet.getSheetByName("Accounts");
    var col = 2
    Gemail = String(subsheet.getRange(Number(row), col).getValue());
  }
  catch(error){
    Logger.log(error.message);
    }
}

function extractPoints(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 6;
  Gpoints = Number(subsheet.getRange(Number(row), col).getValue());
}

function extractUsername(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 4;
  Gusername = String(subsheet.getRange(row, col).getValue());
}

function extractName(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 3;
  Gname = String(subsheet.getRange(row, col).getValue());
}

function extractType(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 7;
  Gtype = String(subsheet.getRange(row, col).getValue());
}

function extractFamily(row){
  var url = "https://docs.google.com/spreadsheets/d/1pIC6Lyx4Q0ZjEA5GURZ3gA5qLmUJ0_7yGPJQmr6-GnQ/edit?usp=sharing";
  var sheet = SpreadsheetApp.openByUrl(url);
  var subsheet = sheet.getSheetByName("Accounts");
  var col = 12;
  Gfamily = String(subsheet.getRange(row, col).getValue());
  Logger.log(Gfamily);
}

function definer(){
  try{
  Utilities.sleep(5000);
  Logger.log(Gfamily);
  var data = [Gemail, Gname, Gusername, Gpoints, Gtype, Gfamily];
  return data;
  }
  catch(error){
    Logger.log(error.message);
  }
}

The code above is the server-side. Each function is called by the client-side along with the row already defined. The first function called by the client-side is extractData. When the global variable Gfamily is logged, it comes out correctly as testers. After the next function: definer is called from the client-side, Gfamily is logged as null. Please tell me how I can improve this question if I was unclear about anything. Below is a screenshot of the logs:
Screenshot: Stackdriver logs showing how Gfamily suddenly becomes undefined


问:
How to show the bucket name when using RANGE_BUCKET in bigquery
Here is my query with public dataset in BigQuery:

```<code>SELECT RANGE_BUCKET(reputation, [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) AS reputation_group, COUNT(*) AS count
FROM `bigquery-public-data.stackoverflow.users`
Where reputation > 200000
GROUP BY 1
ORDER By 1
</code>```

The result is below:

Instead of showing reputation_group as integer, how can I show the bucket's range:

```<code>0: [0-400000]
1: [400001-500000]
2: [500001-600000]
....
</code>```

Thank you very much.

UPDATE:
A big thank to Mikhail's answer with a minor change below:

```<code>SELECT bucket,
  FORMAT('%i - %i', IFNULL(ranges[SAFE_OFFSET(bucket - 1)] + 1, 0), ranges[SAFE_OFFSET(bucket)]) AS reputation_group,
  COUNT(*) AS COUNT
FROM `bigquery-public-data.stackoverflow.users`,
UNNEST([STRUCT([200000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] AS ranges)]),
UNNEST([RANGE_BUCKET(reputation, ranges)]) bucket
WHERE reputation > 200000
GROUP BY 1, 2
ORDER BY bucket
</code>```

Note an extra item 200000 is added to the STRUCT, which makes the result showing
200001 - 400000 instead of 0 - 400000

答:
With a JOIN and some refactoring:

WITH range_array AS (
  SELECT [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]
)
, buckets AS (
  SELECT LAG(bucket_end) OVER(ORDER BY reputation_group) bucket_start, *
  FROM UNNEST((SELECT * FROM range_array)) bucket_end WITH OFFSET reputation_group
)

SELECT *
  , (SELECT AS STRUCT * FROM buckets WHERE a.reputation_group = reputation_group) bucket
FROM (
  SELECT RANGE_BUCKET(reputation, (SELECT * FROM range_array)) AS reputation_group, COUNT(*) AS count
  FROM `bigquery-public-data.stackoverflow.users`
  WHERE reputation > 200000
  GROUP BY 1
  ORDER BY 1
) a
ORDER BY reputation_group
```

<p>But if you are doing all that, it's easier to forget about RANGE_BUCKET:</p>

<pre class="lang-sql prettyprint-override"><code>WITH buckets AS (
  SELECT IFNULL(LAG(max) OVER(ORDER BY grp), -10000000) min, *
  FROM UNNEST([400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) max WITH OFFSET grp
)

SELECT buckets.min, buckets.max, COUNTIF(reputation >= buckets.min AND reputation < buckets.max) c
FROM `bigquery-public-data.stackoverflow.users`, buckets
WHERE reputation > 200000
GROUP BY 1,2
ORDER BY 1
</code>```

Or:

SELECT IFNULL(min,0) min, max, COUNT(*) c
FROM (
  SELECT (SELECT MAX(x) FROM UNNEST(ranges) x WHERE x<reputation) min, (SELECT MIN(x) FROM UNNEST(ranges) x WHERE x>reputation) max
  FROM `bigquery-public-data.stackoverflow.users`
  , (SELECT [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] ranges)
  WHERE reputation > 200000
)
GROUP BY 1, 2
ORDER BY 1
```

Body:
Here is my query with public dataset in BigQuery:

SELECT RANGE_BUCKET(reputation, [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) AS reputation_group, COUNT(*) AS count
FROM `bigquery-public-data.stackoverflow.users`
Where reputation > 200000
GROUP BY 1
ORDER By 1

The result is below:

Instead of showing reputation_group as integer, how can I show the bucket's range:

0: [0-400000]
1: [400001-500000]
2: [500001-600000]
....

Thank you very much.

UPDATE:
A big thank to Mikhail's answer with a minor change below:

SELECT bucket,
  FORMAT('%i - %i', IFNULL(ranges[SAFE_OFFSET(bucket - 1)] + 1, 0), ranges[SAFE_OFFSET(bucket)]) AS reputation_group,
  COUNT(*) AS COUNT
FROM `bigquery-public-data.stackoverflow.users`,
UNNEST([STRUCT([200000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] AS ranges)]),
UNNEST([RANGE_BUCKET(reputation, ranges)]) bucket
WHERE reputation > 200000
GROUP BY 1, 2
ORDER BY bucket

Note an extra item 200000 is added to the STRUCT, which makes the result showing
200001 - 400000 instead of 0 - 400000

Body:
With a JOIN and some refactoring:

WITH range_array AS (
  SELECT [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]
)
, buckets AS (
  SELECT LAG(bucket_end) OVER(ORDER BY reputation_group) bucket_start, *
  FROM UNNEST((SELECT * FROM range_array)) bucket_end WITH OFFSET reputation_group
)

SELECT *
  , (SELECT AS STRUCT * FROM buckets WHERE a.reputation_group = reputation_group) bucket
FROM (
  SELECT RANGE_BUCKET(reputation, (SELECT * FROM range_array)) AS reputation_group, COUNT(*) AS count
  FROM `bigquery-public-data.stackoverflow.users`
  WHERE reputation > 200000
  GROUP BY 1
  ORDER BY 1
) a
ORDER BY reputation_group

But if you are doing all that, it's easier to forget about RANGE_BUCKET:

WITH buckets AS (
  SELECT IFNULL(LAG(max) OVER(ORDER BY grp), -10000000) min, *
  FROM UNNEST([400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) max WITH OFFSET grp
)

SELECT buckets.min, buckets.max, COUNTIF(reputation >= buckets.min AND reputation < buckets.max) c
FROM `bigquery-public-data.stackoverflow.users`, buckets
WHERE reputation > 200000
GROUP BY 1,2
ORDER BY 1

Or:

SELECT IFNULL(min,0) min, max, COUNT(*) c
FROM (
  SELECT (SELECT MAX(x) FROM UNNEST(ranges) x WHERE x<reputation) min, (SELECT MIN(x) FROM UNNEST(ranges) x WHERE x>reputation) max
  FROM `bigquery-public-data.stackoverflow.users`
  , (SELECT [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] ranges)
  WHERE reputation > 200000
)
GROUP BY 1, 2
ORDER BY 1


问:
AWS lambda deployment from Bitbucket
I am working on AWS lambda continuous integration and deployment. I have lambda's written in NodeJs and kept in Bitbucket repo. I am not able to find detailed tutorial or example to deploy those lambda's on AWS instance. AWS code pipeline source allows GitHub but not BitBucket. Any one has any idea how to do it. Please do share information or links if available.</p>

答: Now you can use Bitbucket Pipelines, here a useful tutorial to do that. </p>

Title: AWS lambda deployment from Bitbucket


问:
The type or namespace name 'Json' does not exist in the namespace 'System' (are you missing an assembly reference?)
I am using .NET Framework 4.5 and I'm having this issue.
The type or namespace 'Json' does not exist in the namespace 'System'

I tried to Install-Package System.Json -Version 4.0.20126.16343 but I had this issue afterwards.

The type 'System.Uri' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
```

Source: https://www.nuget.org/packages/System.Json

Any ideas would be really appreciated!

答:
using Newtonsoft.Json; should get the job done.

Now you can use:

```<code>JsonConvert.SerializeObject
JsonConvert.DeserializeObject
</code>```

Body:
I am using .NET Framework 4.5 and I'm having this issue.
The type or namespace 'Json' does not exist in the namespace 'System'

I tried to Install-Package System.Json -Version 4.0.20126.16343 but I had this issue afterwards.

The type 'System.Uri' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Source: https://www.nuget.org/packages/System.Json

Any ideas would be really appreciated!

Body:
using Newtonsoft.Json; should get the job done.

Now you can use:

JsonConvert.SerializeObject
JsonConvert.DeserializeObject


问:
MSAL (Java) Rest API Authentication ( Authorization : Bearer Token )
I'd like to secure a Java Rest API against Azure AD B2C.

I understand that the caller is calling the service using the Authorization header with a value like: Bearer xxx-token

Is that an ID or Access Token ?

What are the steps the service should take to ensure this is a valid token? Java code using MSAL4J would be greatly appreciated.

答:
Have you seen this MSAL4J B2C sample, which calls a protected web api?

Here in the sample is where it's including the access token, from when the user signed-in and appending it to the header as a Bearer token. Then a middleware library, for example Spring Security for java, will validate the token.

private String callB2CApi(String accessToken){
   RestTemplate restTemplate = new RestTemplate();

   HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        headers.set("Authorization", "Bearer " + accessToken);

    HttpEntity<String> entity = new HttpEntity<>(null, headers);

    String result = restTemplate.exchange(authHelper.configuration.api, HttpMethod.GET,
                entity, String.class).getBody();

     return new Date() + result;
}
```

Here's more information on using MSAL4J to create a web app which signs-in users and then calls a protected web api. More code samples for calling a protected web api.

Here's an overview of the b2c token types. The idToken contains the claims about the user and the access token provides scoped permission to your web api.

Body:
Have you seen this MSAL4J B2C sample, which calls a protected web api?

Here in the sample is where it's including the access token, from when the user signed-in and appending it to the header as a Bearer token. Then a middleware library, for example Spring Security for java, will validate the token.

private String callB2CApi(String accessToken){
   RestTemplate restTemplate = new RestTemplate();

   HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        headers.set("Authorization", "Bearer " + accessToken);

    HttpEntity<String> entity = new HttpEntity<>(null, headers);

    String result = restTemplate.exchange(authHelper.configuration.api, HttpMethod.GET,
                entity, String.class).getBody();

     return new Date() + result;
}

Here's more information on using MSAL4J to create a web app which signs-in users and then calls a protected web api. More code samples for calling a protected web api.

Here's an overview of the b2c token types. The idToken contains the claims about the user and the access token provides scoped permission to your web api.


问:
Deserialize json object from a combobox data (loaded from database) Winform
Good morning, I'm having a hard time finding solution to my problem. I have a combobox which is populated using datasource which is from DB and those data where JSON objects. How will I deserialize those data?
This is the JSON data from Database:

{"displayname":{"value":"Test","scope":"contacts","verified":"0"},"address":{"value":"","scope":"private","verified":"0"},"website":{"value":"","scope":"private","verified":"0"},"email":{"value":"","scope":"contacts","verified":"0"},"avatar":{"scope":"contacts","verified":"0"},"phone":{"value":"01234567890","scope":"private","verified":"0"},"twitter":{"value":"","scope":"private","verified":"0"}}

And below is what will be shown in the combobox. I don't want a JSON object in my combobox but instead a deserialized data. Ex: I want to only show the names in my combobox which is the value under displayname in JSON Object.

答:
Download and install Newtonsoft.Json package from NuGet. then you can Deserialize your JSON string and add it to your Combobox items.

e.g

//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;

    string jsonStr = "Your JsonString ... ";
    var parsed = JsonConvert.DeserializeObject<JObject>(jsonStr);
    string[] lst = parsed.Properties().Select(q => q.Name).ToArray();
    comboBox1.Items.AddRange(lst);

```

<hr/>

<p>if you want to have separate <code>DisplayMember</code> and <code>ValueMember</code> you can use your <code>JProperty</code> array as a DataSource.</p>

<p>e.g</p>

<pre class="lang-cs prettyprint-override"><code>    string jsonStr = "Your JsonString ... ";
    var parsed = JsonConvert.DeserializeObject<JObject>(jsonStr);
    comboBox1.DataSource = parsed.Properties().ToArray();
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Value";
</code>```

when you use a DataSource the comboBox1.SelectedItem also is a JProperty. so you can use this object to access other data in your json string.

e.g

   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
   {
      // selectedValue is equal to `value` in the json string
      var selectedValue = ((JProperty)comboBox1.SelectedItem).Value.Value<string>("value");
      MessageBox.Show(selectedValue);
   }
```

Body:
Download and install Newtonsoft.Json package from NuGet. then you can Deserialize your JSON string and add it to your Combobox items.

e.g

//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;

    string jsonStr = "Your JsonString ... ";
    var parsed = JsonConvert.DeserializeObject<JObject>(jsonStr);
    string[] lst = parsed.Properties().Select(q => q.Name).ToArray();
    comboBox1.Items.AddRange(lst);

if you want to have separate DisplayMember and ValueMember you can use your JProperty array as a DataSource.

e.g

    string jsonStr = "Your JsonString ... ";
    var parsed = JsonConvert.DeserializeObject<JObject>(jsonStr);
    comboBox1.DataSource = parsed.Properties().ToArray();
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Value";

when you use a DataSource the comboBox1.SelectedItem also is a JProperty. so you can use this object to access other data in your json string.

e.g

   private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
   {
      // selectedValue is equal to `value` in the json string
      var selectedValue = ((JProperty)comboBox1.SelectedItem).Value.Value<string>("value");
      MessageBox.Show(selectedValue);
   }