问:
React Bootstrap Layout in Navbar
is there anyway to configure layout inside nav / navbar ?

i want to divide a 3 cols with the same size

what i expected should be look like this

Here's my code

<Navbar fixed="bottom" bg="light" variant="light">
  <Container>
   <Row>

      <Col sm>
        Browse Communities
      </Col>
      <Col sm >
        Tasks
      </Col>
      <Col sm>
        Profile
      </Col>

   </Row>
  </Container>
</Navbar>
```

答:
The columns align to a 12-column grid system (uses flexbox), so if you want 3 columns to span the entire grid then each needs to "occupy" 4 columns.

React-Bootstrap Col

```<code><Navbar fixed="bottom" bg="light" variant="light">
  <Container>
   <Row>
    <Nav>
      <Col sm={4}>
        <Nav.Link href="/communities">Browse Communities</Nav.Link>
      </Col>
      <Col sm={4}>
        <Nav.Link href="/tasks">Tasks</Nav.Link>
      </Col>
      <Col sm={4}>
        <Nav.Link href="/profile">Profile</Nav.Link>
      </Col>
    </Nav>
   </Row>
  </Container>
</Navbar>
</code>```

Title: React Bootstrap Layout in Navbar

Body:
The columns align to a 12-column grid system (uses flexbox), so if you want 3 columns to span the entire grid then each needs to "occupy" 4 columns.

React-Bootstrap Col

<Navbar fixed="bottom" bg="light" variant="light">
  <Container>
   <Row>
    <Nav>
      <Col sm={4}>
        <Nav.Link href="/communities">Browse Communities</Nav.Link>
      </Col>
      <Col sm={4}>
        <Nav.Link href="/tasks">Tasks</Nav.Link>
      </Col>
      <Col sm={4}>
        <Nav.Link href="/profile">Profile</Nav.Link>
      </Col>
    </Nav>
   </Row>
  </Container>
</Navbar>


来源: stackexchange

问:
Microsoft Excel - Combining Tables into one "Consolidated" Table
I have 6 sheets in a workbook. Each sheet has an identical table for sections within my organization to track their personnel.

I'd like to have a consolidated sheet that serves as a master sheet that can be refreshed as the section leaders update their rosters. Is that possible?

I've looked into creating relationships, but Pivot Tables don't merge the tables, they just display them all. I'd like one table that refreshes - linked to the section's tables so that when a row is added or deleted, then once refreshed the consolidated sheet/table shows the update. For example:

```<code>Sheet 1:
Last Name Column:
Hall

Sheet 2:
Last Name Column:
Smith

Sheet 3:
Last Name Column:
Jacobs
</code>```

Combined Sheet:

```<code>Last Name Column:
Hall
Smith
Jacobs
</code>```

I need to replicate the entire table though, not just one column. Your help is much appreciated, thank you!

-Dustin

答: You can use "Get and Transform" aka Power Query to solve the the problem. It's made for combining data :). Search for "EXCEL merge tables Power Query"</p>

ContentLicense: CC BY-SA 4.0

Body:
I have 6 sheets in a workbook. Each sheet has an identical table for sections within my organization to track their personnel.

I'd like to have a consolidated sheet that serves as a master sheet that can be refreshed as the section leaders update their rosters. Is that possible?

I've looked into creating relationships, but Pivot Tables don't merge the tables, they just display them all. I'd like one table that refreshes - linked to the section's tables so that when a row is added or deleted, then once refreshed the consolidated sheet/table shows the update. For example:

Sheet 1:
Last Name Column:
Hall

Sheet 2:
Last Name Column:
Smith

Sheet 3:
Last Name Column:
Jacobs

Combined Sheet:

Last Name Column:
Hall
Smith
Jacobs

I need to replicate the entire table though, not just one column. Your help is much appreciated, thank you!

-Dustin


问:
Authenticate to Google Talk (XMPP, Smack) using an authToken
The app I'm writing is connecting to a XMPP server, and if the user chooses, I want to give them the option to connect to their google chat account, without having to enter the credentials...

To do this, I'd get the permission to use the google account, get the token and authenticate to google talk (XMPP server, using Smack) using the token..

The problem is.. how do I do that? I mean, how do I authenticate to the GTalk server if I know the login and the token?

Any ideas, insights? :)

If not, maybe anyone knows where could I find someone that knows? (Google contacts, anyone? :P )

答:
You're looking for documentation on the X-GOOGLE-TOKEN SASL mechanism.  This should be the beginning.  Use service=mail:

```<code>https://www.google.com/accounts/ClientLogin?
    accountType=GOOGLE&
    Email=YOURUSERNAME@gmail.com&
    Passwd=YOURPASSWORD&
    service=mail
</code>```

Which will return 200 OK and three values:

```<code>SID=<long string>
LSID=<long string>
Auth=<long string>
</code>```

Parse out the Auth string, then construct a string with this form:

```<code>jidAndToken ="\0" + UTF8(YOURUSERNAME@gmail.com) + "\0" + Auth
</code>```

(where "\0" is intended to be a single octet with value zero).  Use this in the initial SASL auth:

```<code><auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
      mechanism='X-GOOGLE-TOKEN'>Base64(jidAndToken)</auth>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You're looking for documentation on the X-GOOGLE-TOKEN SASL mechanism.  This should be the beginning.  Use service=mail:

https://www.google.com/accounts/ClientLogin?
    accountType=GOOGLE&
    Email=YOURUSERNAME@gmail.com&
    Passwd=YOURPASSWORD&
    service=mail

Which will return 200 OK and three values:

SID=<long string>
LSID=<long string>
Auth=<long string>

Parse out the Auth string, then construct a string with this form:

jidAndToken ="\0" + UTF8(YOURUSERNAME@gmail.com) + "\0" + Auth

(where "\0" is intended to be a single octet with value zero).  Use this in the initial SASL auth:

<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
      mechanism='X-GOOGLE-TOKEN'>Base64(jidAndToken)</auth>


问:
Cannot see PiHole clients on Docker Swarm
Dears

I am running PiHole on Docker Swarm but I only see 2 clients: 10.0.0.3 and localhost.
If I understood correctly from various discussion over the web, I should be able to see all the clients in PiHole if I expose the DNS ports with Host mode (pihole is forced to run on a single swarm node) in this way:

```<code> ports:
      - published: 53
        target: 53
        protocol: tcp
        mode: host
      - published: 53
        target: 53
        protocol: udp
        mode: host
      - published: 67
        target: 67
        protocol: udp
        mode: ingress
      - published: 8053
        target: 80
        protocol: tcp
        mode: ingress
</code>```

Unfortunately, if I expose ports in this way, the dns service does not work anymore: I can see the port exposed on the container:

```<code>pi@raspy3:~ $ docker port 3be0321961a6
53/tcp -> 0.0.0.0:53
53/udp -> 0.0.0.0:53
</code>```

but i cannot see them with NETSTAT:

```<code>pi@raspy3:~ $ netstat -atu | grep LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp6       0      0 [::]:8053               [::]:*                  LISTEN
tcp6       0      0 [::]:domain             [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
tcp6       0      0 [::]:https              [::]:*                  LISTEN
tcp6       0      0 [::]:8000               [::]:*                  LISTEN
tcp6       0      0 [::]:9000               [::]:*                  LISTEN
tcp6       0      0 [::]:2377               [::]:*                  LISTEN
tcp6       0      0 [::]:7946               [::]:*                  LISTEN
tcp6       0      0 [::]:http               [::]:*                  LISTEN
</code>```

and nslookup does not work:

```<code>pi@raspy4:~ $ nslookup google.com 192.168.32.2
;; connection timed out; no servers could be reached
</code>```

Could you help me understanding what I am loosing, please?

Thanks :)

答:
Solved changing the Interface Listening Behaviour to Listen on all interfaces, permit all origins.

Obviously be sure to follow all the security points from the PiHole's team ;)

Body:
Dears

I am running PiHole on Docker Swarm but I only see 2 clients: 10.0.0.3 and localhost.
If I understood correctly from various discussion over the web, I should be able to see all the clients in PiHole if I expose the DNS ports with Host mode (pihole is forced to run on a single swarm node) in this way:

 ports:
      - published: 53
        target: 53
        protocol: tcp
        mode: host
      - published: 53
        target: 53
        protocol: udp
        mode: host
      - published: 67
        target: 67
        protocol: udp
        mode: ingress
      - published: 8053
        target: 80
        protocol: tcp
        mode: ingress

Unfortunately, if I expose ports in this way, the dns service does not work anymore: I can see the port exposed on the container:

pi@raspy3:~ $ docker port 3be0321961a6
53/tcp -> 0.0.0.0:53
53/udp -> 0.0.0.0:53

but i cannot see them with NETSTAT:

pi@raspy3:~ $ netstat -atu | grep LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp6       0      0 [::]:8053               [::]:*                  LISTEN
tcp6       0      0 [::]:domain             [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN
tcp6       0      0 [::]:https              [::]:*                  LISTEN
tcp6       0      0 [::]:8000               [::]:*                  LISTEN
tcp6       0      0 [::]:9000               [::]:*                  LISTEN
tcp6       0      0 [::]:2377               [::]:*                  LISTEN
tcp6       0      0 [::]:7946               [::]:*                  LISTEN
tcp6       0      0 [::]:http               [::]:*                  LISTEN

and nslookup does not work:

pi@raspy4:~ $ nslookup google.com 192.168.32.2
;; connection timed out; no servers could be reached

Could you help me understanding what I am loosing, please?

Thanks :)


问:
Angular 7: Enabel and Disable buttons according to number to form fields filled
I very new to angular 7 and I came up with a situation where I have two buttons :

submit

Check

I have to enable check button when 3 form fields are filled i.e

```<code>semester, branch and subject
</code>```

on the other hand I want to enable submit button when all the 4 fields are filled i.e

```<code>semester, branch and subject, image
</code>```

I am using FromValidation and can successfully enable the submit button when 4 fields are filled, now the problem is how to enable the check button when 3 form fields are filled

