问:
d3.js - area chart vertical overflow if y.domain doesn't start at 0
How do I limit the contents of an area chart to stay inside the area determined by the two axes?

Here's the situation. If I set the vertical domain to be between 0 and the maximum of my data set, I don't have a problem:

```<code>y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
</code>```

However, sometimes I can't start from 0. When I need to start from the smallest number in the data set, the problem emerges:

```<code>y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
</code>```

As you see, the blue area of the chart flows over the bottom horizontal axis, and that's just ugly and messy. I could switch to a line chart to avoid this problem, but I'd much rather keep an area chart and resolve the issue. Any solutions?

EDIT This is the full code I'm using. If the full parameter is true, then the chart starts at 0. If not, then it starts at the data minimum.

```<code>function create_area_chart(data, full){
    var svg = d3.select(".chart-holder").append("svg").attr("width","800").attr("height", "400")
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y-%m-%d")
        bisectDate = d3.bisector(function(d) { return d.date; }).left;

    var x = d3.scaleTime()
        .rangeRound([0, width]);

    var y = d3.scaleLinear()
        .rangeRound([height, 0]);

    var area = d3.area()
        .x(function(d) { return x(d.date); })
        .y1(function(d) { return y(d.value); });

    data.forEach(function(d) {
        d.date = parseTime(d.date);
        d.value = +d.value;
    });

    x.domain(d3.extent(data, function(d) { return d.date; }));
    if(full)
        y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    else
        y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));

    g.append("path")
        .datum(data)
        .attr("fill", "steelblue")
        .attr("d", area);

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("Price ($)");

    svg.append("rect")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .attr("class", "overlay")
        .attr("width", width)
        .attr("height", height);
}
</code>```

答:
I think the problem might come from the range of your scales.

Maybe try with

```<code>var y = d3.scaleLinear()
        .rangeRound([height-margin.bottom, margin.top]);
</code>```

edit : it's probably not what's wrong with your code though, since you define height minus the two margins already. Sorry, best of luck !

Body:
How do I limit the contents of an area chart to stay inside the area determined by the two axes?

Here's the situation. If I set the vertical domain to be between 0 and the maximum of my data set, I don't have a problem:

y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);

However, sometimes I can't start from 0. When I need to start from the smallest number in the data set, the problem emerges:

y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);

As you see, the blue area of the chart flows over the bottom horizontal axis, and that's just ugly and messy. I could switch to a line chart to avoid this problem, but I'd much rather keep an area chart and resolve the issue. Any solutions?

EDIT This is the full code I'm using. If the full parameter is true, then the chart starts at 0. If not, then it starts at the data minimum.

function create_area_chart(data, full){
    var svg = d3.select(".chart-holder").append("svg").attr("width","800").attr("height", "400")
        margin = {top: 20, right: 20, bottom: 30, left: 50},
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y-%m-%d")
        bisectDate = d3.bisector(function(d) { return d.date; }).left;

    var x = d3.scaleTime()
        .rangeRound([0, width]);

    var y = d3.scaleLinear()
        .rangeRound([height, 0]);

    var area = d3.area()
        .x(function(d) { return x(d.date); })
        .y1(function(d) { return y(d.value); });

    data.forEach(function(d) {
        d.date = parseTime(d.date);
        d.value = +d.value;
    });

    x.domain(d3.extent(data, function(d) { return d.date; }));
    if(full)
        y.domain([0, 1.1*d3.max(data, function(d) { return d.value; })]);
    else
        y.domain([0.91*d3.min(data, function(d) { return d.value; }), 1.1*d3.max(data, function(d) { return d.value; })]);
    area.y0(y(0));

    g.append("path")
        .datum(data)
        .attr("fill", "steelblue")
        .attr("d", area);

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("Price ($)");

    svg.append("rect")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .attr("class", "overlay")
        .attr("width", width)
        .attr("height", height);
}

Body:
I think the problem might come from the range of your scales.

Maybe try with

var y = d3.scaleLinear()
        .rangeRound([height-margin.bottom, margin.top]);

edit : it's probably not what's wrong with your code though, since you define height minus the two margins already. Sorry, best of luck !


来源: stackexchange

问:
Proper way to convert SQL results to JSON
I am creating a API using nodejs. The API takes request and responds in JSON

For example:
I have a table QUESTION in my database so a GET request to endpoint http://localhost/table/question will output the table in JSON format.

However there is a problem when performing JOINS

Considering tables QUESTION and CHOICE. A question has many choices (answers) their join will be

Table:

I am trying to convert to something like this

```<code>{
   "0":{
      "QUESTION":"If Size of integer pointer is 4 Bytes what is size of float pointer ?",
      "OPTION":{
         "A":"3 Bytes",
         "B":"32 Bits",
         "C":"64 Bits",
         "D":"12 Bytes"
      }
   },
   "1":{
      "QUESTION":"Which one is not a SFR",
      "OPTION":{
         "A":"PC",
         "B":"R1",
         "C":"SBUF"
      }
   },
   "2":{
      "QUESTION":"What is Size of DPTR in 8051",
      "OPTION":{
         "A":"16 Bits",
         "B":"8 Bytes",
         "C":"8 Bits"
      }
   },
   "3":{
      "QUESTION":"Is to_string() is valid builtin function prior to c++11 ? ",
      "OPTION":{
         "A":"Yes",
         "B":"No"
      }
   }
}
</code>```

The obvious solution is to parse it query using JOIN and convert it to JSON.
Is there any more efficient way to do it?

答:
In MySQL you can achieve this with group_concat

tablenames, fieldnames, etc are pure fantasy :-)

```<code>select
    q.text as question,
    group_concat(answer.label, ';;;') as labels,
    group_concat(answer.text, ';;;') as answers
from
    question as q
    join answer as a on a.quesion = q.id
group by
    q.text
</code>```

And then in your application (nodejs)

```<code>let resultRows = callSomeFunctionsThatReturnesAllRowsAsArray();
let properStructure = resultRows.map(row => {
    let texts = row.answers.split(';;;');
    return {
        question: row.question,
        options: row.labels.split(';;;').map((label, index) => {label: label, answer: texts[index]});
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating a API using nodejs. The API takes request and responds in JSON

For example:
I have a table QUESTION in my database so a GET request to endpoint http://localhost/table/question will output the table in JSON format.

However there is a problem when performing JOINS

Considering tables QUESTION and CHOICE. A question has many choices (answers) their join will be

Table:

I am trying to convert to something like this

{
   "0":{
      "QUESTION":"If Size of integer pointer is 4 Bytes what is size of float pointer ?",
      "OPTION":{
         "A":"3 Bytes",
         "B":"32 Bits",
         "C":"64 Bits",
         "D":"12 Bytes"
      }
   },
   "1":{
      "QUESTION":"Which one is not a SFR",
      "OPTION":{
         "A":"PC",
         "B":"R1",
         "C":"SBUF"
      }
   },
   "2":{
      "QUESTION":"What is Size of DPTR in 8051",
      "OPTION":{
         "A":"16 Bits",
         "B":"8 Bytes",
         "C":"8 Bits"
      }
   },
   "3":{
      "QUESTION":"Is to_string() is valid builtin function prior to c++11 ? ",
      "OPTION":{
         "A":"Yes",
         "B":"No"
      }
   }
}

The obvious solution is to parse it query using JOIN and convert it to JSON.
Is there any more efficient way to do it?

Body:
In MySQL you can achieve this with group_concat

tablenames, fieldnames, etc are pure fantasy :-)

select
    q.text as question,
    group_concat(answer.label, ';;;') as labels,
    group_concat(answer.text, ';;;') as answers
from
    question as q
    join answer as a on a.quesion = q.id
group by
    q.text

And then in your application (nodejs)

let resultRows = callSomeFunctionsThatReturnesAllRowsAsArray();
let properStructure = resultRows.map(row => {
    let texts = row.answers.split(';;;');
    return {
        question: row.question,
        options: row.labels.split(';;;').map((label, index) => {label: label, answer: texts[index]});
    }
});


问:
JavaScript Submit and Button
1.A user is guided through a sequence of web pages, entering details which are then stored in hidden fields until all the user information is finally sent to the server.
Each button on each webpage should be:

```<code><input type=button>
<input type=submit>
</code>```

2.A user has to enter some information on a web page. After successful validation, the information is sent to a servlet or CGI script.
The button on the webpage should be:

```<code><input type=button>
<input type=submit>
</code>```

There are two scenarios to ask you the difference between ‘submit’ and ‘button’. Can you tell me the best choice for above scenarios and why?

答:
Basically, that's your homework, and it's not cool, but the general idea here is that storing all the info on the client side and only sending it to the server at the end is:

Error-prone.

Unsecure

The user cannot resume the process from a different browser/computer.

Title: JavaScript Submit and Button

Body:
1.A user is guided through a sequence of web pages, entering details which are then stored in hidden fields until all the user information is finally sent to the server.
Each button on each webpage should be:

<input type=button>
<input type=submit>

2.A user has to enter some information on a web page. After successful validation, the information is sent to a servlet or CGI script.
The button on the webpage should be:

<input type=button>
<input type=submit>

There are two scenarios to ask you the difference between ‘submit’ and ‘button’. Can you tell me the best choice for above scenarios and why?


问:
MYSQL Workbench. Trigger that blocks a certain insertion
I'm desperately trying to make the database replace the 0 with 1 every time I insert it in a table field.
I have this field called Stazione, in which there is "numerodibinari", and I don't want it to be zero.
I've tried like this.

```<code>Create trigger gestionebinari

