问:
Angular - search data based on selected item
I am trying to search data depending upon selected item, as of now global search is working for all items.
suppose if i select mobile item and then type iphone 11 in search then search should be done only on mobile array list.
Can anyone please help and tell me How to search data on basis of selected option (category).

HTML

```<code><div class="container">
  <div class="mt-4">
    <div class="form-group has-search">
      <span class="fa fa-search form-control-feedback"></span>
      <input type="text" class="form-control" [(ngModel)]="searchKeywords" (keyup)="getSmartSearchValues(searchKeywords)" placeholder="Search here">
    </div>
  </div>
  <!-- Nav tabs -->
  <ul class="nav nav-tabs mt-3" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" data-toggle="tab" href="#list" (click)="getAllData()">All</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Coffee')">Coffee</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Brewer')">Brewer</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Mobile')">Mobile</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-toggle="tab" href="#list" (click)="getGlobalSearchList('DancingGoatMvc-Laptop')">Laptop</a>
    </li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div class="col p-0">
      <h5 class="mt-2">Total Results - {{this.CoffeeItemList.length}} Products</h5>
    </div>
    <div id="menu1" class="tab-pane container active in">
      <div class="row">
      <div class="card col-3" *ngFor="let items of CoffeeItemList">
        <div class="card-body">
          <h5 class="card-title">{{items?.title }}</h5>
          <div class="img-box">

            <img src="http://infogainpune.com{{items.image |slice:1}}" class="w-100" onerror="this.src='https://thestonecafe.com/saved/noImageAvailable.gif';"  alt="..." />
          </div>
          <p class="card-text">{{items?.content}}</p>
          <h4 class="card-text item-prics">${{items?.price}}</h4>
          <h5 class="card-text item-type"> {{items?.type | slice:15}}</h5>
        </div>
      </div>
    </div>
    </div>
    <div *ngIf="! CoffeeItemList?.length" class="mt-5 text-center">
       <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRMp-5DU0H4U_joMB6heA3nMMcUZe8EjqMqb0nVRql4CbTWSi6V"/>
 </div>
  </div>
</div>
</code>```

TS

```<code>searchKeywords: string;
  coffeeResults: any;
  CoffeeItemList: any = [];

  // tslint:disable-next-line:max-line-length
  constructor(private getDataListingService: DataListingService) {}

  ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
  }
  getAllData() {
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
    });
  }
  getGlobalSearchList(type: string) {
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
      let data = [];
      data = value.data;
      console.log(data);
      for (let i = 0; i < data.length - 1; i++) {
        if (data[i].type === type) {
            this.CoffeeItemList.push(data[i]);
        }
    }
    });
  }
  getSmartSearchValues(search: string) {
    if (search === '' ) {
      this.getGlobalSearchList('');
      return false;
    }
    this.getDataListingService.searchList(search).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
}
</code>```

This service code is for searching data
smart-search.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { SmartSearchList } from '../shared/models/smartSearchList';

@Injectable({
  providedIn: 'root'
})
export class SmartSearchService {

  baseUrl = 'apiurlhere';

  constructor(private http: HttpClient) { }

  getAllSmartSearchDataLists(): Observable<SmartSearchList> {
    return this.http.get<SmartSearchList>(this.baseUrl);
  }
}
</code>```

Displaying list of product
data-listing.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DataLists  } from '../shared/models/dataListing';

@Injectable({
  providedIn: 'root'
})
export class DataListingService {
  baseUrl = 'http://infogainpune.com/api/products';

  constructor(private http: HttpClient) { }

  getAllDataLists(): Observable<DataLists> {
    return this.http.get<DataLists>(this.baseUrl);
  }

  searchList(search: string): Observable<DataLists> {
    return this.http.get<DataLists>('search url here' + search);
  }
}
</code>```

JSON Response

JSON Product response attributes

答:
Try this,
Take one variable to store selected type value.

TS

```<code>selectedType: string = '';

getGlobalSearchList(type: string) {

    this.selectedType = type;
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {

        let data = [];
        data = value.data;
        console.log(data);
        for (let i = 0; i < data.length - 1; i++) {
            if (data[i].type === type) {
                this.CoffeeItemList.push(data[i]);
            }
        }
    });
}

getSmartSearchValues(search: string) {
    if (search === '' ) {
        this.getGlobalSearchList('');
        return false;
    }
    this.getDataListingService.searchList(search).subscribe(value => {

        let data = [];
        data = value.data;
        this.CoffeeItemList = value.data;

        // check selected type either coffee, mobile or ALL.
        if(this.selectedType && this.selectedType != '') {
            this.CoffeeItemList = [];
            for (let i = 0; i < data.length - 1; i++) {
                if (data[i].type === this.selectedType) {
                    this.CoffeeItemList.push(data[i]);
                }
            }
        }
    });
}
</code>```

Body:
I am trying to search data depending upon selected item, as of now global search is working for all items.
suppose if i select mobile item and then type iphone 11 in search then search should be done only on mobile array list.
Can anyone please help and tell me How to search data on basis of selected option (category).

HTML

      <input type="text" class="form-control" [(ngModel)]="searchKeywords" (keyup)="getSmartSearchValues(searchKeywords)" placeholder="Search here">

      All

      Coffee

      Brewer

      Mobile

      Laptop

Total Results - {{this.CoffeeItemList.length}} Products

{{items?.title }}

{{items?.content}}

${{items?.price}}

 {{items?.type | slice:15}}

TS

searchKeywords: string;
  coffeeResults: any;
  CoffeeItemList: any = [];

  // tslint:disable-next-line:max-line-length
  constructor(private getDataListingService: DataListingService) {}

  ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
  }
  getAllData() {
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
    });
  }
  getGlobalSearchList(type: string) {
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
      let data = [];
      data = value.data;
      console.log(data);
      for (let i = 0; i < data.length - 1; i++) {
        if (data[i].type === type) {
            this.CoffeeItemList.push(data[i]);
        }
    }
    });
  }
  getSmartSearchValues(search: string) {
    if (search === '' ) {
      this.getGlobalSearchList('');
      return false;
    }
    this.getDataListingService.searchList(search).subscribe(value => {
      this.CoffeeItemList = value.data;
    });

  }
}

This service code is for searching data
smart-search.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { SmartSearchList } from '../shared/models/smartSearchList';

@Injectable({
  providedIn: 'root'
})
export class SmartSearchService {

  baseUrl = 'apiurlhere';

