问:
Coalesce over Rows in MSSQL 2008,
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

```<code>TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null
</code>```

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

```<code>SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active
</code>```

Here would be the results:

```<code>TransDate  Id  Active
---------------------
1/18 6pm   5   0
</code>```

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

答:
This example should help, using analytical functions Max() OVER and Row_Number() OVER

```<code>create table tww( transdate datetime, id int, active bit)
insert tww select GETDATE(), 5, 1
insert tww select 1+GETDATE(), 5, 0
insert tww select 2+GETDATE(), 5, null
insert tww select 3+GETDATE(), 5, 1
insert tww select 4+GETDATE(), 5, 0
insert tww select 5+GETDATE(), 5, null

select maxDate as Transdate, id, Active
from (
    select *,
        max(transdate) over (partition by id) maxDate,
        ROW_NUMBER() over (partition by id
                order by case when active is not null then 0 else 1 end, transdate desc) rn
    from tww
) x
where rn=1
</code>```

Another option, quite expensive, would be doing it through XML. For educational purposes only

```<code>select
    ID = n.c.value('@id', 'int'),
    trandate = n.c.value('(data/transdate)[1]', 'datetime'),
    active = n.c.value('(data/active)[1]', 'bit')
from
(select xml=convert(xml,
    (select id [@id],
        (   select *
            from tww t
            where t.id=tww.id
            order by transdate desc
            for xml path('data'), type)
    from tww
    group by id
    for xml path('node'), root('root'), elements)
)) x cross apply xml.nodes('root/node') n(c)
</code>```

It works on the principle that the XML generated has each record as a child node of the ID. Null columns have been omitted, so the first column found using xpath (child/columnname) is the first non-null value similar to COALESCE.

Title: Coalesce over Rows in MSSQL 2008,

Body:
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active

Here would be the results:

TransDate  Id  Active
---------------------
1/18 6pm   5   0

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

Body:
This example should help, using analytical functions Max() OVER and Row_Number() OVER

create table tww( transdate datetime, id int, active bit)
insert tww select GETDATE(), 5, 1
insert tww select 1+GETDATE(), 5, 0
insert tww select 2+GETDATE(), 5, null
insert tww select 3+GETDATE(), 5, 1
insert tww select 4+GETDATE(), 5, 0
insert tww select 5+GETDATE(), 5, null

select maxDate as Transdate, id, Active
from (
    select *,
        max(transdate) over (partition by id) maxDate,
        ROW_NUMBER() over (partition by id
                order by case when active is not null then 0 else 1 end, transdate desc) rn
    from tww
) x
where rn=1

Another option, quite expensive, would be doing it through XML. For educational purposes only

select
    ID = n.c.value('@id', 'int'),
    trandate = n.c.value('(data/transdate)[1]', 'datetime'),
    active = n.c.value('(data/active)[1]', 'bit')
from
(select xml=convert(xml,
    (select id [@id],
        (   select *
            from tww t
            where t.id=tww.id
            order by transdate desc
            for xml path('data'), type)
    from tww
    group by id
    for xml path('node'), root('root'), elements)
)) x cross apply xml.nodes('root/node') n(c)

It works on the principle that the XML generated has each record as a child node of the ID. Null columns have been omitted, so the first column found using xpath (child/columnname) is the first non-null value similar to COALESCE.


来源: stackexchange

问:
How to land on a specific tab using vuejs
I want to go to a specific tab using vuejs and element-ui.
Here is the jsfiddle file. https://jsfiddle.net/hutsu1zf/10/

By default it lands to first tab. How can I land on any other tab while page load event. I am new to vuejs so even some hints would be appreciated.

答:
You can use the activeName attribute of tab.
Look at this fiddle:

https://jsfiddle.net/hutsu1zf/21/

Change activeName as per your requirement.

ContentLicense: CC BY-SA 3.0


问:
Array of hashes whose key is an array containing ranges
I need to map a number of IDs and ranges of IDs to single values. I would like to store the whole structure in one object.

Is the following a sensible way to do this? What is the best way to search the keys by a single integer value to return the corresponding value?

```<code>large array = [
   {[3110..3220, 10200, 43680] =>   'A0300'},
   {[5200, 7100..8990, 9100..9900] => 'B0400'},
   {[17110..18121, 20160, 2210..22290] => 'C0600'}
]
</code>```

答:
If the values were hardwired, one could use a case statement.

```<code>def look_it_up(n)
  case n
  when 7100..8990, 9100..9900, 5200
    'B0400'
  when 17110..18121, 22100..22290, 20160
    'C0600'
  when 3110..3220, 10200, 43680
    'A0300'
  else
    nil
  end
end

look_it_up 10200 #=> "A0300"
look_it_up  9135 #=> "B0400"
look_it_up 22100 #=> "C0600"
look_it_up  3079 #=> nil
</code>```

Assuming n is somewhat uniformly distributed, I have, for reasons of efficiency, ordered the when clauses by decreasing numbers of numbers included, and within each when clause, I put the ranges first and ordered those ranges by decreasing size.

If the values are not necessarily hardwired, one could use find/detect, as @mudasobwa has done.

If many lookups were to be performed, I would suggest constructing a hash whose keys are integers.

```<code>def init_arr(*args)
  args.each do |*a, value|
    a.each do |e|
      if e.is_a?(Range)
        e.each { |n| @h[n] = value }
      else
        @h[e] = value
      end
    end
  end
end
</code>```

Then for any n, @h[n] gives its value. For example,

```<code>@h = {}
init_arr [1..4, 8..10, 11, "cat"]
  @h #=> {1=>"cat", 2=>"cat", 3=>"cat", 4=>"cat", 8=>"cat", 9=>"cat",
     #    10=>"cat", 11=>"cat"}
init_arr [13..14, 7, "dog"]
  @h #=> {1=>"cat", 2=>"cat", 3=>"cat", 4=>"cat", 8=>"cat", 9=>"cat",
     #    10=>"cat", 11=>"cat", 13=>"dog", 14=>"dog", 7=>"dog"}
</code>```

Then (say),

```<code>@h[13]
  #=> "dog"
@h[11]
  #=> "cat"
@h[12]
  #=> nil
</code>```

Naturally, this assumes @h.size is manageable.

One could alternatively construct a look-up array, say @arr, which should be faster than using a hash (though it might consume much more memory than would a hash). @arr[n] would return the value for n or nil if there is no corresponding value. If some values were negative, or if the smallest n were quite large, one would instead write @arr[n+@offset], where @offset is the obvious value.

Body:
I need to map a number of IDs and ranges of IDs to single values. I would like to store the whole structure in one object.

Is the following a sensible way to do this? What is the best way to search the keys by a single integer value to return the corresponding value?

large array = [
   {[3110..3220, 10200, 43680] =>   'A0300'},
   {[5200, 7100..8990, 9100..9900] => 'B0400'},
   {[17110..18121, 20160, 2210..22290] => 'C0600'}
]

Body:
If the values were hardwired, one could use a case statement.

def look_it_up(n)
  case n
  when 7100..8990, 9100..9900, 5200
    'B0400'
  when 17110..18121, 22100..22290, 20160
    'C0600'
  when 3110..3220, 10200, 43680
    'A0300'
  else
    nil
  end
end

look_it_up 10200 #=> "A0300"
look_it_up  9135 #=> "B0400"
look_it_up 22100 #=> "C0600"
look_it_up  3079 #=> nil

Assuming n is somewhat uniformly distributed, I have, for reasons of efficiency, ordered the when clauses by decreasing numbers of numbers included, and within each when clause, I put the ranges first and ordered those ranges by decreasing size.

If the values are not necessarily hardwired, one could use find/detect, as @mudasobwa has done.

If many lookups were to be performed, I would suggest constructing a hash whose keys are integers.

def init_arr(*args)
  args.each do |*a, value|
    a.each do |e|
      if e.is_a?(Range)
        e.each { |n| @h[n] = value }
      else
        @h[e] = value
      end
    end
  end
end

Then for any n, @h[n] gives its value. For example,

@h = {}
init_arr [1..4, 8..10, 11, "cat"]
  @h #=> {1=>"cat", 2=>"cat", 3=>"cat", 4=>"cat", 8=>"cat", 9=>"cat",
     #    10=>"cat", 11=>"cat"}
init_arr [13..14, 7, "dog"]
  @h #=> {1=>"cat", 2=>"cat", 3=>"cat", 4=>"cat", 8=>"cat", 9=>"cat",
     #    10=>"cat", 11=>"cat", 13=>"dog", 14=>"dog", 7=>"dog"}

Then (say),

@h[13]
  #=> "dog"
@h[11]
  #=> "cat"
@h[12]
  #=> nil

Naturally, this assumes @h.size is manageable.

One could alternatively construct a look-up array, say @arr, which should be faster than using a hash (though it might consume much more memory than would a hash). @arr[n] would return the value for n or nil if there is no corresponding value. If some values were negative, or if the smallest n were quite large, one would instead write @arr[n+@offset], where @offset is the obvious value.


问:
Select distinct for one column
I have a compound primary key where the single parts are potentially random. They aren't in any particular order and one can be unique or they can be all the same.

I do not care which row I get. This is like "Just pick one from each group".

My table:

```<code>KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

</code>```

Now what I want is to get for each entry in colD one row, I do not care which one.

```<code>KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5
</code>```

答:
For rows that are unique by colD, you will have to decide which other column values will be discarded. Here, within the over clause I have use  partition by colD which provides the wanted uniqueness by that column, but the order by is arbitrary and you may want to change it to suit your needs.

