问:
Drawing points in phylogenetic tree R
I would like to draw only one point on the fist node, and then draw another one in the first tip. So far I could draw points but only all of them at once and I cannot find the way to draw it separately.  What I have so far:

```<code>library(ape)
t3 = '((a:1,b:1):1,(c:1.5,d:0.5):0.5):1;'
plot(read.tree(text = t3),root.edge=T)
nodelabels(pch=21, col="black", adj=1, bg='blue', cex=2)
</code>```

any help is appreciated

答:
This isn't the exact answer, but it should help. I got this by looking at the code for nodelabels function.

```<code>library(ape)
t3 = '((a:1,b:1):1,(c:1.5,d:0.5):0.5):1;'
plot(read.tree(text = t3),root.edge=T)

lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
node <- (lastPP$Ntip + 1):length(lastPP$xx)
XX <- lastPP$xx[node]
YY <- lastPP$yy[node]
BOTHlabels(text="", node, XX[1], YY[1], adj = c(0.5, 0.5),
frame = "rect", pch = 21, thermo = NULL, pie = NULL,
piecol = NULL, col = "blue", bg = "blue",
horiz = FALSE, width = NULL, height = NULL, cex=2)
</code>```

The XX's and YY's gives the nodes. Here, I'm using only the first one. What you have to do for tips is similar, too. Have a look at the code for tiplabels.

Title: Drawing points in phylogenetic tree R

Body:
I would like to draw only one point on the fist node, and then draw another one in the first tip. So far I could draw points but only all of them at once and I cannot find the way to draw it separately.  What I have so far:

library(ape)
t3 = '((a:1,b:1):1,(c:1.5,d:0.5):0.5):1;'
plot(read.tree(text = t3),root.edge=T)
nodelabels(pch=21, col="black", adj=1, bg='blue', cex=2)

any help is appreciated

Body:
This isn't the exact answer, but it should help. I got this by looking at the code for nodelabels function.

library(ape)
t3 = '((a:1,b:1):1,(c:1.5,d:0.5):0.5):1;'
plot(read.tree(text = t3),root.edge=T)

lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
node <- (lastPP$Ntip + 1):length(lastPP$xx)
XX <- lastPP$xx[node]
YY <- lastPP$yy[node]
BOTHlabels(text="", node, XX[1], YY[1], adj = c(0.5, 0.5),
frame = "rect", pch = 21, thermo = NULL, pie = NULL,
piecol = NULL, col = "blue", bg = "blue",
horiz = FALSE, width = NULL, height = NULL, cex=2)

The XX's and YY's gives the nodes. Here, I'm using only the first one. What you have to do for tips is similar, too. Have a look at the code for tiplabels.


来源: stackexchange

问:
Access to external value inside apply
Short example:

```<code>class MyClass {
 val someName = "want this value"
 val someOther = SomeOther().apply{ someName = someName }
 // other stuff below
}
</code>```

SomeOther will apply the value of its own someName to someName, so value application makes no difference (x=x).

Q: How can I access external someName ("want this value") being inside apply?

UPDATE
I have further doubts related to suggestion to use this.someName=someName, below 2 code snippets, the first one works as expected, surprisingly the second fails with similar behavior as described.

First

```<code>fun main(args: Array<String>) {
    class SomeOther {
        var someName: String? = null
    }
    val someName = "want this value"
    print(SomeOther().apply { this.someName = someName }.someName) // works!

}
</code>```

Second

```<code>class SomeOther {
    var someName: String? = null
}

class MyClass {
    val someName = "want this value"
    val someOther = SomeOther().apply { this.someName = someName }
    fun go() = print(someOther.someName)
}

fun main(args: Array<String>) = MyClass().go() // prints null
</code>```

Q: Where's the difference?

答:
Try this:</p>

```<code>val someName = "want this value"
val otherName = SomeOther().apply { this.someName = someName }
//                     internal someName ---^          ^
//                                external someName ---^

print(otherName.someName) // >>> want this name
</code>```

ContentLicense: CC BY-SA 3.0

Title: Access to external value inside apply

Body:
Short example:

class MyClass {
 val someName = "want this value"
 val someOther = SomeOther().apply{ someName = someName }
 // other stuff below
}

SomeOther will apply the value of its own someName to someName, so value application makes no difference (x=x).

Q: How can I access external someName ("want this value") being inside apply?

UPDATE
I have further doubts related to suggestion to use this.someName=someName, below 2 code snippets, the first one works as expected, surprisingly the second fails with similar behavior as described.

First

fun main(args: Array<String>) {
    class SomeOther {
        var someName: String? = null
    }
    val someName = "want this value"
    print(SomeOther().apply { this.someName = someName }.someName) // works!

}

Second

class SomeOther {
    var someName: String? = null
}

class MyClass {
    val someName = "want this value"
    val someOther = SomeOther().apply { this.someName = someName }
    fun go() = print(someOther.someName)
}

fun main(args: Array<String>) = MyClass().go() // prints null

Q: Where's the difference?

Body:
Try this:

val someName = "want this value"
val otherName = SomeOther().apply { this.someName = someName }
//                     internal someName ---^          ^
//                                external someName ---^

print(otherName.someName) // >>> want this name


问:
Get Json from $http request
Need help to make changes in Angular Factory. Have example working with array JSON data, but need this code work with JSON data from $http request, how do that?

This is example Factory:

```<code>    angular.module('starter.services', [])

.factory('catgs', function() {
  // Might use a resource here that returns a JSON array

  // Some fake testing data
  var catgs = [{
    id: 0,
    name: 'CATG1',
    items: [{
      img:'img/G1I1.png',
      name:'category1Item1',
      status:'OPEN'

       }]
  },{
    id: 1,
    name: 'CATG2',
    items: [{
      img:'img/G2I1.png',
      name:'category2Item1',
      status:'OPEN'

       },{
      img:'img/G2I2.png',
      name:'category2Item2',
      status:'CLOSED'

       }]
  }];

  return {
    all: function() {
      return catgs;
    },
    remove: function(catg) {
      catgs.splice(catgs.indexOf(catg), 1);
    },
    get: function(catgId) {
      for (var i = 0; i < catgs.length; i++) {
        if (catgs[i].id === parseInt(catgId)) {
          return catgs[i];
        }
      }
      return null;
    }
  };
});
</code>```

Need help to replace catgs JSON data to $http request, for example musite.com/jsondata.json

答:
```<code>//try this
$http.get('your api url or .json').then(function(result){
   $scope.jsonData = result.data;
}, function(err) {
   console.log(err);
});
</code>```

Title: Get Json from $http request

Body:
Need help to make changes in Angular Factory. Have example working with array JSON data, but need this code work with JSON data from $http request, how do that?

This is example Factory:

    angular.module('starter.services', [])

.factory('catgs', function() {
  // Might use a resource here that returns a JSON array

  // Some fake testing data
  var catgs = [{
    id: 0,
    name: 'CATG1',
    items: [{
      img:'img/G1I1.png',
      name:'category1Item1',
      status:'OPEN'

       }]
  },{
    id: 1,
    name: 'CATG2',
    items: [{
      img:'img/G2I1.png',
      name:'category2Item1',
      status:'OPEN'

       },{
      img:'img/G2I2.png',
      name:'category2Item2',
      status:'CLOSED'

       }]
  }];

  return {
    all: function() {
      return catgs;
    },
    remove: function(catg) {
      catgs.splice(catgs.indexOf(catg), 1);
    },
    get: function(catgId) {
      for (var i = 0; i < catgs.length; i++) {
        if (catgs[i].id === parseInt(catgId)) {
          return catgs[i];
        }
      }
      return null;
    }
  };
});

Need help to replace catgs JSON data to $http request, for example musite.com/jsondata.json


问:
Java-based workflow solutions
We currently use a sequential workflow to process documents. We have a total of 10 distinct workflow steps. We have re-analyzed the workflow and realized that we could restructure the workflow to process in parallel a number of the workflow steps. Basically we are able to process steps 1,2,3,4 in parallel, wait until steps 1-4 are completed and then process step 5, then process steps 6,7,8,9 in parallel wait until steps 6-9 are completed and then finally process step 10. If we were able to implement this new workflow we could boost our processing throughput dramatically.

My question is: What java-based open-source workflow projects would you recommend? Do they typically support what I outlined above?

Thanks for all the replies. After taking a quick look at the the websites you all have listed I think I have more than enough to chew on for a while.

答: I'd suggest that you check out Bonita Open Solution. It can do the parallel processing you describe, the provided IDE/Studio is pretty good and the out-of-the-box portal functionality is nice.</p>

ContentLicense: CC BY-SA 2.5

Title: Java-based workflow solutions


问:
Bootstrap modal on another modal
I just want to show modal on another modal. (Close current one and needs to open new one) So I used

```<code><a href="#contact" data-toggle="modal" data-target="#forget-password" data-dismiss="modal">Register here</a>
</code>```

data-dismiss="modal" I try with this attribute end of link and it's woking fine. The problem is that the second modal height is bit higher. I can't scroll down to see it's upper content. and input fields looking weird. Please see this image.

Is there any other way to show modal when another modal by closing first modal?

答:
try this

```<code>$('#myModal-1').on('hidden.bs.modal', function (e) {
        $('#myModal-2').modal('show');
});
</code>```

https://jsfiddle.net/princesodhi/ru2rz404/

Title: Bootstrap modal on another modal

Body:
I just want to show modal on another modal. (Close current one and needs to open new one) So I used

Register here

data-dismiss="modal" I try with this attribute end of link and it's woking fine. The problem is that the second modal height is bit higher. I can't scroll down to see it's upper content. and input fields looking weird. Please see this image.

Is there any other way to show modal when another modal by closing first modal?

Body:
try this

$('#myModal-1').on('hidden.bs.modal', function (e) {
        $('#myModal-2').modal('show');
});

https://jsfiddle.net/princesodhi/ru2rz404/


问:
Unknown column in WHERE clause in subquery
I have pages table which I'm trying to truncate.
I need to leave last 10 versions of each page (page is identified by uid).

```<code>id----|----uid----|----version

1 ----|---- 1 ----|---- 1

2 ----|---- 1 ----|---- 2

3 ----|---- 1 ----|---- 3

4 ----|---- 1 ----|---- 4

5 ----|---- 2 ----|---- 1

6 ----|---- 2 ----|---- 2

...........

55 ----|---- 1 ----|---- 23

56 ----|---- 2 ----|---- 14

57 ----|---- 2 ----|---- 15
</code>```

I've tried with this MySQL query:

```<code>DELETE FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)
</code>```

but above SQL returns:

Unknown column 'p.uid' in 'where clause'

On Stackoverflow is loads of answers for similar questions like mine but as I'm not SQL ninja I wasn't able to convert any of these to fit my problem.
I don't want to overkill my query as well.
There must be some simple answer to this.