Before insert on stazione

for each row

Begin
If (new.'numero di binari'=0)

then
Set (new.'numero di binari'=1);
</code>```

but it still doesn't work. What can I do?

答:
You cannot use single quotes to escape column names. Use back ticks (`), instead. BTW white spaces in column names is not a good idea, nor is random unnecessary bracketing. Try</p>

```<code>drop table if exists stazione;
create table stazione(`numero di binari` int);

drop trigger if exists gestionebinari;

delimiter $$
Create trigger gestionebinari
Before insert on stazione
for each row
Begin
If new.`numero di binari`=0
then
Set new.`numero di binari`=1;
end if;
end $$
delimiter ;

insert into stazione values (0);
select * from stazione;

mysql> select * from stazione;
+------------------+
| numero di binari |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm desperately trying to make the database replace the 0 with 1 every time I insert it in a table field.
I have this field called Stazione, in which there is "numerodibinari", and I don't want it to be zero.
I've tried like this.

Create trigger gestionebinari

Before insert on stazione

for each row

Begin
If (new.'numero di binari'=0)

then
Set (new.'numero di binari'=1);

but it still doesn't work. What can I do?

Body:
You cannot use single quotes to escape column names. Use back ticks (`), instead. BTW white spaces in column names is not a good idea, nor is random unnecessary bracketing. Try

drop table if exists stazione;
create table stazione(`numero di binari` int);

drop trigger if exists gestionebinari;

delimiter $$
Create trigger gestionebinari
Before insert on stazione
for each row
Begin
If new.`numero di binari`=0
then
Set new.`numero di binari`=1;
end if;
end $$
delimiter ;

insert into stazione values (0);
select * from stazione;

mysql> select * from stazione;
+------------------+
| numero di binari |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)


问:
How to declare function prototype that returns std iterator?
So as a class assignment I'm reimplementing std::vector, and I'm having trouble with declaring the prototype for:

```<code>iterator insert ( iterator position, const T& x );
</code>```

The template for my iterator class looks like this

```<code>template<typename T>
class VectorIterator : public std::iterator<std::input_iterator_tag, T>
</code>```

The template for my vector class looks like this

```<code>template<typename T>
class Vector
</code>```

How can I declare the prototype for insert to return std::iterator instead of my own VectorIterator class?  I will of course be returning an instance of my own VectorIterator class.

答:
That function doesn't return a std::iterator; it returns a std::vector<T, Alloc>::iterator.  You need to typedef your VectorIterator in your Vector:

```<code>template <typename T>
class Vector {
    typedef VectorIterator<T> iterator;
};
</code>```

This is the return type of the insert function.  Any references to iterator and const_iterator in the std::vector specification are to the typedefs that you need to provide.

ContentLicense: CC BY-SA 2.5

Body:
So as a class assignment I'm reimplementing std::vector, and I'm having trouble with declaring the prototype for:

iterator insert ( iterator position, const T& x );

The template for my iterator class looks like this

template<typename T>
class VectorIterator : public std::iterator<std::input_iterator_tag, T>

The template for my vector class looks like this

template<typename T>
class Vector

How can I declare the prototype for insert to return std::iterator instead of my own VectorIterator class?  I will of course be returning an instance of my own VectorIterator class.

Body:
That function doesn't return a std::iterator; it returns a std::vector<T, Alloc>::iterator.  You need to typedef your VectorIterator in your Vector:

template <typename T>
class Vector {
    typedef VectorIterator<T> iterator;
};

This is the return type of the insert function.  Any references to iterator and const_iterator in the std::vector specification are to the typedefs that you need to provide.


答:
If you want your button to do something (a function with JavaScript or something like that) without the form being submitted use type="button".

If you want your button to submit the form then use type="submit".

Here is some more info on input types
https://www.w3schools.com/html/html_form_input_types.asp

Title: JavaScript Submit and Button


问:
Handling collection updates with JPA
I have a collection of custom objects and I'd like to persist it in the easiest way using JPA.

My CustomObject class is mapped to a table. Now I'm wondering if JPA provides some kind of utility to handle object collection.

In particular I'd like to add or remove objects to/from my collection and then pass to a save(Collection<CustomObject> cco) method without checking which objects have changed (which of them I need to add and which to remove...)

Is it possible?

答:
Brief explanation : so I have users and their corresponding rights. I want to be able to maintain my database with those information.

This is a solution I use :

Beans :

```<code>...
@Entity
public class User implements Serializable {
...
@OneToMany(mappedBy = "idu", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, orphanRemoval = true)
private List<Userrights> userRightsList;
...
}

...
@Entity
public class Userrights implements Serializable {
...
@JoinColumn(name = "idu", referencedColumnName = "idu")
@ManyToOne
private User idu;
...
}
</code>```

Spring :

```<code>@Component
public class UserBean implements IUser {

    @Autowired
    private MyPersistenceContext<User> pc;
    ...
    @Transactional
    @Override
    public void update(User user) throws Exception {
        pc.update(user, UPDATE_ERR);
    }
    ...
}

@Component
public class MyPersistenceContext<T> {
    @PersistenceContext
    protected EntityManager EM;
    ...
    public void insert(T object, String errMsg) {
        EM.persist(object);
    }
    public void update(T object, String errMsg) {
        EM.merge(object);
    }
...
}

public void delete(T object, String errMsg) {
    T forDeletion = null;

    if (!EM.contains(object)) {
        forDeletion = EM.merge(object);
    }

    if (forDeletion != null) {
        EM.remove(forDeletion);
    }
}
</code>```

Test :

```<code>@Test
public void testDb_InsertOrUpdateOfExistinguserRights() throws Exception {
        User u = null;
        try {
            u = IAS.DS().user().getByUsername("kor1 username");
        } catch (Exception e) {
        }

        List<Userrights> lur = new ArrayList<>();
        boolean newUser = true;

        if (u != null) {
            newUser = false;
            lur = IAS.DS().userRights().get(u);
        } else {
            u = new User("kor1", "kor1 prezime", "kor1 username", "kor1 pass");
        }

        if (lur.isEmpty()) {
            lur.add(new Userrights(u, IAS.DS().roles().get(1)));
            lur.add(new Userrights(u, IAS.DS().roles().get(2)));
            lur.add(new Userrights(u, IAS.DS().roles().get(4)));
        } else {
            lur.clear();
            lur.add(new Userrights(u, IAS.DS().roles().get(1)));
            lur.add(new Userrights(u, IAS.DS().roles().get(5)));
        }

        u.setUserRightsList(lur);
        if (!newUser) {
            IAS.DS().user().update(u);
        } else {
            IAS.DS().user().insert(u);
        }
    }
</code>```

Title: Handling collection updates with JPA

Body:
Brief explanation : so I have users and their corresponding rights. I want to be able to maintain my database with those information.

This is a solution I use :

Beans :

...
@Entity
public class User implements Serializable {
...
@OneToMany(mappedBy = "idu", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, orphanRemoval = true)
private List<Userrights> userRightsList;
...
}

...
@Entity
public class Userrights implements Serializable {
...
@JoinColumn(name = "idu", referencedColumnName = "idu")
@ManyToOne
private User idu;
...
}

Spring :

@Component
public class UserBean implements IUser {

    @Autowired
    private MyPersistenceContext<User> pc;
    ...
    @Transactional
    @Override
    public void update(User user) throws Exception {
        pc.update(user, UPDATE_ERR);
    }
    ...
}

@Component
public class MyPersistenceContext<T> {
    @PersistenceContext
    protected EntityManager EM;
    ...
    public void insert(T object, String errMsg) {
        EM.persist(object);
    }
    public void update(T object, String errMsg) {
        EM.merge(object);
    }
...
}

public void delete(T object, String errMsg) {
    T forDeletion = null;

    if (!EM.contains(object)) {
        forDeletion = EM.merge(object);
    }

    if (forDeletion != null) {
        EM.remove(forDeletion);
    }
}

Test :

@Test
public void testDb_InsertOrUpdateOfExistinguserRights() throws Exception {
        User u = null;
        try {
            u = IAS.DS().user().getByUsername("kor1 username");
        } catch (Exception e) {
        }

        List<Userrights> lur = new ArrayList<>();
        boolean newUser = true;

        if (u != null) {
            newUser = false;
            lur = IAS.DS().userRights().get(u);
        } else {
            u = new User("kor1", "kor1 prezime", "kor1 username", "kor1 pass");
        }

        if (lur.isEmpty()) {
            lur.add(new Userrights(u, IAS.DS().roles().get(1)));
            lur.add(new Userrights(u, IAS.DS().roles().get(2)));
            lur.add(new Userrights(u, IAS.DS().roles().get(4)));
        } else {
            lur.clear();
            lur.add(new Userrights(u, IAS.DS().roles().get(1)));
            lur.add(new Userrights(u, IAS.DS().roles().get(5)));
        }

        u.setUserRightsList(lur);
        if (!newUser) {
            IAS.DS().user().update(u);
        } else {
            IAS.DS().user().insert(u);
        }
    }


