问:
MySQL: the inconsistency of auto increment in id numbers
I wonder if you have come across this that the id numbers of auto increment don't arrange in correct order when you click on Browse button on phpMyAdmin - is it just me? Something I have set incorrectly in the db table?

For instance, when you insert a series of data into a table and you have deleted some of them as well, so when you check this table on phpMyAdmin, these data should appear in an order like this,

```<code>id

2
24
28
296
300
</code>```

but in most of my tables they don't appear in orders, instead they appear in something like this,

```<code>id

24
300
2
296
28
</code>```

as in this picture below,

Can we do something about it so that the IDs appear in the correct order?

EDIT 1:

I think most of you have misunderstood the issue I raided here. I mean when you click on Browser button on the phpMyAdmin to list all the data in your tables - not when you use SQL query to list the output by using order by.

Does it make sense?

EDIT 2:

This is one of my table structure - does it help you to see what is wrong in it?

```<code>CREATE TABLE IF NOT EXISTS `root_pages` (
  `pg_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pg_url` varchar(255) DEFAULT NULL,
  `pg_title` varchar(255) DEFAULT NULL,
  `pg_subtitle` varchar(255) DEFAULT NULL,
  `pg_description` text,
  `pg_introduction` text,
  `pg_content_1` text,
  `pg_content_2` text,
  `pg_content_3` text,
  `pg_content_4` text,
  `pg_order` varchar(255) DEFAULT NULL,
  `pg_hide` varchar(255) DEFAULT '0',
  `pg_highlight` varchar(255) DEFAULT '0',
  `pg_important` varchar(255) DEFAULT '0',
  `pg_parent` varchar(255) DEFAULT '0',
  `parent_id` varchar(255) DEFAULT NULL,
  `pg_cat_id` varchar(255) DEFAULT NULL COMMENT 'page category id',
  `ps_cat_id` varchar(255) DEFAULT NULL COMMENT 'post category id',
  `tmp_id` varchar(255) DEFAULT NULL COMMENT 'template id',
  `pg_backdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pg_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
</code>```

答:
Not sure if this applies to you but is your PK of type INT? If it's some sort of VARCHAR or TEXT it could order like the example you showed. And are you sure that column is actually your PK? Post the SHOW CREATE TABLE output of the table and it might become clearer.

And which storage engine are you using. The default order of a select is insert order for MYISAM and PK for InnoDB if I remember correctly. This would also depend of your version of MySql. To be sure in all circumstances you SHOULD use ORDER BY in your select statement.

Body:
I wonder if you have come across this that the id numbers of auto increment don't arrange in correct order when you click on Browse button on phpMyAdmin - is it just me? Something I have set incorrectly in the db table?

For instance, when you insert a series of data into a table and you have deleted some of them as well, so when you check this table on phpMyAdmin, these data should appear in an order like this,

id

2
24
28
296
300

but in most of my tables they don't appear in orders, instead they appear in something like this,

id

24
300
2
296
28

as in this picture below,

Can we do something about it so that the IDs appear in the correct order?

EDIT 1:

I think most of you have misunderstood the issue I raided here. I mean when you click on Browser button on the phpMyAdmin to list all the data in your tables - not when you use SQL query to list the output by using order by.

Does it make sense?

EDIT 2:

This is one of my table structure - does it help you to see what is wrong in it?

CREATE TABLE IF NOT EXISTS `root_pages` (
  `pg_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pg_url` varchar(255) DEFAULT NULL,
  `pg_title` varchar(255) DEFAULT NULL,
  `pg_subtitle` varchar(255) DEFAULT NULL,
  `pg_description` text,
  `pg_introduction` text,
  `pg_content_1` text,
  `pg_content_2` text,
  `pg_content_3` text,
  `pg_content_4` text,
  `pg_order` varchar(255) DEFAULT NULL,
  `pg_hide` varchar(255) DEFAULT '0',
  `pg_highlight` varchar(255) DEFAULT '0',
  `pg_important` varchar(255) DEFAULT '0',
  `pg_parent` varchar(255) DEFAULT '0',
  `parent_id` varchar(255) DEFAULT NULL,
  `pg_cat_id` varchar(255) DEFAULT NULL COMMENT 'page category id',
  `ps_cat_id` varchar(255) DEFAULT NULL COMMENT 'post category id',
  `tmp_id` varchar(255) DEFAULT NULL COMMENT 'template id',
  `pg_backdate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pg_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pg_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


来源: stackexchange

问:
I want to enable textbox when checkbox is checked in jquery or javascript
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash" onclick="cash(this)">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

答:
when checkbox is checked form content load from ajax page in modal
  popup

It seems you need to delegate the event

