问:
how to redirect to another page if condition true
i want to redirect if user state is loggedIn to true then it redirect to homescreen it show state is change when i login but did'nt redirect to homescreen.

```<code>`componentDidMount() {
//realtime auth state subscriber
this.auth_unsb = firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.setState({ loggedIn: true });
    //if logged in
    this.handleUser(user);

    //each time user logs in, subscribe to realtime changes for it's doc
    this.user_unsb = this.firebase
      .firestore()
      .collection("users")
      .doc(user.uid)
      .onSnapshot(
        doc =>
          //sync user data to store
          (Store.currentUserDoc = doc.data()),
        e => {}
      );
  } //if logged out
  else {
    this.setState({ loggedIn: false });
    //unsubscribing from realtime user do changes
    if (this.user_unsb) this.user_unsb();
    return <Redirect to="/login" />;
  }
});
</code>```

}
`

答:
You can use the history object,

```<code>history.push("/login");
</code>```

or
in the render method check for this.user_unsb value,

```<code>if(this.user_unsb){
  return <Redirect to="/login" />;
}

// return your component jsx;
</code>```

Hope this can help you!

Body:
i want to redirect if user state is loggedIn to true then it redirect to homescreen it show state is change when i login but did'nt redirect to homescreen.

`componentDidMount() {
//realtime auth state subscriber
this.auth_unsb = firebase.auth().onAuthStateChanged(user => {
  if (user) {
    this.setState({ loggedIn: true });
    //if logged in
    this.handleUser(user);

    //each time user logs in, subscribe to realtime changes for it's doc
    this.user_unsb = this.firebase
      .firestore()
      .collection("users")
      .doc(user.uid)
      .onSnapshot(
        doc =>
          //sync user data to store
          (Store.currentUserDoc = doc.data()),
        e => {}
      );
  } //if logged out
  else {
    this.setState({ loggedIn: false });
    //unsubscribing from realtime user do changes
    if (this.user_unsb) this.user_unsb();
    return <Redirect to="/login" />;
  }
});

}
`

Body:
You can use the history object,

history.push("/login");

or
in the render method check for this.user_unsb value,

if(this.user_unsb){
  return <Redirect to="/login" />;
}

// return your component jsx;

Hope this can help you!


来源: stackexchange

问:
How to implement an interface member correctly?
I am coding a simple application that works with collections. How do I properly implement an interface method in the case below? Currently, it shows an error "not all code paths return a value".

This is my home task. The class "Time" is already implemented and works properly. I tried to find any examples of successful implementation of this method on the Internet but failed.

```<code>class MyCollection : ICollection<Time>
    {
        List<Time> arr = new List<Time>();

        int ICollection<Time>.Count
        {

            get
            {
                arr.Count();
            }
        }
     }
</code>```

I am getting an error:

CS0161 "MyCollection.ICollection.Count.get': not all code paths
  return a value"

答:
Also, you can use Expression body definition =>

```<code>class MyCollection : ICollection<Time>
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count => arr.Count;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am coding a simple application that works with collections. How do I properly implement an interface method in the case below? Currently, it shows an error "not all code paths return a value".

This is my home task. The class "Time" is already implemented and works properly. I tried to find any examples of successful implementation of this method on the Internet but failed.

class MyCollection : ICollection<Time>
    {
        List<Time> arr = new List<Time>();

        int ICollection<Time>.Count
        {

            get
            {
                arr.Count();
            }
        }
     }

I am getting an error:

CS0161 "MyCollection.ICollection.Count.get': not all code paths
  return a value"

Body:
Also, you can use Expression body definition =>

class MyCollection : ICollection<Time>
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count => arr.Count;
}


问:
Send file to a folder in a bucket via storage client
I am following the documentation and have been able to successfully send an image file to a bucket using the code provided at the bottom of the answer (all taken from the documentation). The file is coming from Angular.

I am now trying to send  this file to a particular folder in that same bucket but couldn't make it work.

```<code>const format = require('util').format;
const express = require('express');
const Multer = require('multer');
const bodyParser = require('body-parser');
var cors = require('cors')
var morgan = require('morgan')
const fs = require('fs');
require('dotenv').config()
const { Storage } = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

const app = express();
app.use(morgan("short"));
app.use(cors())
app.use(bodyParser.json());

// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
    if (!req.file) {
        res.status(400).send('No file uploaded.');
        return;
    }

    // Create a new blob in the bucket and upload the file data.
    const blob = bucket.file(req.file.originalname)
    const blobStream = blob.createWriteStream();

    blobStream.on('error', (err) => {
        next(err);
    });

    blobStream.on('finish', () => {
        // The public URL can be used to directly access the file via HTTP.
        const publicUrl = format(`https://storage.googleapis.com/${bucket.name}/${blob.name}`);
        console.log('publicUrl', publicUrl);
        res.status(200).send({ message: publicUrl });
    });

    blobStream.end(req.file.buffer);
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
    console.log('Press Ctrl+C to quit.');
});
</code>```

答: The string you pass to bucket.file() should be the full path of the destination file.  Right now you are just passing req.file.originalname.  Instead, build a full file path and pass that string.

Body:
I am following the documentation and have been able to successfully send an image file to a bucket using the code provided at the bottom of the answer (all taken from the documentation). The file is coming from Angular.

I am now trying to send  this file to a particular folder in that same bucket but couldn't make it work.

const format = require('util').format;
const express = require('express');
const Multer = require('multer');
const bodyParser = require('body-parser');
var cors = require('cors')
var morgan = require('morgan')
const fs = require('fs');
require('dotenv').config()
const { Storage } = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

const app = express();
app.use(morgan("short"));
app.use(cors())
app.use(bodyParser.json());

// Multer is required to process file uploads and make them available via
// req.files.
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

// A bucket is a container for objects (files).
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);

// Process the file upload and upload to Google Cloud Storage.
app.post('/upload', multer.single('file'), (req, res, next) => {
    if (!req.file) {
        res.status(400).send('No file uploaded.');
        return;
    }

    // Create a new blob in the bucket and upload the file data.
    const blob = bucket.file(req.file.originalname)
    const blobStream = blob.createWriteStream();

    blobStream.on('error', (err) => {
        next(err);
    });

    blobStream.on('finish', () => {
        // The public URL can be used to directly access the file via HTTP.
        const publicUrl = format(`https://storage.googleapis.com/${bucket.name}/${blob.name}`);
        console.log('publicUrl', publicUrl);
        res.status(200).send({ message: publicUrl });
    });

    blobStream.end(req.file.buffer);
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}`);
    console.log('Press Ctrl+C to quit.');
});


问:
How to keep div elements at bottom of page
I have a two-columned div element that I need to have at the bottom of the page to act as a footer. The problem is I have tried using position:fixed and bottom:0 to make the element appear at the bottom. This works but only brings one of the #column divs down to the bottom, the other disappears. I would appreciate any assistance.

Code:

/* ~ Copyright (c) Macleay Netball Association (made by Tom Carpenter for Year 11 IPT Assessment Task #2.) 2019. */

html>body {
  background: none;
  padding: 0;
  margin: 0;
  height: 100%;
  overflow: hidden;
  font-family: 'Trebuchet MS', sans-serif;
  /* Trebuchet MS as main font throughout website, sans-serif acting as a backup */
}

#wrapper {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  position: absolute;
  background: #1B315E;
}

::-webkit-scrollbar {
  display: none;
}

* {
  box-sizing: border-box;
  /* Alignment of DropDown Navigation Menu and Slideshow */
}

.navigation {
  background: #444;
  overflow: hidden;
  top: 0;
}

.menuDropDown {
  overflow: hidden;
  float: left;
}

.menuDropDown>#menuButton {
  font-size: 12px;
  padding: 16px 16px;
  /* Will result in final height of navigation */
  margin: 0;
  outline: none;
  border: none;
  font: inherit;
  background: inherit;
  color: #FFF;
}

#menuButton:hover,
.navigation>.menuDropDown:hover>#menuButton {
  border: none;
  outline: none;
  background: #666;
  color: #1B315E;
}

.menuDropDown:hover>.menuContent {
  display: block;
}

.menuContent {
  display: none;
  position: absolute;
  background: none;
  width: 100%;
  left: 0;
  max-height: 85vh;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.menuRow:after {
  display: table;
  clear: both;
  content: "";
}

.menuColumn {
  width: 25%;
  height: 100px;
  overflow-y: auto;
  padding: 5px;
  float: left;
  background: #666;
}

.menuColumn>a {
  float: none;
  display: block;
  text-align: left;
  text-decoration: none;
  font-size: 14px;
  padding: 8px;
  color: #1B315E;
}

.menuColumn>a.current {
  background: #777;
}

.menuColumn>a:hover {
  background: #888;
}

.logo {
  float: right;
  padding-right: 10px;
  width: 60px;
  height: 50px;
}

.main {
  width: 100%;
  height: calc(100vh - 43px);
  float: left;
  background: none;
  position: absolute;
  overflow: auto;
  padding: 8px;
}

.mainHeader {
  color: #FFF;
  text-align: center;
}

.mainImg {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}

.mainBody {
  color: #FFF;
  padding: 8px;
}

.row:after {
  content: "";
  clear: both;
  display: table;
}

.column {
  float: left;
  width: 33.33%;
  padding: 8px;
}

#column {
  float: left;
  width: 50%;
  padding: 8px;
  background: #888;
  bottom: 0;
}

.sponsers {
  float: left;
  width: 20%;
  padding: 8px;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
}

.sponsers:hover {
  -webkit-filter: grayscale(80%);
  filter: grayscale(80%);
}

.slideshow {
  /* Slideshow Container containing Images, Sliders and Captions */
  position: relative;
  margin: auto;
  max-width: 1000px;
}

.slides {
  display: none;
}

.slideshowImages {
  width: 100%;
}

.slideButton {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  padding: 16px 32px;
  font-size: 18px;
  text-align: center;
  border-radius: 10px;
  font-weight: bold;
}

.mnaHeader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.slideButton:hover {
  background: #666;
}

.previous,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: #FFF;
  font-weight: bold;
  font-size: 18px;
  transition: 0.3s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.previous:hover,
.next:hover {
  background: rgba(0, 0, 0, 0.8);
}

table {
  width: 100%;
  font-size: 16px;
  color: #FFF;
}

.tableCaption {
  font-weight: bold;
  font-size: 18px;
  color: #33CC33;
}

table,
th,
td {
  border-collapse: collapse;
  border: 2px solid #888;
}

th,
td {
  padding: 8px;
  text-align: left;
}

#headerTable {
  width: 33.33%;
  background: #888;
  font-size: 18px;
  color: #33CC33;
}

.linkProp {
  color: #FFF;
  text-decoration: underline;
}

.newsPanel {
  width: 100%;
  background: #888;
  height: 135px;
}

.imgNewsPreview {
  width: 215px;
  height: 135px;
  padding: 4px;
  float: left;
}

.newsHeaderPreview {
  color: #FFF;
  margin-top: 0px;
}

.newsBodyPreview {
  color: #FFF;
  margin-top: -12px;
}

.caption {
  color: #33CC33;
  text-align: center;
  position: absolute;
  font-size: 20px;
  width: 100%;
  padding: 8px 12px;
  bottom: 16px;
}

.collapsible {
  background: #888;
  color: #FFF;
  font-weight: bold;
  width: 100%;
  padding: 18px;
  cursor: pointer;
  font-size: 16px;
  outline: none;
  border: none;
  text-align: left;
}

.active,
.collapsible:hover {
  background: #666;
}

.collapsible:after {
  content: '\002B';
  color: #FFF;
  font-weight: bold;
  float: right;
  margin-left: 4px;
}

.active:after {
  content: '\2212';
}

.contentCollapsible {
  padding: 0px 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background: #F8F8F8;
}

.fade {
  -webkit-animation-name: fade;
  /* To work on Safari (Apple) */
  -webkit-animation-duration: 1s;
  /* To work on Safari (Apple) */
  animation-name: fade;
  animation-duration: 1s;
}

.buttonReturn {
  position: absolute;
  margin-left: 20px;
  margin-top: 20px;
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  font-size: 36px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
}

.videoProp {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  height: 400px;
}

@-webkit-keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@media screen and (max-width: 600px) {
  /* Stacks navigation menu acting for the site to be responsive */
  .menuColumn {
    width: 100%;
    height: auto;
  }
}

@media screen and (max-width: 800px) {
  /* Stacks Image Header on Top - acting as responsive */
  .column,
  #column {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Responsive Sponser Images */
  .sponsers {
    width: 33.33%;
  }
}

@media screen and (max-width: 800px) {
  /* Increases video resolution as screen reduces */
  .videoProp {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Reduces font-size as screen resolution lowers */
  .newsBodyPreview {
    font-size: 14px;
  }
}

@media screen and (max-width: 300px) {
  /* Reduces font-sizes within the slideshow
 */
  .previous,
  .next,
  .caption {
    font-size: 14px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<!--
 ~ Copyright (c) Macleay Netball Association (made by Tom Carpenter for Year 11 IPT Assessment Task #2.) 2019.
-->
<html lang="en-AU">

<head>
  <title>Contact Us — Macleay Netball Association</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
  <link rel="stylesheet" href="../style.css" type="text/css">
  <!-- Internal Stylesheet -->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
  <!-- External Font Stylesheet -->
  <link rel="shortcut icon" href="../Assets/Img/mnaHeader.png">
  <!-- Tab Browser Icon (Favicon) -->
</head>

<body>
  <div id="wrapper">
    <div class="navigation">
      <div class="menuDropDown">
        <button id="menuButton" title="Navigation Menu"><i class="fas fa-bars"></i> Menu</button>
        <div class="menuContent">
          <div class="menuRow">
            <div class="menuColumn">
              <i class="fas fa-home"></i> Home
              <i class="fas fa-address-book"></i> Association Contacts
            </div>
            <div class="menuColumn">
              <i class="fas fa-user-friends"></i> Weekly Draw
              <i class="far fa-newspaper"></i> News
            </div>
            <div class="menuColumn">
              <i class="fas fa-bookmark"></i> Quick Links
              <i class="fas fa-certificate"></i> Representative Teams
            </div>
            <div class="menuColumn">
              <i class="fas fa-file"></i> Documentation
              <i class="fas fa-phone"></i> Contact Us
            </div>
          </div>
        </div>
      </div>
      <img src="../Assets/Img/mnaHeader.png" alt="Macleay Netball Association" title="Macleay Netball Association" class="logo">
      <!-- Macleay Netball Association Main Logo -->
    </div>
    <!-- End of Navigation -->
    <div class="main">
      <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3417.0548484369647!2d152.83521681537312!3d-31.080401281517187!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x6b9ddf84d6da904b%3A0xfc941d1ded8f7a25!2sPam+Guyer+Netball+Centre!5e0!3m2!1sen!2sau!4v1559129788713!5m2!1sen!2sau"
        width="100%" height="400px" frameborder="0" style="border:0" allowfullscreen></iframe>
      <!-- Google Maps Embed -->
      <br>

      <div class="row">
        <div id="column">1</div>
        <div id="column">2</div>
      </div>
      <!-- End of Footer -->
    </div>
    <!-- End of Main -->
  </div>
  <!-- End of Wrapper -->
</body>

</html></code>```

Attached are some images if I put position:fixed bottom:0 in the #column CSS Code. Only Column 2 goes down, 1 is hidden.

答:
Add an id to the element you want as a footer, remove the class and use the css below to style the element.</p>

```<code>#footer {
clear: both;
}
</code>```

```<code><div id="footer">
<div id="column">1</div>
<div id="column">2</div>
</div> <!-- End of Footer -->
</code>```

Body:
I have a two-columned div element that I need to have at the bottom of the page to act as a footer. The problem is I have tried using position:fixed and bottom:0 to make the element appear at the bottom. This works but only brings one of the #column divs down to the bottom, the other disappears. I would appreciate any assistance.

Code:

/* ~ Copyright (c) Macleay Netball Association (made by Tom Carpenter for Year 11 IPT Assessment Task #2.) 2019. */

html>body {
  background: none;
  padding: 0;
  margin: 0;
  height: 100%;
  overflow: hidden;
  font-family: 'Trebuchet MS', sans-serif;
  /* Trebuchet MS as main font throughout website, sans-serif acting as a backup */
}

#wrapper {
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  position: absolute;
  background: #1B315E;
}

::-webkit-scrollbar {
  display: none;
}

* {
  box-sizing: border-box;
  /* Alignment of DropDown Navigation Menu and Slideshow */
}

.navigation {
  background: #444;
  overflow: hidden;
  top: 0;
}

.menuDropDown {
  overflow: hidden;
  float: left;
}

.menuDropDown>#menuButton {
  font-size: 12px;
  padding: 16px 16px;
  /* Will result in final height of navigation */
  margin: 0;
  outline: none;
  border: none;
  font: inherit;
  background: inherit;
  color: #FFF;
}

#menuButton:hover,
.navigation>.menuDropDown:hover>#menuButton {
  border: none;
  outline: none;
  background: #666;
  color: #1B315E;
}

.menuDropDown:hover>.menuContent {
  display: block;
}

.menuContent {
  display: none;
  position: absolute;
  background: none;
  width: 100%;
  left: 0;
  max-height: 85vh;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.menuRow:after {
  display: table;
  clear: both;
  content: "";
}

.menuColumn {
  width: 25%;
  height: 100px;
  overflow-y: auto;
  padding: 5px;
  float: left;
  background: #666;
}

.menuColumn>a {
  float: none;
  display: block;
  text-align: left;
  text-decoration: none;
  font-size: 14px;
  padding: 8px;
  color: #1B315E;
}

.menuColumn>a.current {
  background: #777;
}

.menuColumn>a:hover {
  background: #888;
}

.logo {
  float: right;
  padding-right: 10px;
  width: 60px;
  height: 50px;
}

.main {
  width: 100%;
  height: calc(100vh - 43px);
  float: left;
  background: none;
  position: absolute;
  overflow: auto;
  padding: 8px;
}

.mainHeader {
  color: #FFF;
  text-align: center;
}

.mainImg {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}

.mainBody {
  color: #FFF;
  padding: 8px;
}

.row:after {
  content: "";
  clear: both;
  display: table;
}

.column {
  float: left;
  width: 33.33%;
  padding: 8px;
}

#column {
  float: left;
  width: 50%;
  padding: 8px;
  background: #888;
  bottom: 0;
}

.sponsers {
  float: left;
  width: 20%;
  padding: 8px;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
}

.sponsers:hover {
  -webkit-filter: grayscale(80%);
  filter: grayscale(80%);
}

.slideshow {
  /* Slideshow Container containing Images, Sliders and Captions */
  position: relative;
  margin: auto;
  max-width: 1000px;
}

.slides {
  display: none;
}

.slideshowImages {
  width: 100%;
}

.slideButton {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  padding: 16px 32px;
  font-size: 18px;
  text-align: center;
  border-radius: 10px;
  font-weight: bold;
}

.mnaHeader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.slideButton:hover {
  background: #666;
}

