问:
Angular Reactive Forms: How to Populate A Multi-Selection Checkbox form?
How can I populate check boxes of a form group while in "Edit Mode"?

I am working on a project where I am making and editing workouts, then storing them to a database (using firebase at this current time). The workout creation worked flawlessly with the Angular template driven approach, but I am trying to add the functionality where I can edit an existing workout. Because of this, I have made the form reactive where depending on if I am in editMode (this mode is determined from the route params) or not, the information is either populated, or it isn't.

This works great for the basic string population, such as title and imagepath. Here, I am in editMode (coming from the route params) and things are populated accordingly:

However, I also have checkboxes to be filled on this same form. I am using Material Theme for the checkboxes. Here's an example from a workoutphase selection:

```<code><mat-form-field
  hideRequiredMarker
  appearance="fill"
  class="phase">
  <mat-label>Phase</mat-label>
  <mat-select multiple id="phase" name="phase" formControlName="phases">
    <mat-option value="Base 1">Base 1</mat-option>
    <mat-option value="Base 2">Base 2</mat-option>
    <mat-option value="Base 3">Base 3</mat-option>
    <mat-option value="Build 1">Build 1</mat-option>
    <mat-option value="Build 2">Build 2</mat-option>
    <mat-option value="Recovery">Recovery</mat-option>
    <mat-option value="Peak">Peak</mat-option>
    <mat-option value="Race">Race</mat-option>
    <mat-option value="Testing">Testing</mat-option>
  </mat-select>
</mat-form-field>
</code>```

and how it appears when creating a workout (the problem is when trying to populate while in editMode):

This appears with a list dropdown that later returns an array of selected items to be added to the workouts.

With the reactive approach, I am trying to be able to populate the checkboxes as filled while being in editMode (or when the information is being pulled in). Is there a way to populate checkboxes? Or would I simply need to "re-check" which boxes I want while in edit mode?

So far I have tried using a new FormArray([]); that takes this array and populates everything as it should be. This gives me loads of errors related to the formGroup.

This form is in the WorkoutEditComponent found in app/features/workouts-page/workout-edit
You can get to the edit form by clicking on any workout on the home view workouts page, then clicking edit button at the top.

Here is the stackblitz to this code.
 You can see that if you go to the side menu and select workouts, create workout, then there is a checkbox option and the dropdown works. But when you go through the workouts/edit, then the checkboxes are unable to populate. I have simplified and backtracked a bit on this stackblitz for the sake of simplicity of the problem. Any method used with the FormArray([]) seemed to make the problem worse.

Here is some more information:

I am initializing the form through my ngOnInit after checking whether or not I am in edit mode:

```<code>ngOnInit()
 this.route.params.subscribe((params: Params) => {
    this.id = +params["id"];
    this.editMode = params["id"] != null;
    this.initForm();
  });
}
</code>```

and the initForm():

```<code>private initForm() {
  let workoutImgPath = "";
  let workoutTitle = "";
  if (this.editMode) {
    const workout = this.workoutService.getWorkout(this.id);
    workoutTitle = workout.title;
    workoutImgPath = workout.imagePath;
    console.log(workout);
  }

 this.workoutForm = new FormGroup({
    title: new FormControl(workoutTitle, Validators.required),
    imgPath: new FormControl(workoutImgPath, Validators.required)
  });
}
</code>```

Above is the currently working solution where only the image path and title are being added to the form whilst in edit mode.

Can these checkboxes also be populated from an array of items while editing an existing workout?

答:
Hope this helps, In edit mode patch the list of phases to the formcontrol.

HTML

```<code><form>
<div>
    <button class="btn btn-primary" (click)="onEdit()">Edit</button>
</div>
<div style="margin-top: 100px;">
    <mat-form-field>
        <mat-label>Phases</mat-label>
        <mat-select [formControl]="phases" multiple>
            <mat-option value="Base 1">Base 1</mat-option>
            <mat-option value="Base 2">Base 2</mat-option>
            <mat-option value="Base 3">Base 3</mat-option>
            <mat-option value="Build 1">Build 1</mat-option>
            <mat-option value="Build 2">Build 2</mat-option>
            <mat-option value="Recovery">Recovery</mat-option>
            <mat-option value="Peak">Peak</mat-option>
            <mat-option value="Race">Race</mat-option>
            <mat-option value="Testing">Testing</mat-option>
        </mat-select>
      </mat-form-field>
</div>
</code>```

TS

```<code>phases = new FormControl();

constructor() { }

 ngOnInit() {
    this.phases.valueChanges.subscribe(data => {
      console.log('Selected Options', data)
    });
  }

onEdit() {
    this.phases.patchValue(["Base 1", "Build 1"])
  }
</code>```

Body:
How can I populate check boxes of a form group while in "Edit Mode"?

I am working on a project where I am making and editing workouts, then storing them to a database (using firebase at this current time). The workout creation worked flawlessly with the Angular template driven approach, but I am trying to add the functionality where I can edit an existing workout. Because of this, I have made the form reactive where depending on if I am in editMode (this mode is determined from the route params) or not, the information is either populated, or it isn't.

This works great for the basic string population, such as title and imagepath. Here, I am in editMode (coming from the route params) and things are populated accordingly:

However, I also have checkboxes to be filled on this same form. I am using Material Theme for the checkboxes. Here's an example from a workoutphase selection:

<mat-form-field
  hideRequiredMarker
  appearance="fill"
  class="phase">
  <mat-label>Phase</mat-label>
  <mat-select multiple id="phase" name="phase" formControlName="phases">
    <mat-option value="Base 1">Base 1</mat-option>
    <mat-option value="Base 2">Base 2</mat-option>
    <mat-option value="Base 3">Base 3</mat-option>
    <mat-option value="Build 1">Build 1</mat-option>
    <mat-option value="Build 2">Build 2</mat-option>
    <mat-option value="Recovery">Recovery</mat-option>
    <mat-option value="Peak">Peak</mat-option>
    <mat-option value="Race">Race</mat-option>
    <mat-option value="Testing">Testing</mat-option>
  </mat-select>
</mat-form-field>

and how it appears when creating a workout (the problem is when trying to populate while in editMode):

This appears with a list dropdown that later returns an array of selected items to be added to the workouts.

With the reactive approach, I am trying to be able to populate the checkboxes as filled while being in editMode (or when the information is being pulled in). Is there a way to populate checkboxes? Or would I simply need to "re-check" which boxes I want while in edit mode?

So far I have tried using a new FormArray([]); that takes this array and populates everything as it should be. This gives me loads of errors related to the formGroup.

This form is in the WorkoutEditComponent found in app/features/workouts-page/workout-edit
You can get to the edit form by clicking on any workout on the home view workouts page, then clicking edit button at the top.

Here is the stackblitz to this code.
 You can see that if you go to the side menu and select workouts, create workout, then there is a checkbox option and the dropdown works. But when you go through the workouts/edit, then the checkboxes are unable to populate. I have simplified and backtracked a bit on this stackblitz for the sake of simplicity of the problem. Any method used with the FormArray([]) seemed to make the problem worse.

Here is some more information:

I am initializing the form through my ngOnInit after checking whether or not I am in edit mode:

ngOnInit()
 this.route.params.subscribe((params: Params) => {
    this.id = +params["id"];
    this.editMode = params["id"] != null;
    this.initForm();
  });
}

and the initForm():

private initForm() {
  let workoutImgPath = "";
  let workoutTitle = "";
  if (this.editMode) {
    const workout = this.workoutService.getWorkout(this.id);
    workoutTitle = workout.title;
    workoutImgPath = workout.imagePath;
    console.log(workout);
  }

 this.workoutForm = new FormGroup({
    title: new FormControl(workoutTitle, Validators.required),
    imgPath: new FormControl(workoutImgPath, Validators.required)
  });
}

Above is the currently working solution where only the image path and title are being added to the form whilst in edit mode.