component.html

```<code><app-teacher-header></app-teacher-header>
<div class="container">
  <div class="row">
    <div class="col-sm-12" *ngIf="!checkAssignment">
        <form>
            <div class="form-group">
                <label for="exampleInputEmail1">Name</label>
                <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                [(ngModel)]="assignment.name" name="name" [value]="assignment.name" disabled>
              </div>

              <!-----------------SEMESTER  ----------------------->
              <div class="form-group" #userform="ngForm" [formGroup]="assignmentUploadValidation">
                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.semester" name="semester"
                      formControlName="semester">
                        <mat-option *ngFor="let semester of semesters" [value]="semester.semester">
                            {{semester.semester}}
                        </mat-option>
                      </mat-select>
                      <div *ngIf="(validations.semester.invalid && validations.semester.touched) || validations.semester.dirty">
                        <small *ngIf="validations.semester.errors?.required" class="text-danger">Subject is required</small>
                      </div>
                    </mat-form-field>
              </div>
              <!----------------- /SEMESTER  ----------------------->

              <!-----------------BRANCH  ----------------------->

            <div class="form-group" #userform="ngForm" [formGroup]="assignmentUploadValidation">
              <mat-form-field>
                <mat-label>Select Branch</mat-label>
                <mat-select [(ngModel)]="assignment.branch"  [(ngModel)]="teacher.branch" name="branch" formControlName="branch"
                (openedChange)="branchChanges($event)">
                  <mat-option *ngFor="let branch of branchs" [value]="branch.branch">
                    {{branch.branch}}
                  </mat-option>
                </mat-select>
                <div *ngIf="(validations.branch.invalid && validations.branch.touched) || validations.branch.dirty">
                  <small *ngIf="validations.branch.errors?.required" class="text-danger">Branch is required</small>
                </div>
              </mat-form-field>
            </div>
            <!-----------------/BRANCH  ----------------------->

              <div class="form-group" #userform="ngForm" [formGroup]="assignmentUploadValidation">
                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.subject" [(ngModel)]="teacher.subject" name="subject"
                      formControlName="subject">
                        <mat-option *ngFor="let subject of subjects" [value]="subject.subject">
                            {{subject.subject}}
                        </mat-option>
                      </mat-select>
                      <div *ngIf="(validations.subject.invalid && validations.subject.touched) || validations.subject.dirty">
                        <small *ngIf="validations.subject.errors?.required" class="text-danger">Branch is required</small>
                      </div>
                    </mat-form-field>
              </div>

              <div class="form-group"  #userform="ngForm" [formGroup]="assignmentUploadValidation">
                <input type="file" name="image" (change)="onFileSelect($event)" formControlName="image">
                <div *ngIf="(validations.image.invalid && validations.image.touched) || validations.image.dirty">
                  <small *ngIf="validations.image.errors?.required" class="text-danger">Branch is required</small>
                </div>
              </div>

              <button type="submit" class="btn btn-primary" (click)="onUpload()" [disabled]="userform.invalid">Submit</button>
    </form>
    </div>
    <div class="col-sm-12">
        <app-check-assignment *ngIf="checkAssignment"
        [receivedFromTeacherAssignment]="recivedAssignment" [justMsg]="parentMsg"></app-check-assignment>
        <div>
          <button class="btn btn-primary" (click)="onCheckAssignment()">check</button>
        </div>
    </div>

  </div>
</div>
</code>```

component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Teacher } from 'src/app/shared/teacher.model';
import { TeachersService } from '../teachers.service';
import { SharedService } from 'src/app/shared/shared.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

export interface Assignment {
  name: string,
  semester : number,
  branch: string,
  subject: string,
  image: string
}

@Component({
  selector: 'app-teacher-assignment',
  templateUrl: './teacher-assignment.component.html',
  styleUrls: ['./teacher-assignment.component.css']
})
export class TeacherAssignmentComponent implements OnInit {
  private teacher = Teacher
  private recivedAssignment : {name: string, assignment: string}
  semesters = []
  branchs = [];

  subjects = [];

  checkAssignment = false;
  parentMsg : string = '';
  assignment : Assignment = {
    name: "",
    semester: null,
    branch: "",
    subject: "",
    image: ""
  }

  assignmentUploadValidation = new FormGroup({

     semester: new FormControl('',
     [

       Validators.required
     ]),
     branch: new FormControl('',[
       Validators.required
     ]),
     subject: new FormControl('', [
       Validators.required
     ]),
     image: new FormControl('', [
       Validators.required
     ])
   })

  constructor(private teacherServ: TeachersService, private sharedServ: SharedService) {}

  ngOnInit() {
  }

  get validations() {
    return this.assignmentUploadValidation.controls;
  }

  onUpload() {
    const fd = new FormData();
    for( var key in this.assignment) {
      fd.append(key , this.assignment[key])
    }

    if(fd) {
      this.teacherServ.uploadAssignment(fd)
      .subscribe(
        res => console.log(res),
        err => console.log(err)
      )
    }

    console.log("assignment: ",this.assignment)
  }

  onCheckAssignment() {
    this.checkAssignment=!this.checkAssignment
    console.log("THis is assignment", this.assignment)
    this.parentMsg = "demos"
    this.teacherServ.checkAssignment(this.assignment)
    .subscribe(
      res => {
        this.recivedAssignment = res.result[0]
        console.log(this.recivedAssignment)
      },
      err => console.log(err)
    )
  }

}
</code>```

答:
Try</p>

```<code><button class="btn btn-primary" (click)="onCheckAssignment()" [disabled]="assignmentUploadValidation.controls.semester.invalid || assignmentUploadValidation.controls.branch.invalid || assignmentUploadValidation.controls.subject.invalid">check</button>
</code>```

Body:
I very new to angular 7 and I came up with a situation where I have two buttons :

submit

Check

I have to enable check button when 3 form fields are filled i.e

semester, branch and subject

on the other hand I want to enable submit button when all the 4 fields are filled i.e

semester, branch and subject, image

I am using FromValidation and can successfully enable the submit button when 4 fields are filled, now the problem is how to enable the check button when 3 form fields are filled

component.html

<app-teacher-header></app-teacher-header>

        <form>

                Name
                <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                [(ngModel)]="assignment.name" name="name" [value]="assignment.name" disabled>

                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.semester" name="semester"
                      formControlName="semester">
                        <mat-option *ngFor="let semester of semesters" [value]="semester.semester">
                            {{semester.semester}}
                        </mat-option>
                      </mat-select>

                        Subject is required

                    </mat-form-field>

              <mat-form-field>
                <mat-label>Select Branch</mat-label>
                <mat-select [(ngModel)]="assignment.branch"  [(ngModel)]="teacher.branch" name="branch" formControlName="branch"
                (openedChange)="branchChanges($event)">
                  <mat-option *ngFor="let branch of branchs" [value]="branch.branch">
                    {{branch.branch}}
                  </mat-option>
                </mat-select>

                  Branch is required

              </mat-form-field>

                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.subject" [(ngModel)]="teacher.subject" name="subject"
                      formControlName="subject">
                        <mat-option *ngFor="let subject of subjects" [value]="subject.subject">
                            {{subject.subject}}
                        </mat-option>
                      </mat-select>

                        Branch is required

                    </mat-form-field>

                <input type="file" name="image" (change)="onFileSelect($event)" formControlName="image">

                  Branch is required

              <button type="submit" class="btn btn-primary" (click)="onUpload()" [disabled]="userform.invalid">Submit</button>
    </form>

        <app-check-assignment *ngIf="checkAssignment"
        [receivedFromTeacherAssignment]="recivedAssignment" [justMsg]="parentMsg"></app-check-assignment>

          <button class="btn btn-primary" (click)="onCheckAssignment()">check</button>

component.ts

import { Component, OnInit } from '@angular/core';
import { Teacher } from 'src/app/shared/teacher.model';
import { TeachersService } from '../teachers.service';
import { SharedService } from 'src/app/shared/shared.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

export interface Assignment {
  name: string,
  semester : number,
  branch: string,
  subject: string,
  image: string
}

@Component({
  selector: 'app-teacher-assignment',
  templateUrl: './teacher-assignment.component.html',
  styleUrls: ['./teacher-assignment.component.css']
})
export class TeacherAssignmentComponent implements OnInit {
  private teacher = Teacher
  private recivedAssignment : {name: string, assignment: string}
  semesters = []
  branchs = [];

  subjects = [];

  checkAssignment = false;
  parentMsg : string = '';
  assignment : Assignment = {
    name: "",
    semester: null,
    branch: "",
    subject: "",
    image: ""
  }

  assignmentUploadValidation = new FormGroup({

     semester: new FormControl('',
     [

       Validators.required
     ]),
     branch: new FormControl('',[
       Validators.required
     ]),
     subject: new FormControl('', [
       Validators.required
     ]),
     image: new FormControl('', [
       Validators.required
     ])
   })

  constructor(private teacherServ: TeachersService, private sharedServ: SharedService) {}

  ngOnInit() {
  }

  get validations() {
    return this.assignmentUploadValidation.controls;
  }

  onUpload() {
    const fd = new FormData();
    for( var key in this.assignment) {
      fd.append(key , this.assignment[key])
    }

    if(fd) {
      this.teacherServ.uploadAssignment(fd)
      .subscribe(
        res => console.log(res),
        err => console.log(err)
      )
    }

    console.log("assignment: ",this.assignment)
  }

  onCheckAssignment() {
    this.checkAssignment=!this.checkAssignment
    console.log("THis is assignment", this.assignment)
    this.parentMsg = "demos"
    this.teacherServ.checkAssignment(this.assignment)
    .subscribe(
      res => {
        this.recivedAssignment = res.result[0]
        console.log(this.recivedAssignment)
      },
      err => console.log(err)
    )
  }

}

Body:
Try

<button class="btn btn-primary" (click)="onCheckAssignment()" [disabled]="assignmentUploadValidation.controls.semester.invalid || assignmentUploadValidation.controls.branch.invalid || assignmentUploadValidation.controls.subject.invalid">check</button>


问:
Does it make sense to use Vuejs and Reactjs on the same project
So my question is pretty self explanatory. Does it make sense to use Vue.js and React.js together on a same project ?</p>

答:
You can use the two together but you will have to carefully consider the architecture. You might have to consider something like the Microfrontend architecture but remember this comes at the cost of a lot of complexity and is not suited for all use cases.

Good intro to Micro Frontends


问:
How to convert string into binary
I want to convert a string into binary codes, I try to use

```<code>test_str = "a"

