问:
I want to add a new row to UITableView with the click of a Button
when I click the add button it return the error 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

```<code>import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath as IndexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count-1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
        return cell
    }

}
</code>```

I have checked my table and add button I don't know where the error is coming from

答:
This is not the proper way to add rows in a table view.
First of all you don't have to add rows in tableView(_:cellForRowAt:).

The table view data source needs to be changed in order to achieve what you want.
Since you wrote this

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}
</code>```

The table view always expect to have two rows.

Solution

So, first of all you have to return the number of the array because it tells the table view how many rows will be shown.

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return addPointTableArray.count
}
</code>```

Then, if you want to add a new row, you need to update the array before calling insertRows(at:with:):

```<code>@IBAction func addPointButton(_ sender: Any) {
    addPointTableArray.append("New element")
    addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
}
</code>```

You don't need to call beginUpdates() and endUpdates() because you're only inserting, those methods are needed for multiple manipulation.

Finally, as I said before, change the tableView(_:cellForRowAt:) to this:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath) as! AddPointCellCell
    cell.addPointTextfiedl.tag = indexPath.row
    cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: .touchUpInside)
    return cell
}
</code>```

So at the end your class would look like

```<code>import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.dataSource = self
        addPointableview.delegate = self
    }

    @IBAction func addPointButton(_ sender: Any) {
        addPointTableArray.append("New element")
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addPointTableArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        return cell
    }

}

</code>```

I suggest you to re-study how to implement a basic table view before dealing with insertion/removing.

Body:
when I click the add button it return the error 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath as IndexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count-1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
        return cell
    }

}

I have checked my table and add button I don't know where the error is coming from

Body:
This is not the proper way to add rows in a table view.
First of all you don't have to add rows in tableView(_:cellForRowAt:).

The table view data source needs to be changed in order to achieve what you want.
Since you wrote this

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}

The table view always expect to have two rows.

Solution

So, first of all you have to return the number of the array because it tells the table view how many rows will be shown.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return addPointTableArray.count
}

Then, if you want to add a new row, you need to update the array before calling insertRows(at:with:):

@IBAction func addPointButton(_ sender: Any) {
    addPointTableArray.append("New element")
    addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
}

You don't need to call beginUpdates() and endUpdates() because you're only inserting, those methods are needed for multiple manipulation.

Finally, as I said before, change the tableView(_:cellForRowAt:) to this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath) as! AddPointCellCell
    cell.addPointTextfiedl.tag = indexPath.row
    cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: .touchUpInside)
    return cell
}

So at the end your class would look like

import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.dataSource = self
        addPointableview.delegate = self
    }

    @IBAction func addPointButton(_ sender: Any) {
        addPointTableArray.append("New element")
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addPointTableArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        return cell
    }

}

I suggest you to re-study how to implement a basic table view before dealing with insertion/removing.


来源: stackexchange

问:
pouchdb-find operation is very slow
I followed the official page of pouchdb-find to search the latest entry and it works but it is slow. The debug shows:

```<code>pouchdb:find creating index +8m _design/idx-a5

pouchdb:find planning query +368ms {selector: {…}, fields: Array(7), sort}
pouchdb:find query plan +4ms {queryOpts: {…}, index: {…}, inMemoryFields: Array(1)}
</code>```

When I first run it, the query plan takes +590ms. My issue now is I need to display the result but it takes additional seconds to be returned back to me as an observable. Is it because I am creating the Index on every call (the index id is always the same tho so I am thinking it is using already existing index). How can I improve the speed it retrieves the data? I have 1000 documents with type payment and I need one.

```<code>  public getData(): Observable<any> {

    let vm: any = this;

    return new Observable(observer => {

      db.createIndex({
        index: {fields: ['paidOn']}
      }).then(function () {
        return vm.local.find({
          selector: {type: 'payment', paidOn: {$gt: null} },
          fields: ['paidOn'],
          sort: [{'paidOn' : "desc"}],
          limit : 1
        }).then(function (result) {

         observer.next(result)
         observer.complete()
        }).catch(function (err) {
          // ouch, an error
          observer.error(err);
          observer.complete();
        });;
      });

    });
  }
</code>```

then I get it :

```<code>  getData().subscribe(data=>{

    if (data['docs'] != undefined && data['docs'].length>0){

      console.log(data['docs'][0]);

    }
  })
</code>```

答:
Yeah you shouldn't recreate the index on every call if you aren't changing it. Try this.

```<code>let vm: any = this;
    vm.index = await db.createIndex({
        index: {fields: ['paidOn']}
      })
</code>```

Move this code up here into a constructor of your object or to on onInit function.

```<code>public async getData(): Promise<Observable<any>> {
    const result = await vm.local.find({
          selector: {type: 'payment', paidOn: {$gt: null} },
          fields: ['paidOn'],
          sort: [{'paidOn' : "desc"}],
          limit : 1
        });
    return new Observable(observer => {observer.next(result); observer.complete()});
  }
</code>```

Although now that I'm looking at your code. You are returning an observable to get a data then immediately completing that same observable. You should keep the same observable and just use the .next() method when you want update the data or refactor this to just return a promised result and not even worry about using an observable. I'm not super clear on your use case, so I can't be certain about what is best for your situation.

Edit: Async functions return promises so I fixed return type

ContentLicense: CC BY-SA 4.0

Title: pouchdb-find operation is very slow

Body:
I followed the official page of pouchdb-find to search the latest entry and it works but it is slow. The debug shows:

pouchdb:find creating index +8m _design/idx-a5

pouchdb:find planning query +368ms {selector: {…}, fields: Array(7), sort}
pouchdb:find query plan +4ms {queryOpts: {…}, index: {…}, inMemoryFields: Array(1)}

When I first run it, the query plan takes +590ms. My issue now is I need to display the result but it takes additional seconds to be returned back to me as an observable. Is it because I am creating the Index on every call (the index id is always the same tho so I am thinking it is using already existing index). How can I improve the speed it retrieves the data? I have 1000 documents with type payment and I need one.

  public getData(): Observable<any> {

    let vm: any = this;

    return new Observable(observer => {

      db.createIndex({
        index: {fields: ['paidOn']}
      }).then(function () {
        return vm.local.find({
          selector: {type: 'payment', paidOn: {$gt: null} },
          fields: ['paidOn'],
          sort: [{'paidOn' : "desc"}],
          limit : 1
        }).then(function (result) {

         observer.next(result)
         observer.complete()
        }).catch(function (err) {
          // ouch, an error
          observer.error(err);
          observer.complete();
        });;
      });

    });
  }

then I get it :

  getData().subscribe(data=>{

    if (data['docs'] != undefined && data['docs'].length>0){

      console.log(data['docs'][0]);

    }
  })

Body:
Yeah you shouldn't recreate the index on every call if you aren't changing it. Try this.

let vm: any = this;
    vm.index = await db.createIndex({
        index: {fields: ['paidOn']}
      })

Move this code up here into a constructor of your object or to on onInit function.

public async getData(): Promise<Observable<any>> {
    const result = await vm.local.find({
          selector: {type: 'payment', paidOn: {$gt: null} },
          fields: ['paidOn'],
          sort: [{'paidOn' : "desc"}],
          limit : 1
        });
    return new Observable(observer => {observer.next(result); observer.complete()});
  }

Although now that I'm looking at your code. You are returning an observable to get a data then immediately completing that same observable. You should keep the same observable and just use the .next() method when you want update the data or refactor this to just return a promised result and not even worry about using an observable. I'm not super clear on your use case, so I can't be certain about what is best for your situation.

Edit: Async functions return promises so I fixed return type


问:
Using a *ngFor inside a custom ng-template #treeNodeTemplate causes the tree to refresh infinitely, making the browser crash

Adding *ngFor to ng-template #treeNodeTemplate causes the tree to refresh infinitely.

Related to angular-tree-component with Angular 7.

<tree-root [nodes]="data" #tree [options]="customTemplateStringOptions">
  <ng-template #treeNodeTemplate let-node="node" let-index="index">

{{ node.data.getItemText() }}

      <ng-template ngFor [ngForOf]="getTestData()" let-item>
        {{item}}
      </ng-template>

  </ng-template>
</tree-root>
```

<p>Tried this with simple </p>

```
 (or getTestData(), same result)
```

<p>This is the tree options object:</p>

<pre class="lang-js prettyprint-override"><code>  public customTemplateStringOptions: ITreeOptions = {
    // displayField: 'subTitle',
    // isExpandedField: 'expanded',
    idField: 'uuid',
    getChildren: this.getChildren.bind(this),
    nodeHeight: 23,
    allowDrag: (node) => {
      return false;
    },
    allowDrop: (node) => {
      return false;
    }
  }
</code>```

Here is getTestData():

```<code>getTestData() {
    console.log('test data');
    return [1, 2, 3];
  }