Can these checkboxes also be populated from an array of items while editing an existing workout?

Body:
Hope this helps, In edit mode patch the list of phases to the formcontrol.

HTML

<form>
<div>
    <button class="btn btn-primary" (click)="onEdit()">Edit</button>
</div>
<div style="margin-top: 100px;">
    <mat-form-field>
        <mat-label>Phases</mat-label>
        <mat-select [formControl]="phases" multiple>
            <mat-option value="Base 1">Base 1</mat-option>
            <mat-option value="Base 2">Base 2</mat-option>
            <mat-option value="Base 3">Base 3</mat-option>
            <mat-option value="Build 1">Build 1</mat-option>
            <mat-option value="Build 2">Build 2</mat-option>
            <mat-option value="Recovery">Recovery</mat-option>
            <mat-option value="Peak">Peak</mat-option>
            <mat-option value="Race">Race</mat-option>
            <mat-option value="Testing">Testing</mat-option>
        </mat-select>
      </mat-form-field>
</div>

TS

phases = new FormControl();

constructor() { }

 ngOnInit() {
    this.phases.valueChanges.subscribe(data => {
      console.log('Selected Options', data)
    });
  }

onEdit() {
    this.phases.patchValue(["Base 1", "Build 1"])
  }


来源: stackexchange

问:
check for end of execution of class in java
I have written a small program to validate 3 data files and convert them into a csv file.

-Every file is converted by a different class file

-There is a main class which instantiates all the other classes for processing files one after other

How do i make sure that the next file is processed only after the previous file is done?

The pseudocode for my program is as follows

```<code>mainExecute Class()
{
    executeFile1converter();
    executeFile2Converter();
    executeFile3Converter();
}
</code>```

答: If its single threaded and there is no exception/error occurred then it guarantees that behavior </p>

ContentLicense: CC BY-SA 3.0

Body:
I have written a small program to validate 3 data files and convert them into a csv file.

-Every file is converted by a different class file

-There is a main class which instantiates all the other classes for processing files one after other

How do i make sure that the next file is processed only after the previous file is done?

The pseudocode for my program is as follows

mainExecute Class()
{
    executeFile1converter();
    executeFile2Converter();
    executeFile3Converter();
}


问:
How to merge two intersecting arrays via es6
I have two arrays that have properties: minValue, maxValue, avgValue.  I would like to write a very clean approach to identifying which objects match (the displayName) in the array and then assign the values of the new array to the old (minPrice, maxPrice, avgPrice).

I have this code so far

```<code>export interface Player {
    displayName: string;
    MinPrice: number;
    MaxPrice: number;
    AvgPrice: number;}

export const MERGE_PLAYER_STATS = (playerStat: Player[], auctionStat: Player[]): any => {
      const reducer = (playerStat, auctionStat) => {
        playerStat.MinPrice = auctionStat.minPrice,
        playerStat.MaxPrice = auctionStat.maxPrice,
        playerStat.AvgPrice = auctionStat.avgPrice,
        playerStat.Team = auctionStat.team;
     }
      return reducer(playerStat, auctionStat =>
        filter(auctionStat, playerStat => auctionStat.displayName.includes(playerStat.displayName)));
}

Input: two different set of player arrays that have common display Names.
playerStat: [] = [];
auctionStat: [] = [];

playerStat.push( {
displayName: "Josh Allen",
minPrice: "",
maxPrice: "",
avgPrice: ""
},
{
displayName: "No One",
minPrice: "",
maxPrice: "",
avgPrice: ""
});

auctionStat.push( {
displayName: "Josh Allen",
minPrice: 1,
maxPrice: 2,
avgPrice: 1
},
{
displayName: "No One 2",
minPrice: 1,
maxPrice: 1,
avgPrice: 2
});
</code>```

The output should only have Josh Allen stats being updated from blank values to 1,2,1 respectively.

Please let me know what your clean approach this.  FYI, this code is not returning what I want it to.

答:
The simple approach would be to simply write a mapping function that copies in new objects based on matching keys.

Given an interface:

```<code>interface MyInterface {
  key: string;
  value: number;
}
</code>```

And two arrays:

```<code>const existingArray: MyInterface[] = [
  { key: 'a', value: 1 },
  { key: 'b', value: 2 },
  { key: 'c', value: 3 }
];

const newArray: MyInterface[] = [
  { key: 'b', value: 20 },
  { key: 'c', value: 30 },
  { key: 'd', value: 40 }
];
</code>```

Expected output

I want to update the existingArray with the values from newArray where the keys match.

If a value isn't found in newArray, the existing item is untouched.

If a new value is found in newArray, it isn't merged in to oldArray

All property values are to be overwritten

My expected output is:

```<code>const expected = [
  { key: 'a', value: 1 },
  { key: 'b', value: 20 },
  { key: 'c', value: 30 }
];
</code>```

Solution

I would achieve this by using this merge function. It is just a javascript array map:

```<code>private merge<T>(existing: T[], updated: T[], getKey: (t: T) => string): T[] {
  // start with the existing array items
  return existing.map(item => {
    // get the key using the callback
    const key: string = getKey(item);
    // find the matching item by key in the updated array
    const matching: T = updated.find(x => getKey(x) === key);
    if (matching) {
      // if a matching item exists, copy the property values to the existing item
      Object.assign(item, matching);
    }
    return item;
  });
}
</code>```

I have made it generic to allow you to use it with any type. All you need to do it provide the 2 arrays, and a callback to identify the key.

I would use it to created a merged array like this:

```<code>const merged = this.merge(existingArray, newArray, x => x.key);
</code>```

DEMO: https://stackblitz.com/edit/angular-nn8hit

A word of warning

This wouldn't scale well with very large arrays. If you are using large arrays, I would optimise by creating indexes of type Map<string, T>, to keep the number of loops fixed. This implementation is out of scope of this question.

Edit:

If you only want to update specific values, you could pass in an update callback:

```<code>private merge<T>(existing: T[], updated: T[], getKey: (t: T) => string,
  update: (item, matching) => void
): T[] {
  return existing.map(item => {
    const key: string = getKey(item);
    const matching: T = updated.find(x => getKey(x) === key);
    if (matching) {
      update(item, matching);
    }
    return item;
  });
}
</code>```

And call it like this:

```<code>const merged = this.merge(existingArray, newArray, x => x.key,
  (item, matching) => item.value = matching.value);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two arrays that have properties: minValue, maxValue, avgValue.  I would like to write a very clean approach to identifying which objects match (the displayName) in the array and then assign the values of the new array to the old (minPrice, maxPrice, avgPrice).

I have this code so far

export interface Player {
    displayName: string;
    MinPrice: number;
    MaxPrice: number;
    AvgPrice: number;}

export const MERGE_PLAYER_STATS = (playerStat: Player[], auctionStat: Player[]): any => {
      const reducer = (playerStat, auctionStat) => {
        playerStat.MinPrice = auctionStat.minPrice,
        playerStat.MaxPrice = auctionStat.maxPrice,
        playerStat.AvgPrice = auctionStat.avgPrice,
        playerStat.Team = auctionStat.team;
     }
      return reducer(playerStat, auctionStat =>
        filter(auctionStat, playerStat => auctionStat.displayName.includes(playerStat.displayName)));
}

Input: two different set of player arrays that have common display Names.
playerStat: [] = [];
auctionStat: [] = [];

playerStat.push( {
displayName: "Josh Allen",
minPrice: "",
maxPrice: "",
avgPrice: ""
},
{
displayName: "No One",
minPrice: "",
maxPrice: "",
avgPrice: ""
});

auctionStat.push( {
displayName: "Josh Allen",
minPrice: 1,
maxPrice: 2,
avgPrice: 1
},
{
displayName: "No One 2",
minPrice: 1,
maxPrice: 1,
avgPrice: 2
});

The output should only have Josh Allen stats being updated from blank values to 1,2,1 respectively.

Please let me know what your clean approach this.  FYI, this code is not returning what I want it to.

Body:
The simple approach would be to simply write a mapping function that copies in new objects based on matching keys.

Given an interface:

interface MyInterface {
  key: string;
  value: number;
}

And two arrays:

const existingArray: MyInterface[] = [
  { key: 'a', value: 1 },
  { key: 'b', value: 2 },
  { key: 'c', value: 3 }
];

const newArray: MyInterface[] = [
  { key: 'b', value: 20 },
  { key: 'c', value: 30 },
  { key: 'd', value: 40 }
];

Expected output

I want to update the existingArray with the values from newArray where the keys match.

If a value isn't found in newArray, the existing item is untouched.

If a new value is found in newArray, it isn't merged in to oldArray

All property values are to be overwritten

My expected output is:

const expected = [
  { key: 'a', value: 1 },
  { key: 'b', value: 20 },
  { key: 'c', value: 30 }
];

Solution

I would achieve this by using this merge function. It is just a javascript array map:

private merge<T>(existing: T[], updated: T[], getKey: (t: T) => string): T[] {
  // start with the existing array items
  return existing.map(item => {
    // get the key using the callback
    const key: string = getKey(item);
    // find the matching item by key in the updated array
    const matching: T = updated.find(x => getKey(x) === key);
    if (matching) {
      // if a matching item exists, copy the property values to the existing item
      Object.assign(item, matching);
    }
    return item;
  });
}

I have made it generic to allow you to use it with any type. All you need to do it provide the 2 arrays, and a callback to identify the key.

I would use it to created a merged array like this:

const merged = this.merge(existingArray, newArray, x => x.key);

DEMO: https://stackblitz.com/edit/angular-nn8hit

A word of warning

This wouldn't scale well with very large arrays. If you are using large arrays, I would optimise by creating indexes of type Map<string, T>, to keep the number of loops fixed. This implementation is out of scope of this question.

Edit:

If you only want to update specific values, you could pass in an update callback:

private merge<T>(existing: T[], updated: T[], getKey: (t: T) => string,
  update: (item, matching) => void
): T[] {
  return existing.map(item => {
    const key: string = getKey(item);
    const matching: T = updated.find(x => getKey(x) === key);
    if (matching) {
      update(item, matching);
    }
    return item;
  });
}

And call it like this:

const merged = this.merge(existingArray, newArray, x => x.key,
  (item, matching) => item.value = matching.value);


问:
WooCommerce: check if product has attribute
I'm trying to append text to products that cointain the attribute "pa_sprog" value "dansk"

I am working from this post
this is what I have so far:

add_action( 'woocommerce_before_add_to_cart_form', 'flag1' );
function flag1() {
    $product = wc_get_product( $product_id );

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog="dansk" ){
        echo '
"Dansk!"
';
    } else {
        // Engelsk
    }
}
```

答:
Give it a try this way, I left the code to debug, so that you can view the WC_Product_Attribute Object in detail. Afterwards you can safely remove this

function flag1() {
    global $product;

    // for debug purposes, place in comment tags or delete this code
    $product_attributes = $product->get_attributes();
    echo '```', print_r($product_attributes, 1), '```';

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog == "dansk" ) {
        echo '
Dansk!
';
    } else {
        echo '
Engelsk!
';
    }
}
add_action( 'woocommerce_before_add_to_cart_form', 'flag1' );
```

Body:
Give it a try this way, I left the code to debug, so that you can view the WC_Product_Attribute Object in detail. Afterwards you can safely remove this

function flag1() {
    global $product;

    // for debug purposes, place in comment tags or delete this code
    $product_attributes = $product->get_attributes();
    echo '<pre>', print_r($product_attributes, 1), '</pre>';

    // Get the product attribute value
    $sprog = $product->get_attribute('pa_sprog');

    // if product has attribute 'sprog' value(s)
    if( $sprog == "dansk" ) {
        echo '<div class="">Dansk!</div>';
    } else {
        echo '<div class="">Engelsk!</div>';
    }
}
add_action( 'woocommerce_before_add_to_cart_form', 'flag1' );


问:
Uploaded images with malicious code in Amazon S3
I have a custom php web application where users will be able to upload images.
I know that there is a security concern with image files as a hacker can add malicious code to them and trigger them through the url of the image file.

So I'm no longer storing images in the web server and uploading them directly into Amazon S3. I was wondering if it is still possible for a hacker to achieve the same results with a malicious image even if the image files are stored in a completely separate place like Amazon S3.

答:
If you upload files into S3 then there would be no need to worry about the server side exploits like RCE as it is an object storage which won't be executed, but you need to take care of client side vulnerabilities like XSS...
i.e., even in your case of image upload, attacker cannot harm the server side setup directly by exploiting Unrestricted file upload but he can embed client side script into the image and exploit... as @dy10 mentioned, setting the proper content-type would help...</p>


问:
Wrapping text around an image with indentation and justify
I want to make something like this.

The problem is that I need the p to have an indentation and justify as alignment.

I could float the image to the left and then set the display of h3 and p to inline but then I am unable to set an indentation and more importantly to make the text justify.

答:
One more way to do the same. It can also use the shape-outside property to control float text around an image.

.wrapper {
  width: 35rem;
}

h3 {
  line-height: 2rem;
  margin-bottom: -0.6rem;
}

p {
  text-align: justify;
  text-indent: 2em;
}

img {
  width: 11rem;
  height: 11rem;
  float: left;
  margin: 0 2rem 1rem 0;
}

.shape {
  shape-outside: inset(0 0 0 0);
}

.circle {
  shape-outside: circle(50%);
}```

  <img class='shape' src="data:image/jpeg;base64,[encoded data, 11528 characters]"
    alt="bulb">

This is a heading

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
    in culpa qui officia deserunt mollit anim id est laborum. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  <img class='circle' src="data:image/jpeg;base64,[encoded data, 11528 characters]"
    alt="bulb">

CSS Shape-Outside

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
    in culpa qui officia deserunt mollit anim id est laborum. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

```

Body:
One more way to do the same. It can also use the shape-outside property to control float text around an image.

.wrapper {
  width: 35rem;
}

h3 {
  line-height: 2rem;
  margin-bottom: -0.6rem;
}

p {
  text-align: justify;
  text-indent: 2em;
}

img {
  width: 11rem;
  height: 11rem;
  float: left;
  margin: 0 2rem 1rem 0;
}

.shape {
  shape-outside: inset(0 0 0 0);
}

.circle {
  shape-outside: circle(50%);
}

<div class='wrapper'>
  <img class='shape' src="data:image/jpeg;base64,[encoded data, 11528 characters]"
    alt="bulb">
  <h3>This is a heading</h3>
  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
    in culpa qui officia deserunt mollit anim id est laborum. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<hr>
<div class='wrapper'>
  <img class='circle' src="data:image/jpeg;base64,[encoded data, 11528 characters]"
    alt="bulb">
  <h3>CSS Shape-Outside</h3>
  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt
    in culpa qui officia deserunt mollit anim id est laborum. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>


问:
How to generate uniformly distributed random numbers between 0 and 1 in a C code using OpenMP?
I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. In addition, the random number distributions need to be different every time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences? Will the sequences be different every time the code is called? What is the correct way of doing this? The following code has each thread generating 5 samples but in an actual run it will be order of millions.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}
</code>```

答:
You don't mention what OS you're using, but if it's Linux or a POSIX compliant system, there's erand48() for thread-safe generation of random numbers uniformly distributed in the range [0.0, 1.0). It uses a 48-bit seed that's passed as an argument. Generating the initial seed can be done in a number of ways. OpenBSD and Linux have getentropy(), BSDs have arc4random_buf(), you can read from the /dev/urandom special file on many OSes, or do something like you're currently using with time, pid, etc. I'd suggest a higher resolution timer than time(), though - clock_gettime() is a good source.