  constructor(private http: HttpClient) { }

  getAllSmartSearchDataLists(): Observable<SmartSearchList> {
    return this.http.get<SmartSearchList>(this.baseUrl);
  }
}

Displaying list of product
data-listing.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DataLists  } from '../shared/models/dataListing';

@Injectable({
  providedIn: 'root'
})
export class DataListingService {
  baseUrl = 'http://infogainpune.com/api/products';

  constructor(private http: HttpClient) { }

  getAllDataLists(): Observable<DataLists> {
    return this.http.get<DataLists>(this.baseUrl);
  }

  searchList(search: string): Observable<DataLists> {
    return this.http.get<DataLists>('search url here' + search);
  }
}

JSON Response

JSON Product response attributes

Body:
Try this,
Take one variable to store selected type value.

TS

selectedType: string = '';

getGlobalSearchList(type: string) {

    this.selectedType = type;
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {

        let data = [];
        data = value.data;
        console.log(data);
        for (let i = 0; i < data.length - 1; i++) {
            if (data[i].type === type) {
                this.CoffeeItemList.push(data[i]);
            }
        }
    });
}

getSmartSearchValues(search: string) {
    if (search === '' ) {
        this.getGlobalSearchList('');
        return false;
    }
    this.getDataListingService.searchList(search).subscribe(value => {

        let data = [];
        data = value.data;
        this.CoffeeItemList = value.data;

        // check selected type either coffee, mobile or ALL.
        if(this.selectedType && this.selectedType != '') {
            this.CoffeeItemList = [];
            for (let i = 0; i < data.length - 1; i++) {
                if (data[i].type === this.selectedType) {
                    this.CoffeeItemList.push(data[i]);
                }
            }
        }
    });
}


来源: stackexchange