```<code>select
       d.*
from (
      select
             t.*
           , row_number() over (partition by t.colD
                                order by t.KeyPart1,t.KeyPart2,t.KeyPart) as rn
      from yourtable t
     ) d
where d.rn = 1;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Select distinct for one column

Body:
I have a compound primary key where the single parts are potentially random. They aren't in any particular order and one can be unique or they can be all the same.

I do not care which row I get. This is like "Just pick one from each group".

My table:

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
11       22       39                 d2
12       21       39                 d2
12       22       39                 d3
13       21       38                 d3
13       22       38                 d5

Now what I want is to get for each entry in colD one row, I do not care which one.

KeyPart1 KeyPart2 KeyPart3 colA colB colD
11       21       39                 d1
12       21       39                 d2
12       22       39                 d3
13       22       38                 d5

Body:
For rows that are unique by colD, you will have to decide which other column values will be discarded. Here, within the over clause I have use  partition by colD which provides the wanted uniqueness by that column, but the order by is arbitrary and you may want to change it to suit your needs.

select
       d.*
from (
      select
             t.*
           , row_number() over (partition by t.colD
                                order by t.KeyPart1,t.KeyPart2,t.KeyPart) as rn
      from yourtable t
     ) d
where d.rn = 1;


问:
difference between stack segment and uninitialized data segment
I was trying to get a hand over the memory allocation in c.

According to the following link, the stack and the uninitialized data segment are different and the uninitialized data of the local function goes to the uninitialized data segment.

If that is the case then what is stored in the stack segment in case of a code with uninitialized local variables? Is it empty?

答:
I would not recommend reading "geeksforgeeks" tutorials. You have some misconceptions.

What they call "uninitialized data", the .bss segment, is in fact a store for variables of static storage duration that are zero-initialized. Including any such variable which is explicitly initialized to value zero.
An explanation of static storage duration and the different common segments, with examples, can be found here.

Only variables with static storage duration end up in .bss and .data. Local variables always end up on the stack, or in CPU registers, no matter if they are initialized or not.

(Please note that none of this is specified by the ISO C standard, but rather by industry de facto standards.)


问:
How to do that Mongodb aggregation in golang
I have a MongoDB collection like this:

```<code>{ "_id" : ObjectId("5a017ee061313781045889ea"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
{ "_id" : ObjectId("5a017f7b61313781045889eb"),  "device_id" : "1111",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : ObjectId("5a017fdd61313781045889ec"),  "device_id" : "12222",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : ObjectId("5a017ff561313781045889ed"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:42:13.658Z") }
</code>```

I want to distinct it by "device_id" AND sort it by "pubtime".

I know that Golang could use pipe to do it. But I don't know how to do it. What I tried:

```<code>o1 := bson.M{"_id": bson.M{"device_id": "$device_id"}}

o2 := bson.M{"pubtime": bson.M{"$last": "$pubtime"}}
o3 := bson.M{"$group": []bson.M{o1, o2}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
_ = pipe.All(&result)
fmt.Println(result)
</code>```

The result is empty.

It is ok in MongoDB:

```<code>db.collections.aggregate({"$group":
                        {"_id":{"device_id":"$device_id"},
                        "pubtime":{"$last": "$pubtime"} ,
                       "value":{"$last": "$value"} ,
                        }});
</code>```

答:
It can be done using $group and $first in mongodb aggregation pipeline

Mongodb shell query

```<code>db.collection.aggregate([
    {$group: {_id:{device_id:"$device_id"}, pubtime:{$first:"$pubtime"}}}
]);
</code>```

The result which we get after executing the above query in mongo shell

```<code>{ "_id" : { "device_id" : "12222" }, "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : { "device_id" : "1111" }, "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : { "device_id" : "1232213" }, "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
</code>```

Body:
I have a MongoDB collection like this:

{ "_id" : ObjectId("5a017ee061313781045889ea"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }
{ "_id" : ObjectId("5a017f7b61313781045889eb"),  "device_id" : "1111",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : ObjectId("5a017fdd61313781045889ec"),  "device_id" : "12222",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : ObjectId("5a017ff561313781045889ed"),  "device_id" : "1232213",   "value" : "23233", "pubtime" : ISODate("2017-11-07T09:42:13.658Z") }

I want to distinct it by "device_id" AND sort it by "pubtime".

I know that Golang could use pipe to do it. But I don't know how to do it. What I tried:

o1 := bson.M{"_id": bson.M{"device_id": "$device_id"}}

o2 := bson.M{"pubtime": bson.M{"$last": "$pubtime"}}
o3 := bson.M{"$group": []bson.M{o1, o2}}
pipe := c.Pipe([]bson.M{o3})
var result = []bson.M{}
_ = pipe.All(&result)
fmt.Println(result)

The result is empty.

It is ok in MongoDB:

db.collections.aggregate({"$group":
                        {"_id":{"device_id":"$device_id"},
                        "pubtime":{"$last": "$pubtime"} ,
                       "value":{"$last": "$value"} ,
                        }});

Body:
It can be done using $group and $first in mongodb aggregation pipeline

Mongodb shell query

db.collection.aggregate([
    {$group: {_id:{device_id:"$device_id"}, pubtime:{$first:"$pubtime"}}}
]);

The result which we get after executing the above query in mongo shell

{ "_id" : { "device_id" : "12222" }, "pubtime" : ISODate("2017-11-07T09:41:49.452Z") }
{ "_id" : { "device_id" : "1111" }, "pubtime" : ISODate("2017-11-07T09:40:11.204Z") }
{ "_id" : { "device_id" : "1232213" }, "pubtime" : ISODate("2017-11-07T09:37:37.006Z") }


问:
resolve xamarin android "path too long" without relocation
I have recently started getting the error ResolveLibraryProjectImports: PathTooLongException on my xamarin android project within xamarin.forms. When I look up online all solutions say to relocate the project. Is there any way to change the project properties or a way to remap that can help me avoid relocating the entire project?

Update:

Due the the bounty and since the question has come up below, here is why I am looking for an alternate solution to relocating:

Directory hierarchies are there for a reason. If not everyone would have the whole bunch of folders the root. They are designed to allow us to organize everything. Same is my case. I have organized all folders based cloud, codes, frameworks etc. Of all the frameworks I have worked with, I have never had relocate a project because of an internal requirement of the project. So, I do not see a reason I need to move a project out of all these folders (which also means out of cloud) and throw them in some location apart from the rest of the projects, just because the project asks for it.

答: I faced this issue too. Updating VS 2017 to 15.4.0 fixed it for me. Moving it closer to C:\ didn't change anything.</p>


问:
How do I convert an object to an array?
```<code><?php
   print_r($response->response->docs);
?>
</code>```

Outputs the following:

```<code>    Array
(
    [0] => Object
            (
                [_fields:private] => Array
                                    (
                                        [id]=>9093
                                        [name]=>zahir
                                    )
            Object
            (
                [_fields:private] => Array
                                    (
                                        [id]=>9094
                                        [name]=>hussain
                                    )..
            )
)
</code>```

How can I convert this object to an array?  I'd like to output the following:

```<code>Array
(
    [0]=>
    (
        [id]=>9093
        [name]=>zahir
    )
    [1]=>
    (
        [id]=>9094
        [name]=>hussain
    )...
)
</code>```

Is this possible?

答:
Try this:-</p>

```<code> <?php
  print_r(json_decode(json_encode($response->response->docs),true));
 ?>
</code>```

Title: How do I convert an object to an array?

Body:
<?php
   print_r($response->response->docs);
?>

Outputs the following:

    Array
(
    [0] => Object
            (
                [_fields:private] => Array
                                    (
                                        [id]=>9093
                                        [name]=>zahir
                                    )
            Object
            (
                [_fields:private] => Array
                                    (
                                        [id]=>9094
                                        [name]=>hussain
                                    )..
            )
)

How can I convert this object to an array?  I'd like to output the following:

Array
(
    [0]=>
    (
        [id]=>9093
        [name]=>zahir
    )
    [1]=>
    (
        [id]=>9094
        [name]=>hussain
    )...
)

Is this possible?

Body:
Try this:-

 <?php
  print_r(json_decode(json_encode($response->response->docs),true));
 ?>


问:
set permalink multiple pages visited
I am creating a web site with multiple pages, this is the url for example.

```<code>    www.example.com/gallery
</code>```

The gallery page is perfect but on visiting second page the url change to

```<code>www.example.com/second-page
</code>```

it should be

```<code>www.example.com/gallery/second-page
</code>```

in URl tab

on visiting another page
url turn to
    www.example.com/gallery/second-page/etc/etc/etc

please help me

how to set permalinks properly

答: Create a folder with the name of the gallery in your hosting. Then rename the gallery page with the index name and place it inside the gallery folder. Likewise with second-page pages also placed in the gallery folder.

Title: set permalink multiple pages visited

Body:
I am creating a web site with multiple pages, this is the url for example.

    www.example.com/gallery

The gallery page is perfect but on visiting second page the url change to

www.example.com/second-page

it should be

www.example.com/gallery/second-page

in URl tab

on visiting another page
url turn to
    www.example.com/gallery/second-page/etc/etc/etc

please help me

how to set permalinks properly


问:
Defining text for the legend of boxplot in ggplot2
How can I display a1 (random), a2 (random 2), a3 (random 3) in the legend instead of displaying the boxplot symbole?

The code I'm working with is

```<code>library(ggplot2)
library(reshape2)

B <- 25
datainit <- data.frame(v1 = 1:B, a1 = randl, a2 = rand2, a3 =  rand3)
idinit <- rep(c('a1', 'a2', 'a3'), each = B)
dat.minit <- melt(datainit, id.vars=idinit, measure.vars=c('a1', 'a2', 'a3'))
position <- c('a1', 'a2', 'a3')

plegend <- ggplot(dat.minit, aes(x = idinit, y = value, fill =  idinit)) +
 geom_boxplot(fill='white',color="darkred", show.legend = TRUE, width = 0.4) +
 stat_boxplot(geom = "errorbar", width = 0.5, color="darkred") +
 labs(x =   "methods", y = "values")  +
 scale_x_discrete(limits = position)  +
 scale_fill_discrete(name="some\nmethods",
    labels=c('random', 'random 2', 'random 3'))
</code>```

The data is like

```<code>  v1        a1        a2        a3
1   1 0.6715123 0.6851999 0.6858062
2   2 0.6123710 0.6330409 0.6317203
</code>```

答:
One option could be to use grid commands to dig into the structure of the legend, and replace the boxplot keys with a1, a2, a3.

```<code>library(ggplot)
library(grid)

plegend <- ggplot(dat.minit, aes(x = idinit, y = value, fill =  idinit)) +
  geom_boxplot(fill='white',color="darkred", show.legend = TRUE, width = 0.4)      +
  stat_boxplot(geom = "errorbar", width = 0.5, color="darkred") +
  labs(x =   "methods", y = "values")  +
  scale_x_discrete(limits = position)  +
  scale_fill_discrete(name="some\nmethods",
    labels=c('random', 'random 2', 'random 3'))

# Get the plot grob
g = ggplotGrob(plegend )

# Get the legend
leg = g$grobs[[which(g$layout$name == "guide-box")]]

# Get the positions of keys in the legend layout
pos = grep("key-[0-9]+-1-1", leg$grobs[[1]]$layout$name)

# Get the labels
label = c("a1", "a2", "a3")

# Replace the keys with the labels
for(i in seq_along(pos)) {
   leg$grobs[[1]]$grobs[[pos[i]]] = textGrob(label[i], gp = gpar(cex = .75))
   }

# Put the legend back into the plot
g$grobs[[which(g$layout$name == "guide-box")]] = leg

# Draw it
grid.newpage()
grid.draw(g)
</code>```

Body:
How can I display a1 (random), a2 (random 2), a3 (random 3) in the legend instead of displaying the boxplot symbole?

The code I'm working with is

library(ggplot2)
library(reshape2)

B <- 25
datainit <- data.frame(v1 = 1:B, a1 = randl, a2 = rand2, a3 =  rand3)
idinit <- rep(c('a1', 'a2', 'a3'), each = B)
dat.minit <- melt(datainit, id.vars=idinit, measure.vars=c('a1', 'a2', 'a3'))
position <- c('a1', 'a2', 'a3')

plegend <- ggplot(dat.minit, aes(x = idinit, y = value, fill =  idinit)) +
 geom_boxplot(fill='white',color="darkred", show.legend = TRUE, width = 0.4) +
 stat_boxplot(geom = "errorbar", width = 0.5, color="darkred") +
 labs(x =   "methods", y = "values")  +
 scale_x_discrete(limits = position)  +
 scale_fill_discrete(name="some\nmethods",
    labels=c('random', 'random 2', 'random 3'))

The data is like

  v1        a1        a2        a3
1   1 0.6715123 0.6851999 0.6858062
2   2 0.6123710 0.6330409 0.6317203

Body:
One option could be to use grid commands to dig into the structure of the legend, and replace the boxplot keys with a1, a2, a3.

library(ggplot)
library(grid)

plegend <- ggplot(dat.minit, aes(x = idinit, y = value, fill =  idinit)) +
  geom_boxplot(fill='white',color="darkred", show.legend = TRUE, width = 0.4)      +
  stat_boxplot(geom = "errorbar", width = 0.5, color="darkred") +
  labs(x =   "methods", y = "values")  +
  scale_x_discrete(limits = position)  +
  scale_fill_discrete(name="some\nmethods",
    labels=c('random', 'random 2', 'random 3'))

# Get the plot grob
g = ggplotGrob(plegend )

# Get the legend
leg = g$grobs[[which(g$layout$name == "guide-box")]]

# Get the positions of keys in the legend layout
pos = grep("key-[0-9]+-1-1", leg$grobs[[1]]$layout$name)

# Get the labels
label = c("a1", "a2", "a3")

# Replace the keys with the labels
for(i in seq_along(pos)) {
   leg$grobs[[1]]$grobs[[pos[i]]] = textGrob(label[i], gp = gpar(cex = .75))
   }

# Put the legend back into the plot
g$grobs[[which(g$layout$name == "guide-box")]] = leg

# Draw it
grid.newpage()
grid.draw(g)


问:
Understanding the delegates in UITableView and UITableViewController
I am learning how to use the UITableView and UITableViewController in the iOS and I think I may have confused myself. I have created a simple TableView and I have 2 sections.  Nothing complicated.

I have the following defined and it builds fine:

```<code>-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    // Section is going to be either 0 or 1, high or low
    if (section == 0) {
        return 1;
    }
    else {
        return 2;
    }
}
</code>```

However what I don't understand is the definitions of the methods.  Both methods have to return an integer so I understand the starting (NSInteger).  The numberOfRowsInSection starts with tableView:(UITableView *)tableView and I don't understand why?

I'm am new to programming the iOS so be gentle :-)  All help greatly appreciated.

Mike

答: This is Apple's naming convention for delegate and data source methods. numberOfSectionsInTableView: has no arguments other than the table view, so that argument is added at the end. tableView:numberOfRowsInSection: takes another argument, the index of the section in question. Apple has decided that, when there are other arguments, the calling object should go first, and the arguments come after that.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am learning how to use the UITableView and UITableViewController in the iOS and I think I may have confused myself. I have created a simple TableView and I have 2 sections.  Nothing complicated.

I have the following defined and it builds fine:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    // Section is going to be either 0 or 1, high or low
    if (section == 0) {
        return 1;
    }
    else {
        return 2;
    }
}

However what I don't understand is the definitions of the methods.  Both methods have to return an integer so I understand the starting (NSInteger).  The numberOfRowsInSection starts with tableView:(UITableView *)tableView and I don't understand why?

I'm am new to programming the iOS so be gentle :-)  All help greatly appreciated.

Mike


问:
Try to validate a xml-file by more than one xsd-file
I try to validate a xml-file aganist two xsd-files, but I get every time an error on validation. I use the "xml copy editor" to validate. I do not know, if this is a problem of my xml/xsd or the program (which maybe can not validate aganist multiple xsd!?). Can anybody help?

I try to follow the example on page.

XML-file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<PostAdress xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\XML\XSD1.xsd">
    <Meta>
        <Name>Hallo</Name>
    </Meta>
</PostAdress>
</code>```

XSD1.xsd:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:xs2="http://aa.bb.cc">
    <xs:import namespace="http://aa.bb.cc" schemaLocation="D:\XML\XSD0.xsd" />
    <xs:element name="PostAdress">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Meta" type="xs2:Adress" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

XSD0.xsd:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://aa.bb.cc">
  <xs:element name="Adress">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Name" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

PS: I get the error: "Error at line 7: column 96: type 'http://aa.bb.cc:Adress' not found." I think the program means Line 7 in XSD1.xsd.

PS2: I try also to run a small VB.net-App for validation. I get nearly the same error message. So, I think there is a problem with the files.

答:
I tried it also with notepad++, with the same result.  So, I think it is maybe not problem of two xsd-files. So I put all the nessesary content in one xsd and....same error. After that I look a little bit closer to my xsd-file and I found the mistake. I had this structure:

Instance.xml >> XSD1.xsd >> XSD0.xsd
Usage "PostAdress" >> Definition of "PostAdress" by using of "Adress" as type >> Definition of "Adress"

The wrong line was by the definition of the "Adress". I wrote...

```<code>  <xs:element name="Adress">
    <xs:complexType>
      ...
    </xs:complexType>
  </xs:element>
</code>```

But correct is:

```<code>   <xs:complexType name="Adress">
      <xs:sequence>
      ...
      </xs:sequence>
   </xs:complexType>
</code>```

So my files look like:

XSD1.xsd:

```<code><xs:element name="PostAdress">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Meta" type="andererNs:Adress" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</code>```

And XSD0.xsd:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://aa.bb.cc">

   <xs:complexType name="Adress">
      <xs:sequence>
        <xs:element name="Name" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
   </xs:complexType>

</xs:schema>
</code>```

At the end, it is possible to validate with more than one xsd-file with the program "xml copy editor" (or notepad++). Also, relative file names are good enough, if the files are in the same folder.

Thanks to the helpers.

Body:
I try to validate a xml-file aganist two xsd-files, but I get every time an error on validation. I use the "xml copy editor" to validate. I do not know, if this is a problem of my xml/xsd or the program (which maybe can not validate aganist multiple xsd!?). Can anybody help?

I try to follow the example on page.

XML-file:

<?xml version="1.0" encoding="UTF-8"?>
<PostAdress xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\XML\XSD1.xsd">
    <Meta>
        <Name>Hallo</Name>
    </Meta>
</PostAdress>

XSD1.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:xs2="http://aa.bb.cc">
    <xs:import namespace="http://aa.bb.cc" schemaLocation="D:\XML\XSD0.xsd" />
    <xs:element name="PostAdress">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Meta" type="xs2:Adress" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSD0.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://aa.bb.cc">
  <xs:element name="Adress">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Name" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

PS: I get the error: "Error at line 7: column 96: type 'http://aa.bb.cc:Adress' not found." I think the program means Line 7 in XSD1.xsd.

PS2: I try also to run a small VB.net-App for validation. I get nearly the same error message. So, I think there is a problem with the files.

Body:
I tried it also with notepad++, with the same result.  So, I think it is maybe not problem of two xsd-files. So I put all the nessesary content in one xsd and....same error. After that I look a little bit closer to my xsd-file and I found the mistake. I had this structure:

Instance.xml >> XSD1.xsd >> XSD0.xsd
Usage "PostAdress" >> Definition of "PostAdress" by using of "Adress" as type >> Definition of "Adress"

The wrong line was by the definition of the "Adress". I wrote...

  <xs:element name="Adress">
    <xs:complexType>
      ...
    </xs:complexType>
  </xs:element>

But correct is:

   <xs:complexType name="Adress">
      <xs:sequence>
      ...
      </xs:sequence>
   </xs:complexType>

So my files look like:

XSD1.xsd:

<xs:element name="PostAdress">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Meta" type="andererNs:Adress" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

And XSD0.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://aa.bb.cc">

   <xs:complexType name="Adress">
      <xs:sequence>
        <xs:element name="Name" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
   </xs:complexType>

</xs:schema>

At the end, it is possible to validate with more than one xsd-file with the program "xml copy editor" (or notepad++). Also, relative file names are good enough, if the files are in the same folder.

Thanks to the helpers.


问:
Fetching data from a ReST micro service in angular 2 application
I am trying to fetch data from a ReST Microservice which gives me data ( username and password)
in JSON format ( [{"username":"Mark","password":"mark123"}] ) through its endpoint
"http://localhost:8080/checkUsers"

I created a simple application in angular 2 with login and home components which includes .html and .ts files.

I created a routing.ts file which routes my components.

I also included a header.component.ts and header.component.html which implements the menu bar of my application.

Below shown is my code

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { routing } from "./app.routing";
import { LoginComponent } from './login/login.component';
import { RouterModule, Routes} from '@angular/router';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [ AppComponent, HeaderComponent, LoginComponent,
HomeComponent],

  imports: [ RouterModule, BrowserModule, routing  ],

  providers: [],

  bootstrap: [AppComponent]
 })
 export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
 })
export class AppComponent {
  title = '';
}
</code>```

app.component.html

```<code> <div style="text-align:justify-all;">
  <h1>
    {{title}}
  </h1>

 <div class="container">
 <router-outlet></router-outlet>
 </div>
</code>```

app.routing.ts

```<code>import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent },
];
export const routing = RouterModule.forRoot(APP_ROUTES);
</code>```

header.component.html

```<code> <div class="row">
 <div class="col-xs-12"><ul class="nav nav-pills">
    <li routerLinkActive="active"><a [routerLink]="['/home']">
 <strong>Home</strong></a></li>
    <li><a [routerLink]="['/login']"><strong>Logout</strong></a></li>
    </ul></div>
 </div>
</code>```

header.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',

})
export class HeaderComponent {
 }
</code>```

Here is my login component

login.component.html

```<code>  <div class="container formWidth" style="text-align:left;">
    <h1> eSpace Login</h1>
<br/>
   <form (submit)="loginUser($event)">
    <div class="form-group">
      <label for="Username">Username:</label>
      <input type="Username"  id="Username" placeholder="Enter Username"
name="Username">
    </div>
    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password"  id="pwd" placeholder="Enter password"
name="pwd">
    </div>

    <br/>
       <button type="submit" class="btn btn-default">Submit</button>
  </form>

</div>
</code>```

login.component.ts

```<code>import { Component, OnInit } from '@angular/core';
 import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {

  constructor(private router:Router ) {
   }
  ngOnInit() {
  }

loginUser(e){
e.preventDefault();
 console.log(e);
    var username=e.target.elements[0].value;
    var password=e.target.elements[1].value;

    if (username == 'heena' && password == 'mille' )
    this.router.navigate(['home']);
}
}
</code>```

Here is my home component

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';

 @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
</code>```

home.component.html

```<code>      <app-header></app-header>
    <hr>
<p> <strong> Welcome to eSpace Home </strong></p>

<img src="/../../assets/i9.jpeg" class="img-rounded" alt="home" height="400" width="1150">
</code>```

can anybody please please guide through the process of fetching data from the ReST micro service in my angular 2 application.

答: You must add a service to your app which would be responsible for providing the required data to your component. Your service will use $http object to call the microservices and provide the data using observables which would be accessible in your component. You also need to inject the service to your component.

Body:
I am trying to fetch data from a ReST Microservice which gives me data ( username and password)
in JSON format ( [{"username":"Mark","password":"mark123"}] ) through its endpoint
"http://localhost:8080/checkUsers"

I created a simple application in angular 2 with login and home components which includes .html and .ts files.

I created a routing.ts file which routes my components.

I also included a header.component.ts and header.component.html which implements the menu bar of my application.

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { routing } from "./app.routing";
import { LoginComponent } from './login/login.component';
import { RouterModule, Routes} from '@angular/router';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [ AppComponent, HeaderComponent, LoginComponent,
HomeComponent],

  imports: [ RouterModule, BrowserModule, routing  ],

  providers: [],

  bootstrap: [AppComponent]
 })
 export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
 })