</code>```

Results:
Console output after tree is rendered

```<code>test data
test data
test data
test data
test data
test data
...
</code>```

This problem was opened in the following link but looks like it was never addressed as the poster did not respond:
Problem Link

答:
I think the problem is that you're using a function as the input for a property binding e.g. [ngForOf]="getTestData()"

Angular tries to check if the input value has changed during the change detection cycle, and it expects the input value to be a variable in the template, or a property on the class. If it has to call a function to retrieve the value, it will simply call it indefinitely

Try setting the data as a property on the class - see if that narrows down the issue

Note: this is also why pure pipes are necessary

Body:
Adding *ngFor to ng-template #treeNodeTemplate causes the tree to refresh infinitely.

Related to angular-tree-component with Angular 7.

<tree-root [nodes]="data" #tree [options]="customTemplateStringOptions">
  <ng-template #treeNodeTemplate let-node="node" let-index="index">

{{ node.data.getItemText() }}

      <ng-template ngFor [ngForOf]="getTestData()" let-item>
        {{item}}
      </ng-template>

  </ng-template>
</tree-root>

Tried this with simple

 (or getTestData(), same result)

This is the tree options object:

  public customTemplateStringOptions: ITreeOptions = {
    // displayField: 'subTitle',
    // isExpandedField: 'expanded',
    idField: 'uuid',
    getChildren: this.getChildren.bind(this),
    nodeHeight: 23,
    allowDrag: (node) => {
      return false;
    },
    allowDrop: (node) => {
      return false;
    }
  }

Here is getTestData():

getTestData() {
    console.log('test data');
    return [1, 2, 3];
  }

Results:
Console output after tree is rendered

test data
test data
test data
test data
test data
test data
...

This problem was opened in the following link but looks like it was never addressed as the poster did not respond:
Problem Link


问:
is there such a thing as IndexOf(any white character, startIndex)?
A white space character is a single space, a tab, return, and new line. To detect these, use this regular expression: \s

My question is: Is there a way for me to use a single IndexOf statement that will return the index of any white space character?

```<code>//works
int index = richTextBox1.Text.IndexOf(' ', 0);
int index = richTextBox1.Text.IndexOf('\n', 0);

//doesn't work
int index = richTextBox1.Text.IndexOf('\\s', 0);
int index = richTextBox1.Text.IndexOf("\\s", 0);
</code>```

'\S' causes an error that there are too many characters while "\s" ends up looking for \s in a string just looking for a in "heaven". I don't mind checking each type but if there is a better way, please let me know.
Thank you.

答:
string.IndexOfAny(char[]) will get you the index of the string where the first character of any of the characters in the array appears.

The trick is defining what "whitespace" is. The example below has 25 characters defined as whitespace, the more common ones being ' ', '\n', '\t', '\v', '\r'. The following will use the unicode definitions and char.IsWhitespace to determine what whitespace characters there are.

```<code>public static void Main()
{
    var wsChars = Enumerable.Range(0, ushort.MaxValue)
                            .Where(c => char.IsWhiteSpace(Convert.ToChar(c)))
                            .Select(c => Convert.ToChar(c)).ToArray();

    Console.WriteLine(wsChars.Length);

    var someText = "This_is_a\tstring with \nsome whitespace characters.";

    Console.WriteLine(someText.IndexOfAny(wsChars));
}
</code>```

Try it out on .NET Fiddle

If you want to start at a specific index, just use the string.IndexOfAny(char[], int) to provide a starting index.

Body:
A white space character is a single space, a tab, return, and new line. To detect these, use this regular expression: \s

My question is: Is there a way for me to use a single IndexOf statement that will return the index of any white space character?

//works
int index = richTextBox1.Text.IndexOf(' ', 0);
int index = richTextBox1.Text.IndexOf('\n', 0);

//doesn't work
int index = richTextBox1.Text.IndexOf('\\s', 0);
int index = richTextBox1.Text.IndexOf("\\s", 0);

'\S' causes an error that there are too many characters while "\s" ends up looking for \s in a string just looking for a in "heaven". I don't mind checking each type but if there is a better way, please let me know.
Thank you.

Body:
string.IndexOfAny(char[]) will get you the index of the string where the first character of any of the characters in the array appears.

The trick is defining what "whitespace" is. The example below has 25 characters defined as whitespace, the more common ones being ' ', '\n', '\t', '\v', '\r'. The following will use the unicode definitions and char.IsWhitespace to determine what whitespace characters there are.

public static void Main()
{
    var wsChars = Enumerable.Range(0, ushort.MaxValue)
                            .Where(c => char.IsWhiteSpace(Convert.ToChar(c)))
                            .Select(c => Convert.ToChar(c)).ToArray();

    Console.WriteLine(wsChars.Length);

    var someText = "This_is_a\tstring with \nsome whitespace characters.";

    Console.WriteLine(someText.IndexOfAny(wsChars));
}

Try it out on .NET Fiddle

If you want to start at a specific index, just use the string.IndexOfAny(char[], int) to provide a starting index.


问:
How to see MySQL statements and error (if any) in CakePHP shell
I am using CakePHP 1.3 and writing custom shells to run mundane tasks in cronjobs. I am seeing failed Model->save() from time to time but I don't know anyway to find out what the exact problem is.

Is there a way to display the actual SQL statements executed and warning/error returned by MySQL in a CakePHP shell?

Thanks.

答:
You can use the following SQL dump task for shells.

http://bakery.cakephp.org/articles/carcus88/2011/04/08/sql_dump_task_for_shells

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
read a text file and remove all occurences of a duplicates
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

```<code>hello i am a businessman  i am also a student
</code>```

output should be:

```<code>hello businessman also student
</code>```

my approach was like this:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}
</code>```

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.

答:
I am only writing this, because there are a lot of answers that give complex and non-optimal solutions.

The advice that @Sambit gave is simple and you should do just that!

From the code you already have, just use list1.

```<code>public class MyClass {

  public static void main(String[] args) throws FileNotFoundException {

    Scanner input = new Scanner(new File("test1.txt"));

    ArrayList<String> list1 = new ArrayList<>();

    while (input.hasNext()) {
        list1.add(input.next());

    }

    // This will automatically remove all duplicates from your list.
    HashSet<String> uniqueWords = new HashSet<>(list1);

    // Print all the unique words
    for(String word : uniqueWords)
      System.out.println(word);
}
</code>```

Output:

hello i am a businessman also student

A set is a collection of distinct objects, which means that there are no duplicates.

The documentation for a HashSet is here

Body:
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

hello i am a businessman  i am also a student

output should be:

hello businessman also student

my approach was like this:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.

Body:
I am only writing this, because there are a lot of answers that give complex and non-optimal solutions.

The advice that @Sambit gave is simple and you should do just that!

From the code you already have, just use list1.

public class MyClass {