问:
Error in execute process task while uploading a file to sftp server using PSFTP.exe
I created a execute process task in SSIS to upload a file to a sftp server. I have full access to the server folder and was able to drag and drop files using filezilla. I am using putty sftp client psftp.exe to do the upload. Now when I use the psftp.exe with user and pass and batch arguments, it works perfectly fine in windows cmd. But when I execute the same in SSIS, I get the following error:

```<code>Error: 0xC0029151 at Execute Process Task, Execute Process Task: In Executing "C:\temp\psftp.exe" "user -pw pass -be -batch -b Upload.bat" at "C:\temp", The process exit code was "1" while the expected was "0".
Task failed: Execute Process Task
</code>```

My windows cmd arguments are :

```<code>psftp.exe devsftp@secftp2.alliedpilots.org -b UploadUsersToSftp.bat
</code>```

and then it asks for password and after entering password, file upload is done successfully. But I am having trouble performing same through SSIS. Below is the SSIS process task argument screenshot:

I searched online and found some similar questions at here but nothing specific to psftp. Also found same question on stackoverflow here but the solution mentioned is permissions, which I already checked.

Any help would be appreciated.

答:
The SSIS most probably runs under a different local account than the one you use in "Windows cmd".

An SFTP access requires confirmation of a host key. You have probably verified  the host key in your local account in the past, so it is cached in Windows registry.

But the account that runs SSIS does not have the host key cached. So it must fail.

You should add -hostkey switch to psftp.exe command line with the fingerprint of the expected host key.

If that does not help, wrap the psftp.exe to a batch file and redirect its output to a file.

```<code>psftp.exe devsftp@secftp2.alliedpilots.org -b UploadUsersToSftp.bat > c:\temp\psftp.out 2>&1
</code>```

And run the batch file in SSIS, instead of psftp.exe directly.

Then check the file for errors.

Body:
I created a execute process task in SSIS to upload a file to a sftp server. I have full access to the server folder and was able to drag and drop files using filezilla. I am using putty sftp client psftp.exe to do the upload. Now when I use the psftp.exe with user and pass and batch arguments, it works perfectly fine in windows cmd. But when I execute the same in SSIS, I get the following error:

Error: 0xC0029151 at Execute Process Task, Execute Process Task: In Executing "C:\temp\psftp.exe" "user -pw pass -be -batch -b Upload.bat" at "C:\temp", The process exit code was "1" while the expected was "0".
Task failed: Execute Process Task

My windows cmd arguments are :

psftp.exe devsftp@secftp2.alliedpilots.org -b UploadUsersToSftp.bat

and then it asks for password and after entering password, file upload is done successfully. But I am having trouble performing same through SSIS. Below is the SSIS process task argument screenshot:

I searched online and found some similar questions at here but nothing specific to psftp. Also found same question on stackoverflow here but the solution mentioned is permissions, which I already checked.

Any help would be appreciated.

Body:
The SSIS most probably runs under a different local account than the one you use in "Windows cmd".

An SFTP access requires confirmation of a host key. You have probably verified  the host key in your local account in the past, so it is cached in Windows registry.

But the account that runs SSIS does not have the host key cached. So it must fail.

You should add -hostkey switch to psftp.exe command line with the fingerprint of the expected host key.

If that does not help, wrap the psftp.exe to a batch file and redirect its output to a file.

psftp.exe devsftp@secftp2.alliedpilots.org -b UploadUsersToSftp.bat > c:\temp\psftp.out 2>&1

And run the batch file in SSIS, instead of psftp.exe directly.

Then check the file for errors.


问:
Hide or show between two div
I have 2
 say it div1 and div2. before I click submit I want div1 will show and div2 will hide but after I click submit, div1 will hide and div2 will show

My code in kanjiconverter.php

```<code>   <?php
  if(isset($_POST['submit1'])){
        $kanji = ($_POST['convertkanji']);

        $replacements = [
        'class="rt">' => "",
        ];
        $newkanji = strtr($kanji, $replacements);
  }
?>
</code>```

my form code

```<code><form id="convertkanji" method="post" action="kanjiconverter.php"></form>
        <form>
          <div class="form-row">

            <!-- START DIV1 HERE -->
          <div id="div1" class="form-group col-md-6">
            <label for="convertkanji">Kanji Convert</label>
            <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
            <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />
          </div>
          <!-- Ended DIV1 HERE -->

          <!-- START DIV2 HERE -->
            <div id="div2" class="form-group col-md-6" style="display: none;">
      <label for="kanji">New Kanji</label>
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>
    </div>
          <!-- Ended DIV2 HERE -->
    </form>
</code>```

and jquery script here

```<code>      <script>
        $(function() {
  $('#div1').show();
  $('#div2').hide();

  $('input[name="submit1"]').on('click', function(e) {
    e.preventDefault();

    $('#div1').hide();
    $('#div2').show();

    $.post('kanjiconverter.php', $('form').serialize(), function(response) {
      //Your response from the server-side
    })
  });
});
      </script>
</code>```

i place jquery code above  and  in head tag.

between show and hide is working, but when i click submit button i dont get any data.

答:
You must attach a click or submit event to your submit button then send the data to your server side using ajax request to prevent the page from refreshing and hide/show the divs you want inside the event.