I can achieve needed truncation in MSSQL Server with query below:

```<code>DELETE FROM pages WHERE id NOT IN (
    SELECT Versions.id FROM
        (SELECT TOP (10) q.id FROM pages AS q WHERE pages.uid = q.uid ORDER BY q.version DESC)
    AS Versions
)
</code>```

Thanks

答:
You don't need to co-ordinate the queries together here; just select a list of IDs to delete- the tables are the same

```<code>DELETE FROM pages WHERE id NOT IN

    (SELECT TOP (10) id FROM pages ORDER BY q.version DESC)
</code>```

You can't "order by" a delete query..

If youre after the MySQL version, and your version of MySQL doesnt support LIMIT for subqueries, and it doesn't support window functions like this:

```<code>delete from pages where id in
  (select id from
    (select id, row_number() over(order by dt desc) as rown from pages) a where a.rown > 10)
  )
</code>```

then you could consider something like:

```<code>CREATE table x as SELECT * FROM pages ORDER BY q.Version DESC LIMIT 10

TRUNCATE /*or delete from*/ pages

INSERT INTO pages SELECT * FROM x
</code>```

Body:
I have pages table which I'm trying to truncate.
I need to leave last 10 versions of each page (page is identified by uid).

id----|----uid----|----version

1 ----|---- 1 ----|---- 1

2 ----|---- 1 ----|---- 2

3 ----|---- 1 ----|---- 3

4 ----|---- 1 ----|---- 4

5 ----|---- 2 ----|---- 1

6 ----|---- 2 ----|---- 2

...........

55 ----|---- 1 ----|---- 23

56 ----|---- 2 ----|---- 14

57 ----|---- 2 ----|---- 15

I've tried with this MySQL query:

DELETE FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)

but above SQL returns:

Unknown column 'p.uid' in 'where clause'

On Stackoverflow is loads of answers for similar questions like mine but as I'm not SQL ninja I wasn't able to convert any of these to fit my problem.
I don't want to overkill my query as well.
There must be some simple answer to this.

I can achieve needed truncation in MSSQL Server with query below:

DELETE FROM pages WHERE id NOT IN (
    SELECT Versions.id FROM
        (SELECT TOP (10) q.id FROM pages AS q WHERE pages.uid = q.uid ORDER BY q.version DESC)
    AS Versions
)

Thanks

Body:
You don't need to co-ordinate the queries together here; just select a list of IDs to delete- the tables are the same

DELETE FROM pages WHERE id NOT IN

    (SELECT TOP (10) id FROM pages ORDER BY q.version DESC)

You can't "order by" a delete query..

If youre after the MySQL version, and your version of MySQL doesnt support LIMIT for subqueries, and it doesn't support window functions like this:

delete from pages where id in
  (select id from
    (select id, row_number() over(order by dt desc) as rown from pages) a where a.rown > 10)
  )

then you could consider something like:

CREATE table x as SELECT * FROM pages ORDER BY q.Version DESC LIMIT 10

TRUNCATE /*or delete from*/ pages

INSERT INTO pages SELECT * FROM x


问:
How to show/hide element in ng-repeat based on value in object? Angularjs
Ok, I'm trying to figure out how to show my various action buttons for each of my items in the list based on the value of item.Status. For example: I would like to only show the Edit button if item.Status is 'New'. What is the best way to approach this?

Also, the solution would need to be able to support multiple values. For example, the Delete button would only show for 'New' and 'Completed', but not for 'In Progress'.

Can this be done with just ng-show?

```<code><ul class="sidebar-list">
    <li class="list-item" ng-repeat="item in requestslist.value | filter:searchText | orderBy:'Modified':true">
        <div class="list-item-info">
            <ul id="" class="list-inline clearfix">
                <li class=""><span id="" class="">#{{item.Id}}</span></li>
                <li class=""><span id="" class="bold">{{item.RecipientName}}</span></li>
                <li class=""><span id="" class="">{{item.RecipientCompany}}</span></li>
            </ul>
            <ul id="" class="list-inline clearfix">
                <li class=""><span id="" class="label label-primary">{{item.Status}}</span></li>
            </ul>
        </div>
        <div class="list-item-actions">
            <div class="btn-group">
                <button ng-click="doRemind()" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-bullhorn"></span> Remind</button>
                <button ng-click="doView()" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-eye-open"></span> View</button>
                <button ng-click="doEdit(item)" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-pencil"></span> Edit</button>
                <button ng-click="doClose(item)" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-ban-circle"></span> Close</button>
                <button ng-click="doDelete(item)" type="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-ban-minus"></span> Delete</button>
            </div>
        </div>
    </li>
</ul>
</code>```

答:
Even since it has been a while since the OP asked the question, adding my two cents in case someone else needs an easier option which is to use the angularjs filter.

So to show only items where item.status === new use:

```<code> ng-repeat="item in requestslist.value | filter: {status: 'new'}
</code>```

IF on the other hand you want only items where item.status !== new use:

```<code> ng-repeat="item in requestslist.value | filter: {status: '!new'}
</code>```

Body:
Ok, I'm trying to figure out how to show my various action buttons for each of my items in the list based on the value of item.Status. For example: I would like to only show the Edit button if item.Status is 'New'. What is the best way to approach this?

Also, the solution would need to be able to support multiple values. For example, the Delete button would only show for 'New' and 'Completed', but not for 'In Progress'.

Can this be done with just ng-show?

#{{item.Id}}

{{item.RecipientName}}

{{item.RecipientCompany}}

{{item.Status}}

                <button ng-click="doRemind()" type="button" class="btn btn-default btn-sm"> Remind</button>
                <button ng-click="doView()" type="button" class="btn btn-default btn-sm"> View</button>
                <button ng-click="doEdit(item)" type="button" class="btn btn-default btn-sm"> Edit</button>
                <button ng-click="doClose(item)" type="button" class="btn btn-default btn-sm"> Close</button>
                <button ng-click="doDelete(item)" type="button" class="btn btn-default btn-sm"> Delete</button>

Body:
Even since it has been a while since the OP asked the question, adding my two cents in case someone else needs an easier option which is to use the angularjs filter.

So to show only items where item.status === new use:

 ng-repeat="item in requestslist.value | filter: {status: 'new'}

IF on the other hand you want only items where item.status !== new use:

 ng-repeat="item in requestslist.value | filter: {status: '!new'}


问:
Find an unused number in a bunch of numbers
I have a huge table filled with numbers (1001001..1009999) and there are certainly a bunch of unused numbers in that area. So, I could have all these numbers returned by doing:

```<code>SELECT MY_IDENTIFIER FROM MY_TABLE
</code>```

that would return all used numbers. How could I get a list of unused numbers from that table? I work serverside (rhino/jaxer) with JavaScript and my database is Oracle 10g.

Thanks,

答:
Javascript is not really related to that, isn't it?
I did something similiar years before.

I had a table with all numbers in a range and joined these two tables and selected those numbers which could not be joined. A negative select.

Something like

```<code> select nr bulk collect into nrs1 from tbl1 where nr not in
                (select nr from tbl2);
</code>```

Body:
I have a huge table filled with numbers (1001001..1009999) and there are certainly a bunch of unused numbers in that area. So, I could have all these numbers returned by doing:

SELECT MY_IDENTIFIER FROM MY_TABLE

that would return all used numbers. How could I get a list of unused numbers from that table? I work serverside (rhino/jaxer) with JavaScript and my database is Oracle 10g.

Thanks,

Body:
Javascript is not really related to that, isn't it?
I did something similiar years before.

I had a table with all numbers in a range and joined these two tables and selected those numbers which could not be joined. A negative select.

Something like

 select nr bulk collect into nrs1 from tbl1 where nr not in
                (select nr from tbl2);


问:
How to round a number upto n decimal places in sql server
I have column in table which I want to round upto some decimal places.
Which is stored in some other table.

Actually my data is stored as 8 decimal places, but based on user preference, I need to show upto that decimal place.

Column datatype is numeric(19,8)

I have procedure which is returning all rows. So At that time only I want to round my column up to specified decimal decimal

Want to do something like

```<code>declare @i int = 2
Begin
select cast (12533333.193 as numeric(38,@i))
end
</code>```

how to achieve this?
Please suggest

答:
This is the MOST easy of all

Before starting I want to tell that this works only for float type (Yes! you need to convert your decimals / numerics to float!). Syntax wise it is Most Readable as well!

select round(cast(65.456 as float),2) (This will round off to 2 decimal places)

select round(cast(65.456 as float),1) (This will round off to 1 decimal places)

select round(cast(65.456 as float),0) (This will round off to 0 decimal places)

See the snapshot below

Body:
I have column in table which I want to round upto some decimal places.
Which is stored in some other table.

Actually my data is stored as 8 decimal places, but based on user preference, I need to show upto that decimal place.

Column datatype is numeric(19,8)

I have procedure which is returning all rows. So At that time only I want to round my column up to specified decimal decimal

Want to do something like

declare @i int = 2
Begin
select cast (12533333.193 as numeric(38,@i))
end

how to achieve this?
Please suggest


答:
using this reference expression as below:

```<code>val someOther = SomeOther().apply { someName = this@MyClass.someName }
//                 reference to the outer class ---^
</code>```

AND the T.apply function is a convenient way to applying Builder Design Pattern, in this way you never need using this or additional parameter at all, for example:

```<code>val foo = Foo().apply {
  //v--- no need using `this` or any addition parameters
    foo = "bar"
    fuzz = "buzz"
}

class Foo {
    lateinit var foo: String;
    lateinit var fuzz: String
}
</code>```

Edit

you can assuming apply(lambda) which will apply an anonymous class of Function2<T,ARG,T> instance, then you know why immediately?

in your first approach it looks like as below:

```<code>val lambda: Function2<SomeOther, String, SomeOther> = { thisRef, arg ->
    thisRef.someName = arg;
    //                 ^--- parameter is used in lambda
    thisRef
}

val someName = lambda(SomeOther(), "want this value").someName

println(someName)
</code>```

in your second approach it looks like as below:

```<code>class MyClass {
    val lambda: Function2<SomeOther, MyClass, SomeOther> = { thisRef, arg ->
        //              the parameter `arg` is never used in lambda ---^
        thisRef.someName = thisRef.someName
        //                    ^--- it use thisRef's someName rather than arg's
        thisRef
    }

    val someOther = lambda(SomeOther(), this)
}
</code>```

Title: Access to external value inside apply

Body:
using this reference expression as below:

val someOther = SomeOther().apply { someName = this@MyClass.someName }
//                 reference to the outer class ---^

AND the T.apply function is a convenient way to applying Builder Design Pattern, in this way you never need using this or additional parameter at all, for example:

val foo = Foo().apply {
  //v--- no need using `this` or any addition parameters
    foo = "bar"
    fuzz = "buzz"
}