res = ''.join(format(ord(i), 'b') for i in test_str)

</code>```

and I get 1100001, but I don't need the first two bits '11' which is used to distinguish capital and lower, I only need '00001', how can I do this?

答:
You may use a slice to remove the first two chars [2:] and apply this for every char of the string

```<code>def binary(value):
    return ''.join(format(ord(i), 'b')[2:] for i in value)

print(binary('a'))  # 00001
print(binary('b'))  # 00010
print(binary('ab')) # 0000100010
</code>```

Title: How to convert string into binary

Body:
I want to convert a string into binary codes, I try to use

test_str = "a"

res = ''.join(format(ord(i), 'b') for i in test_str)

and I get 1100001, but I don't need the first two bits '11' which is used to distinguish capital and lower, I only need '00001', how can I do this?

Body:
You may use a slice to remove the first two chars [2:] and apply this for every char of the string

def binary(value):
    return ''.join(format(ord(i), 'b')[2:] for i in value)

print(binary('a'))  # 00001
print(binary('b'))  # 00010
print(binary('ab')) # 0000100010


问:
Added alert for when user clicks back button but now I want to remove it when submitting the form
I have a very long survey and I want to prevent the user from clicking the back button and losing all of their data. So far I have an alert that tells them they will lose all the data but when they submit the form to process the page it will pop up with the alert. Is there a way I can disable the alert only when they press the submit button? This is the method I am using to create the alert:</p>

```<code>window.onbeforeunload = function() { return "Your work will be lost."; };
</code>```

答:
After trying so many complex way, I get this solution. </p>

```<code>    window.onbeforeunload = function () {
        return 'Are you sure? Your work will be lost.';
    };

    $(document).on("submit", "form", function () {
        window.onbeforeunload = null;
    });
</code>```

Body:
I have a very long survey and I want to prevent the user from clicking the back button and losing all of their data. So far I have an alert that tells them they will lose all the data but when they submit the form to process the page it will pop up with the alert. Is there a way I can disable the alert only when they press the submit button? This is the method I am using to create the alert:

window.onbeforeunload = function() { return "Your work will be lost."; };

Body:
After trying so many complex way, I get this solution.

    window.onbeforeunload = function () {
        return 'Are you sure? Your work will be lost.';
    };

    $(document).on("submit", "form", function () {
        window.onbeforeunload = null;
    });


问:
This program is accepting only 5 inputs while i am giving n=8

Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.

code written by me:

```<code>#include <bits/stdc++.h>
#include <iostream>

using namespace std;

int main()
{
    int n;
    int a[n];
    float sum1=0,sum2=0,sum3=0;
    cin>>n;

    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(int i=0;i<n;i++)
    {
        if(a[i]<0)
        {
           sum1++ ;
        }
        else if(a[i]>0)
        {
            sum2++ ;
        }
        else
        {
            sum3++ ;
        }
    }

     cout<<(sum2/n)<<endl;
     cout<<(sum1/n)<<endl;
     cout<<(sum3/n)<<endl;
}
</code>```

答:
This program is accepting only 5 inputs while i am giving n=8, kindly help me out to find the error

The int n; (in the function main()) declares a variable with automatic storage class and it has garbage value (unless you initialize it int n = 100;). So, it's undefined what value variable n will hold and since, you are using it to declare an array of int with size n, the array may have random size. So, running such a program may give you some undefined behavior that may vary from machine to machine or may be you get different behavior if you run the same program in the same machine multiple times.

The compiler is free to do anything from crashing to summoning demons through your nasal passages.

The right way to do this is:

```<code>#define MAX_ARRAY_SIZE    100

int n = 0;
int arr[MAX_ARRAY_SIZE];
</code>```

or

```<code>int n = 0;
std::cin >> n;
int arr[n];
</code>```

or using std::vector

```<code>#include <iostream>
#include <vector>
#include <algorithm>

int main(void)
{
    int n;
    std::vector<int> arr;
    std::cin >> n;

    for(int i = 0; i < n; i++)
    {
        int e;
        std::cin >> e;
        arr.push_back(e);
    }
    int sum1 = std::count_if(std::begin(arr), std::end(arr), [] (int num) { return num < 0; });
    int sum2 = std::count_if(std::begin(arr), std::end(arr), [] (int num) { return num > 0; });
    int sum3 = n - (sum1 + sum2);

    std::cout << (float(sum2) / n) << std::endl;
    std::cout << (float(sum1) / n) << std::endl;
    std::cout << (float(sum3) / n) << std::endl;

    return 0;
}
</code>```

Body:
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.

code written by me:

#include <bits/stdc++.h>
#include <iostream>

using namespace std;

int main()
{
    int n;
    int a[n];
    float sum1=0,sum2=0,sum3=0;
    cin>>n;

    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(int i=0;i<n;i++)
    {
        if(a[i]<0)
        {
           sum1++ ;
        }
        else if(a[i]>0)
        {
            sum2++ ;
        }
        else
        {
            sum3++ ;
        }
    }

     cout<<(sum2/n)<<endl;
     cout<<(sum1/n)<<endl;
     cout<<(sum3/n)<<endl;
}

Body:
This program is accepting only 5 inputs while i am giving n=8, kindly help me out to find the error

The int n; (in the function main()) declares a variable with automatic storage class and it has garbage value (unless you initialize it int n = 100;). So, it's undefined what value variable n will hold and since, you are using it to declare an array of int with size n, the array may have random size. So, running such a program may give you some undefined behavior that may vary from machine to machine or may be you get different behavior if you run the same program in the same machine multiple times.

The compiler is free to do anything from crashing to summoning demons through your nasal passages.

The right way to do this is:

#define MAX_ARRAY_SIZE    100

int n = 0;
int arr[MAX_ARRAY_SIZE];

or

int n = 0;
std::cin >> n;
int arr[n];

or using std::vector

#include <iostream>
#include <vector>
#include <algorithm>

int main(void)
{
    int n;
    std::vector<int> arr;
    std::cin >> n;

    for(int i = 0; i < n; i++)
    {
        int e;
        std::cin >> e;
        arr.push_back(e);
    }
    int sum1 = std::count_if(std::begin(arr), std::end(arr), [] (int num) { return num < 0; });
    int sum2 = std::count_if(std::begin(arr), std::end(arr), [] (int num) { return num > 0; });
    int sum3 = n - (sum1 + sum2);

    std::cout << (float(sum2) / n) << std::endl;
    std::cout << (float(sum1) / n) << std::endl;
    std::cout << (float(sum3) / n) << std::endl;

    return 0;
}


问:
How to test a library against different Python *patch* versions?
I'm writing a library and want to test against different Python patch versions, like 3.7.1, 3.7.2, etc

I've been using tox for a long time, however, according to this answer, it doesn't really support this kind of usage.

Any suggestions?

答:
For a one of check against 3.8.1 (assuming your python3.8 points to 3.8.2) you can use the discover flag

tox --discover /path/to/python3.8.1 -e py38
```

<p>If you want to define an environment that always uses 3.8.1 you can do that by defining a new tox environment and setting basepython as <code>python3.8.1</code>.</p>

```[testenv:py381]
basepython = python3.8.1

[testenv:py382]
basepython = python3.8.2
```

Body:
For a one of check against 3.8.1 (assuming your python3.8 points to 3.8.2) you can use the discover flag

tox --discover /path/to/python3.8.1 -e py38

If you want to define an environment that always uses 3.8.1 you can do that by defining a new tox environment and setting basepython as python3.8.1.

[testenv:py381]
basepython = python3.8.1

[testenv:py382]
basepython = python3.8.2


问:
Flutter: How to fit the web view size to screen?
I am new in flutter,

tried to use web view in flutter, but the the size of the web view is bigger than the screen.

I want to fit the web page size to the phone screen size.

How I can do that?

Here is what I get now:

I want to see:

Here is my code:

import 'package:flutter/material.dart';

import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

```<code>class CoursesInformation extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<CoursesInformation> {
  TextEditingController controller = TextEditingController();
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var urlString = "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx";

  launchUrl() {
    setState(() {
      urlString = controller.text;
     flutterWebviewPlugin.reloadUrl(urlString);
       flutterWebviewPlugin.launch(urlString,
              rect: new Rect.fromLTWH(
                  0.0,
                  0.0,
                  MediaQuery.of(context).size.width,
                  300.0));
    });
  }

  @override
  void initState() {
    super.initState();

    flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
      print(wvs.type);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
    textDirection: TextDirection.rtl,
    child: WebviewScaffold(
      appBar: AppBar(
        title: Text('מידע על קורסים'),
        centerTitle: true
      ),
      url: urlString,
      withZoom: true,
      scrollBar: true,
      withJavascript: true,
      useWideViewPort: true,

      withLocalStorage: true,
        ));
  }
}
</code>```

答:
Remove

```<code>useWideViewPort: true,
</code>```

Read more documentation at https://pub.dev/documentation/flutter_webview_plugin/latest/

It now looks like

Body:
I am new in flutter,

tried to use web view in flutter, but the the size of the web view is bigger than the screen.

I want to fit the web page size to the phone screen size.

How I can do that?

Here is what I get now:

I want to see:

Here is my code:

import 'package:flutter/material.dart';