.previous,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: #FFF;
  font-weight: bold;
  font-size: 18px;
  transition: 0.3s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.previous:hover,
.next:hover {
  background: rgba(0, 0, 0, 0.8);
}

table {
  width: 100%;
  font-size: 16px;
  color: #FFF;
}

.tableCaption {
  font-weight: bold;
  font-size: 18px;
  color: #33CC33;
}

table,
th,
td {
  border-collapse: collapse;
  border: 2px solid #888;
}

th,
td {
  padding: 8px;
  text-align: left;
}

#headerTable {
  width: 33.33%;
  background: #888;
  font-size: 18px;
  color: #33CC33;
}

.linkProp {
  color: #FFF;
  text-decoration: underline;
}

.newsPanel {
  width: 100%;
  background: #888;
  height: 135px;
}

.imgNewsPreview {
  width: 215px;
  height: 135px;
  padding: 4px;
  float: left;
}

.newsHeaderPreview {
  color: #FFF;
  margin-top: 0px;
}

.newsBodyPreview {
  color: #FFF;
  margin-top: -12px;
}

.caption {
  color: #33CC33;
  text-align: center;
  position: absolute;
  font-size: 20px;
  width: 100%;
  padding: 8px 12px;
  bottom: 16px;
}

.collapsible {
  background: #888;
  color: #FFF;
  font-weight: bold;
  width: 100%;
  padding: 18px;
  cursor: pointer;
  font-size: 16px;
  outline: none;
  border: none;
  text-align: left;
}

.active,
.collapsible:hover {
  background: #666;
}

.collapsible:after {
  content: '\002B';
  color: #FFF;
  font-weight: bold;
  float: right;
  margin-left: 4px;
}

.active:after {
  content: '\2212';
}

.contentCollapsible {
  padding: 0px 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background: #F8F8F8;
}

.fade {
  -webkit-animation-name: fade;
  /* To work on Safari (Apple) */
  -webkit-animation-duration: 1s;
  /* To work on Safari (Apple) */
  animation-name: fade;
  animation-duration: 1s;
}

.buttonReturn {
  position: absolute;
  margin-left: 20px;
  margin-top: 20px;
  background: #888;
  color: #FFF;
  border: none;
  cursor: pointer;
  font-size: 36px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
}

.videoProp {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
  height: 400px;
}

@-webkit-keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: 0.4
  }
  to {
    opacity: 1
  }
}

@media screen and (max-width: 600px) {
  /* Stacks navigation menu acting for the site to be responsive */
  .menuColumn {
    width: 100%;
    height: auto;
  }
}

@media screen and (max-width: 800px) {
  /* Stacks Image Header on Top - acting as responsive */
  .column,
  #column {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Responsive Sponser Images */
  .sponsers {
    width: 33.33%;
  }
}

@media screen and (max-width: 800px) {
  /* Increases video resolution as screen reduces */
  .videoProp {
    width: 100%;
  }
}

@media screen and (max-width: 600px) {
  /* Reduces font-size as screen resolution lowers */
  .newsBodyPreview {
    font-size: 14px;
  }
}

@media screen and (max-width: 300px) {
  /* Reduces font-sizes within the slideshow
 */
  .previous,
  .next,
  .caption {
    font-size: 14px;
  }
}

<!DOCTYPE HTML>

  <title>Contact Us — Macleay Netball Association</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0">
  <link rel="stylesheet" href="../style.css" type="text/css">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

  <link rel="shortcut icon" href="../Assets/Img/mnaHeader.png">

        <button id="menuButton" title="Navigation Menu"> Menu</button>

               Home
               Association Contacts

               Weekly Draw
               News

               Quick Links
               Representative Teams

               Documentation
               Contact Us

1

2

Attached are some images if I put position:fixed bottom:0 in the #column CSS Code. Only Column 2 goes down, 1 is hidden.

Body:
Add an id to the element you want as a footer, remove the class and use the css below to style the element.

#footer {
clear: both;
}

<div id="footer">
<div id="column">1</div>
<div id="column">2</div>
</div> <!-- End of Footer -->


问:
return last word in a file that starts with capital letter
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "
</code>```

but this isn't working.

I also tried this:

```<code>    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "
</code>```

Any help?

答:
You need are returning " " at first fail. That's why you don't get expected result.

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in reversed(word_list):
            if word[0].isupper():
                return word
        return ""
```

<p>However if your file is much bigger, you might want to read file in a reverse order. Which will let you find what you looking for much easier.</p>

<pre class="lang-py prettyprint-override"><code>import os

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        wordfile.seek(0, os.SEEK_END)
        position = wordfile.tell()
        word = ''
        while position >= 0:
            qfile.seek(position)
            next_char = qfile.read(1)
            if next_char == " ":
                if word[0].isupper():
                    return word
                word = ''
            else:
                word += next_char
            position -= 1
        return ""
</code>```

I suggest using similar approach to solve your problem.

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?

Body:
You need are returning " " at first fail. That's why you don't get expected result.

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in reversed(word_list):
            if word[0].isupper():
                return word
        return ""

However if your file is much bigger, you might want to read file in a reverse order. Which will let you find what you looking for much easier.

import os

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        wordfile.seek(0, os.SEEK_END)
        position = wordfile.tell()
        word = ''
        while position >= 0:
            qfile.seek(position)
            next_char = qfile.read(1)
            if next_char == " ":
                if word[0].isupper():
                    return word
                word = ''
            else:
                word += next_char
            position -= 1
        return ""

I suggest using similar approach to solve your problem.


问:
Python JIRA Non-Mandatory fields being forced on create issue
When using the jira python library and creating issues, non mandatory fields are being enforced on create_issue call.

Response on create issue attempt:

text: No issue link type with name 'Automated' found.

Response on create meta call to check mandatory fields:

'hasDefaultValue': False,
                                                               u'key': u'issuelinks',
                                                               u'name': u'Linked Issues',
                                                               u'operations': [u'add'],
                                                               u'required': False,

答:
Jira behaves strange many times.
createmeta call returns you all the possible issuetypes, and their all fields, and which field is mandatory or not.

But even after this, there are certain fields which are mandatory but createmeta wont tell you this. You need to rely on the exception message that you got after filing create_issue().

In the exception message, exception_obj.response.text gives you the json having key/value of exact field required.

Then, you can search in response of createmeta about its schema type, and may be the allowedValues set.
And, then try again.

Basically, you need to do retry of above mechanism.


问:
Can I exclude blanks / 0 from an ArrayFormula countif?
I have a simpe ArrayFormula:

```<code>=ArrayFormula(countif(I2:I,J2:J))
</code>```

How do I filter out the null counts?

The results I expect are rows that actually have results.  I don't want a sheet full of 0s.

答:
To avoid displaying all 0s in the relevant column (whether because 'I' or 'J' cell empty/blank) you might format it as:

```<code>#;
</code>```

Body:
I have a simpe ArrayFormula:

=ArrayFormula(countif(I2:I,J2:J))

How do I filter out the null counts?

The results I expect are rows that actually have results.  I don't want a sheet full of 0s.

Body:
To avoid displaying all 0s in the relevant column (whether because 'I' or 'J' cell empty/blank) you might format it as:

#;


问:
Call to undefined method Illuminate\Support\Facades\Redis::connect()
Running Laravel 5.7 via Homestead.

This is happening in:

```<code>/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php
"line":66
"function":"establishConnection"

</code>```

We are using PHP Redis and in config/database.php:

```<code>'redis' => [

        'client' => 'phpredis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 6,
        ],

    ],
</code>```

I've seen other answers on here and none of the steps work. There is no redis cluster in use.  PhpRedis extension is installed on VM and confirmed with php -m. Redis server is running at 127.0.0.1 and can be connected to outside of the code.

I'm unable to change the code as it works for others. It must be a configuration issue on my VM but I can't see what it could be. If anyone has had a similar issue I'd much appreciate any advice.

答:
The problem you are having is because of class naming conflict: PhpRedisConnector creates new \Redis client, but it seems that you have alias for Illuminate\Support\Facades\Redis facade set up somewhere in your app. PhpRedisConnector creates new Redis and gets facade object instead.

Try removing this line in your config/app.php:

```<code>'aliases' => [
    ...
    'Redis' => Illuminate\Support\Facades\Redis::class, // remove this line
    ...
]
</code>```

Body:
Running Laravel 5.7 via Homestead.

This is happening in:

/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php
"line":66
"function":"establishConnection"

We are using PHP Redis and in config/database.php:

'redis' => [

        'client' => 'phpredis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 6,
        ],

    ],

I've seen other answers on here and none of the steps work. There is no redis cluster in use.  PhpRedis extension is installed on VM and confirmed with php -m. Redis server is running at 127.0.0.1 and can be connected to outside of the code.

I'm unable to change the code as it works for others. It must be a configuration issue on my VM but I can't see what it could be. If anyone has had a similar issue I'd much appreciate any advice.

Body:
The problem you are having is because of class naming conflict: PhpRedisConnector creates new \Redis client, but it seems that you have alias for Illuminate\Support\Facades\Redis facade set up somewhere in your app. PhpRedisConnector creates new Redis and gets facade object instead.

Try removing this line in your config/app.php:

'aliases' => [
    ...
    'Redis' => Illuminate\Support\Facades\Redis::class, // remove this line
    ...
]


问:
Should I refactor code for unit testing in mvp android?
I made an mvp application in kotlin and in each function of my presenter I call a view method so should I refactor my code for unit-testing or i just let this like that?

For exemple i have a function that make a regex

```<code>private fun checkPassword(isRegister: Boolean, pass: String, confirmPass: String): Boolean {
    val regex = Regex("^(?=.{8,}\$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])")
    if (isRegister) {
        if (pass != confirmPass) {
            loginView.showNotMatchingPassword() // display an alert on a inputtext
            return false
        }
        if (!pass.contains(regex)) {
            loginView.showInvalidPassword() // display an alert on a inputtext
            return false
        }
    }
    return true
}
</code>```

答: your code is fine as per the MVP Architecture, you need not refactor the code. Your code is also testable in unit testing.</p>

Body:
I made an mvp application in kotlin and in each function of my presenter I call a view method so should I refactor my code for unit-testing or i just let this like that?

For exemple i have a function that make a regex

private fun checkPassword(isRegister: Boolean, pass: String, confirmPass: String): Boolean {
    val regex = Regex("^(?=.{8,}\$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])")
    if (isRegister) {
        if (pass != confirmPass) {
            loginView.showNotMatchingPassword() // display an alert on a inputtext
            return false
        }
        if (!pass.contains(regex)) {
            loginView.showInvalidPassword() // display an alert on a inputtext
            return false
        }
    }
    return true
}


问:
cannot get rid of date unit testing - javascript
I'm new to unit testing and I implementing a unit test for a function that returns date.

```<code>const getLastHour = () => {
const date = new Date().getTime() - 3600000;
return date;
};
</code>```

I made something like this but it deosn't work

```<code>describe('getLastHour', () => {
        const getLastHour = mobileArticleService.__get__('getLastHour');
        const getTime = sinon.stub(2019052906);
        const Date = sinon.stub({ getTime });

        before(() => {
            mobileArticleService.__set__({
                Date,
                getTime,
            });
        });

        it('should return date with hours ', () => {
            expect(Date).to.be.called;
            expect(getTime).to.be.called;
        });
    });