class Foo {
    lateinit var foo: String;
    lateinit var fuzz: String
}

Edit

you can assuming apply(lambda) which will apply an anonymous class of Function2<T,ARG,T> instance, then you know why immediately?

in your first approach it looks like as below:

val lambda: Function2<SomeOther, String, SomeOther> = { thisRef, arg ->
    thisRef.someName = arg;
    //                 ^--- parameter is used in lambda
    thisRef
}

val someName = lambda(SomeOther(), "want this value").someName

println(someName)

in your second approach it looks like as below:

class MyClass {
    val lambda: Function2<SomeOther, MyClass, SomeOther> = { thisRef, arg ->
        //              the parameter `arg` is never used in lambda ---^
        thisRef.someName = thisRef.someName
        //                    ^--- it use thisRef's someName rather than arg's
        thisRef
    }

    val someOther = lambda(SomeOther(), this)
}


问:
Difference between passing as int and the pointer inside class gives me segmentation fault
I am trying to implement a simple linkedlist insertion in C++. Now, my code looks like in the first attempt, the code itself is self-explanatory but I have added some obvious comment as stackoverflow is not allowing me to post the question without putting some comments:

```<code>// Simple class and struct node
struct node {
        int data;
        struct node *next;
};

class list {
     // Member functions
     private:
        // Defining struct object
        node *root;

    public:
        bool insertNode(node *root); // Insertion function
        void print_list();
};

bool list::insertNode(node *n){
    root->next = n;
    return true;
    /*
     node *temp = new node;
     temp->data = data;

    if(root == NULL){
        root->next = new node;`enter code here`
        root->next->data = data;
        root->next->next = NULL;
        cout << "Coming" << "\n";
        return true;
    } else {
        temp->next = root;
        root = temp;
        return true;
    } */

}

void list::print_list(){

    node *p = root;
    // . Iterating the list
    p = p->next;
    while(p != NULL){
        cout << p->data << "\n";
        p = p->next;
    }
}

int main(){

    class list l;
    node *n = new node;
    n->data = 5;
    n->next = NULL;
    if(!l.insertNode(n)){
        cout << "Failed" << "\n";
        return 1;
    }
    l.print_list();

    return 1;
}
</code>```

The thing is that when i try to modify my program as below, difference is that instead of having a node as argument in insert function, if I have an int as argument then it gives me segmentation fault.

==========================================================================

include

```<code>#include <string>

using namespace std;

struct node {
        int data;
        struct node *next;
};

class list {

     private:
        node *root;

    public:
        bool insertNode(int data);
        void print_list();
};

// Insertion function
bool list::insertNode(int data){

    if(root == NULL){
        root = new node;
        root->data = data;
        root->next = NULL;
        return true;
    } else {
        node *temp = new node;
        temp->data = data;
        temp->next = root;
        root = temp;
        return true;
    }

    return false;
}

// Print function
void list::print_list(){

    node *p = root;

    p = p->next;
    while(p != NULL){
        cout << p->data << "\n";
        p = p->next;
    }
}

// Main driver code
int main(){

    class list l;

    if(!l.insertNode(5)){
        cout << "Failed" << "\n";`enter code here`
        return 1;
    }
    l.print_list();

    return 1;
}

</code>```

output:./p

```<code>5
0
Segmentation fault: 11
</code>```

Which means that in insertion function I pass an integer instead of a node then why I get segmentation fault? Since root defined in the list class has never been allocated memory and in my insertion function if I detect that root is null so I simply do root = new node; whats wrong with it? On the other hand if I insert a node instead of "int" in the insertion function then I get correct output? What is the difference?

答:
So I figured out the solution. It was indeed the constructor and destructor like Michael pointed out. In order to use the "root" I needed to initialize it and then I can use it for new and delete. Initialization and deletion should be in constructor and destructor. Complete code is below, please comment if you see any wrongdoing.</p>

```<code>#include <iostream>
#include <string>

using namespace std;

struct node {
        int data;
        struct node *next;
};

class list {

     private:
        node *root;

    public:
        list(); // Default constructor
        ~list(); // Default destructor;

        bool insertNode(int data);
        bool remove(int data);
        void print_list();
};

list::list(void){
     root = NULL;

}

list::~list(void){

      node *p;
      while(root != NULL){
            p = root;
            root = root->next;
            free(p);
      }
}

bool list::remove(int data){

     node *p = root, *prev;
     while(p != NULL){
           if(p->data == data){
              prev->next = p->next;
              delete p;
              return true;
           }
           prev = p;
           p = p->next;
     }

     return false;
}

bool list::insertNode(int data){

    if(root == NULL){
        root = new node;
        root->data = data;
        root->next = NULL;
        return true;
    } else {
        node *temp = new node;
        temp->data = data;
        temp->next = root;
        root = temp;
        return true;
    }

}

void list::print_list(){

    node *p = root;

    while(p != NULL){
        cout << p->data << "\n";
        p = p->next;
    }
}

int main(){

    class list l;
    node *n = new node;
    n->data = 5;
    n->next = NULL;
    if(!l.insertNode(5)){
        cout << "Failed" << "\n";
        return 1;
    }
    l.insertNode(6);
    l.insertNode(7);
    cout << "Before deletion" << "\n";
    l.print_list();
    cout << "After deletion" << "\n";
    l.remove(5);
    l.print_list();

    return 1;
}
</code>```

Body:
I am trying to implement a simple linkedlist insertion in C++. Now, my code looks like in the first attempt, the code itself is self-explanatory but I have added some obvious comment as stackoverflow is not allowing me to post the question without putting some comments:

// Simple class and struct node
struct node {
        int data;
        struct node *next;
};

class list {
     // Member functions
     private:
        // Defining struct object
        node *root;

    public:
        bool insertNode(node *root); // Insertion function
        void print_list();
};

bool list::insertNode(node *n){
    root->next = n;
    return true;
    /*
     node *temp = new node;
     temp->data = data;

    if(root == NULL){
        root->next = new node;`enter code here`
        root->next->data = data;
        root->next->next = NULL;
        cout << "Coming" << "\n";
        return true;
    } else {
        temp->next = root;
        root = temp;
        return true;
    } */

}

void list::print_list(){

    node *p = root;
    // . Iterating the list
    p = p->next;
    while(p != NULL){
        cout <
data << "\n";
        p = p->next;
    }
}

int main(){

    class list l;
    node *n = new node;
    n->data = 5;
    n->next = NULL;
    if(!l.insertNode(n)){
        cout << "Failed" << "\n";
        return 1;
    }
    l.print_list();

    return 1;
}

The thing is that when i try to modify my program as below, difference is that instead of having a node as argument in insert function, if I have an int as argument then it gives me segmentation fault.

==========================================================================

include

#include <string>

using namespace std;

struct node {
        int data;
        struct node *next;
};

class list {

     private:
        node *root;

    public:
        bool insertNode(int data);
        void print_list();
};

// Insertion function
bool list::insertNode(int data){

    if(root == NULL){
        root = new node;
        root->data = data;
        root->next = NULL;
        return true;
    } else {
        node *temp = new node;
        temp->data = data;
        temp->next = root;
        root = temp;
        return true;
    }

    return false;
}

// Print function
void list::print_list(){

    node *p = root;

    p = p->next;
    while(p != NULL){
        cout <
data << "\n";
        p = p->next;
    }
}

// Main driver code
int main(){

    class list l;

    if(!l.insertNode(5)){
        cout << "Failed" << "\n";`enter code here`
        return 1;
    }
    l.print_list();

    return 1;
}

output:./p

5
0
Segmentation fault: 11

Which means that in insertion function I pass an integer instead of a node then why I get segmentation fault? Since root defined in the list class has never been allocated memory and in my insertion function if I detect that root is null so I simply do root = new node; whats wrong with it? On the other hand if I insert a node instead of "int" in the insertion function then I get correct output? What is the difference?

Body:
So I figured out the solution. It was indeed the constructor and destructor like Michael pointed out. In order to use the "root" I needed to initialize it and then I can use it for new and delete. Initialization and deletion should be in constructor and destructor. Complete code is below, please comment if you see any wrongdoing.

#include <iostream>
#include <string>

using namespace std;

struct node {
        int data;
        struct node *next;
};

class list {

     private:
        node *root;

    public:
        list(); // Default constructor
        ~list(); // Default destructor;

        bool insertNode(int data);
        bool remove(int data);
        void print_list();
};

list::list(void){
     root = NULL;

}

list::~list(void){

      node *p;
      while(root != NULL){
            p = root;
            root = root->next;
            free(p);
      }
}

bool list::remove(int data){

     node *p = root, *prev;
     while(p != NULL){
           if(p->data == data){
              prev->next = p->next;
              delete p;
              return true;
           }
           prev = p;
           p = p->next;
     }

     return false;
}

bool list::insertNode(int data){

    if(root == NULL){
        root = new node;
        root->data = data;
        root->next = NULL;
        return true;
    } else {
        node *temp = new node;
        temp->data = data;
        temp->next = root;
        root = temp;
        return true;
    }

}

void list::print_list(){

    node *p = root;

    while(p != NULL){
        cout << p->data << "\n";
        p = p->next;
    }
}

int main(){

    class list l;
    node *n = new node;
    n->data = 5;
    n->next = NULL;
    if(!l.insertNode(5)){
        cout << "Failed" << "\n";
        return 1;
    }
    l.insertNode(6);
    l.insertNode(7);
    cout << "Before deletion" << "\n";
    l.print_list();
    cout << "After deletion" << "\n";
    l.remove(5);
    l.print_list();

    return 1;
}


问:
How to specify start up option with mysql.server start
I am using mariadb, and mysql.server start
I want to specify a start up option as given in the mariadb documentation:

innodb_page_size=4k

however, when I try:

mysql.server start --innodb_page_size=4k

this doesn't work
I also tried to put innodb_page_size in my.cnf under the [mysqld] tag, and this also resulted in a error when I tried to startup the mysql server.

Where exactly can I specify these startup options?

答:
You have mistyped the option. Indeed for Mysql/MariaDB each option has a name for the command line's startup options, and the my.cnf configuration file

use --innodb-page-size for passing the option from the command line

use innodb_page_size for passing the option from my.cnf configuration file

Options taken from mysql 5.7 version's documentation.

Best regards.


问:
Launch external program with multiple commands via Powershell
I am currently attempting to launch a different console (.exe) and pass multiple commands; while starting and entering a command works just fine, I haven't been able to find out how multiple ones can be entered via powershell.

```<code>& "C:\Program Files\Docker Toolbox\start.sh" docker-compose up -d --build
</code>```

The given command works fine, but as mentioned I need to pass more than one command - I tried using arrays, ScriptBlocks and different sequences, though to no avail.

Edit:

Noticed that the docker build has a -f tag which allows me to specify a file; however, the issue now seems to be that the executed cmd removes all backslashes & special characters, rendering the path given useless.

Example:

```<code>&"C:\Program Files\Docker Toolbox\start.sh" 'docker-compose build -f
path\to\dockerfile'
</code>```

will result in an error stating that "pathtodockerfile" is an invalid path.

答:
Turns out that it was easier than expected; Solved it by executing a seperate file that contained the two commands needed and passing it to the start.sh file.</p>

```<code>&"C:\Program Files\Docker Toolbox\start.sh" './xyz/fileContainingCommands.sh'
</code>```

Body:
I am currently attempting to launch a different console (.exe) and pass multiple commands; while starting and entering a command works just fine, I haven't been able to find out how multiple ones can be entered via powershell.

& "C:\Program Files\Docker Toolbox\start.sh" docker-compose up -d --build

The given command works fine, but as mentioned I need to pass more than one command - I tried using arrays, ScriptBlocks and different sequences, though to no avail.

Edit:

Noticed that the docker build has a -f tag which allows me to specify a file; however, the issue now seems to be that the executed cmd removes all backslashes & special characters, rendering the path given useless.

Example:

&"C:\Program Files\Docker Toolbox\start.sh" 'docker-compose build -f
path\to\dockerfile'

will result in an error stating that "pathtodockerfile" is an invalid path.

Body:
Turns out that it was easier than expected; Solved it by executing a seperate file that contained the two commands needed and passing it to the start.sh file.

&"C:\Program Files\Docker Toolbox\start.sh" './xyz/fileContainingCommands.sh'


问:
c# easiest way to extract substring
i have a string:

```<code>string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"
</code>```

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

答:
```<code>String result = Path.GetFileName("\\\\Tecan1\\tecan #1 output\\15939-E.ESY").Split('-')[0];
</code>```

Perhaps?

Title: c# easiest way to extract substring

Body:
i have a string:

string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

Body:
String result = Path.GetFileName("\\\\Tecan1\\tecan #1 output\\15939-E.ESY").Split('-')[0];

Perhaps?


问:
Complete turn x angle values are mapped to half turn using asin function, how to mirror them back?
I have angles that form a complete turn in an array x, from -90 to 270 e.g. (it may be defined otherwise, like from 0 to 360 or -180 to 180) with step 1 or whatever.

asin function is valid only between -90 and +90.

Thus, angles < -90 or > 90 would be "mapped" between these values.

E.g. y = some_asin_func(over_sin(x)) will end up in an y value that is always between -90 and +90. So y is stuck between -90 and +90.

I do need to retrieve to which x-input is y related, because it's ambiguous yet: for example, the function over (x) will give the same y values for x = 120 and x = 60, or x = -47 and x = 223. Which is not what I want.

Put an other way; I need y making a complete turn as x does, ranging from where x starts up to where x ends.

An image will be better:

Here, x ranges between -90 (left) to 270 (right of the graph).

The valid part of the curve is between x=-90 and x=+90 (left half of the graph).

All other values are like mirrored about y=90 or y=-90.

For x=180 for example, I got y=0 and it should be y=180.

For x=270, I have y=-90 but it should be y=270, thus +360.

Here's a code sample:

```<code>A   = 50 # you can make this value vary to have different curves like in the images, when A=0 -> shape is triangle-like, when A=90-> shape is square-like.
x   = np.linspace(-90,270,int(1e3))
u   = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v   = 180*(np.arcsin(u))/math.pi
y   = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
plt.plot(x,y)
plt.grid(True)
</code>```

Once again, first left half of the graph is completely correct.
The right half is also correct in its behavior, but in final, here, it must be mirrored about an horizontal axis at position y=+90 when x>90, like this:

That is, it's like the function is mirrored about y=-90 and y=+90 for y where x is out of the range [-90,+90] and only where where x is out of the range [-90,+90].

I want to un-mirror it outside the valid [-90,+90] range:

 about y=-90 where y is lower than -90

 about y=+90 where y is greater than +90

And of course, modulo each complete turn.

Here an other example where x ranges from -180 to 180 and the desired behavior:

Yet:

Wanted:

I have first tested some simple thing up now:

```<code>A = 50
x = np.linspace(-180,180,int(1e3))
u = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v = 180*(np.arcsin(u))/math.pi
y = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
for i,j in np.ndenumerate(x):
    xval = (j-180)%180-180
    if (xval < -90):
        y[i] = y[i]-val
    elif (xval > 90):
        y[i] = y[i]+val

plt.plot(x,y);
plt.grid(True)
plt.show()
</code>```

which doesn't work at all but I think the background idea is there...

I guess it may be some kind of modulo trick but can't figure it out.

答:
Here a solution that fixes the periodicity of the cos function 'brute force' by calculating an offset and a sign correction based on the x value. I'm sure there is something better out there, but I would almost need a drawing with the angles and distances involved.

```<code>from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots(1,1, figsize=(4,4))

x = np.linspace(-540,540,1000)
sign = np.sign(np.cos(np.pi*x/180))
offset = ((x-90)//180)*180

for A in range(1,91,9):

    u   = np.sin(np.pi*A/180)*np.cos(np.pi*x/180)
    v   = 180*(np.arcsin(u))/np.pi
    y   = 180*np.arcsin(np.sin(np.pi*x/180)/np.cos(np.pi*v/180))/np.pi
    y   = sign*y + offset

    ax.plot(x,y)

ax.grid(True)
plt.show()
</code>```

The result for the interval [-540, 540] looks like this:

Note that you can get pi also from numpy, so you don't need to import math -- I altered the code accordingly.

EDIT:
Apparently I first slightly misunderstood the OP's desired output. If the calculation of offset is just slightly changed, the result is as requested:

```<code>from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots(1,1, figsize=(4,4))

x = np.linspace(-720,720,1000)
sign = np.sign(np.cos(np.pi*x/180))
offset = ((x-90)//180 +1 )*180 - ((x-180)//360+1)*360

for A in range(1,91,9):

    u   = np.sin(np.pi*A/180)*np.cos(np.pi*x/180)
    v   = 180*(np.arcsin(u))/np.pi
    y   = 180*np.arcsin(np.sin(np.pi*x/180)/np.cos(np.pi*v/180))/np.pi
    y   = sign*y + offset

    ax.plot(x,y)

ax.grid(True)
plt.show()
</code>```

The result now looks like this:

Body:
I have angles that form a complete turn in an array x, from -90 to 270 e.g. (it may be defined otherwise, like from 0 to 360 or -180 to 180) with step 1 or whatever.

asin function is valid only between -90 and +90.

Thus, angles < -90 or > 90 would be "mapped" between these values.

E.g. y = some_asin_func(over_sin(x)) will end up in an y value that is always between -90 and +90. So y is stuck between -90 and +90.

I do need to retrieve to which x-input is y related, because it's ambiguous yet: for example, the function over (x) will give the same y values for x = 120 and x = 60, or x = -47 and x = 223. Which is not what I want.

Put an other way; I need y making a complete turn as x does, ranging from where x starts up to where x ends.

An image will be better:

Here, x ranges between -90 (left) to 270 (right of the graph).

The valid part of the curve is between x=-90 and x=+90 (left half of the graph).

All other values are like mirrored about y=90 or y=-90.

For x=180 for example, I got y=0 and it should be y=180.

For x=270, I have y=-90 but it should be y=270, thus +360.

Here's a code sample:

A   = 50 # you can make this value vary to have different curves like in the images, when A=0 -> shape is triangle-like, when A=90-> shape is square-like.
x   = np.linspace(-90,270,int(1e3))
u   = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v   = 180*(np.arcsin(u))/math.pi
y   = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
plt.plot(x,y)
plt.grid(True)

Once again, first left half of the graph is completely correct.
The right half is also correct in its behavior, but in final, here, it must be mirrored about an horizontal axis at position y=+90 when x>90, like this:

That is, it's like the function is mirrored about y=-90 and y=+90 for y where x is out of the range [-90,+90] and only where where x is out of the range [-90,+90].

I want to un-mirror it outside the valid [-90,+90] range:

 about y=-90 where y is lower than -90

 about y=+90 where y is greater than +90

And of course, modulo each complete turn.

Here an other example where x ranges from -180 to 180 and the desired behavior:

Yet:

Wanted:

I have first tested some simple thing up now:

A = 50
x = np.linspace(-180,180,int(1e3))
u = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v = 180*(np.arcsin(u))/math.pi
y = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
for i,j in np.ndenumerate(x):
    xval = (j-180)%180-180
    if (xval < -90):
        y[i] = y[i]-val
    elif (xval > 90):
        y[i] = y[i]+val

plt.plot(x,y);
plt.grid(True)
plt.show()

which doesn't work at all but I think the background idea is there...

I guess it may be some kind of modulo trick but can't figure it out.

Body:
Here a solution that fixes the periodicity of the cos function 'brute force' by calculating an offset and a sign correction based on the x value. I'm sure there is something better out there, but I would almost need a drawing with the angles and distances involved.

from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots(1,1, figsize=(4,4))