import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class CoursesInformation extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<CoursesInformation> {
  TextEditingController controller = TextEditingController();
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var urlString = "https://shoham.biu.ac.il/BiuCoursesViewer/MainPage.aspx";

  launchUrl() {
    setState(() {
      urlString = controller.text;
     flutterWebviewPlugin.reloadUrl(urlString);
       flutterWebviewPlugin.launch(urlString,
              rect: new Rect.fromLTWH(
                  0.0,
                  0.0,
                  MediaQuery.of(context).size.width,
                  300.0));
    });
  }

  @override
  void initState() {
    super.initState();

    flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {
      print(wvs.type);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
    textDirection: TextDirection.rtl,
    child: WebviewScaffold(
      appBar: AppBar(
        title: Text('מידע על קורסים'),
        centerTitle: true
      ),
      url: urlString,
      withZoom: true,
      scrollBar: true,
      withJavascript: true,
      useWideViewPort: true,

      withLocalStorage: true,
        ));
  }
}

Body:
Remove

useWideViewPort: true,

Read more documentation at https://pub.dev/documentation/flutter_webview_plugin/latest/

It now looks like


问:
How to resolve conflict between users decision and IoT system?
In an Internet project, we have to use machine learning to resolve the conflict between the user's decisions and the system. In this project we use TICKstack (Telegraf, Influxdb, Chronograf, Kapacitor). To better understand the subject, consider the following two scenarios.
Is there a plugin in Kapacitor to do this?

Conflict scenarios

答:
I would recommend:

store user actions in one time series

store system predictions in another series

compute the actuation signal based on those two, as a new series

The latter can be done with scripts in Kapacitor. Presumably user input should always override the "smart" system. You may need to consider user input for a boolean variable as tri-state: Unknown (don't care) | Explicitly On | Explicitly Off


问:
Progress Bar while download file over http with Requests
I need to download a sizable (~200MB) file. I figured out how to download and save the file with here. It would be nice to have a progress bar to know how much has been downloaded. I found ProgressBar but I'm not sure how to incorperate the two together.

Here's the code I tried, but it didn't work.

```<code>bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
with closing(download_file()) as r:
    for i in range(20):
        bar.update(i)
</code>```

答:
There is an answer with tqdm.

```<code>def download(url, fname):
    resp = requests.get(url, stream=True)
    total = int(resp.headers.get('content-length', 0))
    with open(fname, 'wb') as file, tqdm(
            desc=fname,
            total=total,
            unit='iB',
            unit_scale=True,
            unit_divisor=1024,
    ) as bar:
        for data in resp.iter_content(chunk_size=1024):
            size = file.write(data)
            bar.update(size)
</code>```

Gits: https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51

Body:
I need to download a sizable (~200MB) file. I figured out how to download and save the file with here. It would be nice to have a progress bar to know how much has been downloaded. I found ProgressBar but I'm not sure how to incorperate the two together.

Here's the code I tried, but it didn't work.

bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
with closing(download_file()) as r:
    for i in range(20):
        bar.update(i)

Body:
There is an answer with tqdm.

def download(url, fname):
    resp = requests.get(url, stream=True)
    total = int(resp.headers.get('content-length', 0))
    with open(fname, 'wb') as file, tqdm(
            desc=fname,
            total=total,
            unit='iB',
            unit_scale=True,
            unit_divisor=1024,
    ) as bar:
        for data in resp.iter_content(chunk_size=1024):
            size = file.write(data)
            bar.update(size)

Gits: https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51


问:
How most iOS developers adapt different screen sizes?
I wonder how other ios developers adapt application for supporting all different screen sizes. I personally used in every single view UIDevice API and Outlets for constraint.
But as time goes by, I became doubtful. Is it the way it is supposed to be?
What is the most efficient way to adjust my application for supporting all different screen sizes?</p>

```<code>if UIDevice.current.userInterfaceIdiom == .pad {
  constraint1.constant = value
  constraint2.constant = value
  constraint3.constant = value
}
</code>```

答:
Your UI already adapts to different screen sizes if you're using auto layout constraints. I think your question is more about how to have different layouts for different screen sizes.

The problem with your approach is that your app may be used as multitasking in split view which means that your if statement is already predicting it wrong. Why? You see your app can be used in one of the layouts shown below.

But your are checking if your device is iPad which doesn't tell you much about what kind of layout your app is in.

Size classes here to rescue

Size classes are traits that are automatically assigned to content areas based on their size. The system defines two size classes, regular (denotes expansive space) and compact (denotes constrained space), which describe the height and width of a view.

More sophisticated solution will be to use size classes which gives you more options on how to arrange your views. So now you should go from this

if UIDevice.current.userInterfaceIdiom == .pad {
  constraint1.constant = value
  constraint2.constant = value
  constraint3.constant = value
}
```

<p>to this</p>

<pre class="lang-swift prettyprint-override"><code>if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
  // Do something
} else {
  // Do something else
}
</code>```

I hope I'd give you a general idea of how to start using size classes now is up to you to do further research. You can start in apple documentation with UITraitCollection class.

Resource: https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/

Body:
I wonder how other ios developers adapt application for supporting all different screen sizes. I personally used in every single view UIDevice API and Outlets for constraint.
But as time goes by, I became doubtful. Is it the way it is supposed to be?
What is the most efficient way to adjust my application for supporting all different screen sizes?

if UIDevice.current.userInterfaceIdiom == .pad {
  constraint1.constant = value
  constraint2.constant = value
  constraint3.constant = value
}

Body:
Your UI already adapts to different screen sizes if you're using auto layout constraints. I think your question is more about how to have different layouts for different screen sizes.

The problem with your approach is that your app may be used as multitasking in split view which means that your if statement is already predicting it wrong. Why? You see your app can be used in one of the layouts shown below.

But your are checking if your device is iPad which doesn't tell you much about what kind of layout your app is in.

Size classes here to rescue

Size classes are traits that are automatically assigned to content areas based on their size. The system defines two size classes, regular (denotes expansive space) and compact (denotes constrained space), which describe the height and width of a view.

More sophisticated solution will be to use size classes which gives you more options on how to arrange your views. So now you should go from this

if UIDevice.current.userInterfaceIdiom == .pad {
  constraint1.constant = value
  constraint2.constant = value
  constraint3.constant = value
}

to this

if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
  // Do something
} else {
  // Do something else
}

I hope I'd give you a general idea of how to start using size classes now is up to you to do further research. You can start in apple documentation with UITraitCollection class.

Resource: https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/


问:
Zend bootstrap, including javascript files for certain pages only
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

```<code>->appendFile('http://myurl.com/js/formscript.js');
</code>```

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

```<code>$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;
</code>```

and this would be in my bootstrap

```<code>if ($view->formscript)
</code>```

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

答:
To include javascript files in a particular pages alone, add the following code in those pages(I mean view scripts - *.phtml).

```<code><?php

 $this->headScript()->appendFile('http://myurl.com/js/formscript.js');

?>
</code>```

Similarly, to add CSS files to a particular page, do the following.

```<code><?php
 $this->headLink()->appendStylesheet('http://myurl.com/styles.css');
?>
</code>```

Body:
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

->appendFile('http://myurl.com/js/formscript.js');

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;

and this would be in my bootstrap

if ($view->formscript)

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

Body:
To include javascript files in a particular pages alone, add the following code in those pages(I mean view scripts - *.phtml).

<?php

 $this->headScript()->appendFile('http://myurl.com/js/formscript.js');

?>

Similarly, to add CSS files to a particular page, do the following.

<?php
 $this->headLink()->appendStylesheet('http://myurl.com/styles.css');
?>


问:
How to use intersect operator in MongoDB?
```<code>(select A from 'TableB' where C = c and G = g)
intersect
(select A from 'TableB' where C = d and G = h)
</code>```

First of all, because Mysql does not provide an intersect operator, I changed the query statement written above as follows.

```<code>select A
from 'TableB'
    where C = c and G = g and A in(
        select A
        from 'TableB'
        where C = d and G = h)
</code>```

I want to use MongoDB to get the same result as above.

Is there any other way??

答:
```<code>let mongoQuery = {
    $and:[
      {C: c},
      {D: d},
      {G: g},
      {G: h}
    ]
};

const result = await TableB.find(mongoQuery, {A: 1});
</code>```

This query will return only elements from 'A' that matches C=c, D=d, G=h, G=g

Hope it helps

Body:
(select A from 'TableB' where C = c and G = g)
intersect
(select A from 'TableB' where C = d and G = h)

First of all, because Mysql does not provide an intersect operator, I changed the query statement written above as follows.

select A
from 'TableB'
    where C = c and G = g and A in(
        select A
        from 'TableB'
        where C = d and G = h)

I want to use MongoDB to get the same result as above.

Is there any other way??

Body:
let mongoQuery = {
    $and:[
      {C: c},
      {D: d},
      {G: g},
      {G: h}
    ]
};

const result = await TableB.find(mongoQuery, {A: 1});

This query will return only elements from 'A' that matches C=c, D=d, G=h, G=g

Hope it helps


问:
Linking (two) bidirectional ports between (two) modules in VHDL
I have an FPGA which accepts an 8-bit address and data bus (one bus is used for both) from two microcontrollers.

Using a 2:1 multiplexer, my FPGA only selects one device's inputs at a time (address and data) and the selection is based on an external signal to the FPGA.

I also have a separate decoder and register module which the microcontroller reads and writes to.  How do I link the bidirectional output signal from my multiplexer to the decoder/register bidirectional input module at the higher level using the port map assignment?

Using a std_logic_vector(7..0), it will not work as I get an error "this signal is connected to multiple drivers".  I think I need to tri-state the two, but I'm not sure.  Looking at the image below, the green circle is what I'm trying to glue together.

My FPGA project

答:
You are right in thinking you need to tri-state, but this is needed at the edge of the FPGA, i.e., on the I/O pins.

You cannot have bidirectional ports inside an FPGA. So for each bidirectional pin you have three signals, incoming outgoing and a direction. If all pins always have the same direction you can use the same signal for all.

For you this means you don't need to multiplex the incoming signals as they can be split (one signal to multiple instances), but you need one for the outgoing signals (multiple instances to one signal).