</code>```

答:
You are not actually stubbing the Date in your current implementation and not calling your unit under test. If you are trying to unit test that function, stub the dependancies. Unit tests focus a lot on inputs and outputs of a single unit of work.

```<code>describe('My Test', function () {
  const dateStub;

  before('', function () {
    dateStub = sinon.stub(Date, 'getTime').returns(143434325325);
  });

  it('should return date with hours ', () => {
    const result = getLastHour();
    expect(dateStub).to.be.called;
  });
});
</code>```

Body:
I'm new to unit testing and I implementing a unit test for a function that returns date.

const getLastHour = () => {
const date = new Date().getTime() - 3600000;
return date;
};

I made something like this but it deosn't work

describe('getLastHour', () => {
        const getLastHour = mobileArticleService.__get__('getLastHour');
        const getTime = sinon.stub(2019052906);
        const Date = sinon.stub({ getTime });

        before(() => {
            mobileArticleService.__set__({
                Date,
                getTime,
            });
        });

        it('should return date with hours ', () => {
            expect(Date).to.be.called;
            expect(getTime).to.be.called;
        });
    });

Body:
You are not actually stubbing the Date in your current implementation and not calling your unit under test. If you are trying to unit test that function, stub the dependancies. Unit tests focus a lot on inputs and outputs of a single unit of work.

describe('My Test', function () {
  const dateStub;

  before('', function () {
    dateStub = sinon.stub(Date, 'getTime').returns(143434325325);
  });

  it('should return date with hours ', () => {
    const result = getLastHour();
    expect(dateStub).to.be.called;
  });
});


问:
Can I capture Performance Counters for an Azure Web/Worker Role remotely...?
I am aware of the generation of the Performance Counters and Diagnosis in webrole and worker-role in Azure.

My question is can I get the Performance Counter on a remote place or remote app, given the subscription ID and other certificates (3rd Party app to give performance Counter).

Question in other words, Can I get the Performance Counter Data, the way I use Service Management API for any hosted service...?

What are the pre-configurations required to be done in Server...? to get CPU data...???

答:
Following is the description of the attributes for Performance counters table:

EventTickCount: Stores the tick count (in UTC) when the log entry was recorded.

DeploymentId: Id of your deployment.

Role: Role name

RoleInstance: Role instance name

CounterName: Name of the counter

CounterValue: Value of the performance counter

One of the key thing here is to understand how to effectively query this table (and other diagnostics table). One of the things we would want from the diagnostics table is to fetch the data for a certain period of time. Our natural instinct would be to query this table on Timestamp attribute. However that's a BAD DESIGN choice because you know in an Azure table the data is indexed on PartitionKey and RowKey. Querying on any other attribute will result in full table scan which will create a problem when your table contains a lot of data.

The good thing about these logs table is that PartitionKey value in a way represents the date/time when the data point was collected. Basically PartitionKey is created by using higher order bits of DateTime.Ticks (in UTC). So if you were to fetch the data for a certain date/time range, first you would need to calculate the Ticks for your range (in UTC) and then prepend a "0" in front of it and use those values in your query.

If you're querying using REST API, you would use syntax like:

PartitionKey ge '0<from date/time ticks in UTC>' and PartitionKey le '0<to date/time in UTC>'.

You could use this syntax if you're querying table storage in our tool Cloud Storage Studio, Visual Studio or Azure Storage Explorer.

Unfortunately I don't have much experience with the Storage Client library but let me work something out. May be I will write a blog post about it. Once I do that, I will post the link to my blog post here.

Gaurav

ContentLicense: CC BY-SA 3.0


问:
Android SQLite auto increment
I currently have a table called User which has a id column which is created as

'INTEGER PRIMARY KEY'

Lets say I have created two users so the table has id 1 and 2

If I delete the second user and create a third the id is 2, I need this to be 3

So it seems Android is selecting the next available id, how can I change this to its more like  a sequence number?

Regards

答:
If speaking for ANDROID, yes, above answers are correct, except naming of the id column.

```<code>   database.execSQL("CREATE TABLE IF NOT EXISTS "
                + TableName
                + " ( rowid INTEGER PRIMARY KEY AUTOINCREMENT,  Raqam VARCHAR, ChandBor INT(3));");
</code>```

It looks like in Android it should be named as 'rowid'.
And with Cursor you need to instantiate it like:

```<code>Cursor cursorLcl = database.rawQuery("SELECT *," + TableName + ".rowid AS rowid" + " FROM " +
                TableName, null);
</code>```

Otherwise it didnt work for me. I don't know why it so.

Title: Android SQLite auto increment

Body:
If speaking for ANDROID, yes, above answers are correct, except naming of the id column.

   database.execSQL("CREATE TABLE IF NOT EXISTS "
                + TableName
                + " ( rowid INTEGER PRIMARY KEY AUTOINCREMENT,  Raqam VARCHAR, ChandBor INT(3));");

It looks like in Android it should be named as 'rowid'.
And with Cursor you need to instantiate it like:

Cursor cursorLcl = database.rawQuery("SELECT *," + TableName + ".rowid AS rowid" + " FROM " +
                TableName, null);

Otherwise it didnt work for me. I don't know why it so.


问:
how to fix passing variable from view to html
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page

view file:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]

    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)
```

<p>html file:</p>

<pre class="lang-html prettyprint-override"><code>      <table>
        <tbody>
            {% for SiteUrls in urlpost %}
          <tr>
            <td>{{SiteUrls.site_title}}</td>
            <td>{{SiteUrls.site_url}}</td>

            <td> {{res}} </td>

            <td>open Site</td>
          </tr>
            {% endfor %}
        </tbody>
      </table>
</code>```

i would like to get back the specific result for each line

答:
Don't use .values_list(). Work with the objects instead and add your value as an additional attribute.

Note that in your code, you are limiting your SiteUrls query to 20 objects, but then you ping all SiteUrls in your DB. I assume you only want to ping these 20 SiteUrls.

```<code>def index(request):

    posts = Layout.objects.all()
    urlpost = list(SiteUrls.objects.all()[:20])

    for site_url in urlpost:
        print(site_url.site_url)
        res = os.system("ping -n 1 " + site_url.site_url )

        if res == 0:
            site_url.res = "connected"
        else:
            site_url.res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
    }

    return render (request, 'posts/index.html', context)
</code>```

Template:

```<code>  <table>
    <tbody>
        {% for SiteUrls in urlpost %}
      <tr>
        <td>{{SiteUrls.site_title}}</td>
        <td>{{SiteUrls.site_url}}</td>

        <td> {{SiteUrls.res}} </td>

        <td><a style="margin-bottom:10px" class="waves-effect waves-light btn">open Site</a></td>
      </tr>
        {% endfor %}
    </tbody>
  </table>
</code>```

Also, it is generally considered a bad idea to call system processes like that in a web request like you are doing here. Once you got this to work, I encourage you to research the concept of task queues.

Body:
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page

view file:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]

    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)

html file:

            {% for SiteUrls in urlpost %}

            {{SiteUrls.site_title}}
            {{SiteUrls.site_url}}

             {{res}}

            open Site

            {% endfor %}

i would like to get back the specific result for each line

Body:
Don't use .values_list(). Work with the objects instead and add your value as an additional attribute.

Note that in your code, you are limiting your SiteUrls query to 20 objects, but then you ping all SiteUrls in your DB. I assume you only want to ping these 20 SiteUrls.

def index(request):

    posts = Layout.objects.all()
    urlpost = list(SiteUrls.objects.all()[:20])

    for site_url in urlpost:
        print(site_url.site_url)
        res = os.system("ping -n 1 " + site_url.site_url )

        if res == 0:
            site_url.res = "connected"
        else:
            site_url.res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
    }

    return render (request, 'posts/index.html', context)

Template:

  <table>
    <tbody>
        {% for SiteUrls in urlpost %}
      <tr>
        <td>{{SiteUrls.site_title}}</td>
        <td>{{SiteUrls.site_url}}</td>

        <td> {{SiteUrls.res}} </td>

        <td><a style="margin-bottom:10px" class="waves-effect waves-light btn">open Site</a></td>
      </tr>
        {% endfor %}
    </tbody>
  </table>

Also, it is generally considered a bad idea to call system processes like that in a web request like you are doing here. Once you got this to work, I encourage you to research the concept of task queues.


答:
You can try with reversed and is_upper keywords:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        word_list = reversed(word_list)
        for word in word_list:
            if word[0].isupper():
                return word

print(find_last_capitalised("demo.txt"))
</code>```