  public static void main(String[] args) throws FileNotFoundException {

    Scanner input = new Scanner(new File("test1.txt"));

    ArrayList<String> list1 = new ArrayList<>();

    while (input.hasNext()) {
        list1.add(input.next());

    }

    // This will automatically remove all duplicates from your list.
    HashSet<String> uniqueWords = new HashSet<>(list1);

    // Print all the unique words
    for(String word : uniqueWords)
      System.out.println(word);
}

Output:

hello i am a businessman also student

A set is a collection of distinct objects, which means that there are no duplicates.

The documentation for a HashSet is here


问:
How to avoid calling malloc for each node in a linked list
This question was inspired by

Prevent malloc function wrapping

I have written a program that allocates memory for individual nodes in a linked list by calling malloc.

There are speed tests in which malloc is wrapped by a function that causes malloc calls to take more time than normal. This allows the tests to detect frequent usage of malloc.

How do I avoid calling malloc for each node?

答:
This program allocates memory for nodes in a linked list in contiguous chunks. When the memory in a chunk is exhausted, a new chunk is allocated.

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

// An imaginary node because the original question did not provide one
struct node {
    struct node *next, *prev;
    int numbers[1024];
    char string[1024];
};

struct node_storage {
    int count;
    int total;
    struct node *node_list;
    struct node_storage *next;
};

struct node_storage *add_storage(int count) {
    struct node_storage *pstorage = malloc(sizeof(struct node_storage));
    // We could avoid a malloc here by making node_list an array
    pstorage->node_list = malloc(sizeof(struct node) * count);
    pstorage->count = count;
    pstorage->total = count;
    pstorage->next = NULL;
    return pstorage;
}

void free_storage(struct node_storage *storage) {
    while (storage) {
        struct node_storage *next = storage->next;
        free(storage->node_list);
        free(storage);
        storage = next;
    }
}

struct node *new_node(struct node **free_list, struct node_storage **storage) {
    struct node *free_node = *free_list;
    struct node_storage *pstorage = *storage;
    struct node *result;
    // If there is a free node
    if (free_node) {
        // Get the new node from the free list
        result = free_node;
        *free_list = free_node->next;
    }
    else {
        // Get the new node from the pre-allocated storage
        result = &pstorage->node_list[pstorage->total - pstorage->count];
        pstorage->count--;
        // If that was the last pre-allocated node
        if (0 == pstorage->count) {
            // Allocate the next chunk of nodes
            pstorage->next = add_storage(pstorage->total);
            *storage = pstorage->next;
        }
    }
    return result;
}

void free_node(struct node **free_list, struct node *node) {
    struct node *pfree_list = *free_list;
    if (pfree_list) {
        node->next = pfree_list;
    }
    *free_list = node;
}

int main() {
    const int node_count = 1000 * 1000;
    struct node_storage *head;
    struct node_storage *curr;
    struct node *free_list = NULL;
    struct node *node_list = NULL;
    head = add_storage(100);
    curr = head;
    // Allocate a lot of nodes and put them in a list
    for (int index = 0; index < node_count; index++) {
        struct node *new = new_node(&free_list, &curr);
        printf("address of new = %p\n", new);
        new->next = node_list;
        node_list = new;
    }
    // Free all of the allocated nodes
    while (node_list) {
        struct node *pnode = node_list;
        node_list = node_list->next;
        free_node(&free_list, pnode);
    }
    // Allocate a lot of nodes so that we can verify that they come from
    // the free list
    for (int index = 0; index < node_count; index ++) {
        struct node *new = new_node(&free_list, &curr);
        printf("address of new = %p\n", new);
    }
    free_storage(head);
    return 0;
}
</code>```

Output

```<code>address of new = 0x10f972000
address of new = 0x10f973410
...
address of new = 0x243570230
</code>```

Warning

This code does no error checking and should not be used in a production environment.

Note

I modified the code so that a freed node is placed on a free list. That list is checked first when requesting a new node. I tested this by comparing the addresses of the nodes like this:

```<code>$ ./test > storage.txt
$ split -l 1000000 storage.txt
$ diff xaa xab
</code>```

Body:
This program allocates memory for nodes in a linked list in contiguous chunks. When the memory in a chunk is exhausted, a new chunk is allocated.

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

// An imaginary node because the original question did not provide one
struct node {
    struct node *next, *prev;
    int numbers[1024];
    char string[1024];
};

struct node_storage {
    int count;
    int total;
    struct node *node_list;
    struct node_storage *next;
};

struct node_storage *add_storage(int count) {
    struct node_storage *pstorage = malloc(sizeof(struct node_storage));
    // We could avoid a malloc here by making node_list an array
    pstorage->node_list = malloc(sizeof(struct node) * count);
    pstorage->count = count;
    pstorage->total = count;
    pstorage->next = NULL;
    return pstorage;
}

void free_storage(struct node_storage *storage) {
    while (storage) {
        struct node_storage *next = storage->next;
        free(storage->node_list);
        free(storage);
        storage = next;
    }
}

struct node *new_node(struct node **free_list, struct node_storage **storage) {
    struct node *free_node = *free_list;
    struct node_storage *pstorage = *storage;
    struct node *result;
    // If there is a free node
    if (free_node) {
        // Get the new node from the free list
        result = free_node;
        *free_list = free_node->next;
    }
    else {
        // Get the new node from the pre-allocated storage
        result = &pstorage->node_list[pstorage->total - pstorage->count];
        pstorage->count--;
        // If that was the last pre-allocated node
        if (0 == pstorage->count) {
            // Allocate the next chunk of nodes
            pstorage->next = add_storage(pstorage->total);
            *storage = pstorage->next;
        }
    }
    return result;
}

void free_node(struct node **free_list, struct node *node) {
    struct node *pfree_list = *free_list;
    if (pfree_list) {
        node->next = pfree_list;
    }
    *free_list = node;
}

int main() {
    const int node_count = 1000 * 1000;
    struct node_storage *head;
    struct node_storage *curr;
    struct node *free_list = NULL;
    struct node *node_list = NULL;
    head = add_storage(100);
    curr = head;
    // Allocate a lot of nodes and put them in a list
    for (int index = 0; index < node_count; index++) {
        struct node *new = new_node(&free_list, &curr);
        printf("address of new = %p\n", new);
        new->next = node_list;
        node_list = new;
    }
    // Free all of the allocated nodes
    while (node_list) {
        struct node *pnode = node_list;
        node_list = node_list->next;
        free_node(&free_list, pnode);
    }
    // Allocate a lot of nodes so that we can verify that they come from
    // the free list
    for (int index = 0; index < node_count; index ++) {
        struct node *new = new_node(&free_list, &curr);
        printf("address of new = %p\n", new);
    }
    free_storage(head);
    return 0;
}

Output

address of new = 0x10f972000
address of new = 0x10f973410
...
address of new = 0x243570230

Warning

This code does no error checking and should not be used in a production environment.

Note

I modified the code so that a freed node is placed on a free list. That list is checked first when requesting a new node. I tested this by comparing the addresses of the nodes like this:

$ ./test > storage.txt
$ split -l 1000000 storage.txt
$ diff xaa xab


问:
How to extract the property from array of objects matching the specific characters (contains query)
I have any array of object having properties id and title.I want to get the ids of all objects which contains the characters entered by user in title properties

```<code>>[{ID: 3, Title: "License 1"},
{ID: 4, Title: "License 2"},
{ID: 36, Title: "License 3"},
{ID: 37, Title: "License 4"},
{ID: 38, Title: "sense 4"}]
</code>```

this the sample array if user enters lic it should return me n array
a=[3,4,36,37]

答:
You can use regular expressions as well as Array methods to match the character search:</p>

```<code>const arr = [{ ID: 3, Title: 'License 1' }, ... ];
const query = 'lic';
const reg = new RegExp('.*' + query + '.*', 'gi');

arr.filter((x) => x.ID.match(reg)).map((x) => x.ID);
// [3, 4, 36, 37, ...]
</code>```

Body:
I have any array of object having properties id and title.I want to get the ids of all objects which contains the characters entered by user in title properties

>[{ID: 3, Title: "License 1"},
{ID: 4, Title: "License 2"},
{ID: 36, Title: "License 3"},
{ID: 37, Title: "License 4"},
{ID: 38, Title: "sense 4"}]

this the sample array if user enters lic it should return me n array
a=[3,4,36,37]

Body:
You can use regular expressions as well as Array methods to match the character search:

const arr = [{ ID: 3, Title: 'License 1' }, ... ];
const query = 'lic';
const reg = new RegExp('.*' + query + '.*', 'gi');

arr.filter((x) => x.ID.match(reg)).map((x) => x.ID);
// [3, 4, 36, 37, ...]


答:
A simple loop through the array and add the items to a new array.

  var i;
    var array = [{ID: 3, Title: "License 1"},
    {ID: 4, Title: "License 2"},
    {ID: 36, Title: "License 3"},
    {ID: 37, Title: "License 4"},
    {ID: 38, Title: "sense 4"}]

    var lic = [];

    for (i = 0;i < array.length; i++){
        lic.push(array[i].ID);
    }

    console.log(lic);```

Title: How to extract the property from array of objects matching the specific characters (contains query)


答:
Don't call methods from the template unless it is response to user action. You end up in a change detection loop.

Add a number[] property to the component:

```<code>testData: number[];
</code>```

Have the component implement OnInit and set the value in ngOnInit.

```<code>ngOnInit() {
   this.testData = [1, 2, 3];
}
</code>```

Change template to

```<code><ng-template [ngForOf]="testData" let-item>
</code>```

Title: Using a *ngFor inside a custom ng-template #treeNodeTemplate causes the tree to refresh infinitely, making the browser crash

Body:
Don't call methods from the template unless it is response to user action. You end up in a change detection loop.

Add a number[] property to the component:

testData: number[];

Have the component implement OnInit and set the value in ngOnInit.

ngOnInit() {
   this.testData = [1, 2, 3];
}

Change template to

<ng-template [ngForOf]="testData" let-item>


问:
Get selected option ID from populated list
I have a radiobutton list that is populated from MySQL. A function to be called when the selected radiobutton changes. I would like to be get the ID of the selected item.

```<code> <ul id="radio" class="input-list">
<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '<li>
<input class="selectedoptions" id="'.$case_id.'" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
<label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
</li>';
}
$stmt->close();
>
</ul>
</code>```

JS:

```<code><script>

    function updateImage(caseid) {

        var selectmenuID = document.getElementById(caseid);
        console.log(selectmenuID);
    }

<script>
</code>```

Attempting to get the id of the selected item is not successful. This is the console output:

```<code><input class="selectedoptions" id="32" name="config-case" value="24"
type="radio" onchange="updateImage(this.id);">
</code>```

I would like to get the 32 (the id). How can I do this? Thank you,

答:
Your code is right. The only fact about it is that you are logging in console the DOM element, not the parameter you recive caseid which value is the ID attribute of the element.

Look at an example:

function updateImage(caseid) {
  var selectmenuID = document.getElementById(caseid);
  console.log(`Clicked on radio input with id:${caseid}`);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="radio" class="input-list">

  <li>
    <input class="selectedoptions" id="1" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
    <label class="sub-label" for="'.$case_id.'">Element with ID 1</label>
  </li>

  <li>
    <input class="selectedoptions" id="2" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
    <label class="sub-label" for="'.$case_id.'">Element with ID 2</label>
  </li>

  <li>
    <input class="selectedoptions" id="3" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
    <label class="sub-label" for="'.$case_id.'">Element with ID 3</label>
  </li>

</ul>

<input class="selectedoptions" id="32" name="config-case" value="24"
type="radio" onchange="updateImage(this.id);"></code>```

Body:
I have a radiobutton list that is populated from MySQL. A function to be called when the selected radiobutton changes. I would like to be get the ID of the selected item.

<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '

<input class="selectedoptions" id="'.$case_id.'" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
'.$case_name.'         [£'.$case_price.']

';
}
$stmt->close();
>

JS:

Body:
Your code is right. The only fact about it is that you are logging in console the DOM element, not the parameter you recive caseid which value is the ID attribute of the element.

Look at an example:

function updateImage(caseid) {
  var selectmenuID = document.getElementById(caseid);
  console.log(`Clicked on radio input with id:${caseid}`);
}

<ul id="radio" class="input-list">

  <li>
    <input class="selectedoptions" id="1" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
    <label class="sub-label" for="'.$case_id.'">Element with ID 1</label>
  </li>

  <li>
    <input class="selectedoptions" id="2" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
    <label class="sub-label" for="'.$case_id.'">Element with ID 2</label>
  </li>

  <li>
    <input class="selectedoptions" id="3" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
    <label class="sub-label" for="'.$case_id.'">Element with ID 3</label>
  </li>

</ul>

<input class="selectedoptions" id="32" name="config-case" value="24"
type="radio" onchange="updateImage(this.id);">


问:
React-select container option width
i' tryin the react-select library, and i like it.

I'm playing with it but i dont' understand how to change the width of the options container.

i tried to saw the documentation at official react select but i didn't find the right section about the width of the options container.

could someone kindly help me :) ?

this is my custom style right now :

```<code>const customStyles = {
      option: (provided, state) => ({
        ...provided,
        borderBottom: '1px solid #979797',
        width: 219,
        borderRadius: 5,
      }),
      control: () => ({
        // none of react-select's styles are passed to <Control />
        width: 219,
        border: '1px solid #979797',
        display: 'flex',
        borderRadius: '5px',
      }),
      valueContainer: (provided) => ({
        ...provided,
        width: 219,
      }),
    }
</code>```

答:
You can pass a selector for container like

```<code>const colourStyles = {
  control: styles => ({ ...styles, backgroundColor: 'white' }),
  container: styles => ({ ...styles,  width: 200 })
};

<Select
  defaultValue={colourOptions[2]}
  label="Single select"
  options={colourOptions}
  styles={colourStyles}
/>
</code>```

Demo

Title: React-select container option width

Body:
i' tryin the react-select library, and i like it.

I'm playing with it but i dont' understand how to change the width of the options container.

i tried to saw the documentation at official react select but i didn't find the right section about the width of the options container.

could someone kindly help me :) ?

this is my custom style right now :

const customStyles = {
      option: (provided, state) => ({
        ...provided,
        borderBottom: '1px solid #979797',
        width: 219,
        borderRadius: 5,
      }),
      control: () => ({
        // none of react-select's styles are passed to <Control />
        width: 219,
        border: '1px solid #979797',
        display: 'flex',
        borderRadius: '5px',
      }),
      valueContainer: (provided) => ({
        ...provided,
        width: 219,
      }),
    }

Body:
You can pass a selector for container like

const colourStyles = {
  control: styles => ({ ...styles, backgroundColor: 'white' }),
  container: styles => ({ ...styles,  width: 200 })
};

<Select
  defaultValue={colourOptions[2]}
  label="Single select"
  options={colourOptions}
  styles={colourStyles}
/>

Demo


问:
How can I create an object in .ascx?
I've wrapped the asp:DropDown control so that I can create a lot of instances of it, all of which using the same additional functionality. I want to be able to create this object completely in the .ascx rather than using the code behind. I'm almost there, with the exception of the ListItems.

Here's what I have thus far, can anyone help me to figure out how to get the list items to populate?

```<code><Control:DropDown ID="choice" runat="server" DropDownListLabel="Some Choice:"
QueryString="choice" SelectedIndex="0" ListItems='<%# new ListItemCollection(){
new ListItem("<no filter>", "-1"), new ListItem("Yes", "y"), new ListItem("No", "n")
} %>' />
</code>```

Everything is working, with the exception of the ListItems, although the list items do work as expected from code behind. Any help on how I can get the ListItems accessor to call properly?

Thanks in advance,
Brett

答:
You probably should have created your control to inherit from System.Web.UI.WebControls.DropDownList then override rendering and add properties that you want extra, this would allow you to something like the following:

```<code><Control:DropDown id="mycontrol" runat="server" DropDownListLabel="Some Choice:" ..>
    <asp:ListItem Text="<no filter" value="-1" />
    ...
</Control:DropDown>
</code>```

Where DropDownListLabel is an added property. Of course in your case you'd add QueryString as a property as well

Title: How can I create an object in .ascx?

Body:
I've wrapped the asp:DropDown control so that I can create a lot of instances of it, all of which using the same additional functionality. I want to be able to create this object completely in the .ascx rather than using the code behind. I'm almost there, with the exception of the ListItems.

Here's what I have thus far, can anyone help me to figure out how to get the list items to populate?

<Control:DropDown ID="choice" runat="server" DropDownListLabel="Some Choice:"
QueryString="choice" SelectedIndex="0" ListItems='<%# new ListItemCollection(){
new ListItem("<no filter>", "-1"), new ListItem("Yes", "y"), new ListItem("No", "n")
} %>' />

Everything is working, with the exception of the ListItems, although the list items do work as expected from code behind. Any help on how I can get the ListItems accessor to call properly?

Thanks in advance,
Brett

Body:
You probably should have created your control to inherit from System.Web.UI.WebControls.DropDownList then override rendering and add properties that you want extra, this would allow you to something like the following:

<Control:DropDown id="mycontrol" runat="server" DropDownListLabel="Some Choice:" ..>
    <asp:ListItem Text="<no filter" value="-1" />
    ...
</Control:DropDown>

Where DropDownListLabel is an added property. Of course in your case you'd add QueryString as a property as well


问:
char array in c not working with visual studio 2015

Is this the only way to pick up a string? Can not you take character by character into an array?

I get an error accessing memory. The code and the error are attached.

```<code>void main()
{
    int counA = 0, countB = 0, Na, Nc, i, index;
    printf("enter Na and Nc\n");
    scanf_s("%d%d", &Na, &Nc);
    char DNA[1000], SEQ[1000], str[1000];

    printf("enter mulekula\n");
    scanf_s("%s", str);
}
</code>```

input:

```<code>2
3
AAA
</code>```

message I get:

```<code>exception thrown...
</code>```

答:
fgets can help , see this code

```<code>#include<stdio.h>
#include<string.h>
int main()
{
chat str[1000];

fegts(str,sizeof(str),stdin);

str[strlen(str)-1]='\0';
return 0;

}
</code>```

This code will take input from console till you press enter , but take care that fgets includes the new line character('\n') with input so we need to remove it and end the string with null character ('\0') .

This is the reason for this line of code str[strlen(str)-1]='\0'; so strlen(str) will return the length of string including new line character.

for example :

if input was "fo" , so it stored in str as follow:

str[0] = 'f' , str[1]='o' , str[2]='\n' and str[3]='\0'.
So strlen(str)-1 will return 2 , so str[2] will be assigned to null character '\0'

And finally the string will be as follow:

str[0] = 'f' , str[1]='o' and str[2]='\0'.

Body:
Is this the only way to pick up a string? Can not you take character by character into an array?

I get an error accessing memory. The code and the error are attached.

void main()
{
    int counA = 0, countB = 0, Na, Nc, i, index;
    printf("enter Na and Nc\n");
    scanf_s("%d%d", &Na, &Nc);
    char DNA[1000], SEQ[1000], str[1000];

    printf("enter mulekula\n");
    scanf_s("%s", str);
}

input:

2
3
AAA

message I get:

exception thrown...

Body:
fgets can help , see this code

#include<stdio.h>
#include<string.h>
int main()
{
chat str[1000];

fegts(str,sizeof(str),stdin);

str[strlen(str)-1]='\0';
return 0;

}

This code will take input from console till you press enter , but take care that fgets includes the new line character('\n') with input so we need to remove it and end the string with null character ('\0') .

This is the reason for this line of code str[strlen(str)-1]='\0'; so strlen(str) will return the length of string including new line character.

for example :

if input was "fo" , so it stored in str as follow:

str[0] = 'f' , str[1]='o' , str[2]='\n' and str[3]='\0'.
So strlen(str)-1 will return 2 , so str[2] will be assigned to null character '\0'

And finally the string will be as follow:

str[0] = 'f' , str[1]='o' and str[2]='\0'.


问:
Connect to Power BI XMLA endpoint with Python
Since the announcement about XMLA endpoints, I've been trying to figure out how to connect to a URL of the form powerbi://api.powerbi.com/v1.0/myorg/[workspace name] as an SSAS OLAP cube via Python, but I haven't gotten anything to work.

I have a workspace in a premium capacity and I am able to connect to it using DAX Studio as well as SSMS as explained here, but I haven't figured out how to do it with Python. I've tried installing olap.xmla, but I get the following error when I try to use the Power BI URL as the location using either the powerbi or https as the prefix.

```<code>import olap.xmla.xmla as xmla
p = xmla.XMLAProvider()
c = p.connect(location="powerbi://api.powerbi.com/v1.0/myorg/[My Workspace]")
[...]
TransportError: Server returned HTTP status 404 (no content available)
</code>```

I'm sure there are authentication issues involved, but I'm a bit out of my depth here. Do I need to set up an "app" in ActiveDirectory and use the API somehow? How is authentication handled for this kind of connection?

If anyone knows of any blog posts or other resources that demonstrate how to connect to a Power BI XMLA endpoint specifically using Python, that would be amazing. My searching has failed me, but surely I can't be the only one who is trying to do this.

答:
I'm not familiar with olap.xmla or using Python to connect to olap cubes, but I think the problem is with the driver (or connector ?) provided in olap.xmla.

In the announcement about XMLA endpoints page, it says that the connection only works with SSMS 18.0 RC1 or later, which is quite new. Same thing with DAX studio, the version where xmla connection is supported (Version 2.8.2, Feb 3 2019), is quite fresh.

The latest version of olap.xmla seems to be from august 2013, so it's possible that there's some Microsoft magic behind the PowerBI XMLA connection and that's why it doesn't work with older connectors.

Body:
Since the announcement about XMLA endpoints, I've been trying to figure out how to connect to a URL of the form powerbi://api.powerbi.com/v1.0/myorg/[workspace name] as an SSAS OLAP cube via Python, but I haven't gotten anything to work.

I have a workspace in a premium capacity and I am able to connect to it using DAX Studio as well as SSMS as explained here, but I haven't figured out how to do it with Python. I've tried installing olap.xmla, but I get the following error when I try to use the Power BI URL as the location using either the powerbi or https as the prefix.

import olap.xmla.xmla as xmla
p = xmla.XMLAProvider()
c = p.connect(location="powerbi://api.powerbi.com/v1.0/myorg/[My Workspace]")
[...]
TransportError: Server returned HTTP status 404 (no content available)

I'm sure there are authentication issues involved, but I'm a bit out of my depth here. Do I need to set up an "app" in ActiveDirectory and use the API somehow? How is authentication handled for this kind of connection?

If anyone knows of any blog posts or other resources that demonstrate how to connect to a Power BI XMLA endpoint specifically using Python, that would be amazing. My searching has failed me, but surely I can't be the only one who is trying to do this.


问:
Why does MySQL safe update mode not allow a LIKE predicate?
Please consider the following scenario:

I have a MySQL table called actor. (Yes, it's from the Sakila sample DB).

In the table there's a varchar column called last_name.

There is a (non-PRIMARY) KEY on the column.

MySQL safe update mode is turned on.

When I run this query, it works:

```<code>DELETE FROM actor WHERE last_name = 'foo';
</code>```

When I run this query:

```<code>DELETE FROM actor WHERE last_name LIKE '%fo' OR last_name LIKE 'fo%';
</code>```

It fails with this error message:

Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.  To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.

Why does safe update mode stop the second command and allow the first command?

答:
According to the documentation:

It is possible for UPDATE and DELETE statements to produce an error in safe-updates mode even with a key specified in the WHERE clause, if the optimizer decides not to use the index on the key column.

A test like LIKE 'fo%' will normally use the index (the index can be used to match the beginning of a column), so it shouldn't cause the error. But a test like LIKE '%fo' cannot be indexed (it doesn't specify the beginning of the column, so a full scan is necessary), so you get an error.

Body:
Please consider the following scenario:

I have a MySQL table called actor. (Yes, it's from the Sakila sample DB).

In the table there's a varchar column called last_name.

There is a (non-PRIMARY) KEY on the column.

MySQL safe update mode is turned on.

When I run this query, it works:

DELETE FROM actor WHERE last_name = 'foo';

When I run this query:

DELETE FROM actor WHERE last_name LIKE '%fo' OR last_name LIKE 'fo%';

It fails with this error message:

Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.  To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.

Why does safe update mode stop the second command and allow the first command?


问:
Build errors. Duplicate class android.support.v4
I have created a simple image to text app using Visual Studio following uTube guide https://www.youtube.com/watch?v=CLjzLiU_GpE

I am new to app dev and wanted to learn this but cant get to compile.

I have tried to follow similar errors in here
Duplicate class android.support.v4.app.INotificationSideChannel found in modules classes?

When I try to follow this and add to the AndroidStudioProjects\ImageToTextApp\gradle.properties
I get more errors

My errors are as show but i have included (only) first and last 2, there are 390 in total.

I think i can see it tells me (as per other issues in here) that the class is in 2 libraries.
(com.android.support:support-compat:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)

Were do i see my project importing these libraries and how do I fix these errors.

Duplicate class android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat found in modules classes.jar (com.android.support:support-compat:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)
Duplicate class android.support.v4.app.ActionBarDrawerToggle found in modules classes.jar (com.android.support:support-core-ui:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)
...
Duplicate class android.support.v4.widget.ViewDragHelper$2 found in modules classes.jar (com.android.support:customview:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)
Duplicate class android.support.v4.widget.ViewDragHelper$Callback found in modules classes.jar (com.android.support:customview:28.0.0) and classes.jar (com.android.support:support-v4:24.0.0)

Go to the documentation to learn how to Fix dependency resolution errors.

Hi @BachVu
I added your suggested line and the build.gradle file now looks like

dependencies {
      implementation fileTree(dir: 'libs', include: ['*.jar'])
      implementation 'com.android.support:appcompat-v7:28.0.0'      implementation
  'com.android.support.constraint:constraint-layout:2.0.0-beta1'
    testImplementation 'junit:junit:4.13-beta-3'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation
  'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services-vision:10.2.4'
    exclude module: 'support-v4'  }

But this just creates more errors

ERROR: Gradle DSL method not found: 'exclude()'

Do i need to add another import or have i added in the wrong place?

答:
Here is my build.Gradle file now and all works fine;

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta1'
    testImplementation 'junit:junit:4.13-beta-3'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services-vision:17.0.2' }
</code>```

The main difference is

```<code>com.google.android.gms:play-services-vision:10.2.4
</code>```

For some reason this was okay then out of nowhere it advised it was out of date. Once I updated from 10.2.4 > 17.0.2 all the errors went away.

Thanks for your time.

Body:
Here is my build.Gradle file now and all works fine;

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:2.0.0-beta1'
    testImplementation 'junit:junit:4.13-beta-3'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.gms:play-services-vision:17.0.2' }

The main difference is

com.google.android.gms:play-services-vision:10.2.4

For some reason this was okay then out of nowhere it advised it was out of date. Once I updated from 10.2.4 > 17.0.2 all the errors went away.

Thanks for your time.


问:
Laravel 5.1 auto incrementing row number with pagination
Is there any way to get pagination pretty url or something like this in laravel 5.1?

I have 15 rows in per page. And I want to increment the row count number even on paginate.

```<code><?php  $count = 1; ?>
<tr>
    <th>No</th>
    <th>Year</th>
    <th>Action</th>
</tr>
@foreach($years as $year)
<tr>
    <td width="20%">{{ $count++ }}</td>
    <td width="50%">{{ $year->year }}</td>
    <td width="30%">
        <a href="{{ route('admin.year.edit', $year->id) }}" class="btn btn-info">Edit</a>
    </td>
</tr>
@endforeach
</code>```

But when I goes to next page the $count var starts from beginning. How can I get  $count = 16 and it will increment and so on?

答:
If you can use pagination then try this:</p>

```<code>@foreach ($noticelist as $key=>$info)
 <tr>
  <th scope="row">{{ ($noticelist->currentpage()-1) * $noticelist->perpage() + $key + 1 }}</th>
  </tr>
@endforeach
</code>```

Body:
Is there any way to get pagination pretty url or something like this in laravel 5.1?

I have 15 rows in per page. And I want to increment the row count number even on paginate.

<?php  $count = 1; ?>