问:
How to get byte[] from float number
How to get byte[] from float number? I need to create message where for data I have four bytes, datum can be unsigned int( it is easy to get byte[] from int), binary and float ( but I don't know how to get four bytes from float ). Any solution ?</p>

答:
Class java.lang.Float has methods floatToIntBits() and floatToRawIntBits() which you can use to get at the bit pattern of a float (as an int). So you could do something like this:

```<code>float value = 1.5e-3f;

int bits = Float.floatToIntBits(value);
byte[] bytes = new byte[4];
bytes[0] = (byte)(bits & 0xff);
bytes[1] = (byte)((bits >> 8) & 0xff);
bytes[2] = (byte)((bits >> 16) & 0xff);
bytes[3] = (byte)((bits >> 24) & 0xff);
</code>```

Note: You'd have to find out for your particular application which of floatToIntBits() or floatToRawIntBits() is appropriate and you'd have to determine in which order you need the bytes (little or big endian).

ContentLicense: CC BY-SA 3.0

Title: How to get byte[] from float number

Body:
Class java.lang.Float has methods floatToIntBits() and floatToRawIntBits() which you can use to get at the bit pattern of a float (as an int). So you could do something like this:

float value = 1.5e-3f;

int bits = Float.floatToIntBits(value);
byte[] bytes = new byte[4];
bytes[0] = (byte)(bits & 0xff);
bytes[1] = (byte)((bits >> 8) & 0xff);
bytes[2] = (byte)((bits >> 16) & 0xff);
bytes[3] = (byte)((bits >> 24) & 0xff);

Note: You'd have to find out for your particular application which of floatToIntBits() or floatToRawIntBits() is appropriate and you'd have to determine in which order you need the bytes (little or big endian).


问:
axios get function not working in Reactjs
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

```<code>app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

</code>```

and I call the API in my reactjs page component

```<code>class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList
</code>```

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

答:
Two things, you are not getting the correct piece of the state in your render function. You also need to deal with that both the API call and setState are async, so you can't rely on it being defined when your component is rendered.

You can do it like this:

```<code> const enduser_tbl = this.state.enduser_tbl || [];
 return (
    <Container>
        { enduser_tbl.map ((enduser, project_id) =>
            <ListGroup>
                <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                </ListGroup>
        )}
    </Container>
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

and I call the API in my reactjs page component

class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

Body:
Two things, you are not getting the correct piece of the state in your render function. You also need to deal with that both the API call and setState are async, so you can't rely on it being defined when your component is rendered.

You can do it like this:

 const enduser_tbl = this.state.enduser_tbl || [];
 return (
    <Container>
        { enduser_tbl.map ((enduser, project_id) =>
            <ListGroup>
                <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                </ListGroup>
        )}
    </Container>
)


问:
How do I set a constantly reassigning random variable that works throughout the program?
I want to create a variable called Random that is constantly changing every time I call on it.

I want this bit of code:

```<code>Random = randint(0, 10)
print Random
print Random
print Random
</code>```

not to give me something like:

```<code>6
6
6
</code>```

but rather something like:

```<code>3
6
1
</code>```

Without having to reassign Random before I use it every time. Also I used Random inside several different functions. So how do I allow it to be used everywhere in the code without having to reassign it as a random variable every single time?

Sorry if this is a stupid question but I'm very new at this and I have no idea what I'm doing. Please keep the explanations simple.

edit: here's some more code:

```<code>def something1(Random, useless, whatever)

etc...

def something2(Random, useless, whatever)

etc...

...

main():

   for index in range(800):

     Random = randint(1, 10)

     something1(Random, useless, whatever)

Random = randing(1, 10)

something2(Random, useless, whatever)
</code>```

and this goes on for a while.

答:
```<code>import numpy as np
x = "np.random.randn()"
for i in range(3):
   print(eval(x))
</code>```

eval() evaluates what's written in the str variable passed to it. Every time one calls eval(x) one gets a new random variable.

A bit of a cheating, I agree, but keeps the code a tad cleaner since eval(x) certainly looks better than calling some expression (especially if your rv distribution is defined by a intricate expression and you use it in your code quite often).

Body:
I want to create a variable called Random that is constantly changing every time I call on it.

I want this bit of code:

Random = randint(0, 10)
print Random
print Random
print Random

not to give me something like:

6
6
6

but rather something like:

3
6
1

Without having to reassign Random before I use it every time. Also I used Random inside several different functions. So how do I allow it to be used everywhere in the code without having to reassign it as a random variable every single time?

Sorry if this is a stupid question but I'm very new at this and I have no idea what I'm doing. Please keep the explanations simple.

edit: here's some more code:

def something1(Random, useless, whatever)

etc...

def something2(Random, useless, whatever)

etc...

...

main():

   for index in range(800):

     Random = randint(1, 10)

     something1(Random, useless, whatever)

Random = randing(1, 10)

something2(Random, useless, whatever)

and this goes on for a while.

Body:
import numpy as np
x = "np.random.randn()"
for i in range(3):
   print(eval(x))

eval() evaluates what's written in the str variable passed to it. Every time one calls eval(x) one gets a new random variable.

A bit of a cheating, I agree, but keeps the code a tad cleaner since eval(x) certainly looks better than calling some expression (especially if your rv distribution is defined by a intricate expression and you use it in your code quite often).


问:
Dropdownlist for select option on DataTable does not work well, How to fix this issue on my JqueryUI?
I have this code below, i want to have select options for column 'WhoAttend' and 'Description', so i implemented some dropdownlist using render to do this and was unfortunate until today. Any help will be highly appreciated, thanks mates and have seen the documentation on DataTable.net but i could not get this right. Surely i am missing some little bit of logic somehow and need some guidance to this logic below.</p>

```<code><h2>EventManagement List</h2>
<table id="EventsManagementsTable" class="cell-border" style="width:100%">

    <thead>
        <tr>

            <th>TrainingType</th>
            <th>TrainingDescription</th>
            <th>Price</th>
            <th>Venue</th>
            <th>Facilitator</th>
            <th>WhoAttend</th>
            <th>RSVP</th>
        </tr>
    </thead>

</table>

@section scripts{

    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>

    <script>

        $(document).ready(function () {

            $("#EventsManagementsTable").DataTable({

                "columns": [
                    {
                        "data": "WhoAttend",
                        "name": "WhoAttend",
                        "render": function (value) {
                            return $("<select/>")
                                .addClass("form-control")
                                .attr("name", "WhoAttend")
                                .append($("<option/>").text("Engineers"))
                                .append($("<option/>").text("Inspectors"))
                                .append($("<option/>").text("Technicians"))
                                .val(value)
                                .html();
                        }
                    }

                ],

                "serverSide": "true",
                "order": [0, "asc"],
                "processing": "true",
                "paginng": true,
                "ordering":true,
                "language": {
                    "processing": "processing...... please wait"
                },

                "ajax": {
                    "url": "/Dashboard/GetData",
                    "type": "POST",
                    "datatype": "JSON"

                },
                "columns": [
                    { "data": "TrainingType", "name": "TrainingType", "autoWidth": true },
                    { "data": "TrainingDescription", "name": "TrainingDescription", "autoWidth": true },
                    { "data": "Price", "name": "Price", "autoWidth": true },
                    { "data": "Venue", "name": "Venue", "autoWidth": true },
                    { "data": "Facilitator", "name": "Facilitator", "autoWidth": true },
                    { "data": "WhoAttend", "name": "WhoAttend", "autoWidth": true },
                    { "data": "RSVP", "name": "RSVP", "autoWidth": true },

                ]

            });

        });

    </script>

// Remodified code
        $(document).ready(function () {

            $("#EventsManagementsTable").DataTable({

                /*"columns": [
                    {
                        "data": "WhoAttend",
                        "name": "WhoAttend",
                        "render": function (value) {
                            return $("<select/>")
                                .addClass("form-control")
                                .attr("name", "WhoAttend")
                                .append($("<option/>").text("Engineers"))
                                .append($("<option/>").text("Inspectors"))
                                .append($("<option/>").text("Technicians"))
                                .val(value)
                                .html();
                        }
                    }

                ],
                */
                  "columns": [
                    { "data": "TrainingType", "name": "trainingType", "autoWidth": true },
                    { "data": "TrainingDescription", "name": "trainingDescription", "autoWidth": true },
                    { "data": "Price", "name": "price", "autoWidth": true },
                    { "data": "Venue", "name": "venue", "autoWidth": true },
                    { "data": "Facilitator", "name": "facilitator", "autoWidth": true },
                    { "data": "WhoAttend", "name": "whoAttend", "autoWidth": true },
                    { "data": "RSVP", "name": "rsvp", "autoWidth": true },

                ],

                "serverSide": "true",
                "order": [0, "asc"],
                "processing": "true",
                "paging": true,
                "ordering":true,
                "language": {
                    "processing": "processing...... please wait"
                },

                "ajax": {
                    "url": "/Dashboard/GetData",
                    "type": "POST",
                    "datatype": "JSON"

                }

            });

        });

    </script>
</code>```

答:
Without knowing more about the problem I would give you a few things to try:

You are defining "columns" definition twice. Once above and once below. It is likely to take the value of the second one and overwrite the first one you define up top so put the top one in the rest at the bottom an decide if you are going to override it.

Simple thing is paging is misspelled maybe:

"paginng": true,

Change to "paging"

Validate the specified values for data such as "TrainingType" are the same as in the data set returned in the JSON from the server? For example is it like this:

{ "trainingType": {value}, "trainingDescription": {value}, "price": {value}, "venue":{value}, "facilitator": {value}, "whoAttend": {value}, "rsvp": {value} }

I only ask because often JSON data is returned in camel case so it would be good to check if the data table code is case sensitive?

Edit: Ah, I see what is going on this is that one thing where it doesn't like to make selects. I don't remember what the rationale for it was but anyways here is some code that will work.

```<code>$(document).ready(function () {
    $("#EventsManagementsTable").DataTable({
        "serverSide": "true",
        "order": [0, "asc"],
        "processing": "true",
        "paging": true,
        "ordering":true,
        "language": {
            "processing": "processing...... please wait"
        },
        "ajax": {
            "url": "/Dashboard/GetData",
            "type": "GET",
            "datatype": "JSON"
        },
        "columns": [
            { "data": "trainingType", "name": "TrainingType", "autoWidth": true },
            { "data": "trainingDescription", "name": "TrainingDescription", "autoWidth": true },
            { "data": "price", "name": "Price", "autoWidth": true },
            { "data": "venue", "name": "Venue", "autoWidth": true },
            { "data": "facilitator", "name": "Facilitator", "autoWidth": true },
            {
                "data": "whoAttend",
                "name": "WhoAttend",
                "render": function (value) {
                    var sel = $('<select />')
                         .addClass("form-control")
                         .attr("name", "WhoAttend")
                         .append($("<option/>", { text: "Engineers", value: "Engineers" }))
                         .append($("<option/>", { text: "Inspectors", value: "Inspectors" }))
                         .append($("<option/>", { text: "Technicians", value: "Technicians" }))[0];

                    $(sel.options).each(function() {
                        if(this.value === value) {
                            $(this).attr("selected",true);
                        }
                    });

                    return sel.outerHTML;
                },
                "autoWidth": true
            },
            { "data": "rsvp", "name": "RSVP", "autoWidth": true }
        ]
    });
});
</code>```

P.S. Don't hold the [0] part of that one line against me. It works. ;-) Maybe you could tell me why it works this way. I remember something like this happening before and someone told me why the val() doesn't select and why the select creation messes up and a more proper way to do it but I don't remember what it all was now. Anyways the code above should surely work now for sure.

Body:
I have this code below, i want to have select options for column 'WhoAttend' and 'Description', so i implemented some dropdownlist using render to do this and was unfortunate until today. Any help will be highly appreciated, thanks mates and have seen the documentation on DataTable.net but i could not get this right. Surely i am missing some little bit of logic somehow and need some guidance to this logic below.

EventManagement List

            TrainingType
            TrainingDescription
            Price
            Venue
            Facilitator
            WhoAttend
            RSVP

@section scripts{

// Remodified code
        $(document).ready(function () {

            $("#EventsManagementsTable").DataTable({

                /*"columns": [
                    {
                        "data": "WhoAttend",
                        "name": "WhoAttend",
                        "render": function (value) {
                            return $("<select/>")
                                .addClass("form-control")
                                .attr("name", "WhoAttend")
                                .append($("<option/>").text("Engineers"))
                                .append($("<option/>").text("Inspectors"))
                                .append($("<option/>").text("Technicians"))
                                .val(value)
                                .html();
                        }
                    }

                ],
                */
                  "columns": [
                    { "data": "TrainingType", "name": "trainingType", "autoWidth": true },
                    { "data": "TrainingDescription", "name": "trainingDescription", "autoWidth": true },
                    { "data": "Price", "name": "price", "autoWidth": true },
                    { "data": "Venue", "name": "venue", "autoWidth": true },
                    { "data": "Facilitator", "name": "facilitator", "autoWidth": true },
                    { "data": "WhoAttend", "name": "whoAttend", "autoWidth": true },
                    { "data": "RSVP", "name": "rsvp", "autoWidth": true },

                ],

                "serverSide": "true",
                "order": [0, "asc"],
                "processing": "true",
                "paging": true,
                "ordering":true,
                "language": {
                    "processing": "processing...... please wait"
                },

                "ajax": {
                    "url": "/Dashboard/GetData",
                    "type": "POST",
                    "datatype": "JSON"

                }

            });

        });

    </script>

Body:
Without knowing more about the problem I would give you a few things to try:

You are defining "columns" definition twice. Once above and once below. It is likely to take the value of the second one and overwrite the first one you define up top so put the top one in the rest at the bottom an decide if you are going to override it.

Simple thing is paging is misspelled maybe:

"paginng": true,

Change to "paging"

Validate the specified values for data such as "TrainingType" are the same as in the data set returned in the JSON from the server? For example is it like this:

{ "trainingType": {value}, "trainingDescription": {value}, "price": {value}, "venue":{value}, "facilitator": {value}, "whoAttend": {value}, "rsvp": {value} }

I only ask because often JSON data is returned in camel case so it would be good to check if the data table code is case sensitive?

Edit: Ah, I see what is going on this is that one thing where it doesn't like to make selects. I don't remember what the rationale for it was but anyways here is some code that will work.

$(document).ready(function () {
    $("#EventsManagementsTable").DataTable({
        "serverSide": "true",
        "order": [0, "asc"],
        "processing": "true",
        "paging": true,
        "ordering":true,
        "language": {
            "processing": "processing...... please wait"
        },
        "ajax": {
            "url": "/Dashboard/GetData",
            "type": "GET",
            "datatype": "JSON"
        },
        "columns": [
            { "data": "trainingType", "name": "TrainingType", "autoWidth": true },
            { "data": "trainingDescription", "name": "TrainingDescription", "autoWidth": true },
            { "data": "price", "name": "Price", "autoWidth": true },
            { "data": "venue", "name": "Venue", "autoWidth": true },
            { "data": "facilitator", "name": "Facilitator", "autoWidth": true },
            {
                "data": "whoAttend",
                "name": "WhoAttend",
                "render": function (value) {
                    var sel = $('<select />')
                         .addClass("form-control")
                         .attr("name", "WhoAttend")
                         .append($("<option/>", { text: "Engineers", value: "Engineers" }))
                         .append($("<option/>", { text: "Inspectors", value: "Inspectors" }))
                         .append($("<option/>", { text: "Technicians", value: "Technicians" }))[0];

                    $(sel.options).each(function() {
                        if(this.value === value) {
                            $(this).attr("selected",true);
                        }
                    });

                    return sel.outerHTML;
                },
                "autoWidth": true
            },
            { "data": "rsvp", "name": "RSVP", "autoWidth": true }
        ]
    });
});

P.S. Don't hold the [0] part of that one line against me. It works. ;-) Maybe you could tell me why it works this way. I remember something like this happening before and someone told me why the val() doesn't select and why the select creation messes up and a more proper way to do it but I don't remember what it all was now. Anyways the code above should surely work now for sure.


问:
Initializing Vuex parameter with a value from an array
I have this code for Vuex and I wanted to initialize a parameter's default value to a value from a Vuex array. How do I do this?

```<code>passcode: this.state.passcodes[0].value
</code>```

It results to an error stating

```<code>Cannot read property 'state' of undefined
</code>```

```<code>const store = new Vuex.Store({
  state: {
    passcodes: [
      {
        label: 'Pass1',
        value: '123456',
      },
      {
        label: 'Pass2',
        value: '654321',
      }
    ],
    data: [
      {
        name: '',
        passcode: this.state.passcode[0].value
      }
    ]
  }
})
</code>```

How do I do this??

答:
const passcodes = [
  {
    label: 'Pass1',
    value: '123456',
  },
  {
    label: 'Pass2',
    value: '654321',
  }
]

const store = new Vuex.Store({
  state: {
    passcodes,
    data: [
      {
        name: '',
        passcode: passcodes[0].value
      }
    ]
  }
})
```

Body:
I have this code for Vuex and I wanted to initialize a parameter's default value to a value from a Vuex array. How do I do this?

passcode: this.state.passcodes[0].value

It results to an error stating

Cannot read property 'state' of undefined

const store = new Vuex.Store({
  state: {
    passcodes: [
      {
        label: 'Pass1',
        value: '123456',
      },
      {
        label: 'Pass2',
        value: '654321',
      }
    ],
    data: [
      {
        name: '',
        passcode: this.state.passcode[0].value
      }
    ]
  }
})

How do I do this??


问:
Need to parse a Json object and append it to a table
```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function myFunction() {
            var abc, obj, i, j;
            abc = {
                "cars": [
                    '{"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]}',
                    '{"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]}',
                    '{"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}'
                ]
            }
            var obj = JSON.parse(abc);
            var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
            document.getElementById("dtable").appendChild(theader);
            var x;
            for (i = 0; i < abc.cars.length; i++) {
                x += "<tr><td>" + obj.cars[i].model + "</td><td>" + obj.cars[i].doors + "</td><td>" + obj.cars[i].lol[0] + "</td></tr>";
                document.getElementById("dtable").appendChild(x);
            }
        };
    </script>
</head>
<body>
    <div class="container" ,id="dsjson">
        <button type="button" onclick="myFunction()">display json</button>
        <br><br>
        <table id="dtable"></table>
    </div>
</body>
</html>
</code>```

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

答:
Use some JSON validator tools like https://jsonlint.com/ or similar.

Now no need for abc var.

```<code>var obj = {
  cars: [
    {
      model: "Sentra",
      doors: 4,
      lol: ["hi", "hello", "hahahaha"]
    },
    {
      model: "Maxima",
      doors: 4,
      lol: ["hi", "hello", "hahahaha"]
    },
    {
      model: "Skyline",
      doors: 2,
      lol: ["hi", "hello", "hahahaha"]
    }
  ]
};
</code>```

Body:
<!DOCTYPE html>

        <button type="button" onclick="myFunction()">display json</button>

The nested json data needs to be displayed in the HTML table. On clicking the button the table displaying the json must appear. We can use JavaScript or JQuery For that one. In my example, I am using JavaScript. I don't know where it's going wrong.

Body:
Use some JSON validator tools like https://jsonlint.com/ or similar.

Now no need for abc var.

var obj = {
  cars: [
    {
      model: "Sentra",
      doors: 4,
      lol: ["hi", "hello", "hahahaha"]
    },
    {
      model: "Maxima",
      doors: 4,
      lol: ["hi", "hello", "hahahaha"]
    },
    {
      model: "Skyline",
      doors: 2,
      lol: ["hi", "hello", "hahahaha"]
    }
  ]
};


问:
How can I reduce the repetitive work of this jquery source?
```<code>   $("#sel1").click(function () {
    $("#itemed1").attr("src", "../img/tab_img_01_on.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
    $("#itemed2").attr("src", "../img/tab_img_02_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
    $("#itemed3").attr("src", "../img/tab_img_03_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
    $("#itemed4").attr("src", "../img/tab_img_04_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
});
</code>```

Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?

答:
This will work up to selects with the number 9. It will need a little more work to make it work with numbers grater then 9

```<code>   $("[id^=sel]").click(function () {  // match every element where the id starts with "sel"
    var idNumber = $(this).attr('id').match(/\d+/); // get the number of given id
    // reset all src paths from all given elements
    $("#itemed1, #itemed2, #itemed3, #itemed4").attr("src", "../img/tab_img_01.png");

    // use the idNumber to concatenate the selector and set the src
    $("#itemed" + idNumber).attr("src", "../img/tab_img_0"+idNumber+"_on.png");

    // remove the add class to all given elements
    $("#sel1, #sel2, #sel3, #sel4").find("span").removeClass("add");

    // add the "add" class to $(this) element
    $(this).find("span").addClass("add");
});
</code>```

Body:
   $("#sel1").click(function () {
    $("#itemed1").attr("src", "../img/tab_img_01_on.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
    $("#itemed2").attr("src", "../img/tab_img_02_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
    $("#itemed3").attr("src", "../img/tab_img_03_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
    $("#itemed4").attr("src", "../img/tab_img_04_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
});

Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?

Body:
This will work up to selects with the number 9. It will need a little more work to make it work with numbers grater then 9

   $("[id^=sel]").click(function () {  // match every element where the id starts with "sel"
    var idNumber = $(this).attr('id').match(/\d+/); // get the number of given id
    // reset all src paths from all given elements
    $("#itemed1, #itemed2, #itemed3, #itemed4").attr("src", "../img/tab_img_01.png");

    // use the idNumber to concatenate the selector and set the src
    $("#itemed" + idNumber).attr("src", "../img/tab_img_0"+idNumber+"_on.png");

    // remove the add class to all given elements
    $("#sel1, #sel2, #sel3, #sel4").find("span").removeClass("add");

    // add the "add" class to $(this) element
    $(this).find("span").addClass("add");
});


问:
How to create a single select list box that shows the selection using Razor
How do I create a simple, single select list box using the Razor view engine? I'm currently running into two problems. The first is that the list box "Select" code generated has 'multiple' automatically added. Question One is how to turn that off. No, I don't want to have to use a drop down list box.

Question Two is trickier. The generated "Select" in the output html does not show any items as being selected, despite the item in question have selected values. Here's my code:

Object model:

```<code>public class Description
{
    public String code { get; set; }
    public SelectList codelist;
}
</code>```

Controller:

```<code>code = "drain";
codelist = new SelectList(sourcelist, "Key", "Value", "drain");
</code>```

View:

```<code>@Html.ListBoxFor(model => model.code, Model.codelist)
</code>```

Output HTML:

```<code><select data-val="true" data-val-required="The Select the permit type to apply for field is required." id="code" multiple="multiple" name="code"><option value="drain">Interior Drain Repair</option>
... yadda yadda yadda
</select>
</code>```

You can see my two problems here. First, "multiple" has been added to the select list, and the selected option "drain" is not selected.

Any suggestions? I'm at the point of just tossing Razor and hand coding this stuff.

答: User Html.DropDownList instead of Html.ListBox to create a single select box.

ContentLicense: CC BY-SA 2.5

Body:
How do I create a simple, single select list box using the Razor view engine? I'm currently running into two problems. The first is that the list box "Select" code generated has 'multiple' automatically added. Question One is how to turn that off. No, I don't want to have to use a drop down list box.

Question Two is trickier. The generated "Select" in the output html does not show any items as being selected, despite the item in question have selected values. Here's my code:

Object model:

public class Description
{
    public String code { get; set; }
    public SelectList codelist;
}

Controller:

code = "drain";
codelist = new SelectList(sourcelist, "Key", "Value", "drain");

View:

@Html.ListBoxFor(model => model.code, Model.codelist)

Output HTML:

<select data-val="true" data-val-required="The Select the permit type to apply for field is required." id="code" multiple="multiple" name="code"><option value="drain">Interior Drain Repair</option>
... yadda yadda yadda
</select>

You can see my two problems here. First, "multiple" has been added to the select list, and the selected option "drain" is not selected.

Any suggestions? I'm at the point of just tossing Razor and hand coding this stuff.


问:
Problems with pip3 and pipenv with Mac OS Catalina fresh install
I installed xcode dev tools first using

```<code>%xcode-select --install
</code>```

then I installed Homebrew using

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

then I did

```<code>%brew install python3

%pip3 install pipenv
</code>```

but when I call

```<code>%pip3
</code>```

I get

```<code>% pip3
Traceback (most recent call last):
  File "/Library/Developer/CommandLineTools/usr/bin/pip3", line 10, in <module>
    sys.exit(main())
TypeError: 'module' object is not callable
</code>```

This is where it says my pip3 and python3 are located

```<code>% which pip3
/usr/bin/pip3

% which python3
/usr/bin/python3
</code>```

Can someone please help me solve this problem. I am trying to learn to program but I can't continue without fixing this

答:
I had a similar problem after upgrading to Catalina since I was already using homebrew and Python/pipenv stopped to work as expected. My Python crashed every time, I ran pipenv install with an error described in this developer.apple.com thread. The answer by Mickey Ristroph sounds like a okay'ish workaround, but it doesn't really solve the problem.

I want to be able to use homebrew for all my MacOS installed software - including Python. But there was help, since the problem was the usage of a wrong version libcrypto dylib version. To fix the issue, update & upgrade brew packages and be sure openssl is installed:

```<code>brew update && brew upgrade && brew install openssl
</code>```

Then we create new symbolic links to the homebrew installed libssl.dylib and libcrypto.dylib libraries:

```<code># go to homebrew installed openssl dir:
cd /usr/local/Cellar/openssl/1.0.2t/lib
sudo cp libssl.1.0.0.dylib libcrypto.1.0.0.dylib /usr/local/lib/

cd /usr/local/lib
# if there are links already, you may backup them:
mv libssl.dylib libssl_bak.dylib
mv libcrypto.dylib libcrypto_bak.dylib

# now create new symbolic links:
sudo ln -s libssl.1.0.0.dylib libssl.dylib
sudo ln -s libcrypto.1.0.0.dylib libcrypto.dylib
</code>```

Now my homebrew installed Python (and pipenv) works like a charm again.

Body:
I installed xcode dev tools first using

%xcode-select --install

then I installed Homebrew using

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

then I did

%brew install python3

%pip3 install pipenv

but when I call

%pip3

I get

% pip3
Traceback (most recent call last):
  File "/Library/Developer/CommandLineTools/usr/bin/pip3", line 10, in <module>
    sys.exit(main())
TypeError: 'module' object is not callable

This is where it says my pip3 and python3 are located

% which pip3
/usr/bin/pip3

% which python3
/usr/bin/python3

Can someone please help me solve this problem. I am trying to learn to program but I can't continue without fixing this

Body:
I had a similar problem after upgrading to Catalina since I was already using homebrew and Python/pipenv stopped to work as expected. My Python crashed every time, I ran pipenv install with an error described in this developer.apple.com thread. The answer by Mickey Ristroph sounds like a okay'ish workaround, but it doesn't really solve the problem.

I want to be able to use homebrew for all my MacOS installed software - including Python. But there was help, since the problem was the usage of a wrong version libcrypto dylib version. To fix the issue, update & upgrade brew packages and be sure openssl is installed:

brew update && brew upgrade && brew install openssl

Then we create new symbolic links to the homebrew installed libssl.dylib and libcrypto.dylib libraries:

# go to homebrew installed openssl dir:
cd /usr/local/Cellar/openssl/1.0.2t/lib
sudo cp libssl.1.0.0.dylib libcrypto.1.0.0.dylib /usr/local/lib/

cd /usr/local/lib
# if there are links already, you may backup them:
mv libssl.dylib libssl_bak.dylib
mv libcrypto.dylib libcrypto_bak.dylib

# now create new symbolic links:
sudo ln -s libssl.1.0.0.dylib libssl.dylib
sudo ln -s libcrypto.1.0.0.dylib libcrypto.dylib

Now my homebrew installed Python (and pipenv) works like a charm again.


问:
Google sitemap error ParseEntityRef: no name on opencart 3
It's my first time using opencart and Google sitemap
Here is my error
Sitemap URL https://www.startpc.ro/index.php?route=extension/feed/google_sitemap
Character Set

Sitemap is valid    No

Warnings  - Errors     [68] xmlParseEntityRef: no name on line 1 [68]
  xmlParseEntityRef: no name on line 1

I don't understand where is my problem
Can someone please explain me how to fix it?
Thank You

答:
How to Setup Google Sitemap in OpenCart 3.x

Time to learn about the Google Sitemap and how to set it up in your new OpenCart 3 installation.

A Sitemap is an organized list of all the web pages in your store, which makes it easier for search engines like Google to scan them. This allows Google to find an index of all the content in your site faster and easier.

In OpenCart, it’s very easy to set up your Sitemap using the Extension system.

Video Tutorials Click Here

The first step is to go to your OpenCart admin and go to Extensions and then Extensions again.

Click the dropdown and select Feeds.

You will see the Google Sitemap extension. Hit the install button and then click Edit.

The first field is to just enable and disable the status of the sitemap. The second field is to enter the data feed URL.

Where to get this URL?

Go to Google Webmaster Tools. There will be a link in the description.

Click the Add a Property button and enter your store’s domain.

You will be asked to verify your ownership of the site.

You have a few ways to do this. We will use the recommended method, which is to upload an HTML verification document to our site.

To upload this document, we will use FileZilla. Access your OpenCart root directory and upload the file there.

Now, open the confirmation link and then verify your entry.

If everything is okay, go to the Crawl menu in your dashboard and click on Sitemaps.

There you’ll see the test/add sitemap button. You will need to enter the last part of your Data Feed URL excluding your site’s main domain.

Hit the submit button and your sitemap should now be ready and active.

Well, that’s all. Your site will now be easier for Google to digest and your pages will be indexed much faster.


问:
Streaming video from Door Station of Hikvision (DS-KV8102-IP)
I need to start Two way audio with Door Station camera Hikvision (DS-KV8102-IP)
I am using Curl to test:

curl --digest -u admin:admin http://192.168.1.224:8102/ISAPI/System/status

It return:

```<code>Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.
</code>```

I set http port for this camera is 8102 but it did not make scene. I also tested with ivs4200 which provided by Hikvision: Camera ran fine. I have change port from 1-9999 but there are no any port work in this case.

I have test with other camera: DS-2CD2143G0-I, DS-2DE2A404IW-DE3. It ran fine.

Do you have any command to make this camera work? Do I need to change port or anything on this camera?

答: DS-KV8102-IP (and all this series) has no webGUI and cannot enable CGI. It only supports SDK from Hikvision website. I got those information from Hikvision technical support team.</p>

Body:
I need to start Two way audio with Door Station camera Hikvision (DS-KV8102-IP)
I am using Curl to test:

curl --digest -u admin:admin http://192.168.1.224:8102/ISAPI/System/status

It return:

Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.

I set http port for this camera is 8102 but it did not make scene. I also tested with ivs4200 which provided by Hikvision: Camera ran fine. I have change port from 1-9999 but there are no any port work in this case.

I have test with other camera: DS-2CD2143G0-I, DS-2DE2A404IW-DE3. It ran fine.

Do you have any command to make this camera work? Do I need to change port or anything on this camera?


问:
Codeblocks 16-bit message
enter image description hereI'm new in Codeblocks and programming world.

( Unsupported 16-Bit Application

The program or feature
"\??C:\Users\Hossen\Desktop\C_Time\try\bin\Debug\Try.exe" cannot
start or run due to incompatibity with 64-bit versions of Windows.
Please contact the software vendor to ask if a 64-bit Windows
compatible version is available.  )

my Codeblocks showing this message and didn't print a single line.
Recently I'm facing this problem. Any One help me to solve this problem, please?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int a, b, c, GCD;
    a = 10;
    b = 20;
    for (c = 1; c <= a && c <= b; c++)
    {
        if (a % c == 0 && b % c == 0)
        {
            GCD = c;
        }
    }
    printf("%d\n", GCD);
    return 0;
}
```

答:
The code looks ok, so I guess your installation is not correct.

As you are new, to keep it simple, you probably just should reinstall Code::Blocks.

Check you have the correct version downloaded before installing. (Supporting 64bit Operating Systems, not 32 Bits)

And then try installing it in Program Files.

Hope this will help.

Title: Codeblocks 16-bit message


问:
Mate How to inject UI component
In the Mate framework for flex.  I'm trying to inject a UIComponent into a non UIComponent.

The reason is the UI component is a library component and it has methods that need to be invoked on it. I'm not able to remove the requirement to invoke the methods.

I've got something like this currently

```<code><ObjectBuilder cache="global" generator="{DashboardController}" registerTarget="true"/>
<EventHandlers type="{DashboardEvent.DASHBOARD_CREATION_COMPLETE}">
    <PropertySetter generator="{DashboardController}"
        targetKey="dashboard"
        source="{lastReturn}"
        sourceKey="target" />
</EventHandlers>
</code>```

And I'm receiving an error like this.

```
<blockquote>
---------------------------------------------------------
MATE Error: Property type mismatch, turn on the debugger for more information
EventType:test.example.events.creationComplete. Error was found in a EventHandlers list in file DashboardEventMap
---------------------------------------------------------
</blockquote>
```

I've also tried using an object builder to set the property.

答:
Got it working. lastReturn was sometimes returning null even though it was in an eventHandling block.

I didn't realise that the event object was in scope here.

```<code><EventHandlers type="{DashboardEvent.DASHBOARD_CREATION_COMPLETE}" debug="true">
    <PropertySetter generator="{DashboardController}"
            targetKey="dashboard"
            source="{event.target}" />
</EventHandlers>
</code>```

Title: Mate How to inject UI component

Body:
In the Mate framework for flex.  I'm trying to inject a UIComponent into a non UIComponent.

The reason is the UI component is a library component and it has methods that need to be invoked on it. I'm not able to remove the requirement to invoke the methods.

I've got something like this currently

<ObjectBuilder cache="global" generator="{DashboardController}" registerTarget="true"/>
<EventHandlers type="{DashboardEvent.DASHBOARD_CREATION_COMPLETE}">
    <PropertySetter generator="{DashboardController}"
        targetKey="dashboard"
        source="{lastReturn}"
        sourceKey="target" />
</EventHandlers>

And I'm receiving an error like this.

---------------------------------------------------------
MATE Error: Property type mismatch, turn on the debugger for more information
EventType:test.example.events.creationComplete. Error was found in a EventHandlers list in file DashboardEventMap
---------------------------------------------------------

I've also tried using an object builder to set the property.

Body:
Got it working. lastReturn was sometimes returning null even though it was in an eventHandling block.

I didn't realise that the event object was in scope here.

<EventHandlers type="{DashboardEvent.DASHBOARD_CREATION_COMPLETE}" debug="true">
    <PropertySetter generator="{DashboardController}"
            targetKey="dashboard"
            source="{event.target}" />
</EventHandlers>


问:
The need for pure in Applicatives
I'm learning Haskell's Applicatives. It seems to me (I'm probably wrong) that the pure function is not really needed, for example:

```<code>pure (+) <*> [1,2,3] <*> [3,4,5]
</code>```

can be written as

```<code>(+) <$> [1,2,3] <*> [3,4,5]
</code>```

Can someone explain the benefit that the pure function provides over explicit mapping with fmap?

答:
I'm at the edge of my competency here, so don't take this for more than it is, but it was a bit too long for a comment.

There may be practical reasons to include pure in the type class, but many Haskell abstractions are derived from theoretical foundations, and I believe that that's the case for Applicative as well. As the documentation says, it's a strong lax monoidal functor (see https://cstheory.stackexchange.com/q/12412/56098 for a elaboration). I suppose that pure serves as the identity, just like return does for Monad (which is a monoid in the category of endofunctors).

Consider pure and liftA2:

```<code>pure :: a -> f a
liftA2 :: (a -> b -> c) -> f a -> f b -> f c
</code>```

If you squint a little, you may be able to imagine that liftA2 is a binary operation, which is also what the documentation states:

Lift a binary function to actions.

pure, then, is the corresponding identity.

Title: The need for pure in Applicatives

Body:
I'm learning Haskell's Applicatives. It seems to me (I'm probably wrong) that the pure function is not really needed, for example:

pure (+) <*> [1,2,3] <*> [3,4,5]

can be written as

(+) <$> [1,2,3] <*> [3,4,5]

Can someone explain the benefit that the pure function provides over explicit mapping with fmap?

Body:
I'm at the edge of my competency here, so don't take this for more than it is, but it was a bit too long for a comment.

There may be practical reasons to include pure in the type class, but many Haskell abstractions are derived from theoretical foundations, and I believe that that's the case for Applicative as well. As the documentation says, it's a strong lax monoidal functor (see https://cstheory.stackexchange.com/q/12412/56098 for a elaboration). I suppose that pure serves as the identity, just like return does for Monad (which is a monoid in the category of endofunctors).

Consider pure and liftA2:

pure :: a -> f a
liftA2 :: (a -> b -> c) -> f a -> f b -> f c

If you squint a little, you may be able to imagine that liftA2 is a binary operation, which is also what the documentation states:

Lift a binary function to actions.

pure, then, is the corresponding identity.


答:
You have few issues in your code.

First of all appendChild() accepts a dom node as the parameter but you are providing htmlString, try insertAdjacentHTML() OR innerHTML instead.

Then you are modifying the DOM  inside the loop with the previous value, this will duplicate the result.

You can try the following way:

function myFunction(){
  var abc,i,j;
  var abc = {
  "cars": [
      {"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]},
      {"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]},
      {"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}
    ]
  };
  var theader = "
Title	Author	year
";
  document.getElementById("dtable").innerHTML = theader;
  var x ='';
  for (i=0; i <  abc.cars.length; i++) {
    x += "
" + abc.cars[i].model + "	" + abc.cars[i].doors+ "	" + abc.cars[i].lol[0]+ "
";
  }
  document.getElementById("dtable").innerHTML += x;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class ="container" id = "dsjson">
  <button type="button" onclick="myFunction()">display json</button>
  <br><br>
  <table id="dtable"></table>
</div></code>```

Title: Need to parse a Json object and append it to a table

Body:
You have few issues in your code.

First of all appendChild() accepts a dom node as the parameter but you are providing htmlString, try insertAdjacentHTML() OR innerHTML instead.

Then you are modifying the DOM  inside the loop with the previous value, this will duplicate the result.

You can try the following way:

function myFunction(){
  var abc,i,j;
  var abc = {
  "cars": [
      {"model":"Sentra", "doors":4, "lol":["hi","hello","hahahaha"]},
      {"model":"Maxima", "doors":4,"lol":["hi","hello","hahahaha"]},
      {"model":"Skyline", "doors":2,"lol":["hi","hello","hahahaha"]}
    ]
  };
  var theader = "<tr><th>Title</th><th>Author</th><th>year</th></tr>";
  document.getElementById("dtable").innerHTML = theader;
  var x ='';
  for (i=0; i <  abc.cars.length; i++) {
    x += "<tr><td>" + abc.cars[i].model + "</td><td>" + abc.cars[i].doors+ "</td><td>" + abc.cars[i].lol[0]+ "</td></tr>";
  }
  document.getElementById("dtable").innerHTML += x;
};

<div class ="container" id = "dsjson">
  <button type="button" onclick="myFunction()">display json</button>
  <br><br>
  <table id="dtable"></table>
</div>


问:
sql query question for most name in table with multiple most names
fbn table:

```<code>create table fbn (
id int,
name varchar(40),
birthday date,
gender varchar(10));

INSERT into fbn values
(1, "James", "2000-04-22", "male"),
(2, "Julia", "2006-02-27", "female"),
(3, "Ethan", "2013-05-23", "male"),
(4, "Lion", "2014-09-11", "male"),
(5, "Ethan", "2006-01-01", "male"),
(6, "Lion", "2006-02-01", "male");
</code>```

what's the name that occur most? note that there are two names (Ethan and Lion) occur most often. I have two solutions as below:

```<code>select tmp2.name
from (select tmp.name,
             dense_rank() over(order by tmp.name_count desc) rank
      from (select name,
                   count(*) name_count
            from fbn
            group by name) tmp
      ) tmp2
where tmp2.rank = 1;
</code>```

and the 2nd solution:

```<code>select name from fbn
group by name
having count(name) = (select count(name) from fbn
                      group by name
                      order by count(name) desc
                      limit 1);
</code>```

both seem to be working, but both looks like too complicated. is there any other solution that's more concise easier to understand? Thanks

答:
Disable ONLY_FULL_GROUP_BY if its enabled using:

```<code>SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
</code>```

Here in inner query provide name with occurrence count. And outer query just use that temporary table to get max count value. Now it will return single row with name & total occurrence(max).

```<code>SELECT name, MAX(occurrence)
FROM (SELECT name, COUNT(id) occurrence
FROM fbn
GROUP BY name) t;
</code>```

Body:
fbn table:

create table fbn (
id int,
name varchar(40),
birthday date,
gender varchar(10));

INSERT into fbn values
(1, "James", "2000-04-22", "male"),
(2, "Julia", "2006-02-27", "female"),
(3, "Ethan", "2013-05-23", "male"),
(4, "Lion", "2014-09-11", "male"),
(5, "Ethan", "2006-01-01", "male"),
(6, "Lion", "2006-02-01", "male");

what's the name that occur most? note that there are two names (Ethan and Lion) occur most often. I have two solutions as below:

select tmp2.name
from (select tmp.name,
             dense_rank() over(order by tmp.name_count desc) rank
      from (select name,
                   count(*) name_count
            from fbn
            group by name) tmp
      ) tmp2
where tmp2.rank = 1;

and the 2nd solution:

select name from fbn
group by name
having count(name) = (select count(name) from fbn
                      group by name
                      order by count(name) desc
                      limit 1);

both seem to be working, but both looks like too complicated. is there any other solution that's more concise easier to understand? Thanks

Body:
Disable ONLY_FULL_GROUP_BY if its enabled using:

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

Here in inner query provide name with occurrence count. And outer query just use that temporary table to get max count value. Now it will return single row with name & total occurrence(max).

SELECT name, MAX(occurrence)
FROM (SELECT name, COUNT(id) occurrence
FROM fbn
GROUP BY name) t;