$(function() {
  $('#div1').show();
  $('#div2').hide();

  $('input[name="submit1"]').on('click', function(e) {
    e.preventDefault();

    $('#div1').hide();
    $('#div2').show();

    $.post('php_file.php', $('form').serialize(), function(response) {
      //Your response from the server-side
    })
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <div class="form-row">
    <!-- START DIV1 HERE -->
    <div id="div1" class="form-group col-md-6">
      <label for="convertkanji">Kanji Convert</label>
      <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
      <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />
    </div>
    <!-- Ended DIV1 HERE -->

    <!-- START DIV2 HERE -->
    <div id="div2" class="form-group col-md-6">
      <label for="kanji">New Kanji</label>
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>
    </div>
    <!-- Ended DIV2 HERE -->
</form></code>```

Title: Hide or show between two div

Body:
I have 2
 say it div1 and div2. before I click submit I want div1 will show and div2 will hide but after I click submit, div1 will hide and div2 will show

My code in kanjiconverter.php

   <?php
  if(isset($_POST['submit1'])){
        $kanji = ($_POST['convertkanji']);

        $replacements = [
        'class="rt">' => "",
        ];
        $newkanji = strtr($kanji, $replacements);
  }
?>

my form code

<form id="convertkanji" method="post" action="kanjiconverter.php"></form>
        <form>

            Kanji Convert
            <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
            <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />

      New Kanji
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>

    </form>

and jquery script here

i place jquery code above  and  in head tag.

between show and hide is working, but when i click submit button i dont get any data.

Body:
You must attach a click or submit event to your submit button then send the data to your server side using ajax request to prevent the page from refreshing and hide/show the divs you want inside the event.

$(function() {
  $('#div1').show();
  $('#div2').hide();

  $('input[name="submit1"]').on('click', function(e) {
    e.preventDefault();

    $('#div1').hide();
    $('#div2').show();

    $.post('php_file.php', $('form').serialize(), function(response) {
      //Your response from the server-side
    })
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <div class="form-row">
    <!-- START DIV1 HERE -->
    <div id="div1" class="form-group col-md-6">
      <label for="convertkanji">Kanji Convert</label>
      <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
      <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />
    </div>
    <!-- Ended DIV1 HERE -->

    <!-- START DIV2 HERE -->
    <div id="div2" class="form-group col-md-6">
      <label for="kanji">New Kanji</label>
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>
    </div>
    <!-- Ended DIV2 HERE -->
</form>


问:
About The switch Statement in Java
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

```<code>int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"
</code>```

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

```<code>import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}
</code>```

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

答:
You need to use nextInt() once to get the input and store it in a variable. Every time you call nextInt() it would look for the next integer value entered.</p>

```<code>Scanner day = new Scanner(System.in);

int dayInput = day.nextInt();
    if (dayInput>7){
        dayInput=dayInput%7;
    }

switch(dayInput){
    case 1 :
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 0:
        System.out.println("Sunday");
    case 7:
        System.out.println("Sunday");
        break;

}
</code>```

Title: About The switch Statement in Java

Body:
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

Body:
You need to use nextInt() once to get the input and store it in a variable. Every time you call nextInt() it would look for the next integer value entered.

Scanner day = new Scanner(System.in);

int dayInput = day.nextInt();
    if (dayInput>7){
        dayInput=dayInput%7;
    }

switch(dayInput){
    case 1 :
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 0:
        System.out.println("Sunday");
    case 7:
        System.out.println("Sunday");
        break;

}


问:
Gathering dependency information took 6.36 min
I am trying to make my nuget package installations faster, but when I try installing, gathering the dependency information took like 6.26 min. I am using Castle.Windsor as my injector. My nuget server too, is a local server.

```<code>Gathering dependency information took 6.36 min
</code>```

I would expect the installation to be much faster. i.e. resolving dependency should be made faster or by using a easier method.

Actually the 6.36 min is for gathering the dependencies, the nuget actions take below 30 sec.

答:
Try Paket, it will manage also the transative dependencies for you once you have correctly configured it and it is actually faster than the integrated NugetPackageManager.

In the other hand you can use FAKE so you will have the ability to produce your own nugets.

Both works pretty good together but both are quite hard to set up, but once you have it you can carry it to other projects.

I cannot provide you any code since it doesn't looks like it is a coding problem.

Body:
I am trying to make my nuget package installations faster, but when I try installing, gathering the dependency information took like 6.26 min. I am using Castle.Windsor as my injector. My nuget server too, is a local server.

Gathering dependency information took 6.36 min

I would expect the installation to be much faster. i.e. resolving dependency should be made faster or by using a easier method.

Actually the 6.36 min is for gathering the dependencies, the nuget actions take below 30 sec.


问:
Sending JSON to a server
How do I turn this...

```<code>{
  'name': 'John',
  'surname': 'Smith'
}
</code>```

...into this?

```<code>name=John&surname=Smith
</code>```

I'm trying to send JSON  to a server via AJAX

thank you

答:
Gernerically (i.e. without any JS framework)...

```<code>var o = {'name': 'John', 'surname': 'Smith'};
var q = [];

for (p in o) {
  if (o.hasOwnProperty(p)) {
    q.push( encodeURIComponent(p) + "=" + encodeURIComponent(o[p]) );
  }
}

q = q.join("&"); // "name=John&surname=Smith"
</code>```

As people in comments already noted, this would work for flat, non-nested objects only. For advanced uses, I strongly recommend doing an HTTP post operation and sending the object unmodified as a JSON string.

All JS libraries provide a way to transform an object to JSON, and there are other ways to serialize an object, like Douglas Crockford's own implementation at http://json.org/js.html.

Title: Sending JSON to a server

Body:
How do I turn this...

{
  'name': 'John',
  'surname': 'Smith'
}

...into this?

name=John&surname=Smith

I'm trying to send JSON  to a server via AJAX

thank you

Body:
Gernerically (i.e. without any JS framework)...

var o = {'name': 'John', 'surname': 'Smith'};
var q = [];

for (p in o) {
  if (o.hasOwnProperty(p)) {
    q.push( encodeURIComponent(p) + "=" + encodeURIComponent(o[p]) );
  }
}

q = q.join("&"); // "name=John&surname=Smith"

As people in comments already noted, this would work for flat, non-nested objects only. For advanced uses, I strongly recommend doing an HTTP post operation and sending the object unmodified as a JSON string.

All JS libraries provide a way to transform an object to JSON, and there are other ways to serialize an object, like Douglas Crockford's own implementation at http://json.org/js.html.


问:
Modal UIViewController can't receive NSNotifications
I have a modal UIViewController:

```<code>let rVC = RecoveryViewController()
rVC.modalPresentationStyle = .overFullScreen
self.present(rVC, animated: true, completion: nil)
</code>```

In viewDownload of this ViewController I have a function user.checkUserData() that would send NSNotifications when the job is done.

And, of course, observers for any of these notifications:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(RecoveryViewController.userVIP), name: userDataIsHere, object: nil)
</code>```

But it seems that my modal ViewController is not able to receive any notifications, because nothing is happening. At the same time if I tried to add such observer to the parent UIViewController (non-modal), it'd work like a charm (actually, I checked).

My notifications are quite simple, and

```<code>let userDataIsHere = Notification.Name("userDataIsHere")
NotificationCenter.default.post(name: userDataIsHere, object: nil)
</code>```

What am I doing wrong here?

答:
Try this.</p>

```<code>class ViewController: UIViewController {
    let userDataIsHere = Notification.Name("userDataIsHere")

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(modalPopUp), name: userDataIsHere, object: nil)
    }

    @objc func modalPopUp() {
        let rVC = RecoveryViewController()
        rVC.modalPresentationStyle = .overFullScreen
        self.present(rVC, animated: true, completion: nil)
    }
}
</code>```

Body:
I have a modal UIViewController:

let rVC = RecoveryViewController()
rVC.modalPresentationStyle = .overFullScreen
self.present(rVC, animated: true, completion: nil)

In viewDownload of this ViewController I have a function user.checkUserData() that would send NSNotifications when the job is done.

And, of course, observers for any of these notifications:

NotificationCenter.default.addObserver(self, selector: #selector(RecoveryViewController.userVIP), name: userDataIsHere, object: nil)

But it seems that my modal ViewController is not able to receive any notifications, because nothing is happening. At the same time if I tried to add such observer to the parent UIViewController (non-modal), it'd work like a charm (actually, I checked).

My notifications are quite simple, and

let userDataIsHere = Notification.Name("userDataIsHere")
NotificationCenter.default.post(name: userDataIsHere, object: nil)

What am I doing wrong here?

Body:
Try this.

class ViewController: UIViewController {
    let userDataIsHere = Notification.Name("userDataIsHere")

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(modalPopUp), name: userDataIsHere, object: nil)
    }

    @objc func modalPopUp() {
        let rVC = RecoveryViewController()
        rVC.modalPresentationStyle = .overFullScreen
        self.present(rVC, animated: true, completion: nil)
    }
}


答:
There a number of ways to do this, but probably the easiest is to write an iterator for your object:</p>

```<code>var propstr = "?";
for (prop in jsonCode) {
   if (jsonCode.hasOwnProperty(prop)) {
      propstr += prop + "=" + jsonCode[prop] + "&"
   }
}
</code>```

Title: Sending JSON to a server

Body:
There a number of ways to do this, but probably the easiest is to write an iterator for your object:

var propstr = "?";
for (prop in jsonCode) {
   if (jsonCode.hasOwnProperty(prop)) {
      propstr += prop + "=" + jsonCode[prop] + "&"
   }
}


问:
run multiple for loop session simultaneously python
I have a list of input.

serverfarm = '''

server1 = 10.1

server2 = 10.2

server3 = 10.3

server4 = 10.4

server5 = 10.5

server6 = 10.6

server7 = 10.7

server8 = 10.8

server9 = 10.9

server10 = 10.10

server11 = 10.11

server12 = 10.12

server13 = 10.13

server14 = 10.14

server15 = 10.15

server16 = 10.16

server17 = 10.17

server18 = 10.18

server19 = 10.19

server20 = 10.20

'''
i do run a for loop for each server:

```<code>for server in serverfarm:<br>
.   ssh each server and do config # its take 5 min to complete a server.
</code>```

the total time to complete the is list is 100 min. I need to reduce this time. I need to run multiple for loop simultaneously. i.e. in this case the for loop run for 5 or 10 servers at once.

let consider 10, in this case the script is taking just 10 min to complete the config on each server. I am not worry about the resource on my script server. just need to reduce the time at any cost.

OR if there is any way to run a master script which make copy of for loop in back-end and update the master script which return the value in 10 min.

答:
You could make a function that does the ssh and config part for a single server and run this with multiprocessing.Process somehow like this:

```<code>from multiprocession import Process

def configure_server(server):
   # Do your ssh and config stuff here

# List of processes
proc = []

# iterate your servers
for server in serverfarm:
    p = Process(target=configure_server, args=(server,))
    p.start()
    proc.append(p)

# Block main thread until all processes are finished
for p in proc:
    p.join()
</code>```

For more details on Process or other multiprocessing related stuff have a look at the Python Documentation.

Body:
I have a list of input.

serverfarm = '''

server1 = 10.1

server2 = 10.2

server3 = 10.3

server4 = 10.4

server5 = 10.5

server6 = 10.6

server7 = 10.7

server8 = 10.8

server9 = 10.9

server10 = 10.10

server11 = 10.11

server12 = 10.12

server13 = 10.13

server14 = 10.14

server15 = 10.15

server16 = 10.16

server17 = 10.17

server18 = 10.18

server19 = 10.19

server20 = 10.20

'''
i do run a for loop for each server:

for server in serverfarm:

.   ssh each server and do config # its take 5 min to complete a server.

the total time to complete the is list is 100 min. I need to reduce this time. I need to run multiple for loop simultaneously. i.e. in this case the for loop run for 5 or 10 servers at once.

let consider 10, in this case the script is taking just 10 min to complete the config on each server. I am not worry about the resource on my script server. just need to reduce the time at any cost.

OR if there is any way to run a master script which make copy of for loop in back-end and update the master script which return the value in 10 min.

Body:
You could make a function that does the ssh and config part for a single server and run this with multiprocessing.Process somehow like this:

from multiprocession import Process

def configure_server(server):
   # Do your ssh and config stuff here

# List of processes
proc = []

# iterate your servers
for server in serverfarm:
    p = Process(target=configure_server, args=(server,))
    p.start()
    proc.append(p)

# Block main thread until all processes are finished
for p in proc:
    p.join()

For more details on Process or other multiprocessing related stuff have a look at the Python Documentation.


问:
XPath to select elements based on class
How do I effectively use the :not to select elements in a situation like below:

```<code><div class="parent">
    <div class="a b c"/>
    <div class="a"/>
</div>
</code>```

I need to select the div with just class 'a' and exclude the div with classes 'a', 'b' and 'c'.
 Thing is the number of div's with the class that I need varies for every load of page and so would have to use logic of finding div's with class 'a' and not having class 'b' and 'c'

答:
This XPath,

```<code>//div[@class="a"]
</code>```

will select all div elements with a class attribute equal exactly to "a".  It will not select div elements such as
.

It's actually harder to include div elements where a is among one of the classes selected:

```<code>//div[contains(concat(' ', normalize-space(@class), ' '), ' a ')]
</code>```

This takes care to select
 but not

Title: XPath to select elements based on class

Body:
How do I effectively use the :not to select elements in a situation like below:

I need to select the div with just class 'a' and exclude the div with classes 'a', 'b' and 'c'.
 Thing is the number of div's with the class that I need varies for every load of page and so would have to use logic of finding div's with class 'a' and not having class 'b' and 'c'

Body:
This XPath,

//div[@class="a"]

will select all div elements with a class attribute equal exactly to "a".  It will not select div elements such as <div class="a b c"/>.

It's actually harder to include div elements where a is among one of the classes selected:

//div[contains(concat(' ', normalize-space(@class), ' '), ' a ')]

This takes care to select <div class="a b c"/> but not <div class="abc"/>


问:
Continent - creating a new variable - R
I have 198 countries, named by the UN, in my data frame. I want to create a new variable that divides these countries in continents.

I have been using the following code so far:

```<code>attach(df)
df$Continent[Country==c('country', 'country', ...)] <- "Americas"
df$Continent[Country==c('country', 'country', ...)] <- "Africa"
df$Continent[Country==c('country', 'country', ...)] <- "Asia"
df$Continent[Country==c('country', 'country', ...)] <- "Europe"
df$Continent[Country==c('country', 'country', ...)] <- "Oceania"
detach(df)
</code>```

The problem is that R doesn't let me put all the country names available for each continent in the same bracket, displaying the warning message “longer object length is not a multiple of shorter object length”. If I separate the countries in multiple lines, I can make it. However, this is quite inefficient, so I wonder if there is a clever/quickest way to do it?

答:
As LyzandeR stated, you can use the %in% operator. It may also be cleaner to define the list of countries first, like so:

```<code>americas <- c("country", "country", "country", ...)
africa <- c("country", "country", "country", ...)
asia <- c("country", "country", "country", ...)
# and so on...

attach(df)
df$Continent[Country %in% americas] <- "Americas"
df$Continent[Country %in% africa] <- "Africa"
df$Continent[Country %in% asia] <- "Asia"
df$Continent[Country %in% europe] <- "Europe"
df$Continent[Country %in% oceania] <- "Oceania"
detach(df)
</code>```

Title: Continent - creating a new variable - R

Body:
I have 198 countries, named by the UN, in my data frame. I want to create a new variable that divides these countries in continents.

I have been using the following code so far:

attach(df)
df$Continent[Country==c('country', 'country', ...)] <- "Americas"
df$Continent[Country==c('country', 'country', ...)] <- "Africa"
df$Continent[Country==c('country', 'country', ...)] <- "Asia"
df$Continent[Country==c('country', 'country', ...)] <- "Europe"
df$Continent[Country==c('country', 'country', ...)] <- "Oceania"
detach(df)

The problem is that R doesn't let me put all the country names available for each continent in the same bracket, displaying the warning message “longer object length is not a multiple of shorter object length”. If I separate the countries in multiple lines, I can make it. However, this is quite inefficient, so I wonder if there is a clever/quickest way to do it?

Body:
As LyzandeR stated, you can use the %in% operator. It may also be cleaner to define the list of countries first, like so:

americas <- c("country", "country", "country", ...)
africa <- c("country", "country", "country", ...)
asia <- c("country", "country", "country", ...)
# and so on...

attach(df)
df$Continent[Country %in% americas] <- "Americas"
df$Continent[Country %in% africa] <- "Africa"
df$Continent[Country %in% asia] <- "Asia"
df$Continent[Country %in% europe] <- "Europe"
df$Continent[Country %in% oceania] <- "Oceania"
detach(df)


问:
Is `-1` correct for using as maximum value of an unsigned integer?
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

```<code>unsigned short i = -1; // unsigned short max
</code>```

can easily be changed to any other type, like

```<code>unsigned long i = -1; // unsigned long max
</code>```

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.

答:
The C++ standard says this about signed to unsigned conversions ([conv.integral]/2):

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo
  2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

So yes, converting -1 to an n-bit unsigned integer will always give you 2n-1, regardless of which signed integer type the -1 started as.

Whether or not unsigned x = -1; is more or less readable than unsigned x = UINT_MAX; though is another discussion (there's definitely the chance that it'll raise some eyebrows, maybe even your own when you look at your own code later;).

Body:
Is there any c++ standard paragraph which says that using -1 for this is portable and correct way or the only way of doing this correctly is using predefined values?

I have had a conversation with my colleague, what is better: using -1 for a maximum unsigned integer number or using a value from limits.h or std::numeric_limits ?

I have told my colleague that using predefined maximum values from limits.h or std::numeric_limits is the portable and clean way of doing this, however, the colleague objected to -1 being as same portable as numeric limits, and more, it has one more advantage:

unsigned short i = -1; // unsigned short max

can easily be changed to any other type, like

unsigned long i = -1; // unsigned long max

when using the predefined value from the limits.h header file or std::numeric_limits also requires to rewrite it too along with the type to the left.


问:
dyld: Library not loaded: @rpath/libswiftCore.dylib
I am getting this issue in my existing project and i tried to create new project then i run in device getting same issue

```<code>    dyld: Library not loaded: @rpath/libswiftCore.dylib
      Referenced from: /var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Pro
Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib: mmap() errno=1 validating first page of '/private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib'
</code>```

some of the answer i tired but still getting same issue

dyld: Library not loaded: @rpath/libswiftCore.dylib

答:
Ok. i solve this a little bit different way. As you know, grater than Xcode 7, you can run your iOS project(only one iphone) on your iphone without purchase Apple Developer Program(registration is enough).

if you have a Apple ID and not purchased yet.

And you was build on the different iPhone(Divece A)

Now, you want to build different iPhone(Divece B)

for this scenario, you can get an error which is detailed below

dyld: Library not loaded: @rpath/libswiftCore.dylib
  uzun hali de
  dyld: Library not loaded: @rpath/libswiftCore.dylib Referenced from: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/AppName Reason: no suitable image found. Did find: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/Frameworks/libswiftCore.dylib: mmap() error 1 at address=0x008A1000, size=0x001A4000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/APPLICATION_NAME/Frameworks/libswiftCore.dylib

You must delete Provision Profile or you should get new Apple Developer account for new iPhone.

Body:
I am getting this issue in my existing project and i tried to create new project then i run in device getting same issue

    dyld: Library not loaded: @rpath/libswiftCore.dylib
      Referenced from: /var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Pro
Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib: mmap() errno=1 validating first page of '/private/var/mobile/Containers/Bundle/Application/D14EA274-0C2B-457B-8E8F-494197978F34/Pro.app/Frameworks/libswiftCore.dylib'

some of the answer i tired but still getting same issue

dyld: Library not loaded: @rpath/libswiftCore.dylib


问:
How to union two collections without overriding any value
I am trying to get the union of two collections without overriding any value:

First Collection:

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"
   ]]}