    No
    Year
    Action

@foreach($years as $year)

    {{ $count++ }}
    {{ $year->year }}

        id) }}" class="btn btn-info">Edit

@endforeach

But when I goes to next page the $count var starts from beginning. How can I get  $count = 16 and it will increment and so on?

Body:
If you can use pagination then try this:

@foreach ($noticelist as $key=>$info)
 <tr>
  <th scope="row">{{ ($noticelist->currentpage()-1) * $noticelist->perpage() + $key + 1 }}</th>
  </tr>
@endforeach


问:
How to fabricate ASPX POST request
I'm battling with this for days, I have an ASPX page that has a file upload control and an upload button, and no matter what I do, I can't get the page to accept the automated POST request.

The request body is as follows (all newlines CRLF), all UTF8 == ANSII (no spec chars right now)

```<code>-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="btnUpload"

Upload
-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="ctrFileUpload"; filename="myfile.txt"
Content-Type: text/plain

This is a test!

-----------------------------8cdc74445fc88d0--
</code>```

The form has multiple buttons, so I need to kinda fill the file upload, and press the upload button. But this doesn't seem to work.

The same page works just fine from a web browser, although, in that scenario there is a viewstate garbage as one of the parts. I tried EnableViewState="false", ValidateRequest="false", EnableSessionState="ReadOnly", but the garbage part is still there when I use the browser.

