问:
De-Bug Rock Paper Scissors
Question

I am creating a rock paper scissors game. In terms of the functionality built so far it should:

Allow the player to select a choice

The computer then selects a random choice

The images representing the respective hands change

The winner is stated in text

The respective winner's score is updated.

all work perfectly.

But 4. and 5. I can not understand why they aren't working!

Please help me identify the issue :)

This is the code (I left out CSS because I don't think its important to the problem):

if(document.readyState == 'loading'){
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}

let score = [0, 0];
let playerScore = score[0];
let computerScore = score[1];
const playerOptns = ['rock', 'paper', 'scissors']
const computerOptns = ['rock', 'paper', 'scissors']
let playerCurrentHand = [playerOptns[1]];
let computerCurrentHand = [computerOptns[0]];

function ready(){
    let choiceBtn = document.getElementsByClassName('btn');
    for(let i = 0; i < choiceBtn.length; i++){
        let button = choiceBtn[i]
        button.addEventListener('click', changeHands)

    }
}

function changeHands(event){
    let buttonClicked = event.target;
    if(buttonClicked.classList.contains('rock')){
        changeToRock();
    } else if(buttonClicked.classList.contains('paper')){
        changeToPaper();
    } else if(buttonClicked.classList.contains('scissors')){
        changeToScissors();
    }
    computerRandom()
}

function changeToPaper(){
    document.getElementById('hand1').src="Assets/paper.png";
    playerCurrentHand = 'paper';
}

function changeToRock(){
    document.getElementById('hand1').src="Assets/rock.png";
    playerCurrentHand = 'rock';
}

function changeToScissors(){
    document.getElementById('hand1').src="Assets/scissors.png";
    playerCurrentHand = 'scissors';
}

function computerRandom(){
    let number = Math.round(Math.random()*2)
    if(number== 0){
        document.getElementById('hand2').src="Assets/paper.png";
        computerCurrentHand = 'paper';
    } else if(number==1){
        document.getElementById('hand2').src="Assets/rock.png";
        computerCurrentHand = 'rock';
    } else {
        document.getElementById('hand2').src="Assets/scissors.png"
        computerCurrentHand= 'scissors';
    }
    compareWinner()
}

function compareWinner(){
    if(playerCurrentHand=='paper' && computerCurrentHand =='scissors'){
        computerWins();

    } else if(playerCurrentHand=='paper' && computerCurrentHand=='rock'){
        playerWins();

    } else if(playerCurrentHand=='scissors' && computerCurrentHand=='rock'){
        computerWins();

    } else if (playerCurrentHand=='scissors' && computerCurrentHand=='paper'){
        playerWins();

    } else if(playerCurrentHand=='rock' && computerCurrentHand=='scissors'){
        playerWins();

    } else if(playerCurrentHand=='rock' && computerCurrentHand=='paper'){
        computerWins();

    } else {
        tied()
    }
}

function computerWins(){
    computerScore++;
    score[0] = computerScore;
    let celebrationText = document.querySelector('.winner')[0];
    celebrationText.textContent = "Computer Wins";
    document.getElementByClassName('comp-score')[0].textContent = computerScore;
}

function playerWins() {
    playerScore++;
    score[0] = playerScore;
    let celebrationText = document.querySelector('.winner')[0];
    celebrationText.textContent = "Player Wins";
    document.getElementsByClassName('play-score')[0].textContent = playerScore;
}

function tied(){
    let celebrationText = document.querySelector('.winner')[0];
    celebrationText.textContent = "No Winner";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="./styles.css" />
        <title>Rock paper scissors</title>
    </head>
    <body>
        <div class="score-board">
            <div class="columned score-1">
                <div>
                    Player
                </div>

                <div class="play-score">
                    0
                </div>
            </div>
            <div class="columned score-2">
                <div>
                    Computer
                </div>
                <div class="comp-score">
                    0
                </div>
            </div>
    </div>
        <div class="winner">
            Player Wins
        </div>

        <div class="hands">
            <div>
                <img id="hand1" src="Assets/paper.png">
            </div>
            <div>
                <img id="hand2" src="Assets/rock.png">
            </div>
        </div>

     <div class="buttons">

            <button class="btn rock">rock</button>

            <button class="btn paper">paper</button>

            <button class="btn scissors">scissors</button>

     </div>

        <script src="app.js"></script>
    </body>
</html></code>```

答:
The answer

There were two issues:

The query selector had an iteration count of [0]. This was because I changed it from getElementsByClassName() in an attempt to fix the problem.

At one point there was a getElementsByClassName() written as getElementByClassName()

Rookie errors, but glad its resolved. :)

Title: De-Bug Rock Paper Scissors

Body:
Question

I am creating a rock paper scissors game. In terms of the functionality built so far it should:

Allow the player to select a choice

The computer then selects a random choice

The images representing the respective hands change

The winner is stated in text

The respective winner's score is updated.

all work perfectly.

But 4. and 5. I can not understand why they aren't working!

Please help me identify the issue :)

This is the code (I left out CSS because I don't think its important to the problem):

if(document.readyState == 'loading'){
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}

let score = [0, 0];
let playerScore = score[0];
let computerScore = score[1];
const playerOptns = ['rock', 'paper', 'scissors']
const computerOptns = ['rock', 'paper', 'scissors']
let playerCurrentHand = [playerOptns[1]];
let computerCurrentHand = [computerOptns[0]];

function ready(){
    let choiceBtn = document.getElementsByClassName('btn');
    for(let i = 0; i < choiceBtn.length; i++){
        let button = choiceBtn[i]
        button.addEventListener('click', changeHands)

    }
}

function changeHands(event){
    let buttonClicked = event.target;
    if(buttonClicked.classList.contains('rock')){
        changeToRock();
    } else if(buttonClicked.classList.contains('paper')){
        changeToPaper();
    } else if(buttonClicked.classList.contains('scissors')){
        changeToScissors();
    }
    computerRandom()
}

function changeToPaper(){
    document.getElementById('hand1').src="Assets/paper.png";
    playerCurrentHand = 'paper';
}

function changeToRock(){
    document.getElementById('hand1').src="Assets/rock.png";
    playerCurrentHand = 'rock';
}

function changeToScissors(){
    document.getElementById('hand1').src="Assets/scissors.png";
    playerCurrentHand = 'scissors';
}

function computerRandom(){
    let number = Math.round(Math.random()*2)
    if(number== 0){
        document.getElementById('hand2').src="Assets/paper.png";
        computerCurrentHand = 'paper';
    } else if(number==1){
        document.getElementById('hand2').src="Assets/rock.png";
        computerCurrentHand = 'rock';
    } else {
        document.getElementById('hand2').src="Assets/scissors.png"
        computerCurrentHand= 'scissors';
    }
    compareWinner()
}

function compareWinner(){
    if(playerCurrentHand=='paper' && computerCurrentHand =='scissors'){
        computerWins();

    } else if(playerCurrentHand=='paper' && computerCurrentHand=='rock'){
        playerWins();

    } else if(playerCurrentHand=='scissors' && computerCurrentHand=='rock'){
        computerWins();

    } else if (playerCurrentHand=='scissors' && computerCurrentHand=='paper'){
        playerWins();

    } else if(playerCurrentHand=='rock' && computerCurrentHand=='scissors'){
        playerWins();

    } else if(playerCurrentHand=='rock' && computerCurrentHand=='paper'){
        computerWins();

    } else {
        tied()
    }
}

function computerWins(){
    computerScore++;
    score[0] = computerScore;
    let celebrationText = document.querySelector('.winner')[0];
    celebrationText.textContent = "Computer Wins";
    document.getElementByClassName('comp-score')[0].textContent = computerScore;
}

function playerWins() {
    playerScore++;
    score[0] = playerScore;
    let celebrationText = document.querySelector('.winner')[0];
    celebrationText.textContent = "Player Wins";
    document.getElementsByClassName('play-score')[0].textContent = playerScore;
}

function tied(){
    let celebrationText = document.querySelector('.winner')[0];
    celebrationText.textContent = "No Winner";

}

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="./styles.css" />
        <title>Rock paper scissors</title>

                    Player

                    0

                    Computer

                    0

            Player Wins

            <button class="btn rock">rock</button>

            <button class="btn paper">paper</button>

            <button class="btn scissors">scissors</button>


来源: stackexchange

问:
Django filter by two parameters
I want to filter by two parameters. I have this:

```<code>    def get_queryset(self):
        queryset = Product.objects.filter(
             Q(category__in=self.request.GET.getlist("category")) &
             Q(brand__in=self.request.GET.getlist("brand")))
        return queryset
</code>```

But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that?

答:
You can actually write model manager for custom query_sets. For more information you can read the documentation: https://docs.djangoproject.com/en/3.0/topics/db/managers/#calling-custom-queryset-methods-from-the-manager

```<code>class ProductQuerySet(models.query.QuerySet):

def active(self):
    return self.filter(active=True)

def search(self, query):
    lookups = (Q(title__icontains=query) |
              Q(description__icontains=query) |
              Q(price__icontains=query) |
              Q(tag__title__icontains=query))  # (model_name)__(model_field)__(filter)
    return self.filter(lookups).distinct()
</code>```

class ProductManager(models.Manager):

```<code>def get_queryset(self):
    return ProductQuerySet(self.model, using=self._db)

def active(self):
    return self.get_queryset().active()

def search(self, query):
    return self.get_queryset().active().search(query)
</code>```

In Views.py:

```<code>def get_queryset(self, *args, **kwargs):
    request = self.request
    query = request.GET.get('q', None)
    if query is not None:
        query = query.strip()
        return Product.objects.search(query)
    return Product.objects.featured()
</code>```

I hope that will help you. Good Luck

ContentLicense: CC BY-SA 4.0

Title: Django filter by two parameters

Body:
I want to filter by two parameters. I have this:

    def get_queryset(self):
        queryset = Product.objects.filter(
             Q(category__in=self.request.GET.getlist("category")) &
             Q(brand__in=self.request.GET.getlist("brand")))
        return queryset

But this works only if two filters are chosen(otherwise it returns nothing). I want my program to filter by one filter if only one is chosen and filter by two parameters if two are chosen. How can I do that?

Body:
You can actually write model manager for custom query_sets. For more information you can read the documentation: https://docs.djangoproject.com/en/3.0/topics/db/managers/#calling-custom-queryset-methods-from-the-manager

class ProductQuerySet(models.query.QuerySet):

def active(self):
    return self.filter(active=True)

def search(self, query):
    lookups = (Q(title__icontains=query) |
              Q(description__icontains=query) |
              Q(price__icontains=query) |
              Q(tag__title__icontains=query))  # (model_name)__(model_field)__(filter)
    return self.filter(lookups).distinct()

class ProductManager(models.Manager):

def get_queryset(self):
    return ProductQuerySet(self.model, using=self._db)

def active(self):
    return self.get_queryset().active()

def search(self, query):
    return self.get_queryset().active().search(query)

In Views.py:

def get_queryset(self, *args, **kwargs):
    request = self.request
    query = request.GET.get('q', None)
    if query is not None:
        query = query.strip()
        return Product.objects.search(query)
    return Product.objects.featured()

I hope that will help you. Good Luck


问:
flask deployment to heroku
using flask app, my Procfile is "web: gunicorn app:app",   my app file name is "app"

Any ideas what went wrong ?

below shows the log

```<code>2020-05-29T18:45:44.045795+00:00 app[web.1]:     self.stop()
2020-05-29T18:45:44.045832+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop
2020-05-29T18:45:44.046212+00:00 app[web.1]:     time.sleep(0.1)
2020-05-29T18:45:44.046246+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 244, in handle_chld
2020-05-29T18:45:44.046532+00:00 app[web.1]:     self.reap_workers()
2020-05-29T18:45:44.046569+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 524, in reap_workers
2020-05-29T18:45:44.047026+00:00 app[web.1]:     raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2020-05-29T18:45:44.047104+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2020-05-29T18:45:44.144366+00:00 heroku[web.1]: Process exited with status 1
2020-05-29T18:45:44.201658+00:00 heroku[web.1]: State changed from starting to crashed

</code>```

答: The problem Is that you are trying to connect to a db that doesn't exist. In your code you are connecting to a localhost postgresql db. You need to open a db in heroku</p>

Title: flask deployment to heroku

Body:
using flask app, my Procfile is "web: gunicorn app:app",   my app file name is "app"

Any ideas what went wrong ?

below shows the log

2020-05-29T18:45:44.045795+00:00 app[web.1]:     self.stop()
2020-05-29T18:45:44.045832+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop
2020-05-29T18:45:44.046212+00:00 app[web.1]:     time.sleep(0.1)
2020-05-29T18:45:44.046246+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 244, in handle_chld
2020-05-29T18:45:44.046532+00:00 app[web.1]:     self.reap_workers()
2020-05-29T18:45:44.046569+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 524, in reap_workers
2020-05-29T18:45:44.047026+00:00 app[web.1]:     raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2020-05-29T18:45:44.047104+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2020-05-29T18:45:44.144366+00:00 heroku[web.1]: Process exited with status 1
2020-05-29T18:45:44.201658+00:00 heroku[web.1]: State changed from starting to crashed


问:
Angular + Electron - Cannot find module main.js
I am trying to build macOs app using electron by running electron-packager . --platform=darwin

It creates an app but when i run it gives me following error

```<code>Uncaught Exception:
Error: Cannot find module '/Users/msaadbashir/Downloads/Angular/accounting/accounting-darwin-x64/accounting.app/Contents/Resources/app/main.js'
    at Module._resolveFilename (internal/modules/cjs/loader.js:797:17)
    at Function../lib/common/reset-search-paths.ts.Module._resolveFilename (electron/js2c/browser_init.js:7736:16)
    at Object.<anonymous> (electron/js2c/browser_init.js:6116:37)
    at Object../lib/browser/init.ts (electron/js2c/browser_init.js:6124:30)
    at __webpack_require__ (electron/js2c/browser_init.js:20:30)
    at electron/js2c/browser_init.js:84:18
    at electron/js2c/browser_init.js:87:10
    at NativeModule.compile (internal/bootstrap/loaders.js:287:5)
    at NativeModule.compileForPublicLoader (internal/bootstrap/loaders.js:222:8)
    at loadNativeModule (internal/modules/cjs/helpers.js:23:9)
</code>```

I have done the following apart from installing electron.

index.html <base href="./">

main.js

```<code>const { app, BrowserWindow } = require('electron')
let win;
function createWindow() {
    win = new BrowserWindow({
        width: 600,
        height: 600,
        backgroundColor: '#ffffff',
    })
    win.loadFile('./dist/accounting/index.html')
    win.on('closed',function() {
        win = null
    })
}
app.on('ready',createWindow)
app.on('window-all-closed',function() {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
app.on('activate',function() {
    if (win === null) {
        createWindow()
    }
})
</code>```

package.json

```<code>{
  "name": "accounting",
  "version": "0.0.0",
  "main": "main.js",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "electron": "electron .",
    "electron-build": "ng build --prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.6",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "~9.0.6",
    "@angular/compiler": "~9.0.6",
    "@angular/core": "~9.0.6",
    "@angular/forms": "~9.0.6",
    "@angular/localize": "~9.0.6",
    "@angular/material": "^9.2.4",
    "@angular/platform-browser": "~9.0.6",
    "@angular/platform-browser-dynamic": "~9.0.6",
    "@angular/router": "~9.0.6",
    "@ng-bootstrap/ng-bootstrap": "^6.1.0",
    "@ng-select/ng-select": "^4.0.0",
    "@ngx-loading-bar/core": "^4.2.0",
    "@ngx-loading-bar/http-client": "^4.2.0",
    "@ngx-loading-bar/router": "^4.2.0",
    "bootstrap": "^4.5.0",
    "e-ngx-print": "^5.3.1",
    "html2canvas": "^1.0.0-rc.5",
    "html2pdf.js": "^0.9.2",
    "jquery": "^3.5.1",
    "jspdf": "^1.5.3",
    "ng2-date-picker": "^9.0.0",
    "ngx-bootstrap": "^5.6.1",
    "ngx-infinite-scroll": "^9.0.0",
    "ngx-mask": "^9.0.2",
    "ngx-toastr": "^12.0.1",
    "rxjs": "^6.5.5",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.6",
    "@angular/cli": "~9.0.6",
    "@angular/compiler-cli": "~9.0.6",
    "@angular/language-service": "~9.0.6",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "electron": "^9.0.0",
    "electron-packager": "^14.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.7.5"
  }
}
</code>```

答:
You need:

set base-href to the root folder npm run electron-build -- --base-href ./

be sure the main.js in the root

be sure that in package.json main field refers to correct path of main.js

Body:
I am trying to build macOs app using electron by running electron-packager . --platform=darwin

It creates an app but when i run it gives me following error

Uncaught Exception:
Error: Cannot find module '/Users/msaadbashir/Downloads/Angular/accounting/accounting-darwin-x64/accounting.app/Contents/Resources/app/main.js'
    at Module._resolveFilename (internal/modules/cjs/loader.js:797:17)
    at Function../lib/common/reset-search-paths.ts.Module._resolveFilename (electron/js2c/browser_init.js:7736:16)
    at Object.<anonymous> (electron/js2c/browser_init.js:6116:37)
    at Object../lib/browser/init.ts (electron/js2c/browser_init.js:6124:30)
    at __webpack_require__ (electron/js2c/browser_init.js:20:30)
    at electron/js2c/browser_init.js:84:18
    at electron/js2c/browser_init.js:87:10
    at NativeModule.compile (internal/bootstrap/loaders.js:287:5)
    at NativeModule.compileForPublicLoader (internal/bootstrap/loaders.js:222:8)
    at loadNativeModule (internal/modules/cjs/helpers.js:23:9)

I have done the following apart from installing electron.

index.html <base href="./">

main.js

const { app, BrowserWindow } = require('electron')
let win;
function createWindow() {
    win = new BrowserWindow({
        width: 600,
        height: 600,
        backgroundColor: '#ffffff',
    })
    win.loadFile('./dist/accounting/index.html')
    win.on('closed',function() {
        win = null
    })
}
app.on('ready',createWindow)
app.on('window-all-closed',function() {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
app.on('activate',function() {
    if (win === null) {
        createWindow()
    }
})

package.json

{
  "name": "accounting",
  "version": "0.0.0",
  "main": "main.js",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "electron": "electron .",
    "electron-build": "ng build --prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.6",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "~9.0.6",
    "@angular/compiler": "~9.0.6",
    "@angular/core": "~9.0.6",
    "@angular/forms": "~9.0.6",
    "@angular/localize": "~9.0.6",
    "@angular/material": "^9.2.4",
    "@angular/platform-browser": "~9.0.6",
    "@angular/platform-browser-dynamic": "~9.0.6",
    "@angular/router": "~9.0.6",
    "@ng-bootstrap/ng-bootstrap": "^6.1.0",
    "@ng-select/ng-select": "^4.0.0",
    "@ngx-loading-bar/core": "^4.2.0",
    "@ngx-loading-bar/http-client": "^4.2.0",
    "@ngx-loading-bar/router": "^4.2.0",
    "bootstrap": "^4.5.0",
    "e-ngx-print": "^5.3.1",
    "html2canvas": "^1.0.0-rc.5",
    "html2pdf.js": "^0.9.2",
    "jquery": "^3.5.1",
    "jspdf": "^1.5.3",
    "ng2-date-picker": "^9.0.0",
    "ngx-bootstrap": "^5.6.1",
    "ngx-infinite-scroll": "^9.0.0",
    "ngx-mask": "^9.0.2",
    "ngx-toastr": "^12.0.1",
    "rxjs": "^6.5.5",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.6",
    "@angular/cli": "~9.0.6",
    "@angular/compiler-cli": "~9.0.6",
    "@angular/language-service": "~9.0.6",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "electron": "^9.0.0",
    "electron-packager": "^14.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.7.5"
  }
}


问:
How to save/download generate QR Code in react native using hooks?
I'm trying to build an app generator and scanner QR code in react native using hooks. I want a solution to save/download the QR code in the device after generating them. I need help plz, thanks

react-native-qrcode-generator
 Can anyone give me suggestions on how to save this generated QR Code? Any help much appreciated

答:
If you want to save the QR Code as an image to your device, you should convert the QRcode view component into a png image and then store it.

You may use react-native-view-shot to convert the QRcode view component into a png image and rn-fetch-blob to save the image to your gallery.


问:
Parsing a tab-delimited text file to replace columns with one vertical list (Python)
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine
</code>```

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

```<code>while segmentedLine:
    item = segmentedLine.split("\t")
    print item
</code>```

Thanks very much for any input.

答:
You've got the lines split properly in the first loop. What you want to do then is have a second for loop to iterate over each tab-separated item. That'll look like this:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("\t")
    for item in segmentedLine:
        print item
</code>```

Or more concisely, without the temporary variable:

```<code>for line in open('feddocs_2011.txt', 'r'):
    for item in line.split("\t"):
        print item
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

while segmentedLine:
    item = segmentedLine.split("\t")
    print item

Thanks very much for any input.

Body:
You've got the lines split properly in the first loop. What you want to do then is have a second for loop to iterate over each tab-separated item. That'll look like this:

for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("\t")
    for item in segmentedLine:
        print item

Or more concisely, without the temporary variable:

for line in open('feddocs_2011.txt', 'r'):
    for item in line.split("\t"):
        print item


问:
Why I can't get right answer?
Code on Github

A baby programmer seeking for help, please.
What went wrong in my code if anyone can help?

A very simple python program to compare two numbers using functions

```<code>from sys import exit

def main():
    check()
    compare(x, y)

def check():
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() == False and y.isnumeric() == False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare(x, y):
    # TODO
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()
</code>```

答:
You are making a common mistake.

1- You have made two functions check() and compare() and you are working on x and y in both of them. But any variable which is defined in a function has scope in that function only. So, you can use x and y only in the check function as they are defined there.To use variables in multiple functions, you can declare them as global. Then the variables can be accessed from any function.

2- Another mistake here is that you are passing x and y as arguments to compare function, but as x and y are only available for check to use, so it is giving error. I have removed the arguments and have worked with the global approach instead.

See the below code:

```<code>from sys import exit

def main():
    check()
    compare()

def check():
    #initialising x and y as global
    global x, y
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() == False and y.isnumeric() == False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare():
    global x, y
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()
</code>```

The output for x = 5 and y = 3 as test case is-

```<code>x is greater than y
</code>```

Title: Why I can't get right answer?

Body:
Code on Github

A baby programmer seeking for help, please.
What went wrong in my code if anyone can help?

A very simple python program to compare two numbers using functions

from sys import exit

def main():
    check()
    compare(x, y)

def check():
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() == False and y.isnumeric() == False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare(x, y):
    # TODO
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()

Body:
You are making a common mistake.

1- You have made two functions check() and compare() and you are working on x and y in both of them. But any variable which is defined in a function has scope in that function only. So, you can use x and y only in the check function as they are defined there.To use variables in multiple functions, you can declare them as global. Then the variables can be accessed from any function.

2- Another mistake here is that you are passing x and y as arguments to compare function, but as x and y are only available for check to use, so it is giving error. I have removed the arguments and have worked with the global approach instead.

See the below code:

from sys import exit

def main():
    check()
    compare()

def check():
    #initialising x and y as global
    global x, y
    # prompt user for two numbers
    x = input("x: ")
    y = input("y: ")

    # apply sanity check
    if x.isnumeric() == False and y.isnumeric() == False:
        print("Usage: only real numbers are accepted.")
        exit(1)
    else:
        return x, y

def compare():
    global x, y
    if x < y:
        return print("x is smaller than y")
    elif x > y:
        return print("x is greater than y")
    else:
        return print("They are the same!")

main()

The output for x = 5 and y = 3 as test case is-

x is greater than y


问:
Android wear: keeping display on
On my watchface I need sometimes do wait a relative long time for data. During this wait cycle I think, it would be nice to keep the display on.

Unfortunately I didn't got it running with the same way I got it on my mobile phone (using PowerManager.WakeLock).

Can someone suggest me a right way to do that?

Thanks a lot

Luca

答:
Well, I got it with PowerManager...

I just forgot to add:

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

to my AndroidManifest.xml... :(

Thanks

Luca

Title: Android wear: keeping display on

Body:
Well, I got it with PowerManager...

I just forgot to add:

<uses-permission android:name="android.permission.WAKE_LOCK" />

to my AndroidManifest.xml... :(

Thanks

Luca


问:
Smooth the edges of binary images (Face) using Python and Open CV
I am looking for a perfect way to smooth edges of binary images. The problem is the binary image appears to be a staircase like borders which is very unpleasing for my further masking process.

I am attaching a raw binary image that is to be converted into smooth edges and I am also providing the expected outcome. I am also looking for a solution that would work even if we increase the dimensions of the image.

Problem Image    Expected Outcome

答:
To preserve the sharpness of a binary image, I would recommend applying something like a median filter. Here is an example of this:

```<code>from PIL import Image, ImageFilter

image = Image.open('input_image.png')
image = image.filter(ImageFilter.ModeFilter(size=13))
image.save('output_image.png')
</code>```

which gives us the following results:

Figure 1. Left: The original input image. Right: The output image with a median filter of size 13.

Increasing the size of the filter would increase the degree of smoothing, but of course this comes as a trade-off because you also lose high-frequency information such as the sharp corner on the bottom-left of this sample image. Unfortunately, high-frequency features are similar in nature to the staircase-like borders.

Body:
To preserve the sharpness of a binary image, I would recommend applying something like a median filter. Here is an example of this:

from PIL import Image, ImageFilter

image = Image.open('input_image.png')
image = image.filter(ImageFilter.ModeFilter(size=13))
image.save('output_image.png')

which gives us the following results:

Figure 1. Left: The original input image. Right: The output image with a median filter of size 13.

Increasing the size of the filter would increase the degree of smoothing, but of course this comes as a trade-off because you also lose high-frequency information such as the sharp corner on the bottom-left of this sample image. Unfortunately, high-frequency features are similar in nature to the staircase-like borders.


问:
How to get rid of spaces in a grid css layout and place the elements together one after the other
I am trying to understand how to place elements by using display: grid without explicitly saying how tall the elements are. This is useful for example if you just have some elements and you want to stack them one after the other following a given order but disregarding the height.

So, given a certain number of elements with same width but different height. How can you place them together in a given order with pure css in such a way that there's no space between them. This is an example:

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  height: 200px;
  background-color: blue;
  grid-area: b2;
}

.box3 {
  height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  height: 250px;
  background-color: orange;
  grid-area: b4;
}

.box5 {
  height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  height: 400px;
  background-color: gray;
  grid-area: b6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
</div></code>```

答:
If you want to maintain the designated heights, you can wrap the column 2 divs into a flex wrapper:

```<code><div class="container">
  <div class="box box1">1</div>
  <div class="box box5">5</div>
 <div class = "flex">
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box6">6</div>
   </div>
</div>
</code>```

And then change your grid CSS a bit to accommodate:

```<code>.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b3" "b5 b3";
}
</code>```

Now the only boxes that need grid-area are the 2 on the left (b1 and b5) and the flex wrapper (b3 in my code):

```<code>.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  height: 200px;
  background-color: blue;
}

.box3 {
  height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  height: 250px;
  background-color: orange;
}

.box5 {
  height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  height: 400px;
  background-color: gray;
}

.flex {
  display: flex;
  flex-direction: column;
  grid-area: b3;
}
</code>```

Check this demo JSfiddle

Body:
I am trying to understand how to place elements by using display: grid without explicitly saying how tall the elements are. This is useful for example if you just have some elements and you want to stack them one after the other following a given order but disregarding the height.

So, given a certain number of elements with same width but different height. How can you place them together in a given order with pure css in such a way that there's no space between them. This is an example:

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  height: 200px;
  background-color: blue;
  grid-area: b2;
}

.box3 {
  height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  height: 250px;
  background-color: orange;
  grid-area: b4;
}

.box5 {
  height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  height: 400px;
  background-color: gray;
  grid-area: b6;
}

1

2

3

4

5

6

Body:
If you want to maintain the designated heights, you can wrap the column 2 divs into a flex wrapper:

<div class="container">
  <div class="box box1">1</div>
  <div class="box box5">5</div>
 <div class = "flex">
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box6">6</div>
   </div>
</div>

And then change your grid CSS a bit to accommodate:

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b3" "b5 b3";
}

Now the only boxes that need grid-area are the 2 on the left (b1 and b5) and the flex wrapper (b3 in my code):

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  height: 200px;
  background-color: blue;
}

.box3 {
  height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  height: 250px;
  background-color: orange;
}

.box5 {
  height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  height: 400px;
  background-color: gray;
}

.flex {
  display: flex;
  flex-direction: column;
  grid-area: b3;
}

Check this demo JSfiddle


问:
Capture names employees who login and logout cells are empty using for loop
I have a requirement to capture the name of the employee whos login and logout cells are empty and paste from cells range "A30". I used for loop and if condition to capture the employee whos login and logout cells are empty. By using the below code I get only the last person whos login and logout cells are empty.

How to capture all the employee's whos login and logout cells are empty.

```<code>For i = 2 To a

If Worksheets("Output").Cells(i, 3).Value = "" And Worksheets("Output").Cells(i, 4).Value = "" Then

Worksheets("Output").Cells(i, 1).Copy

ThisWorkbook.Worksheets("Output").Range("A35").PasteSpecial xlPasteValues

End If

Next
</code>```

答:
The easy way to do this is to have a variable, which then gets incremented in your for loop.  Since you are pasting to a single cell each time, you can use Cells(x,y) rather than a range.  This makes it easier to use the variable.  Something like this should work for you:</p>

```<code>Dim startOut As Integer
startOut = 30

For i = 2 To a

    If Worksheets("Output").Cells(i, 3).Value = "" And Worksheets("Output").Cells(i, 4).Value = "" Then

        Worksheets("Output").Cells(i, 1).Copy
        ThisWorkbook.Worksheets("Output").Cells(startOut, 1).PasteSpecial xlPasteValues
        startOut = startOut + 1

    End If

Next
</code>```

Body:
I have a requirement to capture the name of the employee whos login and logout cells are empty and paste from cells range "A30". I used for loop and if condition to capture the employee whos login and logout cells are empty. By using the below code I get only the last person whos login and logout cells are empty.

How to capture all the employee's whos login and logout cells are empty.

For i = 2 To a

If Worksheets("Output").Cells(i, 3).Value = "" And Worksheets("Output").Cells(i, 4).Value = "" Then

Worksheets("Output").Cells(i, 1).Copy

ThisWorkbook.Worksheets("Output").Range("A35").PasteSpecial xlPasteValues

End If

Next

Body:
The easy way to do this is to have a variable, which then gets incremented in your for loop.  Since you are pasting to a single cell each time, you can use Cells(x,y) rather than a range.  This makes it easier to use the variable.  Something like this should work for you:

Dim startOut As Integer
startOut = 30

For i = 2 To a

    If Worksheets("Output").Cells(i, 3).Value = "" And Worksheets("Output").Cells(i, 4).Value = "" Then

        Worksheets("Output").Cells(i, 1).Copy
        ThisWorkbook.Worksheets("Output").Cells(startOut, 1).PasteSpecial xlPasteValues
        startOut = startOut + 1

    End If

Next


问:
Calculate PI using Random Numbers
Having trouble with the following question:

In geometry the ratio of the circumference of a circle to its diameter is known as π. The value of π can be estimated from an infinite series of the form:

π / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
There is another novel approach to calculate π. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just π square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is π / 4.

To simuluate the throwing of darts we will use a random number generator. The Random module has several random number generating functions that can be used. For example, the function uniform(a, b) returns a floating point random number in the range a (inclusive) and b (exclusive).

Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.

A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. The way we achieve that is:

```<code>xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)
</code>```

To determine if a point is inside the circle its distance from the center of the circle must be strictly less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is math.hypot (xPos, yPos). The radius of the circle is 1 unit.

The program that you will be writing will be called CalculatePI. It will have the following structure:

```<code>import math
import random

def computePI ( numThrows ):
  ...

def main ():
  ...

main()
</code>```

Your function main() will call the function computePI() for a given number of throws. The function computePI() will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will determine if that randomly generated point is inside the circle or not. You will do this as many times as specified by the number of throws. You will keep a count of the number of times a dart lands within the circle. That count divided by the total number of throws is the ratio π/4. The function computePI() will then return the computed value of PI.
In your function main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by math.pi. The quantity Difference in the output is your calculated value of PI minus math.pi. Use the following number of throws to run your experiment - 100, 1000, 10,000, 100,000, 1,000,000, and 10,000,000. You will call the function computePI() with these numbers as input parameters. Your output will be similar to the following, i.e. the actual values of your Calculated PI and Difference will be different but close to the ones shown:

```<code>Computation of PI using Random Numbers

num = 100        Calculated PI = 3.320000   Difference = +0.178407
num = 1000       Calculated PI = 3.080000   Difference = -0.061593
num = 10000      Calculated PI = 3.120400   Difference = -0.021193
num = 100000     Calculated PI = 3.144720   Difference = +0.003127
num = 1000000    Calculated PI = 3.142588   Difference = +0.000995
num = 10000000   Calculated PI = 3.141796   Difference = +0.000204

Difference = Calculated PI - math.pi
</code>```

Your output must be in the above format. The number of throws must be left justified. The calculated value of π and the difference must be expressed correct to six places of decimal. There should be plus or minus sign on the difference. Read the relevant sections in the book on formatting.

Till now I have done:

```<code>import math
import random

def computePI (numThrows):

  xPos = random.uniform (-1.0, 1.0)
  yPos = random.uniform (-1.0, 1.0)

  in_circle = 0
  throws = 0

  while (throws < numThrows):
    if math.hypot (xPos, yPos) <= 1:
      in_circle += 1
    throws += 1
  pi = (4 * in_circle) / numThrows
  return pi

def main ():

  throws = (100, 1000, 10000, 100000, 1000000, 10000000)
  for numThrows in throws[0:7]:

main ()
</code>```

I am having trouble calling the ComputePI function in the Main function. Also how do I print num with left indentation and ensure that all numbers have the required decimal space? Thank you!

答:
This is how I find it easy.

```<code>import random
import math
def approximate_pi():
    total_points = 0
    within_circle = 0
    for i in range (10000):
        x = random.random()
        y = random.random()
        total_points += 1
        distance = math.sqrt(x**2+y**2)
        if distance < 1:
            within_circle += 1
        if total_points % 1000 == 0:
            pi_estimate = 4 * within_circle / total_points
            yield pi_estimate

</code>```

set total point generated and points withing the circle to zero

```<code>total_points = 0
within_circle = 0
</code>```

generate the random values of x and y for multiple times. Calculate the distance of the point from the center of the circle or (0,0). Then if the distance is less than one it means that it's within the circle so it is incremented.

```<code>distance = math.sqrt(x**2+y**2)
        if distance < 1:
            within_circle += 1
</code>```

Now if you have generated let's say multiple of 1000(1000 because we have taken the range for 10,000 so 1000 to get 10 values of pi), calculate the estimated value of pi using this formula which you know already.and the tied the estimate value(pi_estmate)

```<code>if total_points % 1000 == 0:
            pi_estimate = 4 * within_circle / total_points
            yield pi_estimate
</code>```

```<code>pi_estimates = list(es for es in approximate_pi())
errors = list(estimate-math.pi for estimate in approximate_pi())
print(pi_estimates)
print(errors)
</code>```

OUTPUT:

Estimates

```<code>[3.096, 3.142, 3.1253333333333333, 3.121, 3.1384, 3.136, 3.1314285714285712, 3.133, 3.1342222222222222]
</code>```

Errors

```<code>[0.04240734641020705, 0.02240734641020703, 0.03307401307687341, 0.020407346410206806, 0.02320734641020694, 0.0017406797435404187, -0.009021225018364554, -0.011592653589793223, -0.016703764700904067]
</code>```

Hope you understood, I hope my explanation was easy to understand, I am a beginner and learning stuff if there is anything wrong please feel free to notify.
Thank you

Title: Calculate PI using Random Numbers

Body:
Having trouble with the following question:

In geometry the ratio of the circumference of a circle to its diameter is known as π. The value of π can be estimated from an infinite series of the form:

π / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
There is another novel approach to calculate π. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just π square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is π / 4.

To simuluate the throwing of darts we will use a random number generator. The Random module has several random number generating functions that can be used. For example, the function uniform(a, b) returns a floating point random number in the range a (inclusive) and b (exclusive).

Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.

A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. The way we achieve that is:

xPos = random.uniform (-1.0, 1.0)
yPos = random.uniform (-1.0, 1.0)

To determine if a point is inside the circle its distance from the center of the circle must be strictly less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is math.hypot (xPos, yPos). The radius of the circle is 1 unit.

The program that you will be writing will be called CalculatePI. It will have the following structure:

import math
import random

def computePI ( numThrows ):
  ...

def main ():
  ...

main()

Your function main() will call the function computePI() for a given number of throws. The function computePI() will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will determine if that randomly generated point is inside the circle or not. You will do this as many times as specified by the number of throws. You will keep a count of the number of times a dart lands within the circle. That count divided by the total number of throws is the ratio π/4. The function computePI() will then return the computed value of PI.
In your function main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by math.pi. The quantity Difference in the output is your calculated value of PI minus math.pi. Use the following number of throws to run your experiment - 100, 1000, 10,000, 100,000, 1,000,000, and 10,000,000. You will call the function computePI() with these numbers as input parameters. Your output will be similar to the following, i.e. the actual values of your Calculated PI and Difference will be different but close to the ones shown:

Computation of PI using Random Numbers

num = 100        Calculated PI = 3.320000   Difference = +0.178407
num = 1000       Calculated PI = 3.080000   Difference = -0.061593
num = 10000      Calculated PI = 3.120400   Difference = -0.021193
num = 100000     Calculated PI = 3.144720   Difference = +0.003127
num = 1000000    Calculated PI = 3.142588   Difference = +0.000995
num = 10000000   Calculated PI = 3.141796   Difference = +0.000204

Difference = Calculated PI - math.pi

Your output must be in the above format. The number of throws must be left justified. The calculated value of π and the difference must be expressed correct to six places of decimal. There should be plus or minus sign on the difference. Read the relevant sections in the book on formatting.

Till now I have done:

import math
import random

def computePI (numThrows):

  xPos = random.uniform (-1.0, 1.0)
  yPos = random.uniform (-1.0, 1.0)

  in_circle = 0
  throws = 0

  while (throws < numThrows):
    if math.hypot (xPos, yPos) <= 1:
      in_circle += 1
    throws += 1
  pi = (4 * in_circle) / numThrows
  return pi

def main ():

  throws = (100, 1000, 10000, 100000, 1000000, 10000000)
  for numThrows in throws[0:7]:

main ()

I am having trouble calling the ComputePI function in the Main function. Also how do I print num with left indentation and ensure that all numbers have the required decimal space? Thank you!

Body:
This is how I find it easy.

import random
import math
def approximate_pi():
    total_points = 0
    within_circle = 0
    for i in range (10000):
        x = random.random()
        y = random.random()
        total_points += 1
        distance = math.sqrt(x**2+y**2)
        if distance < 1:
            within_circle += 1
        if total_points % 1000 == 0:
            pi_estimate = 4 * within_circle / total_points
            yield pi_estimate

set total point generated and points withing the circle to zero

total_points = 0
within_circle = 0

generate the random values of x and y for multiple times. Calculate the distance of the point from the center of the circle or (0,0). Then if the distance is less than one it means that it's within the circle so it is incremented.

distance = math.sqrt(x**2+y**2)
        if distance < 1:
            within_circle += 1

Now if you have generated let's say multiple of 1000(1000 because we have taken the range for 10,000 so 1000 to get 10 values of pi), calculate the estimated value of pi using this formula which you know already.and the tied the estimate value(pi_estmate)

if total_points % 1000 == 0:
            pi_estimate = 4 * within_circle / total_points
            yield pi_estimate

pi_estimates = list(es for es in approximate_pi())
errors = list(estimate-math.pi for estimate in approximate_pi())
print(pi_estimates)
print(errors)

OUTPUT:

Estimates

[3.096, 3.142, 3.1253333333333333, 3.121, 3.1384, 3.136, 3.1314285714285712, 3.133, 3.1342222222222222]

Errors

[0.04240734641020705, 0.02240734641020703, 0.03307401307687341, 0.020407346410206806, 0.02320734641020694, 0.0017406797435404187, -0.009021225018364554, -0.011592653589793223, -0.016703764700904067]

Hope you understood, I hope my explanation was easy to understand, I am a beginner and learning stuff if there is anything wrong please feel free to notify.
Thank you


问:
How to change MaterialAlertDialog text color properly?
I try to use widgets from Material Components only, but in many cases, it's not documented how styling can be achieved.

Let's consider MaterialAlertDialog.

Each time I want to show a dialog, I call such part of the code:

```<code>MaterialAlertDialogBuilder(context, R.style.Theme_MyApp_Dialog_Alert)
    .setTitle("Title")
    .setMessage("This is message.")
    .setPositiveButton(R.string.ok) { _, _ -> }
    .show()
</code>```

As you can see, I'm using a custom theme.

```<code><style name="Theme.MyApp.Dialog.Alert" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- attributes here -->
</style>
</code>```

The problem is that some of the attributes are not working. For example textColor. So the question is how to change the body or title text color in MaterialAlertDialog?

I use the newest version of Material Components - 1.1.0-alpha07.

PS.

I'm not sure which theme should be a parent. In Material Theme Builder they use @style/ThemeOverlay.MaterialComponents.Dialog.Alert which actually gives an "old" look of dialogs.

答:
You can simply override the default colors using:

```<code>  <style name="Theme.MyApp.Dialog.Alert" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">

     <!-- Text Color for title and message -->
     <item name="colorOnSurface">@color/....</item>
     ....
  </style>
</code>```

Otherwise you can customize the style used by the title and the body text using:

```<code>  <style name="Theme.MyApp.Dialog.Alert" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
      <!-- Title -->
      <item name="materialAlertDialogTitleTextStyle">@style/MyTitle_MaterialAlertDialog.MaterialComponents.Title.Text</item>

     <!-- Body -->
     <item name="materialAlertDialogBodyTextStyle">@style/BodyTextAppearance.MaterialComponents.Body2</item>
  </style>

  <style name="MyTitle_MaterialAlertDialog.MaterialComponents.Title.Text" parent="@style/MaterialAlertDialog.MaterialComponents.Title.Text">
    <item name="android:textColor">@color/...</item>
    <item name="android:textAppearance">@style/....</item>
  </style>

  <style name="BodyTextAppearance.MaterialComponents.Body2" parent="@style/MaterialAlertDialog.MaterialComponents.Body.Text">
    <item name="android:textColor">@color/....</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textAllCaps">true</item>
    <item name="fontFamily">sans-serif-condensed-light</item>
  </style>
</code>```

Body:
I try to use widgets from Material Components only, but in many cases, it's not documented how styling can be achieved.

Let's consider MaterialAlertDialog.

Each time I want to show a dialog, I call such part of the code:

MaterialAlertDialogBuilder(context, R.style.Theme_MyApp_Dialog_Alert)
    .setTitle("Title")
    .setMessage("This is message.")
    .setPositiveButton(R.string.ok) { _, _ -> }
    .show()

As you can see, I'm using a custom theme.

The problem is that some of the attributes are not working. For example textColor. So the question is how to change the body or title text color in MaterialAlertDialog?

I use the newest version of Material Components - 1.1.0-alpha07.

PS.

I'm not sure which theme should be a parent. In Material Theme Builder they use @style/ThemeOverlay.MaterialComponents.Dialog.Alert which actually gives an "old" look of dialogs.

Body:
You can simply override the default colors using:

  <style name="Theme.MyApp.Dialog.Alert" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">

     <!-- Text Color for title and message -->
     <item name="colorOnSurface">@color/....</item>
     ....
  </style>

Otherwise you can customize the style used by the title and the body text using:

  <style name="Theme.MyApp.Dialog.Alert" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
      <!-- Title -->
      <item name="materialAlertDialogTitleTextStyle">@style/MyTitle_MaterialAlertDialog.MaterialComponents.Title.Text</item>

     <!-- Body -->
     <item name="materialAlertDialogBodyTextStyle">@style/BodyTextAppearance.MaterialComponents.Body2</item>
  </style>

  <style name="MyTitle_MaterialAlertDialog.MaterialComponents.Title.Text" parent="@style/MaterialAlertDialog.MaterialComponents.Title.Text">
    <item name="android:textColor">@color/...</item>
    <item name="android:textAppearance">@style/....</item>
  </style>

  <style name="BodyTextAppearance.MaterialComponents.Body2" parent="@style/MaterialAlertDialog.MaterialComponents.Body.Text">
    <item name="android:textColor">@color/....</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textAllCaps">true</item>
    <item name="fontFamily">sans-serif-condensed-light</item>
  </style>


问:
pg_prepare(): Query failed: ERROR: Relation does not exist
I am trying to execute a query on a Postgres database using PHP. I get the following error:

```<code>pg_prepare(): Query failed: ERROR: relation "login" does not exist LINE 1: SELECT * FROM login
</code>```

This is a snippet of my code:

```<code>$connString = "host= port= dbname= user=password=";
$conn = pg_connect($connString);
if ($conn) {
    $sql = 'SELECT * FROM login ';
    if (pg_prepare($conn, "myQuery", $sql)) {
        $result = pg_execute($conn, "myQuery", array());
        if ($result) {
            while ($row = pg_fetch_row($result)) {

                echo $row[0];

                echo $row[1];
            }
        } else {
            echo 'executing error!';
        }
    } else {
        echo 'preparing error!';
    }
} else {
    echo "Connection error!";
}
if ($conn) {
    pg_close($conn);
}
</code>```

When i run this script, it also prints 'preparing error!'

I guess there is something going on within the database.
I have tried to create a new table. I also tried to use quotes in the query on several places, but nothing works.

This is the query I used to create the database:

```<code>CREATE TABLE login
(
    user_id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
    username character varying(50) COLLATE pg_catalog."default",
    pwd character varying(50) COLLATE pg_catalog."default",
    CONSTRAINT pk_user_id PRIMARY KEY (user_id)
)
</code>```

How do I fix this?

答:
Try </p>

```<code>SELECT * FROM public."login"
</code>```

Body:
I am trying to execute a query on a Postgres database using PHP. I get the following error:

pg_prepare(): Query failed: ERROR: relation "login" does not exist LINE 1: SELECT * FROM login

This is a snippet of my code:

$connString = "host= port= dbname= user=password=";
$conn = pg_connect($connString);
if ($conn) {
    $sql = 'SELECT * FROM login ';
    if (pg_prepare($conn, "myQuery", $sql)) {
        $result = pg_execute($conn, "myQuery", array());
        if ($result) {
            while ($row = pg_fetch_row($result)) {

                echo $row[0];

                echo $row[1];
            }
        } else {
            echo 'executing error!';
        }
    } else {
        echo 'preparing error!';
    }
} else {
    echo "Connection error!";
}
if ($conn) {
    pg_close($conn);
}

When i run this script, it also prints 'preparing error!'

I guess there is something going on within the database.
I have tried to create a new table. I also tried to use quotes in the query on several places, but nothing works.

This is the query I used to create the database:

CREATE TABLE login
(
    user_id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
    username character varying(50) COLLATE pg_catalog."default",
    pwd character varying(50) COLLATE pg_catalog."default",
    CONSTRAINT pk_user_id PRIMARY KEY (user_id)
)

How do I fix this?

Body:
Try

SELECT * FROM public."login"


问:
Java version of matlab's linspace
Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.

For example to get all integers from 1 to 30, in matlab I would type:

```<code>1:30
</code>```

or

```<code>linspace(1,30)
</code>```

答:
I think Bill K got the right idea, but I think there is no need to have a Linspace class.</p>

```<code>// If you write linspace(start,end,totalCount) in Matlab ===>

for(float i = start; i < end; i += (end-start)/totalCount)
    something(i);
</code>```

Title: Java version of matlab's linspace

Body:
Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.

For example to get all integers from 1 to 30, in matlab I would type:

1:30

or

linspace(1,30)

Body:
I think Bill K got the right idea, but I think there is no need to have a Linspace class.

// If you write linspace(start,end,totalCount) in Matlab ===>

for(float i = start; i < end; i += (end-start)/totalCount)
    something(i);


问:
Checkbox selected items not updating database
I was trying to pick list of items in a table and assign them to a new table. I'm able to pick and display the query set but it doesn't update into database. Maybe there is some error in the code. The form gets saved but the object list is not saved. The traceback is attached. The query set is not saving into database. Is this related to Foreignkey values? Appreciate some advise or alternatives

Models.py

```<code>class BidItem(models.Model):
bid = models.ForeignKey(Bid, related_name='bids', on_delete=models.CASCADE)
order= models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.ForeignKey(OrderItem, on_delete=models.CASCADE)

def __str__(self):
    return str(self.id)

def bid_price(self):
    return self.price * self.quantity
</code>```

Views.py

```<code>def bid_list(request):
    """Place bids"""
    selected = request.POST.getlist('vendorbid')
    selected_orders = OrderItem.objects.filter(pk__in=selected)

    if request.method == 'POST':
            form = BidListForm(request.POST)
            if form.is_valid():
                bid = form.save()
                for item in selected_orders:
                    BidItem.objects.create(bid=bid,
                                            order = item['order.id'],
                                            product=item['product'],
                                            price=item['price'],
                                            quantity=item['quantity'])

                return render(request,'bids/bid_placed.html')
            else:
                return render(request, 'bids/bid_list.html', {'selected_orders': selected_orders, 'form': form})
        else:
            form = BidListForm()
            orders = OrderItem.objects.all()

            return render(request, 'bids/bid_list.html', {'form': form, 'orders': orders})
</code>```

Error and traceback

The error I get is:
TypeError at /bids/bid_list/
'OrderItem' object is not subscriptable

Trace back is:

答:
I finally solved as there were foreign keys I had to change the variables accordingly:

Here is the resolved part in views.py for anybody's reference:

Views.py edited part

```<code>BidItem.objects.create(bid=bid,
                                    order=item.order,
                                    product=item.product,
                                    price=item.price,
                                    quantity_id=item.quantity)
</code>```

Body:
I was trying to pick list of items in a table and assign them to a new table. I'm able to pick and display the query set but it doesn't update into database. Maybe there is some error in the code. The form gets saved but the object list is not saved. The traceback is attached. The query set is not saving into database. Is this related to Foreignkey values? Appreciate some advise or alternatives

Models.py

class BidItem(models.Model):
bid = models.ForeignKey(Bid, related_name='bids', on_delete=models.CASCADE)
order= models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.ForeignKey(OrderItem, on_delete=models.CASCADE)

def __str__(self):
    return str(self.id)

def bid_price(self):
    return self.price * self.quantity

Views.py

def bid_list(request):
    """Place bids"""
    selected = request.POST.getlist('vendorbid')
    selected_orders = OrderItem.objects.filter(pk__in=selected)

    if request.method == 'POST':
            form = BidListForm(request.POST)
            if form.is_valid():
                bid = form.save()
                for item in selected_orders:
                    BidItem.objects.create(bid=bid,
                                            order = item['order.id'],
                                            product=item['product'],
                                            price=item['price'],
                                            quantity=item['quantity'])

                return render(request,'bids/bid_placed.html')
            else:
                return render(request, 'bids/bid_list.html', {'selected_orders': selected_orders, 'form': form})
        else:
            form = BidListForm()
            orders = OrderItem.objects.all()

            return render(request, 'bids/bid_list.html', {'form': form, 'orders': orders})

Error and traceback

The error I get is:
TypeError at /bids/bid_list/
'OrderItem' object is not subscriptable

Trace back is:

Body:
I finally solved as there were foreign keys I had to change the variables accordingly:

Here is the resolved part in views.py for anybody's reference:

Views.py edited part

BidItem.objects.create(bid=bid,
                                    order=item.order,
                                    product=item.product,
                                    price=item.price,
                                    quantity_id=item.quantity)


问:
Android: How to make type converters (for Room) generic for all List of objects in Kotlin
I am using Room as the local database solution in my project.
For every list of a certain object type I've added type converters to the project so the type convertor would look something like this:

```<code>@TypeConverter
fun convertListToString(video: List<VideoType>): String {

    val videoArray = arrayOfNulls<VideoType>(video.size)
    for (i in 0..video.size - 1) {
        videoArray[i] = video[i]
    }
    var str = ""
    val gson = Gson()
    for (i in videoArray.indices) {
        val jsonString = gson.toJson(videoArray[i])
        str = str + jsonString
        if (i < videoArray.size - 1) {
            str = str + strSeparator
        }
    }

    return str
}

@TypeConverter
fun convertStringToList(videoString: String): List<VideoType> {

    val videoArray = videoString.split(strSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val videos = ArrayList<VideoType>()
    val gson = Gson()
    for (i in 0 until videoArray.size - 1) {
        videos.add(gson.fromJson(videoArray[i], VideoType::class.java))
    }

    return videos
}
</code>```

Problem only is that I have a whole bunch of List of different types that need to be converted, so currently I am just copying this code for every type. I would like to use generics, but so far haven't been able to figure out how to do it.

For example using something like:

```<code>@TypeConverter
inline fun <reified T> convertStringToList(string: String): List<T> {
    val objectArray = string.split(strSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val objects = ArrayList<T>()
    val gson = Gson()
    for (i in 0 until objectArray.size - 1) {
        objects.add(gson.fromJson(objectArray[i], T::class.java))
    }
    return objects
}
</code>```

isn't working and causes compilation error with Android Studio giving me an error telling: Type converters must be public

Anyone an idea how I can use generics for my Room TypeConverter?

答:
Well, basically the main idea of type converters is that databases can't read objects as a parameters.So you've to 2 ways first one is to do it manually with join relation inside the db, Or you can use type converter.
How type converter works?
It's simple it just convert your object to JSON String and save it as string.
In your problem, you've to add annotation before entity

```<code>private class YourDTO(
        @TypeConverters(DateConverter.class)
         Date date
</code>```

And in DateConverter class

```<code>@TypeConverter
public static Long toTimestamp(Date date) {
    return date == null ? null : date.getTime();
}
</code>```

Body:
I am using Room as the local database solution in my project.
For every list of a certain object type I've added type converters to the project so the type convertor would look something like this:

@TypeConverter
fun convertListToString(video: List<VideoType>): String {

    val videoArray = arrayOfNulls<VideoType>(video.size)
    for (i in 0..video.size - 1) {
        videoArray[i] = video[i]
    }
    var str = ""
    val gson = Gson()
    for (i in videoArray.indices) {
        val jsonString = gson.toJson(videoArray[i])
        str = str + jsonString
        if (i < videoArray.size - 1) {
            str = str + strSeparator
        }
    }

    return str
}

@TypeConverter
fun convertStringToList(videoString: String): List<VideoType> {

    val videoArray = videoString.split(strSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val videos = ArrayList<VideoType>()
    val gson = Gson()
    for (i in 0 until videoArray.size - 1) {
        videos.add(gson.fromJson(videoArray[i], VideoType::class.java))
    }

    return videos
}

Problem only is that I have a whole bunch of List of different types that need to be converted, so currently I am just copying this code for every type. I would like to use generics, but so far haven't been able to figure out how to do it.

For example using something like:

@TypeConverter
inline fun <reified T> convertStringToList(string: String): List<T> {
    val objectArray = string.split(strSeparator.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val objects = ArrayList<T>()
    val gson = Gson()
    for (i in 0 until objectArray.size - 1) {
        objects.add(gson.fromJson(objectArray[i], T::class.java))
    }
    return objects
}

isn't working and causes compilation error with Android Studio giving me an error telling: Type converters must be public

Anyone an idea how I can use generics for my Room TypeConverter?

Body:
Well, basically the main idea of type converters is that databases can't read objects as a parameters.So you've to 2 ways first one is to do it manually with join relation inside the db, Or you can use type converter.
How type converter works?
It's simple it just convert your object to JSON String and save it as string.
In your problem, you've to add annotation before entity

private class YourDTO(
        @TypeConverters(DateConverter.class)
         Date date

And in DateConverter class

@TypeConverter
public static Long toTimestamp(Date date) {
    return date == null ? null : date.getTime();
}


问:
codeigniter 3 URI routing - geting right hand side from given url
I need to simulate routing in Codeigniter 3, so my question is how to get the right-hand side from any URL programmatically?

for example, some routes that I have:

```<code>$route["blog"] = "Main/blog/en";
$route["blog/(:any)"] = "Main/blog/en/$1";
$route["novosti"] = "Main/blog/sr";
$route["novosti/(:any)"] = "Main/blog/sr/$1";
$route["contact"] = "Main/contact/en";
$route["kontakt"] = "Main/contact/sr";
</code>```

Now I need a function that can return right-hand side for a given URL part something like this:

```<code>echo $this->route->item("novosti/petar")
</code>```

should print then Main/blog/sr/$1 or Main/blog/sr/petar

Is there such a function in Codeigniter, because I can't find it in documentation?

UPDATE:
I am looking throughout system/router class and I see that protected function _parse_routes is doing something similar so if there is no function that can give me what I need I will create one based on this one.

答:
use this

$this->router->routes['blog']

you will get

Main/blog/en

Body:
I need to simulate routing in Codeigniter 3, so my question is how to get the right-hand side from any URL programmatically?

for example, some routes that I have:

$route["blog"] = "Main/blog/en";
$route["blog/(:any)"] = "Main/blog/en/$1";
$route["novosti"] = "Main/blog/sr";
$route["novosti/(:any)"] = "Main/blog/sr/$1";
$route["contact"] = "Main/contact/en";
$route["kontakt"] = "Main/contact/sr";

Now I need a function that can return right-hand side for a given URL part something like this:

echo $this->route->item("novosti/petar")

should print then Main/blog/sr/$1 or Main/blog/sr/petar

Is there such a function in Codeigniter, because I can't find it in documentation?

UPDATE:
I am looking throughout system/router class and I see that protected function _parse_routes is doing something similar so if there is no function that can give me what I need I will create one based on this one.


问:
How can I track each "step" of a program in PHP?
For example, in my error_log, it says something like:

```<code>Error... require, include, a_function, another_function
</code>```

Basically it tracks each step of the program. I want to implement something like this for debugging purposes. How do I "track" the execution of the program in PHP?

答: In addition to debug_backtrace() as mentioned by others, I would recommend installing Xdebug and making use of the code profiler therein.  When coupled with a cachegrind application to analyze the profile, you can easily view and page through a full trace of your script's execution with execution times per function call.

Body:
For example, in my error_log, it says something like:

Error... require, include, a_function, another_function

Basically it tracks each step of the program. I want to implement something like this for debugging purposes. How do I "track" the execution of the program in PHP?


问:
React API fetch returning an empty object
I am having problems of receiving the data from a api fetch,
I am guessing data might received after the console.log()?

How can I fix this?

```<code>fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        console.log(data[0])
      })
</code>```

This code return a object data straight away

```<code>fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false})
      })
      console.log(this.state.api)