An example:

```<code>#include <errno.h>
#include <fcntl.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
#pragma omp parallel for
  for (int i = 0; i < 4; i++) {
    unsigned short xi[3]; // PRNG state variable

#if 0
    // OpenBSD 5.6+/Linux kernel 3.17+ and glibc 2.25+
    if (getentropy(xi, sizeof xi) < 0) {
      perror("getentropy");
      exit(EXIT_FAILURE);
    }
#else
    // Read from /dev/urandom
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd < 0) {
      perror("open /dev/urandom");
      exit(EXIT_FAILURE);
    }
    if (read(fd, xi, sizeof xi) != sizeof xi) {
      perror("read");
      exit(EXIT_FAILURE);
    }
    close(fd);
#endif

    for (int n = 0; n < 4; n++) {
      printf("Thread %d random number %f\n", omp_get_thread_num(), erand48(xi));
    }
  }

  return 0;
}
</code>```

Body:
I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. In addition, the random number distributions need to be different every time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences? Will the sequences be different every time the code is called? What is the correct way of doing this? The following code has each thread generating 5 samples but in an actual run it will be order of millions.

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}

Body:
You don't mention what OS you're using, but if it's Linux or a POSIX compliant system, there's erand48() for thread-safe generation of random numbers uniformly distributed in the range [0.0, 1.0). It uses a 48-bit seed that's passed as an argument. Generating the initial seed can be done in a number of ways. OpenBSD and Linux have getentropy(), BSDs have arc4random_buf(), you can read from the /dev/urandom special file on many OSes, or do something like you're currently using with time, pid, etc. I'd suggest a higher resolution timer than time(), though - clock_gettime() is a good source.

An example:

#include <errno.h>
#include <fcntl.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
#pragma omp parallel for
  for (int i = 0; i < 4; i++) {
    unsigned short xi[3]; // PRNG state variable

#if 0
    // OpenBSD 5.6+/Linux kernel 3.17+ and glibc 2.25+
    if (getentropy(xi, sizeof xi) < 0) {
      perror("getentropy");
      exit(EXIT_FAILURE);
    }
#else
    // Read from /dev/urandom
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd < 0) {
      perror("open /dev/urandom");
      exit(EXIT_FAILURE);
    }
    if (read(fd, xi, sizeof xi) != sizeof xi) {
      perror("read");
      exit(EXIT_FAILURE);
    }
    close(fd);
#endif

    for (int n = 0; n < 4; n++) {
      printf("Thread %d random number %f\n", omp_get_thread_num(), erand48(xi));
    }
  }

  return 0;
}


问:
Visualization of zero values and small values in the same histogram in MATLAB
I want to plot a single histogram where some of the x-values are 0, while the other x-values range between 0.002 and 0.008. The problem is that even by specifying the xlim, the columns overlap but of course they should not.

```<code>x1 = zeros (3000,1);
hist(x1);xlim([0 0.008]);
h = findobj(gca,'Type','patch');
set(h,'Facecolor',[1 0 0]);
set(h,'FaceAlpha',0.7);
hold on
n = 3000;
R = [0.002 0.008];
x2 = rand(n,1)*range(R)+min(R);
hist(x2);xlim([0 1])
h1 = findobj(gca,'Type','patch');
set(h1,'facealpha',.3)
</code>```

答:
Do you really need to use two histograms?

```<code>hist([x1; x2])
</code>```

Body:
I want to plot a single histogram where some of the x-values are 0, while the other x-values range between 0.002 and 0.008. The problem is that even by specifying the xlim, the columns overlap but of course they should not.

x1 = zeros (3000,1);
hist(x1);xlim([0 0.008]);
h = findobj(gca,'Type','patch');
set(h,'Facecolor',[1 0 0]);
set(h,'FaceAlpha',0.7);
hold on
n = 3000;
R = [0.002 0.008];
x2 = rand(n,1)*range(R)+min(R);
hist(x2);xlim([0 1])
h1 = findobj(gca,'Type','patch');
set(h1,'facealpha',.3)

Body:
Do you really need to use two histograms?

hist([x1; x2])


问:
Binding local variable
I have read the answers for similar question but I still don't know how to do what I want.
I have:

public partial class DbDataToEdit : Window
{
    public SomeDBDataSet.SomeTableRow RowToModify {get;set;}
    public DbDataToEdit(SomeDBDataSet.SomeTableRow row)
    {
           RowToModify = row;
           .....
```

and
fields in XAML: TextBlock, and DatePicker which i want to bind with fields in "SomeTableRow"(someNumber , someDate). SomeTableRow is a some data[one row] from DB.

Is it possible?

optionally: How to connect elements from one row of the database table to the appropriate fields?

答: Yes, it is possible, you can set the source of a UI element by setting its DataContext. With this approach you can bind to almost anything. However, without seeing more details, I cannot advise much further!</p>

Title: Binding local variable

Body:
I have read the answers for similar question but I still don't know how to do what I want.
I have:

public partial class DbDataToEdit : Window
{
    public SomeDBDataSet.SomeTableRow RowToModify {get;set;}
    public DbDataToEdit(SomeDBDataSet.SomeTableRow row)
    {
           RowToModify = row;
           .....

and
fields in XAML: TextBlock, and DatePicker which i want to bind with fields in "SomeTableRow"(someNumber , someDate). SomeTableRow is a some data[one row] from DB.

Is it possible?

optionally: How to connect elements from one row of the database table to the appropriate fields?


问:
How to set top bottom and right side content using flexbox css
I am new in flexbox. I have try to set top , bottom and right side content. See Demo

But I need to set in mobile size like image.

Left side and right side is not same height.

Can we set like image mention above or any other type to set in mobile and tablet screen size

.main {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.left {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}

.center {
  background: #ddd;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 50%;
  flex: 0 0 50%;
  max-width: 50%;
}

.right {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="left">
    <ul>
      <li>1 height not fix</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
      Large content
    </p>
    <p>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
  <div class="right">
    <ul>
      <li>1 height not fix</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
</div></code>```

答:
I simply add media queries to your css. You can modify it for various screen and set width, position etc for each screen.

.main{
  display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
-ms-flex-wrap: wrap;
    flex-wrap: wrap;
}
.left{
  background:#f00;
}
.center{
  background:#ddd;
}
.right{
  background:#f00;
  }

  @media screen and (min-width: 980px) {
.left{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 25%;
    flex: 0 0 25%;
    max-width: 25%;
}
.center{
    -webkit-box-flex: 0;
    -ms-flex: 0 0 50%;
    flex: 0 0 50%;
    max-width: 50%;
}
.right{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 25%;
    flex: 0 0 25%;
    max-width: 25%;
  }

}

@media screen and (max-width: 980px) {
 .left{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.center{
    -webkit-box-flex: 0;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.right{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="left">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
    Large content
    </p>
    <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
  <div class="right">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
</div></code>```

EDIT: The best solution for your problem is to Use css grid: Flexbox is One Dimensional, Grid is Two Dimensional

.main{
 display: grid;
  grid-gap: 10px;
}

.left { grid-area: left; }
.center { grid-area: main; }
.right { grid-area: right; }

.left{
  background:#f00;
  padding: 10px;
}
.center{
  background:#ddd;
    padding: 10px;

}
.right{
  background:#f00;
    padding: 10px;

  }

  @media screen and (min-width: 980px) {
.main{
 display: grid;
  grid-template-areas:'left  main main  right'
          'left  main main  right';
  grid-gap: 10px;
}
}

@media screen and (max-width: 980px) {
 .main{
  grid-template-areas:'left  main main '
          'right  main main ';
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="left">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
    Large content
    </p>
    <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
  <div class="right">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
</div></code>```

Body:
I am new in flexbox. I have try to set top , bottom and right side content. See Demo

But I need to set in mobile size like image.

Left side and right side is not same height.

Can we set like image mention above or any other type to set in mobile and tablet screen size

.main {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.left {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}

.center {
  background: #ddd;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 50%;
  flex: 0 0 50%;
  max-width: 50%;
}

.right {
  background: #f00;
  -webkit-box-flex: 0;
  -ms-flex: 0 0 25%;
  flex: 0 0 25%;
  max-width: 25%;
}

1 height not fix

2

3

      Large content

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
      survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.

1 height not fix

2

3

Body:
I simply add media queries to your css. You can modify it for various screen and set width, position etc for each screen.

.main{
  display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
-ms-flex-wrap: wrap;
    flex-wrap: wrap;
}
.left{
  background:#f00;
}
.center{
  background:#ddd;
}
.right{
  background:#f00;
  }

  @media screen and (min-width: 980px) {
.left{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 25%;
    flex: 0 0 25%;
    max-width: 25%;
}
.center{
    -webkit-box-flex: 0;
    -ms-flex: 0 0 50%;
    flex: 0 0 50%;
    max-width: 50%;
}
.right{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 25%;
    flex: 0 0 25%;
    max-width: 25%;
  }

}

@media screen and (max-width: 980px) {
 .left{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.center{
    -webkit-box-flex: 0;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
}
.right{
   -webkit-box-flex: 0;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
    max-width: 100%;
  }
}

<div class="main">
  <div class="left">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
    Large content
    </p>
    <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
  <div class="right">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
</div>

EDIT: The best solution for your problem is to Use css grid: Flexbox is One Dimensional, Grid is Two Dimensional

.main{
 display: grid;
  grid-gap: 10px;
}

.left { grid-area: left; }
.center { grid-area: main; }
.right { grid-area: right; }

.left{
  background:#f00;
  padding: 10px;
}
.center{
  background:#ddd;
    padding: 10px;

}
.right{
  background:#f00;
    padding: 10px;

  }

  @media screen and (min-width: 980px) {
.main{
 display: grid;
  grid-template-areas:'left  main main  right'
          'left  main main  right';
  grid-gap: 10px;
}
}

@media screen and (max-width: 980px) {
 .main{
  grid-template-areas:'left  main main '
          'right  main main ';
}
}

<div class="main">
  <div class="left">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
  <div class="center">
    <p>
    Large content
    </p>
    <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </p>
  </div>
  <div class="right">
    <ul>
    <li>1 height not fix</li>
    <li>2</li>
    <li>3</li>
    </ul>
  </div>
</div>


问:
HTTP 1.1 Gateway Timeout 504
I have developed an MERN Application so we have ReactJS as frontend and backend as NodeJS. The Application is working on Heroku server.

But now i am scaling things up and I have moved to AWS. I have deployed the frontend in S3 and using it as Static Web Hosting. I have deployed backend in EC2 instance and it is running on NGINX.

We have few resources required such as Camera to be accessed from the browser so I have added SSL certificates on both ends. In EC2 I have used loadbalancer to add SSL certificate.

Now the issue is when ever i make an API call from frontend to backend i am getting GATEWAY TIMEOUT 504 exception.

Frontend : https://portal.visitplan.in

Backend: https://api.visitplan.in

Can you help us out in resolving this? or is this the right way to deploy the application? Is there any other way?

答:
Ok, first of all, your certificate is invalid, you might wanna check on that.

I might know what is happen even thought you are not providing any code.

You might have deployed the frontend and the backend but you might have forgotten to change the request, however, the only request I can make from the portal is the login and this is the console response:

Access to XMLHttpRequest at 'https://api.visitplan.in/account/login' from origin 'https://portal.visitplan.in' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

You need to add the header Access-Control-Allow-Originas stated here. CORS header 'Access-Control-Allow-Origin' missing

One of those reasons might be the problem.

Title: HTTP 1.1 Gateway Timeout 504


问:
How to remove ListView's add item animation?
I have a ListView and I edited its ItemContainerStyle to modify some style but I don't know how to remove that annoying animation when you add an item.

With an ItemsControl, when you add a new item, it appears instantly, without any animation.

With ListView, the item takes a while and then, it starts an animation to show up.

I just want to remove that add animation and when I click on Add item it appears instantly, no extra stuff.

I think that it should belong to ItemContainerStyle but even I commented out all visualstate animations and is still there. I'm missing something out.

答:
Beside the suggested ItemContainerTransitions removal, there's an additional animation you might want to remove.

In the ListViewItem template there's a transform animation called ContentPresenterTranslateTransform, it slides the item content into place. You can just remove that animation from template's storyboards.


问:
custom view button click it's not working
this is my code.

i registered the button action by defining the view in xib.
btn is connected to dismissButtonClick but It didn't work when I clicked the button.
So I tried a way to override touchesBegan Func and It didnt' work.

My third attempt was gesture registration.
It also didn't work....

There is no way for me anymore.

plz help me guys.

```<code>@objc public class CustomView : UIView  {
    static let xibName = "xibName"

    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var viewTopAnchor: NSLayoutConstraint?
    @IBOutlet weak var btn: UIButton?
    var completion: (() -> Void)?

    var parentView : UIViewController!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    public static func getInstance(_ vc : UIViewController, _ completion : (() -> Void)? ) -> UIView {

        let view = Bundle.main.loadNibNamed(CustomView.xibName, owner: self, options: nil)?.first as! CustomView

        view.parentView = vc
        view.completion = completion

        view.initUI()

        return view
    }

    func initUI() {

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(CustomView.dismiss))
        mainView.addGestureRecognizer(tapGestureRecognizer)

        btn?.addTarget(self, action: #selector(CustomView.dismiss), for: .touchUpInside)

        parentView.view.addSubview(self)

        self.translatesAutoresizingMaskIntoConstraints = false

        self.leadingAnchor.constraint(equalTo: parentView.view.leadingAnchor, constant: 0).isActive = true
        self.trailingAnchor.constraint(equalTo: parentView.view.trailingAnchor, constant: 0).isActive = true
        viewTopAnchor?.constant = -150
        viewTopAnchor?.isActive = true

        setNeedsDisplay()
        layoutIfNeeded()

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 ) {
            self.mainView.isHidden = false
            self.showAnimation()
        }
}

    //top down anim
    private func showAnimation(){
        DispatchQueue.main.asyncAfter(deadline: .now() ) {
            self.viewTopAnchor?.constant = 0
            UIView.animate(withDuration: 0.5) {
                self.layoutIfNeeded()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.dismissAnimation(self.duration)
                }
            }
        }
    }

    private func dismissAnimation(_ duration : Double){
        DispatchQueue.main.asyncAfter(deadline: .now() + duration - 0.5) {

            self.viewTopAnchor?.constant = -150
            UIView.animate(withDuration: 1) {
                self.layoutIfNeeded()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.completion?()
                    self.removeFromSuperview()
                }
            }
        }
    }

    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchBegan") // not called
        let touch = touches.first
    }

    public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchBegan") // not called
        self.completion?()
        self.btn?.removeTarget(self, action: #selector(dismissButtonClick), for: .touchUpInside)
        self.removeFromSuperview()
    }

    @objc
    func dismiss(){
        print("dismiss") // not called
        self.completion?()
        self.removeFromSuperview()
    }
    @IBAction func dismissButtonClick(_ sender: Any) {
        print("dismissButtonClick") // not called
        self.completion?()
        self.removeFromSuperview()
    }

}
</code>```

```<code>CustomView.getInstance(view, completion)
</code>```

答:
```<code>    I have created one custom view with one button and wrote method which is called on button click. Please check it out it might be helpful in your case.

https://github.com/bhoomik/Custom_View_Demo

    Custom View Code

    //
    //  CustomView.swift
    //  Temp
    //
    //  Created by Jaimin Modi on 19/02/20.
    //  Copyright © 2020 Jaimin Modi. All rights reserved.
    //

        import UIKit

    //
//  CustomView.swift
//  Temp
//
//

import UIKit

class CustomView: UIView {

    static let xibName = "CustomView"

    @IBOutlet weak var viewTopAnchor: NSLayoutConstraint?
    @IBOutlet weak var btn: UIButton?
    var completion: (() -> Void)?

    var parentView : UIViewController!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    public static func getInstance(_ vc : UIViewController, _ completion : (() -> Void)? ) -> UIView {

        let view = Bundle.main.loadNibNamed(CustomView.xibName, owner: self, options: nil)?.first as! CustomView
        view.parentView = vc
        view.completion = completion
       // view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 120)
        view.initUI()

        return view
    }

    func initUI() {

      //  let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(CustomView.dismiss))
       // mainView.addGestureRecognizer(tapGestureRecognizer)

        //btn?.addTarget(self, action: #selector(CustomView.dismiss), for: .touchUpInside)

        parentView.view.addSubview(self)

        self.translatesAutoresizingMaskIntoConstraints = false

       // self.leadingAnchor.constraint(equalTo: parentView.view.leadingAnchor, constant: 0).isActive = true
      //  self.trailingAnchor.constraint(equalTo: parentView.view.trailingAnchor, constant: 0).isActive = true
     //   viewTopAnchor?.constant = -150

     //   viewTopAnchor?.constant = 300
      //  viewTopAnchor?.isActive = true

        let guide = self.parentView.view.safeAreaLayoutGuide

        NSLayoutConstraint.activate(
            [self.leftAnchor.constraint(equalTo: self.parentView.view.leftAnchor),
             self.heightAnchor.constraint(equalToConstant: 50),
             self.rightAnchor.constraint(equalTo: self.parentView.view.rightAnchor),
             // segmentedControl!.topAnchor.constraint(equalTo: view.topAnchor, constant: 80)]
                self.topAnchor.constraint(equalTo: guide.topAnchor, constant: 0)]

        )

        setNeedsDisplay()
        layoutIfNeeded()

       /* DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 ) {
            self.mainView.isHidden = false
            self.showAnimation()
        }*/

    }

    @IBAction func dismissButtonClick(_ sender: Any) {
        print("dismissButtonClick") // not called
       // self.completion?()
       // self.removeFromSuperview()
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

    UIView Controller code
    :

        import UIKit

        extension UIView {
            class func fromNib<T: UIView>() -> T {
                return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
            }
        }

class ViewController: UIViewController {

    @IBOutlet weak var viewNav :  CustomView!

    var completion: (() -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()

        /*viewNav  = UIView.fromNib()
        viewNav.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: viewNav.frame.size.height)

        self.view.addSubview(viewNav)*/

        CustomView.getInstance(self, completion)

        // Do any additional setup after loading the view.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

  [1]: https://github.com/bhoomik/Custom_View_Demo
</code>```

Body:
this is my code.

i registered the button action by defining the view in xib.
btn is connected to dismissButtonClick but It didn't work when I clicked the button.
So I tried a way to override touchesBegan Func and It didnt' work.

My third attempt was gesture registration.
It also didn't work....

There is no way for me anymore.

plz help me guys.

@objc public class CustomView : UIView  {
    static let xibName = "xibName"

    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var viewTopAnchor: NSLayoutConstraint?
    @IBOutlet weak var btn: UIButton?
    var completion: (() -> Void)?

    var parentView : UIViewController!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    public static func getInstance(_ vc : UIViewController, _ completion : (() -> Void)? ) -> UIView {

        let view = Bundle.main.loadNibNamed(CustomView.xibName, owner: self, options: nil)?.first as! CustomView

        view.parentView = vc
        view.completion = completion

        view.initUI()

        return view
    }

    func initUI() {

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(CustomView.dismiss))
        mainView.addGestureRecognizer(tapGestureRecognizer)

        btn?.addTarget(self, action: #selector(CustomView.dismiss), for: .touchUpInside)

        parentView.view.addSubview(self)

        self.translatesAutoresizingMaskIntoConstraints = false

        self.leadingAnchor.constraint(equalTo: parentView.view.leadingAnchor, constant: 0).isActive = true
        self.trailingAnchor.constraint(equalTo: parentView.view.trailingAnchor, constant: 0).isActive = true
        viewTopAnchor?.constant = -150
        viewTopAnchor?.isActive = true

        setNeedsDisplay()
        layoutIfNeeded()

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5 ) {
            self.mainView.isHidden = false
            self.showAnimation()
        }
}

    //top down anim
    private func showAnimation(){
        DispatchQueue.main.asyncAfter(deadline: .now() ) {
            self.viewTopAnchor?.constant = 0
            UIView.animate(withDuration: 0.5) {
                self.layoutIfNeeded()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.dismissAnimation(self.duration)
                }
            }
        }
    }

    private func dismissAnimation(_ duration : Double){
        DispatchQueue.main.asyncAfter(deadline: .now() + duration - 0.5) {

            self.viewTopAnchor?.constant = -150
            UIView.animate(withDuration: 1) {
                self.layoutIfNeeded()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    self.completion?()
                    self.removeFromSuperview()
                }
            }
        }
    }

    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchBegan") // not called
        let touch = touches.first
    }

    public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("touchBegan") // not called
        self.completion?()
        self.btn?.removeTarget(self, action: #selector(dismissButtonClick), for: .touchUpInside)
        self.removeFromSuperview()
    }

    @objc
    func dismiss(){
        print("dismiss") // not called
        self.completion?()
        self.removeFromSuperview()
    }
    @IBAction func dismissButtonClick(_ sender: Any) {
        print("dismissButtonClick") // not called
        self.completion?()
        self.removeFromSuperview()
    }

}

CustomView.getInstance(view, completion)


问:
ListViewn not scrollable by swipe
I have a ListView inside a ScrollView, and I can scroll the contents of he list via my optical mouse button on my HTC Wildfire - it's like a physical cursor up/down thing. So far so good. The bad thing is that I cannot scroll the list by the normal touch/swipe that normally works on this kind of lists.

What could be wrong?

My layout is like this:

```<code><?xml version="1.0" encoding="utf-8"?>

  <ScrollView android:id="@+id/scroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <ListView android:id="@+id/MessageList"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

  </ScrollView>
</code>```

And some Java code to initialize the list:

```<code>public class MorseIt extends Activity {

    private ListView lv1;
    private String lv_arr[]={"Red","Green","Blue","Purple","White","Black","Pink","Cyan","Magenta"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv1=(ListView)findViewById(R.id.MessageList);
     lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));

    }
}
</code>```

答: This is a very common problem. The ListView itself will scroll for you, using your current layout is against the purpose of the ListView. Either drop the ListView and use a regular LinearLayout, or drop the ScrollView and use the ListView properly. Also see this question.

Title: ListViewn not scrollable by swipe

Body:
I have a ListView inside a ScrollView, and I can scroll the contents of he list via my optical mouse button on my HTC Wildfire - it's like a physical cursor up/down thing. So far so good. The bad thing is that I cannot scroll the list by the normal touch/swipe that normally works on this kind of lists.

What could be wrong?

My layout is like this:

<?xml version="1.0" encoding="utf-8"?>

  <ScrollView android:id="@+id/scroll"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    xmlns:android="http://schemas.android.com/apk/res/android">

        <ListView android:id="@+id/MessageList"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

  </ScrollView>

And some Java code to initialize the list:

public class MorseIt extends Activity {

    private ListView lv1;
    private String lv_arr[]={"Red","Green","Blue","Purple","White","Black","Pink","Cyan","Magenta"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv1=(ListView)findViewById(R.id.MessageList);
     lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));

    }
}


问:
Oracle EBS can't load applet on firefox
i use IE in common for accessing oracle ebs..
but sometimes i'd like to use firefox for doing job in oracle ebs..

what should i do to makes my firefox able to load ebs form (the web-based menu is opened but not with the forms)

答: We start it using Internet Explorer 11 on a windows 7 pc. It requires an old java version and a installed plugin from oracle, but it get started and can open forms</p>

Title: Oracle EBS can't load applet on firefox


答:
I guess that you are aware that media queries need to be used in order to apply different behavior on different screen sizes, and that the real problem is how to position the
 tags.

There are many different solutions, here is one:

First, you need to shift center section to be the first on top, so you can apply float property on smaller screens. In order for this to work, you need to define flex order property for bigger screens. If you are not that familiar with float property, you'll probably want to read about clearfix here: clearfix. Float 'rips' content out of the regular web page flow and clearfix restores it.

Here is an example for big screens: jsfiddle
and here is an example for smaller ones: jsfiddle

Title: How to set top bottom and right side content using flexbox css

Body:
I guess that you are aware that media queries need to be used in order to apply different behavior on different screen sizes, and that the real problem is how to position the <div> tags.

There are many different solutions, here is one:

First, you need to shift center section to be the first on top, so you can apply float property on smaller screens. In order for this to work, you need to define flex order property for bigger screens. If you are not that familiar with float property, you'll probably want to read about clearfix here: clearfix. Float 'rips' content out of the regular web page flow and clearfix restores it.

Here is an example for big screens: jsfiddle
and here is an example for smaller ones: jsfiddle


问:
variable expected when trying to change value of a variable
I'm a student learning java and for this code I'm writing for a homework assignment, cant use ternary operators or any if/switch statments, or add a variable and need to change the value of one of my vairables to one from 0

its a toggle method so needs to change from 0 and 1 when called

```<code>firstSwitchState = firstSwitchState + firstSwitchState % 2 = 0;
</code>```

答:
You can use Increment Operator in the following way</p>

```<code>firstSwitchState = ++firstSwitchState % 2;
</code>```

Body:
I'm a student learning java and for this code I'm writing for a homework assignment, cant use ternary operators or any if/switch statments, or add a variable and need to change the value of one of my vairables to one from 0

its a toggle method so needs to change from 0 and 1 when called

firstSwitchState = firstSwitchState + firstSwitchState % 2 = 0;

Body:
You can use Increment Operator in the following way

firstSwitchState = ++firstSwitchState % 2;


问:
Count the number of times the app was opened in xcode
I want to know if someone know how I can count the number of times that my app has been opened.
NSUserDefalte or something...
Where should I put the var and where should it be initiated to 0?</p>

答:
Swift version - I am using this for SKStoreReviewController.requestReview()

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    setupStart()
    return true
}

private func setupStart()
{
    setAppStartsInfos()
}

private func setAppStartsInfos()
{
    Helper.checkForStoreReviewAppStarted = Helper.uds.integer(forKey: Helper.udKeyAppRunned) + 1
    Helper.udStoreValue(key: Helper.udKeyAppRunned, value: Helper.checkForStoreReviewAppStarted)
}
</code>```

Helper class

```<code>static var checkForStoreReviewUse = true
static let checkForStoreReviewAppStartedLimit: Int = 5
static var checkForStoreReviewAppStarted: Int = 0
static let uds = UserDefaults.standard
static var udKeyAppRunned: String
{
    get
    {
        return "\(getAppVersionClean())_udKeyAppRunned"
    }
}

static func udStoreValue(key: String, value: Any)
{
    return uds.set(value, forKey: key)
}

static func udStoredValue(key: String) -> Any?
{
    return uds.value(forKey: key)
}

static func udStoredValueExists(key: String) -> Bool
{
    return uds.value(forKey: key) != nil
}

static func getAppVersionClean() -> String
{
    if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    {
        return version
    }
    else
    {
        return String()
    }
}

static func checkForStoreReview()
{
    if checkForStoreReviewUse
    {
        if checkForStoreReviewAppStarted < checkForStoreReviewAppStartedLimit
        {
            // STOP checking for this app-run
            checkForStoreReviewUse = false
        }
        else
        {
            // STOP checking for this app-run
            checkForStoreReviewUse = false
            // Request review
            SKStoreReviewController.requestReview()
        }
    }
}
</code>```

Body:
Swift version - I am using this for SKStoreReviewController.requestReview()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    setupStart()
    return true
}

private func setupStart()
{
    setAppStartsInfos()
}

private func setAppStartsInfos()
{
    Helper.checkForStoreReviewAppStarted = Helper.uds.integer(forKey: Helper.udKeyAppRunned) + 1
    Helper.udStoreValue(key: Helper.udKeyAppRunned, value: Helper.checkForStoreReviewAppStarted)
}

Helper class

static var checkForStoreReviewUse = true
static let checkForStoreReviewAppStartedLimit: Int = 5
static var checkForStoreReviewAppStarted: Int = 0
static let uds = UserDefaults.standard
static var udKeyAppRunned: String
{
    get
    {
        return "\(getAppVersionClean())_udKeyAppRunned"
    }
}

static func udStoreValue(key: String, value: Any)
{
    return uds.set(value, forKey: key)
}

static func udStoredValue(key: String) -> Any?
{
    return uds.value(forKey: key)
}

static func udStoredValueExists(key: String) -> Bool
{
    return uds.value(forKey: key) != nil
}

static func getAppVersionClean() -> String
{
    if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    {
        return version
    }
    else
    {
        return String()
    }
}

static func checkForStoreReview()
{
    if checkForStoreReviewUse
    {
        if checkForStoreReviewAppStarted < checkForStoreReviewAppStartedLimit
        {
            // STOP checking for this app-run
            checkForStoreReviewUse = false
        }
        else
        {
            // STOP checking for this app-run
            checkForStoreReviewUse = false
            // Request review
            SKStoreReviewController.requestReview()
        }
    }
}


问:
Migrating from myorg.visualstudio.com to dev.azure.com/myorg
My organization still uses the "old" url when interacting with Azure DevOps: myorg.visualstudio.com.
The options to switch over to the new url has been available for some time in organization settings, but we've not made the move yet.

Today, for the first time, I saw a warning advertising that a feature was only available on the new Url

So I'm thinking it's about time I start moving my organization and push our users to use the new url.
I can see that both the old and new url can be used to access Azure DevOps in a browser, and according to this question: Switch existing organizations to use the new domain name URL, both will continue to works once I flip the switch.

For our non-developer users that only uses the web interface of Azure DevOps (Task management, wiki, etc) this is going to be easy as they can slowly adjust over time to use the new Url.

But I have some concerns for our developers, that I haven't been able to find any answers to.
1. What about Git remote urls?
2. What about Build Agents' connection to Azure DevOps?

I've tested cloning from git, replacing myorg.visualstudio.com with dev.azure.com/myorg in the url, which failed.
I've not yet tested connecting a build agent to Azure DevOps using the new url.

Will I be able to slowly migrate those two things aswell?
Or will I have to have set a date to flip the switch, and instruct our developers to ensure no builds are running, backup local uncommited code changes, and make the appropiate changes at that time?

答:
What about Git remote urls?

According to this article,  the name change from VSTS to Azure DevOps changed the base URL from accountname.visualstudio.com to dev.azure.com/accountname, and this broke the build., the change of organization would affect the Git remote commands.

About the solution mentioned in the article and your test, what about replace myorg.visualstudio.com with myorg:{token}/dev.azure.com or {token}@dev.azure.com/myorg?

What about Build Agents' connection to Azure DevOps?

According to this thread, the conenction will be lost: when you change the URL they still configure to the old one and they can't connect, you must re-configure them to the new URL.


问:
How to retrieve more than 1000 rows from Parse.com?
I have been using Parse to retrieve a data for a list view. Unfortunately they limit requests to 100 by default to a 1000 max. I have well over that 1000 max in my class. I found a link on the web which shows a way to do it on iOS but how would you do it on Android? Web Link

I am currently adding all the data into a arraylist in a loop until all items are complete (100) then adding them to the list

答:
**EDIT : Below answer is redundant because open source parse server doesn't put any limit on max rows to be fetched

```<code> //instead of var result = await query.find();
    query.limit(99999999999);//Any value greater then max rows you want
    var result = await query.find();**
</code>```

Original answer:

Javascript / Cloud Code

Here's a clean way working for all queries

```<code>async function fetchAllIgnoringLimit(query,result) {
  const limit = 1000;
  query.limit(limit);
  query.skip(result.length);

  const results = await query.find();
  result = result.concat(results)

  if(results.length === limit) {
    return await fetchAllIgnoringLimit(query,result );
  } else {
    return result;
  }

}
</code>```

And here's how to use it

```<code>var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
//instead of var result = await query.find();
var result = await fetchAllIgnoringLimit(query,new Array());
console.log("got "+result.length+" rows")
</code>```

Body:
**EDIT : Below answer is redundant because open source parse server doesn't put any limit on max rows to be fetched

 //instead of var result = await query.find();
    query.limit(99999999999);//Any value greater then max rows you want
    var result = await query.find();**

Original answer:

Javascript / Cloud Code

Here's a clean way working for all queries

async function fetchAllIgnoringLimit(query,result) {
  const limit = 1000;
  query.limit(limit);
  query.skip(result.length);

  const results = await query.find();
  result = result.concat(results)

  if(results.length === limit) {
    return await fetchAllIgnoringLimit(query,result );
  } else {
    return result;
  }

}

And here's how to use it

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
//instead of var result = await query.find();
var result = await fetchAllIgnoringLimit(query,new Array());
console.log("got "+result.length+" rows")


问:
Short IF - ELSE statement
I'm trying to make my code more readable, so I decided to use some short IF statements.

Here's my code which doesn't work ("not a statement"):

```<code>jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false);
</code>```

What's wrong with this? Needs brackets? Where?

答:
You can do it as simple as this, I did it in react hooks :

```<code> (myNumber == 12) ? "true" : "false"
</code>```

it was equal to this long if function below :

```<code>if (myNumber == 12) {
  "true"
} else {
  "false"
}
</code>```

Hope it helps ^_^

Title: Short IF - ELSE statement

Body:
I'm trying to make my code more readable, so I decided to use some short IF statements.

Here's my code which doesn't work ("not a statement"):

jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false);

What's wrong with this? Needs brackets? Where?

Body:
You can do it as simple as this, I did it in react hooks :

 (myNumber == 12) ? "true" : "false"

it was equal to this long if function below :

if (myNumber == 12) {
  "true"
} else {
  "false"
}

Hope it helps ^_^


问:
Trouble with website login python requests
I have been trying this out for a while now, but can't seem to figure out how to login with requests on this website for a scraping project. Not sure if it might have something to do with the csrfToken..? No matter what I try it doesen't seem to work.

Any help or advice would be greatly appreciated.

Here is the script:

```<code>import requests
LOGIN_URL="https://example/user/login"
payload={'login':'username', 'password':'password'}