Am I missing something? Tried studying the RFC and everything, but nothing seems to work.

答:
I also don'T know what an "automated post request" is, but setting

```<code><form ... enctype="multipart/form-data">
</code>```

on your form tag might help.

Title: How to fabricate ASPX POST request

Body:
I'm battling with this for days, I have an ASPX page that has a file upload control and an upload button, and no matter what I do, I can't get the page to accept the automated POST request.

The request body is as follows (all newlines CRLF), all UTF8 == ANSII (no spec chars right now)

-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="btnUpload"

Upload
-----------------------------8cdc74445fc88d0
Content-Disposition: form-data; name="ctrFileUpload"; filename="myfile.txt"
Content-Type: text/plain

This is a test!

-----------------------------8cdc74445fc88d0--

The form has multiple buttons, so I need to kinda fill the file upload, and press the upload button. But this doesn't seem to work.

The same page works just fine from a web browser, although, in that scenario there is a viewstate garbage as one of the parts. I tried EnableViewState="false", ValidateRequest="false", EnableSessionState="ReadOnly", but the garbage part is still there when I use the browser.

Am I missing something? Tried studying the RFC and everything, but nothing seems to work.

Body:
I also don'T know what an "automated post request" is, but setting

<form ... enctype="multipart/form-data">

on your form tag might help.


问:
Mask characters in string SQL SERVER
how can i replace characters between x and y char in string in SQL SERVER.
For example if i have: TEST123456 to have at the end TE******56. I don't know how long will be the string but i know that i need to mask characters between x and y in string</p>