</code>```

However, I'll need to save the fetched data into the state, but when I call it after saving it, it returns a empty object, that influences me to print the data to UI.

Help....

答:
state is updated asynchronously. If you want to see the updated state immediately after updating it, pass a second argument to setState function which is a callback function which runs after the state has updated

```<code>this.setState({api: data[0] ,loading:false}, () => console.log(this.state))
</code>```

Body:
I am having problems of receiving the data from a api fetch,
I am guessing data might received after the console.log()?

How can I fix this?

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        console.log(data[0])
      })

This code return a object data straight away

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false})
      })
      console.log(this.state.api)

However, I'll need to save the fetched data into the state, but when I call it after saving it, it returns a empty object, that influences me to print the data to UI.

Help....

Body:
state is updated asynchronously. If you want to see the updated state immediately after updating it, pass a second argument to setState function which is a callback function which runs after the state has updated

this.setState({api: data[0] ,loading:false}, () => console.log(this.state))


问:
MongoDB lookup when foreign field and local field are array of objects
I have two collections 'questions' and 'answers'.
questions document is like this:

```<code>      [
        {
          _id: "8326ccbn73487290nc",
          questions: [
           {id: "12345", question: "Test", correct_answer: '0'},
           {id: "123456", question: "Test 2", correct_answer: '1'},
           {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
       },
       {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
     ]
</code>```

answers document is like this:

```<code>{
  id: '327rhrne7fr873',
  user_id: '43757fn574057fnf',
  question_id: '8326ccbn73487290nc',
  answers: [
    { id: '12345', student_answer: '1'},
    { id: '123456', student_answer: '0'},
  ]
}
</code>```

so i want to return something like this:

```<code>[
    {
        _id: '8326ccbn73487290nc',
        questions: [
          {id: "12345", question: "Test", correct_answer: '0', student_answers: '1'},
          {id: "123456", question: "Test 2", correct_answer: '1', , student_answers: '0'},
          {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
    },
    {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
]
</code>```

Can anyone help me how can i do something like that.

答:
You can use this pipeline under the assumption that an answer object is matched to a single question object.</p>

```<code>db.answers.aggregate([
    {
        $lookup: {
            from: "questions",
            let: {answerIds: {$map: {input: "$answers", as: "answer", in: "$$answer.id"}}},
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $gt: [
                                {
                                    $size: {
                                        $filter: {
                                            input: "$questions",
                                            as: "question",
                                            cond: {
                                                $setIsSubset: [["$$question.id"], "$$answerIds"]
                                            }
                                        }
                                    }
                                },
                                0
                            ]
                        }
                    }
                }
            ],
            as: "questions"
        }
    },
    {
        $unwind: "$questions"
    },
    {
        $project: {
            _id: "$questions._id",
            questions: {
                $map: {
                    input: "$questions.questions",
                    as: "question",
                    in: {
                        $mergeObjects: [
                            "$$question",
                            {
                                $ifNull: [
                                    {
                                        $arrayElemAt: [
                                            {
                                                $filter: {
                                                    input: "$answers",
                                                    as: "answer",
                                                    cond: {$eq: ["$$answer.id", "$$question.id"]}
                                                }
                                            }
                                            , 0
                                        ]
                                    },
                                    {}
                                ]
                            }
                        ]
                    }
                }
            }
        }
    }
])
</code>```

Body:
I have two collections 'questions' and 'answers'.
questions document is like this:

      [
        {
          _id: "8326ccbn73487290nc",
          questions: [
           {id: "12345", question: "Test", correct_answer: '0'},
           {id: "123456", question: "Test 2", correct_answer: '1'},
           {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
       },
       {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
     ]

answers document is like this:

{
  id: '327rhrne7fr873',
  user_id: '43757fn574057fnf',
  question_id: '8326ccbn73487290nc',
  answers: [
    { id: '12345', student_answer: '1'},
    { id: '123456', student_answer: '0'},
  ]
}

so i want to return something like this:

[
    {
        _id: '8326ccbn73487290nc',
        questions: [
          {id: "12345", question: "Test", correct_answer: '0', student_answers: '1'},
          {id: "123456", question: "Test 2", correct_answer: '1', , student_answers: '0'},
          {id: "1234567", question: "Test 3", correct_answer: '1'},
        ]
    },
    {
          _id: "8326ccbn734872ytruy90nclk",
          questions: [
           {id: "345", question: "Test", correct_answer: '0'},
           {id: "3456", question: "Test 2", correct_answer: '1'},
           {id: "34567", question: "Test 3", correct_answer: '1'},
        ]
       }
]

Can anyone help me how can i do something like that.

Body:
You can use this pipeline under the assumption that an answer object is matched to a single question object.

db.answers.aggregate([
    {
        $lookup: {
            from: "questions",
            let: {answerIds: {$map: {input: "$answers", as: "answer", in: "$$answer.id"}}},
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $gt: [
                                {
                                    $size: {
                                        $filter: {
                                            input: "$questions",
                                            as: "question",
                                            cond: {
                                                $setIsSubset: [["$$question.id"], "$$answerIds"]
                                            }
                                        }
                                    }
                                },
                                0
                            ]
                        }
                    }
                }
            ],
            as: "questions"
        }
    },
    {
        $unwind: "$questions"
    },
    {
        $project: {
            _id: "$questions._id",
            questions: {
                $map: {
                    input: "$questions.questions",
                    as: "question",
                    in: {
                        $mergeObjects: [
                            "$$question",
                            {
                                $ifNull: [
                                    {
                                        $arrayElemAt: [
                                            {
                                                $filter: {
                                                    input: "$answers",
                                                    as: "answer",
                                                    cond: {$eq: ["$$answer.id", "$$question.id"]}
                                                }
                                            }
                                            , 0
                                        ]
                                    },
                                    {}
                                ]
                            }
                        ]
                    }
                }
            }
        }
    }
])


问:
How to store a list in a column of a database table
So, per Mehrdad's answer to a related question, I get it that a "proper" database table column doesn't store a list.  Rather, you should create another table that effectively holds the elements of said list and then link to it directly or through a junction table.  However, the type of list I want to create will be composed of unique items (unlike the linked question's fruit example).  Furthermore, the items in my list are explicitly sorted - which means that if I stored the elements in another table, I'd have to sort them every time I accessed them.  Finally, the list is basically atomic in that any time I wish to access the list, I will want to access the entire list rather than just a piece of it - so it seems silly to have to issue a database query to gather together pieces of the list.

AKX's solution (linked above) is to serialize the list and store it in a binary column.  But this also seems inconvenient because it means that I have to worry about serialization and deserialization.

Is there any better solution?  If there is no better solution, then why?  It seems that this problem should come up from time to time.

... just a little more info to let you know where I'm coming from.  As soon as I had just begun understanding SQL and databases in general, I was turned on to LINQ to SQL, and so now I'm a little spoiled because I expect to deal with my programming object model without having to think about how the objects are queried or stored in the database.

Thanks All!

John

UPDATE:  So in the first flurry of answers I'm getting, I see "you can go the CSV/XML route... but DON'T!".  So now I'm looking for explanations of why.  Point me to some good references.

Also, to give you a better idea of what I'm up to:  In my database I have a Function table that will have a list of (x,y) pairs.  (The table will also have other information that is of no consequence for our discussion.)  I will never need to see part of the list of (x,y) pairs.  Rather, I will take all of them and plot them on the screen.  I will allow the user to drag the nodes around to change the values occasionally or add more values to the plot.

答:
I was very reluctant to choose the path I finally decide to take because of many answers. While they add more understanding to what is SQL and its principles, I decided to become an outlaw. I was also hesitant to post my findings as for some it's more important to vent frustration to someone breaking the rules rather than understanding that there are very few universal truthes.

I have tested it extensively and, in my specific case, it was way more efficient than both using array type (generously offered by PostgreSQL) or querying another table.

Here is my answer:
I have successfully implemented a list into a single field in PostgreSQL, by making use of the fixed length of each item of the list. Let say each item is a color as an ARGB hex value, it means 8 char. So you can create your array of max 10 items by multiplying by the length of each item:

```<code>ALTER product ADD color varchar(80)
</code>```

In case your list items length differ you can always fill the padding with \0

NB: Obviously this is not necessarily the best approach for hex number since a list of integers would consume less storage but this is just for the purpose of illustrating this idea of array by making use of a fixed length allocated to each item.

The reason why:
1/ Very convenient: retrieve item i at substring i*n, (i +1)*n.
2/ No overhead of cross tables queries.
3/ More efficient and cost-saving on the server side. The list is like a mini blob that the client will have to split.

While I respect people following rules, many explanations are very theoretical and often fail to acknowledge that, in some specific cases, especially when aiming for cost optimal with low-latency solutions, some minor tweaks are more than welcome.

"God forbid that it is violating some holy sacred principle of SQL": Adopting a more open-minded and pragmatic approach before reciting the rules is always the way to go. Else you might end up like a candid fanatic reciting the Three Laws of Robotics before being obliterated by Skynet

I don't pretend that this solution is a breakthrough, nor that it is ideal in term of readability and database flexibility, but it can certainly give you an edge when it comes to latency.

ContentLicense: CC BY-SA 2.5

Body:
I was very reluctant to choose the path I finally decide to take because of many answers. While they add more understanding to what is SQL and its principles, I decided to become an outlaw. I was also hesitant to post my findings as for some it's more important to vent frustration to someone breaking the rules rather than understanding that there are very few universal truthes.

I have tested it extensively and, in my specific case, it was way more efficient than both using array type (generously offered by PostgreSQL) or querying another table.

Here is my answer:
I have successfully implemented a list into a single field in PostgreSQL, by making use of the fixed length of each item of the list. Let say each item is a color as an ARGB hex value, it means 8 char. So you can create your array of max 10 items by multiplying by the length of each item:

ALTER product ADD color varchar(80)

In case your list items length differ you can always fill the padding with \0

NB: Obviously this is not necessarily the best approach for hex number since a list of integers would consume less storage but this is just for the purpose of illustrating this idea of array by making use of a fixed length allocated to each item.

The reason why:
1/ Very convenient: retrieve item i at substring i*n, (i +1)*n.
2/ No overhead of cross tables queries.
3/ More efficient and cost-saving on the server side. The list is like a mini blob that the client will have to split.

While I respect people following rules, many explanations are very theoretical and often fail to acknowledge that, in some specific cases, especially when aiming for cost optimal with low-latency solutions, some minor tweaks are more than welcome.

"God forbid that it is violating some holy sacred principle of SQL": Adopting a more open-minded and pragmatic approach before reciting the rules is always the way to go. Else you might end up like a candid fanatic reciting the Three Laws of Robotics before being obliterated by Skynet

I don't pretend that this solution is a breakthrough, nor that it is ideal in term of readability and database flexibility, but it can certainly give you an edge when it comes to latency.


问:
How can we change aws instances region from US East (N. Virginia) us-east-1 to Asia Pacific (Mumbai) ap-south-1?
I deployed all my app on an Amazon EC2 instance in US East (N.Virginia). Now I want to move it to Asia Pacific (Mumbai) ap-south-1 region.

I don't want to change my IP (which one I got from US East (N.Virginia)). And I don't want to lose any activity from the EC2 Instance.

Even I tried Move an EC2 Instance to Another Subnet, Availability Zone, or VPC, but did not get anything.

How can we change this?

答:
Take the AMI of the existing machine.

Copy the AMI to the new region.

Launch new machine from the AMI.

NOTE: You can't keep the existing public IP because AWS has different set of IP's for different regions. To overcome this create a public domain in Route53 and create a A record and change the value of A record to new public IP, use your DNS name instead of public IP everywhere.