问:
Clickhouse: split output on select
Performing a select on Clickhouse, on a MergeTree table that is loaded from a KafkaEngine table via a Materialized View, a simple select shows output split in groups in the clickhouse-client:

```<code>:) select * from customersVisitors;
SELECT * FROM customersVisitors

┌────────day─┬─────────createdAt───┬──────────────────_id─┬───────────mSId─┬───────xId──┬─yId─┐
│ 2018-08-17 │ 2018-08-17 11:42:04 │  8761310857292948227 │ DV-1811114459  │ 846817     │ 0   │
│ 2018-08-17 │ 2018-08-17 11:42:04 │ 11444873433837702032 │ DV-2164132903  │ 780066     │ 0   │
└────────────┴─────────────────────┴──────────────────────┴────────────────┴────────────┴─────┘
┌────────day─┬─────────createdAt───┬──────────────────_id─┬───────────────────mSId──┬────────xId─┬─yId─┐
│ 2018-08-17 │ 2018-08-17 10:25:11 │ 14403835623731794748 │ DV-07680633204819271839 │ 307597     │ 0   │
└────────────┴─────────────────────┴──────────────────────┴─────────────────────────┴────────────┴─────┘

3 rows in set. Elapsed: 0.013 sec.
</code>```

Engine is ENGINE = MergeTree(day, (mSId, xId, day), 8192)

Why does the output appear splitted in two groups?

答:
MergeTree Engine is designed for faster WRITE and READ operations.

Fater writes are achieved by inserting data in parts and then the data is merged offline into a single part for faster reads.

you can see the data partition the following directory :

```<code> ls /var/lib/clickhouse/data/database_name/table_name
</code>```

If you run the following query, you will find this that the data is now available in a single group and also a new partition is available at the above location :

```<code>optimize table MY_TABLE_NAME
</code>```

Optimize table forces merging of partition, but in usual cases, you can just leave it on Click house .

Title: Clickhouse: split output on select

Body:
Performing a select on Clickhouse, on a MergeTree table that is loaded from a KafkaEngine table via a Materialized View, a simple select shows output split in groups in the clickhouse-client:

:) select * from customersVisitors;
SELECT * FROM customersVisitors

┌────────day─┬─────────createdAt───┬──────────────────_id─┬───────────mSId─┬───────xId──┬─yId─┐
│ 2018-08-17 │ 2018-08-17 11:42:04 │  8761310857292948227 │ DV-1811114459  │ 846817     │ 0   │
│ 2018-08-17 │ 2018-08-17 11:42:04 │ 11444873433837702032 │ DV-2164132903  │ 780066     │ 0   │
└────────────┴─────────────────────┴──────────────────────┴────────────────┴────────────┴─────┘
┌────────day─┬─────────createdAt───┬──────────────────_id─┬───────────────────mSId──┬────────xId─┬─yId─┐
│ 2018-08-17 │ 2018-08-17 10:25:11 │ 14403835623731794748 │ DV-07680633204819271839 │ 307597     │ 0   │
└────────────┴─────────────────────┴──────────────────────┴─────────────────────────┴────────────┴─────┘

3 rows in set. Elapsed: 0.013 sec.

Engine is ENGINE = MergeTree(day, (mSId, xId, day), 8192)

Why does the output appear splitted in two groups?

Body:
MergeTree Engine is designed for faster WRITE and READ operations.

Fater writes are achieved by inserting data in parts and then the data is merged offline into a single part for faster reads.

you can see the data partition the following directory :

 ls /var/lib/clickhouse/data/database_name/table_name

If you run the following query, you will find this that the data is now available in a single group and also a new partition is available at the above location :

optimize table MY_TABLE_NAME

Optimize table forces merging of partition, but in usual cases, you can just leave it on Click house .


问:
Python Using RandInt to Generate 3-Digit Pattern: Syntax Error
I'm reading a beginners text on Python Programming. And I'm getting a syntax error that, seemingly, is a typo in the text. The code is:

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

```

<p>I'm getting the following error:</p>

```File "ex43.py", line 121
    code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
                                                       ^ SyntaxError: invalid syntax
```

So it seems to be trying to create a 3 digit pattern of random numbers?

答:
f strings are supported from python 3.6+

try:

```<code>code = "".join([str(randint(1,9)) for _ in range(3)])
</code>```

And you might want to use randint(0,9) to get also zeros

Body:
I'm reading a beginners text on Python Programming. And I'm getting a syntax error that, seemingly, is a typo in the text. The code is:

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

I'm getting the following error:

File "ex43.py", line 121
    code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
                                                       ^ SyntaxError: invalid syntax

So it seems to be trying to create a 3 digit pattern of random numbers?

Body:
f strings are supported from python 3.6+

try:

code = "".join([str(randint(1,9)) for _ in range(3)])

And you might want to use randint(0,9) to get also zeros


问:
Svelte Rollup [export name] is not exported by node_modules/
I am trying to import a module from hyphen like this: import { hyphenateHTMLSync } from "hyphen/fr"; in the script tag of a Svelte module but I get Error: 'hyphenateHTMLSync' is not exported by node_modules/hyphen/fr/index.js from rollup.

The module file in quesiton looks like this:

node_modules/hyphen/fr/index.js

```<code>module.exports = require("../export-contract.js")(
    require("../patterns/fr.js")
);
</code>```

node_modules/hyphen/export-contract.js

```<code>var createHyphenator = require("./hyphen.js");

module.exports = function (patterns) {
  return {
    hyphenate: createHyphenator(patterns, { async: true }),
    hyphenateHTML: createHyphenator(patterns, { async: true, html: true }),
    hyphenateHTMLSync: createHyphenator(patterns, { html: true }),
    hyphenateSync: createHyphenator(patterns),
    patterns: patterns
  };
};
</code>```

And hyphen.js contains the function to create hyphenator.

I do not know enough of Rollup, Svelte or even Node to know how to fix this.

答:
Rollup requires extra plugins (@rollup/plugin-node-resolve and @rollup/plugin-commonjs) to deal with CommonJS modules, as explained here.

A very basic rollup example config using both plugins is given here.

In your particular use case, if you still have issues using the basic config, you'll probably want to dig into the dynamicRequireTargets option of the commonjs plugin.

Body:
I am trying to import a module from hyphen like this: import { hyphenateHTMLSync } from "hyphen/fr"; in the script tag of a Svelte module but I get Error: 'hyphenateHTMLSync' is not exported by node_modules/hyphen/fr/index.js from rollup.

The module file in quesiton looks like this:

node_modules/hyphen/fr/index.js

module.exports = require("../export-contract.js")(
    require("../patterns/fr.js")
);

node_modules/hyphen/export-contract.js

var createHyphenator = require("./hyphen.js");

module.exports = function (patterns) {
  return {
    hyphenate: createHyphenator(patterns, { async: true }),
    hyphenateHTML: createHyphenator(patterns, { async: true, html: true }),
    hyphenateHTMLSync: createHyphenator(patterns, { html: true }),
    hyphenateSync: createHyphenator(patterns),
    patterns: patterns
  };
};

And hyphen.js contains the function to create hyphenator.

I do not know enough of Rollup, Svelte or even Node to know how to fix this.


问:
How to detect if new element is added in DOM?
I am trying to make a website, in which one makes a questions and there will be options for that questions.

I have a add option button, when user clicks the add option button, new option is added by this function.

```<code>function addOption(elem) {
            elem = $(elem);
            let ul = $(elem.parent().children()[1]);

            let addedElem = $(
                `<li class='ques-li'><input type='text' name='ques-option' class='ques-option' value='Option'><p class='remove-op'>X</p></li>`
            );
            addedElem.appendTo(ul);

        }

let addOp = $('.ques-add');
$('.ques-add').click(function () {
            addOption($(this));
});
</code>```

This works well with one question, but when a user adds another question.

It is by this function.

```<code>let addQuestion = $('form button');
        addQuestion.click(function () {
            let quesBox = $('div.questions-box');
            quesBox.html(quesBox.html() + `<div class='ques'>
                <input type="text" name="ques-name" class="ques-name">
                <ol class='ques-ul'>
                    <li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
                        <p class='remove-op'>X</p>
                    </li>
                    <li class='ques-li'><input type="text" name='ques-option' class='ques-option'>
                        <p class='remove-op'>X</p>
                    </li>
                </ol>
                <p class='ques-add'>Add Another</p>
            </div>`)
        });
</code>```

When i click the add Question button, it also works

but when i click the add option button on a newly created question,
it does not create a new option.

I noticed when i create a new question, it does not get the new option button.

So, i updated my code as follows :-

```<code>let addOp = $('.ques-add');
        $(document).bind('DOMNodeInserted', function(){
            addOp = $('.ques-add');
        });
        addOp.click(function () {
            addOption($(this));
        });
</code>```

It also does not work.

I have no idea why this code is not working.

Thanks in advance.

答:
Try using delegation approach that uses .on(). This will assure that the event will be attached to all the elements that are added to the document at a later time:

```<code>$('body').on('click', '.ques-add', function () {
  addOption($(this));
});
</code>```

Body:
I am trying to make a website, in which one makes a questions and there will be options for that questions.

I have a add option button, when user clicks the add option button, new option is added by this function.

function addOption(elem) {
            elem = $(elem);
            let ul = $(elem.parent().children()[1]);

            let addedElem = $(
                `<li class='ques-li'><input type='text' name='ques-option' class='ques-option' value='Option'><p class='remove-op'>X</p></li>`
            );
            addedElem.appendTo(ul);

        }

let addOp = $('.ques-add');
$('.ques-add').click(function () {
            addOption($(this));
});

This works well with one question, but when a user adds another question.

It is by this function.

let addQuestion = $('form button');
        addQuestion.click(function () {
            let quesBox = $('div.questions-box');
            quesBox.html(quesBox.html() + `

                <input type="text" name="ques-name" class="ques-name">

<input type="text" name='ques-option' class='ques-option'>

X