答:
My requirement was different from the post, posting here my solution as it may help someone else.</p>

```<code>CREATE FUNCTION [dbo].[uf_MaskText] (@cText VARCHAR(255), @iNumberOfVisibleCharacters INT)
RETURNS VARCHAR(255)
AS

BEGIN
    IF ISNULL(@cText, '') <> ''
    BEGIN
        IF LEN(@cText) > @iNumberOfVisibleCharacters
        BEGIN
            DECLARE @iNumberCharacters INT = LEN(@cText)
            SET @cText = REPLICATE('*', @iNumberCharacters - @iNumberOfVisibleCharacters) + SUBSTRING(@cText, @iNumberCharacters - @iNumberOfVisibleCharacters + 1, @iNumberOfVisibleCharacters)
        END
    END
    RETURN @cText
END
GO
</code>```

Title: Mask characters in string SQL SERVER

Body:
My requirement was different from the post, posting here my solution as it may help someone else.

CREATE FUNCTION [dbo].[uf_MaskText] (@cText VARCHAR(255), @iNumberOfVisibleCharacters INT)
RETURNS VARCHAR(255)
AS

BEGIN
    IF ISNULL(@cText, '') <> ''
    BEGIN
        IF LEN(@cText) > @iNumberOfVisibleCharacters
        BEGIN
            DECLARE @iNumberCharacters INT = LEN(@cText)
            SET @cText = REPLICATE('*', @iNumberCharacters - @iNumberOfVisibleCharacters) + SUBSTRING(@cText, @iNumberCharacters - @iNumberOfVisibleCharacters + 1, @iNumberOfVisibleCharacters)
        END
    END
    RETURN @cText
END
GO


问:
Is It possible to Disable JS for my website on my server
I'm trying to connect my android app to a PHP script on a free server. But as my android app is Trying to get to the page I'm getting an HTML that says that JS is turned off, Switch it on to view the page.
Can I Disable the JS requirement on my server?</p>

答:
It is their security (On premium hosting, this security system is not present)

https://infinityfree.net/support/javascript-error-using-api-or-mobile-android-app/


问:
ng-model between two text box should work based on checkbox input
I am building an UI page, the form consists of 2 textbox and a checkbox, if the checkbox is true the content of both textbox should be updated to each other immediately.

Code sample
"

```<code>Registration number :

<input type="text" name="usr" id="usr" style="width:200px" value="{{usr}}" required="required"> <br>

Moodle Password :

<input type="password" name="pwd" ng-model="pwd2" value="{{pwd}}" id="pwd" style="width:200px"> <br>

Ffcs Password :

<input type="password" name="ffcs_pwd" ng-model="ffcs_pwd2" value="{{ffcs_pwd}}" id="ffcs_pwd" style="width:200px">
<br>

<input type="checkbox" name="same" id="same" unchecked>
 Same password for both
 <br>

<input type="submit" value="Log In">
</code>```

"

答:
Keep ng-model for both password as different as in code below. Use checkbox value if it is true then you can give moodle password value to fcfs password like

```<code>Registration number : <input type="text" ng-model="regno"/>
Moodle Password : <input type="text" ng-model="modpass"/>
Ffcs Password : <input type="text" ng-model="fcfs"/>
Same password for both : <input type="checkbox" ng-model="chkbox"/>

if($scope.chkbox){
    $scope.fcfs = $scope.modpass
}
</code>```

Or you can use $watch on Moodle password model.

Body:
I am building an UI page, the form consists of 2 textbox and a checkbox, if the checkbox is true the content of both textbox should be updated to each other immediately.

Code sample
"

Registration number :

<input type="text" name="usr" id="usr" style="width:200px" value="{{usr}}" required="required">

Moodle Password :

<input type="password" name="pwd" ng-model="pwd2" value="{{pwd}}" id="pwd" style="width:200px">

Ffcs Password :

<input type="password" name="ffcs_pwd" ng-model="ffcs_pwd2" value="{{ffcs_pwd}}" id="ffcs_pwd" style="width:200px">

<input type="checkbox" name="same" id="same" unchecked>
 Same password for both

<input type="submit" value="Log In">

"

Body:
Keep ng-model for both password as different as in code below. Use checkbox value if it is true then you can give moodle password value to fcfs password like

Registration number : <input type="text" ng-model="regno"/>
Moodle Password : <input type="text" ng-model="modpass"/>
Ffcs Password : <input type="text" ng-model="fcfs"/>
Same password for both : <input type="checkbox" ng-model="chkbox"/>

if($scope.chkbox){
    $scope.fcfs = $scope.modpass
}

Or you can use $watch on Moodle password model.


问:
Dynamically add html on click on a amp webpage
Is it possible to dynamically add HTML to a webpage on click when using AMP?

Something along the lines of the

```<code><button on="tap:AMP.setState({foo: 'amp-bind'})">Say "Hello amp-
bind"</button>

<div [text]="foo">This is the placeholder to append the new
content</div>
</code>```

But rather than text HTML?

答: Are the contents of the HTML known ahead of time or generated dynamically based on user input? If the former than it can be present in the page but not visible and you can control its visibility with amp-bind and CSS. If not then yes amp-script would be a solution. Note that it is currently in experimental.</p>

Body:
Is it possible to dynamically add HTML to a webpage on click when using AMP?

Something along the lines of the

<button on="tap:AMP.setState({foo: 'amp-bind'})">Say "Hello amp-
bind"</button>

This is the placeholder to append the new
content

But rather than text HTML?


问:
Ansible Copy vs Synchronize
What are the pros and cons to using Ansible Synchronize vs Copy modules.  As far as I can tell synchronize has all the functionality that copy does but may be much faster so I'm considering changing everything to use synchronize.  The only downside of synchronize is that rsync is required, which seems fairly ubiquitous in the Linux environment.</p>

答:
As of Ansible v2.8, synchronize is still in “preview” status:

This module is not guaranteed to have a backwards compatible interface. [preview]

In Ansible v2.10, the copy module is moved to the Builtin Collection, which is officially maintained by the core team (i.e. Red Hat), and distributed with ansible-base (a.k.a. ansible-core). In contrast, synchronize is moved to the POSIX Collection maintained by community.

I would use copy when I don’t need the performance and functionality of synchronize. I suggest starting with copy, and move to synchronize only when this is the bottleneck. (Verify this with benchmark!)

Title: Ansible Copy vs Synchronize


问:
Asynchronous Remote WMI Calls C#
I'm really struggling to get WMI data from a remote host in an asynchronous way. After a lot of research, I can't find any clear examples, Microsoft's documentation only has VB and C++ code and there are even articles explaining why it's a bad idea. I've come from PowerShell, with that I would just create a new runspace to get the information.

I currently have a WPF window that I want to remain responsive whilst querying the information before updating the window. I've currently only managed to use synchronous calls using CimSession.Create and QueryInstance.

I would really appreciate some help with this :)

答:
You can use ORMi async methods to do async WMI work. For example:</p>

```<code>WMIHelper helper = new WMIHelper("root\\CimV2");
List<Processor> processors = await helper.QueryAsync<Processor>().ToList();
</code>```

Title: Asynchronous Remote WMI Calls C#

Body:
You can use ORMi async methods to do async WMI work. For example:

WMIHelper helper = new WMIHelper("root\\CimV2");
List<Processor> processors = await helper.QueryAsync<Processor>().ToList();


问:
Objective-C release is not called explicitly
```<code>NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];
</code>```

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly

答:
It did work. You have relinquished ownership of that object, and when the system determines that it is no longer owned, it will be marked available for reuse by the system. That may happen immediately, if you were the only owner of the string. It may happen at some later point, if creation of the string caused it to be autoreleased internally. Or, as Dave DeLong points out, the system may optimize it into an object that is never released.

In your case, it's being optimized into a constant string, which will exist for the life of the program. If you were to use an NSMutableString instead of an NSString, you'd see funky behavior that would probably not crash, but wouldn't print what you expected. (See this question for an example.)

If you used an NSArray instead, it would be deallocated when you called release, but you'd still see your NSLog example work correctly until you allocated some other object. Deallocation just marks the memory as available for reuse; it doesn't actually clear it out. So if you passed the array to NSLog, that memory hasn't been changed and thus it still prints correctly.

The key point in all of this, though, is to recognize that calling release will not necessarily cause the object to be deallocated. It may continue to exist for any number of reasons. But once you call release, you have relinquished ownership of the object. If you continue using it after that point, the system is free to do all sorts of weird things at its own will, as demonstrated.

Body:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly


问:
Remove Entries in hashmap using composite String key
I have hashmap
Key is String composed of concatenation of 3 elements (element1+element2+element3)

```<code>String key=element1+element2+element3;
</code>```

which is put in the hashmap

```<code>HashMap<String,Object> map=new Hashmap<String,Object>();
map.put(key,new Object());
</code>```

i want to remove all the entries in the hashmap matching key having element2
if(key.contains("element2")) then remove that entry in hashmap.

How accomplish this?

答:
Simple way is to get keySet() from your map which

Returns a Set view of the keys contained in this map. The set is
  backed by the map, so changes to the map are reflected in the set, and
  vice-versa.

So

```<code>yourMap.keySet().removeIf(key -> key.contains(keyPart));
</code>```

Body:
I have hashmap
Key is String composed of concatenation of 3 elements (element1+element2+element3)