export class AppComponent {
  title = '';
}

app.component.html

    {{title}}

 <router-outlet></router-outlet>

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent },
];
export const routing = RouterModule.forRoot(APP_ROUTES);

header.component.html

 Home

Logout

header.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',

})
export class HeaderComponent {
 }

Here is my login component

login.component.html

 eSpace Login

   <form (submit)="loginUser($event)">

      Username:
      <input type="Username"  id="Username" placeholder="Enter Username"
name="Username">

      Password:
      <input type="password"  id="pwd" placeholder="Enter password"
name="pwd">

       <button type="submit" class="btn btn-default">Submit</button>
  </form>

login.component.ts

import { Component, OnInit } from '@angular/core';
 import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {

  constructor(private router:Router ) {
   }
  ngOnInit() {
  }

loginUser(e){
e.preventDefault();
 console.log(e);
    var username=e.target.elements[0].value;
    var password=e.target.elements[1].value;

    if (username == 'heena' && password == 'mille' )
    this.router.navigate(['home']);
}
}

Here is my home component

home.component.ts

import { Component, OnInit } from '@angular/core';

 @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

home.component.html

      <app-header></app-header>

  Welcome to eSpace Home

can anybody please please guide through the process of fetching data from the ReST micro service in my angular 2 application.


问:
How to click on webtable specific row
I have this code that clicks on first row and column one just fine.