x = np.linspace(-540,540,1000)
sign = np.sign(np.cos(np.pi*x/180))
offset = ((x-90)//180)*180

for A in range(1,91,9):

    u   = np.sin(np.pi*A/180)*np.cos(np.pi*x/180)
    v   = 180*(np.arcsin(u))/np.pi
    y   = 180*np.arcsin(np.sin(np.pi*x/180)/np.cos(np.pi*v/180))/np.pi
    y   = sign*y + offset

    ax.plot(x,y)

ax.grid(True)
plt.show()

The result for the interval [-540, 540] looks like this:

Note that you can get pi also from numpy, so you don't need to import math -- I altered the code accordingly.

EDIT:
Apparently I first slightly misunderstood the OP's desired output. If the calculation of offset is just slightly changed, the result is as requested:

from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots(1,1, figsize=(4,4))

x = np.linspace(-720,720,1000)
sign = np.sign(np.cos(np.pi*x/180))
offset = ((x-90)//180 +1 )*180 - ((x-180)//360+1)*360

for A in range(1,91,9):

    u   = np.sin(np.pi*A/180)*np.cos(np.pi*x/180)
    v   = 180*(np.arcsin(u))/np.pi
    y   = 180*np.arcsin(np.sin(np.pi*x/180)/np.cos(np.pi*v/180))/np.pi
    y   = sign*y + offset

    ax.plot(x,y)

ax.grid(True)
plt.show()

The result now looks like this:


答:
try to use Coalesce function:

```<code>SELECT
    Coalesce(item_id,0) as item_id,
    group_id,
    Coalesce(item_name,0) as item_name,
    Coalesce(quantity,0) as quantity
FROM my_table
GROUP by group_id
</code>```

BTW, in MySQL this would work too:

```<code>SELECT *
FROM my_table
GROUP by group_id
</code>```

Title: MySQL: get items by group

Body:
I have table like this:

_______________________________________________
| item_id  | group_id | item_name  | quantity |
-----------------------------------------------
|        1 | 0001     |   cup_1    |        5 |
-----------------------------------------------
|        2 | 0001     |   cup_2    |        3 |
-----------------------------------------------
|        3 | 0002     |   spoon_1  |        2 |
-----------------------------------------------
|        4 | 0002     |   spoon_2  |        2 |
-----------------------------------------------
|        5 | 0003     |   table_1  |        6 |
-----------------------------------------------
|        6 | 0004     |   table_2  |        7 |
-----------------------------------------------
|        7 | 0004     |   table_3  |        1 |
-----------------------------------------------
|        8 | 0005     |   chair_1  |        5 |
-----------------------------------------------
|        9 | 0005     |   chair_2  |        4 |
-----------------------------------------------

I need to show to the user 20 items from this table, but items with the same group_id should be grouped in one.
So cup_1 and cup_2 are like one item.
The problem is that there could be any number of items in group.
So in fact I need to show 20 groups of items.

I tried to use "group by" statement, but it did not work in this case

How could I compose such query?

Thanks!

UPD.
I'm trying to get items in first 'n' groups (or next 'n' groups - it's for catalog).
The result should look like previous table.
For example:

SELECT * FROM my_table ... LIMIT 1,2:

_______________________________________________
| item_id  | group_id | item_name  | quantity |
-----------------------------------------------
|        3 | 0002     |   spoon_1  |        2 |
-----------------------------------------------
|        4 | 0002     |   spoon_2  |        2 |
-----------------------------------------------
|        5 | 0003     |   table_1  |        6 |
-----------------------------------------------

First 2 groups only

SELECT * FROM my_table ... LIMIT 3,2 - next 2 groups and so on:

_______________________________________________
| item_id  | group_id | item_name  | quantity |
-----------------------------------------------
|        6 | 0004     |   table_2  |        7 |
-----------------------------------------------
|        7 | 0004     |   table_3  |        1 |
-----------------------------------------------
|        8 | 0005     |   chair_1  |        5 |
-----------------------------------------------
|        9 | 0005     |   chair_2  |        4 |
-----------------------------------------------

Engine: MyISAM

Body:
try to use Coalesce function:

SELECT
    Coalesce(item_id,0) as item_id,
    group_id,
    Coalesce(item_name,0) as item_name,
    Coalesce(quantity,0) as quantity
FROM my_table
GROUP by group_id

BTW, in MySQL this would work too:

SELECT *
FROM my_table
GROUP by group_id


问:
If data exist in database Edit button should be display else Add Button without page reload display in ajax success function
If the data exist in the database, the Edit button should be displayed, else Add Button should be displayed without page reload display in ajax success function.

In my form the First Panel is working fine with the same code I did in the second panel where it is not working.

form

```<code><form action="" id="data_form" method="post" >
    <div class="dashboard-column-main">
    <div class="dashboard-container">
    <div class="title-section">
    <h3 class="section_title">Company Information</h3>
    </div>

    <div class="profile-back">
    <div class="panel-group" id="accordion">

    <!--First pannel ends-->
    <div class="panel panel-default">

    <div class="panel-heading row" id="first">
    <div class="col-md-4 col-sm-4 col-xs-4">Company Name</div>
    <div class="col-md-4 col-sm-4 col-xs-4 ellipsis" id="cname"><?php
    if (isset($s_company_name)) {
    echo $s_company_name;
    }
    ?>
    </div>

    <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
    <div class="profile-edit col-sm-4 col-xs-4 col-md-4 aj-text">
    <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
    Add
    <?php else: ?>
    <i class="fa fa-pencil"></i> Edit
    <?php endif; ?>
    </div>
    </a>
    </div>

    <div id="collapseOne" class="panel-collapse collapse">
    <div class="panel-body">
    <div class="row">
    <div class="col-md-7 col-lg-offset-2 text-center">
    <label class="col-md-4">Company Name</label>
    <div class="col-md-8">
    <input type="text" name="company_name" id="company_name" class="form-control"
    value="<?= (isset($s_company_name)) ? $s_company_name : null; ?>"/><br>
    <input type="hidden" name="save_type" id="save_type" value="<?= (empty($s_company_name[0]) || empty($s_company_name)) ? 'Save' : 'Update'; ?>">

    <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
    <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Save</button>
    <?php else: ?>
    <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Update</button>
    <?php endif; ?>
    <button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    <!--First pannel ends-->

    <!--second pannel starts-->
    <div class="panel panel-default">
    <div class="panel-heading row">
    <div class="col-md-4 col-sm-4 col-xs-4">Company Established Date</div>
    <div class="col-md-4 col-sm-4 col-xs-4 ellipsis" id="cdate"><?php
    if (isset($s_company_estd_date)) {
    echo $s_company_estd_date;
    }
    ?>
    </div>
    <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
    <div class="profile-edit col-sm-4 col-xs-4 col-md-4 aj-textt">
    <?php if (empty($s_company_estd_date[0]) || empty($s_company_estd_date)): ?>
    Add
    <?php else: ?>
    <i class="fa fa-pencil"></i> Edit
    <?php endif; ?>
    </div>
    </a>

    </div>
    <div id="collapseTwo" class="panel-collapse collapse">
    <div class="panel-body">
    <div class="row">
    <div class="col-md-7 col-lg-offset-2 text-center">
    <label class="col-md-4">Company Established Date</label>
    <div class="col-md-8">
    <input name="company_estd_date" id="company_estd_date" type ="text" class="form-control" value="<?= (isset($s_company_estd_date)) ? $s_company_estd_date : null; ?>"/><br>
    <input type="hidden" name="save_typee" id="save_typee" value="<?= (empty($s_company_estd_date[0]) || empty($s_company_estd_date)) ? 'Save' : 'Update'; ?>">
    <?php if (empty($s_company_estd_date[0]) || empty($s_company_estd_date)): ?>
    <button type="submit" class="btn btn-success aj-text-btnn" data-target="#collapseTwo" data-toggle="collapse">Save</button>
    <?php else: ?>
    <button type="submit" class="btn btn-success aj-text-btnn" data-target="#collapseTwo" data-toggle="collapse">Update</button>
    <?php endif; ?>
    <button type="button" data-target="#collapseTwo" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
<!--second pannel ends-->

</div>
</div>
</div>
</div>
</form>

<script>
$(document).ready(function () {

$('#data_form').on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/Profile_cntrl/supplier_company_insert_update',
data: form_data,
dataType: 'json',
success: function (result)
{
$(".aj-text").html(result.replace_text);
$(".aj-text-btn").html(result.btn_text);
$("#save_type").val(result.save_type);

$('#cname').text($("#company_name").val());

$(".aj-textt").html(result.replace_textt);
$(".aj-text-btnn").html(result.btn_textt);
$("#save_typee").val(result.save_typee);
$('#cdate').text($("#company_estd_date").val());

},
error: function ()
{
alert('failed');
}
});
});
});
</script>
</code>```

Controller code

```<code>public function supplier_company_insert_update() {

$this->db->select('*');
$this->db->from('supplier_otherdetails');
$this->db->where('supplierid_fk', $this->session->id);
$query = $this->db->get();
$save_type = $this->input->post('save_type');
$save_typee = $this->input->post('save_typee');
$company_name = $this->input->post('company_name');
$cdate = $this->input->post('company_estd_date');

if ($query->num_rows() > 0) {
$this->Profile_model->update_supplier_company();
//redirect('welcome/suppliercompany');
} else {
$this->Profile_model->insert_supplier_company();
//redirect('welcome/suppliercompany');
}

if (trim($company_name) != '')
echo json_encode(array('replace_text' => 'Edit', 'btn_text' => 'Update', 'save_type' => $save_type));
else
echo json_encode(array('replace_text' => 'Add', 'btn_text' => 'Save', 'save_type' => $save_type));

if (trim($cdate) != '')
echo json_encode(array('replace_textt' => 'Edit', 'btn_textt' => 'Update', 'save_typee' =>  $save_typee));
else
echo json_encode(array('replace_textt' => 'Add', 'btn_textt' => 'Save', 'save_typee' =>  $save_typee));
}
</code>```

答:
modified code in controller

```<code> public function supplier_company_insert_update() {

        $this->db->select('*');
        $this->db->from('supplier_otherdetails');
        $this->db->where('supplierid_fk', $this->session->id);
        $query = $this->db->get();
        $save_type = $this->input->post('save_type');
        $company_name = $this->input->post('company_name');

        $save_typee = $this->input->post('save_typee');
        $cdate = $this->input->post('company_estd_date');

 if ($query->num_rows() > 0) {
            $this->Profile_model->update_supplier_company();
            //redirect('welcome/suppliercompany');
        } else {
            $this->Profile_model->insert_supplier_company();
            //redirect('welcome/suppliercompany');
        }

        if (trim($company_name) != '')
            $return_name = array('replace_text' => 'Edit', 'btn_text' => 'Update', 'save_type' => $save_type);
        else
            $return_name = array('replace_text' => 'Add', 'btn_text' => 'Save', 'save_type' => $save_type);

        if (trim($cdate) != '')
            $return_cdate = array('replace_textt' => 'Edit', 'btn_textt' => 'Update', 'save_typee' => $save_typee);
        else
            $return_cdate = array('replace_textt' => 'Add', 'btn_textt' => 'Save', 'save_typee' => $save_typee);
        echo json_encode(array_merge($return_name, $return_cdate));
}
</code>```

Body:
If the data exist in the database, the Edit button should be displayed, else Add Button should be displayed without page reload display in ajax success function.

In my form the First Panel is working fine with the same code I did in the second panel where it is not working.

form

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

Company Information

Company Name

<?php
    if (isset($s_company_name)) {
    echo $s_company_name;
    }
    ?>

    <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
    Add
    <?php else: ?>
     Edit
    <?php endif; ?>

    Company Name

    <input type="text" name="company_name" id="company_name" class="form-control"
    value="<?= (isset($s_company_name)) ? $s_company_name : null; ?>"/>

    <input type="hidden" name="save_type" id="save_type" value="<?= (empty($s_company_name[0]) || empty($s_company_name)) ? 'Save' : 'Update'; ?>">

    <?php if (empty($s_company_name[0]) || empty($s_company_name)): ?>
    <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Save</button>
    <?php else: ?>
    <button type="submit" class="btn btn-success aj-text-btn" data-target="#collapseOne" data-toggle="collapse">Update</button>
    <?php endif; ?>
    <button type="button" data-target="#collapseOne" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>

Company Established Date

<?php
    if (isset($s_company_estd_date)) {
    echo $s_company_estd_date;
    }
    ?>

    <?php if (empty($s_company_estd_date[0]) || empty($s_company_estd_date)): ?>
    Add
    <?php else: ?>
     Edit
    <?php endif; ?>

    Company Established Date

    <input name="company_estd_date" id="company_estd_date" type ="text" class="form-control" value="<?= (isset($s_company_estd_date)) ? $s_company_estd_date : null; ?>"/>

    <input type="hidden" name="save_typee" id="save_typee" value="<?= (empty($s_company_estd_date[0]) || empty($s_company_estd_date)) ? 'Save' : 'Update'; ?>">
    <?php if (empty($s_company_estd_date[0]) || empty($s_company_estd_date)): ?>
    <button type="submit" class="btn btn-success aj-text-btnn" data-target="#collapseTwo" data-toggle="collapse">Save</button>
    <?php else: ?>
    <button type="submit" class="btn btn-success aj-text-btnn" data-target="#collapseTwo" data-toggle="collapse">Update</button>
    <?php endif; ?>
    <button type="button" data-target="#collapseTwo" data-toggle="collapse" class="btn btn-warning cancel-name">Cancel</button>

</form>

Controller code

public function supplier_company_insert_update() {

$this->db->select('*');
$this->db->from('supplier_otherdetails');
$this->db->where('supplierid_fk', $this->session->id);
$query = $this->db->get();
$save_type = $this->input->post('save_type');
$save_typee = $this->input->post('save_typee');
$company_name = $this->input->post('company_name');
$cdate = $this->input->post('company_estd_date');

if ($query->num_rows() > 0) {
$this->Profile_model->update_supplier_company();
//redirect('welcome/suppliercompany');
} else {
$this->Profile_model->insert_supplier_company();
//redirect('welcome/suppliercompany');
}

if (trim($company_name) != '')
echo json_encode(array('replace_text' => 'Edit', 'btn_text' => 'Update', 'save_type' => $save_type));
else
echo json_encode(array('replace_text' => 'Add', 'btn_text' => 'Save', 'save_type' => $save_type));

if (trim($cdate) != '')
echo json_encode(array('replace_textt' => 'Edit', 'btn_textt' => 'Update', 'save_typee' =>  $save_typee));
else
echo json_encode(array('replace_textt' => 'Add', 'btn_textt' => 'Save', 'save_typee' =>  $save_typee));
}

Body:
modified code in controller

 public function supplier_company_insert_update() {

        $this->db->select('*');
        $this->db->from('supplier_otherdetails');
        $this->db->where('supplierid_fk', $this->session->id);
        $query = $this->db->get();
        $save_type = $this->input->post('save_type');
        $company_name = $this->input->post('company_name');

        $save_typee = $this->input->post('save_typee');
        $cdate = $this->input->post('company_estd_date');

 if ($query->num_rows() > 0) {
            $this->Profile_model->update_supplier_company();
            //redirect('welcome/suppliercompany');
        } else {
            $this->Profile_model->insert_supplier_company();
            //redirect('welcome/suppliercompany');
        }

        if (trim($company_name) != '')
            $return_name = array('replace_text' => 'Edit', 'btn_text' => 'Update', 'save_type' => $save_type);
        else
            $return_name = array('replace_text' => 'Add', 'btn_text' => 'Save', 'save_type' => $save_type);

        if (trim($cdate) != '')
            $return_cdate = array('replace_textt' => 'Edit', 'btn_textt' => 'Update', 'save_typee' => $save_typee);
        else
            $return_cdate = array('replace_textt' => 'Add', 'btn_textt' => 'Save', 'save_typee' => $save_typee);
        echo json_encode(array_merge($return_name, $return_cdate));
}


问:
Show hidden values in chrome
I was wondering if there is a way to show the values for the key variable?
There isn't a check for the answers, and I cannot for the life of me find out the answer. Please help:

<form method="post" action="/webwork2//Section13.3/5/"
  enctype="multipart/form-data" id="problemMainForm" name="problemMainForm" onsubmit="submitAction()">
  <input type="hidden" name="user" value="name" id="hidden_user" />
  <input type="hidden" name="effectiveUser" value="name" id="hidden_effectiveUser" />
  <input type="hidden" name="key" value="ZHaiEU4qkcpMc1m2kBaYrMvbOo5TktAY" id="hidden_key" />
</form>```

答:
This simple JavaScript function makes visible all hidden inputs on the site:

function showHiddenInputs() {
    inputs = Array.from(document.getElementsByTagName('input'));
    inputs.forEach((input) => {
        if (input.type === 'hidden')
            input.type = 'text';
})}

showHiddenInputs();
```
<p>One-liner to the browser console:</p>
<pre class="lang-js prettyprint-override"><code>inputs = Array.from(document.getElementsByTagName('input')); inputs.forEach((input) => { if (input.type === 'hidden') input.type = 'text'; })
</code>```

If you wanna get value only from element with name "key", use this in console:

document.getElementsByName('key')[0].value
```
<p>You can use any other number instead of 0, if there are multiple elements with name "key" or you can use this loop:</p>
<pre class="lang-js prettyprint-override"><code>elements = Array.from(document.getElementsByName('lsd'));
elements.forEach((element) => {
    if (element.type === 'hidden')
        console.log(element.value);
})
</code>```

Title: Show hidden values in chrome

Body:
This simple JavaScript function makes visible all hidden inputs on the site:

function showHiddenInputs() {
    inputs = Array.from(document.getElementsByTagName('input'));
    inputs.forEach((input) => {
        if (input.type === 'hidden')
            input.type = 'text';
})}

showHiddenInputs();

One-liner to the browser console:

inputs = Array.from(document.getElementsByTagName('input')); inputs.forEach((input) => { if (input.type === 'hidden') input.type = 'text'; })

If you wanna get value only from element with name "key", use this in console:

document.getElementsByName('key')[0].value

You can use any other number instead of 0, if there are multiple elements with name "key" or you can use this loop:

elements = Array.from(document.getElementsByName('lsd'));
elements.forEach((element) => {
    if (element.type === 'hidden')
        console.log(element.value);
})

ContentLicense: CC BY-SA 4.0


问:
.htaccess redirect dynamic url to another domain
I want to redirect www.olddomain.com/confirm/dynamic_url
To www.newdomain/confirm/same_dynamic_url

Example
Everything after/confirm/ is dynamic value and change everytime.

www.domain1.com/confirm/cb505b970cf819590ac9488810cb75beeb04335b/1499332181/ahJlfm9mZml0by1hcHBncmVlZHlyFAsSB0FjY291bnQYgICAgNShxwoM

has to change

www.domain2.com/confirm/cb505b970cf819590ac9488810cb75beeb04335b/1499332181/ahJlfm9mZml0by1hcHBncmVlZHlyFAsSB0FjY291bnQYgICAgNShxwoM

Everything after /confirm/ is dynamic and change every time.

domain1.com has to be functional when the url has not /confirm/ in and not redirect root.

Example

www.domain1.com/contactus ->No redirect

www.domain1.com/confirm/bla/bla/bla ->redirect

Thanks

答:
You can use this </p>

```<code>Redirect 301 /confirm www.domain2.com/confirm/cb505b970cf819590ac9488810cb75beeb04335b/1499332181/ahJlfm9mZml0by1hcHBncmVlZHlyFAsSB0FjY291bnQYgICAgNShxwoM
</code>```

Body:
You can use this

Redirect 301 /confirm www.domain2.com/confirm/cb505b970cf819590ac9488810cb75beeb04335b/1499332181/ahJlfm9mZml0by1hcHBncmVlZHlyFAsSB0FjY291bnQYgICAgNShxwoM


答:
```<code>DELETE PG FROM pages PG
LEFT JOIN
 (
    SELECT  q.id FROM pages AS q ORDER BY q.version DESC LIMIT 10 OFFSET 0
 ) Versions ON Versions.ID=PG.ID
WHERE Versions.ID IS NULL
</code>```

You can try above query.

Title: Unknown column in WHERE clause in subquery

Body:
I have pages table which I'm trying to truncate.
I need to leave last 10 versions of each page (page is identified by uid).

id----|----uid----|----version

1 ----|---- 1 ----|---- 1

2 ----|---- 1 ----|---- 2

3 ----|---- 1 ----|---- 3

4 ----|---- 1 ----|---- 4

5 ----|---- 2 ----|---- 1

6 ----|---- 2 ----|---- 2

...........

55 ----|---- 1 ----|---- 23

56 ----|---- 2 ----|---- 14

57 ----|---- 2 ----|---- 15

I've tried with this MySQL query:

DELETE FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10)
    AS Versions
)

but above SQL returns:

Unknown column 'p.uid' in 'where clause'

On Stackoverflow is loads of answers for similar questions like mine but as I'm not SQL ninja I wasn't able to convert any of these to fit my problem.
I don't want to overkill my query as well.
There must be some simple answer to this.

I can achieve needed truncation in MSSQL Server with query below:

DELETE FROM pages WHERE id NOT IN (
    SELECT Versions.id FROM
        (SELECT TOP (10) q.id FROM pages AS q WHERE pages.uid = q.uid ORDER BY q.version DESC)
    AS Versions
)

Thanks

Body:
DELETE PG FROM pages PG
LEFT JOIN
 (
    SELECT  q.id FROM pages AS q ORDER BY q.version DESC LIMIT 10 OFFSET 0
 ) Versions ON Versions.ID=PG.ID
WHERE Versions.ID IS NULL

You can try above query.


问:
Android Studio: Application Installation Failed
I've been trying to learn how to use Android Studio but when I attempted to run one of the sample programs I get this error message:

Installation failed with message null.
      It is possible that this issue is resolved by uninstalling an existing version of the apk if it is present, and then re-installing.

WARNING: Uninstalling will remove the application data!

Do you want to uninstall the existing application?

I've tried to do this on 5 more sample programs and all of them give me this error. Does anyone know how to solve this?

答:
Disable Instant Run

Preferences > Build, Execution, Deployment > Instant Run

Source: comment by @user77309


问:
IIS php extension URL rewrite rule and wordpress in sub directory conflict
I have wordpress installed in a sub directory called 'blog' in the main root folder, and a web.config URL rewrite to detail with the .php extension in the root folder. I also have the standard wordpress web.config file in the 'blog' sub directory.

All works except for some reason the login page keeps refreshing itself on login which leads me to believe there is a conflict.

Would omitting the 'blog' directory in the root web.config help? I have tried but all I receive is 500 errors.

Here is the root web.config...

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect .php extension" stopProcessing="false">
  <match url="^(.*).php$" ignoreCase="true" />
<conditions logicalGrouping="MatchAny">
  <add input="{URL}" pattern="(.*).php$" ignoreCase="false" />
</conditions>
  <action type="Redirect" url="{R:1}" redirectType="Permanent" />
</rule>
<rule name="hide .php extension" stopProcessing="true">
  <match url="^(.*)$" ignoreCase="true" />
<conditions>
  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  <add input="{REQUEST_FILENAME}.php" matchType="IsFile" />
  </conditions>
  <action type="Rewrite" url="{R:0}.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
</code>```

And here is the blog/ web.config...

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
  <rules>
        <rule name="wordpress" patternSyntax="Wildcard">
            <match url="*"/>
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                </conditions>
            <action type="Rewrite" url="index.php"/>
        </rule></rules>
</rewrite>
</system.webServer>
</configuration>
</code>```

Any ideas much appreciated.

答:
I finally found a solution to this issue and it now works a treat.

I added a new rule to omit the blog folder...
<rule name="block" stopProcessing="true">
    <match url="^blog/wp-login.php$" />
    <action type="None" />
    </rule>

This overcame the issue. This solution was found at...
How to exclude a directory with IIS URL rewriting

Body:
I have wordpress installed in a sub directory called 'blog' in the main root folder, and a web.config URL rewrite to detail with the .php extension in the root folder. I also have the standard wordpress web.config file in the 'blog' sub directory.

All works except for some reason the login page keeps refreshing itself on login which leads me to believe there is a conflict.

Would omitting the 'blog' directory in the root web.config help? I have tried but all I receive is 500 errors.

Here is the root web.config...

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect .php extension" stopProcessing="false">
  <match url="^(.*).php$" ignoreCase="true" />
<conditions logicalGrouping="MatchAny">
  <add input="{URL}" pattern="(.*).php$" ignoreCase="false" />
</conditions>
  <action type="Redirect" url="{R:1}" redirectType="Permanent" />
</rule>
<rule name="hide .php extension" stopProcessing="true">
  <match url="^(.*)$" ignoreCase="true" />
<conditions>
  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  <add input="{REQUEST_FILENAME}.php" matchType="IsFile" />
  </conditions>
  <action type="Rewrite" url="{R:0}.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

And here is the blog/ web.config...

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
  <rules>
        <rule name="wordpress" patternSyntax="Wildcard">
            <match url="*"/>
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                </conditions>
            <action type="Rewrite" url="index.php"/>
        </rule></rules>
</rewrite>
</system.webServer>
</configuration>

Any ideas much appreciated.


问:
Return the contents of an image in php file?
I really do not know any PHP but I'd love to do one simple thing:

I access a php page from within a  and I'd like to have an image returned from another URL.

I came up with:

```<code><?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;
</code>```

And it works:

Avatar selection http://vercas.webuda.com/img.php?.png

(Reload the page a few times!)

答:
Just generate or read, then output the image using PHP.

```<code>...get image data from file or dynamically...
header('Content-type: image/png'); //or whatever MIME type

print $imgdata;
</code>```

Or check out this: http://php.net/manual/en/function.imagepng.php

Body:
I really do not know any PHP but I'd love to do one simple thing:

I access a php page from within a  and I'd like to have an image returned from another URL.

I came up with:

<?php
header('Content-Type: image/png');
readfile('i' . rand(1,3) . '.png');
exit;

And it works:

Avatar selection http://vercas.webuda.com/img.php?.png

(Reload the page a few times!)

Body:
Just generate or read, then output the image using PHP.

...get image data from file or dynamically...
header('Content-type: image/png'); //or whatever MIME type

print $imgdata;

Or check out this: http://php.net/manual/en/function.imagepng.php


问:
QMainWindow - wait until 'show' function is done
Is there a signal that tells when 'show' function finishes?

I have a problem in my code: If I write:

```<code>QMainWinObj.show();
QMainWinObj.someGuiFunc();
</code>```

the code doesn't work. But, if I write:

```<code>QMainWinObj.show();
sleep(3000);
QMainWinObj.someGuiFunc();
</code>```

It does.

So I think the problem is that 'show' dosn't finish its jub before I call 'someGuiFunc'. That's why I want to have some kind of a sign that 'show' is finished..

答:
Problem can decide without subclassing, just installing event filter like this:

```<code>class CWidgetIsPainting_EF : public QObject
{
    bool m_bIsPainted = false;
public:
    CWidgetIsPainting_EF( QObject * parent = 0 ) : QObject (parent) { }

    inline bool IsPainted() const { return m_bIsPainted; }
    inline void setIsPainted( bool bIsPainted ) { m_bIsPainted = bIsPainted; }

protected:
    bool eventFilter( QObject * obj, QEvent *event )
    {
        if (event->type() == QEvent::Paint)
        {
            m_bIsPainted = true;
            return true;
        };
        return QObject::eventFilter(obj, event);
    }
};
</code>```

...
...

```<code>CWidgetIsPainting_EF * pPaintingEF = new CWidgetIsPainting_EF( m_pWidget );
m_pWidget->installEventFilter( pPaintingEF );
</code>```

...
...

```<code>while ( !pPaintingEF->IsPainted() )
    QApplication::processEvents();
</code>```

Body:
Is there a signal that tells when 'show' function finishes?

I have a problem in my code: If I write:

QMainWinObj.show();
QMainWinObj.someGuiFunc();

the code doesn't work. But, if I write:

QMainWinObj.show();
sleep(3000);
QMainWinObj.someGuiFunc();

It does.

So I think the problem is that 'show' dosn't finish its jub before I call 'someGuiFunc'. That's why I want to have some kind of a sign that 'show' is finished..

Body:
Problem can decide without subclassing, just installing event filter like this:

class CWidgetIsPainting_EF : public QObject
{
    bool m_bIsPainted = false;
public:
    CWidgetIsPainting_EF( QObject * parent = 0 ) : QObject (parent) { }

    inline bool IsPainted() const { return m_bIsPainted; }
    inline void setIsPainted( bool bIsPainted ) { m_bIsPainted = bIsPainted; }

protected:
    bool eventFilter( QObject * obj, QEvent *event )
    {
        if (event->type() == QEvent::Paint)
        {
            m_bIsPainted = true;
            return true;
        };
        return QObject::eventFilter(obj, event);
    }
};

...
...

CWidgetIsPainting_EF * pPaintingEF = new CWidgetIsPainting_EF( m_pWidget );
m_pWidget->installEventFilter( pPaintingEF );

...
...

while ( !pPaintingEF->IsPainted() )
    QApplication::processEvents();


问:
Haxe for loop only uses last item
After some hours doing some testing I figured out that my map contains the correct values, but the loop that I am using only seems to be using the last added value in this map. Am I missing something obvious here?

The function that adds items to the map: (controls is the map variable)

```<code>public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
    {
        var controllerName = "Thumbstick"+mLocation;
        if(!controls.exists(controllerName)){

            createRecycledActor(mActorType, 0, 0, Script.FRONT);
            var lastActor = getLastCreatedActor();
            var myPosition = GetPosition(controllerName, lastActor);
            lastActor.setX(myPosition.x);
            lastActor.setY(myPosition.y);
            var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());
            var controlUnit = new ControlUnit(lastActor, myPos, -1);
            controls.set(controllerName, controlUnit);

            trace("added key: " + controllerName +" with value: "+ lastActor);
        } else {
            trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
        }
    }