String key=element1+element2+element3;

which is put in the hashmap

HashMap<String,Object> map=new Hashmap<String,Object>();
map.put(key,new Object());

i want to remove all the entries in the hashmap matching key having element2
if(key.contains("element2")) then remove that entry in hashmap.

How accomplish this?

Body:
Simple way is to get keySet() from your map which

Returns a Set view of the keys contained in this map. The set is
  backed by the map, so changes to the map are reflected in the set, and
  vice-versa.

So

yourMap.keySet().removeIf(key -> key.contains(keyPart));


问:
PowerShell Multiple Catch Issue
I'm following Microsoft examples and I get an error when I run this in PowerShell (5.1). I am unable to repro this in the ISE.

```<code>$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
}
catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}
</code>```

Error:

catch : The term 'catch' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

The odd thing is it works fine on the first catch. If I switch the order, the second one always fails with this message.  Any ideas why this is error'ing?

答: Your type-specific catches should always come before your catch-all, so expect an error if you switch the order of the catches above. However, the error you're getting is not what I'd expect, so I can only assume you've got a syntax typo somewhere. The only way I can repro this is if I execute a catch block without a try in front of it.</p>

Title: PowerShell Multiple Catch Issue

Body:
I'm following Microsoft examples and I get an error when I run this in PowerShell (5.1). I am unable to repro this in the ISE.

$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
}
catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}

Error:

catch : The term 'catch' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

The odd thing is it works fine on the first catch. If I switch the order, the second one always fails with this message.  Any ideas why this is error'ing?


问:
Is this Ruby PSQL safe from injection?
If I have the following PSQL statement via ruby:

```<code>user = User.find_by_email(params[:email])
sql2 = "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"email\" = \'#{params[:email]}\' LIMIT 1"
@result3 = Otherdb.connection.execute(sql2);
</code>```

Fed by the following form:

```<code><form action="/sessions" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="tj5rfiJG+yip8gXhMSq/RR/Znu+L/nhkGnqqK78wggRjI85zl4T/wBEkouY8XWlh2aylfKH0lZWjH282fc6Qdg==" />
    <div class="login">
      <h1>Login to Web App</h1>
      <p id="alert">User not present in db</p>
      <form method="post" action="">
        <p><label for="email">Email</label>
        <input type="text" name="email" id="email" /></p>
        <p><label for="password">Password</label>
        <input type="password" name="password" id="password" /></p>
        <p class="remember_me">
    <label for="remember_me">
     <input type="checkbox" name="remember_me" id="remember_me" value="1" />
     Remember me on this computer
    </label>
        </p>
        <p class="submit"><input type="submit" name="commit" value="Login" data-disable-with="Login" /></p>
      </form>
    </div>
    </form>
</code>```

I have been able to generally escape the form by using ' followed by characters, but I can't seem to get any payloads to execute.

Is this secure, or is there a more complicated escape sequence for breaking out of the statement

答:
Yes, it is definitely SQL injection.
To test it you can pass SQL like '; select count(*) from users; in params[:email].

To avoid SQL injection you could rewrite your code like:

```<code>sql2 = User.where(email: params[:email]).limit(1).to_sql
@result3 = Otherdb.connection.execute(sql2)
</code>```

Just let ActiveRecord escape and sanitize the query and the params for you.

Title: Is this Ruby PSQL safe from injection?

Body:
If I have the following PSQL statement via ruby:

user = User.find_by_email(params[:email])
sql2 = "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"email\" = \'#{params[:email]}\' LIMIT 1"
@result3 = Otherdb.connection.execute(sql2);

Fed by the following form:

<form action="/sessions" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="tj5rfiJG+yip8gXhMSq/RR/Znu+L/nhkGnqqK78wggRjI85zl4T/wBEkouY8XWlh2aylfKH0lZWjH282fc6Qdg==" />

Login to Web App

User not present in db

      <form method="post" action="">

Email
        <input type="text" name="email" id="email" />

Password
        <input type="password" name="password" id="password" />

     <input type="checkbox" name="remember_me" id="remember_me" value="1" />
     Remember me on this computer

<input type="submit" name="commit" value="Login" data-disable-with="Login" />

      </form>

    </form>

I have been able to generally escape the form by using ' followed by characters, but I can't seem to get any payloads to execute.

Is this secure, or is there a more complicated escape sequence for breaking out of the statement

Body:
Yes, it is definitely SQL injection.
To test it you can pass SQL like '; select count(*) from users; in params[:email].

To avoid SQL injection you could rewrite your code like:

sql2 = User.where(email: params[:email]).limit(1).to_sql
@result3 = Otherdb.connection.execute(sql2)

Just let ActiveRecord escape and sanitize the query and the params for you.


问:
Google Map not showing in Firebase Test Lab
I used Firebase Test Lab Robo Test to test my application and I found the map is not showing

I know it looks like I didn't properly set up the package names and SHA1s of my Maps API. But the truth is:

My Google Maps API is enabled

The package name and the SHA1 of keystore files are added in API settings (both debug and release)

The map can be showed on my real devices as well as the emulator in Android Studio

Any ideas?

答:
I suspect that Firebase Test Lab re-signs your app for testing, and therefore changes the SHA-1 signature.

The Google Play pre-launch report, which is based on Firebase Test Lab, mentions that the app will be re-signed in its docs:

As of October 2017, the pre-launch report uses a new crawler to provide a more comprehensive review of your app. To do so, the pre-launch report must temporarily re-sign your APK or app bundle within our test environment.


问:
Keeping a bootstrap carousel as a static background with text on top
So I'm trying to implement something like this:

http://bootsnipp.com/snippets/featured/carousel-static-headline-caption

Where there is text with a carousel as a background. currently when I scroll through my carousel the text scrolls as well. Here's the carousel code I'm working with.

HTML:

```<code>    <!-- Wrapper for Slides -->
    <div class="carousel-inner">
        <div class="item active">
            <!-- Set the first background image using inline CSS below. -->
            <div class="fill" style="background-image:url('image');"></div>
            <div class="carousel-caption">
            <h1>Text that I would like to stay</h1>
            </div>
        </div>
        <div class="item">
            <!-- Set the second background image using inline CSS below. -->
            <div class="fill" style="background-image:url('image');"></div>
            <div class="carousel-caption">
            </div>
        </div>
        <div class="item">
            <!-- Set the third background image using inline CSS below. -->
            <div class="fill" style="background-image:url('image');"></div>
            <div class="carousel-caption">
            </div>
        </div>
    </div>

    <!-- Controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
        <span class="icon-prev"></span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
        <span class="icon-next"></span>
    </a>

</header>
</code>```

CSS:

```<code>    html,
    body {
        height: 100%;

    }

    .carousel,
    .item,
    .active {
        height: 100%;

    }

    .carousel-inner {
        height: 100%;
    }

    .carousel-caption {
        padding-bottom: 475px;

    }

    /* Background images are set within the HTML using inline CSS, not here */

    .fill {
        width: 100%;
        height: 100%;
        background-position: center;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        background-size: cover;
        -o-background-size: cover;
        opacity: 0.9;
        top: 50px
    }

    footer {
        margin: 50px 0;
    }
body {
    width: 100%;
    height: 100%;
}

html {
    width: 100%;
    height: 100%;
}

@media(min-width:767px) {
    .navbar {
        opacity: 0.6;
        -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
        -moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
        transition: background .5s ease-in-out,padding .5s ease-in-out;
    }

    .top-nav-collapse {
        padding: 0;
    }

}.intro-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #fff;
}

.about-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #eee;
}

.services-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #fff;
}

.contact-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #eee;
}
</code>```

答:
Although the link in the question provides a nice solution if we want a fixed text and also scrolling text at the same time, in most cases we only need either fixed or scrolling. Making the text fixed in Bootstrap is as simple as taking the
 outside the
 and placing it directly under the
. No need for any additional CSS or HTML. Example:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

Static Headline And Content

Nulla vitae elit libero, a pharetra augue mollis interdum.