<input type="text" name='ques-option' class='ques-option'>

X

Add Another

`)
        });

When i click the add Question button, it also works

but when i click the add option button on a newly created question,
it does not create a new option.

I noticed when i create a new question, it does not get the new option button.

So, i updated my code as follows :-

let addOp = $('.ques-add');
        $(document).bind('DOMNodeInserted', function(){
            addOp = $('.ques-add');
        });
        addOp.click(function () {
            addOption($(this));
        });

It also does not work.

I have no idea why this code is not working.

Thanks in advance.

Body:
Try using delegation approach that uses .on(). This will assure that the event will be attached to all the elements that are added to the document at a later time:

$('body').on('click', '.ques-add', function () {
  addOption($(this));
});


问:
Sort Numeric Bands in R
I have some numeric variables which are categorised into a few bands (like 1-3, 3-5, 5-7 etc). I want to main their band order. For example, in the data frame below.

```<code>df <- data.frame(x = c("1-3", "3-5","5-9", "9-10", "10-12"))
</code>```

When I run any data manipulation operation (like group_by, count) in this column, it returns this output.

Current Output

```<code>library(tidyverse)
df %>% count(x)

  x         n
  <fct> <int>
1 1-3       1
2 3-5       1
3 5-9       1
4 9-10      1
5 10-12     1
</code>```

Desired Output

```<code>  x         n
  <fct> <int>
1 1-3       1
2 3-5       1
3 5-9       1
4 9-10      1
5 10-12     1
</code>```

Important Note - Solution should be dynamic which means it should run on any type of numeric bands even if it starts from 1000 or any other numeric value (For example 1250 - 2500, 2500 - 5000, 5000 - 10000, 10000 - 20000 etc). Solution in dplyr is preferred one.

答:
If x is always sorted and in the same order as shown in the example you could arrange the factor levels based on their appearance before using count.

```<code>library(dplyr)
library(rlang)

df %>%
  mutate(x = factor(x, levels = unique(x))) %>%
  count(x)
</code>```

However, a general solution would be to get the number before "-" and arrange data based on that.

```<code>df %>%
  mutate(x1 = as.numeric(sub('-.*', '', x)),
         x = factor(x, levels = x[order(x1)])) %>%
  count(x)
</code>```

To wrap this in a function we can use :

```<code>count_band_data <- function(data, col, sep = '-') {
   data %>%
     mutate(temp = as.numeric(sub(paste0(sep, '.*'), '', {{col}})),
            {{col}} := factor({{col}}, levels = {{col}}[order(temp)])) %>%
     count({{col}})
 }
</code>```

and then use it as :

```<code>df %>% count_band_data(x)

# A tibble: 5 x 2
#  x         n
#  <fct> <int>
#1 1-3       1
#2 3-5       1
#3 5-9       1
#4 9-10      1
#5 10-12     1
</code>```

Title: Sort Numeric Bands in R

Body:
I have some numeric variables which are categorised into a few bands (like 1-3, 3-5, 5-7 etc). I want to main their band order. For example, in the data frame below.

df <- data.frame(x = c("1-3", "3-5","5-9", "9-10", "10-12"))

When I run any data manipulation operation (like group_by, count) in this column, it returns this output.

Current Output

library(tidyverse)
df %>% count(x)

  x         n
  <fct> <int>
1 1-3       1
2 3-5       1
3 5-9       1
4 9-10      1
5 10-12     1

Desired Output

  x         n
  <fct> <int>
1 1-3       1
2 3-5       1
3 5-9       1
4 9-10      1
5 10-12     1

Important Note - Solution should be dynamic which means it should run on any type of numeric bands even if it starts from 1000 or any other numeric value (For example 1250 - 2500, 2500 - 5000, 5000 - 10000, 10000 - 20000 etc). Solution in dplyr is preferred one.

Body:
If x is always sorted and in the same order as shown in the example you could arrange the factor levels based on their appearance before using count.

library(dplyr)
library(rlang)

df %>%
  mutate(x = factor(x, levels = unique(x))) %>%
  count(x)

However, a general solution would be to get the number before "-" and arrange data based on that.

df %>%
  mutate(x1 = as.numeric(sub('-.*', '', x)),
         x = factor(x, levels = x[order(x1)])) %>%
  count(x)

To wrap this in a function we can use :

count_band_data <- function(data, col, sep = '-') {
   data %>%
     mutate(temp = as.numeric(sub(paste0(sep, '.*'), '', {{col}})),
            {{col}} := factor({{col}}, levels = {{col}}[order(temp)])) %>%
     count({{col}})
 }

and then use it as :

df %>% count_band_data(x)

# A tibble: 5 x 2
#  x         n
#  <fct> <int>
#1 1-3       1
#2 3-5       1
#3 5-9       1
#4 9-10      1
#5 10-12     1


问:
Python progress bar and downloads
I have a Python script that launches a URL that is a downloadable file. Is there some way to have Python display the download progress as oppose to launching the browser?</p>

答:
There is an answer with requests and tqdm.

import requests
from tqdm import tqdm

def download(url: str, fname: str):
    resp = requests.get(url, stream=True)
    total = int(resp.headers.get('content-length', 0))
    # Can also replace 'file' with a io.BytesIO object
    with open(fname, 'wb') as file, tqdm(
        desc=fname,
        total=total,
        unit='iB',
        unit_scale=True,
        unit_divisor=1024,
    ) as bar:
        for data in resp.iter_content(chunk_size=1024):
            size = file.write(data)
            bar.update(size)
```

Gist: https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51

Title: Python progress bar and downloads

Body:
There is an answer with requests and tqdm.

import requests
from tqdm import tqdm

def download(url: str, fname: str):
    resp = requests.get(url, stream=True)
    total = int(resp.headers.get('content-length', 0))
    # Can also replace 'file' with a io.BytesIO object
    with open(fname, 'wb') as file, tqdm(
        desc=fname,
        total=total,
        unit='iB',
        unit_scale=True,
        unit_divisor=1024,
    ) as bar:
        for data in resp.iter_content(chunk_size=1024):
            size = file.write(data)
            bar.update(size)

Gist: https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51


问:
How to remove blank and null values from a list that passed into dataframe in python
I have dataframe column like below.

```<code>df['lane']
AZ
NL

NaN
BL
AZ
</code>```

My code

```<code>unique_lane = df['lane'].unique()
unique_lane = pd.DataFrame( list(zip(unique_lane)), columns =['unique_lane'])
t = ', '.join(unique_lane['unique_lane'].astype(str))
</code>```

While I am passing unique list values blank('') or Null values should be removed from the list.
The list t created should contain not blank or  not Null values.

```<code>bigdata_null_zones = bigdata_null_zones[~bigdata_null_zones["lane"].isin([t])]
</code>```

How can this be done in python?

答:
Sample data for test DataFrame from question:

```<code>df = pd.DataFrame({'lane':['AZ','NL','', np.nan, 'BL','AZ']})
</code>```

Test for pass only misisng values or empty strings:

```<code>df = pd.DataFrame({'lane':['', np.nan]})
print (df)
  lane
0
1  NaN

bigdata_null_zones = pd.DataFrame({'lane':['AZ','NL','AB', 'BL','AZ']})
print (bigdata_null_zones)
  lane
0   AZ
1   NL
2   AB
3   BL
4   AZ
</code>```

After remove it get empty Series:

```<code>t = df['lane'].replace('',np.nan).dropna()
print (t)
Series([], Name: lane, dtype: float64)
</code>```

So if pass get same values, because nothing filtered:

```<code>bigdata_null_zones[bigdata_null_zones["lane"].isin(t)]
print (bigdata_null_zones)
  lane
0   AZ
1   NL
2   AB
3   BL
4   AZ
</code>```

If same DataFrame:

```<code>df = pd.DataFrame({'lane':['AZ','NL','', np.nan, 'BL','AZ'],
                   'col':range(6)})

print (df)
  lane  col
0   AZ    0
1   NL    1
2         2
3  NaN    3
4   BL    4
5   AZ    5

df1 = df.assign(lane= df['lane'].replace('',np.nan)).dropna(subset=['lane'])
print (df1)
  lane  col
0   AZ    0
1   NL    1
4   BL    4
5   AZ    5
</code>```

Body:
I have dataframe column like below.

df['lane']
AZ
NL

NaN
BL
AZ

My code

unique_lane = df['lane'].unique()
unique_lane = pd.DataFrame( list(zip(unique_lane)), columns =['unique_lane'])
t = ', '.join(unique_lane['unique_lane'].astype(str))

While I am passing unique list values blank('') or Null values should be removed from the list.
The list t created should contain not blank or  not Null values.

bigdata_null_zones = bigdata_null_zones[~bigdata_null_zones["lane"].isin([t])]

How can this be done in python?

Body:
Sample data for test DataFrame from question:

df = pd.DataFrame({'lane':['AZ','NL','', np.nan, 'BL','AZ']})

Test for pass only misisng values or empty strings:

df = pd.DataFrame({'lane':['', np.nan]})
print (df)
  lane
0
1  NaN

bigdata_null_zones = pd.DataFrame({'lane':['AZ','NL','AB', 'BL','AZ']})
print (bigdata_null_zones)
  lane
0   AZ
1   NL
2   AB
3   BL
4   AZ

After remove it get empty Series:

t = df['lane'].replace('',np.nan).dropna()
print (t)
Series([], Name: lane, dtype: float64)

So if pass get same values, because nothing filtered:

bigdata_null_zones[bigdata_null_zones["lane"].isin(t)]
print (bigdata_null_zones)
  lane
0   AZ
1   NL
2   AB
3   BL
4   AZ

If same DataFrame:

df = pd.DataFrame({'lane':['AZ','NL','', np.nan, 'BL','AZ'],
                   'col':range(6)})

print (df)
  lane  col
0   AZ    0
1   NL    1
2         2
3  NaN    3
4   BL    4
5   AZ    5

df1 = df.assign(lane= df['lane'].replace('',np.nan)).dropna(subset=['lane'])
print (df1)
  lane  col