```<code>Set oExcptnDetail = Description.Create
oExcptnDetail("micclass").value = "WebElement"
oExcptnDetail("html tag").value = "TD"
Set chobj=Browser("").Page("").WebTable("Code").ChildObjects(oExcptnDetail)
chobj(0).Click
</code>```

How can I click on a specific row using above code?

I used childitem that did not work.

```<code>set objLink = Browser("bb").Page("bb").WebTable("Name_2").ChildItem(4, 1, "WebElement",0)
</code>```

Update 1

I tried the below code. It did not click row 3 col 1.

```<code>Set desc = Description.Create
desc("html tag").value = "TR"
Set rows = table.ChildObjects(desc)
desc("html tag").value = "TD"
Set cells = rows(3).ChildObjects(desc)
Set TableCell = cells(1)
Browser("").Page("").WebTable(TableCell).Click
</code>```

答:
UFT's ChildItem function returns elements contained within cells, this means that it won't return the TD that is the cell, only its descendants.

In order to get the cell itself you should use WebTable.Cell, this is a relatively new functionality in UFT and you may not have it. If you don't you should be able to write a helper function like this (note I'm writing this without checking it out, it may need additional work and error handling):

```<code>Function TableCell(table, nRow, nCol)
    Set desc = Description.Create

    desc("html tag").value = "TR" ' Or "T[RH]" to capture TH too
    Set rows = table.ChildObjects(desc)

    desc("html tag").value = "TD"
    Set cells = rows(nRow).ChildObjects(desc)

    Set TableCell = cells(nCol)
End Function
</code>```

Then you can use RegisterUserFunc to use it as WebTable.Cell if you wish.

Then you can use it thus:

```<code>TableCell(Browser("").Page("").WebTable("Code"), 4, 1).Click
</code>```

Or if you used RegisterUserFunc to register it as Cell:

```<code>Browser("").Page("").WebTable("Code").Cell(4, 1).Click
</code>```

Title: How to click on webtable specific row

Body:
I have this code that clicks on first row and column one just fine.

Set oExcptnDetail = Description.Create
oExcptnDetail("micclass").value = "WebElement"
oExcptnDetail("html tag").value = "TD"
Set chobj=Browser("").Page("").WebTable("Code").ChildObjects(oExcptnDetail)
chobj(0).Click

How can I click on a specific row using above code?

I used childitem that did not work.

set objLink = Browser("bb").Page("bb").WebTable("Name_2").ChildItem(4, 1, "WebElement",0)

Update 1

I tried the below code. It did not click row 3 col 1.

Set desc = Description.Create
desc("html tag").value = "TR"
Set rows = table.ChildObjects(desc)
desc("html tag").value = "TD"
Set cells = rows(3).ChildObjects(desc)
Set TableCell = cells(1)
Browser("").Page("").WebTable(TableCell).Click

Body:
UFT's ChildItem function returns elements contained within cells, this means that it won't return the TD that is the cell, only its descendants.

In order to get the cell itself you should use WebTable.Cell, this is a relatively new functionality in UFT and you may not have it. If you don't you should be able to write a helper function like this (note I'm writing this without checking it out, it may need additional work and error handling):

Function TableCell(table, nRow, nCol)
    Set desc = Description.Create

    desc("html tag").value = "TR" ' Or "T[RH]" to capture TH too
    Set rows = table.ChildObjects(desc)

    desc("html tag").value = "TD"
    Set cells = rows(nRow).ChildObjects(desc)

    Set TableCell = cells(nCol)
End Function

Then you can use RegisterUserFunc to use it as WebTable.Cell if you wish.

Then you can use it thus:

TableCell(Browser("").Page("").WebTable("Code"), 4, 1).Click

Or if you used RegisterUserFunc to register it as Cell:

Browser("").Page("").WebTable("Code").Cell(4, 1).Click


问:
How can I remove special characters from a list of elements in python?
I have a list of elements containing special characters.  I want to convert the list to only alphanumeric characters.  No special characters.
my_list = ["on@3", "two#", "thre%e"]

my expected output is,

```<code>out_list = ["one","two","three"]
</code>```

I cannot simply apply strip() to these items, please help.

答:
Using two for loops