</code>```

Second Collection

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
  "status": "Reminder",
  "letterPaymentAmount": 4300,
  "BankAccountNo": "SEK",
  "Date": "2017-08-15T16:01:30",
  "DueDate": "2017-08-30T00:00:00",
  "ocr": "3000002406",
  "lastDatePayDay": "30",
  "lastDatePayMonth": "Aug",
  "Country": "Singapore",
  "Customer": "TickTack"
   ]]}
</code>```

I want to acomplish this:

```<code>Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"],
    1=> [
      "status": "Reminder",
      "letterPaymentAmount": 4300,
      "BankAccountNo": "SEK",
      "Date": "2017-08-15T16:01:30",
      "DueDate": "2017-08-30T00:00:00",
      "ocr": "3000002406",
      "lastDatePayDay": "30",
      "lastDatePayMonth": "Aug",
      "Country": "Singapore",
      "Customer": "TickTack"  ]]}
</code>```

I do not want to override any existing key or value just add them together.

I have tried union() but that overrides the existing keys and does not take keys that do not exist in first collection .

Any help would be much appreciated

答:
Use merge()

```<code>$first = collect(['One','Two']);

$second = collect(['Two','Five']);

$merged = $first->merge($second);

// $merged->all();
</code>```

Body:
I am trying to get the union of two collections without overriding any value:

First Collection:

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"
   ]]}

Second Collection

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
  "status": "Reminder",
  "letterPaymentAmount": 4300,
  "BankAccountNo": "SEK",
  "Date": "2017-08-15T16:01:30",
  "DueDate": "2017-08-30T00:00:00",
  "ocr": "3000002406",
  "lastDatePayDay": "30",
  "lastDatePayMonth": "Aug",
  "Country": "Singapore",
  "Customer": "TickTack"
   ]]}

I want to acomplish this:

Collection {#246 ▼
  #items: array [▼
    0 => array [▼
      "status" => "Invoice"
      "letterPaymentAmount" => 4240.0
      "BankAccountNo" => "SEK"
      "Date" => "2017-07-15T16:32:22"
      "DueDate" => "2017-07-28T00:00:00"
      "ocr" => "3000000202"
      "lastDatePayDay" => "28"],
    1=> [
      "status": "Reminder",
      "letterPaymentAmount": 4300,
      "BankAccountNo": "SEK",
      "Date": "2017-08-15T16:01:30",
      "DueDate": "2017-08-30T00:00:00",
      "ocr": "3000002406",
      "lastDatePayDay": "30",
      "lastDatePayMonth": "Aug",
      "Country": "Singapore",
      "Customer": "TickTack"  ]]}

I do not want to override any existing key or value just add them together.

I have tried union() but that overrides the existing keys and does not take keys that do not exist in first collection .

Any help would be much appreciated

Body:
Use merge()

$first = collect(['One','Two']);

$second = collect(['Two','Five']);

$merged = $first->merge($second);

// $merged->all();


问:
How can I check if a device supports SMS?
I want to disable SMS features programmatically on tablets without SIM card slot.

I have tried this:

```<code>if (context.getSystemService(Context.TELEPHONY_SERVICE) != null)
{
    // SMS features: enable
}
else
{
    // SMS features: disable
}
</code>```

but on my NVidia Shield Tablet K1 (without sim card slot) context.getSystemService(Context.TELEPHONY_SERVICE) returns something and it looks like I have telephony service.

What is wrong with my code?

答:
I would not assume that getSystemService() to retrieve the TelephonyManager would necessarily return null in this case.

The official way to check for telephony is to call hasSystemFeature(PackageManager.FEATURE_TELEPHONY) on a PackageManager, which you can get by calling getPackageManager().

I have dusted off my NVIDIA Shield K1, and I get false from hasSystemFeature(PackageManager.FEATURE_TELEPHONY) on that device.

Body:
I want to disable SMS features programmatically on tablets without SIM card slot.

I have tried this:

if (context.getSystemService(Context.TELEPHONY_SERVICE) != null)
{
    // SMS features: enable
}
else
{
    // SMS features: disable
}

but on my NVidia Shield Tablet K1 (without sim card slot) context.getSystemService(Context.TELEPHONY_SERVICE) returns something and it looks like I have telephony service.

What is wrong with my code?


问:
Counting letters in the text R
I have a program that counts letters and characters in the text, but it does not work correctly. As you can see from the example below, the program does not count column indexes. I do not know how to set the program after the last letter (character) in the line to go to the next line and count from 1. Can you help me? I have two different programs, one does not count rows.

My codes:

```<code>library(tidyverse)
library(stringr)
str_split(text, "")[[1]] %>%
  tibble(char = .) %>%
  rownames_to_column('rn') %>%
  group_by(char) %>%
  summarise(Count = n(), row = 1, col = toString(rn))

unique(unlist(strsplit(text, ""))) %>%
  sapply(gregexpr, text, fixed = TRUE) %>%
  unlist() %>%
  data.frame(letter = names(.), col = .) %>%
  group_by(letter = gsub("^(.).*", "\\1", letter)) %>%
  summarize(count = n(),
            col = paste(col, collapse = ","))

text <- "Only two things are infinite,
the universe and human stupidity,
and I'm not sure about the former. (A. Einstein)"
</code>```

Results:

```<code># A tibble: 31 x 4
    char Count   row                                                                    col
   <chr> <int> <dbl>                                                                  <chr>
 1     '     1     1                                                                     72
 2          18     1 5, 9, 16, 20, 30, 35, 44, 48, 54, 65, 70, 74, 78, 83, 89, 93, 101, 105
 3  "\n"     2     1                                                                 31, 66
 4     (     1     1                                                                    102
 5     )     1     1                                                                    114
 6     ,     2     1                                                                 29, 64
 7     .     2     1                                                               100, 104
 8     a     5     1                                                     17, 45, 52, 67, 84
 9     A     1     1                                                                    103
10     b     1     1                                                                     85
# ... with 21 more rows
</code>```

答:
You can try </p>

```<code>library(tidyverse)
library(stringr)
library(stringi)

data.frame(Text=str_split(text, pattern = "\n")[[1]]) %>%
  group_by(n=row_number()) %>%
  mutate(letters=sum(stri_count_fixed(tolower(Text), letters))) %>%
  mutate(marks=sum(stri_count_regex(tolower(Text), "[[:punct:]]"))) %>%
  mutate(spaces=sum(stri_count_regex(tolower(Text),"[[:blank:]]")))
# A tibble: 3 x 5
# Groups:   n [3]
                                              Text     n letters marks spaces
                                            <fctr> <int>   <int> <int>  <int>
1                   Only two things are infinite,      1      24     1      5
2               the universe and human stupidity,      2      28     1      5
3 and I'm not sure about the former. (A. Einstein)     3      35     5      8
</code>```

Title: Counting letters in the text R

Body:
I have a program that counts letters and characters in the text, but it does not work correctly. As you can see from the example below, the program does not count column indexes. I do not know how to set the program after the last letter (character) in the line to go to the next line and count from 1. Can you help me? I have two different programs, one does not count rows.

My codes:

library(tidyverse)
library(stringr)
str_split(text, "")[[1]] %>%
  tibble(char = .) %>%
  rownames_to_column('rn') %>%
  group_by(char) %>%
  summarise(Count = n(), row = 1, col = toString(rn))

unique(unlist(strsplit(text, ""))) %>%
  sapply(gregexpr, text, fixed = TRUE) %>%
  unlist() %>%
  data.frame(letter = names(.), col = .) %>%
  group_by(letter = gsub("^(.).*", "\\1", letter)) %>%
  summarize(count = n(),
            col = paste(col, collapse = ","))

text <- "Only two things are infinite,
the universe and human stupidity,
and I'm not sure about the former. (A. Einstein)"

Results:

# A tibble: 31 x 4
    char Count   row                                                                    col
   <chr> <int> <dbl>                                                                  <chr>
 1     '     1     1                                                                     72
 2          18     1 5, 9, 16, 20, 30, 35, 44, 48, 54, 65, 70, 74, 78, 83, 89, 93, 101, 105
 3  "\n"     2     1                                                                 31, 66
 4     (     1     1                                                                    102
 5     )     1     1                                                                    114
 6     ,     2     1                                                                 29, 64
 7     .     2     1                                                               100, 104
 8     a     5     1                                                     17, 45, 52, 67, 84
 9     A     1     1                                                                    103
10     b     1     1                                                                     85
# ... with 21 more rows

Body:
You can try

library(tidyverse)
library(stringr)
library(stringi)

data.frame(Text=str_split(text, pattern = "\n")[[1]]) %>%
  group_by(n=row_number()) %>%
  mutate(letters=sum(stri_count_fixed(tolower(Text), letters))) %>%
  mutate(marks=sum(stri_count_regex(tolower(Text), "[[:punct:]]"))) %>%
  mutate(spaces=sum(stri_count_regex(tolower(Text),"[[:blank:]]")))
# A tibble: 3 x 5
# Groups:   n [3]
                                              Text     n letters marks spaces
                                            <fctr> <int>   <int> <int>  <int>
1                   Only two things are infinite,      1      24     1      5
2               the universe and human stupidity,      2      28     1      5
3 and I'm not sure about the former. (A. Einstein)     3      35     5      8


答:
First, are you using any javascript library? (jquery, prototype, etc...). If you are there are functions to do this somewhere in there.

Otherwise you could use something like:

```<code>var urlParams = '?';
var index = 0;
for(var key in obj){
If(index != 0) urlParams += '&';
 urlParams += key + '='+obj[key];
}
</code>```

Title: Sending JSON to a server

Body:
How do I turn this...

{
  'name': 'John',
  'surname': 'Smith'
}

...into this?

name=John&surname=Smith

I'm trying to send JSON  to a server via AJAX

thank you

Body:
First, are you using any javascript library? (jquery, prototype, etc...). If you are there are functions to do this somewhere in there.

Otherwise you could use something like:

var urlParams = '?';
var index = 0;
for(var key in obj){
If(index != 0) urlParams += '&';
 urlParams += key + '='+obj[key];
}


问:
C# ExecuteNonQuery Error (Connecting My.ASP Web Form to an Access DB)
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