Title: return last word in a file that starts with capital letter

Body:
You can try with reversed and is_upper keywords:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        word_list = reversed(word_list)
        for word in word_list:
            if word[0].isupper():
                return word

print(find_last_capitalised("demo.txt"))


问:
Time-complexity with recursion
Below is an algorithm that find the biggest sum in a triangle. I want to say this algorithm is O(N^2) since the findMax function call can be replaced with a nested for loop looking through each child for each node. However the recursion make me uncertain. So how can I tell the time-complexity of this code with recursion?</p>

```<code>int maxValue = 0;

void findMax ( Node * n , int sum ) {

if ( n == NULL ) {

    if ( maxValue < sum ) {

        maxValue = sum ;

    }

    return ;

}

findMax (n - > leftChild , sum + n - > value ) ;

findMax (n - > rightChild , sum + n - > value ) ;
}
</code>```

答:
```<code>int maxValue = 0; // will be executed once so O(1).

void findMax ( Node * n , int sum ) {

if ( n == NULL ) { // Will be executed in every call of function so if considering the function is called C times it is O(C)

    if ( maxValue < sum ) { // will be executed if the previous if is right so O(c')

        maxValue = sum ; // will be exceuted if the previous if is right so O(c')

    }

    return ; // will be executed once so O(1)

}

findMax (n - > leftChild , sum + n - > value ) ; // visiting every left child of each node

findMax (n - > rightChild , sum + n - > value ) ; // visiting every right child of each node

// so we are visiting every node at least once if we have n node and m connections(edges) between nodes we have:
// O(n+m+C(c'+c'+1))=O(n+m) + O(K)
</code>```

Title: Time-complexity with recursion

Body:
Below is an algorithm that find the biggest sum in a triangle. I want to say this algorithm is O(N^2) since the findMax function call can be replaced with a nested for loop looking through each child for each node. However the recursion make me uncertain. So how can I tell the time-complexity of this code with recursion?

int maxValue = 0;

void findMax ( Node * n , int sum ) {

if ( n == NULL ) {

    if ( maxValue < sum ) {

        maxValue = sum ;

    }

    return ;

}

findMax (n - > leftChild , sum + n - > value ) ;

findMax (n - > rightChild , sum + n - > value ) ;
}


问:
How to execute one function whether it normal or carried and yield the same result?
What would be the body of a the multiply function that if executed in both ways below would give the same result. So either calling multiply(2,4) or multiply(2)(4) would output 8?

答:
Whenever you have a curied function, you need some way to end the currying, just as you need a base case for recursion. That end condition can either be

(1) the number of arguments, e.g. 2 in this case:

```<code>  const curry = (fn, n) => {
     const c = (...args) => (...args2) => args.length + args.length >= n ? fn(...args, ...args2) : c(...args, ...args2);
     return c();
  };

  const add = curry((a, b) => a + b, 2);
</code>```

(1b) For sure that can also be derived from the functions signature:

```<code> const curry = (fn, ...keep) => (...args) => keep.length + args.length >= fn.length ? fn(...keep,  ...args) : curry(fn, ...keep, ...args);

 const add = curry((a, b) => a + b);
</code>```

(2) a final empty function call e.g. add(1, 2)() or add(1)(2)()

```<code>   const curry = fn => (...args) => (...args2) => args2.length ? curry(fn)(...args, ...args2) : fn(...args, ...args2);

  const add = curry((a, b) => a + b);
</code>```

(3) some typecast at the end, to trigger the result to be calculated, e.g. +add(1, 2) or +add(1)(2):

```<code>  const curry = (fn, ...keep) => {
    const c = (...args) => curry(fn, ...keep, ...args);
    c.valueOf = () => fn(...keep);
    return c;
  };

  const add = curry((a, b) => a + b);
</code>```

Body:
Whenever you have a curied function, you need some way to end the currying, just as you need a base case for recursion. That end condition can either be

(1) the number of arguments, e.g. 2 in this case:

  const curry = (fn, n) => {
     const c = (...args) => (...args2) => args.length + args.length >= n ? fn(...args, ...args2) : c(...args, ...args2);
     return c();
  };

  const add = curry((a, b) => a + b, 2);

(1b) For sure that can also be derived from the functions signature:

 const curry = (fn, ...keep) => (...args) => keep.length + args.length >= fn.length ? fn(...keep,  ...args) : curry(fn, ...keep, ...args);

 const add = curry((a, b) => a + b);

(2) a final empty function call e.g. add(1, 2)() or add(1)(2)()

   const curry = fn => (...args) => (...args2) => args2.length ? curry(fn)(...args, ...args2) : fn(...args, ...args2);

  const add = curry((a, b) => a + b);

(3) some typecast at the end, to trigger the result to be calculated, e.g. +add(1, 2) or +add(1)(2):

  const curry = (fn, ...keep) => {
    const c = (...args) => curry(fn, ...keep, ...args);
    c.valueOf = () => fn(...keep);
    return c;
  };

  const add = curry((a, b) => a + b);


问:
How to save a recorded audio in objective C (iPhone)
I am using AV audio framework to record audio files on the iPhone. Here is the current code :

```<code>NSArray *dirPaths;
NSString *docsDir;

dirPaths = NSSearchPathForDirectoriesInDomains(
                                               NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
                           stringByAppendingPathComponent:@"sound.caf"];

NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

NSDictionary *recordSettings = [NSDictionary
                                dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithInt:AVAudioQualityMin],
                                AVEncoderAudioQualityKey,
                                [NSNumber numberWithInt:16],
                                AVEncoderBitRateKey,
                                [NSNumber numberWithInt: 2],
                                AVNumberOfChannelsKey,
                                [NSNumber numberWithFloat:44100.0],
                                AVSampleRateKey,
                                nil];

NSError *error = nil;

audioRecorder = [[AVAudioRecorder alloc]
                 initWithURL:soundFileURL
                 settings:recordSettings
                 error:&error];
</code>```

Now I have another function and I want to send the sound.caf file to that function something like:

```<code>NSData *soundData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:soundFilePath ofType:@"caf"]];
</code>```

But for some reason that above line seems to return a 0kb file.

Any suggestions?

答:
I don't see you triggering the record method:
http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html

Nor points your file open to the same file name.

Last, you cant save in the app directory. You can only save data in the Documents folder.

Body:
I am using AV audio framework to record audio files on the iPhone. Here is the current code :

NSArray *dirPaths;
NSString *docsDir;

dirPaths = NSSearchPathForDirectoriesInDomains(
                                               NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
                           stringByAppendingPathComponent:@"sound.caf"];

NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

NSDictionary *recordSettings = [NSDictionary
                                dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithInt:AVAudioQualityMin],
                                AVEncoderAudioQualityKey,
                                [NSNumber numberWithInt:16],
                                AVEncoderBitRateKey,
                                [NSNumber numberWithInt: 2],
                                AVNumberOfChannelsKey,
                                [NSNumber numberWithFloat:44100.0],
                                AVSampleRateKey,
                                nil];

NSError *error = nil;

audioRecorder = [[AVAudioRecorder alloc]
                 initWithURL:soundFileURL
                 settings:recordSettings
                 error:&error];

Now I have another function and I want to send the sound.caf file to that function something like:

NSData *soundData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:soundFilePath ofType:@"caf"]];

But for some reason that above line seems to return a 0kb file.

Any suggestions?


问:
How can i change a boolean value in model A, when a new instance of model B (have many2one field to model A) is created in ODOO 12?
I have two odoo 12 models,(biblio.location and biblio.book),
-the model "biblio.book" contains a boolean "disponibile" set to true by defaul.
-the model "biblio.location" have a many2one field references to model "biblio.book".

i want the value of the boolean "disponible" in biblio.book to be changed automatically (change also in database) when a new instance of biblio.location is created, in other way when we rent(location) a book we must change disponibility in model book to FALSE.

i tried "computed field, @api.onchange and @api.depends" and nothing works for me, please help me in this issue and i want to know de difference between those three mehods.thank you

class book(models.Model):

```<code>_name = 'biblio.book'
_description = 'All books'
name=fields.Char()
annee_edition = fields.Date(string="année d'édition")
ISBN = fields.Integer(required=True)
editor = fields.Char(required=True)
auteur = fields.Many2many('biblio.author',string='auteur_livre',required=True)
</code>```

disponible=fields.Boolean(default=True,required=True,related='biblio.location.disponible',store=True )

class location(models.Model):

```<code>_name = 'biblio.location'
_description = 'All librarians'

name=fields.Char()
livre = fields.Many2one('biblio.book',string='livre',required=True,domain =[('disponible','=',True)])
client = fields.Many2one('biblio.customer',string="client",required=True)
date_location =fields.Datetime(required=True)
date_retour_prevu=fields.Datetime(required=True,string="Date retour prévu")
date_retour_reelle=fields.Datetime(required=True,string="Date retour réelle")
</code>```

disponible = fields.Boolean(default=False)

File "C:\Users\PycharmProjects\Odoo12\odoo\odoo\fields.py", line 484, in setup_full
    self._setup_related_full(model)
  File "C:\User\PycharmProjects\Odoo12\odoo\odoo\fields.py", line 527, in _setup_related_full field = target._fields[name]