```<code>l = ['@','#','%']
out_list = []
for x in my_list:
    for y in l:
        if y in x:
            x = x.replace(y,'')
            out_list.append(x)
            break
</code>```

Using list comprehension

```<code>out_list = [ x.replace(y,'')  for x in my_list for y in l if y in x ]
</code>```

Assuming 3 in on@3 is a typo, the output will be on@3 and not one as expected

Body:
I have a list of elements containing special characters.  I want to convert the list to only alphanumeric characters.  No special characters.
my_list = ["on@3", "two#", "thre%e"]

my expected output is,

out_list = ["one","two","three"]

I cannot simply apply strip() to these items, please help.

Body:
Using two for loops

l = ['@','#','%']
out_list = []
for x in my_list:
    for y in l:
        if y in x:
            x = x.replace(y,'')
            out_list.append(x)
            break

Using list comprehension

out_list = [ x.replace(y,'')  for x in my_list for y in l if y in x ]

Assuming 3 in on@3 is a typo, the output will be on@3 and not one as expected


问:
Array of function pointers as a member of a C struct
I have built the following C example trying to simulate simplistic generic driver code which can be used in small ARM micro-controllers:

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

typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

typedef struct {
        generic_func_t init;
        generic_func_t open;
        generic_func_t read;
        generic_func_t write;
        generic_func_t close;
        generic_func_t exit;
} driver_t;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_open(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_read(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_read 0x%x\n", x);
}

void USB_write(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_write 0x%x\n", x);
}

void USB_close(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

void USB_exit(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

typedef struct driver_t USB_driver;

#if 1
        USB_driver.init = &USB_init;
        USB_driver.open = &USB_open;
        USB_driver.read  = &USB_read;
        USB_driver.write = &USB_write;
        USB_driver.close = &USB_close;
        USB_driver.exit  = &USB_exit;
#endif

#if 1
void main(void) {}
#endif
#if 0
void main(void) {
        USB_driver.init(0x01);
        USB_driver.open(0x02);
        USB_driver.read(0x03);
        USB_driver.write(0x04);
        USB_driver.close(0x05);
        USB_driver.exit(0x06);
}
#endif
</code>```

The following error appears:

```<code>[user@localhost fn-ptr]$ emacs fn-ptr.c

(emacs:4983): Gtk-WARNING **: Allocating size to Emacs 0xdb4270 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate?
[user@localhost fn-ptr]$ gcc fn-ptr.c
fn-ptr.c:78:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.init = &USB_init;
           ^
fn-ptr.c:79:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.open = &USB_open;
           ^
fn-ptr.c:80:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.read  = &USB_read;
           ^
fn-ptr.c:81:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.write = &USB_write;
           ^
fn-ptr.c:82:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.close = &USB_close;
           ^
fn-ptr.c:83:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.exit  = &USB_exit;
           ^
[user@localhost fn-ptr]$
</code>```

The question here is: what should I do to make this code to work, since the following single function pointer example, upon which this code is built, works perfectly:

```<code>typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

generic_func_t init;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

init = &USB_init;
</code>```

答:
First of all, USB_driver is a type, not a variable. You need to have a variable of this type first to access the members (for example, initialize the values of the members).

That said, at a first look, it seems

```<code>    USB_driver.init = &USB_init;
    USB_driver.open = &USB_open;
    USB_driver.read  = &USB_read;
    USB_driver.write = &USB_write;
    USB_driver.close = &USB_close;
    USB_driver.exit  = &USB_exit;
</code>```

these statements, the assignment statements, resides in file scope. That is not allowed. Assignment operation (different than initialization) is allowed only in block scope.

You need them to have them in block scope, inside some function, main(), probably.

Body:
I have built the following C example trying to simulate simplistic generic driver code which can be used in small ARM micro-controllers:

#include <stdio.h>
#include <string.h>

typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

typedef struct {
        generic_func_t init;
        generic_func_t open;
        generic_func_t read;
        generic_func_t write;
        generic_func_t close;
        generic_func_t exit;
} driver_t;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_open(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

void USB_read(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_read 0x%x\n", x);
}

void USB_write(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_write 0x%x\n", x);
}

void USB_close(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

void USB_exit(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_close 0x%x\n", x);
}

typedef struct driver_t USB_driver;

#if 1
        USB_driver.init = &USB_init;
        USB_driver.open = &USB_open;
        USB_driver.read  = &USB_read;
        USB_driver.write = &USB_write;
        USB_driver.close = &USB_close;
        USB_driver.exit  = &USB_exit;
#endif

#if 1
void main(void) {}
#endif
#if 0
void main(void) {
        USB_driver.init(0x01);
        USB_driver.open(0x02);
        USB_driver.read(0x03);
        USB_driver.write(0x04);
        USB_driver.close(0x05);
        USB_driver.exit(0x06);
}
#endif

The following error appears:

[user@localhost fn-ptr]$ emacs fn-ptr.c

(emacs:4983): Gtk-WARNING **: Allocating size to Emacs 0xdb4270 without calling gtk_widget_get_preferred_width/height(). How does the code know the size to allocate?
[user@localhost fn-ptr]$ gcc fn-ptr.c
fn-ptr.c:78:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.init = &USB_init;
           ^
fn-ptr.c:79:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.open = &USB_open;
           ^
fn-ptr.c:80:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.read  = &USB_read;
           ^
fn-ptr.c:81:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.write = &USB_write;
           ^
fn-ptr.c:82:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.close = &USB_close;
           ^
fn-ptr.c:83:11: error: expected identifier or ‘(’ before ‘.’ token
 USB_driver.exit  = &USB_exit;
           ^
[user@localhost fn-ptr]$

The question here is: what should I do to make this code to work, since the following single function pointer example, upon which this code is built, works perfectly:

typedef unsigned char uint8_t;
typedef void (*generic_func_t)(uint8_t);

generic_func_t init;

void USB_init(uint8_t x)
{
        /* here body of this f-n */
        printf("USB_open 0x%x\n", x);
}

init = &USB_init;

Body:
First of all, USB_driver is a type, not a variable. You need to have a variable of this type first to access the members (for example, initialize the values of the members).

That said, at a first look, it seems

    USB_driver.init = &USB_init;
    USB_driver.open = &USB_open;
    USB_driver.read  = &USB_read;
    USB_driver.write = &USB_write;
    USB_driver.close = &USB_close;
    USB_driver.exit  = &USB_exit;

these statements, the assignment statements, resides in file scope. That is not allowed. Assignment operation (different than initialization) is allowed only in block scope.

You need them to have them in block scope, inside some function, main(), probably.


问:
Create a portlet inside of a custom theme in liferay 7
I know in Liferay it is possible to embed a predefined Portlet in a theme's .ftl file by using following code:

```<code><@liferay_portlet["runtime"]
    portletProviderAction=ACTION
    portletProviderClassName="CLASS_NAME"
/>
</code>```

But I'd like to create a new portlet (with all its Java classes) inside of a theme. For example, a sample skeleton of my theme project can be found in the below.

My question is, In Liferay 7 is it possible to have a complete portlet inside of a theme and end-users access to that portlet? (end-users should be able to add it to wherever they want by using add menu from the right side the admin page).

If yes, where should I place my Java code? How should I deploy and build it? Is there any example of it?

One of the benefits of it is having a theme with many different suitable custom theme in one package and you can share it with others.

答:
I keep myself away from themes these days, but understand that they're largely deployed as webapps, WAR files (which Liferay transforms to WAB bundles internally). While you can have portlets in WAR files, Liferay 7 and DXP work well with many smaller plugins, and you're a lot more flexible by packaging portlets in OSGi bundles.

Unless you implement your portlet in a technology that still requires WAR packaging, you're not gaining a lot from packaging all in the same WAR file. Updating the portlet would cause you to also always having to update the theme and everything else packaged with it - and you can do a lot better with this generation of Liferay.

My advice is to package a portlet as a portlet, and a theme as a theme. The number of plugins doesn't matter any more, as it did in earlier versions. In fact, there are now more than 500 modules (plugins) in the default installation of Liferay DXP. There's no need to minify the number of plugins and no benefit, apart from the number of files you're installing. And that's the last thing I'd worry about.

Body:
I know in Liferay it is possible to embed a predefined Portlet in a theme's .ftl file by using following code:

<@liferay_portlet["runtime"]
    portletProviderAction=ACTION
    portletProviderClassName="CLASS_NAME"
/>

But I'd like to create a new portlet (with all its Java classes) inside of a theme. For example, a sample skeleton of my theme project can be found in the below.

My question is, In Liferay 7 is it possible to have a complete portlet inside of a theme and end-users access to that portlet? (end-users should be able to add it to wherever they want by using add menu from the right side the admin page).

If yes, where should I place my Java code? How should I deploy and build it? Is there any example of it?

One of the benefits of it is having a theme with many different suitable custom theme in one package and you can share it with others.


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
Well, as a side note, it depends on what x is. If x is a primitive in Java, you have to call .toString() using one of its wrappers, like

Integer.toString(x)

I would say using toString() is generally better, because x + "", in at least Java, is saying you want to append the two Strings together.

Like in this example:

```<code> public static void main(String[] args)
 {
   int x = 3;
   String s = x + "";
 }
</code>```

That ends up, in bytecode, as :

```<code>public static void main(java.lang.String[]);
  Code:
   0:   iconst_3
   1:   istore_1
   2:   new #2; //class java/lang/StringBuilder
   5:   dup
   6:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   9:   iload_1
   10:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   13:  ldc #5; //String
   15:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   18:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   21:  astore_2
   22:  return
</code>```

So it has to create a StringBuilder to append  "" and the String value of x together. While the efficiency lost isn't that much, it isn't too much to just use the toString function.

Compare with using toString:

```<code> public static void main(String[] args)
 {
   int x = 3;
   String s = Integer.toString(x);
 }
</code>```

Which ends up as:

```<code>public static void main(java.lang.String[]);
Code:
 0: iconst_3
 1: istore_1
 2: iload_1
 3: invokestatic    #2; //Method java/lang/Integer.toString:(I)Ljava/lang/String;
 6: astore_2
 7: return
</code>```

And although it might just be my opinion, using .toString reflects what you actually want -- you want the String value of x, while using x + "" is kind of a hack and says -- I want the String value of x concatenated with "".

Side Note:
I can't speak on the intermediate bytecode C# would emit, but I imagine something similar to this. Plus, with C#, you can just call .ToString() on your value types just as easily as reference types, so I think my advice would apply the same.

Body:
Well, as a side note, it depends on what x is. If x is a primitive in Java, you have to call .toString() using one of its wrappers, like

Integer.toString(x)

I would say using toString() is generally better, because x + "", in at least Java, is saying you want to append the two Strings together.

Like in this example:

 public static void main(String[] args)
 {
   int x = 3;
   String s = x + "";
 }

That ends up, in bytecode, as :

public static void main(java.lang.String[]);
  Code:
   0:   iconst_3
   1:   istore_1
   2:   new #2; //class java/lang/StringBuilder
   5:   dup
   6:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   9:   iload_1
   10:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   13:  ldc #5; //String
   15:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   18:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   21:  astore_2
   22:  return

So it has to create a StringBuilder to append  "" and the String value of x together. While the efficiency lost isn't that much, it isn't too much to just use the toString function.

Compare with using toString:

 public static void main(String[] args)
 {
   int x = 3;
   String s = Integer.toString(x);
 }

Which ends up as:

public static void main(java.lang.String[]);
Code:
 0: iconst_3
 1: istore_1
 2: iload_1
 3: invokestatic    #2; //Method java/lang/Integer.toString:(I)Ljava/lang/String;
 6: astore_2
 7: return

And although it might just be my opinion, using .toString reflects what you actually want -- you want the String value of x, while using x + "" is kind of a hack and says -- I want the String value of x concatenated with "".

Side Note:
I can't speak on the intermediate bytecode C# would emit, but I imagine something similar to this. Plus, with C#, you can just call .ToString() on your value types just as easily as reference types, so I think my advice would apply the same.


答:
You must declare a variable of type USB_driver like

```<code>void main(void) {
    USB_driver dr
    dr.init(0x01);
    dr.open(0x02);
    dr.read(0x03);
    dr.write(0x04);
    dr.close(0x05);
    dr.exit(0x06);
}
</code>```

Try with that

Title: Array of function pointers as a member of a C struct

Body:
You must declare a variable of type USB_driver like

void main(void) {
    USB_driver dr
    dr.init(0x01);
    dr.open(0x02);
    dr.read(0x03);
    dr.write(0x04);
    dr.close(0x05);
    dr.exit(0x06);
}

Try with that


问:
Is it possible to write to a DynamoDB Global Secondary Index?
For example, would it possible to put or update an item using the Global Secondary Index?</p>

答:
The simple answer is no - it's not possible to put or update an item using an index.

But this is a really interesting question and I think it helps to think about why it is not possible. First, an index is a projection of the source data, and the index is not necessarily a bijection between the original data set and the projected set. Said differently, the index could contain duplicates records, so how would you handle that for writes? I suppose you could make an argument that the system could do a bulk update for all source records but that is not always correct.


问:
'In' clause in SQL server with multiple columns
I have a component that retrieves data from database based on the keys provided.
However I want my java application to get all the data for all keys in a single database hit to fasten up things.
I can use 'in' clause when I have only one key.

While working on more than one key I can use below query in oracle

```<code>SELECT * FROM <table_name>
where (value_type,CODE1) IN (('I','COMM'),('I','CORE'));
</code>```

which is similar to writing

```<code>SELECT * FROM <table_name>
where value_type = 1 and CODE1 = 'COMM'
</code>```

and

```<code>SELECT * FROM <table_name>
where value_type = 1 and CODE1 = 'CORE'
</code>```

together

However, this concept of using 'in' clause as above is giving below error in 'SQL server'

ERROR:An expression of non-boolean type specified in a context where a condition is expected, near ','.

Please let know if their is any way to achieve the same in SQL server.

答:
Normally you can not do it, but can use the following technique.</p>

```<code>SELECT * FROM <table_name>
where (value_type+'/'+CODE1) IN (('I'+'/'+'COMM'),('I'+'/'+'CORE'));
</code>```

Body:
I have a component that retrieves data from database based on the keys provided.
However I want my java application to get all the data for all keys in a single database hit to fasten up things.
I can use 'in' clause when I have only one key.

While working on more than one key I can use below query in oracle

SELECT * FROM <table_name>
where (value_type,CODE1) IN (('I','COMM'),('I','CORE'));

which is similar to writing

SELECT * FROM <table_name>
where value_type = 1 and CODE1 = 'COMM'

and

SELECT * FROM <table_name>
where value_type = 1 and CODE1 = 'CORE'

together

However, this concept of using 'in' clause as above is giving below error in 'SQL server'

ERROR:An expression of non-boolean type specified in a context where a condition is expected, near ','.

Please let know if their is any way to achieve the same in SQL server.

Body:
Normally you can not do it, but can use the following technique.

SELECT * FROM <table_name>
where (value_type+'/'+CODE1) IN (('I'+'/'+'COMM'),('I'+'/'+'CORE'));


Title: Max count with related values in spark

Body:
I have a dataset having some colors and counts with related dates.

+-----------+----------+-----+
|      color|      Date|count|
+-----------+----------+-----+
|        red|2014-05-26|    5|
|        red|2014-05-02|    1|
|        red|2015-04-02|    1|
|        red|2015-04-26|    1|
|        red|2015-09-26|    2|
|       blue|2014-05-26|    3|
|       blue|2014-06-02|    1|
|      brown|2014-07-31|    2|
|      green|2014-08-01|    2|
+-----------+----------+-----+

I want max count for each colors with related dates. I am using Spark 2.0.2 with Java 8.

when I used max function then it removed date column and when I put date into groupBy then it gives same table as input dataset.

df.groupBy(color).max("count").show();

+-----------+----------+
|color      |max(count)|
+-----------+----------+
|        red|         5|
|       blue|         3|
|      brown|         2|
|      green|         2|
+-----------+----------+

Expected output:

+-----------+----------+----------+
|color      |      date|max(count)|
+-----------+----------+----------+
|        red|2014-05-26|         5|
|       blue|2014-05-26|         3|
|      brown|2014-07-31|         2|
|      green|2014-08-01|         2|
+-----------+----------+----------+

Body:
Here you want related column with max value so you can used agg() function for max value and first() for those related column.

df.groupBy(color).agg(first("date").alias(date),max("count")).show();

+-----------+----------+----------+
|color      |      date|max(count)|
+-----------+----------+----------+
|        red|2014-05-26|         5|
|       blue|2014-05-26|         3|
|      brown|2014-07-31|         2|
|      green|2014-08-01|         2|
+-----------+----------+----------+


问:
Jupyter Notebook - How to hide everything except notebooks on main screen?
I don't use Jupyter as much as I want to, but I am going to start doing it as I want to write reports with my code.

When I launch into the main screen though, I am presented with 'all' the files on my computer which makes finding the notebooks a little harder and it is messy (I know, first world problems!)

Is there any way of hiding everything except my notebooks?

答:
It is a bit of stepping aside, but you can create a folder with your notebooks, then launch jupyter notebook from the command line, after setting yourself in that folder.

```<code>$ cd my_notebooks
my_notebooks$ jupyter notebook
</code>```

At launch, the window will only show the files residing in that folder.

Body:
It is a bit of stepping aside, but you can create a folder with your notebooks, then launch jupyter notebook from the command line, after setting yourself in that folder.

$ cd my_notebooks
my_notebooks$ jupyter notebook

At launch, the window will only show the files residing in that folder.


问:
Coalesce over Rows in MSSQL 2008,
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

```<code>TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null
</code>```

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

```<code>SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active
</code>```

Here would be the results:

```<code>TransDate  Id  Active
---------------------
1/18 6pm   5   0
</code>```

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

答:
You could use a subquery:</p>

```<code>SELECT MAX(TransDate) AS TransDate
,      Id
,      (
       SELECT  TOP 1 t2.Active
       FROM    YourTable t2
       WHERE   t1.id = t2.id
               and t2.Active is not null
       ORDER BY
               t2.TransDate desc
       )
FROM   YourTable t1
</code>```

Title: Coalesce over Rows in MSSQL 2008,

Body:
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active

Here would be the results:

TransDate  Id  Active
---------------------
1/18 6pm   5   0

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

Body:
You could use a subquery:

SELECT MAX(TransDate) AS TransDate
,      Id
,      (
       SELECT  TOP 1 t2.Active
       FROM    YourTable t2
       WHERE   t1.id = t2.id
               and t2.Active is not null
       ORDER BY
               t2.TransDate desc
       )
FROM   YourTable t1


问:
How to add a customer file in the git folder
I have downloaded a code from github as

```<code>git clone https://github.com/askmike/gekko.git
</code>```

And I changed to develop branch as

```<code>git checkout origin/develop
</code>```

Now, I am in develop branch that can be known by

```<code>git status
HEAD detached at origin/develop
nothing to commit, working directory clean
</code>```

I will add a new file to the folder gekko such as configure_customer.js. If the next time the develop branch update, I just use

```<code>git pull
</code>```

However, it often detects that configure_customer.js is new file and I must use git add configure_customer.js to do add it to the project. Then, I command git pull again and my file is lost. Which step did I missing? Thanks

答:
You need to commit your change and push it to the server:

```<code>git add --all # or `git add <file>`
git commit
# Type the commit message and save
git push origin develop
</code>```

In case you want to add all your new files, git add --all is better, while git add . will only add new files in your current working directory, if it happens not to be the root directory of the repository.

Body:
I have downloaded a code from github as

git clone https://github.com/askmike/gekko.git

And I changed to develop branch as

git checkout origin/develop

Now, I am in develop branch that can be known by

git status
HEAD detached at origin/develop
nothing to commit, working directory clean

I will add a new file to the folder gekko such as configure_customer.js. If the next time the develop branch update, I just use

git pull

However, it often detects that configure_customer.js is new file and I must use git add configure_customer.js to do add it to the project. Then, I command git pull again and my file is lost. Which step did I missing? Thanks

Body:
You need to commit your change and push it to the server:

git add --all # or `git add <file>`
git commit
# Type the commit message and save
git push origin develop

In case you want to add all your new files, git add --all is better, while git add . will only add new files in your current working directory, if it happens not to be the root directory of the repository.


问:
Executing

```

答:
This worked for me by calling eval on each script content from ajax .done :

```<code>$.ajax({}).done(function (data) {
    $('div#content script').each(function (index, element) { eval(element.innerHTML);
})
</code>```

Note: I didn't write parameters to $.ajax which you have to adjust
  according to your ajax.

Title: Executing <script> injected by innerHTML after AJAX call

Body:
There's a div called "Content":

It should be filled with data from a PHP file, by AJAX, including a

Body:
This worked for me by calling eval on each script content from ajax .done :

$.ajax({}).done(function (data) {
    $('div#content script').each(function (index, element) { eval(element.innerHTML);
})

Note: I didn't write parameters to $.ajax which you have to adjust
  according to your ajax.


问:
Any sublime plugin to make angular view template smarter
Working in sublime on angular(2/4) is great until I am in the view template file. The interpolation cannot provide auto-completion for class properties backing the view, which I have seen it working by using VS Code.

Is there any plugin to make this work in sublime 3?

答:
There is a typescript plugin for sublime which I use for angular 2 projects.

You can install that package by pressing "Ctrl+Shift+P" from the sublime text editor, type "Install Package" , type "Typescript", and select and install one with "IO Wrapper".

After successful installation, select typescript from right bottom dropdown in the sublime editor.

This would show color coding or syntax highlighting.


问:
How to land on a specific tab using vuejs
I want to go to a specific tab using vuejs and element-ui.
Here is the jsfiddle file. https://jsfiddle.net/hutsu1zf/10/

By default it lands to first tab. How can I land on any other tab while page load event. I am new to vuejs so even some hints would be appreciated.

答:
Notice the value attribute in el-tabs and the name in el-tab-pane:

```<code><el-tabs type="border-card" value="2">
  <el-tab-pane   id="tab-1" label="Route">
    Route
  </el-tab-pane>
  <el-tab-pane id="tab-0"  label="Config">
    Config
  </el-tab-pane>
  <el-tab-pane id="tab-2" name="2" label="Role">
    Role
  </el-tab-pane>
  <el-tab-pane id="tab-3" label="Task">
    Task
  </el-tab-pane>
</el-tabs>
</code>```

Body:
Notice the value attribute in el-tabs and the name in el-tab-pane:

<el-tabs type="border-card" value="2">
  <el-tab-pane   id="tab-1" label="Route">
    Route
  </el-tab-pane>
  <el-tab-pane id="tab-0"  label="Config">
    Config
  </el-tab-pane>
  <el-tab-pane id="tab-2" name="2" label="Role">
    Role
  </el-tab-pane>
  <el-tab-pane id="tab-3" label="Task">
    Task
  </el-tab-pane>
</el-tabs>


问:
Datepicker for React-Strap
I am using react-strap npm package to use Bootstrap 4 components in my React app.

When I try to add the datepicker react-bootstrap-date-picker

```<code>npm install --save react-bootstrap-date-picker
</code>```

then try to use it in my component:

```<code>var DatePicker = require("react-bootstrap-date-picker");
</code>```

I get the error

Error in ./~/react-bootstrap-date-picker/lib/index.js

Module not found: 'react-bootstrap/lib/Button' in C:\Users\y\Desktop\Code\test\node_modules\react-bootstrap-date-picker\lib

@ ./~/react-bootstrap-date-picker/lib/index.js 15:14-51

Is this because react-bootstrap-date-picker is not compatible with react-strap? In this case, which npm packages should I install for bootstrap 4 components so that the datepicker module can work?

答:
react-bootstrap-date-picker is using react-bootstrap, react-bootstrap depends on bootstrap3. reactstrap is for bootstrap4 That is why it doesnt work.

You can use react-widgets DateTimePicker instead.

Title: Datepicker for React-Strap

Body:
I am using react-strap npm package to use Bootstrap 4 components in my React app.

When I try to add the datepicker react-bootstrap-date-picker

npm install --save react-bootstrap-date-picker

then try to use it in my component:

var DatePicker = require("react-bootstrap-date-picker");

I get the error

Error in ./~/react-bootstrap-date-picker/lib/index.js

Module not found: 'react-bootstrap/lib/Button' in C:\Users\y\Desktop\Code\test\node_modules\react-bootstrap-date-picker\lib

@ ./~/react-bootstrap-date-picker/lib/index.js 15:14-51

Is this because react-bootstrap-date-picker is not compatible with react-strap? In this case, which npm packages should I install for bootstrap 4 components so that the datepicker module can work?


问:
Regex - printable ASCII that not contain some chars (JS)
I'm trying to find a Regex, that allows printable ASCII chars except - " / \ [ ] : ; | = , + * ? < >

The string length must be 1-25

This will work:

```<code>/^[^\\[\]\:\;\|\=\,\/+\*\?<>\"]{1,25}$/
</code>```

But it will match also non-ASCII chars

答:
You may use

```<code>/^(?:(?![:[\];|\\=,\/+*?<>"])[ -~]){1,25}$/
</code>```

See the regex demo

Details

^ - start of string

(?: - outer grouping to enable matching a quantified lookahead-restricted ASCII char range

(?![:[\];|\\=,\/+*?<>"]) - the next char cannot be one defined in the character class (:, [, ], ;, |, \, =, ,, /, +, *, ?,
<, > and ")

[ -~] - any printable ASCII

){1,25}  - 1 to 25 occurrences

$ - end of string

Body:
I'm trying to find a Regex, that allows printable ASCII chars except - " / \ [ ] : ; | = , + * ? < >

The string length must be 1-25

This will work:

/^[^\\[\]\:\;\|\=\,\/+\*\?<>\"]{1,25}$/

But it will match also non-ASCII chars

Body:
You may use

/^(?:(?![:[\];|\\=,\/+*?<>"])[ -~]){1,25}$/

See the regex demo

Details

^ - start of string

(?: - outer grouping to enable matching a quantified lookahead-restricted ASCII char range

(?![:[\];|\\=,\/+*?<>"]) - the next char cannot be one defined in the character class (:, [, ], ;, |, \, =, ,, /, +, *, ?,
<, > and ")

[ -~] - any printable ASCII

){1,25}  - 1 to 25 occurrences

$ - end of string


问:
Printing multiple words in a line using printf() in bash
Im trying to print like below

```<code>2333 k4k3 34kk 34r4
233k 2344 234l llll
</code>```

with command

```<code>printf "%04d \n" "1111" "1123" "3333" "3333"
</code>```

but its breaks it. what I want to happen is all 4 values will be in single line and then add new line again.

答:
The C style printf in bash expects each format specifier and an associated argument to be provided. For example

```<code>printf "Surname: %s Name: %s\n" "foo" "bar"
</code>```

So you need to provide the specifiers for each of the arguments needed, something like

```<code>printf "%04d %04d %04d %04d\n" "1111" "1123" "3333" "3333"
</code>```

(or) if you want to treat the entire set of words as a single string literal, you just need to use a single string format specifier. Notice below the quotes covering the entire set of arguments as one.

```<code>printf "%s \n" "1111 1123 3333 3333"
</code>```

See The printf command in bash for more options and help articles.

Body:
Im trying to print like below

2333 k4k3 34kk 34r4
233k 2344 234l llll

with command

printf "%04d \n" "1111" "1123" "3333" "3333"

but its breaks it. what I want to happen is all 4 values will be in single line and then add new line again.

Body:
The C style printf in bash expects each format specifier and an associated argument to be provided. For example

printf "Surname: %s Name: %s\n" "foo" "bar"

So you need to provide the specifiers for each of the arguments needed, something like

printf "%04d %04d %04d %04d\n" "1111" "1123" "3333" "3333"

(or) if you want to treat the entire set of words as a single string literal, you just need to use a single string format specifier. Notice below the quotes covering the entire set of arguments as one.

printf "%s \n" "1111 1123 3333 3333"

See The printf command in bash for more options and help articles.


答:
You need to add and commit the file, followed by pushing your branch. And after that, you should do git pull

```<code>git add configure_customer.js
git commit configure_customer.js -m "some message here"
git push origin develop
git pull
</code>```

In case, you want to add all new files, you should use

```<code>git add .
git commit . -m "commit message here"
</code>```

Title: How to add a customer file in the git folder

Body:
You need to add and commit the file, followed by pushing your branch. And after that, you should do git pull

git add configure_customer.js
git commit configure_customer.js -m "some message here"
git push origin develop
git pull

In case, you want to add all new files, you should use

git add .
git commit . -m "commit message here"


问:
setinterval vs settimeout
How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.

I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.

1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?

2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?

This works for me

```<code>window.setInterval(function() {
    var date = new Date();
    if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
    millisTill10 += 86400000;
}
setTimeout(function() {
    alert("It's 10am!")
}, millisTill10);
</code>```

答:
setInterval is used to repeat a callback function with a given time, setTimeout is used to run a callback after a specific amount of time. Since you need to create a counter, you can use setInterval here.

Note: If you want to display the users every sconds in 10 minutes, you may use 1000 as the interval timing value. But if you want to show every minutes in the 10 minute duration, then using 60 * 1000 as the interval timing value is better.

```<code>setInterval(function(){
   var dateNow = new Date();
   if(dateNow.getHours() >= 7 &&
      dateNow.getMinutes >= 50 &&
      dateNow.getHours < 8)
   {
       // if the alert box isn't displayed yet
       // display it first.
       // update the display.
   }else{
       // if the alert box is displayed
       // hide it
   }
}, 1000); // or 1000 * 60 for minute based display
</code>```

Title: setinterval vs settimeout

Body:
How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.

I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.

1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?

2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?

This works for me

window.setInterval(function() {
    var date = new Date();
    if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
    millisTill10 += 86400000;
}
setTimeout(function() {
    alert("It's 10am!")
}, millisTill10);

Body:
setInterval is used to repeat a callback function with a given time, setTimeout is used to run a callback after a specific amount of time. Since you need to create a counter, you can use setInterval here.

Note: If you want to display the users every sconds in 10 minutes, you may use 1000 as the interval timing value. But if you want to show every minutes in the 10 minute duration, then using 60 * 1000 as the interval timing value is better.

setInterval(function(){
   var dateNow = new Date();
   if(dateNow.getHours() >= 7 &&
      dateNow.getMinutes >= 50 &&
      dateNow.getHours < 8)
   {
       // if the alert box isn't displayed yet
       // display it first.
       // update the display.
   }else{
       // if the alert box is displayed
       // hide it
   }
}, 1000); // or 1000 * 60 for minute based display


问:
Array of hashes whose key is an array containing ranges
I need to map a number of IDs and ranges of IDs to single values. I would like to store the whole structure in one object.

Is the following a sensible way to do this? What is the best way to search the keys by a single integer value to return the corresponding value?

```<code>large array = [
   {[3110..3220, 10200, 43680] =>   'A0300'},
   {[5200, 7100..8990, 9100..9900] => 'B0400'},
   {[17110..18121, 20160, 2210..22290] => 'C0600'}
]
</code>```

答:
It is pointless to use arrays and/or ranges as hash key, when you want to look up the data given a single value. The advantage of a hash is that, given a key, you can find a value quickly. In your case, you would have to traverse the hash sequentially to find the entry. In this case, it would make more sense to use an arrays of pairs, the first component describing the range and the second component describing the ID.

If you want to use a hash, you should make a corresponding entry for each possible integer value.

If you know that the integer values can not be higher than a certain size, you could create a sparse array, where the integer value is the index position, and the ID is the content of the array cell. This is fastest, but of course takes up some space.

Body:
I need to map a number of IDs and ranges of IDs to single values. I would like to store the whole structure in one object.

Is the following a sensible way to do this? What is the best way to search the keys by a single integer value to return the corresponding value?

large array = [
   {[3110..3220, 10200, 43680] =>   'A0300'},
   {[5200, 7100..8990, 9100..9900] => 'B0400'},
   {[17110..18121, 20160, 2210..22290] => 'C0600'}
]


问:
How to record a two minut video using pc camera and store it pc locally in vb.net using iis server and notepad
I have a one table in which 3 column , one in question column other is record video and last is upload.

My problem is that when user click on record Button we record two minut video

and Save it PC Locally and so on .

i am using notepad , internet information Service and front end in  aspx and back end in vb .net

i have this code check it  this is aspx file extension that i store on IIS server and use itsee this pic

```<code>     <%@ Page Language="VB" Debug="true" %>
     <%@ Import Namespace="System.Data" %>
     <%@ Import Namespace="System.Configuration" %>
     <%@ Import Namespace="System.Data.SqlClient" %>
     <%@ Import Namespace="System.Web.Security" %>
     <%@ Import Namespace="AForge.Video" %>
     <%@ Import Namespace="AForge.Video.DirectShow" %>

     <script runat="server">

     Protected  Sub Button1_Click(sender As Object, e As EventArgs)

    ' here to write a code for record a video

     End Sub

     </script>

     <!DOCTYPE html>

     <html>

     <head>

     <Style>
     #center_div
     {
        position: absolute;
        height: 200px;
        width: 850px;
        margin: -100px 0 0 -200px;
        top:20%;
        left: 30%;

     }
      table {
      border-collapse: collapse;
      width: 100%;
      }
      th, td {
    text-align: left;
    padding: 8px;
    }
    tr:nth-child(even){background-color: #f2f2f2}

    th {
    background-color: #4CAF50;
    color: white;
    }
    table, th, td {
        border: 1px solid black;
    }
     th {
        display: table-cell;
        vertical-align: inherit;
        font-weight: bold;
        text-align: center;
    }
    </Style>

    <title> Sign Up </title>

    </head>

    <body>

    <div id="center_div">

    <form  runat="server" id="myform">

    <fieldset>

    <legend>Answers the Question:</legend>
    <table>
    <tr>
    <th>Question</th><th>Record Videos</th><th>Upload</th>
    </tr>
    <tr>
    <td class="label" Style="width:500px">What is Your Name and Why we Take           Admission  in our university </td><td Style="width:200px"> <asp:Button  ID="Button9" runat="server" Text="Record" onClick="Button1_Click" /></td>
    <td Style="width:200px"> <asp:Button ID="Button3" runat="server" Text="Upload" onClick="Button1_Click" /></td>
    </tr>
    <tr>
    <td class="label" Style="width:500px">Why you Select this univeristy for  Study </td><td Style="width:200px"> <asp:Button ID="Button10" runat="server" Text="Record" onClick="Button1_Click" /></td>
    <td Style="width:200px"> <asp:Button ID="Button30" runat="server" Text="Upload" onClick="Button1_Click" /></td>
    </tr>
    <tr>
    <td class="label" Style="width:500px">Why you Select this univeristy for   Study </td><td Style="width:200px"> <asp:Button ID="Button101" runat="server" Text="Record" onClick="Button1_Click" /></td>
    <td Style="width:200px"> <asp:Button ID="Button301" runat="server"   Text="Upload" onClick="Button1_Click" /></td>
    </tr>

    </table>

    <asp:Button ID="Button2" runat="server" Text="Submit" onClick="Button1_Click" />

   <asp:Label ID = "Label2" runat = "server" text="" Style="color:red">    </asp:Label>
    </form>
    </div>
    </body>
     </html>
</code>```

答:
For recording a video Directx Library is used in c#

But in Asp .net Application can not used Directx on the client machine.So alternative used to flash , sliver light or Html 5.

So I solve My Problem By using Jquery Plugin for recording a video .

Video.js Record ##

Jquery Plugin

This Plugin is record my  video and store on my pc.For recording a video it is very good plugin for record a  video on server side in asp .net .

Body:
I have a one table in which 3 column , one in question column other is record video and last is upload.

My problem is that when user click on record Button we record two minut video

and Save it PC Locally and so on .

i am using notepad , internet information Service and front end in  aspx and back end in vb .net

i have this code check it  this is aspx file extension that i store on IIS server and use itsee this pic

     <%@ Page Language="VB" Debug="true" %>
     <%@ Import Namespace="System.Data" %>
     <%@ Import Namespace="System.Configuration" %>
     <%@ Import Namespace="System.Data.SqlClient" %>
     <%@ Import Namespace="System.Web.Security" %>
     <%@ Import Namespace="AForge.Video" %>
     <%@ Import Namespace="AForge.Video.DirectShow" %>

     <!DOCTYPE html>

    <title> Sign Up </title>

    <form  runat="server" id="myform">

    <fieldset>

    <legend>Answers the Question:</legend>

    Question	Record Videos	Upload

    What is Your Name and Why we Take           Admission  in our university 	 <asp:Button  ID="Button9" runat="server" Text="Record" onClick="Button1_Click" />
     <asp:Button ID="Button3" runat="server" Text="Upload" onClick="Button1_Click" />

    Why you Select this univeristy for  Study 	 <asp:Button ID="Button10" runat="server" Text="Record" onClick="Button1_Click" />
     <asp:Button ID="Button30" runat="server" Text="Upload" onClick="Button1_Click" />

    Why you Select this univeristy for   Study 	 <asp:Button ID="Button101" runat="server" Text="Record" onClick="Button1_Click" />
     <asp:Button ID="Button301" runat="server"   Text="Upload" onClick="Button1_Click" />

    <asp:Button ID="Button2" runat="server" Text="Submit" onClick="Button1_Click" />

   <asp:Label ID = "Label2" runat = "server" text="" Style="color:red">    </asp:Label>
    </form>


问:
Java: static abstract (again) - best practice how to work around
I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in Java .

But how do I solve such a problem then?

My application uses files of a few types, which I want to assign static properties like a description of that file type (like "data file", the other being "config file", etc.).
Obviously, I would put that into a static String so that the description is accessible without instancing a file (useful for the GUI f.i.).
On the other hand, obviously all file types should have some common methods like getStatus(), which obviously I want to inherit from a common superclass MyFileType.

getDescription() would of course be abstract in the superclass.

Tried using a combination of a superclass and an interface, but similar problem: A static implementation of an abstract method is not allowed.

How would a Java guru solve this?
Is it really such a bad implementation that I want to create?

Many thanks,
Philipp

答:
The question is not clear enough to provide an objective answer. Since I cannot give you a fish, this answer is more on the lines of "Teach you to fish" :)

When faced with design issues like these, where you think "duh..now sure why such a simple thing is so hard" more often than not, you are either designing it just incorrectly, or you are overcomplicating things. If I am empathizing correctly, your design issue seems like a "common requirement" yet the language is not allowing for any elegant solutions.

Trace back your design steps/decisions

question all the "obvious" and "of course" you are basing your design on (you are using quite a few above)

see if things can be simplified (don't take any of the OO concepts to their logical extreme. Make compromises based on ROI)

...and you will most likely arrive at an acceptable answer.

If you still don't, post back the classes and interfaces you think you want (with compile errors since language is not allowing certain things), and maybe we can help you tune your design.