```<code>String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();
</code>```

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

答:
Based on what you said you are trying to, this is all the code you need.

Please be aware your code is vulnerable to SQL Injection because you are stuffing the user input directly into a query. A user can own your database or destroy it very easily. See this for more information and research OleDbParameter.

```<code>string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
try
{
    using(OleDbConnection myConnection = new  OleDbConnection(connString))
    {
        using(OleDbCommand myCommand = myConnection.CreateCommand())
        {
            myCommand.CommandText = myQuery;
            myConnection.Open();
            myCommmand.ExecuteNonQuery();
            SuccReglbl.Text = "successful registration";
        }
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler " + ex.Message;
}
</code>```

Body:
I'm trying to connect my ASP.NET online registration form to  MS Access backend database. The connection code I'm using is

String connString;
connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
OleDbConnection myConnection = new  OleDbConnection(connString);
myConnection.Open();
string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();

try
{
    using (myConnection)
    {
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        SuccReglbl.Text = "successful registration";
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler" + ex;
}
finally
{

}

myCommand.ExecuteNonQuery();
OleDbDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{

}
myConnection.Close();

I keep getting an error when I click on the "Register" button. The error is

"ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."

I'm unsure how to fix this.

Body:
Based on what you said you are trying to, this is all the code you need.

Please be aware your code is vulnerable to SQL Injection because you are stuffing the user input directly into a query. A user can own your database or destroy it very easily. See this for more information and research OleDbParameter.

string myQuery = "INSERT INTO Parent([Username], [FirstName], [Surname], [Email], [Mobile], [Postcode], [Password]) values('" + Usernametb.Text + "','" + Firsttnametb.Text + "','" + Surnametb.Text + "','" + Emailtb.Text + "','" + Mobiletb.Text + "','" + Postcodetb.Text + "','" + Passwordtb.Text + "')";
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Z\Desktop\Comp\MyWebsite\WorkDatabase.mdb";
try
{
    using(OleDbConnection myConnection = new  OleDbConnection(connString))
    {
        using(OleDbCommand myCommand = myConnection.CreateCommand())
        {
            myCommand.CommandText = myQuery;
            myConnection.Open();
            myCommmand.ExecuteNonQuery();
            SuccReglbl.Text = "successful registration";
        }
    }
}
catch (Exception ex)
{
    SuccReglbl.Text = "Exception in DBHandler " + ex.Message;
}


问:
PHP Extract Codes From TextArea and Pass to Mysql SELECT IN Query
I have the following data which gets submitted in a text area:

```<code>new myProduct('', 'bbc_609'),
new myProduct('', '35857'),
</code>```

What I am aiming to do is extract the codes from the above and pass just the codes to a Mysql Select IN query.

I can successfully get the codes out no problem with the following:

```<code>$text = trim($_POST['newfeatured']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind

foreach ($textAr as $line) {
  $g = preg_match("/new myProduct\('', '(.*?)'\)/i", $line, $match);
  $br = $match[1];
  echo "<br>";
}
// returns bbc_6093
// returns 5857
</code>```

However, if I try:

```<code>var_dump($br)
</code>```

... following is returned:

```<code>string(7) "bbc_609"
</code>```

Or if I try to implode and echo, I get nothing back:

```<code>$gr = implode(", ", $br);
echo $gr;
//nothing returns
</code>```

Therefore, given the above, I will not be able to pass the variable to the Mysql statement:

```<code>select product.productid, product.name, product.brand, price.code from product inner join price on product.productid=price.productid
WHERE product.productid IN('".implode("','",$br)."')";
//if I pass in $br in this case.
</code>```

I have also tried without the foreach loop:

```<code>if(isset($_POST['newfeatured'])) {
$g = preg_match_all("/new featuredProduct\('', '(.*?)'\)/i",$_POST['newfeatured'], $match);
    $g = $match[1];

    $codes = implode(", ", $g); //so now we need to be able to pass $codes to the Mysql correctly.
    //var_dump($codes); returns the data in the array fine.
}
</code>```

And when I try to pass $codes to the mysql select IN query, no data is returned?

Any help appreciated.

Cheers

答:
First about the pattern:

You don't need any capture groups just use \K to restart the fullstring match.

I'd use '[^']*' on the first/empty single quoted component of your input string just in case some text does fill that position.

About your query:

It is unsafe.  You must not directly insert user submitted data into a query for security purposes.

Here prepared statements with ? placeholders are used.

Because the number of placeholders/params-to-be-bound are variable, the convolution of call_user_func_array() is required.

I have also implemented bind_result() to aid in the processing of the resultset.

Untested Code:

```<code>$_POST['newfeatured']="new myProduct('', 'bbc_609'),
new myProduct('', '35857'),";

if(preg_match_all("/new (?:my|featured)Product\('[^']*', '\K[^']*/",$_POST['newfeatured'],$prd_ids)){
    $params=$prd_ids[0];  // the fullstring matches
    $count=count($params);  // number of fullstring matches
    $csph=implode(',',array_fill(0,$count,'?'));  // comma-separated placeholders

    $query="SELECT A.productid, A.name, A.brand, B.code
            FROM product A
            INNER JOIN price B ON A.productid=B.productid
            WHERE A.productid IN ($csph);";

    $stmt=$mysqli->prepare($query);  // for security reasons

    array_unshift($params,str_repeat('s',$count));  // prepend the type values string
    $ref=[];  // add references
    foreach($params as $i=>$v){
        $ref[$i]=&$params[$i];  // pass by reference as required/advised by the manual
    }
    call_user_func_array([$stmt,'bind_param'],$ref);

    $stmt->execute();
    $stmt->bind_result($id,$name,$brand,$code);
    while($stmt->fetch()){
        echo "Whatever you want to do with the results: $id, $name, $brand, $code\n";
    }
    $stmt->close();
}else{
    echo "bonk";
}
</code>```

Body:
I have the following data which gets submitted in a text area:

new myProduct('', 'bbc_609'),
new myProduct('', '35857'),

What I am aiming to do is extract the codes from the above and pass just the codes to a Mysql Select IN query.

I can successfully get the codes out no problem with the following:

$text = trim($_POST['newfeatured']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind

foreach ($textAr as $line) {
  $g = preg_match("/new myProduct\('', '(.*?)'\)/i", $line, $match);
  $br = $match[1];
  echo "
";
}
// returns bbc_6093
// returns 5857

However, if I try:

var_dump($br)

... following is returned:

string(7) "bbc_609"

Or if I try to implode and echo, I get nothing back:

$gr = implode(", ", $br);
echo $gr;
//nothing returns

Therefore, given the above, I will not be able to pass the variable to the Mysql statement:

select product.productid, product.name, product.brand, price.code from product inner join price on product.productid=price.productid
WHERE product.productid IN('".implode("','",$br)."')";
//if I pass in $br in this case.

I have also tried without the foreach loop:

if(isset($_POST['newfeatured'])) {
$g = preg_match_all("/new featuredProduct\('', '(.*?)'\)/i",$_POST['newfeatured'], $match);
    $g = $match[1];

    $codes = implode(", ", $g); //so now we need to be able to pass $codes to the Mysql correctly.
    //var_dump($codes); returns the data in the array fine.
}

And when I try to pass $codes to the mysql select IN query, no data is returned?

Any help appreciated.

Cheers

Body:
First about the pattern:

You don't need any capture groups just use \K to restart the fullstring match.

I'd use '[^']*' on the first/empty single quoted component of your input string just in case some text does fill that position.

About your query:

It is unsafe.  You must not directly insert user submitted data into a query for security purposes.

Here prepared statements with ? placeholders are used.

Because the number of placeholders/params-to-be-bound are variable, the convolution of call_user_func_array() is required.

I have also implemented bind_result() to aid in the processing of the resultset.

Untested Code:

$_POST['newfeatured']="new myProduct('', 'bbc_609'),
new myProduct('', '35857'),";

if(preg_match_all("/new (?:my|featured)Product\('[^']*', '\K[^']*/",$_POST['newfeatured'],$prd_ids)){
    $params=$prd_ids[0];  // the fullstring matches
    $count=count($params);  // number of fullstring matches
    $csph=implode(',',array_fill(0,$count,'?'));  // comma-separated placeholders

    $query="SELECT A.productid, A.name, A.brand, B.code
            FROM product A
            INNER JOIN price B ON A.productid=B.productid
            WHERE A.productid IN ($csph);";

    $stmt=$mysqli->prepare($query);  // for security reasons

    array_unshift($params,str_repeat('s',$count));  // prepend the type values string
    $ref=[];  // add references
    foreach($params as $i=>$v){
        $ref[$i]=&$params[$i];  // pass by reference as required/advised by the manual
    }
    call_user_func_array([$stmt,'bind_param'],$ref);

    $stmt->execute();
    $stmt->bind_result($id,$name,$brand,$code);
    while($stmt->fetch()){
        echo "Whatever you want to do with the results: $id, $name, $brand, $code\n";
    }
    $stmt->close();
}else{
    echo "bonk";
}


问:
Tsql transpose rows to columns, grouping by a column
I've this set of data:

```<code>cId    item     value
-------------------------------------
1      A        string1
2      A        string2
3      A        string3
1      B        string4
2      B        string5
1      C        string6
3      C        string7
</code>```

And i would to transpose item ad cId rows into columns, in order to have this result:

```<code>cId        A           B             C
----------------------------------------------
1          string1     string4       string6
2          string2     string5       NULL
3          string3     NULL          string7
</code>```

item and cId rows are not fixed, so i think i need some of dynamic sql for pivoting.
How can i do in tsql?
Thanks

答:
The following will do it:</p>

```<code>DECLARE @pivotFields varchar(255) =
    STUFF(
        (
            SELECT ', [' + item + ']'
            FROM
                (
                    SELECT DISTINCT item
                    FROM YourTable
                ) Q
            ORDER BY item
            FOR XML PATH ('')
        )
        , 1, 2, ''
    )

DECLARE @sql varchar(1000) =
    '
        SELECT cId, ' + @pivotFields + '
        FROM
            (
                SELECT
                    cId
                    , item
                    , value
                FROM YourTable
            ) Q
            PIVOT
            (
                MAX(value)
                FOR item IN (' + @pivotFields + ')
            ) P
    '

EXEC (@sql)
</code>```

Body:
I've this set of data:

cId    item     value
-------------------------------------
1      A        string1
2      A        string2
3      A        string3
1      B        string4
2      B        string5
1      C        string6
3      C        string7

And i would to transpose item ad cId rows into columns, in order to have this result:

cId        A           B             C
----------------------------------------------
1          string1     string4       string6
2          string2     string5       NULL
3          string3     NULL          string7

item and cId rows are not fixed, so i think i need some of dynamic sql for pivoting.
How can i do in tsql?
Thanks

Body:
The following will do it:

DECLARE @pivotFields varchar(255) =
    STUFF(
        (
            SELECT ', [' + item + ']'
            FROM
                (
                    SELECT DISTINCT item
                    FROM YourTable
                ) Q
            ORDER BY item
            FOR XML PATH ('')
        )
        , 1, 2, ''
    )

DECLARE @sql varchar(1000) =
    '
        SELECT cId, ' + @pivotFields + '
        FROM
            (
                SELECT
                    cId
                    , item
                    , value
                FROM YourTable
            ) Q
            PIVOT
            (
                MAX(value)
                FOR item IN (' + @pivotFields + ')
            ) P
    '

EXEC (@sql)


问:
Passing view inside arrayadapter for snackbar
I am trying to pass a View object in an arrayadapter, to open a snackbar.
I need to pass a view into it, but taking a final view before the ClickListeners does not work.

How can I get the view variable past the PopupMenu.OnMenuItemClickListener and DialogInterface.OnClickListener

I want to avoid creating a separate OnMenuItemClickListener to pass parameters.

```<code>@Override
public View getView(final int position,  View convertView, final ViewGroup parent) {
case R.id.exercise_options_area:

try {//setting texts for custom listView

            deleteArea.setOnClickListener(new View.OnClickListener() {//set to the linear layout

                @Override
                public void onClick(View v) {
final PopupMenu popup = new PopupMenu(parent.getContext(), v);
popup.getMenu().add(0, 0, 0, menuIconWithText(parent.getResources().getDrawable(R.drawable.ic_rename), "Rename"));
//if i try using v in snackbar in this line it works, but I don't want it here, I want it down there. using final view = v  does not work

popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        exerciseName = getItem(position);//no spaces, the exerciseName before rename
        switch (item.getOrder()) {
            case 0:///////////////////////RENAME

                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(parent.getContext());
                 View viewInput = (LayoutInflater.from(parent.getContext())).inflate(R.layout.user_input, null);
                final EditText inputExerciseName = viewInput.findViewById(R.id.userInput);

                alertBuilder.setView(viewInput);//show viewInput which is the editText prompt (user_input.xml)

                alertBuilder.setCancelable(true)
                        .setTitle("Enter New Exercise Name")
                        .setPositiveButton("Save", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {//on clicking save
                                if (!mainList.contains(inputExerciseName.getText().toString())) {
                                    String renamed = inputExerciseName.getText().toString();
                                    renameItem(position, renamed);//rename in the list

                                    if (sp.contains(mostRecent +  workoutName + " " + exerciseName + " sets")){//only copy if data exists
                                        copySharedPreferencesRename(renamed, workoutName, exerciseName,sp,editor);//rename by copying data to new name
                                    }

                                    checkSharedPreferencesDeleteExercise(workoutName, exerciseName,sp,editor);//delete the data in old name
                                    editor.apply();//apply must be done here since this action is separate
                                    //refreshListView();//refresh view

                                    ((ExerciseList)mContext).recreate();//refresh activity. for past date it refreshes to current
                                    if (visitState.equals("pastDate")){

                                    }
                                    else
                                    *{
                                        simpleSnackBar("Renamed", "#424242", "#FFFFFF", **NEED VIEW HERE**, Snackbar.LENGTH_LONG );//800 grey, white
                                       //debug passes this point, but snackbar does not show with final view v
                                    }*
                                }
                                else{

                                    return;//make user enter again
                                }
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {//on clicking cancel
                            public void onClick(DialogInterface dialog, int which) {
                                InputMethodManager imm = (InputMethodManager) parent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);//remove keyboard
                                imm.hideSoftInputFromWindow(inputExerciseName.getWindowToken(), 0);
                                dialog.dismiss();
                            }
                        });

                AlertDialog dialog = alertBuilder.create();
                dialog.show();
                dialog.setCanceledOnTouchOutside(false);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

                break;
</code>```

答:
You need to pass the rootView of your Fragment or the root ViewGroup of your Activity to your ArrayAdapter when it's created in its constructor.

Hold this view as a field of the ArrayAdapter and use it for showing SnackBars.

SnackBar wants the view that it's going to show at the bottom of, I assume that is not the result for your Adapter's getView() method.

Body:
I am trying to pass a View object in an arrayadapter, to open a snackbar.
I need to pass a view into it, but taking a final view before the ClickListeners does not work.

How can I get the view variable past the PopupMenu.OnMenuItemClickListener and DialogInterface.OnClickListener

I want to avoid creating a separate OnMenuItemClickListener to pass parameters.

@Override
public View getView(final int position,  View convertView, final ViewGroup parent) {
case R.id.exercise_options_area:

try {//setting texts for custom listView

            deleteArea.setOnClickListener(new View.OnClickListener() {//set to the linear layout

                @Override
                public void onClick(View v) {
final PopupMenu popup = new PopupMenu(parent.getContext(), v);
popup.getMenu().add(0, 0, 0, menuIconWithText(parent.getResources().getDrawable(R.drawable.ic_rename), "Rename"));
//if i try using v in snackbar in this line it works, but I don't want it here, I want it down there. using final view = v  does not work

popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        exerciseName = getItem(position);//no spaces, the exerciseName before rename
        switch (item.getOrder()) {
            case 0:///////////////////////RENAME

                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(parent.getContext());
                 View viewInput = (LayoutInflater.from(parent.getContext())).inflate(R.layout.user_input, null);
                final EditText inputExerciseName = viewInput.findViewById(R.id.userInput);

                alertBuilder.setView(viewInput);//show viewInput which is the editText prompt (user_input.xml)

                alertBuilder.setCancelable(true)
                        .setTitle("Enter New Exercise Name")
                        .setPositiveButton("Save", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {//on clicking save
                                if (!mainList.contains(inputExerciseName.getText().toString())) {
                                    String renamed = inputExerciseName.getText().toString();
                                    renameItem(position, renamed);//rename in the list

                                    if (sp.contains(mostRecent +  workoutName + " " + exerciseName + " sets")){//only copy if data exists
                                        copySharedPreferencesRename(renamed, workoutName, exerciseName,sp,editor);//rename by copying data to new name
                                    }

                                    checkSharedPreferencesDeleteExercise(workoutName, exerciseName,sp,editor);//delete the data in old name
                                    editor.apply();//apply must be done here since this action is separate
                                    //refreshListView();//refresh view

                                    ((ExerciseList)mContext).recreate();//refresh activity. for past date it refreshes to current
                                    if (visitState.equals("pastDate")){

                                    }
                                    else
                                    *{
                                        simpleSnackBar("Renamed", "#424242", "#FFFFFF", **NEED VIEW HERE**, Snackbar.LENGTH_LONG );//800 grey, white
                                       //debug passes this point, but snackbar does not show with final view v
                                    }*
                                }
                                else{

                                    return;//make user enter again
                                }
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {//on clicking cancel
                            public void onClick(DialogInterface dialog, int which) {
                                InputMethodManager imm = (InputMethodManager) parent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);//remove keyboard
                                imm.hideSoftInputFromWindow(inputExerciseName.getWindowToken(), 0);
                                dialog.dismiss();
                            }
                        });

                AlertDialog dialog = alertBuilder.create();
                dialog.show();
                dialog.setCanceledOnTouchOutside(false);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

                break;