KeyError: 'biblio' - - -

答:
OK, for this to work the way you want it you need to set up a foreign key in your biblio.book model.

```<code>book_location = fields.Many2one('biblio.location', string='Book Location')
</code>```

Then you can do your computed field

```<code>disponible = field.Boolean(compute='_disponible', string='Available for Loan', default=False)

@api.model
def _disponible(self):
    for book in self:
        book.disponible = True if book.book_location else False
</code>```

You don't want to set this as storable as you want it to check every time that the field is called.  If you set it to storable it will only compute when the record is created.

Body:
I have two odoo 12 models,(biblio.location and biblio.book),
-the model "biblio.book" contains a boolean "disponibile" set to true by defaul.
-the model "biblio.location" have a many2one field references to model "biblio.book".

i want the value of the boolean "disponible" in biblio.book to be changed automatically (change also in database) when a new instance of biblio.location is created, in other way when we rent(location) a book we must change disponibility in model book to FALSE.

i tried "computed field, @api.onchange and @api.depends" and nothing works for me, please help me in this issue and i want to know de difference between those three mehods.thank you

class book(models.Model):

_name = 'biblio.book'
_description = 'All books'
name=fields.Char()
annee_edition = fields.Date(string="année d'édition")
ISBN = fields.Integer(required=True)
editor = fields.Char(required=True)
auteur = fields.Many2many('biblio.author',string='auteur_livre',required=True)

disponible=fields.Boolean(default=True,required=True,related='biblio.location.disponible',store=True )

class location(models.Model):

_name = 'biblio.location'
_description = 'All librarians'

name=fields.Char()
livre = fields.Many2one('biblio.book',string='livre',required=True,domain =[('disponible','=',True)])
client = fields.Many2one('biblio.customer',string="client",required=True)
date_location =fields.Datetime(required=True)
date_retour_prevu=fields.Datetime(required=True,string="Date retour prévu")
date_retour_reelle=fields.Datetime(required=True,string="Date retour réelle")

disponible = fields.Boolean(default=False)

File "C:\Users\PycharmProjects\Odoo12\odoo\odoo\fields.py", line 484, in setup_full
    self._setup_related_full(model)
  File "C:\User\PycharmProjects\Odoo12\odoo\odoo\fields.py", line 527, in _setup_related_full field = target._fields[name]
KeyError: 'biblio' - - -

Body:
OK, for this to work the way you want it you need to set up a foreign key in your biblio.book model.

book_location = fields.Many2one('biblio.location', string='Book Location')

Then you can do your computed field

disponible = field.Boolean(compute='_disponible', string='Available for Loan', default=False)

@api.model
def _disponible(self):
    for book in self:
        book.disponible = True if book.book_location else False

You don't want to set this as storable as you want it to check every time that the field is called.  If you set it to storable it will only compute when the record is created.


答:
Fist of all, your algorithm would return the first capitlized word, not the last so there needs to be a little change in logic. Also the simplest way to check if word is capitalized is provided:</p>

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        last_cap_word = " "
        for word in word_list:
            if word[0].isupper():
                last_cap_word = word

        return last_cap_word
</code>```

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?

Body:
Fist of all, your algorithm would return the first capitlized word, not the last so there needs to be a little change in logic. Also the simplest way to check if word is capitalized is provided:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        last_cap_word = " "
        for word in word_list:
            if word[0].isupper():
                last_cap_word = word

        return last_cap_word


问:
How to implement desktop push notifications in an Angular 7 web application supporting Safari?
I implemented this feature using Firebase Cloud Messaging. But it is not working in Safari since it lack Push API support ( which the FCM is built upon). Have somebody implemented it in a proper manner to support all 3 major browsers?</p>

答:
If you are using Nodejs then you can go for node-notifier. Easiest method to implement notification service.

https://www.npmjs.com/package/node-notifier

```<code>npm i node-notifier

const notifier = require('node-notifier');
// String
notifier.notify('Message');

// Object
notifier.notify({
  title: 'My notification',
  message: 'Hello, there!'
});
</code>```

Body:
If you are using Nodejs then you can go for node-notifier. Easiest method to implement notification service.

https://www.npmjs.com/package/node-notifier

npm i node-notifier

const notifier = require('node-notifier');
// String
notifier.notify('Message');

// Object
notifier.notify({
  title: 'My notification',
  message: 'Hello, there!'
});


问:
Can I invoke a delegate/function pointer passed into a remote web service using ASP.NET?
Assuming you have a remote .NET web service(meaning it doesn't reside on the same server as the consuming client) what will the behavior be if you attempt to pass a delegate into the web service and invoke it?</p>

答:
An exception at best -- delegates can't cross system boundaries in that manner.

Now, you can perhaps get to the same plays doing an asynchronous call to create a continuation of sorts . . .


问:
Change item background on RecyclerView item
I want to make clickable item of my RecyclerView. However it is not working. item_background.xml is defined well, it works in other parts of my project. However in this case, I have more items in LinearLayout, which contain some onClick listeners. When I click on an item, background is not changed. Please see the code below.

I cannot set background for inside items instead, because I need the whole item to change background color, not only parts.

item.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:background="@drawable/item_background"
    android:clickable="true"
    ...
    >

    <TextView
        <!-- NO BACKGROUND -->
        ... />

    <ImageView
        <!-- NO BACKGROUND -->
        ... />

    ...

</LinearLayout>
</code>```

item_bg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/darker_gray" android:state_pressed="true"/>
    <item android:drawable="@android:color/darker_gray" android:state_focused="true"/>
    <item android:drawable="@android:color/transparent"/>
</selector>
</code>```

答:
To change the background or highlight the selected item in recyclerview you can try this

```<code>public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
        private int selected_position = -1;

        @Override
        public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
            if (selected_position == position) {
                // do your stuff here like
                //Change selected item background
               parentLayout.setBackgroundColor(Color.parse("darkgraycolorcode"));

            } else {
                  // do your stuff here like
                  //Change  unselected item background
                   parentLayout.setBackgroundColor(Color.TRANSPARENT);
            }
  // rest of the code here

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(selected_position==position){
                        selected_position=-1;
                        notifyDataSetChanged();
                        return;
                    }
                    selected_position = position;
                    notifyDataSetChanged();

            }
        });

    //rest of the code here

     }

}
</code>```

Also you can define the parent layout click listener ie linearlayout in view holder also

Body:
I want to make clickable item of my RecyclerView. However it is not working. item_background.xml is defined well, it works in other parts of my project. However in this case, I have more items in LinearLayout, which contain some onClick listeners. When I click on an item, background is not changed. Please see the code below.

I cannot set background for inside items instead, because I need the whole item to change background color, not only parts.

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:background="@drawable/item_background"
    android:clickable="true"
    ...
    >

    <TextView

        ... />

    <ImageView

        ... />

    ...

</LinearLayout>

item_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/darker_gray" android:state_pressed="true"/>
    <item android:drawable="@android:color/darker_gray" android:state_focused="true"/>
    <item android:drawable="@android:color/transparent"/>
</selector>

Body:
To change the background or highlight the selected item in recyclerview you can try this

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.ViewHolder> {
        private int selected_position = -1;

        @Override
        public void onBindViewHolder(PlacesLocationAdapter.ViewHolder holder, final int position) {
            if (selected_position == position) {
                // do your stuff here like
                //Change selected item background
               parentLayout.setBackgroundColor(Color.parse("darkgraycolorcode"));

            } else {
                  // do your stuff here like
                  //Change  unselected item background
                   parentLayout.setBackgroundColor(Color.TRANSPARENT);
            }
  // rest of the code here

    holder.linelayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(selected_position==position){
                        selected_position=-1;
                        notifyDataSetChanged();
                        return;
                    }
                    selected_position = position;
                    notifyDataSetChanged();

            }
        });

    //rest of the code here

     }

}

Also you can define the parent layout click listener ie linearlayout in view holder also


问:
Position navbar icons inline on mobile with Bootstrap 4?
I'm trying to configure a navbar in Bootstrap 4 to display additional icons to left the hamburger menu that only display on mobile.

I'm not able to get the icons to display inline and can't sort out where i am going wrong.

I add the classes navbar-nav to the list, d-lg-none to hide on larger devices. Are there built in classes in bootstrap that can fix the alignment of these? I can't even sort out where i am going wrong.

HTML:

```<code>        <nav class="navbar navbar-expand-lg">
            <div class="container">
                <a class="navbar-brand" href="#">
                    <img src="assets/images/logo-blue-sm.png" alt="">
                </a>
                <ul class="navbar-nav d-lg-none ml-auto navbar-icons ">
                    <li class="nav-item">
                        <a class="nav-link" href="tel:+1234567890"><i class="fa fa-3x fa-map-marker"></i></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="tel:+1234567890"><i class="fa fa-3x fa-comments"></i></a>
                    </li>
                </ul>
                <button class="navbar-toggler ml-auto" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"> </span>
                </button>
                <div class="collapse navbar-collapse" id="navbarCollapse">
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="docMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Experience</a>
                            <ul class="dropdown-menu" aria-labelledby="docMenu">
                                <li> <a class="dropdown-item" href="#">Our Story</a> </li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <div class="nav-item border-0 d-none d-lg-inline-block align-self-center">
                    <a href="#" class=" btn btn-sm btn-grad text-white mb-0">Get Started</a>
                </div>
            </div>
        </div>
    </nav>
</code>```

Additional CSS:

```<code>.navbar-icons .nav-item{
  border-bottom:none;
  padding:0 5px;
  position:relative;
 }