</code>```

Upon creating 3 thumbsticks, the log states the following:

```<code>added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]
</code>```

When the screen is touched, it should loop through each item in my map, but it is using the last added item 3 times to check the distance with, rather then all 3 items once. Here is the Listener that is being called when the screen is touched:

```<code>addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
        {
            for (unit in controls){
                trace(lastDebugLine + "checking distance to " + unit.GetActor());
                if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
                    break;
                }
            }
        });
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!
</code>```

Upon touching the screen, the log states the following:

```<code>checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
</code>```

I am quite new to the Haxe language, so my guess is that I am missing something obvious, even after I have followed the Haxe API very closely. This is the example used from the Haxe API page:

```<code>var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
for (value in map4) {
    trace(value); // Monday \n Tuesday
}
</code>```

All explanations are welcome!

Added ControlUnit class:

```<code>import com.stencyl.models.Actor;

class ControlUnit
{
    static var actor;
    static var center;
    static var touchID;

    public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int)
    {
        actor = mActor;
        center = mPosition;
        touchID = mTouchID;
    }

    public function GetActor():Actor{
        return(actor);
    }

    public function GetCenter():Vector2{
        return(center);
    }

    public function GetTouchID():Int{
        return(touchID);
    }
}
</code>```

答: Are you sure that getLastCreatedActor() is returning a separate instance each time? If it's returning the same instance each time you will likely see what you're getting.

Title: Haxe for loop only uses last item

Body:
After some hours doing some testing I figured out that my map contains the correct values, but the loop that I am using only seems to be using the last added value in this map. Am I missing something obvious here?

The function that adds items to the map: (controls is the map variable)

public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
    {
        var controllerName = "Thumbstick"+mLocation;
        if(!controls.exists(controllerName)){

            createRecycledActor(mActorType, 0, 0, Script.FRONT);
            var lastActor = getLastCreatedActor();
            var myPosition = GetPosition(controllerName, lastActor);
            lastActor.setX(myPosition.x);
            lastActor.setY(myPosition.y);
            var myPos = new Vector2(lastActor.getXCenter(), lastActor.getYCenter());
            var controlUnit = new ControlUnit(lastActor, myPos, -1);
            controls.set(controllerName, controlUnit);

            trace("added key: " + controllerName +" with value: "+ lastActor);
        } else {
            trace("!!WARNING!! Control unit already exists in this position. Command ignored!");
        }
    }

Upon creating 3 thumbsticks, the log states the following:

added key: Thumbstick1 with value: [Actor 1,Thumbstick]
added key: Thumbstick2 with value: [Actor 2,Thumbstick]
added key: Thumbstick3 with value: [Actor 3,Thumbstick]

When the screen is touched, it should loop through each item in my map, but it is using the last added item 3 times to check the distance with, rather then all 3 items once. Here is the Listener that is being called when the screen is touched:

addMultiTouchStartListener(function(event:TouchEvent, list:Array<Dynamic>):Void
        {
            for (unit in controls){
                trace(lastDebugLine + "checking distance to " + unit.GetActor());
                if(GetDistance(unit.GetCenter(), touch.GetPosition()) < 64){
                    break;
                }
            }
        });
// used "touch.GetPosition()" instead of actuall code for easy reading. This is not causing any problems!

Upon touching the screen, the log states the following:

checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]
checking distance to [Actor 3,Thumbstick]

I am quite new to the Haxe language, so my guess is that I am missing something obvious, even after I have followed the Haxe API very closely. This is the example used from the Haxe API page:

var map4 = ["M"=>"Monday", "T"=>"Tuesday"];
for (value in map4) {
    trace(value); // Monday \n Tuesday
}

All explanations are welcome!

Added ControlUnit class:

import com.stencyl.models.Actor;

class ControlUnit
{
    static var actor;
    static var center;
    static var touchID;

    public function new(mActor:Actor, mPosition:Vector2, mTouchID:Int)
    {
        actor = mActor;
        center = mPosition;
        touchID = mTouchID;
    }

    public function GetActor():Actor{
        return(actor);
    }

    public function GetCenter():Vector2{
        return(center);
    }

    public function GetTouchID():Int{
        return(touchID);
    }
}


问:
Not able to get excel sheet using UDF with Selenium webdriver
I am new in UDF(User defined function) with hybrid framework. I have created the "ExcelUtils" class. In which I have written the code for read and write the excel sheet. Also, I have created the "Utils" class, in this after capturing the testcase name from excel I have created one function name getRowContains in these I am not able to get object excelSheet.

Utils class:

```<code>public class Utils {

    private static FirefoxDriver driver;

    public static WebDriver openBrowser(int iTestCaseRow){
        String sBrowserName;
        try{
            sBrowserName= ExcelUtils.getCellData(iTestCaseRow, Constant.Col_Browser);

            if(sBrowserName.equals("Mozilla")){
                System.setProperty("webdriver.gecko.driver", "/Users/ileadsynapse/Desktop/CT/geckodriver");
                DesiredCapabilities capabilities= DesiredCapabilities.firefox();
                capabilities.setCapability("marionette", true);
                driver = new FirefoxDriver(capabilities);
                Log.info("New driver instantiated");
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                Log.info("Implicit wait applied on the driver for 10 seconds");
                driver.get(Constant.URL);
                Log.info("Web application get launched");
            }
        }catch(Exception e){
            Log.error("Class Utils | Method OpenBrowser | Exception Desc:"+e.getMessage());
        }

        return driver;

    }

    public static String getTestCaseName(String sTestCase){
        String value= sTestCase;

        try {
            int posi= value.indexOf("@");
            value = value.substring(0, posi);
            posi= value.lastIndexOf(".");
            value= value.substring(posi+1);

            return value;

        } catch (Exception e) {
            // TODO: handle exception
             Log.error("Class Utils | Method getTestCaseName | Exception desc : "+e.getMessage());
             throw(e);
        }

    }

    public static int getRowContains(String sTestCaseName, int colNum){
                int i;
        try{
            int rowCount= excelSheet.

        }catch(Exception e){

        }
    }

}
</code>```

ExcelUtils:

```<code>public class ExcelUtils {

    private static XSSFWorkbook excelBook;
    private static XSSFSheet excelSheet;
    private static XSSFCell cell;
    private static XSSFRow row;

    //This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
    public static void setExcelFile(String Path, String SheetName) throws Exception{
        try{
            //Open excel file
            FileInputStream excelFile = new FileInputStream(Path);
            // Access the required test data sheet
            excelBook = new XSSFWorkbook(excelFile);
            excelSheet = excelBook.getSheet("Sheet1");
        }catch(Exception e){
            throw(e);
        }
    }

    //This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    public static String getCellData(int RowNum, int ColNum){
        try {
            cell = excelSheet.getRow(RowNum).getCell(ColNum);
            String cellData = cell.getStringCellValue();
            return cellData;
        } catch (Exception e) {
            return "";
        }
    }

    //This method is to write in the Excel cell, Row num and Col num are the parameters
    public static void setCellData(String Result, int RowNum, int ColNum) throws Exception{
        try{
            row = excelSheet.getRow(RowNum);
            cell = row.getCell(ColNum, row.RETURN_BLANK_AS_NULL);
            if(cell==null){
                cell = row.createCell(ColNum);
                cell.setCellValue(Result);
            }else{
                cell.setCellValue(Result);
            }

            // Constant variables Test Data path and Test Data file name
            FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData+ Constant.File_TestData);
            excelBook.write(fileOut);
            fileOut.flush();
            fileOut.close();

        }catch(Exception e){
            throw(e);
        }
    }

}
</code>```

Can any one please help to resolving it. I have referred this tutorial: http://toolsqa.com/selenium-webdriver/user-defined-functions/

答:
You haven't created excel object to access the excelsheet in Utils class.

declare private static XSSFSheet excelSheet; in utils class to get excelsheet object.

or

create ExcelUtils object in utils class to access all the elements of ExcelUtils

Body:
I am new in UDF(User defined function) with hybrid framework. I have created the "ExcelUtils" class. In which I have written the code for read and write the excel sheet. Also, I have created the "Utils" class, in this after capturing the testcase name from excel I have created one function name getRowContains in these I am not able to get object excelSheet.

Utils class:

public class Utils {

    private static FirefoxDriver driver;

    public static WebDriver openBrowser(int iTestCaseRow){
        String sBrowserName;
        try{
            sBrowserName= ExcelUtils.getCellData(iTestCaseRow, Constant.Col_Browser);

            if(sBrowserName.equals("Mozilla")){
                System.setProperty("webdriver.gecko.driver", "/Users/ileadsynapse/Desktop/CT/geckodriver");
                DesiredCapabilities capabilities= DesiredCapabilities.firefox();
                capabilities.setCapability("marionette", true);
                driver = new FirefoxDriver(capabilities);
                Log.info("New driver instantiated");
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                Log.info("Implicit wait applied on the driver for 10 seconds");
                driver.get(Constant.URL);
                Log.info("Web application get launched");
            }
        }catch(Exception e){
            Log.error("Class Utils | Method OpenBrowser | Exception Desc:"+e.getMessage());
        }

        return driver;

    }

    public static String getTestCaseName(String sTestCase){
        String value= sTestCase;

        try {
            int posi= value.indexOf("@");
            value = value.substring(0, posi);
            posi= value.lastIndexOf(".");
            value= value.substring(posi+1);

            return value;

        } catch (Exception e) {
            // TODO: handle exception
             Log.error("Class Utils | Method getTestCaseName | Exception desc : "+e.getMessage());
             throw(e);
        }

    }

    public static int getRowContains(String sTestCaseName, int colNum){
                int i;
        try{
            int rowCount= excelSheet.

        }catch(Exception e){

        }
    }

}

ExcelUtils:

public class ExcelUtils {

    private static XSSFWorkbook excelBook;
    private static XSSFSheet excelSheet;
    private static XSSFCell cell;
    private static XSSFRow row;

    //This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
    public static void setExcelFile(String Path, String SheetName) throws Exception{
        try{
            //Open excel file
            FileInputStream excelFile = new FileInputStream(Path);
            // Access the required test data sheet
            excelBook = new XSSFWorkbook(excelFile);
            excelSheet = excelBook.getSheet("Sheet1");
        }catch(Exception e){
            throw(e);
        }
    }

    //This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    public static String getCellData(int RowNum, int ColNum){
        try {
            cell = excelSheet.getRow(RowNum).getCell(ColNum);
            String cellData = cell.getStringCellValue();
            return cellData;
        } catch (Exception e) {
            return "";
        }
    }

    //This method is to write in the Excel cell, Row num and Col num are the parameters
    public static void setCellData(String Result, int RowNum, int ColNum) throws Exception{
        try{
            row = excelSheet.getRow(RowNum);
            cell = row.getCell(ColNum, row.RETURN_BLANK_AS_NULL);
            if(cell==null){
                cell = row.createCell(ColNum);
                cell.setCellValue(Result);
            }else{
                cell.setCellValue(Result);
            }

            // Constant variables Test Data path and Test Data file name
            FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData+ Constant.File_TestData);
            excelBook.write(fileOut);
            fileOut.flush();
            fileOut.close();

        }catch(Exception e){
            throw(e);
        }
    }

}

Can any one please help to resolving it. I have referred this tutorial: http://toolsqa.com/selenium-webdriver/user-defined-functions/


问:
How to setup "master" in a sub folder
In a Git repository, I need to change the path of the "master" branch to a subfolder instead of the root folder (default).

Example:

```<code>/ -> contains some config files, could be the "sources" branch