```

The carousel is designed so we place scrolling content inside
 and fixed content directly inside
. We can provide both, but they will overlap each other and we need additional CSS to move them apart. But most cases don't need both at the same time.

Body:
So I'm trying to implement something like this:

http://bootsnipp.com/snippets/featured/carousel-static-headline-caption

Where there is text with a carousel as a background. currently when I scroll through my carousel the text scrolls as well. Here's the carousel code I'm working with.

HTML:

Text that I would like to stay

CSS:

    html,
    body {
        height: 100%;

    }

    .carousel,
    .item,
    .active {
        height: 100%;

    }

    .carousel-inner {
        height: 100%;
    }

    .carousel-caption {
        padding-bottom: 475px;

    }

    /* Background images are set within the HTML using inline CSS, not here */

    .fill {
        width: 100%;
        height: 100%;
        background-position: center;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        background-size: cover;
        -o-background-size: cover;
        opacity: 0.9;
        top: 50px
    }

    footer {
        margin: 50px 0;
    }
body {
    width: 100%;
    height: 100%;
}

html {
    width: 100%;
    height: 100%;
}

@media(min-width:767px) {
    .navbar {
        opacity: 0.6;
        -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
        -moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
        transition: background .5s ease-in-out,padding .5s ease-in-out;
    }

    .top-nav-collapse {
        padding: 0;
    }

}.intro-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #fff;
}

.about-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #eee;
}

.services-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #fff;
}

.contact-section {
    height: 100%;
    padding-top: 150px;
    text-align: center;
    background: #eee;
}

Body:
Although the link in the question provides a nice solution if we want a fixed text and also scrolling text at the same time, in most cases we only need either fixed or scrolling. Making the text fixed in Bootstrap is as simple as taking the <div class="carousel-caption"> outside the <div class="item"> and placing it directly under the <div class="carousel-inner">. No need for any additional CSS or HTML. Example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="item active">
      <img src="http://placehold.it/1200x500/3498db/2980b9" alt="First slide">
    </div>
    <div class="item">
      <img src="http://placehold.it/1200x500/9b59b6/8e44ad" alt="Second slide">
    </div>
    <div class="item">
      <img src="http://placehold.it/1200x500/34495e/2c3e50" alt="Third slide">
    </div>
    <div class="carousel-caption">
      <h3>Static Headline And Content</h3>
      <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
    </div>
  </div>
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
</div>

The carousel is designed so we place scrolling content inside <div class="item"> and fixed content directly inside <div class="carousel-inner">. We can provide both, but they will overlap each other and we need additional CSS to move them apart. But most cases don't need both at the same time.


问:
How to render a React component multiple times but each time with an updated State?
So I am working on a react project. I have a text area where I enter data and then that data is hashed and a Block with the Block number, hashed data and time is rendered on the screen whenever a button is clicked. However, when I enter the data again and hit the button again, it just rerenders the block as block number 2. I want the previous block to remain on screen and a new block to be rendered below the previous block whenever I click the button. How do I solve this? I have tried a lot but nothing seems to work. I am in the learning stages of react so please excuse me if this question seems trivial.

App.js

```<code>import React, {Component} from 'react';
import BlockList from './BlockList.js';
import InputText from './InputText.js';
import Button from './Button.js';

constructor() {
  super();
  console.log('constructor invoked')
  this.state = {
    blockno:0,
    Data:'',
    hash:'',
    showDiv: false

  }

onButtonClick = (event) => {
  console.log('onButtonClick invoked')
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}

}

render() {

  return(
    <div>
<InputText onSearchChange={this.OnSearchChange}/>
<Button onButtonClick={this.onButtonClick} />
       {
          this.state.showDiv
          ?
            <div>

              <BlockList blockno={this.state.blockno} Data={this.state.Data} />

            </div>
          : ''
        }

    </div>
    );
}

}

export default App;

</code>```

Block.js

```<code>import React from 'react';
import SHA256 from 'sha256-es';

const Block = ({blockno,Data}) => {

        const hashdata = () =>{
            return(
                SHA256.hash(Data)
                );
            }
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
return(
<div className="tc ws-pre">
    <h1 className="underline">Block {blockno}</h1>
    <h2>Data: {Data}</h2>
    <h2>Hash: {hashdata()}</h2>
    <h2>Date: {today}</h2>
</div>

        );

}

export default Block
</code>```

BlockList.js

```<code>import React from 'react';
import Block from './Block.js';

const BlockList = ({blockno,Data,isBlockUpdated}) => {

    const BlockItems = () => {
        return(
            <div>
                {console.log('A block item is now returned')}
                <Block blockno={blockno} Data={Data} />
            </div>
            );
    }

return(

<div>

    <BlockItems />

</div>

    );

}

export default BlockList

</code>```

I want to display a new block below the previous one every time I click the button.

答:
I've just had a quick look through. So each time you press the button in App.js you're adding 1 to blockno in the state. This is just a number so that number is just being updated and passed down into Block.js

If you want to display multiple blocks you need to create an array that you can iterate over and display a Block component for each block.

Essentially you're state needs to be something like this:

```<code>blocks: [{ block data here }]
</code>```

onButtonClick then needs to add an object to that array. Then you can pass that array down to BlockList and you can iterate over it there.

BlockList then looks something like this:

```<code>{blocks.map(block => (
  <Block data={block.data} />
))}
</code>```

Does that make sense?

Body:
So I am working on a react project. I have a text area where I enter data and then that data is hashed and a Block with the Block number, hashed data and time is rendered on the screen whenever a button is clicked. However, when I enter the data again and hit the button again, it just rerenders the block as block number 2. I want the previous block to remain on screen and a new block to be rendered below the previous block whenever I click the button. How do I solve this? I have tried a lot but nothing seems to work. I am in the learning stages of react so please excuse me if this question seems trivial.

App.js

import React, {Component} from 'react';
import BlockList from './BlockList.js';
import InputText from './InputText.js';
import Button from './Button.js';

constructor() {
  super();
  console.log('constructor invoked')
  this.state = {
    blockno:0,
    Data:'',
    hash:'',
    showDiv: false

  }

onButtonClick = (event) => {
  console.log('onButtonClick invoked')
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}

}

render() {

  return(

<InputText onSearchChange={this.OnSearchChange}/>
<Button onButtonClick={this.onButtonClick} />
       {
          this.state.showDiv
          ?

              <BlockList blockno={this.state.blockno} Data={this.state.Data} />

          : ''
        }

    );
}

}

export default App;

Block.js

import React from 'react';
import SHA256 from 'sha256-es';

const Block = ({blockno,Data}) => {

        const hashdata = () =>{
            return(
                SHA256.hash(Data)
                );
            }
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;
return(

Block {blockno}

Data: {Data}

Hash: {hashdata()}

Date: {today}

        );

}

export default Block

BlockList.js

import React from 'react';
import Block from './Block.js';

const BlockList = ({blockno,Data,isBlockUpdated}) => {

    const BlockItems = () => {
        return(

                {console.log('A block item is now returned')}
                <Block blockno={blockno} Data={Data} />

            );
    }

return(

    <BlockItems />

    );

}

export default BlockList

I want to display a new block below the previous one every time I click the button.

Body:
I've just had a quick look through. So each time you press the button in App.js you're adding 1 to blockno in the state. This is just a number so that number is just being updated and passed down into Block.js

If you want to display multiple blocks you need to create an array that you can iterate over and display a Block component for each block.

Essentially you're state needs to be something like this:

blocks: [{ block data here }]

onButtonClick then needs to add an object to that array. Then you can pass that array down to BlockList and you can iterate over it there.

BlockList then looks something like this:

{blocks.map(block => (
  <Block data={block.data} />
))}

Does that make sense?


问:
What is purpose of FDPhysSQLiteDriverLink?
When use FDPhysSQLiteDriverLink in SQLite? Is it necessary and how set up in delphi.

My Sqlite work without FDPhysSQLiteDriverLink.

答:
As I recall, I needed that for certain advanced features in some other SQLite components.

Security (TFDSQLiteSecurity).  The class allowing you to manage a SQLite database encryption/passwords.  It requires you use FDPhysSQLiteDriverLink.

Database Validation (TFDSQLiteValidate).  This component allows you to access the SQLite Validation Service to perform Sweep, Vacuum, for example.  It requires you to use FDPhysSQLiteDriverLink.

Backup (TFDSQLiteBackup).  This component allows you to perform database backup/restore/copy operations.  It requires you to use FDPhysSQLiteDriverLink.

As for setting it up, I did nothing other than add the component to my project and then point the other components mentioned above to it.  I left DriverID blank.


问:
Create method that returns associated object's attribute value if current object's attribute is nil (jsonb type)
I have the following two classes:

```<code>class Account < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb

  has_one :plan
end

class Plan < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb
end
</code>```

And will be calling features like this:

```<code>account.features    # being account is an instance of Account
# or
account.features[:feature_key]
</code>```

The thing is I want account to look for features or features[:feature_key] within itself, and if that is nil or empty it should pick the value from the associated Plan object.

Something like:

```<code>features.present? ? features : plan.features
# and
features[:feature_key].present ? features[:feature_key] : plan.features[:feature_key]
</code>```

But in a proper method within Account class

答:
Not sure I completely understand but given your comment under the other answer I am assuming you are looking for something like:

```<code>class Account < ActiveRecord::Base

  def feature_info(key)
    return plan.features[key] unless features.present? && features[key].present?
    features[key]
  end
end
</code>```

Then called as

```<code>   account = Account.first
   account.feature_info(:feature_key)
</code>```

This might be cleaner though

```<code>class Account < ActiveRecord::Base
  def features
    read_attribute(:features) || {}
  end
  def feature_info(key)
    return plan.features[key] unless features[key].present?
    features[key]
  end
end
</code>```

Body:
I have the following two classes:

class Account < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb

  has_one :plan
end

class Plan < ActiveRecord::Base
  # columns
  # ...
  # features :jsonb
end

And will be calling features like this:

account.features    # being account is an instance of Account
# or
account.features[:feature_key]

The thing is I want account to look for features or features[:feature_key] within itself, and if that is nil or empty it should pick the value from the associated Plan object.

Something like:

features.present? ? features : plan.features
# and
features[:feature_key].present ? features[:feature_key] : plan.features[:feature_key]

But in a proper method within Account class

Body:
Not sure I completely understand but given your comment under the other answer I am assuming you are looking for something like:

class Account < ActiveRecord::Base

  def feature_info(key)
    return plan.features[key] unless features.present? && features[key].present?
    features[key]
  end
end

Then called as

   account = Account.first
   account.feature_info(:feature_key)

This might be cleaner though

class Account < ActiveRecord::Base
  def features
    read_attribute(:features) || {}
  end
  def feature_info(key)
    return plan.features[key] unless features[key].present?
    features[key]
  end
end