with requests.Session() as s:
    p = s.post(LOGIN_URL, data=payload)
    print p.text
    r = s.get('https://example.com/account/')
    print r.text
</code>```

here are the html post fields:

```<code><form method="POST" action="https://example.com/user/doConsent" id="consentForm" class="consent-form">
    <input type='hidden' name='CsrfToken' value='' />
    <input type="hidden" name="key" value="">

    <form method="POST" action="https://example.com/user/doLogin" id="loginForm" novalidate>
    <input type='hidden' name='CsrfToken' value='' />
    <input type="email" class="mb20" name="login" id="login" placeholder="Email or Profile name">

    <input type="password" class="mb30" name="password" id="password" placeholder="Password">
</code>```

答: If your ‘CsrfToken‘ is empty when you make the actual POST requests, then that's your problem. You need an actual csrf token that matches both the form and the header when you send the data.</p>

Body:
I have been trying this out for a while now, but can't seem to figure out how to login with requests on this website for a scraping project. Not sure if it might have something to do with the csrfToken..? No matter what I try it doesen't seem to work.

Any help or advice would be greatly appreciated.

Here is the script:

import requests
LOGIN_URL="https://example/user/login"
payload={'login':'username', 'password':'password'}

with requests.Session() as s:
    p = s.post(LOGIN_URL, data=payload)
    print p.text
    r = s.get('https://example.com/account/')
    print r.text

here are the html post fields:

<form method="POST" action="https://example.com/user/doConsent" id="consentForm" class="consent-form">
    <input type='hidden' name='CsrfToken' value='' />
    <input type="hidden" name="key" value="">

    <form method="POST" action="https://example.com/user/doLogin" id="loginForm" novalidate>
    <input type='hidden' name='CsrfToken' value='' />
    <input type="email" class="mb20" name="login" id="login" placeholder="Email or Profile name">

    <input type="password" class="mb30" name="password" id="password" placeholder="Password">


问:
Django: Get 10 random instances from a queryset and order them into a new queryset?
I want to create a dynamic homepage for my app that features 10 different pages/profiles of people using the site each time the home page is accessed. I know that the django SQL query for randomized query is extremely slow so I am trying to write my own method of doing this (pseudo)random sample by creating an empty list, and creating a list of random numbers and then grabbing the random nth element of the queryset and placing that into the list.  </p>

```<code>import random
profilelist = [] #create an empty list
qindex = ProfilePage.objects.filter(profileisbannedis=False) #queryset for all of possible profiles to be displayed
randlist = random.sample(xrange(qindex.count()), 10) #create a list of 10 numbers between range 0 and the size of the queryset.
#this method also does not repeat the same randomly generated number which is ideal since I don't want to feature the same profile twice
for i in randlist:
    tile = qindex[i] #for each random number created, get that element of the queryset
    profilelist.extend(tile) #place each object in the previous queryset into a new list of objects and continue extending the list for each of 10 random numbers