</code>```

答:
Based on your layout you could easily solve that using bootstrap flex utility classes Read more.

Just add d-flex and flex-row classes to the ul that contains the items:

```<code><ul class="navbar-nav d-lg-none ml-auto navbar-icons d-flex flex-row">
</code>```

this will change the uls display to flex and force the flex direction to be row style, so the items will be displayed side by side.

here is a very good guide to flexbox. try understanding the basics and using it together with the bootstrap flex classes.

Body:
I'm trying to configure a navbar in Bootstrap 4 to display additional icons to left the hamburger menu that only display on mobile.

I'm not able to get the icons to display inline and can't sort out where i am going wrong.

I add the classes navbar-nav to the list, d-lg-none to hide on larger devices. Are there built in classes in bootstrap that can fix the alignment of these? I can't even sort out where i am going wrong.

HTML:

                <button class="navbar-toggler ml-auto" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Experience

 Our Story

                    Get Started

Additional CSS:

.navbar-icons .nav-item{
  border-bottom:none;
  padding:0 5px;
  position:relative;
 }

Body:
Based on your layout you could easily solve that using bootstrap flex utility classes Read more.

Just add d-flex and flex-row classes to the ul that contains the items:

<ul class="navbar-nav d-lg-none ml-auto navbar-icons d-flex flex-row">

this will change the uls display to flex and force the flex direction to be row style, so the items will be displayed side by side.

here is a very good guide to flexbox. try understanding the basics and using it together with the bootstrap flex classes.


问:
How to clear the field after i set ComboBox value as null?
I have a ComboBox  called projectRequirementComboBox that is dependent from projectComboBox, from where I get the list to show in the dropdown in projectRequirementComboBox, but I want to do something like: when a user changes the project I want to empty projectRequirementComboBox, to be more clear none of the item will not be selected I am doing this right now but still my projectRequirementComboBox  has the old value, I don't know what am I missing .I am using vaadin.version 8.0.7 .

```<code>private void refreshProjectRequirementCombobox()
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (projectComboBox.getValue() != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(projectComboBox.getValue().getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
    projectRequirementComboBox.setValue(null);

}

private void loadProjectRequirement(Project project)
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (project != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(project.getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
}
</code>```

I call refreshProjectRequirementCombobox here.

```<code> projectComboBox.addValueChangeListener(event ->
            {
                refreshProjectRequirementCombobox();
                loadRejectReason();
            });
</code>```

答:
Normally this should work. I created a minimum example with two ComboBoxes "main" and "dependent". The selection of the dependent ComboBox depends on the selection of the main ComboBox. Therefore there is a ValueChangeListener on the main ComboBox that resets the items and the selected value of the dependent ComboBox. When you start the application you see that the offered items of the dependent ComboBox change and that none of these new items is selected.

I think you have to post more of your code (where do you call refreshProjectRequirementCombobox from?) to see what you are doing different.

Here is my example minimum project code:

```<code>@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    final ComboBox<String> main = new ComboBox<>();
    final ComboBox<String> dependent = new ComboBox<>();
    final Map<String, String[]> dependentsByMain = new HashMap<>();
    dependentsByMain.put("A", new String[]{"AA", "AB", "AC"});
    dependentsByMain.put("B", new String[]{"BA", "BB", "BC"});
    dependentsByMain.put("C", new String[]{"CA", "CB", "CC"});

    List<String> mainItems = new ArrayList<>(dependentsByMain.keySet());
    main.setItems(mainItems);
    dependent.setItems(Arrays.asList("Test1", "Test2", "Test3"));
    dependent.setValue("Test1");
    main.addValueChangeListener((HasValue.ValueChangeListener<String>) valueChangeEvent -> {
        if (valueChangeEvent.getValue() != null) {
            dependent.setItems(dependentsByMain.get(valueChangeEvent.getValue()));
            dependent.setValue(null);
        }
    });
    layout.addComponents(main, dependent);
    setContent(layout);
}
</code>```

UPDATE:

Have a look at Srinivasan Sekar's answer and its comments. This is a bug in the used version (8.0.7) which seems to be fixed in version 8.5 (according to https://github.com/vaadin/framework/issues/9047#issuecomment-437864866). I tried my example code with version 8.7.1 so it works. With version 8.0.7 it doesn't.

So the main solution is to update the used Vaadin version. As a workaround (when unable to upgrade the Vaadin version) you FIRST have to set the ComboBox's value to null and THEN set the new items. So in my example the ValueChangeListener must look like:

```<code>main.addValueChangeListener((HasValue.ValueChangeListener<String>) valueChangeEvent -> {
    if (valueChangeEvent.getValue() != null) {
        dependent.setValue(null);
        dependent.setItems(dependentsByMain.get(valueChangeEvent.getValue()));
    }
});
</code>```

Body:
I have a ComboBox  called projectRequirementComboBox that is dependent from projectComboBox, from where I get the list to show in the dropdown in projectRequirementComboBox, but I want to do something like: when a user changes the project I want to empty projectRequirementComboBox, to be more clear none of the item will not be selected I am doing this right now but still my projectRequirementComboBox  has the old value, I don't know what am I missing .I am using vaadin.version 8.0.7 .

private void refreshProjectRequirementCombobox()
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (projectComboBox.getValue() != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(projectComboBox.getValue().getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
    projectRequirementComboBox.setValue(null);

}

private void loadProjectRequirement(Project project)
{
    List<ProjectRequirement> projectRequirements = new ArrayList<>();
    if (project != null)
    {
        projectRequirements = projectRequirementService.findCurrentProjectRequirements(project.getProjectId());
    }
    projectRequirementComboBox.setItems(projectRequirements);
}

I call refreshProjectRequirementCombobox here.

 projectComboBox.addValueChangeListener(event ->
            {
                refreshProjectRequirementCombobox();
                loadRejectReason();
            });

Body:
Normally this should work. I created a minimum example with two ComboBoxes "main" and "dependent". The selection of the dependent ComboBox depends on the selection of the main ComboBox. Therefore there is a ValueChangeListener on the main ComboBox that resets the items and the selected value of the dependent ComboBox. When you start the application you see that the offered items of the dependent ComboBox change and that none of these new items is selected.

I think you have to post more of your code (where do you call refreshProjectRequirementCombobox from?) to see what you are doing different.

Here is my example minimum project code:

@Override
protected void init(VaadinRequest vaadinRequest) {
    final VerticalLayout layout = new VerticalLayout();
    final ComboBox<String> main = new ComboBox<>();
    final ComboBox<String> dependent = new ComboBox<>();
    final Map<String, String[]> dependentsByMain = new HashMap<>();
    dependentsByMain.put("A", new String[]{"AA", "AB", "AC"});
    dependentsByMain.put("B", new String[]{"BA", "BB", "BC"});
    dependentsByMain.put("C", new String[]{"CA", "CB", "CC"});

    List<String> mainItems = new ArrayList<>(dependentsByMain.keySet());
    main.setItems(mainItems);
    dependent.setItems(Arrays.asList("Test1", "Test2", "Test3"));
    dependent.setValue("Test1");
    main.addValueChangeListener((HasValue.ValueChangeListener<String>) valueChangeEvent -> {
        if (valueChangeEvent.getValue() != null) {
            dependent.setItems(dependentsByMain.get(valueChangeEvent.getValue()));
            dependent.setValue(null);
        }
    });
    layout.addComponents(main, dependent);
    setContent(layout);
}

UPDATE:

Have a look at Srinivasan Sekar's answer and its comments. This is a bug in the used version (8.0.7) which seems to be fixed in version 8.5 (according to https://github.com/vaadin/framework/issues/9047#issuecomment-437864866). I tried my example code with version 8.7.1 so it works. With version 8.0.7 it doesn't.

So the main solution is to update the used Vaadin version. As a workaround (when unable to upgrade the Vaadin version) you FIRST have to set the ComboBox's value to null and THEN set the new items. So in my example the ValueChangeListener must look like:

main.addValueChangeListener((HasValue.ValueChangeListener<String>) valueChangeEvent -> {
    if (valueChangeEvent.getValue() != null) {
        dependent.setValue(null);
        dependent.setItems(dependentsByMain.get(valueChangeEvent.getValue()));
    }
});


问:
How to call another class with button and pass variable between classes?
I want to pass variable between GUI classes. Below, when i Show Other_b  class, it Show frame but i couldn't get Main1 class' data to there. However when i try to Show Other_a class, it passes x value (because of it is inside of __init__) but it doesn't pass the y value because of it is related to Btn2(and of course because of not having any frame to pressing button).

How can i overcome this problem? Any help would be appreciated.

```<code>import wx

class Main1 (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.Btn1 = wx.Button( self, wx.ID_ANY, u"Btn1", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer1.Add( self.Btn1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer1 )
        self.Btn1.Bind( wx.EVT_BUTTON, self.btn1_f )

    def btn1_f( self, event ):
        print("here 1")
        self.x = 12
        self.y = 30

        a=Other_a(self).Show()
        b=Other_b(self).Show()

class Other_a (wx.Frame):
    def __init__(self, foo):
        wx.Frame.__init__ ( self )
        self.bSizer2 = wx.BoxSizer( wx.VERTICAL )
        self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer2.Add( self.Btn2, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer2 )
        self.Btn2.Bind( wx.EVT_BUTTON, self.btn2_f )

        print("here 2")
        print(foo.x)

    def btn2_f(self,foo):
        print("here 3")
        print(foo.y)

class Other_b (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer3.Add( self.Btn3, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer3 )
        self.Btn3.Bind( wx.EVT_BUTTON, self.btn3_f )
        print("here 4")

    def btn3_f(self,event):
        print("here 5")
        print(self.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()
</code>```

答:
You are very close!

A few judicious uses of self and parent resolve your issues.

```<code>import wx

class Main1 (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.Btn1 = wx.Button( self, wx.ID_ANY, u"Btn1", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer1.Add( self.Btn1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer1 )
        self.Btn1.Bind( wx.EVT_BUTTON, self.btn1_f )

    def btn1_f( self, event ):
        print("here 1")
        self.x = 12
        self.y = 30

        a=Other_a(parent=self).Show()
        b=Other_b(parent=self).Show()

class Other_a (wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__ (self,parent)
        self.parent = parent
        self.bSizer2 = wx.BoxSizer( wx.VERTICAL )
        self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn A 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer2.Add( self.Btn2, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer2 )
        self.Btn2.Bind( wx.EVT_BUTTON, self.btn2_f )

        print("here 2")
        print(self.parent.x)

    def btn2_f(self,foo):
        print("here 3")
        print(self.parent.y)

class Other_b (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.parent = parent
        self.bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn B 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer3.Add( self.Btn3, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer3 )
        self.Btn3.Bind( wx.EVT_BUTTON, self.btn3_f )
        print("here 4")

    def btn3_f(self,event):
        print("here 5")
        print(self.parent.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()
</code>```

Gives:

```<code>python 20190529.py
here 1
here 2
12
here 4
here 3
30
here 5
12
</code>```

Here is the diff between your code and the code above:

```<code><         a=Other_a(self).Show()
<         b=Other_b(self).Show()
---
>         a=Other_a(parent=self).Show()
>         b=Other_b(parent=self).Show()
23,24c23,25
<     def __init__(self, foo):
<         wx.Frame.__init__ ( self )
---
>     def __init__(self, parent):
>         wx.Frame.__init__ (self,parent)
>         self.parent = parent
26c27
<         self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
---
>         self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn A 2", wx.DefaultPosition, wx.DefaultSize, 0 )
32c33
<         print(foo.x)
---
>         print(self.parent.x)
36c37
<         print(foo.y)
---
>         print(self.parent.y)
40a42
>         self.parent = parent
42c44
<         self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
---
>         self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn B 2", wx.DefaultPosition, wx.DefaultSize, 0 )
50c52
<         print(self.x)
---
>         print(self.parent.x)
</code>```

Body:
I want to pass variable between GUI classes. Below, when i Show Other_b  class, it Show frame but i couldn't get Main1 class' data to there. However when i try to Show Other_a class, it passes x value (because of it is inside of __init__) but it doesn't pass the y value because of it is related to Btn2(and of course because of not having any frame to pressing button).

How can i overcome this problem? Any help would be appreciated.

import wx

class Main1 (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.Btn1 = wx.Button( self, wx.ID_ANY, u"Btn1", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer1.Add( self.Btn1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer1 )
        self.Btn1.Bind( wx.EVT_BUTTON, self.btn1_f )

    def btn1_f( self, event ):
        print("here 1")
        self.x = 12
        self.y = 30

        a=Other_a(self).Show()
        b=Other_b(self).Show()

class Other_a (wx.Frame):
    def __init__(self, foo):
        wx.Frame.__init__ ( self )
        self.bSizer2 = wx.BoxSizer( wx.VERTICAL )
        self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer2.Add( self.Btn2, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer2 )
        self.Btn2.Bind( wx.EVT_BUTTON, self.btn2_f )

        print("here 2")
        print(foo.x)

    def btn2_f(self,foo):
        print("here 3")
        print(foo.y)

class Other_b (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer3.Add( self.Btn3, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer3 )
        self.Btn3.Bind( wx.EVT_BUTTON, self.btn3_f )
        print("here 4")

    def btn3_f(self,event):
        print("here 5")
        print(self.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()

Body:
You are very close!

A few judicious uses of self and parent resolve your issues.

import wx

class Main1 (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.Btn1 = wx.Button( self, wx.ID_ANY, u"Btn1", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer1.Add( self.Btn1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer1 )
        self.Btn1.Bind( wx.EVT_BUTTON, self.btn1_f )

    def btn1_f( self, event ):
        print("here 1")
        self.x = 12
        self.y = 30

        a=Other_a(parent=self).Show()
        b=Other_b(parent=self).Show()

class Other_a (wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__ (self,parent)
        self.parent = parent
        self.bSizer2 = wx.BoxSizer( wx.VERTICAL )
        self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn A 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer2.Add( self.Btn2, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer2 )
        self.Btn2.Bind( wx.EVT_BUTTON, self.btn2_f )

        print("here 2")
        print(self.parent.x)

    def btn2_f(self,foo):
        print("here 3")
        print(self.parent.y)

class Other_b (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.parent = parent
        self.bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn B 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer3.Add( self.Btn3, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer3 )
        self.Btn3.Bind( wx.EVT_BUTTON, self.btn3_f )
        print("here 4")

    def btn3_f(self,event):
        print("here 5")
        print(self.parent.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()

Gives:

python 20190529.py
here 1
here 2
12
here 4
here 3
30
here 5
12

Here is the diff between your code and the code above:

<         a=Other_a(self).Show()
<         b=Other_b(self).Show()
---
>         a=Other_a(parent=self).Show()
>         b=Other_b(parent=self).Show()
23,24c23,25
<     def __init__(self, foo):
<         wx.Frame.__init__ ( self )
---
>     def __init__(self, parent):
>         wx.Frame.__init__ (self,parent)
>         self.parent = parent
26c27
<         self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
---
>         self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn A 2", wx.DefaultPosition, wx.DefaultSize, 0 )
32c33
<         print(foo.x)
---
>         print(self.parent.x)
36c37
<         print(foo.y)
---
>         print(self.parent.y)
40a42
>         self.parent = parent
42c44
<         self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
---
>         self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn B 2", wx.DefaultPosition, wx.DefaultSize, 0 )
50c52
<         print(self.x)
---
>         print(self.parent.x)


问:
Read and write image(large object) from postgres with qt
I want to read and write large object like image or video in postgres with oid type with framework qt. In query i can using lo_import and lo_export to read and write largeobject with specific local address for import and export. But question is how can i read and write with qt and qsqlquery?</p>

答:
Let's assume you have a table named "my_table". For storing large binary objects with PostgreSQL it is recommended to use bytea type for a datafield, so name it "binary_data".

To insert data I'd use QSqlRecord, like this:

```<code>QSqlTableModel *model;
QSqlDatabase m_database;
m_database = ...//connect to the database here
model = new QSqlTableModel(0, m_database);
model->setTable("my_table");
model->select();
QSqlRecord rec;
rec = model->record();
QFile f("path_to_a_big_file");
if(f.open(QIODevice::ReadOnly))
{
    QByteArray ba = f.readAll();
    rec.setValue("binary_data",ba.toBase64());
}
model->insertRecord(-1,rec);
model->submitAll();
</code>```

To update the data QSqlQuery will do:

```<code>QSqlQuery query(m_database);
query.prepare("update my_table set binary_data = :binary_data where [condition]....");
QFile f("path_to_a_big_file");
if(f.open(QIODevice::ReadOnly))
{
    QByteArray ba = f.readAll();
    query.bindValue(":binary_data",ba.toBase64());
}
query.exec();
</code>```

And finally to read the data you'll need to do something like this:

```<code>QSqlTableModel *model;
model = new QSqlTableModel(0, m_database);
model->setTable("my_table");
model->select();
 while(model->canFetchMore())
    model->fetchMore();
for (int i = 0; i < model->rowCount(); ++i)
{
    QByteArray ba = QByteArray::fromBase64(model->record(i).value("binary_data").toByteArray())
    //do something with the retrieved data
}
</code>```

Also note that it is your responsibility to remember the type of a file you put inside the table.

Body:
Let's assume you have a table named "my_table". For storing large binary objects with PostgreSQL it is recommended to use bytea type for a datafield, so name it "binary_data".

To insert data I'd use QSqlRecord, like this:

QSqlTableModel *model;
QSqlDatabase m_database;
m_database = ...//connect to the database here
model = new QSqlTableModel(0, m_database);
model->setTable("my_table");
model->select();
QSqlRecord rec;
rec = model->record();
QFile f("path_to_a_big_file");
if(f.open(QIODevice::ReadOnly))
{
    QByteArray ba = f.readAll();
    rec.setValue("binary_data",ba.toBase64());
}
model->insertRecord(-1,rec);
model->submitAll();

To update the data QSqlQuery will do:

QSqlQuery query(m_database);
query.prepare("update my_table set binary_data = :binary_data where [condition]....");
QFile f("path_to_a_big_file");
if(f.open(QIODevice::ReadOnly))
{
    QByteArray ba = f.readAll();
    query.bindValue(":binary_data",ba.toBase64());
}
query.exec();

And finally to read the data you'll need to do something like this:

QSqlTableModel *model;
model = new QSqlTableModel(0, m_database);
model->setTable("my_table");
model->select();
 while(model->canFetchMore())
    model->fetchMore();
for (int i = 0; i < model->rowCount(); ++i)
{
    QByteArray ba = QByteArray::fromBase64(model->record(i).value("binary_data").toByteArray())
    //do something with the retrieved data
}

Also note that it is your responsibility to remember the type of a file you put inside the table.


答:
const multiply = (a,b) => !b ? (b) => a * b : a * b;
console.log(multiply(2, 4))
console.log(multiply(2)(4))```

Title: How to execute one function whether it normal or carried and yield the same result?

Body: What would be the body of a the multiply function that if executed in both ways below would give the same result. So either calling multiply(2,4) or multiply(2)(4) would output 8?