0   AZ    0
1   NL    1
4   BL    4
5   AZ    5


问:
Python function: Find Change from purchase amount
I'm looking for the most efficient way to figure out a change amount (Quarters, dimes, nickels, and pennies) from a purchase amount. The purchase amount must be less than $1, and the change is from one dollar. I need to know how many quarters, dimes, nickels, and pennies someone would get back.

Would it be best to set up a dictionary?

答:
This is probably pretty fast - just a few operations per denomination:</p>

```<code>def change(amount):
    money = ()
    for coin in [25,10,5,1]
        num = amount/coin
        money += (coin,) * num
        amount -= coin * num

    return money
</code>```

OwnerDisplayName: Jason

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Oddthinking

Body:
This is probably pretty fast - just a few operations per denomination:

def change(amount):
    money = ()
    for coin in [25,10,5,1]
        num = amount/coin
        money += (coin,) * num
        amount -= coin * num

    return money

OwnerDisplayName: Triptych


问:
Spring Boot LDAP template query
How do I write the query in LDAP template for the following AD query:

```<code>(&(objectcategory=person)(objectclass=user)(userAccountControl:1.2.840.113556.1.4.803:=2)(|(extensionAttribute2=fte)(extensionAttribute2=intern)(extensionAttribute2=awf))(whenchanged>=20200512064756.0Z))
</code>```

This is something I formed which dont seem to be working :

```<code>query().where("whenchanged").is(20200512064756.0Z),
      .and(query().where("extensionAttribute2").is("fte").or("extensionAttribute2").is("intern").or("extensionAttribute2").is("awf")),
      .and(query().where("objectcategory").is("person").and("objectclass").is("user").and("userAccountControl:1.2.840.113556.1.4.803:").is(2))
</code>```

答:
```<code>ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC")).minusHours(inactiveHours);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss[.S]'Z'");
        AndFilter af = new AndFilter();
        af.and(new EqualsFilter("objectcategory", "person")).and(new EqualsFilter("objectclass", "user"))
                .and(new EqualsFilter("userAccountControl:1.2.840.113556.1.4.803:", 2));
        OrFilter of = new OrFilter();
        of.or(new EqualsFilter(AD_EXTENSIONATTRIBUTE2, "fte")).or(new EqualsFilter(AD_EXTENSIONATTRIBUTE2, "awf"))
                .or(new EqualsFilter(AD_EXTENSIONATTRIBUTE2, "intern"));
        af.append(of).append(new GreaterThanOrEqualsFilter("whenchanged", zdt.format(formatter)));
</code>```

Title: Spring Boot LDAP template query

Body:
How do I write the query in LDAP template for the following AD query:

(&(objectcategory=person)(objectclass=user)(userAccountControl:1.2.840.113556.1.4.803:=2)(|(extensionAttribute2=fte)(extensionAttribute2=intern)(extensionAttribute2=awf))(whenchanged>=20200512064756.0Z))

This is something I formed which dont seem to be working :

query().where("whenchanged").is(20200512064756.0Z),
      .and(query().where("extensionAttribute2").is("fte").or("extensionAttribute2").is("intern").or("extensionAttribute2").is("awf")),
      .and(query().where("objectcategory").is("person").and("objectclass").is("user").and("userAccountControl:1.2.840.113556.1.4.803:").is(2))


问:
Search Everywhere for Comments in Pycharm
Pycharm Search Everywhere function easily allows the user to search everywhere for source code in every file of the project. However it is not able to search for comments, is there a way around that problem?.

I usually leave important comments of lessons learned  or links to stack overflow containing helpfull code, and would love a way to easily serach for these comments, when I forget where I wrote them.

Thanks for Reading

答:
I once had a problem with Search Everywhere or Find in Path(Ctrl + Shift + F for windows) i.e. project wide search for a django project in Pycharm Professional 2020.1.

Although filter was selected as Anywhere, still some were not being found in the project files which were actually there.

But after invalidating caches & restarting like the picture, everything was fine.

First select Invalidate Caches / Restart... in File menu.

Then click Invalidate and Restart in the Invalidate Caches popup window.


问:
Translation with Flutter and Dart
I am currently working on a project which involves translation, I am building an app using the framework Flutter and the language Dart.

The problem is that I can't figure out how to translate text with my app in dart.

I tried using all sorts of platforms like google translate API, Firebase, Yandex... But I don't have any money which is kind of a problem.

So I tried this https://learn.microsoft.com/fr-fr/azure//cognitive-services/translator/reference/v3-0-translate#request-url but I got this error message {"error":{"code":405000,"message":"The request method is not supported for the requested resource."}}.

Then I tried using a dart package: https://pub.dev/packages/localize_and_translate, it worked, but it's to translate text that you already have in json files and I need to translate text that users will give me.

I also tried to get what was inside one of the google translate requests, to get an answer without having to manually go to the website, when I tried to analyse the request I only got this link : https://fonts.googleapis.com/css?lang=fr&family=Product+Sans%7CRoboto:400,700.

Some help or ideas would definitely be very much appreciated.

Thanks for everything !

答:
You can use AWS Translate(One year free), which I have created an plugin for my production used apps. Earlier I used Android native and IOS native AWS official packages with Flutter MethodChannel and later I decided to make it package so that others like you can get help from.

Here is that package: https://pub.dev/packages/aws_translate

Read more about AWS translate: https://aws.amazon.com/translate/

Here is a simple example of how to use it:

```<code>AwsTranslate awsTranslate = AwsTranslate(
    poolId: poolId, // your pool id here
    region: Regions.AP_NORTHEAST_2); // your region here

// from parameter is default to ``auto``
String textToTranslate = 'If you press on this text, I can translate this text for you.';
String translated = await awsTranslate.translateText(textToTranslate, to: 'es');
if (!mounted) return;
print(textToTranslate);
setState(() => textToTranslate = translated);
</code>```

Example app for my AWS translate plugin can be found here: https://github.com/Blasanka/aws_translate_plugin/tree/master/example (You must have AWS account to get pool id and region).

If you just want to try out google translate(without any login but you cannot use in production apps), try https://pub.dev/packages/translator

Working example for translator can be found here: https://github.com/gabrielpacheco23/google-translator/blob/master/example/main.dart

Title: Translation with Flutter and Dart

Body:
You can use AWS Translate(One year free), which I have created an plugin for my production used apps. Earlier I used Android native and IOS native AWS official packages with Flutter MethodChannel and later I decided to make it package so that others like you can get help from.

Here is that package: https://pub.dev/packages/aws_translate

Read more about AWS translate: https://aws.amazon.com/translate/

Here is a simple example of how to use it:

AwsTranslate awsTranslate = AwsTranslate(
    poolId: poolId, // your pool id here
    region: Regions.AP_NORTHEAST_2); // your region here

// from parameter is default to ``auto``
String textToTranslate = 'If you press on this text, I can translate this text for you.';
String translated = await awsTranslate.translateText(textToTranslate, to: 'es');
if (!mounted) return;
print(textToTranslate);
setState(() => textToTranslate = translated);

Example app for my AWS translate plugin can be found here: https://github.com/Blasanka/aws_translate_plugin/tree/master/example (You must have AWS account to get pool id and region).

If you just want to try out google translate(without any login but you cannot use in production apps), try https://pub.dev/packages/translator

Working example for translator can be found here: https://github.com/gabrielpacheco23/google-translator/blob/master/example/main.dart


问:
Create a function that deletes downloaded files
I am using this sample code:
https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py

I use the !yt command because the !play command has stability issues.
I need to create a function that eliminates downloaded music files. I had thought of deleting the entire folder every time a song was played but the idea does not seem so brilliant to me. Can anyone tell me how to do it?

答:
Assuming you want to put this in a command,

```<code>@bot.command(name='del')
@commands.is_owner #only bot owner can use this
for folder in os.listdir('./foldermp3filesarestored'):
    if folder.endswith('.mp3'):
        os.remove(folder)
    else:
        print("found file not ending in .mp3")

</code>```

You could put this in a for loop in on_ready too.

Body:
Assuming you want to put this in a command,

@bot.command(name='del')
@commands.is_owner #only bot owner can use this
for folder in os.listdir('./foldermp3filesarestored'):
    if folder.endswith('.mp3'):
        os.remove(folder)
    else:
        print("found file not ending in .mp3")

You could put this in a for loop in on_ready too.


问:
Entity Framework related entities generate unnecessary joins of the same table
I am running into issue of EF Core 3.1 generating multiple INNER JOINs to the same table even though it has enough information to avoid it.

Simplified model with mapping :

```<code>internal class PRecord
{
    public int Id { get; private set; }
    public string Name { get; private set; }

    public PImport Import { get; private set; }

    private PRecord()
    {
    }

    internal PRecord(string name)
    {
        Name = name;
    }

    public class PRecordDbMapping : IEntityTypeConfiguration<PRecord>
    {
        public void Configure(EntityTypeBuilder<PRecord> builder)
        {
            builder.ToTable("p_records");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("PImportId").HasColumnName("p_import_id");

            builder.HasOne(x => x.Import).WithMany(x => x.Records).HasForeignKey("PImportId").IsRequired();
        }
    }
}

internal class PImport
{
    public long Id { get; private set; }
    public PSource Source { get; private set; }

    public IEnumerable<PRecord> Records { get; private set; }

    private PImport()
    {
    }

    internal PImport(PSource source)
    {
        Source = source;
    }

    public class PImportDbMapping : IEntityTypeConfiguration<PImport>
    {
        public void Configure(EntityTypeBuilder<PImport> builder)
        {
            builder.ToTable("p_imports");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<int>("PSourceId").HasColumnName("p_source_id");

            builder.HasOne(x => x.Source).WithMany(x => x.Imports).HasForeignKey("PSourceId").IsRequired();
        }
    }
}

internal class PSource
{
    public int Id { get; private set; }
    public PImport CurrentImport { get; private set; }

    public IEnumerable<PImport> Imports { get; private set; }

    private PSource()
    {
    }

    internal PSource(int id)
    {
        Id = id;
    }

    public class PSourceDbMapping : IEntityTypeConfiguration<PSource>
    {
        public void Configure(EntityTypeBuilder<PSource> builder)
        {
            builder.ToTable("p_sources");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("CurrentPImportId").HasColumnName("current_p_import_id");

            builder.HasOne(x => x.CurrentImport).WithOne().HasForeignKey<PEPSource>("CurrentPImportId");
        }
    }
}
</code>```