/master/ -> contains the files of the "master" branch
</code>```

Is this possible? How can I do it?

More precisions:

Usually I use Github pages feature, so I use the "worktree" feature to set the "gh-pages" branch in a subfolder. With Hugo, this is in "/public". See Hugo's documentation for details:

https://gohugo.io/tutorials/github-pages-blog/

Git's worktree feature:

https://git-scm.com/docs/git-worktree

However, on one of the server, generated files must be in /, in "master". So if I still want to have Hugo source files in the same repositories, I need to have them in an other folder and/or branch.

答:
After reading an other question of yours (it looks like you didn't find your answer in the previous one so you're asking again), it looks like you'd like to store different parts of your project in different branches (adding your Hugo configuration to an other branch).

Usually, a whole projet is splitted in different directories or repositories rather than branches. Why wouldn't you do that?

You could have a project with the following tree :

```<code>.
├── .git
├── conf
└── src
</code>```

Splitting in branches sounds unusual to me and probably isn't a so good idea.

Title: How to setup "master" in a sub folder

Body:
In a Git repository, I need to change the path of the "master" branch to a subfolder instead of the root folder (default).

Example:

/ -> contains some config files, could be the "sources" branch

/master/ -> contains the files of the "master" branch

Is this possible? How can I do it?

More precisions:

Usually I use Github pages feature, so I use the "worktree" feature to set the "gh-pages" branch in a subfolder. With Hugo, this is in "/public". See Hugo's documentation for details:

https://gohugo.io/tutorials/github-pages-blog/

Git's worktree feature:

https://git-scm.com/docs/git-worktree

However, on one of the server, generated files must be in /, in "master". So if I still want to have Hugo source files in the same repositories, I need to have them in an other folder and/or branch.

Body:
After reading an other question of yours (it looks like you didn't find your answer in the previous one so you're asking again), it looks like you'd like to store different parts of your project in different branches (adding your Hugo configuration to an other branch).

Usually, a whole projet is splitted in different directories or repositories rather than branches. Why wouldn't you do that?

You could have a project with the following tree :

.
├── .git
├── conf
└── src

Splitting in branches sounds unusual to me and probably isn't a so good idea.


问:
How to Upload Image to server using webservice in Android?
I have develop android app in which one UserProfile is there. I have send all details of user to server using Ksoap2. I also want to send image to server. But, i don't know how to send image to webservice using Ksoap2 in android. </p>

<p>I have take image from sdcard and convert it to ByteArray. Is there I have to send that parameter as ByteArray of image to webservice? I want to pass all details of user and image to webservice. How can I do this?  </p>

答: You can convert the your image into base64 string,and then handle them again to image at server side. but it getting a poor quality of image</p>

Body:
I have develop android app in which one UserProfile is there. I have send all details of user to server using Ksoap2. I also want to send image to server. But, i don't know how to send image to webservice using Ksoap2 in android.

I have take image from sdcard and convert it to ByteArray. Is there I have to send that parameter as ByteArray of image to webservice? I want to pass all details of user and image to webservice. How can I do this?