</code>```

<p>I can't really figure out how to do it this way since I know I get the error "object is not iterable" on the last line of the code so creating a new queryset piece by piece like this is not the proper way. How can I go about doing this/creating my random queryset made from a previous filtered queryset? </p>

答:
I prefer to shuffle the entire queryset everytime page loads and slice the first ten objects in the template.
In the views:

ids = [i.id for i in Model.objects.filter(some_field=some_variable)]
random.shuffle(ids)
shuffled = [Model.objects.get(id=i) for i in ids]
```

<p>In the template:</p>

<pre class="lang-html prettyprint-override"><code>{% for i in shuffled|slice:'10' %}

</code>```

Body:
I want to create a dynamic homepage for my app that features 10 different pages/profiles of people using the site each time the home page is accessed. I know that the django SQL query for randomized query is extremely slow so I am trying to write my own method of doing this (pseudo)random sample by creating an empty list, and creating a list of random numbers and then grabbing the random nth element of the queryset and placing that into the list.

import random
profilelist = [] #create an empty list
qindex = ProfilePage.objects.filter(profileisbannedis=False) #queryset for all of possible profiles to be displayed
randlist = random.sample(xrange(qindex.count()), 10) #create a list of 10 numbers between range 0 and the size of the queryset.
#this method also does not repeat the same randomly generated number which is ideal since I don't want to feature the same profile twice
for i in randlist:
    tile = qindex[i] #for each random number created, get that element of the queryset
    profilelist.extend(tile) #place each object in the previous queryset into a new list of objects and continue extending the list for each of 10 random numbers

I can't really figure out how to do it this way since I know I get the error "object is not iterable" on the last line of the code so creating a new queryset piece by piece like this is not the proper way. How can I go about doing this/creating my random queryset made from a previous filtered queryset?

Body:
I prefer to shuffle the entire queryset everytime page loads and slice the first ten objects in the template.
In the views:

ids = [i.id for i in Model.objects.filter(some_field=some_variable)]
random.shuffle(ids)
shuffled = [Model.objects.get(id=i) for i in ids]

In the template:

{% for i in shuffled|slice:'10' %}