I tried multiple variants of the following, but with slight variations I always get the same problem in SQL :

```<code>var query = ctx.PRecords
               .Where(x => x.Name.Contains("bla"))
               .Where(x => x.Import.Source.CurrentImport == x.Import)
               .Select(x => new { Record = x, Source = x.Import.Source });

SELECT
    [p].[id], [p].[name], [p].[p_import_id], [p1].[id], [p1].[current_p_import_id]
FROM [p_records] AS [p]
INNER JOIN [p_source_imports] AS [p0] ON [p].[p_import_id] = [p0].[id]
INNER JOIN [p_sources] AS [p1] ON [p0].[p_source_id] = [p1].[id]
INNER JOIN [p_source_imports] AS [p2] ON [p1].[current_p_import_id] = [p2].[id]
WHERE (CHARINDEX(N'bla', [p].[name]) > 0) AND ([p2].[id] = [p0].[id])
</code>```

I am able to generate the SQL I want with the following code :

```<code>var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));
</code>```

The issue with this one is that I want to move the .Where(x => x.Record.Name.Contains("bla")) into extension method. And in this query I have to apply it on the anonymous type.

So I have two questions :

Can the first query be salvaged to generate reasonable SQL, while still returning IQueryable<PRecord> or if not possible a queryable of some non-anonymous type ?

If (1) cannot be achieved reasonably, can I achieve the moving of the WHERE condition on the Name to some extension method anyway?

EDIT: specified EF Core 3.1 as the verswion used

EDIT: the accepted solution is enough for my case. Completely clean solution might not be possible in the current version of EF Core. As I was browsing github issues for EF Core it seems the SQL generator might have restrictions that cause the more straightforward queries to use unnecessary 'JOIN's.

So the query I went with is :

```<code>var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new SourceRecordPair() { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));
</code>```

答:
Unfortunately, you cannot pass anonymous types from one method to the other and still access the properties.  You will need to strongly type the following:</p>

```<code>new SomeModel { Record = y, Source = x })
</code>```

Body:
I am running into issue of EF Core 3.1 generating multiple INNER JOINs to the same table even though it has enough information to avoid it.

Simplified model with mapping :

internal class PRecord
{
    public int Id { get; private set; }
    public string Name { get; private set; }

    public PImport Import { get; private set; }

    private PRecord()
    {
    }

    internal PRecord(string name)
    {
        Name = name;
    }

    public class PRecordDbMapping : IEntityTypeConfiguration<PRecord>
    {
        public void Configure(EntityTypeBuilder<PRecord> builder)
        {
            builder.ToTable("p_records");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("PImportId").HasColumnName("p_import_id");

            builder.HasOne(x => x.Import).WithMany(x => x.Records).HasForeignKey("PImportId").IsRequired();
        }
    }
}

internal class PImport
{
    public long Id { get; private set; }
    public PSource Source { get; private set; }

    public IEnumerable<PRecord> Records { get; private set; }

    private PImport()
    {
    }

    internal PImport(PSource source)
    {
        Source = source;
    }

    public class PImportDbMapping : IEntityTypeConfiguration<PImport>
    {
        public void Configure(EntityTypeBuilder<PImport> builder)
        {
            builder.ToTable("p_imports");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<int>("PSourceId").HasColumnName("p_source_id");

            builder.HasOne(x => x.Source).WithMany(x => x.Imports).HasForeignKey("PSourceId").IsRequired();
        }
    }
}

internal class PSource
{
    public int Id { get; private set; }
    public PImport CurrentImport { get; private set; }

    public IEnumerable<PImport> Imports { get; private set; }

    private PSource()
    {
    }

    internal PSource(int id)
    {
        Id = id;
    }

    public class PSourceDbMapping : IEntityTypeConfiguration<PSource>
    {
        public void Configure(EntityTypeBuilder<PSource> builder)
        {
            builder.ToTable("p_sources");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("CurrentPImportId").HasColumnName("current_p_import_id");

            builder.HasOne(x => x.CurrentImport).WithOne().HasForeignKey<PEPSource>("CurrentPImportId");
        }
    }
}

I tried multiple variants of the following, but with slight variations I always get the same problem in SQL :

var query = ctx.PRecords
               .Where(x => x.Name.Contains("bla"))
               .Where(x => x.Import.Source.CurrentImport == x.Import)
               .Select(x => new { Record = x, Source = x.Import.Source });

SELECT
    [p].[id], [p].[name], [p].[p_import_id], [p1].[id], [p1].[current_p_import_id]
FROM [p_records] AS [p]
INNER JOIN [p_source_imports] AS [p0] ON [p].[p_import_id] = [p0].[id]
INNER JOIN [p_sources] AS [p1] ON [p0].[p_source_id] = [p1].[id]
INNER JOIN [p_source_imports] AS [p2] ON [p1].[current_p_import_id] = [p2].[id]
WHERE (CHARINDEX(N'bla', [p].[name]) > 0) AND ([p2].[id] = [p0].[id])

I am able to generate the SQL I want with the following code :

var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));

The issue with this one is that I want to move the .Where(x => x.Record.Name.Contains("bla")) into extension method. And in this query I have to apply it on the anonymous type.

So I have two questions :

Can the first query be salvaged to generate reasonable SQL, while still returning IQueryable<PRecord> or if not possible a queryable of some non-anonymous type ?

If (1) cannot be achieved reasonably, can I achieve the moving of the WHERE condition on the Name to some extension method anyway?

EDIT: specified EF Core 3.1 as the verswion used

EDIT: the accepted solution is enough for my case. Completely clean solution might not be possible in the current version of EF Core. As I was browsing github issues for EF Core it seems the SQL generator might have restrictions that cause the more straightforward queries to use unnecessary 'JOIN's.

So the query I went with is :

var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new SourceRecordPair() { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));

Body:
Unfortunately, you cannot pass anonymous types from one method to the other and still access the properties.  You will need to strongly type the following:

new SomeModel { Record = y, Source = x })


问:
Problems with if ....==NULL in C
I have this code, note that it is shortened down. The problem is if the file exists
it still overwrites it. Been 30 years since I did any programming so bear with me. Thanks!</p>

```<code>FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");
            exit(0);
        }
    return pointer;
}
</code>```

答:
If you're using the C11 standard you can use the "x" argument to specify that if the file exists the fopen() function will fail.

For reference: http://www.cplusplus.com/reference/cstdio/fopen/

Title: Problems with if ....==NULL in C

Body:
I have this code, note that it is shortened down. The problem is if the file exists
it still overwrites it. Been 30 years since I did any programming so bear with me. Thanks!

FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");
            exit(0);
        }
    return pointer;
}


问:
Python webbrowser.open() to open Chrome browser
According to the documentation http://docs.python.org/3.3/library/webbrowser.html it's supposed to open in the default browser, but for some reason on my machine it opens IE. I did a google search and I came across an answer that said I need to register browsers, but I'm not sure how to use webbrowser.register() and the documentation doesn't seem to be very clear. How do I register Chrome so that urls I pass to webbrowser.open() open in Chrome instead of IE?</p>

答:
```<code>if sys.platform[:3] == "win":
    # First try to use the default Windows browser
    register("windows-default", WindowsDefault)

    # Detect some common Windows browsers, fallback to IE
    iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
                            "Mozilla Firefox\\FIREFOX.EXE")
    for browser in ("firefox", "firebird", "seamonkey", "mozilla",
                    "netscape", "opera", iexplore):
        if shutil.which(browser):
            register(browser, None, BackgroundBrowser(browser))
</code>```

100% Work....See line number 535-545..Change the path of iexplore to firefox or Chrome According to your requirement...
  in my case change path I Mention in the above code for firefox setting......

Body:
if sys.platform[:3] == "win":
    # First try to use the default Windows browser
    register("windows-default", WindowsDefault)

    # Detect some common Windows browsers, fallback to IE
    iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
                            "Mozilla Firefox\\FIREFOX.EXE")
    for browser in ("firefox", "firebird", "seamonkey", "mozilla",
                    "netscape", "opera", iexplore):
        if shutil.which(browser):
            register(browser, None, BackgroundBrowser(browser))

100% Work....See line number 535-545..Change the path of iexplore to firefox or Chrome According to your requirement...
  in my case change path I Mention in the above code for firefox setting......


问:
Mass renaming linkages in a FLA
I have an AS3 based FLA that, for various reasons, needs nearly all of the linkages in the library reworked (need to move to a different package namespace).  This particular FLA is pretty big, so doing this by hand would be rather tedious.

What is the best way to handle this?

I have considered saving out the FLA as an XFL, and just hand editing all of the XML files in the LIBRARY folder, and then saving out as FLA.  Has anyone tried this?  I have never worked with XFL files before, so I don't know what quirks I may run across.

Are there any existing JSFL scripts that handle this?

Thanks.

EDIT:

My problem has to do with loading SWFs and class conflicts because of multiple SWFs using the same package namespace.  Without getting into too many details, I know about ApplicationDomain and LoaderContext.  I am currently loading into a new ApplicationDomain, but that isn't an ideal situation and is causing grief that won't be maintainable in the long run.

答:
I don't have access to Flash IDE today but you can easily adapt my
script to do what you want :
Automated importing/renaming of Flash assets
renaming-of-flash-assets/6031965#6031965

There is an easy way to find what Jsfl functions you have to use :

Open History panel  (Window > Other Panels > History)

Make one linkage renaming

Copy history to jsfl and adapt code

Title: Mass renaming linkages in a FLA