// Using change event handler and delegating the event using on from body
// to target element
$('body').on('change', '#cash', function() {
  // checking if it is checked
  if (this.checked === true) {
    $('#cashAmount').attr("disabled", false);
  } else {
    $('#cashAmount').attr("disabled", true);
  }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to enable textbox when checkbox is checked form content load from ajax page in modal popup but its not working and not showing any error in browser console.

function cash(cash) {
  if ($(cash).is(':checked')) {
    $('#cashAmount').attr("disabled", false);
  } else {
    alert("checkbox is not checked");
  }
}

  Cash <input type="checkbox" name="cash" id="cash" onclick="cash(this)">

  Amount *
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>

Body:
when checkbox is checked form content load from ajax page in modal
  popup

It seems you need to delegate the event

// Using change event handler and delegating the event using on from body
// to target element
$('body').on('change', '#cash', function() {
  // checking if it is checked
  if (this.checked === true) {
    $('#cashAmount').attr("disabled", false);
  } else {
    $('#cashAmount').attr("disabled", true);
  }

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 field-option">
  <strong>Cash</strong> <input type="checkbox" name="cash" id="cash">
</div>
<div class="col-md-6 col-sm-6 custom_field">
  <!-- custom_field -->
  <span><strong>Amount <i>*</i></strong></span>
  <input type="text" name="cashAmount" id="cashAmount" class="form-control" disabled>
</div>


问:
Access on kernel module
I wrote a linux kernel module char device (SuSE 13.2 Kernel 3.16.6), and an application for using this device.

In principle, the driver, the application and the communication works. The application can open, read, write and close the char device.

But there is a sporadic issue, that the application somtime 'lost' the reference to the module's write function. After 3 to 4 (sometime much more) write commands from the application to the module, the module's write funtion isn't executed.

I reduced and the write function inside module:

```<code>static ssize_t fWrite(struct file *file, const char  *buffer, size_t length, loff_t *offset)
{
  printk(KERN_ERR "INSIDE\n");
  return 0;
}
</code>```

And I also reduced the applcation:

```<code>int main (int argc, char **argv)
{
  unsigned short buffer=0xffff;
  fd = open ("/dev/MYPCI" , O_SYNC | O_RDWR );
  OUTPW (0, buffer ,fd );
  OUTPW (2, buffer,fd );
  OUTPW (4, buffer,fd );
  OUTPW (196, buffer,fd );
  OUTPW (70000, buffer,fd );
  OUTPW (400, buffer,fd );

  printf("DEV-Handle: %d\n", fd);
  close (fd );
}

int OUTPW (unsigned short ByteAddr, unsigned short value, int fd)
{
  int x;
  int size = (ByteAddr/2) <<16;
  size +=2;

  printf ("\nByteAddr:0x%08hX value:0x%08hX size:0x%08hX WRITE-Handle: 0x%04hX\n" , ByteAddr,value,size, &write);

  x= write(fd, &value, size) ;

  return x;
}
</code>```

The output looks loke this. sometime I can read 3 times, sometime I can read 4 times, sometimes much more.

The write function handle is still valid. If one write command fails, all following will also fail.
If I close&open the device again (inside the application) the write is temporary fixed.

The same behaviour exists on read command.

Any ideas?

答:
In the driver function fWrite() return length instead of 0.</p>

```<code>static ssize_t fWrite(struct file *file, const char  *buffer, size_t length, loff_t *offset)
{
printk(KERN_ERR "INSIDE\n");
return length;
}
</code>```

Title: Access on kernel module

Body:
I wrote a linux kernel module char device (SuSE 13.2 Kernel 3.16.6), and an application for using this device.

In principle, the driver, the application and the communication works. The application can open, read, write and close the char device.

But there is a sporadic issue, that the application somtime 'lost' the reference to the module's write function. After 3 to 4 (sometime much more) write commands from the application to the module, the module's write funtion isn't executed.

I reduced and the write function inside module:

static ssize_t fWrite(struct file *file, const char  *buffer, size_t length, loff_t *offset)
{
  printk(KERN_ERR "INSIDE\n");
  return 0;
}

And I also reduced the applcation:

int main (int argc, char **argv)
{
  unsigned short buffer=0xffff;
  fd = open ("/dev/MYPCI" , O_SYNC | O_RDWR );
  OUTPW (0, buffer ,fd );
  OUTPW (2, buffer,fd );
  OUTPW (4, buffer,fd );
  OUTPW (196, buffer,fd );
  OUTPW (70000, buffer,fd );
  OUTPW (400, buffer,fd );

  printf("DEV-Handle: %d\n", fd);
  close (fd );
}

int OUTPW (unsigned short ByteAddr, unsigned short value, int fd)
{
  int x;
  int size = (ByteAddr/2) <<16;
  size +=2;

  printf ("\nByteAddr:0x%08hX value:0x%08hX size:0x%08hX WRITE-Handle: 0x%04hX\n" , ByteAddr,value,size, &write);

  x= write(fd, &value, size) ;

  return x;
}

The output looks loke this. sometime I can read 3 times, sometime I can read 4 times, sometimes much more.

The write function handle is still valid. If one write command fails, all following will also fail.
If I close&open the device again (inside the application) the write is temporary fixed.

The same behaviour exists on read command.

Any ideas?

Body:
In the driver function fWrite() return length instead of 0.

static ssize_t fWrite(struct file *file, const char  *buffer, size_t length, loff_t *offset)
{
printk(KERN_ERR "INSIDE\n");
return length;
}


问:
Use Linq to search through table for items from a custom class
My code below works but I'm trying to find out how to optimize this and/or make it faster by changing it to one line because currently it performs a query on the database table once per loop and this seems to take forever

The custom class and sql table both have the same exact names as you can see. The queryList is a list of the custom class.

```<code>foreach (var item in queryList)
{
    var query = context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days).ToList();

    if (query.Count() > 0)
    {
         context.DataTable.RemoveRange(query);
    }
}
</code>```

答:
You can use Union to fetch all data at one trip to database:

```<code>var query = context.DataTable.Where(x => x.Id == 0);
foreach (var item in queryList)
    query = query.Union(context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days));

var allData = query.ToList();
if (allData.Count() > 0)
    context.DataTable.RemoveRange(allData);
</code>```

Body:
My code below works but I'm trying to find out how to optimize this and/or make it faster by changing it to one line because currently it performs a query on the database table once per loop and this seems to take forever

The custom class and sql table both have the same exact names as you can see. The queryList is a list of the custom class.

foreach (var item in queryList)
{
    var query = context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days).ToList();

    if (query.Count() > 0)
    {
         context.DataTable.RemoveRange(query);
    }
}

Body:
You can use Union to fetch all data at one trip to database:

var query = context.DataTable.Where(x => x.Id == 0);
foreach (var item in queryList)
    query = query.Union(context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days));

var allData = query.ToList();
if (allData.Count() > 0)
    context.DataTable.RemoveRange(allData);


问:
C++ Singly Linked List Copy Constructor Segmentation Fault
I'm trying to create a deep copy constructor of a singly linked list class. It copies the head of the new list and appends elements to the end of it (by calling an append) function.

The full code is available here: https://onlinegdb.com/Hke0ev8bG

Can anyone point out where I'm going wrong? Much appreciated!

```<code>class LinkedList
{
    class Node
    {
    public:
        int *data;
        Node *next;
        Node() {
            data = NULL;
            next = NULL;
        }
        Node(int *d) {
            data = d;
            next = NULL;
        }
    };

private:
    Node *head;
    int itemCount;

public:
    LinkedList() {
        head = NULL;
        itemCount = 0;
}

//COPY CONSTRUCTOR
LinkedList(LinkedList &copy)
{
    Node *temp = copy.head;
    while (temp != NULL)
    {
         append(temp->data);
         temp = temp->next;
    }
}

//ADD TO THE END OF A LIST
void append(int *d) {
    Node *tail = new Node;

    tail->data = d;
    tail->next = NULL;

    if (head == NULL) {
        head = tail;
    }
    else {
        Node *temp = new Node;
        temp = head;

        while (temp->next != NULL) {
            temp = temp->next;
        }

        temp->next = tail;
    }
    itemCount++;
}
</code>```

The problem is that the program runs into a "Segmentation fault" at the copy constructor part.

答:
You forgot to initialize LinkedList::head and LinkedList::itemCount in the copy constructor. The initialization performed in the regular constructor only applies when the regular constructor is actually used.

As a result, LinkedList::append sees random garbage when checking the head pointer, assumes it's valid and then causes a seg fault when using that invalid pointer.

Body:
I'm trying to create a deep copy constructor of a singly linked list class. It copies the head of the new list and appends elements to the end of it (by calling an append) function.

The full code is available here: https://onlinegdb.com/Hke0ev8bG

Can anyone point out where I'm going wrong? Much appreciated!

class LinkedList
{
    class Node
    {
    public:
        int *data;
        Node *next;
        Node() {
            data = NULL;
            next = NULL;
        }
        Node(int *d) {
            data = d;
            next = NULL;
        }
    };

private:
    Node *head;
    int itemCount;

public:
    LinkedList() {
        head = NULL;
        itemCount = 0;
}

//COPY CONSTRUCTOR
LinkedList(LinkedList &copy)
{
    Node *temp = copy.head;
    while (temp != NULL)
    {
         append(temp->data);
         temp = temp->next;
    }
}

//ADD TO THE END OF A LIST
void append(int *d) {
    Node *tail = new Node;

    tail->data = d;
    tail->next = NULL;

    if (head == NULL) {
        head = tail;
    }
    else {
        Node *temp = new Node;
        temp = head;

        while (temp->next != NULL) {
            temp = temp->next;
        }

        temp->next = tail;
    }
    itemCount++;
}

The problem is that the program runs into a "Segmentation fault" at the copy constructor part.


问:
How to know about all the files which are compiled together to make an executable?
We are looking for an procedure through which we can easily list down all the file which are compiled together to make an executable.

Use Case : Suppose, We have large repository and we want to know what all are the files existing in repository which are compiled to make an executable (i.e a.out)

For example :

```<code>dwarfdump a.out | grep "NS uri"
0x0000064a  [   9, 0] NS uri: "/home/main.c"
0x000006dd  [   2, 0] NS uri: "/home/zzzz.c"
0x000006f1  [   2, 0] NS uri: "/home/yyyy.c"
0x00000705  [   2, 0] NS uri: "/home/xxxx.c"
0x00000719  [   2, 0] NS uri: "/home/wwww.c"
</code>```

but it doesn't listed down the all the header files.
please suggest.

答:
How to Extract Source Code From Executable with Debug Symbol Available ?

You cannot do that. I guess you are on Linux/x86-64 (and your question is operating system and ABI specific, and debugging format specific). Of course, you should pass -g (or even -g3) to all the gcc compilation commands for your executable. Without that -g or -g3 option used to compile every translation unit (including perhaps those of shared libraries!) you might not have enough information.

Even with debug information in DWARF format, the ELF executable don't contain source code, but only references to source code (e.g. source file path, position as line and column numbers). So the debug information contains stuff like file src/foo.c, line 34 column 5 (but don't give anything about the content of src/foo.c near that position). Of course once gdb knows the file path src/foo.c it is able to read that source file (if available and up to date w.r.t. executable) so it can list it.

Extracting that debugging meta-data is a different question. Once you have understood DWARF you could use tools like objdump or readelf or addr2line or dwarfdump or libdwarf; and you could also script gdb (recent versions of GDB may be extendable in Python or in Guile) and use it on your ELF executable.

Perhaps you should consider Ian Taylor's libbacktrace. It uses the DWARF information  to provide nice looking backtraces at runtime.

BTW, cgdb is (like ddd) only a front-end to gdb which does all the real work of processing that DWARF information. It is free software, you can study its source code.

i have only a.out then i want to list done file names

You might try dwarfdump -i | grep DW_AT_decl_file and you could use some GNU awk command instead of grep. You need to dive into the details of DWARF specifications and you need to understand more about the elf(5) format.

It doesn't listed down the all the header files

This is expected. Most header files don't contain any code, only declarations (e.g. printf is not implemented in <stdio.h> but in some C source file of your C standard library, e.g. in tree/src/stdio/printf.c if you use musl-libc; it is just declared in /usr/include/stdio.h). DWARF (and other debug information formats) are describing the binary code. And some header files get included only to give access to a few preprocessor macros (which get expanded or skipped at preprocessing time).

Maybe you dream of homoiconic programming languages, then try Common Lisp (e.g. with SBCL).

If your question is how to use gdb, then please read the Debugging with GDB manual.

If your question is about decompilers, be aware that it is an impossible task in  general (e.g. because of Rice's theorem). BTW, programs inside most Linux distributions are generally free software, so it is quite easy to get the source code (and you could even avoid using proprietary software on Linux).

BTW, you could also do more things at compilation time by passing more flags to gcc. You might pass -H or -M (etc...) to gcc (in addition of -g). You could even consider writing your own GCC plugin to collect the information you want in some database (but that is probably not worth the effort). You could also consider improving your build automation (e.g. adding more into your Makefile) to collect such information. BTW, many large C programs use some metaprogramming techniques by having some .c files perhaps containing #line directives generated by tools (e.g. bison) or scripts, then what kind of file path do you want to keep ??

We are looking for an procedure through which we can easily list down all the files which are compiled together to make an executable.

If you are writing that executable and compiling it from its source code, I would suggest collecting that information at build time. It could be as trivial as passing some -M and/or -H flag to gcc, perhaps into some generated timestamp.c file (see this for inspiration; but your timestamp.c might contain information provided by gcc -M etc...). Your timestamp file might contain git version control metadata (like generated in this Makefile). Read also about reproducible builds and about package managers.

Body:
We are looking for an procedure through which we can easily list down all the file which are compiled together to make an executable.

Use Case : Suppose, We have large repository and we want to know what all are the files existing in repository which are compiled to make an executable (i.e a.out)

For example :

dwarfdump a.out | grep "NS uri"
0x0000064a  [   9, 0] NS uri: "/home/main.c"
0x000006dd  [   2, 0] NS uri: "/home/zzzz.c"
0x000006f1  [   2, 0] NS uri: "/home/yyyy.c"
0x00000705  [   2, 0] NS uri: "/home/xxxx.c"
0x00000719  [   2, 0] NS uri: "/home/wwww.c"

but it doesn't listed down the all the header files.
please suggest.


问:
No access to Program Files in Windows 7
I'm totally new to windows 7 and have just installed Apache server. I want to change httpd file... But when opening file with notepad and saving it, I get a message that I have no rights... My user is a member of Administrators group. What else can I do?

Thanks

P.S. Could you suggest any nice tutorials on dealing with user administration and admin accounts?

答:
You need to take ownership of the folder, which requires a registry hack. (You can search for takeown registry)

My advice is to install your Apache server outside of "Program Files". You should not have files requiring regular modifications in Program Files.

ContentLicense: CC BY-SA 2.5

Title: No access to Program Files in Windows 7


问:
Select certain columns from A table to JOIN certain columns in B table in R
1.Simply like using Ctrl+X select a columns add Ctrl+V into a certain
  columns in another table freely.

2.Select bigger table's columns to join smaller table that full_join and by
function cannot do.(also they have different cols names.)

```<code>#A table (bigger table)

 Manufactor Models  date  Serial
1       audi    r55 21341  34j
2        bmw    e44 13214  F34
3    cadillc   fr4c 23124  00deaa
4       benz   c45z 21415  3rf
5      lexus  l56fs 97014  3r
6     toyota   de22 75199  2ghre

#B table (smaller table)
      Markers   Price   Types
1      Asaudi    4011    ar55
2        abmw    2334    ae44
3    acadillc    1445   fsr4c
4       fbenz    1455  cdf45z
5     falexus  5551l5   ff6fs
6    12toyota   51242    de22
</code>```

Expected picture

```<code>#B table
      Markers   Price   Types
1      Asaudi    4011    ar55
2        abmw    2334    ae44
3    acadillc    1445   fsr4c
4       fbenz    1455  cdf45z
5     falexus  5551l5   ff6fs
6    12toyota   51242    de22
7       audi      NA      r55
8        bmw      NA      e44
9    cadillc      NA     fr4c
10       benz     NA     c45z
11     lexus      NA    l56fs
12    toyota      NA     de22
</code>```

Eliminate unnecessary cols in A table firstly, to fit full_join by =c("x col name"="y col name") limitation is the way but it is inefficient .Are there
more clean and efficient way to do that?

答:
Your illustration suggests that you can achieve the expected result using below code snippet

```<code>library(dplyr)
A %>%
  select(-date, -Serial) %>%
  `colnames<-`(c('Markers','Types')) %>%
  bind_rows(B,.)
</code>```

Output is:

```<code>    Markers  Price  Types
1    Asaudi   4011   ar55
2      abmw   2334   ae44
3  acadillc   1445  fsr4c
4     fbenz   1455 cdf45z
5   falexus 5551l5  ff6fs
6  12toyota  51242   de22
7      audi   <NA>    r55
8       bmw   <NA>    e44
9   cadillc   <NA>   fr4c
10     benz   <NA>   c45z
11    lexus   <NA>  l56fs
12   toyota   <NA>   de22
</code>```

Sample data:

```<code>> dput(A)
structure(list(Manufactor = structure(c(1L, 3L, 4L, 2L, 5L, 6L
), .Label = c("audi", "benz", "bmw", "cadillc", "lexus", "toyota"
), class = "factor"), Models = structure(c(6L, 3L, 4L, 1L, 5L,
2L), .Label = c("c45z", "de22", "e44", "fr4c", "l56fs", "r55"
), class = "factor"), date = c(21341L, 13214L, 23124L, 21415L,
97014L, 75199L), Serial = structure(c(3L, 6L, 1L, 5L, 4L, 2L), .Label = c("00deaa",
"2ghre", "34j", "3r", "3rf", "F34"), class = "factor")), .Names = c("Manufactor",
"Models", "date", "Serial"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

> dput(B)
structure(list(Markers = structure(c(4L, 2L, 3L, 6L, 5L, 1L), .Label = c("12toyota",
"abmw", "acadillc", "Asaudi", "falexus", "fbenz"), class = "factor"),
    Price = structure(c(4L, 3L, 1L, 2L, 6L, 5L), .Label = c("1445",
    "1455", "2334", "4011", "51242", "5551l5"), class = "factor"),
    Types = structure(c(2L, 1L, 6L, 3L, 5L, 4L), .Label = c("ae44",
    "ar55", "cdf45z", "de22", "ff6fs", "fsr4c"), class = "factor")), .Names = c("Markers",
"Price", "Types"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6"))
</code>```

Body:
1.Simply like using Ctrl+X select a columns add Ctrl+V into a certain
  columns in another table freely.

2.Select bigger table's columns to join smaller table that full_join and by
function cannot do.(also they have different cols names.)

#A table (bigger table)

 Manufactor Models  date  Serial
1       audi    r55 21341  34j
2        bmw    e44 13214  F34
3    cadillc   fr4c 23124  00deaa
4       benz   c45z 21415  3rf
5      lexus  l56fs 97014  3r
6     toyota   de22 75199  2ghre

#B table (smaller table)
      Markers   Price   Types
1      Asaudi    4011    ar55
2        abmw    2334    ae44
3    acadillc    1445   fsr4c
4       fbenz    1455  cdf45z
5     falexus  5551l5   ff6fs
6    12toyota   51242    de22

Expected picture

#B table
      Markers   Price   Types
1      Asaudi    4011    ar55
2        abmw    2334    ae44
3    acadillc    1445   fsr4c
4       fbenz    1455  cdf45z
5     falexus  5551l5   ff6fs
6    12toyota   51242    de22
7       audi      NA      r55
8        bmw      NA      e44
9    cadillc      NA     fr4c
10       benz     NA     c45z
11     lexus      NA    l56fs
12    toyota      NA     de22

Eliminate unnecessary cols in A table firstly, to fit full_join by =c("x col name"="y col name") limitation is the way but it is inefficient .Are there
more clean and efficient way to do that?

Body:
Your illustration suggests that you can achieve the expected result using below code snippet

library(dplyr)
A %>%
  select(-date, -Serial) %>%
  `colnames<-`(c('Markers','Types')) %>%
  bind_rows(B,.)

Output is:

    Markers  Price  Types
1    Asaudi   4011   ar55
2      abmw   2334   ae44
3  acadillc   1445  fsr4c
4     fbenz   1455 cdf45z
5   falexus 5551l5  ff6fs
6  12toyota  51242   de22
7      audi   <NA>    r55
8       bmw   <NA>    e44
9   cadillc   <NA>   fr4c
10     benz   <NA>   c45z
11    lexus   <NA>  l56fs
12   toyota   <NA>   de22

Sample data:

> dput(A)
structure(list(Manufactor = structure(c(1L, 3L, 4L, 2L, 5L, 6L
), .Label = c("audi", "benz", "bmw", "cadillc", "lexus", "toyota"
), class = "factor"), Models = structure(c(6L, 3L, 4L, 1L, 5L,
2L), .Label = c("c45z", "de22", "e44", "fr4c", "l56fs", "r55"
), class = "factor"), date = c(21341L, 13214L, 23124L, 21415L,
97014L, 75199L), Serial = structure(c(3L, 6L, 1L, 5L, 4L, 2L), .Label = c("00deaa",
"2ghre", "34j", "3r", "3rf", "F34"), class = "factor")), .Names = c("Manufactor",
"Models", "date", "Serial"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

> dput(B)
structure(list(Markers = structure(c(4L, 2L, 3L, 6L, 5L, 1L), .Label = c("12toyota",
"abmw", "acadillc", "Asaudi", "falexus", "fbenz"), class = "factor"),
    Price = structure(c(4L, 3L, 1L, 2L, 6L, 5L), .Label = c("1445",
    "1455", "2334", "4011", "51242", "5551l5"), class = "factor"),
    Types = structure(c(2L, 1L, 6L, 3L, 5L, 4L), .Label = c("ae44",
    "ar55", "cdf45z", "de22", "ff6fs", "fsr4c"), class = "factor")), .Names = c("Markers",
"Price", "Types"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6"))


问:
Having errors when importing Jquery to Angular 4
I was trying to import bootstrap to my angular4 project. So first of all, I was trying to import jQuery.
I coded as showen below.

```<code>npm install jquery --save
npm install --save-dev @types/jquery
</code>```

I am 100% percent sure I imported the js and css file.

And after that, I could do

```<code>$("asc").show()
</code>```

However, when I do ng server. There appeared hundreds of errors about

console output:

```<code>"/Users/Eva/Desktop/auction/node_modules/@types/jquery/index.d.ts (6514,45): Duplicate identifier 'never'"
</code>```

Anyone could tell what's could be the problem? I spent a lot of time and find a line of code in the index.d.ts of @types/jQuery saying:

// TypeScript Version: 2.3
 and my TypeScript version is 2.6. Is this the problem? If it is, how to change to 2.3? Any tsc after 2.3 couldn't use jQuery?

答:
If you are using Cli you can try these steps

```<code>This is without using typing in the below link you can find with types as well
</code>```

Update your Angular-cli.json

```<code>  "scripts": ["../node_modules/jquery/dist/jquery.js"
  ]
</code>```

Component

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

declare var $ :any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}
</code>```

Then you can use the jquery in ngAfterViewInit

Working example in this link

More on the same https://rahulrsingh09.github.io/AngularConcepts/faq

Body:
I was trying to import bootstrap to my angular4 project. So first of all, I was trying to import jQuery.
I coded as showen below.

npm install jquery --save
npm install --save-dev @types/jquery

I am 100% percent sure I imported the js and css file.

And after that, I could do

$("asc").show()

However, when I do ng server. There appeared hundreds of errors about

console output:

"/Users/Eva/Desktop/auction/node_modules/@types/jquery/index.d.ts (6514,45): Duplicate identifier 'never'"

Anyone could tell what's could be the problem? I spent a lot of time and find a line of code in the index.d.ts of @types/jQuery saying:

// TypeScript Version: 2.3
 and my TypeScript version is 2.6. Is this the problem? If it is, how to change to 2.3? Any tsc after 2.3 couldn't use jQuery?

Body:
If you are using Cli you can try these steps

This is without using typing in the below link you can find with types as well

Update your Angular-cli.json

  "scripts": ["../node_modules/jquery/dist/jquery.js"
  ]

Component

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

declare var $ :any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

Then you can use the jquery in ngAfterViewInit

Working example in this link

More on the same https://rahulrsingh09.github.io/AngularConcepts/faq


问:
Sum up all matching elements in an array
How can I sum up all of the matching elements in an array? I currently trying to use a nested for loop, but if a number occurs more than 2 times it won't sum up the total correctly.I feel like am missing something small here.

```<code>public class Game {
ColoredDice dice[] = new ColoredDice[6];
private int diceValues[] = new int[6];

public Game() {
    rollSixDice();
    score();
}

public void rollSixDice(){
    for(int i = 0;i < 6;i++){
        dice[i] = new ColoredDice();
    }
    // getDiceValue returns the int value of the die
    for(int i =0;i<dice.length;i++){
        diceValues[i] = dice[i].getDiceValue();
    }
}

public void score(){
    for(int i=0;i<dice.length;i++){
        for(int j = i+1 ;j < 6;j++){
            if(dice[i].getDiceValue() == diceValues[j]){
                score += dice[i].getDiceValue();
            }
        }
    }
    System.out.println(score);
  }
}

public class DiceTester {
public static void main(String[] args) {
new Game();
  }
}
</code>```

To be clear more then what on what happens..
Both arrays here are identical and are of type int.
Example role values: 2,3,4,2,6,6.
Score:8

答:
You can use hash map where key is on which you want do group and value is sum.This will increase space complexity to O(N) and time complexity O(N).
Or you can do O(nlogn) by sorting first and then summing the same element consecutively </p>

Body:
How can I sum up all of the matching elements in an array? I currently trying to use a nested for loop, but if a number occurs more than 2 times it won't sum up the total correctly.I feel like am missing something small here.

public class Game {
ColoredDice dice[] = new ColoredDice[6];
private int diceValues[] = new int[6];

public Game() {
    rollSixDice();
    score();
}

public void rollSixDice(){
    for(int i = 0;i < 6;i++){
        dice[i] = new ColoredDice();
    }
    // getDiceValue returns the int value of the die
    for(int i =0;i<dice.length;i++){
        diceValues[i] = dice[i].getDiceValue();
    }
}

public void score(){
    for(int i=0;i<dice.length;i++){
        for(int j = i+1 ;j < 6;j++){
            if(dice[i].getDiceValue() == diceValues[j]){
                score += dice[i].getDiceValue();
            }
        }
    }
    System.out.println(score);
  }
}

public class DiceTester {
public static void main(String[] args) {
new Game();
  }
}

To be clear more then what on what happens..
Both arrays here are identical and are of type int.
Example role values: 2,3,4,2,6,6.
Score:8


问:
Before closing window Sublime Text
Is there a way in Sublime Text to detect before window is closing to add a custom command?

I run a custom command with this shortcuts:

```<code>[
{ "keys": ["ctrl+shift+w"], "command": "custom_command"},
{ "keys": ["alt+f4"], "command": "custom_command"}
]
</code>```

But there are other ways to close Sublime Text and makes sense that a before closing window event should cover all.

答:
Maybe python's atexit https://docs.python.org/3/library/atexit.html would work.

(I have not tried it - it is possible that python plugin API will not be fully working at the time atexit functions are called)

Title: Before closing window Sublime Text

Body:
Is there a way in Sublime Text to detect before window is closing to add a custom command?

I run a custom command with this shortcuts:

[
{ "keys": ["ctrl+shift+w"], "command": "custom_command"},
{ "keys": ["alt+f4"], "command": "custom_command"}
]

But there are other ways to close Sublime Text and makes sense that a before closing window event should cover all.


问:
Creating winforms controls dynamically
I am learning c#. I want to create some controls dynamically. Here is the code that I am trying to create new elements on form dynamically, but it doesn't do anything. Please help me to solve this problem.</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

    namespace Sampless
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int n = 4;

        private void btnDisplay_Click(object sender, EventArgs e)
        {
            TextBox[] textBox = new TextBox[n];
            Label[] label = new Label[n];

            for (int i = 0; i < n; i++)
            {
                textBox[i] = new TextBox();
                textBox[i].Name = "n" + i;
                textBox[i].Text = "n" + i;

                label[i] = new Label();
                label[i].Name = "n" + i;
                label[i].Text = "n" + i;
            }

            for (int i = 0; i < n; i++)
            {
                this.Controls.Add(textBox[i]);
                this.Controls.Add(label[i]);
            }
        }
    }
}
</code>```

答:
```<code>namespace Sample
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        TextBox txbx = new TextBox();
        private void button1_Click(object sender, EventArgs e)
        {
            AddNewTextBox();

            txbx = new TextBox();

            txbx.Location = new Point(10, 20);

            txbx.Visible = true;

            Controls.Add(txbx);

        }

    }
}
</code>```

Title: Creating winforms controls dynamically

Body:
I am learning c#. I want to create some controls dynamically. Here is the code that I am trying to create new elements on form dynamically, but it doesn't do anything. Please help me to solve this problem.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

    namespace Sampless
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int n = 4;

        private void btnDisplay_Click(object sender, EventArgs e)
        {
            TextBox[] textBox = new TextBox[n];
            Label[] label = new Label[n];

            for (int i = 0; i < n; i++)
            {
                textBox[i] = new TextBox();
                textBox[i].Name = "n" + i;
                textBox[i].Text = "n" + i;

                label[i] = new Label();
                label[i].Name = "n" + i;
                label[i].Text = "n" + i;
            }

            for (int i = 0; i < n; i++)
            {
                this.Controls.Add(textBox[i]);
                this.Controls.Add(label[i]);
            }
        }
    }
}


Title: Conversion of Array and objects to bulk insert in mysql Sequelize + Nodejs

Body:
This is my json object:

    {
    "groups":

 [
        {
            "id": 1,
            "groupname": "Angular",
            "createdAt": "2017-12-05T09:36:05.000Z",
            "updatedAt": "2017-12-05T09:36:05.000Z",
            "contactgroups": [
            {
                "id": 1,
                "contact":
                {
                    "gsm": "12345"
                }
            },
            {
                "id": 3,
                "contact":
                {
                    "gsm": "54321"
                }
            },
            {
                "id": 4,
                "contact":
                {
                    "gsm": "99999"
                }
            }],
            "select": true
        },
        {
            "id": 2,
            "groupname": "React",
            "createdAt": "2017-12-05T09:36:10.000Z",
            "updatedAt": "2017-12-05T09:36:10.000Z",
            "contactgroups": [
            {
                "id": 2,
                "contact":
                {
                    "gsm": "66666"
                }
            },
            {
                "id": 5,
                "contact":
                {
                    "gsm": "54321"
                }
            }],
            "select": true
        },
        {
            "id": 3,
            "groupname": "Vue",
            "createdAt": "2017-12-05T09:36:15.000Z",
            "updatedAt": "2017-12-05T09:36:15.000Z",
            "contactgroups": [
            {
                "id": 6,
                "contact":
                {
                    "gsm": "12345"
                }
            }]
        },
     ],
    "sender": "ifelse",
    "message": "test"
}

I want to convert above object like this:

[
    {"gsm": 12345, "sender": "ifelse", "message": "test"},
    {"gsm": 54321, "sender": "ifelse", "message": "test"},
    {"gsm": 99999, "sender": "ifelse", "message": "test"},
    {"gsm": 66666, "sender": "ifelse", "message": "test"},
    {"gsm": 54321, "sender": "ifelse", "message": "test"},
    {"gsm": 12345, "sender": "ifelse", "message": "test"},

]

Then only i am able to bulk insert in sequelize.

How to do this using for or foreach or any other functions? to done this stuff?

is foreach better? is it possible to do with map?

I want my final json object, then only sequelize allowed to bulk create.

Ps: I want "select": true json gsm numbers only

Body:
In your case, I am using for loop to make JSON object

 var data={
    "groups":

 [
        {
            "id": 1,
            "groupname": "Angular",
            "createdAt": "2017-12-05T09:36:05.000Z",
            "updatedAt": "2017-12-05T09:36:05.000Z",
            "contactgroups": [
            {
                "id": 1,
                "contact":
                {
                    "gsm": "12345"
                }
            },
            {
                "id": 3,
                "contact":
                {
                    "gsm": "54321"
                }
            },
            {
                "id": 4,
                "contact":
                {
                    "gsm": "99999"
                }
            }],
            "select": true
        },
        {
            "id": 2,
            "groupname": "React",
            "createdAt": "2017-12-05T09:36:10.000Z",
            "updatedAt": "2017-12-05T09:36:10.000Z",
            "contactgroups": [
            {
                "id": 2,
                "contact":
                {
                    "gsm": "66666"
                }
            },
            {
                "id": 5,
                "contact":
                {
                    "gsm": "54321"
                }
            }],
            "select": true
        },
        {
            "id": 3,
            "groupname": "Vue",
            "createdAt": "2017-12-05T09:36:15.000Z",
            "updatedAt": "2017-12-05T09:36:15.000Z",
            "contactgroups": [
            {
                "id": 6,
                "contact":
                {
                    "gsm": "12345"
                }
            }]
        },
     ],
    "sender": "ifelse",
    "message": "test"
 }

    var result=[
        {"gsm": 12345, "sender": "ifelse", "message": "test"},
        {"gsm": 54321, "sender": "ifelse", "message": "test"},
        {"gsm": 99999, "sender": "ifelse", "message": "test"},
        {"gsm": 66666, "sender": "ifelse", "message": "test"},
        {"gsm": 54321, "sender": "ifelse", "message": "test"},
        {"gsm": 12345, "sender": "ifelse", "message": "test"},

    ]
    var arr=[];
    for(var i=0;i<data.groups.length;i++){
       if(data.groups[i].select){
        for(var j=0;j<data.groups[i].contactgroups.length;j++){    arr.push({gsm:data.groups[i].contactgroups[j].contact.gsm,sender:data.sender,message:data.message});
        }
       }
    }
    console.log(arr);


问:
How to manually decode an an array in swift 4 Codable?
Here is my code. But I do not know what to set the value to. It has to be done manually because the real structure is slightly more complex than this example.

Any help please?

```<code>struct Something: Decodable {
   value: [Int]

   enum CodingKeys: String, CodingKeys {
      case value
   }

   init (from decoder :Decoder) {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      value = ??? // < --- what do i put here?
   }
}
</code>```

答:
Thanks for Joshua Nozzi's hint. Here's how I implement to decode an array of Int:

```<code>let decoder = JSONDecoder()
let intArray = try? decoder.decode([Int].self, from: data)
</code>```

without decoding manually.

Body:
Here is my code. But I do not know what to set the value to. It has to be done manually because the real structure is slightly more complex than this example.

Any help please?

struct Something: Decodable {
   value: [Int]

   enum CodingKeys: String, CodingKeys {
      case value
   }

   init (from decoder :Decoder) {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      value = ??? // < --- what do i put here?
   }
}

Body:
Thanks for Joshua Nozzi's hint. Here's how I implement to decode an array of Int:

let decoder = JSONDecoder()
let intArray = try? decoder.decode([Int].self, from: data)

without decoding manually.


问:
introduction to latex
what's a good website that has an introduction to latex for window users? I will be using it mainly to write math homework problems and probably then converting it to a PDF to print out. I'm hoping somebody has bookmarked a good link already so I don't have to search. Thanks!</p>

答:
I recommend this one: http://en.wikibooks.org/wiki/LaTeX

LaTeX works the same across platforms (and even across its distros, except some may provide features that others don't), so it doesn't really matter what your platform is.

Title: introduction to latex


问:
Re-prompt credential box if username/pw is incorrect
How do you Re-prompt credential box if username/pw is incorrect?

```<code>Import-Module ActiveDirectory
Write-Host "Please enter Admin credential..."
$Creds = Get-Credential
</code>```

My script runs everyline after even putting wrong username/pw (w error obvously)

I need Get-Credential to appear everytime the user/pass is invalid so I won't rerun the same script everytime I put in wrong information.

UPDATE:

Heres the sample script:

```<code>Import-Module ActiveDirectory
Write-Host "Please enter Admin credential..."
$Creds = Get-Credential
$Tpm = Get-wmiobject -ComputerName $wsid -Credential $Creds -Namespace ROOT\CIMV2\Security\MicrosoftTpm -Class Win32_Tpm
</code>```

I need to get the TPM of another computer and will require to enter user/pw to do the job. What I need is to validate if the user/name pw is correct and if not, reprompt the Get-Credentials screen.

答:
You can't validate credential with get-credential, instead you can use a try catch statement against the get-wmiobject, something like  </p>

```<code>$c=get-credential
try{
    gwmi -ComputerName comp1 -Credential $c -Class win32_bios
}
catch [System.UnauthorizedAccessException]{
    "wrong credential retry please"
    $c=get-credential
}
</code>```

Body:
How do you Re-prompt credential box if username/pw is incorrect?

Import-Module ActiveDirectory
Write-Host "Please enter Admin credential..."
$Creds = Get-Credential

My script runs everyline after even putting wrong username/pw (w error obvously)

I need Get-Credential to appear everytime the user/pass is invalid so I won't rerun the same script everytime I put in wrong information.

UPDATE:

Heres the sample script:

Import-Module ActiveDirectory
Write-Host "Please enter Admin credential..."
$Creds = Get-Credential
$Tpm = Get-wmiobject -ComputerName $wsid -Credential $Creds -Namespace ROOT\CIMV2\Security\MicrosoftTpm -Class Win32_Tpm

I need to get the TPM of another computer and will require to enter user/pw to do the job. What I need is to validate if the user/name pw is correct and if not, reprompt the Get-Credentials screen.

Body:
You can't validate credential with get-credential, instead you can use a try catch statement against the get-wmiobject, something like

$c=get-credential
try{
    gwmi -ComputerName comp1 -Credential $c -Class win32_bios
}
catch [System.UnauthorizedAccessException]{
    "wrong credential retry please"
    $c=get-credential
}


问:
Error:Unknown host 'dl.google.com' You may need to adjust the proxy settings in Gradle
I am getting this error in android studio 3.0.

Unknown host 'dl.google.com' You may need to adjust the proxy settings in Gradle

I have checked my auto proxy option already.

答:
I was also having the same problem. I tried the following and it's working for me:

Windows

Go to : File > Settings > Appearance & Behavior > System Settings > HTTP Proxy [Under IDE Settings] Enable following option Auto-detect proxy settings

Mac

Go to : Android Studio > Preferences > Appearance & Behavior.. etc

You can also use the test connection button and check with google.com to see if it works or not.

ContentLicense: CC BY-SA 4.0


问:
Getting file path of imported module
How can I get the file path of a module imported in python. I am using Linux (if it matters).

Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.

答:
I could be late here, some of the modules would throw AttributeError when using __file__ attribute to find the path. In those case one can use __path__ to get the path of the module.

```<code>>>> import some_module
>>> somemodule.__path__
['/usr/lib64/python2.7/site-packages/somemodule']
</code>```

Title: Getting file path of imported module

Body:
I could be late here, some of the modules would throw AttributeError when using __file__ attribute to find the path. In those case one can use __path__ to get the path of the module.

>>> import some_module
>>> somemodule.__path__
['/usr/lib64/python2.7/site-packages/somemodule']


问:
How to run pmd through pom without failing the build in Jenkins?
I am running pmd (checkstyle and findbugs as well) via maven plugins in my pom.xml. The build on Jenkins fails due to errors reported by pmd.

The build stage runs 6 modules in parallel and I run the publisher and another stage after that. If pmd fails the whole build fails and stops immediately.

This is a snippet from my pom.xml:

```<code></properties>
    <failOnChecks>true</failOnChecks>
</properties>
<!-- ...... -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-pmd-plugin</artifactId>
    <version>3.8</version>
    <dependencies>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-core</artifactId>
            <version>${version.pmd}</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-java</artifactId>
            <version>${version.pmd}</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-javascript</artifactId>
            <version>${version.pmd}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-jsp</artifactId>
            <version>${version.pmd}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>my.software</groupId>
            <artifactId>build-tools</artifactId>
            <version>${version.build-tools}</version>
        </dependency>
    </dependencies>
    <configuration>
        <rulesets>
            <ruleset>pmd/ruleset.xml</ruleset>
        </rulesets>
        <failOnViolation>${failOnChecks}</failOnViolation>
    </configuration>
    <executions>
        <execution>
            <phase>process-resources</phase>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

The Jenkinsfile has those two stages:

```<code>stage('modules') {
  gitlabCommitStatus('modules') {
    parallel Config.stepsForParallel
  }
}

stage('Jenkins Code Analysis') {
  pmd canRunOnFailed: true, canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '', unHealthy: ''
  checkstyle canRunOnFailed: true, canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '', unHealthy: ''
  //findbugs canComputeNew: false, defaultEncoding: '', excludePattern: '', healthy: '', includePattern: '', pattern: '', unHealthy: ''
}
</code>```

It fails in the build before the second stage can be reached.

The plugins should not stop the pipeline but instead finish it and then fail, and run the publisher afterwards, so I can see the issue in Jenkins.

So far I set failOnViolation via a property, but I am not able to let the build fail at the end. I think I need to check the status there somewhere and call error.

Is there any cleaner way to achieve this?

答:
You can use the goal pmd instead of check which will analyse the code and generate a report but will not fail the build. Then configure Jenkin's PMD Plugin and Static Code Analysis Plugin to mark the build as failed or unstable depending on the number of violations in the report.

Note that changing the goal will also stop failing the Maven build when run manually. We usually configure the maven-pmd-plugin in <pluginManagement> without the <executions> and create two Maven profiles: a default profile that runs maven-pmd-plugin with the goal check and a profile jenkins with the goal pmd. By doing it this way a developer can run the build manually and it will fail when there are PMD violations while it will not fail when run on Jenkins with the profile jenkins.

Body:
I am running pmd (checkstyle and findbugs as well) via maven plugins in my pom.xml. The build on Jenkins fails due to errors reported by pmd.

The build stage runs 6 modules in parallel and I run the publisher and another stage after that. If pmd fails the whole build fails and stops immediately.

This is a snippet from my pom.xml:

</properties>
    <failOnChecks>true</failOnChecks>
</properties>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-pmd-plugin</artifactId>
    <version>3.8</version>
    <dependencies>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-core</artifactId>
            <version>${version.pmd}</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-java</artifactId>
            <version>${version.pmd}</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-javascript</artifactId>
            <version>${version.pmd}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.pmd</groupId>
            <artifactId>pmd-jsp</artifactId>
            <version>${version.pmd}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>my.software</groupId>
            <artifactId>build-tools</artifactId>
            <version>${version.build-tools}</version>
        </dependency>
    </dependencies>
    <configuration>
        <rulesets>
            <ruleset>pmd/ruleset.xml</ruleset>
        </rulesets>
        <failOnViolation>${failOnChecks}</failOnViolation>
    </configuration>
    <executions>
        <execution>
            <phase>process-resources</phase>
            <goals>
                <goal>check</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The Jenkinsfile has those two stages:

stage('modules') {
  gitlabCommitStatus('modules') {
    parallel Config.stepsForParallel
  }
}

stage('Jenkins Code Analysis') {
  pmd canRunOnFailed: true, canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '', unHealthy: ''
  checkstyle canRunOnFailed: true, canComputeNew: false, defaultEncoding: '', healthy: '', pattern: '', unHealthy: ''
  //findbugs canComputeNew: false, defaultEncoding: '', excludePattern: '', healthy: '', includePattern: '', pattern: '', unHealthy: ''
}

It fails in the build before the second stage can be reached.

The plugins should not stop the pipeline but instead finish it and then fail, and run the publisher afterwards, so I can see the issue in Jenkins.

So far I set failOnViolation via a property, but I am not able to let the build fail at the end. I think I need to check the status there somewhere and call error.

Is there any cleaner way to achieve this?


问:
How bind the scroll event on a Live()?
A while ago I've solve an issue for someone that wanted his textarea to grow. I've made a function that listens to the scroll and keyup events of the area and recalculates the number of rows. I wanted to use the code in another project, but there's a problem. The textarea's are not know  To solve this, I'm using live instead of bind, so that future area's will be bound as well.

Now I'm finding that the live executes a lot slower than a bind. I've created a simplified example on jsFiddle. The upper textarea behaves as I want, but newly added ones flicker due to the late signaling (I'm using Chrome).

How can I make the live as fast as the bind? The problem is that the scroll can't be used with a live statement. Is there a way to enable scroll for live? Is there maybe a jQuery event that signals me that a new TextArea has been added, so I can use a bind to add the scroll on the newly created element?

I'm looking forward to your ideas.

EDIT: Changed link to the code. Removed scrollingCode. Added another button to create a different textarea. The problem has to do with 'scroll'. It doesn't fire.

Clarification: I will not know what function will create the textarea's. I see flickering on the dynamically added boxes in Chrome.

For future readers:

In jQuery 1.3.x only the following
  JavaScript events (in addition to
  custom events) could be bound with
  .live(): click, dblclick, keydown,
  keypress, keyup, mousedown, mousemove,
  mouseout, mouseover, and mouseup. As
  of jQuery 1.4 the .live() method
  supports custom events as well as all
  JavaScript events that bubble. As of
  jQuery 1.4.1 even focus and blur work
  with live (mapping to the more
  appropriate, bubbling, events focusin
  and focusout). As of jQuery 1.4.1 the
  hover event can be specified (mapping
  to mouseenter and mouseleave, which,
  in turn, are mapped to mouseover and
  mouseout).

答:
The answer is simple. scroll is what prevents the flickering, because it fires at the very first moment of resize. But scroll has no effect with live (because it doesn't bubble), so your newly created textareas will be resized on keyup but it fires later (thus the flickering).

Update: Of course I can even solve your problem. You just need to ask :) [Demo]

```<code>$('textarea.autoresize').live('keyup', function() {
    var el = $(this);
    if (!el.data("has-scroll")) {
        el.data("has-scroll", true);
        el.scroll(function(){
           resizeTextArea(el);
        });
    }
    resizeTextArea(el);
});
</code>```

The point is, it mixes live with bind. The keyup event, which fires on all elements (because of live), adds the unique scroll event conditionally.

Update 2: Oh, and by the way your whole resizing code can be better written as:

```<code>// resize text area (fixed version of Pointy's)
function resizeTextArea(elem) {
    elem.height(1); elem.scrollTop(0);
    elem.height(elem[0].scrollHeight - elem[0].clientHeight + elem.height())
}
</code>```

Title: How bind the scroll event on a Live()?

Body:
The answer is simple. scroll is what prevents the flickering, because it fires at the very first moment of resize. But scroll has no effect with live (because it doesn't bubble), so your newly created textareas will be resized on keyup but it fires later (thus the flickering).

Update: Of course I can even solve your problem. You just need to ask :) [Demo]

$('textarea.autoresize').live('keyup', function() {
    var el = $(this);
    if (!el.data("has-scroll")) {
        el.data("has-scroll", true);
        el.scroll(function(){
           resizeTextArea(el);
        });
    }
    resizeTextArea(el);
});

The point is, it mixes live with bind. The keyup event, which fires on all elements (because of live), adds the unique scroll event conditionally.

Update 2: Oh, and by the way your whole resizing code can be better written as:

// resize text area (fixed version of Pointy's)
function resizeTextArea(elem) {
    elem.height(1); elem.scrollTop(0);
    elem.height(elem[0].scrollHeight - elem[0].clientHeight + elem.height())
}


问:
Dividing a Java List into sublists based on values
Here's my list:

```<code>myList =
 ["HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","CALL_TO_ACTION"]
</code>```

I would like to have some logic in place that would help me divide myList into below three sub-lists (stored as, say,  List<List<String> subLists):

```<code>["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","CALL_TO_ACTION"]
</code>```

Please note, the number three comes from the number of occurrences of the element "HEADING" (which I could find out using Collections.frequency(myList, "HEADING")).

答:
One way to do this is,

Step 1: Collect all the indices from your myList where "HEADING" appears.

```<code>List<Integer> indexList = new ArrayList<>();
    for(int index = 0; index < list.size(); index++) {
        if(list.get(index).equals("HEADING"))
            indexList.add(index);
    }
</code>```

Step 2: Iterate through this indexList and create sub lists by using current index and the next index.

```<code>for(int builderIndex = 0; builderIndex < indexList.size(); builderIndex++) {
    List<String> test = null;
    if(builderIndex == indexList.size() - 1) {
        test = list.subList(indexList.get(builderIndex), list.size());
    } else {
        test = list.subList(indexList.get(builderIndex), indexList.get(builderIndex + 1));
    }
    System.out.println(test);
}
</code>```

Boundary condition is to check if the current index is equal to one less than the size of the indexList. If yes, then the end index of the sub list would be the size of the original list.

I hope this helps.

Body:
Here's my list:

myList =
 ["HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","CALL_TO_ACTION"]

I would like to have some logic in place that would help me divide myList into below three sub-lists (stored as, say,  List<List<String> subLists):

["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","CALL_TO_ACTION"]

Please note, the number three comes from the number of occurrences of the element "HEADING" (which I could find out using Collections.frequency(myList, "HEADING")).

Body:
One way to do this is,

Step 1: Collect all the indices from your myList where "HEADING" appears.

List<Integer> indexList = new ArrayList<>();
    for(int index = 0; index < list.size(); index++) {
        if(list.get(index).equals("HEADING"))
            indexList.add(index);
    }

Step 2: Iterate through this indexList and create sub lists by using current index and the next index.

for(int builderIndex = 0; builderIndex < indexList.size(); builderIndex++) {
    List<String> test = null;
    if(builderIndex == indexList.size() - 1) {
        test = list.subList(indexList.get(builderIndex), list.size());
    } else {
        test = list.subList(indexList.get(builderIndex), indexList.get(builderIndex + 1));
    }
    System.out.println(test);
}

Boundary condition is to check if the current index is equal to one less than the size of the indexList. If yes, then the end index of the sub list would be the size of the original list.

I hope this helps.


问:
Team Services permissions - how to prevent dashboard access but allow GIT/Code access
is it possible to allow access to Team Services GIT repo but not allow

We have a Project X which we want to allow a user to access teh GIT repo but not see workitems etc

i have created a Team within Project X which is currently just inheriting from "Contributors" - i would like to lock this Team down so that it only has permission to the GIT repo and nothing else

is this possible?

Cheers

答:
You could restrict access to resources that you manage in VSTS by setting the permission state to Deny through a security group/team.

You could deny the builds /Release and so on...  For a comprehensive list of default groups and permissions, see Permission reference for Team Foundation Server.

For restricting users to see work items, you could deny the View work items in this node permission under an Area path:

View work items in this node

If you set the View work items in this node to Deny, the user will not
  be able to see any work items in this area node. A Deny will
  override any implicit allow, even for accounts that are members of
  administrative groups such as Team Foundation Administrators.

More details please refer this link.


问:
How to publish two apps under one IIS Website
I have an Angular2 App, and a Web api.

I currently have one IIS website to publish the each the Angular2 App and Web api.

How can I publish those two apps under one IIS Website?

答:
I have done it by :
Add publish in the root of the website under iis
and add the other application as a web application under the website itself </p>


问:
How to fix overlapping objects
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>
</code>```

答: In Constraint Layouts you can easily overcome overlapping using Blue print adjusting objects. For eg. select one object and drag to the top edge using the point arrow(you will find while dragging) and to the left edge and to the right edge and to the bottom edge and then you can now adjust the position of the object.</p>

Title: How to fix overlapping objects

Body:
I have recently started understanding on how to code in Android Studio and want to set up basic coding. I created 2 number objects and 1 button, 1 plain text object.
Without writing any piece of code, when I click on Run App button on Android Studio and select any Emulator, all the objects stack up on each other. Is there a simple way to fix this?

Following is the text in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication70.MainActivity">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Result"
        android:inputType="numberDecimal"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="223dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="60dp" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberSigned"
        tools:layout_editor_absoluteX="67dp"
        tools:layout_editor_absoluteY="134dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        tools:layout_editor_absoluteX="100dp"
        tools:layout_editor_absoluteY="319dp" />

</android.support.constraint.ConstraintLayout>


问:
Is there any control for achieving truncate the label & show the full text when click the arrow
I have developed the xamarin forms project. I need to truncate the text as default then show the remaining text once the button clicked. Again the text need to be truncated when click the button. It is like "See more" & "See less" functionality. Please anyone suggest me how to achieve this. I have added the screenshot for further reference.

This is how it should look when expanded:

And this is how it should look like when collapsed:

答:
First of all I think you have the carets wrong. The downward caret is usually the one for an expanded control and vice versa. At the end it's up to you, but you should stick to common UX idioms unless you have a very good reason not to.

If one line of preview text would suffice there is quite an easy solution for your issue: You can set the LineBreakMode of the label when your view is clicked:

XAML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Test_SO.ExpansibleControl">
    <ContentView.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding ClickCommand}" />
    </ContentView.GestureRecognizers>
    <ContentView.Content>
        <Grid RowSpacing="10" Padding="10">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="*" />
              <ColumnDefinition Width="Auto" />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
              <RowDefinition Height="Auto"></RowDefinition>
          </Grid.RowDefinitions>
          <Label Text="{Binding Text}" LineBreakMode="{Binding LineBreakMode}" HorizontalOptions="StartAndExpand" />
          <Label Grid.Column="1" Text="{Binding CaretCharacter}" HorizontalOptions="End" />
      </Grid>
  </ContentView.Content>
</ContentView>
</code>```

Just a short outline of what I've done

Added a Grid to ExpansibleControl

Within the grid there is a Label for the text

The Text is bound to the Text property of a viewmodel (see below)

The LineBreakMode is bound to the LineBreakMode of a viewmodel

Furthermore a second Label is added for the caret

This would be an image in a real app, but for the purpose of demonstration a Label will suffice

The Text is bound to the CaretCharacter property of our viewmodel

Furthermore I've added a TapGestureRecognizer and bound its Command to the ClickCommand property of out viewmodel.

Viewmodel

As stated above, the views in our ExpansibleControl are bound to a viewmodel. Here is the respective code

```<code>public class ExpansibleControlViewModel : INotifyPropertyChanged
{
    private char _caretCharacter;
    private bool _isCollapsed;
    private LineBreakMode _lineBreakMode;
    private string _text;

    public ExpansibleControlViewModel()
    {
        ClickCommand = new Command(OnClick);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public char CaretCharacter
    {
        get => _caretCharacter;

        private set
        {
            if (_caretCharacter == value)
            {
                return;
            }

            _caretCharacter = value;
            OnPropertyChanged();
        }
    }

    public Command ClickCommand { get; private set; }

    public bool IsCollapsed
    {
        get => _isCollapsed;

        set
        {
            _isCollapsed = value;

            if (_isCollapsed)
            {
                LineBreakMode = LineBreakMode.TailTruncation;
                CaretCharacter = '<';
            }
            else
            {
                LineBreakMode = LineBreakMode.WordWrap;
                CaretCharacter = 'v';
            }
        }
    }

    public LineBreakMode LineBreakMode
    {
        get => _lineBreakMode;
        private set
        {
            if (_lineBreakMode == value)
            {
                return;
            }

            _lineBreakMode = value;
            OnPropertyChanged();
        }
    }

    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            if (_text == value)
            {
                return;
            }

            _text = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void OnClick()
    {
        ToggleIsCollapsed();
    }

    private void ToggleIsCollapsed()
    {
        IsCollapsed = !IsCollapsed;
    }
}
</code>```

The viewmodel implements INotifyPropertyChanged to inform the view that properties have changed (otherwise the bound views would not be updated when a value changes). Due to CallerMemberNameAttribute the name of the property that calls OnPropertyChanged is automatically passed in the propertyName parameter when the optional parameter is omitted.

IsCollapsed:bool is rather a helper, to simplify the code and reveal intention. When the callback for ClickCommand is called, IsCollapsed is inverted. When it has changed, we set the LineBreakMode and the CaretCharacter to the according values. The setters of those in turn call OnPropertyChanged to raise the PropertyChanged event and the UI updates. By setting the LineBreakMode we "tell" the label either to truncate the text or to break text at words (there are other options).

What if you need a larger portion of text?

There are some options you can go with here.

You could for example fix the LineBreakMode to WordWrap and set the HeightRequest of the Label to a value >0 to show just a portion of the text and to -1 to show the whole text. In that case you could overlay a gradient from transparent to your background color, to fade out text from top to bottom, as a hint that there is more text to show.

Another option is to manipulate the text itself. You could have a writeable property OriginalText and a read-only property Text and just truncate the text "by hand".

Anyway, for both options you will have to take care that it scales across platforms, which may or may not be an easy endeavour.

Body:
First of all I think you have the carets wrong. The downward caret is usually the one for an expanded control and vice versa. At the end it's up to you, but you should stick to common UX idioms unless you have a very good reason not to.

If one line of preview text would suffice there is quite an easy solution for your issue: You can set the LineBreakMode of the label when your view is clicked:

XAML:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Test_SO.ExpansibleControl">
    <ContentView.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding ClickCommand}" />
    </ContentView.GestureRecognizers>
    <ContentView.Content>
        <Grid RowSpacing="10" Padding="10">
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="*" />
              <ColumnDefinition Width="Auto" />
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
              <RowDefinition Height="Auto"></RowDefinition>
          </Grid.RowDefinitions>
          <Label Text="{Binding Text}" LineBreakMode="{Binding LineBreakMode}" HorizontalOptions="StartAndExpand" />
          <Label Grid.Column="1" Text="{Binding CaretCharacter}" HorizontalOptions="End" />
      </Grid>
  </ContentView.Content>
</ContentView>

Just a short outline of what I've done

Added a Grid to ExpansibleControl

Within the grid there is a Label for the text

The Text is bound to the Text property of a viewmodel (see below)

The LineBreakMode is bound to the LineBreakMode of a viewmodel

Furthermore a second Label is added for the caret

This would be an image in a real app, but for the purpose of demonstration a Label will suffice

The Text is bound to the CaretCharacter property of our viewmodel

Furthermore I've added a TapGestureRecognizer and bound its Command to the ClickCommand property of out viewmodel.

Viewmodel

As stated above, the views in our ExpansibleControl are bound to a viewmodel. Here is the respective code

public class ExpansibleControlViewModel : INotifyPropertyChanged
{
    private char _caretCharacter;
    private bool _isCollapsed;
    private LineBreakMode _lineBreakMode;
    private string _text;

    public ExpansibleControlViewModel()
    {
        ClickCommand = new Command(OnClick);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public char CaretCharacter
    {
        get => _caretCharacter;

        private set
        {
            if (_caretCharacter == value)
            {
                return;
            }

            _caretCharacter = value;
            OnPropertyChanged();
        }
    }

    public Command ClickCommand { get; private set; }

    public bool IsCollapsed
    {
        get => _isCollapsed;

        set
        {
            _isCollapsed = value;

            if (_isCollapsed)
            {
                LineBreakMode = LineBreakMode.TailTruncation;
                CaretCharacter = '<';
            }
            else
            {
                LineBreakMode = LineBreakMode.WordWrap;
                CaretCharacter = 'v';
            }
        }
    }

    public LineBreakMode LineBreakMode
    {
        get => _lineBreakMode;
        private set
        {
            if (_lineBreakMode == value)
            {
                return;
            }

            _lineBreakMode = value;
            OnPropertyChanged();
        }
    }

    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            if (_text == value)
            {
                return;
            }

            _text = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void OnClick()
    {
        ToggleIsCollapsed();
    }

    private void ToggleIsCollapsed()
    {
        IsCollapsed = !IsCollapsed;
    }
}

The viewmodel implements INotifyPropertyChanged to inform the view that properties have changed (otherwise the bound views would not be updated when a value changes). Due to CallerMemberNameAttribute the name of the property that calls OnPropertyChanged is automatically passed in the propertyName parameter when the optional parameter is omitted.

IsCollapsed:bool is rather a helper, to simplify the code and reveal intention. When the callback for ClickCommand is called, IsCollapsed is inverted. When it has changed, we set the LineBreakMode and the CaretCharacter to the according values. The setters of those in turn call OnPropertyChanged to raise the PropertyChanged event and the UI updates. By setting the LineBreakMode we "tell" the label either to truncate the text or to break text at words (there are other options).

What if you need a larger portion of text?

There are some options you can go with here.

You could for example fix the LineBreakMode to WordWrap and set the HeightRequest of the Label to a value >0 to show just a portion of the text and to -1 to show the whole text. In that case you could overlay a gradient from transparent to your background color, to fade out text from top to bottom, as a hint that there is more text to show.

Another option is to manipulate the text itself. You could have a writeable property OriginalText and a read-only property Text and just truncate the text "by hand".

Anyway, for both options you will have to take care that it scales across platforms, which may or may not be an easy endeavour.


问:
Background just stops after adding elements with jQuery
I have a problem with my website. I add a variable amount of elements to a page based on a JSON file. If there are too many, the background color just stops.
However, it seems like the problem only occurs in Firefox and Edge. It looks fine on Chrome.

This is the general CSS code for my layout:

```<code>body{
    font-family: 'Roboto', sans-serif;
    display: grid;
    grid-template-rows: 1fr 20px;
    grid-template-columns: 13% 87%;
    height: 100vh;
    grid-template-areas:
    "sidebar content"
    "footer footer";
}

main{
    background-color:#D0CABF;
    grid-area: content;
    text-align: center;
    display: grid;
    grid-template-rows: 30% 1fr 20%;
    grid-template-columns: 100%;
    grid-template-areas:
    "top"
    "mid"
    "bottom";
 }
</code>```

This is the JS code:

```<code>$.getJSON('/data/risks.json', function(data) {
var html = '';
$.each(data.risk, function(key, value){
    html += '<div class="cardS">';
    html += '<br><p><b>'+value.name+'</b><br><br>'+value.description+'<br><p class="hiddenID">'+value.id+'</p></p>';
    html += '</div>';
 });
$('#jsondata').html(html);
});
</code>```

I've tried to set the position of the body to "fixed" but it seems like this prevents scrolling. I'm not sure how to solve this problem...

Here is a screenshot:

Thanks!

答:
This is because the block inside the main are floated and may be there is not clearfix CSS for it OR clear CSS to clear the floated blocks.

You may use

```<code>.clear{clear: both; display: block;}
</code>```

Body:
I have a problem with my website. I add a variable amount of elements to a page based on a JSON file. If there are too many, the background color just stops.
However, it seems like the problem only occurs in Firefox and Edge. It looks fine on Chrome.

This is the general CSS code for my layout:

body{
    font-family: 'Roboto', sans-serif;
    display: grid;
    grid-template-rows: 1fr 20px;
    grid-template-columns: 13% 87%;
    height: 100vh;
    grid-template-areas:
    "sidebar content"
    "footer footer";
}

main{
    background-color:#D0CABF;
    grid-area: content;
    text-align: center;
    display: grid;
    grid-template-rows: 30% 1fr 20%;
    grid-template-columns: 100%;
    grid-template-areas:
    "top"
    "mid"
    "bottom";
 }

This is the JS code:

$.getJSON('/data/risks.json', function(data) {
var html = '';
$.each(data.risk, function(key, value){
    html += '
';
    html += '

'+value.name+'

'+value.description+'

'+value.id+'

';
    html += '
';
 });
$('#jsondata').html(html);
});

I've tried to set the position of the body to "fixed" but it seems like this prevents scrolling. I'm not sure how to solve this problem...

Here is a screenshot:

Thanks!

Body:
This is because the block inside the main are floated and may be there is not clearfix CSS for it OR clear CSS to clear the floated blocks.

You may use

.clear{clear: both; display: block;}


问:
GMSAutocompleteViewController iOS, How can I get different color for text in searchControllers?
I'm implementing the default GMSAutocompleteViewController for my app. But couldn't find any documentation or guide to change the color of text in the searchController's textField to white. right now it seems black

I want it be white so the text is more visible.

UPDATE : I'm using following code to change to change the 'Cancel' button color to white as well but it's the same.

```<code>let autocompleteController = GMSAutocompleteViewController()
autocompleteController.tintColor = .white
</code>```

答:
I used this code :

Swift 2: as mentioned in the comments by @Ercell0

GMSAutocompleteViewController iOS, how to change the text color in the searchBar

Swift 4.0:

```<code>let searchBarTextAttributes: [String : AnyObject] = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white, NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: UIFont.systemFontSize)]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes
</code>```

Swift 4.2. & above:

```<code>let autocompleteController = GMSAutocompleteViewController()
let searchBarTextAttributes: [NSAttributedString.Key : AnyObject] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.white, NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): UIFont.systemFont(ofSize: UIFont.systemFontSize)]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes
</code>```

Body:
I'm implementing the default GMSAutocompleteViewController for my app. But couldn't find any documentation or guide to change the color of text in the searchController's textField to white. right now it seems black

I want it be white so the text is more visible.

UPDATE : I'm using following code to change to change the 'Cancel' button color to white as well but it's the same.

let autocompleteController = GMSAutocompleteViewController()
autocompleteController.tintColor = .white

Body:
I used this code :

Swift 2: as mentioned in the comments by @Ercell0

GMSAutocompleteViewController iOS, how to change the text color in the searchBar

Swift 4.0:

let searchBarTextAttributes: [String : AnyObject] = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white, NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: UIFont.systemFontSize)]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes

Swift 4.2. & above:

let autocompleteController = GMSAutocompleteViewController()
let searchBarTextAttributes: [NSAttributedString.Key : AnyObject] = [NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.white, NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): UIFont.systemFont(ofSize: UIFont.systemFontSize)]
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes


问:
Optimal performance for two dim array to datatable conversion
I was looking for an optimized method to convert a square array of type

double[ , ]

to DataTable

I looked up over the internet and couldn't find a way faster than the currently implemented in my method which depends on two nested for loops.

The problem is that the performance is very bad. My input array could be any where from 500 to 15000 elements in each dimension. (Math can be scary)...

This means that it could take ages for the conversion to complete with the current method.

I was thinking about using some unmanaged code or even assembly code to improve the performance but I didn't know how to do it..

My Current code is this...

```<code>// helper method to get row as a string array
private static string[] GetRowFromArray(double[,] array, int column )

{

int dim = array.GetUpperBound(0) +1;

string[] row = new string[dim];

for(int i = 0; i < dim; i++)

{

    row[i] = array[i, column].ToString();

}

return row;

}

//the static extension method used to convert the array to datatable

public static DataTable ToDataTable(this double[,] array)

{

DataTable dt = new DataTable();

int rowsCount = array.GetUpperBound(0) + 1;

int colsCount = array.GetUpperBound(1) + 1;

int i = 0;

while (i < colsCount)

{

   dt.Columns.Add(); i++;

}

int ii = 0;

while (ii < rowsCount)

{

    string[] a = GetRowFromArray(array, ii);

    dt.Rows.Add(a);

    ii++;

}

return dt;

}
</code>```

Any ideas on how can we optimize this to make it run faster.

Just a side note, the array is square array, so  ColumnsCount = RowsCount

And so many thanks for any help.

答:
You can optimize the code by...

Eliminating DataTable (just use the array directly).

Using jagged arrays and eliminating double to string conversions.

Using DataTable is by far the most significant contributor to poor performance.  But, let's assume you must use DataTable.  In that case, your main problem is the need to construct a single dimension array to provide to the DataRowCollection.Add() method.

By using jagged arrays, you can provide the single dimension array directly.  This speeds up the code almost 7x.

```<code>Original poster's code ran in 15679 msec.
My code ran in 2261 msec.
My code is 6.94x faster.
</code>```

I believe you transposed the rows and columns in your GetRowFromArray function.  This is apparent if the multi-dimension array is not square.  I realize you said it is, but I wrote my code with separate lengths for x and y.

Here's my code.

```<code>using System;
using System.Data;
using System.Diagnostics;

namespace DataTable
{
    public class Program
    {
        private const int _xLength = 15000;
        private const int _yLength = 1000;
        private static Random _random;

        public static void Main(string[] args)
        {
            double[,] array = new double[_xLength, _yLength];
            _random = new Random();
            for (int x = 0; x < _xLength; x++)
            {
                for (int y = 0; y < _yLength; y++)
                {
                    array[x, y] = _random.NextDouble();
                }
            }
            Stopwatch stopwatch = Stopwatch.StartNew();
            OriginalPoster(array);
            stopwatch.Stop();
            TimeSpan originalCodeDuration = stopwatch.Elapsed;
            Console.WriteLine($"Original poster's code ran in {originalCodeDuration.TotalMilliseconds:0} msec.");
            array = null;
            GC.Collect();
            double[][] jaggedArray = new double[_xLength][];
            for (int x = 0; x < _xLength; x++)
            {
                jaggedArray[x] = new double[_yLength];
                for (int y = 0; y < _yLength; y++)
                {
                    jaggedArray[x][y] = _random.NextDouble();
                }
            }
            stopwatch.Restart();
            Mine(jaggedArray);
            stopwatch.Stop();
            TimeSpan myCodeDuration = stopwatch.Elapsed;
            Console.WriteLine($"My code ran in {myCodeDuration.TotalMilliseconds:0} msec.");
            double speedUp = originalCodeDuration.TotalMilliseconds / myCodeDuration.TotalMilliseconds;
            Console.WriteLine($"My code is {speedUp:0.00}x faster.");
        }

        private static void OriginalPoster(double[,] array)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            int rowsCount = array.GetUpperBound(0) + 1;
            int colsCount = array.GetUpperBound(1) + 1;
            int i = 0;
            while (i < colsCount)
            {
                dt.Columns.Add(); i++;
            }
            int ii = 0;
            while (ii < rowsCount)
            {
                string[] a = GetRowFromArray(array, ii);
                dt.Rows.Add(a);
                ii++;
            }
        }

        private static string[] GetRowFromArray(double[,] array, int rowNumber)
        {
            int dim = array.GetUpperBound(1) + 1;
            string[] row = new string[dim];
            for (int i = 0; i < dim; i++)
            {
                row[i] = array[rowNumber, i].ToString();
            }
            return row;
        }

        private static void Mine(double[][] Array)
        {
            System.Data.DataTable dataTable = new System.Data.DataTable();
            for (int y = 0; y < _yLength; y++)
            {
                dataTable.Columns.Add();
            }
            for (int x = 0; x < _xLength; x++)
            {
                dataTable.Rows.Add(Array[x]);
            }
        }
    }
}
</code>```

Body:
I was looking for an optimized method to convert a square array of type

double[ , ]

to DataTable

I looked up over the internet and couldn't find a way faster than the currently implemented in my method which depends on two nested for loops.

The problem is that the performance is very bad. My input array could be any where from 500 to 15000 elements in each dimension. (Math can be scary)...

This means that it could take ages for the conversion to complete with the current method.

I was thinking about using some unmanaged code or even assembly code to improve the performance but I didn't know how to do it..

My Current code is this...

// helper method to get row as a string array
private static string[] GetRowFromArray(double[,] array, int column )

{

int dim = array.GetUpperBound(0) +1;

string[] row = new string[dim];

for(int i = 0; i < dim; i++)

{

    row[i] = array[i, column].ToString();

}

return row;

}

//the static extension method used to convert the array to datatable

public static DataTable ToDataTable(this double[,] array)

{

DataTable dt = new DataTable();

int rowsCount = array.GetUpperBound(0) + 1;

int colsCount = array.GetUpperBound(1) + 1;

int i = 0;

while (i < colsCount)

{

   dt.Columns.Add(); i++;

}

int ii = 0;

while (ii < rowsCount)

{

    string[] a = GetRowFromArray(array, ii);

    dt.Rows.Add(a);

    ii++;

}

return dt;

}

Any ideas on how can we optimize this to make it run faster.

Just a side note, the array is square array, so  ColumnsCount = RowsCount

And so many thanks for any help.

Body:
You can optimize the code by...

Eliminating DataTable (just use the array directly).

Using jagged arrays and eliminating double to string conversions.

Using DataTable is by far the most significant contributor to poor performance.  But, let's assume you must use DataTable.  In that case, your main problem is the need to construct a single dimension array to provide to the DataRowCollection.Add() method.

By using jagged arrays, you can provide the single dimension array directly.  This speeds up the code almost 7x.

Original poster's code ran in 15679 msec.
My code ran in 2261 msec.
My code is 6.94x faster.

I believe you transposed the rows and columns in your GetRowFromArray function.  This is apparent if the multi-dimension array is not square.  I realize you said it is, but I wrote my code with separate lengths for x and y.

Here's my code.

using System;
using System.Data;
using System.Diagnostics;

namespace DataTable
{
    public class Program
    {
        private const int _xLength = 15000;
        private const int _yLength = 1000;
        private static Random _random;

        public static void Main(string[] args)
        {
            double[,] array = new double[_xLength, _yLength];
            _random = new Random();
            for (int x = 0; x < _xLength; x++)
            {
                for (int y = 0; y < _yLength; y++)
                {
                    array[x, y] = _random.NextDouble();
                }
            }
            Stopwatch stopwatch = Stopwatch.StartNew();
            OriginalPoster(array);
            stopwatch.Stop();
            TimeSpan originalCodeDuration = stopwatch.Elapsed;
            Console.WriteLine($"Original poster's code ran in {originalCodeDuration.TotalMilliseconds:0} msec.");
            array = null;
            GC.Collect();
            double[][] jaggedArray = new double[_xLength][];
            for (int x = 0; x < _xLength; x++)
            {
                jaggedArray[x] = new double[_yLength];
                for (int y = 0; y < _yLength; y++)
                {
                    jaggedArray[x][y] = _random.NextDouble();
                }
            }
            stopwatch.Restart();
            Mine(jaggedArray);
            stopwatch.Stop();
            TimeSpan myCodeDuration = stopwatch.Elapsed;
            Console.WriteLine($"My code ran in {myCodeDuration.TotalMilliseconds:0} msec.");
            double speedUp = originalCodeDuration.TotalMilliseconds / myCodeDuration.TotalMilliseconds;
            Console.WriteLine($"My code is {speedUp:0.00}x faster.");
        }

        private static void OriginalPoster(double[,] array)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            int rowsCount = array.GetUpperBound(0) + 1;
            int colsCount = array.GetUpperBound(1) + 1;
            int i = 0;
            while (i < colsCount)
            {
                dt.Columns.Add(); i++;
            }
            int ii = 0;
            while (ii < rowsCount)
            {
                string[] a = GetRowFromArray(array, ii);
                dt.Rows.Add(a);
                ii++;
            }
        }

        private static string[] GetRowFromArray(double[,] array, int rowNumber)
        {
            int dim = array.GetUpperBound(1) + 1;
            string[] row = new string[dim];
            for (int i = 0; i < dim; i++)
            {
                row[i] = array[rowNumber, i].ToString();
            }
            return row;
        }

        private static void Mine(double[][] Array)
        {
            System.Data.DataTable dataTable = new System.Data.DataTable();
            for (int y = 0; y < _yLength; y++)
            {
                dataTable.Columns.Add();
            }
            for (int x = 0; x < _xLength; x++)
            {
                dataTable.Rows.Add(Array[x]);
            }
        }
    }
}