Title: Reshaping multiple groups of columns in a data frame from wide to long

Body:
I am working with air-quality data. I tried to reshape the data frame from wide to long using melt function. Here is the data: Elev stands for Elevation, Obs for observation and US3, DK1, DE1 are models, where lm and ul represents first and third quantiles.

Elev      Obs       lm       ul      US3       lm       ul      DK1       lm       ul
1    0 37.74289 34.33422 41.27840 38.82037 35.35241 42.30042 49.31111 45.00134 53.90968
2  100 38.14076 34.71842 41.36560 39.82727 36.49086 43.22209 50.46545 45.79068 55.44664
3  250 39.31056 35.98180 42.50011 40.94909 37.70768 44.40232 50.79818 45.76405 55.54795
4  500 41.03098 37.78005 44.02544 42.54909 39.25627 45.72927 51.24182 46.76091 55.88568
5  750 43.57307 40.52575 46.92804 43.48000 40.55918 46.62914 51.90364 47.40586 56.37514
       DE1       lm       ul
1 41.15185 37.81824 44.62509
2 40.89455 37.38491 44.34759
3 40.93455 37.33400 44.32573
4 41.26727 37.90150 44.68568
5 43.04545 40.04541 46.12386

I used

 melt(f,id.vars=c("Elev", "lm","um"),measure.vars=c("US3", "DK1", "DE1","Obs" ))

and I got

Elev       lm       ul      variable    value
   0 34.33422 41.27840           US3 38.82037
 100 34.71842 41.36560           US3 39.82727
 250 35.98180 42.50011           US3 40.94909
 500 37.78005 44.02544           US3 42.54909
 750 40.52575 46.92804           US3 43.48000
   0 34.33422 41.27840           DK1 49.31111
 100 34.71842 41.36560           DK1 50.46545
 250 35.98180 42.50011           DK1 50.79818
 500 37.78005 44.02544           DK1 51.24182
 750 40.52575 46.92804           DK1 51.90364
   0 34.33422 41.27840           DE1 41.15185
 100 34.71842 41.36560           DE1 40.89455
 250 35.98180 42.50011           DE1 40.93455
 500 37.78005 44.02544           DE1 41.26727
 750 40.52575 46.92804           DE1 43.04545
   0 34.33422 41.27840           Obs 37.74289
 100 34.71842 41.36560           Obs 38.14076
 250 35.98180 42.50011           Obs 39.31056
 500 37.78005 44.02544           Obs 41.03098
 750 40.52575 46.92804           Obs 43.57307

As it can clearly be seen the values of lm and ul are repeated for every elevation. How can I have a long format without the repetition of those values?
My expected result is:

Elev    lm      ul      variable  value
  0 35.35241 42.30042      US3 38.82037
100 36.49086 43.22209      US3 39.82727
250 37.70768 44.40232      US3 40.94909
500 39.25627 45.72927      US3 42.54909
750 40.55918 46.62914      US3 43.48000
  0 45.00134 53.90968      DK1 49.31111
100 45.79068 55.44664      DK1 50.46545
250 45.76405 55.54795      DK1 50.79818
500 46.76091 55.88568      DK1 51.24182
750 47.40586 56.37514      DK1 51.90364
  0 37.81824 44.62509      DE1 41.15185
100 37.38491 44.34759      DE1 40.89455
250 37.33400 44.32573      DE1 40.93455
500 37.90150 44.68568      DE1 41.26727
750 40.04541 46.12386      DE1 43.04545
  0 34.33422 41.27840      Obs 37.74289
100 34.71842 41.36560      Obs 38.14076
250 35.98180 42.50011      Obs 39.31056
500 37.78005 44.02544      Obs 41.03098
750 40.52575 46.92804      Obs 43.57307

Body:
The recent versions of data.table allow to melt multiple columns simultaneously

An additional difficulty is that the data frame contains columns with the same name. Thanks to the patterns() function, it is not required to rename the columns beforehand.

library(data.table) # version 1.10.4 used here

# create vector of the names of data groups - in the order they appear in the DF !
dg_names <- c("Obs", "US3", "DK1", "DE1")

# coerce DF to data.table and melt using the patterns() function to identify columns
molten <- melt(setDT(DF),
               measure.vars = patterns(paste(dg_names, collapse = "|"), "lm", "ul"),
               value.name = c("value", "lm", "ul"))

# rename variable column to something meaningful
molten[, variable := factor(variable, labels = dg_names)]

Despite the different order of columns and rows, the result is as expected by the OP:

molten
#    Elev variable    value       lm       ul
# 1:    0      Obs 37.74289 34.33422 41.27840
# 2:  100      Obs 38.14076 34.71842 41.36560
# 3:  250      Obs 39.31056 35.98180 42.50011
# 4:  500      Obs 41.03098 37.78005 44.02544
# 5:  750      Obs 43.57307 40.52575 46.92804
# 6:    0      US3 38.82037 35.35241 42.30042
# 7:  100      US3 39.82727 36.49086 43.22209
# 8:  250      US3 40.94909 37.70768 44.40232
# 9:  500      US3 42.54909 39.25627 45.72927
#10:  750      US3 43.48000 40.55918 46.62914
#11:    0      DK1 49.31111 45.00134 53.90968
#12:  100      DK1 50.46545 45.79068 55.44664
#13:  250      DK1 50.79818 45.76405 55.54795
#14:  500      DK1 51.24182 46.76091 55.88568
#15:  750      DK1 51.90364 47.40586 56.37514
#16:    0      DE1 41.15185 37.81824 44.62509
#17:  100      DE1 40.89455 37.38491 44.34759
#18:  250      DE1 40.93455 37.33400 44.32573
#19:  500      DE1 41.26727 37.90150 44.68568
#20:  750      DE1 43.04545 40.04541 46.12386

Data

DF <- structure(list(Elev = c(0L, 100L, 250L, 500L, 750L), Obs = c(37.74289,
38.14076, 39.31056, 41.03098, 43.57307), lm = c(34.33422, 34.71842,
35.9818, 37.78005, 40.52575), ul = c(41.2784, 41.3656, 42.50011,
44.02544, 46.92804), US3 = c(38.82037, 39.82727, 40.94909, 42.54909,
43.48), lm = c(35.35241, 36.49086, 37.70768, 39.25627, 40.55918
), ul = c(42.30042, 43.22209, 44.40232, 45.72927, 46.62914),
    DK1 = c(49.31111, 50.46545, 50.79818, 51.24182, 51.90364),
    lm = c(45.00134, 45.79068, 45.76405, 46.76091, 47.40586),
    ul = c(53.90968, 55.44664, 55.54795, 55.88568, 56.37514),
    DE1 = c(41.15185, 40.89455, 40.93455, 41.26727, 43.04545),
    lm = c(37.81824, 37.38491, 37.334, 37.9015, 40.04541), ul = c(44.62509,
    44.34759, 44.32573, 44.68568, 46.12386)), .Names = c("Elev",
"Obs", "lm", "ul", "US3", "lm", "ul", "DK1", "lm", "ul", "DE1",
"lm", "ul"), row.names = c(NA, -5L), class = "data.frame")


来源: stackexchange

问:
Set "hide" attribute on folders in windows OS?
Trying to hide folder without success. I've found this :

```<code>import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:\Dir\folder1', 2)
</code>```

but it did not work for me. What am I doing wrong?

答:
Try this code:</p>

```<code>import os
os.system("attrib +h " + "your file name")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to hide folder without success. I've found this :

import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:\Dir\folder1', 2)

but it did not work for me. What am I doing wrong?

Body:
Try this code:

import os
os.system("attrib +h " + "your file name")


问:
Why does the compiler ask for the day,month and year of joining simultaneously?
```<code> #include <stdio.h>
 #include <conio.h>
 struct personal
{
    char name[20];
    int day;
    char month[12];
    int year;
    float salary;
};
 void main()
{
        struct personal person;/*Name of structure is personal*/
        printf("Enter name of employee");
        scanf("%s",&person.name);
        printf("\nEnter day of joining");
        scanf("%d",&person.day);
        printf("\nEnter month of joining");
        scanf("%s",&person.month);
        printf("\nEnter year of joining");
        scanf("%d",&person.year);
        printf("\nEnter salary of employee");
        scanf("%f",&person.salary);
        printf("\nThe details are as follows\n");
        printf("Name of employee-%s\n",person.name);
              ("Date of joining-%d %s
                     %d\n",person.day,person.month,person.year);
               ("Salary of employee-$%f",person.salary);
     getch();}
</code>```

Is the above code correct?What's the best way to learn structures in C?
How does one combine structures and functions?

答:
The reason that its asking all three at same time because while entering the name of the employee, you are entering "a blank space", but name is a char array and if you use scanf, it will skip other inputs.
So better to use "gets()" function. So the code would look like-  </p>

```<code> #include <stdio.h>
 #include <conio.h>
 struct personal
{
    char name[20];
    int day;
    char month[12];
    int year;
    float salary;
};
 void main()
{
        struct personal person;/*Name of structure is personal*/
        printf("Enter name of employee");
        /*Replace this line - scanf("%s",&person.name); by*/
        gets(person.name);
        printf("\nEnter day of joining");
        scanf("%d",&person.day);
        printf("\nEnter month of joining");
        scanf("%s",&person.month);
        printf("\nEnter year of joining");
        scanf("%d",&person.year);
        printf("\nEnter salary of employee");
        scanf("%f",&person.salary);
        printf("\nThe details are as follows\n");
        printf("Name of employee-%s\n",person.name);
              ("Date of joining-%d %s
                     %d\n",person.day,person.month,person.year);
               ("Salary of employee-$%f",person.salary);
     getch();}
</code>```

Body:
 #include <stdio.h>
 #include <conio.h>
 struct personal
{
    char name[20];
    int day;
    char month[12];
    int year;
    float salary;
};
 void main()
{
        struct personal person;/*Name of structure is personal*/
        printf("Enter name of employee");
        scanf("%s",&person.name);
        printf("\nEnter day of joining");
        scanf("%d",&person.day);
        printf("\nEnter month of joining");
        scanf("%s",&person.month);
        printf("\nEnter year of joining");
        scanf("%d",&person.year);
        printf("\nEnter salary of employee");
        scanf("%f",&person.salary);
        printf("\nThe details are as follows\n");
        printf("Name of employee-%s\n",person.name);
              ("Date of joining-%d %s
                     %d\n",person.day,person.month,person.year);
               ("Salary of employee-$%f",person.salary);
     getch();}

Is the above code correct?What's the best way to learn structures in C?
How does one combine structures and functions?

Body:
The reason that its asking all three at same time because while entering the name of the employee, you are entering "a blank space", but name is a char array and if you use scanf, it will skip other inputs.
So better to use "gets()" function. So the code would look like-

 #include <stdio.h>
 #include <conio.h>
 struct personal
{
    char name[20];
    int day;
    char month[12];
    int year;
    float salary;
};
 void main()
{
        struct personal person;/*Name of structure is personal*/
        printf("Enter name of employee");
        /*Replace this line - scanf("%s",&person.name); by*/
        gets(person.name);
        printf("\nEnter day of joining");
        scanf("%d",&person.day);
        printf("\nEnter month of joining");
        scanf("%s",&person.month);
        printf("\nEnter year of joining");
        scanf("%d",&person.year);
        printf("\nEnter salary of employee");
        scanf("%f",&person.salary);
        printf("\nThe details are as follows\n");
        printf("Name of employee-%s\n",person.name);
              ("Date of joining-%d %s
                     %d\n",person.day,person.month,person.year);
               ("Salary of employee-$%f",person.salary);
     getch();}


问:
How to add a space between images in a CSS image slideshow?
EDIT:

Good progress... By updating the following code, I almost get exactly what I want to achieve, but I don't understand exactly why it almost works. Spacing both sides during transition, spacing hidden after transition, but with a slight amount of clipping of image: https://codepen.io/anon/pen/LWqPJB

```<code>body {
     margin: -6%;
}
div#slider {
     overflow: hidden;
}
div#slider figure img {
     width: 18%;
     float: left;
     padding-left: 1%;
     padding-right: 1%;
}
</code>```

Although, it's not a perfect solution, the second alternative that seems to do the job is:

```<code>div#slider {
    margin-left: -6%;
    margin-right: -6%;
    overflow: hidden;
}
div#slider figure img {
    width: 18%;
    margin-left: 1%;
    margin-right: 1%;
    float: left;
}
</code>```

Problem

I'm implementing a simple image slideshow in a webpage using only HTML and CSS. The code I am starting with is below and at https://codepen.io/anon/pen/wJRVwP

Currently each slide follows the next with no space between images (image 1). However, I'm trying to add a 100px space between each image that is only visible during the transition. So attempting to add a gap, I change the CSS code below;

from:

```<code>div#slider figure img { width: 20%; float: left;}
</code>```

(demo 1: https://codepen.io/anon/pen/wJRVwP)

to:

```<code>div#slider figure img { width: 20%; float: left; padding-left: 100px;}
</code>```

(demo 2: https://codepen.io/anon/pen/vxvoNy)

The result of changing the code adds a 100px space between all images, but, the code change introduces a new problem — images no longer align and progressively get worse after each slide change (image 2).

Question

How can I achieve a space between images and fix this? In code, how
  can I change the CSS code to add a 100px space between each image, and keep
  all images aligned during and after transition?

Images

demo 1 during transition.

demo 1 after transition.

required outcome.

Code

https://codepen.io/anon/pen/wJRVwP

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider">
  <figure>
    <img src="austin-fireworks.jpg" alt>
    <img src="taj-mahal_copy.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
    <img src="ankor-wat.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
  </figure>
</div></code>```

答:
```<code><base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider">
<figure>
<img src="austin-fireworks.jpg" alt>
<img src="taj-mahal_copy.jpg" alt>
<img src="austin-fireworks.jpg" alt>
<img src="ankor-wat.jpg" alt>
<img src="austin-fireworks.jpg" alt>
</figure>
</div>
<style>
    @keyframes slidy {
        0% { left: 0%; }
        20% { left: 0%; }
        25% { left: -100%;}
        45% { left: -100%; }
        50% { left: -200%; }
        70% { left: -200%; }
        75% { left: -300%; }
        95% { left: -300%; }
        100% { left: -400%;}
    }
    body { margin: 0; }
    div#slider { overflow: hidden;}
    div#slider figure img {
        width: 19%; float: left;margin-left:0.5%;margin-right:0.5%;
    }
    div#slider figure {
      position: relative;
      width: 500%;
      margin: 0px;
      left: 0;
      text-align: left;
      font-size: 0;
      animation: 20s slidy infinite;

    }

</style>
</code>```

Body:
EDIT:

Good progress... By updating the following code, I almost get exactly what I want to achieve, but I don't understand exactly why it almost works. Spacing both sides during transition, spacing hidden after transition, but with a slight amount of clipping of image: https://codepen.io/anon/pen/LWqPJB

body {
     margin: -6%;
}
div#slider {
     overflow: hidden;
}
div#slider figure img {
     width: 18%;
     float: left;
     padding-left: 1%;
     padding-right: 1%;
}

Although, it's not a perfect solution, the second alternative that seems to do the job is:

div#slider {
    margin-left: -6%;
    margin-right: -6%;
    overflow: hidden;
}
div#slider figure img {
    width: 18%;
    margin-left: 1%;
    margin-right: 1%;
    float: left;
}

Problem

I'm implementing a simple image slideshow in a webpage using only HTML and CSS. The code I am starting with is below and at https://codepen.io/anon/pen/wJRVwP

Currently each slide follows the next with no space between images (image 1). However, I'm trying to add a 100px space between each image that is only visible during the transition. So attempting to add a gap, I change the CSS code below;

from:

div#slider figure img { width: 20%; float: left;}

(demo 1: https://codepen.io/anon/pen/wJRVwP)

to:

div#slider figure img { width: 20%; float: left; padding-left: 100px;}

(demo 2: https://codepen.io/anon/pen/vxvoNy)

The result of changing the code adds a 100px space between all images, but, the code change introduces a new problem — images no longer align and progressively get worse after each slide change (image 2).

Question

How can I achieve a space between images and fix this? In code, how
  can I change the CSS code to add a 100px space between each image, and keep
  all images aligned during and after transition?

Images

demo 1 during transition.

demo 1 after transition.

required outcome.

Code

https://codepen.io/anon/pen/wJRVwP

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}

<base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">


问:
How to truncate some tables?
I am trying to TRUNCATE some TABLES in my DB in MySQL, but when I try to do it, there is an error.

Please have in count that I've set the FOREIGN_KEY_CHECK to 0, like says in line 2 and returned back to 1 in line 9

Why and how to solve it?

Here my query

Here is the error I got

Adding tables structure

```<code>--
-- Table structure for table `metadata`
--

CREATE TABLE IF NOT EXISTS `metadata` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user` int(11) NOT NULL,
  `date` date NOT NULL,
  `time` time NOT NULL,
  `ip` varchar(15) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user` (`user`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=54 ;

-- --------------------------------------------------------

--
-- Table structure for table `patients`
--

CREATE TABLE IF NOT EXISTS `patients` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `nss` bigint(11) DEFAULT NULL,
  `name_1st` varchar(50) NOT NULL,
  `name_2nd` varchar(30) DEFAULT NULL,
  `last_name_1st` varchar(50) NOT NULL,
  `last_name_2nd` varchar(30) DEFAULT NULL,
  `clinic` int(11) DEFAULT NULL,
  `attached` text,
  `valid` tinyint(1) DEFAULT NULL,
  `status` tinyint(2) NOT NULL,
  `metadata` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `status` (`status`),
  KEY `clinic` (`clinic`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;

-- --------------------------------------------------------

--
-- Table structure for table `queue`
--

CREATE TABLE IF NOT EXISTS `queue` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `consecutive` int(11) NOT NULL,
  `creat_day` date NOT NULL,
  `patient` bigint(20) DEFAULT NULL,
  `status` tinyint(2) DEFAULT NULL,
  `metadata` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `consecutive` (`consecutive`,`creat_day`),
  KEY `status` (`status`),
  KEY `metadata` (`metadata`),
  KEY `patient_ident` (`patient`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;

-- --------------------------------------------------------

--
-- Table structure for table `triage_regs`
--

CREATE TABLE IF NOT EXISTS `triage_regs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `queue` bigint(20) NOT NULL,
  `patient` bigint(20) NOT NULL,
  `cod_color` int(11) NOT NULL,
  `medicines` text NOT NULL,
  `time_start_triage` time NOT NULL,
  `time_end_triage` time NOT NULL,
  `tens_arterial` varchar(7) NOT NULL,
  `frec_card` int(3) NOT NULL,
  `frec_resp` int(3) NOT NULL,
  `temp` int(3) NOT NULL,
  `gluc` int(3) NOT NULL,
  `esc_glasgown` int(3) NOT NULL,
  `atention` varchar(500) NOT NULL DEFAULT 'n/a',
  `questions` longtext,
  `exp_fis` longtext,
  `aux_diag` longtext,
  `pron` longtext,
  `trat` longtext,
  `diag` longtext,
  `status` tinyint(2) NOT NULL,
  `metadata` bigint(20) DEFAULT NULL,
  `metadata2` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `patient` (`patient`),
  KEY `status` (`status`),
  KEY `metadata2` (`metadata2`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
</code>```

答:
It is exactly as the error says: You cannot truncate a table referenced BY a foreign key constraint, being it a WITH CHECK constraint or not. This is because TRUNCATE forces the table to be dropped and then created again, and obviously a table which is defined as "master" in a foreign key relationship cannot be dropped, even temporarily.

So what you have to do is first drop all FK constraints which reference your table, then TRUNCATE it, then recreate the FK constraints.

ContentLicense: CC BY-SA 4.0

Title: How to truncate some tables?

Body:
I am trying to TRUNCATE some TABLES in my DB in MySQL, but when I try to do it, there is an error.

Please have in count that I've set the FOREIGN_KEY_CHECK to 0, like says in line 2 and returned back to 1 in line 9

Why and how to solve it?

Here my query

Here is the error I got

Adding tables structure

--
-- Table structure for table `metadata`
--

CREATE TABLE IF NOT EXISTS `metadata` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user` int(11) NOT NULL,
  `date` date NOT NULL,
  `time` time NOT NULL,
  `ip` varchar(15) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user` (`user`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=54 ;

-- --------------------------------------------------------

--
-- Table structure for table `patients`
--

CREATE TABLE IF NOT EXISTS `patients` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `nss` bigint(11) DEFAULT NULL,
  `name_1st` varchar(50) NOT NULL,
  `name_2nd` varchar(30) DEFAULT NULL,
  `last_name_1st` varchar(50) NOT NULL,
  `last_name_2nd` varchar(30) DEFAULT NULL,
  `clinic` int(11) DEFAULT NULL,
  `attached` text,
  `valid` tinyint(1) DEFAULT NULL,
  `status` tinyint(2) NOT NULL,
  `metadata` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `status` (`status`),
  KEY `clinic` (`clinic`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;

-- --------------------------------------------------------

--
-- Table structure for table `queue`
--

CREATE TABLE IF NOT EXISTS `queue` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `consecutive` int(11) NOT NULL,
  `creat_day` date NOT NULL,
  `patient` bigint(20) DEFAULT NULL,
  `status` tinyint(2) DEFAULT NULL,
  `metadata` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `consecutive` (`consecutive`,`creat_day`),
  KEY `status` (`status`),
  KEY `metadata` (`metadata`),
  KEY `patient_ident` (`patient`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;

-- --------------------------------------------------------

--
-- Table structure for table `triage_regs`
--

CREATE TABLE IF NOT EXISTS `triage_regs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `queue` bigint(20) NOT NULL,
  `patient` bigint(20) NOT NULL,
  `cod_color` int(11) NOT NULL,
  `medicines` text NOT NULL,
  `time_start_triage` time NOT NULL,
  `time_end_triage` time NOT NULL,
  `tens_arterial` varchar(7) NOT NULL,
  `frec_card` int(3) NOT NULL,
  `frec_resp` int(3) NOT NULL,
  `temp` int(3) NOT NULL,
  `gluc` int(3) NOT NULL,
  `esc_glasgown` int(3) NOT NULL,
  `atention` varchar(500) NOT NULL DEFAULT 'n/a',
  `questions` longtext,
  `exp_fis` longtext,
  `aux_diag` longtext,
  `pron` longtext,
  `trat` longtext,
  `diag` longtext,
  `status` tinyint(2) NOT NULL,
  `metadata` bigint(20) DEFAULT NULL,
  `metadata2` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `patient` (`patient`),
  KEY `status` (`status`),
  KEY `metadata2` (`metadata2`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;


问:
appending elements in jquery
i am trying to append a div to other div here :

```<code> <script>if($(window).width()>500){
            $("body").append("<?php include('includes/middle.php') ?>");
    }
    </script>
</code>```

Which becomes:

```<code><script>if($(window).width()>500){
            $("body").append("<div class='middle'>
                <div class='middleOne'>

             <a href='http://localhost/jhandwa/story/11-illustrations-that-perfectly-capture-how-life-changes-when-we-grow-up'>
               <img src='https://files.brightside.me/files/news/part_31/310360/12086810-10111660-1-0-1487765591-1487765607-0-1488442321-0-1488458395-1488458410-650-1-1488458410-650-0c369e17e2-1488484030.jpg'>
               <div class='miniTitle'>11 Illustrations That Perfectly Capture How Life Changes When We Grow Up<br /><span>2017-03-17 17:12:36</span></div>
            </a>
        </div>
               <div class='middleOne'>

             <a href='http://localhost/jhandwa/story/10-things-you-didnt-know-about-the-us-secret-service'>
               <img src='https://www.whitehouse.gov/sites/whitehouse.gov/files/images/first-family/44_barack_obama%5B1%5D.jpg'>
               <div class='miniTitle'>10 Things You Didn't Know About<br /><span>2017-03-17 15:15:29</span></div>
            </a>
        </div>
               <div class='middleOne'>

             <a href='http://localhost/jhandwa/story/who-is-actually-dumb-and-dumber-after-watching-these-crime-serials'>
               <img src='https://s-media-cache-ak0.pinimg.com/originals/36/45/e6/3645e66b26b611a30fabf923f7247d23.jpg'>
               <div class='miniTitle'>Who is Actually 'dumb' and 'dumber' after this? <br /><span>2017-02-28 00:00:00</span></div>
            </a>
        </div>

   </div>");
    }
    </script>
</code>```

what am i doing wrong here? i feel its something wrong because of double or single quotes.why isn't it working?

答:
Updating my original answer:

First, you need to wrap your code in document.ready(). It should append when the dom is ready.

Second, it is not working because your outputted HTML is on multiple lines. If you look at your console, you would see the following errors:

```<code>Uncaught SyntaxError: Invalid or unexpected token
</code>```

There are many ways to solve this issue, the simplest would be to use template literals, this means you should wrap your code within backtick.

```<code>$(document).ready(function () {
    if ($(window).width() > 500) {
        $("body").append(`<?php include('includes/middle.php') ?>`);
    }
});
</code>```

However, this solution may not be  compatible with all browsers as this feature has been introduced in ES6.

A much better way would be to call the sidebar.php via ajax.

```<code>$(document).ready(function () {
    if ($(window).width() > 500) {
        $.get("includes/middle.php", function (data, status) {
            $("body").append(data);

        })
    }
});
</code>```

Title: appending elements in jquery

Body:
i am trying to append a div to other div here :

Which becomes:

what am i doing wrong here? i feel its something wrong because of double or single quotes.why isn't it working?

Body:
Updating my original answer:

First, you need to wrap your code in document.ready(). It should append when the dom is ready.

Second, it is not working because your outputted HTML is on multiple lines. If you look at your console, you would see the following errors:

Uncaught SyntaxError: Invalid or unexpected token

There are many ways to solve this issue, the simplest would be to use template literals, this means you should wrap your code within backtick.

$(document).ready(function () {
    if ($(window).width() > 500) {
        $("body").append(`<?php include('includes/middle.php') ?>`);
    }
});

However, this solution may not be  compatible with all browsers as this feature has been introduced in ES6.

A much better way would be to call the sidebar.php via ajax.

$(document).ready(function () {
    if ($(window).width() > 500) {
        $.get("includes/middle.php", function (data, status) {
            $("body").append(data);

        })
    }
});


问:
Pattern Replacing in string with escaped characters failing with replaceAll
I have a use case where I want to replace some values in html string, so I need to do replaceAll for that, but that is not working, although replace is working fine, here is my code:

```<code>    String str  = "<style type=\"text/css\">#include(\"Invoice_Service_Tax.css\")</style>";
    String pattern = "#include(\"Invoice_Service_Tax.css\")";
    System.out.println(str.replace(pattern, "some-value"));
    System.out.println(str.replaceAll(pattern, "some-value"));
</code>```

output is :

```<code><style type="text/css">some-value</style>
<style type="text/css">#include("Invoice_Service_Tax.css")</style>
</code>```

For my use case I need to do replaceAll only, I tried with below patterns also but no help:

```<code>"#include(\\\"Invoice_Service_Tax.css\\\")"
"#include(Invoice_Service_Tax.css)"
</code>```

答:
The key difference between String.replace and String.replaceAll is that the first parameter for String.replace is string literal, but for String.replaceAll it is a regex. java doc of those two methods has great explanation about it. So if there's special chars like \ or $ in the string which you want to replace, you'll see the different behaves again, like:

```<code>public static void main(String[] args) {
    String str  = "<style type=\"text/css\">#include\"Invoice_Service_Tax\\.css\"</style>";
    String pattern = "#include\"Invoice_Service_Tax\\.css\"";
    System.out.println(str.replace(pattern, "some-value")); // works
    System.out.println(str.replaceAll(pattern, "some-value")); // not works, pattern should be: "#include\"Invoice_Service_Tax\\\\.css\""
}
</code>```

Body:
I have a use case where I want to replace some values in html string, so I need to do replaceAll for that, but that is not working, although replace is working fine, here is my code:

    String str  = "";
    String pattern = "#include(\"Invoice_Service_Tax.css\")";
    System.out.println(str.replace(pattern, "some-value"));
    System.out.println(str.replaceAll(pattern, "some-value"));

output is :

For my use case I need to do replaceAll only, I tried with below patterns also but no help:

"#include(\\\"Invoice_Service_Tax.css\\\")"
"#include(Invoice_Service_Tax.css)"

Body:
The key difference between String.replace and String.replaceAll is that the first parameter for String.replace is string literal, but for String.replaceAll it is a regex. java doc of those two methods has great explanation about it. So if there's special chars like \ or $ in the string which you want to replace, you'll see the different behaves again, like:

public static void main(String[] args) {
    String str  = "<style type=\"text/css\">#include\"Invoice_Service_Tax\\.css\"</style>";
    String pattern = "#include\"Invoice_Service_Tax\\.css\"";
    System.out.println(str.replace(pattern, "some-value")); // works
    System.out.println(str.replaceAll(pattern, "some-value")); // not works, pattern should be: "#include\"Invoice_Service_Tax\\\\.css\""
}


问:
Why divs are not centered well?
I have such code https://jsfiddle.net/96Lnxr38/3/ but as you can see - divs with class d1 are not aligned properly. If I add more spaces between

 elements - alignment will work fine. Is it a browser bug or my mistake? I have found that FF works fine and Chome/Safari show me this bug.

答:
The problem is because of whitespace between your inline-block divs. These whitespace characters also participate in the flow and take up space between inline or inline-block elements.

Try simply removing spaces between your div.d1 elements:

.cont {
      text-align: center;
      width: 500px;
      word-spacing: 80px;
    }

    .d1 {
      width: 300px;
      height: 500px;
      margin-top: 10px;
      background-color: red;
      display: inline-block;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="cont">
    <!-- Note no whitespace between divs -->
    <div class="d1"></div><div class="d1"></div><div class="d1"></div>
  </div>
</body></code>```

Another option is to change the display to block in your .d1 style.

Title: Why divs are not centered well?

Body:
The problem is because of whitespace between your inline-block divs. These whitespace characters also participate in the flow and take up space between inline or inline-block elements.

Try simply removing spaces between your div.d1 elements:

.cont {
      text-align: center;
      width: 500px;
      word-spacing: 80px;
    }

    .d1 {
      width: 300px;
      height: 500px;
      margin-top: 10px;
      background-color: red;
      display: inline-block;
    }

<body>
  <div class="cont">
    <!-- Note no whitespace between divs -->
    <div class="d1"></div><div class="d1"></div><div class="d1"></div>
  </div>
</body>

Another option is to change the display to block in your .d1 style.


问:
python3 datetime.datetime.strftime failed to accept utf-8 string format
python3 datetime.datetime.strftime failed to accept utf-8 string format

what I did is::

```<code># encoding: utf-8
import datetime

f = "%Y年%m月%d日"
now = datetime.datetime.now()
print( now.strftime(f) )
</code>```

and what I get is:

```<code>D:\pytools>python a.py
Traceback (most recent call last):
  File "a.py", line 6, in <module>
    print( now.strftime(f) )
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2
: Illegal byte sequence
</code>```

Why and how can I fix this?

答:
I also have the same problem on my windows10, fixed it by:

```<code>import locale
locale.setlocale(locale.LC_CTYPE, 'chinese')
print(datetime.now().strftime('%Y年%m月%d日 %H时%M分%S秒'))
</code>```

result：2017年04月01日 15时56分34秒

Body:
python3 datetime.datetime.strftime failed to accept utf-8 string format

what I did is::

# encoding: utf-8
import datetime

f = "%Y年%m月%d日"
now = datetime.datetime.now()
print( now.strftime(f) )

and what I get is:

D:\pytools>python a.py
Traceback (most recent call last):
  File "a.py", line 6, in <module>
    print( now.strftime(f) )
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2
: Illegal byte sequence

Why and how can I fix this?

Body:
I also have the same problem on my windows10, fixed it by:

import locale
locale.setlocale(locale.LC_CTYPE, 'chinese')
print(datetime.now().strftime('%Y年%m月%d日 %H时%M分%S秒'))

result：2017年04月01日 15时56分34秒


问:
jQuery UI dialog and Ajax POST in asp.net
In the example below, how can i post data to webservice after clicking login button in asp.net?</p>

```

        $(document).ready(function () {
        var username=$("#username").val();
        var password=$("#pass").val();

            $("#dialog").dialog({
                bgiframe: true,
                autoOpen: false,
                height: 400,
                width: 300,
                modal: true,
                buttons: {
                    "Cancel": function () {
                        $(this).dialog("close");
                    },
                    "Login":function() {
                    $.ajax(
                    {
                    type:"POST",
                    dataType:"json",
                    url:"WebService.asmx/Login",
                    contentType:"application/json",
                    data:"{username:'"+username+"',password:'"+password+"'}",
                    success:function(val)
                    {
                    $("#isValid").attr("value",val.d);
                    }}
                    );
                    },
                },
            });

            var isValid = $("#isValid").val();
            if (isValid== "false") {
                // Display the modal dialog.
                $("#dialog").dialog("open");

            }
        });

```

答:
If you have the following signature on your WebService...

```<code>function bool Login(string userName, string password)
</code>```

You just need to provide a javascript object in the JSON-notation that looks like this:

```<code>{ "userName" : "Admin", "password": "1234" }
</code>```

Hint: make sure that the names in the javascript object do have the same name and casing... Makes life much easier.

Hope I understood your question correctly...

ContentLicense: CC BY-SA 2.5

Body:
In the example below, how can i post data to webservice after clicking login button in asp.net?

        $(document).ready(function () {
        var username=$("#username").val();
        var password=$("#pass").val();

            $("#dialog").dialog({
                bgiframe: true,
                autoOpen: false,
                height: 400,
                width: 300,
                modal: true,
                buttons: {
                    "Cancel": function () {
                        $(this).dialog("close");
                    },
                    "Login":function() {
                    $.ajax(
                    {
                    type:"POST",
                    dataType:"json",
                    url:"WebService.asmx/Login",
                    contentType:"application/json",
                    data:"{username:'"+username+"',password:'"+password+"'}",
                    success:function(val)
                    {
                    $("#isValid").attr("value",val.d);
                    }}
                    );
                    },
                },
            });

            var isValid = $("#isValid").val();
            if (isValid== "false") {
                // Display the modal dialog.
                $("#dialog").dialog("open");

            }
        });

Body:
If you have the following signature on your WebService...

function bool Login(string userName, string password)

You just need to provide a javascript object in the JSON-notation that looks like this:

{ "userName" : "Admin", "password": "1234" }

Hint: make sure that the names in the javascript object do have the same name and casing... Makes life much easier.

Hope I understood your question correctly...


问:
Need help ... Bootstrap Button / matchMedia / removeClass
In a website I use a menu. If you call the page with the PC the menu should be fully visible. If you call the page with the mobile phone, only one button should be visible and with a click on the button the menu opens.

In the PC version everything is ok. The Menu is visible and the button hidden.

When calling with the mobile phone the button is visible. The Menu is however also folded out.

Here is the code:

<button class="btn btn-default btn-block hidden-md hidden-lg hidden-xl" data-toggle="collapse" data-target="#menulist">Show more ...</button>

Menu 1

Menu 2

Menu 3

```

答:
Just remove this line

```<code><div id="menulist" class="collapse in">
</code>```

with

```<code><div id="menulist" class="navbar-collapse collapse">
</code>```

Body:
Just remove this line

<div id="menulist" class="collapse in">

with

<div id="menulist" class="navbar-collapse collapse">


问:
paperclip: image not getting uploaded rails
I am using paperclip gem in rails,

my user model file contains:

```<code>    has_attached_file :profile_pic, styles: { medium: "300x300>", thumb: "100x100>" },
    default_url: "/images/:style/missing.png",
    :url  => "/assets/users/:id/:style/:basename.:extension",
    :path => ":rails_root/public/assets/users/:id/:style/:basename.:extension"
</code>```

My image is not getting uploaded and hence not getting displayed (broken Image with "missing.png" appears).what should i do to upload my image to /assets/images path ?

and My view part look like:

```<code><%= image_tag current_user.profile_pic.url(:thumb)  %>
</code>```

答:
It might be due to various reason

1) In strong parameter you need to define :profile_pic

2) you forgot to put missing.png

3):path =>:rails_root/public/assets/users/:id/:style/:basename.:extension"

it might be wrong way to define path first :class then :style and then after :extension

:path => "images/:class/:style/:id.:extension"

Body:
I am using paperclip gem in rails,

my user model file contains:

    has_attached_file :profile_pic, styles: { medium: "300x300>", thumb: "100x100>" },
    default_url: "/images/:style/missing.png",
    :url  => "/assets/users/:id/:style/:basename.:extension",
    :path => ":rails_root/public/assets/users/:id/:style/:basename.:extension"

My image is not getting uploaded and hence not getting displayed (broken Image with "missing.png" appears).what should i do to upload my image to /assets/images path ?

and My view part look like:

<%= image_tag current_user.profile_pic.url(:thumb)  %>


问:
what is the best way to Upload a file to a php webservice and save it to mysql database?
I'm creating a PHP web service that saves files to MySql database.

The client side of my application is Android.

What is the proper way to upload a file(image, pdf, etc.) from android and save it to MySql database using PHP?

I'm not looking for codes right now, just wondering how I can do that?

答:
The android can use the base64 to encode the img. Then you create a post http request to your php server.Your php save the base64 code to the mysql.
When you read the img.You can decode base64 to img.
Note:If you encode a img to base64 the base64 code size will bigger then img.</p>


问:
Add a new row in bounded dataGridView on button click
I have a datagridview and filling it using datatable as datasource .

I want to add a new row on button click , using method to first unbound it and then add new row in it . As the following :

```<code> dataGridView1.AutoGenerateColumns = false;
 dataGridView1.DataSource= null;
 dataGridView1.Rows.Add();
</code>```

But instead of adding new row below the existing row , it clears the existing data in row. I think present that row as new row.

how can I add the new row below the existing row and keep the data in other rows safe .

NOTE -- columns of datagridview view are custom columns  .

答:
If you need to keep safe the existing rows, you must retain the datasource. Can try the following please?</p>

```<code>public partial class Form1 : Form
{
    DataTable dt;

    public Form1()
    {
        InitializeComponent();

        InitDataGridView();
    }

    private void InitDataGridView()
    {
        dt = new DataTable();

        dt.Columns.Add("A"); dt.Columns.Add("B");

        var dr = dt.NewRow();

        dr["A"] = "A-init"; dr["B"] = "B-init";

        dt.Rows.Add(dr);

        dataGridView1.DataSource = dt;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        var dr = dt.NewRow();

        var counter = dt.Rows.Count;

        dr["A"] = "A-" + counter; dr["B"] = "B-" + counter;

        dt.Rows.Add(dr);
    }
}
</code>```

Body:
I have a datagridview and filling it using datatable as datasource .

I want to add a new row on button click , using method to first unbound it and then add new row in it . As the following :

 dataGridView1.AutoGenerateColumns = false;
 dataGridView1.DataSource= null;
 dataGridView1.Rows.Add();

But instead of adding new row below the existing row , it clears the existing data in row. I think present that row as new row.

how can I add the new row below the existing row and keep the data in other rows safe .

NOTE -- columns of datagridview view are custom columns  .

Body:
If you need to keep safe the existing rows, you must retain the datasource. Can try the following please?

public partial class Form1 : Form
{
    DataTable dt;

    public Form1()
    {
        InitializeComponent();

        InitDataGridView();
    }

    private void InitDataGridView()
    {
        dt = new DataTable();

        dt.Columns.Add("A"); dt.Columns.Add("B");

        var dr = dt.NewRow();

        dr["A"] = "A-init"; dr["B"] = "B-init";

        dt.Rows.Add(dr);

        dataGridView1.DataSource = dt;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        var dr = dt.NewRow();

        var counter = dt.Rows.Count;

        dr["A"] = "A-" + counter; dr["B"] = "B-" + counter;

        dt.Rows.Add(dr);
    }
}


答:
Based on this answer and as you directly echo inside the included page, you can use backtick (`) to wrap multiline string in js properly.</p>

```<code> <script>
 $(document).ready(function() {
     if($(window).width()>500){
         $("body").append(`<?php include('includes/middle.php'); ?>`);
     }
 });
 </script>
</code>```

Title: appending elements in jquery

Body:
Based on this answer and as you directly echo inside the included page, you can use backtick (`) to wrap multiline string in js properly.

 <script>
 $(document).ready(function() {
     if($(window).width()>500){
         $("body").append(`<?php include('includes/middle.php'); ?>`);
     }
 });
 </script>


问:
How use integer_sort from boost library?
I use boost::sort() from boost/range/algorithm.hpp but is really... slow and I'm just working with unsigned integer type, so I thought "Maybe using integer_sort() from boost/sort/spreadsort/integer_sort.hpp I can improve the speed"
The Question is that std::sort(v.begin(), v.end()) run in ~54 seconds and boost:sort(v) in ~54 seconds (Same time)

But I Write something like radix sort, and takes ~28 seconds, but I think that integer_sort can be more optimized that my code, but I don't know how use integer_sort.

```<code>#include <vector>
#include <boost/range/algorithm.hpp>
#include <boost/sort/spreadsort/integer_sort.hpp> // I WANT USE THIS
#include "myLib.hpp"

using namespace std;

int main(void)
{
  vector <unsigned> v(20);

  for (unsigned i = 0; i < v.size(); i++)
    v[i] = rand() % 1000;

  imprime(v); // THIS PRINTS THE VECTOR
  boost::sort(v); // THIS SORT THE VECTOR
  imprime(v);
  integer_sort(v.begin(), v.end()); // THIS DOES'T WORK

  return 0;
}
</code>```

If I try with integer_sort(v.begin(), v.end()); I get

```<code>sort.cpp: In function ‘int main()’:
sort.cpp:23:34: error: ‘integer_sort’ was not declared in this scope
   integer_sort(v.begin(), v.end());
                                  ^
sort.cpp:23:34: note: suggested alternatives:
In file included from sort.cpp:5:0:
/usr/include/boost/sort/spreadsort/integer_sort.hpp:173:15: note:   ‘boost::sort::spreadsort::integer_sort’
   inline void integer_sort(RandomAccessIter first, RandomAccessIter last,
               ^~~~~~~~~~~~
In file included from /usr/include/boost/sort/spreadsort/integer_sort.hpp:26:0,
                 from sort.cpp:5:
/usr/include/boost/sort/spreadsort/detail/integer_sort.hpp:482:5: note:   ‘boost::sort::spreadsort::detail::integer_sort’
     integer_sort(RandomAccessIter first, RandomAccessIter last, Div_type,
     ^~~~~~~~~~~~
</code>```

I know that this has something to do with the (v.begin(), v.end()) RandomAccessIter first <- I get something similar when I try std::sort(v) <- this is not correct. But I don't understand the error message.
Don't say candidate expects 3 arguments, 1 provided like in std::sort.

So How use integer_sort()?

Boost Doc Says:

Each of integer_sort, float_sort, and string_sort have 3 main versions: The base version, which takes a first iterator and a last iterator, just like std::sort:

```<code>integer_sort(array.begin(), array.end());
float_sort(array.begin(), array.end());
string_sort(array.begin(), array.end());
</code>```

答:
You are missing a namespace qualification in your call to integer_sort.

integer_sort is in the boost::sort::spreadsort namespace (see the documentation). So your call should look like:

```<code>boost::sort::spreadsort::integer_sort(v.begin(), v.end());
</code>```

Also note that you will have problems if you try to use boost::sort and the Boost.Sort library in the same program, as the boost::sort function template conflicts with the Boost.Sort namespace (see the bug report).

boost::sort is just a wrapper for std::sort, so it is expected that the two would have identical performance.

boost::sort::spreadsort::integer_sort will use std::sort if the data size is too small (below boost::sort::spreadsort::detail::min_sort_size), so for small data sizes it would be expected that they too have nearly identical performance (up to the extra cost of integer_sort checking whether to use std::sort or not).

Body:
I use boost::sort() from boost/range/algorithm.hpp but is really... slow and I'm just working with unsigned integer type, so I thought "Maybe using integer_sort() from boost/sort/spreadsort/integer_sort.hpp I can improve the speed"
The Question is that std::sort(v.begin(), v.end()) run in ~54 seconds and boost:sort(v) in ~54 seconds (Same time)

But I Write something like radix sort, and takes ~28 seconds, but I think that integer_sort can be more optimized that my code, but I don't know how use integer_sort.

#include <vector>
#include <boost/range/algorithm.hpp>
#include <boost/sort/spreadsort/integer_sort.hpp> // I WANT USE THIS
#include "myLib.hpp"

using namespace std;

int main(void)
{
  vector <unsigned> v(20);

  for (unsigned i = 0; i < v.size(); i++)
    v[i] = rand() % 1000;

  imprime(v); // THIS PRINTS THE VECTOR
  boost::sort(v); // THIS SORT THE VECTOR
  imprime(v);
  integer_sort(v.begin(), v.end()); // THIS DOES'T WORK

  return 0;
}

If I try with integer_sort(v.begin(), v.end()); I get

sort.cpp: In function ‘int main()’:
sort.cpp:23:34: error: ‘integer_sort’ was not declared in this scope
   integer_sort(v.begin(), v.end());
                                  ^
sort.cpp:23:34: note: suggested alternatives:
In file included from sort.cpp:5:0:
/usr/include/boost/sort/spreadsort/integer_sort.hpp:173:15: note:   ‘boost::sort::spreadsort::integer_sort’
   inline void integer_sort(RandomAccessIter first, RandomAccessIter last,
               ^~~~~~~~~~~~
In file included from /usr/include/boost/sort/spreadsort/integer_sort.hpp:26:0,
                 from sort.cpp:5:
/usr/include/boost/sort/spreadsort/detail/integer_sort.hpp:482:5: note:   ‘boost::sort::spreadsort::detail::integer_sort’
     integer_sort(RandomAccessIter first, RandomAccessIter last, Div_type,
     ^~~~~~~~~~~~

I know that this has something to do with the (v.begin(), v.end()) RandomAccessIter first <- I get something similar when I try std::sort(v) <- this is not correct. But I don't understand the error message.
Don't say candidate expects 3 arguments, 1 provided like in std::sort.

So How use integer_sort()?

Boost Doc Says:

Each of integer_sort, float_sort, and string_sort have 3 main versions: The base version, which takes a first iterator and a last iterator, just like std::sort:

integer_sort(array.begin(), array.end());
float_sort(array.begin(), array.end());
string_sort(array.begin(), array.end());

Body:
You are missing a namespace qualification in your call to integer_sort.

integer_sort is in the boost::sort::spreadsort namespace (see the documentation). So your call should look like:

boost::sort::spreadsort::integer_sort(v.begin(), v.end());

Also note that you will have problems if you try to use boost::sort and the Boost.Sort library in the same program, as the boost::sort function template conflicts with the Boost.Sort namespace (see the bug report).

boost::sort is just a wrapper for std::sort, so it is expected that the two would have identical performance.

boost::sort::spreadsort::integer_sort will use std::sort if the data size is too small (below boost::sort::spreadsort::detail::min_sort_size), so for small data sizes it would be expected that they too have nearly identical performance (up to the extra cost of integer_sort checking whether to use std::sort or not).


问:
Does a favicon have to be 32×32 or 16×16?
I'd like to use a single image as both a regular favicon and iPhone/iPad friendly favicon.

Is this possible? Would an iPad-friendly 72×72 PNG scale if linked to as a regular browser favicon? Or do I have to use a separate 16×16 or 32×32 image?

答:
2021 standards thanks to faviconit

I use faviconit.com for the best browser and device support possible. You upload an image and this site gives you the code, the converted images and a browserconfig file.

We could simply upload a favicon manually to our website of 16x16 and it will probably show up in almost any browser.

But when you will mark it as one of your favorites on your smartphone or tablet, we will need larger images (60x60 to 144x144).

And lets say one of our users creates a shortcut on their desktop. In that case a 196x196 looks better!

Example code of what faviconit would give you, next to all the converted images:

```<code><!-- place this in your <head></head> -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
<link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png">
<link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png">
<link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">
<link rel="apple-touch-icon" href="/favicon-57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">
</code>```

Since Windows 8

But that is not all. Since windows 8 we are able to create shortcuts to websites with tiles!

```<code><!-- place this in your <head></head> -->
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="msapplication-TileImage" content="/favicon-144.png">
<meta name="msapplication-config" content="/browserconfig.xml">
</code>```

Browserconfig.xml

Upload a file named browserconfig.xml (to enable the tiles in windows >8)

```<code><browserconfig>
    <msapplication>
        <tile>
            <square70x70logo src="/favicon-70.png"/>
            <square150x150logo src="/favicon-150.png"/>
            <square310x310logo src="/favicon-310.png"/>
            <TileColor>#FFFFFF</TileColor>
        </tile>
    </msapplication>
</browserconfig>
</code>```

Body:
2021 standards thanks to faviconit

I use faviconit.com for the best browser and device support possible. You upload an image and this site gives you the code, the converted images and a browserconfig file.

We could simply upload a favicon manually to our website of 16x16 and it will probably show up in almost any browser.

But when you will mark it as one of your favorites on your smartphone or tablet, we will need larger images (60x60 to 144x144).

And lets say one of our users creates a shortcut on their desktop. In that case a 196x196 looks better!

Example code of what faviconit would give you, next to all the converted images:

<!-- place this in your <head></head> -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="icon" sizes="16x16 32x32 64x64" href="/favicon.ico">
<link rel="icon" type="image/png" sizes="196x196" href="/favicon-192.png">
<link rel="icon" type="image/png" sizes="160x160" href="/favicon-160.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96.png">
<link rel="icon" type="image/png" sizes="64x64" href="/favicon-64.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png">
<link rel="apple-touch-icon" href="/favicon-57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/favicon-114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/favicon-72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/favicon-144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/favicon-60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/favicon-120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/favicon-76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/favicon-152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/favicon-180.png">

Since Windows 8

But that is not all. Since windows 8 we are able to create shortcuts to websites with tiles!

<!-- place this in your <head></head> -->
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="msapplication-TileImage" content="/favicon-144.png">
<meta name="msapplication-config" content="/browserconfig.xml">

Browserconfig.xml

Upload a file named browserconfig.xml (to enable the tiles in windows >8)

<browserconfig>
    <msapplication>
        <tile>
            <square70x70logo src="/favicon-70.png"/>
            <square150x150logo src="/favicon-150.png"/>
            <square310x310logo src="/favicon-310.png"/>
            <TileColor>#FFFFFF</TileColor>
        </tile>
    </msapplication>
</browserconfig>


问:
PHP - magic quotes gpc and stripslashes question
Okay my hosting company has magic_quotes_gpc turned ON and I coded my PHP script using stripslashes() in preparation of this. But now the hosting company says its going to turn magic_quotes_gpc OFF and I was wondering what will happen now to my data now when stripslashes() is present should I go through all my millions of lines of code and get rid of stripslashes()? or leave the stripslashes() function alone? will leaving the stripslashes() ruin my data?

答: I would start going through and removing stripslashes().  You can do this ahead of time by testing for magic_quotes_gpc and only calling stripslahes() if it is needed.


问:
How to Replace null with "-" using single line in Jquery
How to Replace null with -  using single line in jQuery

For Example

```<code>    var obj={
        "Key1":null,
        "key2":"I have null",
        "key3":null

    }
</code>```

Expected Output:

```<code>var obj={
    "Key1":"-",
    "key2":"I have null",
    "key3":"-"

}
</code>```

答:
This one-line function will work:

```<code>function nullToDash(obj){for(e in obj){if(obj.hasOwnProperty(e) && obj[e]===null){obj[e]="-";}}}
</code>```

Edit: Unminified above function for better understanding

```<code>function nullToDash(obj){
    for(e in obj){
        if(obj.hasOwnProperty(e) && obj[e]===null){
            obj[e]="-";
        }
    }
}
</code>```

Body:
How to Replace null with -  using single line in jQuery

For Example

    var obj={
        "Key1":null,
        "key2":"I have null",
        "key3":null

    }

Expected Output:

var obj={
    "Key1":"-",
    "key2":"I have null",
    "key3":"-"

}

Body:
This one-line function will work:

function nullToDash(obj){for(e in obj){if(obj.hasOwnProperty(e) && obj[e]===null){obj[e]="-";}}}

Edit: Unminified above function for better understanding

function nullToDash(obj){
    for(e in obj){
        if(obj.hasOwnProperty(e) && obj[e]===null){
            obj[e]="-";
        }
    }
}


问:
Implement a method in java mysql database connection class to use preparedStatements
I have created a database connection class in my project to create and share database instance across the all class in the project.

Database connection obtained using this code

```<code>void createConnection(){
    try{
        connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "");
        System.out.println("Connected");
    }catch(Exception e) {
        System.out.println("Connection Failed");
        System.out.println(e);
    }

}
</code>```

Then I created a method to insert values to database using prepared statements as follows

```<code>public boolean execAction(String query){
    try {
        pstatement = (PreparedStatement) connection.prepareStatement(query);
        pstatement.execute(query);
        System.out.println("Values inserted");
        return true;
    } catch (SQLException ex) {
        Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Values insertion failed");
        return false;
    } finally {

    }
</code>```

I want to find a way to pass preparedstatement variable values to this method.

答:
My advice would be:
First think about what you need this method to do.  Does it only need to take a single values, or many? Are the parameters of the same type?

Once you've got that, decide what data structure best represents this. Since PreparedStatement references parameters by index, if you want many values you probably want a list of some kind.  If each entry needs a type as well, you probably want to create a data class to hold that and the value in one place.

Since this looks like a programming assignment, I won't write the code for you, but that would give me something like this as a starting point:

```<code>public class DatabaseHandler {
    public boolean execAction(String query, List<PreparedStatementArgument> arguments){
        // code here
    }
}

class PreparedStatementArgument {
    private final PreparedStatementArgumentType type;
    private final Object value;

    // Constructor, getters
}

enum PreparedStatementArgumentType {
    INT, STRING; //etc
}
</code>```

You might also consider using polymorphism for the PreparedStatementArguments, depending how complex you're prepared for this to get.

If this isn't a programming assignment, please be aware that the problem with a method like this is that it can't validate the parameters its given match the SQL - this makes it harder to spot if there's a mismatch, and is likely to make your application more error prone in the long run.

Body:
I have created a database connection class in my project to create and share database instance across the all class in the project.

Database connection obtained using this code

void createConnection(){
    try{
        connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "");
        System.out.println("Connected");
    }catch(Exception e) {
        System.out.println("Connection Failed");
        System.out.println(e);
    }

}

Then I created a method to insert values to database using prepared statements as follows

public boolean execAction(String query){
    try {
        pstatement = (PreparedStatement) connection.prepareStatement(query);
        pstatement.execute(query);
        System.out.println("Values inserted");
        return true;
    } catch (SQLException ex) {
        Logger.getLogger(databaseHandler.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Values insertion failed");
        return false;
    } finally {

    }

I want to find a way to pass preparedstatement variable values to this method.

Body:
My advice would be:
First think about what you need this method to do.  Does it only need to take a single values, or many? Are the parameters of the same type?

Once you've got that, decide what data structure best represents this. Since PreparedStatement references parameters by index, if you want many values you probably want a list of some kind.  If each entry needs a type as well, you probably want to create a data class to hold that and the value in one place.

Since this looks like a programming assignment, I won't write the code for you, but that would give me something like this as a starting point:

public class DatabaseHandler {
    public boolean execAction(String query, List<PreparedStatementArgument> arguments){
        // code here
    }
}

class PreparedStatementArgument {
    private final PreparedStatementArgumentType type;
    private final Object value;

    // Constructor, getters
}

enum PreparedStatementArgumentType {
    INT, STRING; //etc
}

You might also consider using polymorphism for the PreparedStatementArguments, depending how complex you're prepared for this to get.

If this isn't a programming assignment, please be aware that the problem with a method like this is that it can't validate the parameters its given match the SQL - this makes it harder to spot if there's a mismatch, and is likely to make your application more error prone in the long run.


问:
How to loop through a menu expander using java and selenium
Main Menu

option 1

option 2

option 3

option 4

option 5

Here when I click on the Main menu. rest of the options appear. I want to loop through all the options and click them.

```<code>    List<WebElement> elements =submenuclick.findElements(By.xpath("//div[@id='...']/ul/li"));
           for (WebElement element: elements) {
              System.out.println(element.getText());
        }
</code>```

when i execute this, a no such element exception occurs.

答:
You need to change your Xpath for storing list element as below as it should be till Unordered List:

```<code>  List <WebElement> elements =submenuclick.findElements(By.xpath("//div[@id='...']/ul"));
</code>```

Try Now.

Body:
Main Menu

option 1

option 2

option 3

option 4

option 5

Here when I click on the Main menu. rest of the options appear. I want to loop through all the options and click them.

    List<WebElement> elements =submenuclick.findElements(By.xpath("//div[@id='...']/ul/li"));
           for (WebElement element: elements) {
              System.out.println(element.getText());
        }

when i execute this, a no such element exception occurs.

Body:
You need to change your Xpath for storing list element as below as it should be till Unordered List:

  List <WebElement> elements =submenuclick.findElements(By.xpath("//div[@id='...']/ul"));

Try Now.


问:
Use of index on Guid column
What is the use of having an index on a Guid column in SQL Server? Indexes sort the rows, as per my knowledge. If Guids are randomly generated and are not sorted how do indexes work on them?

Thanks in advance.

答:
Imagine you have a telephone book with (person,number) pairs. Is there any reason to sort the book by number? Obviously not: you will never ask queries which search for persons having number between number1 and number2. BUT: you might want to search for the owner of a particular number. And indexing the number is the only efficient way to do this.

Likewise, indexing a GUID helps you quickly identify the unique tuple with this value. And an index is necessary for this.

Title: Use of index on Guid column


问:
How to create two views in Android that use 50% height each, unless one is smaller?
Imagine a full Android device screen, I want it split in to two sections:

The upper half has text in it, which may be larger than the space available (or not) and so the text will scroll (i.e. TextView inside a ScrollView)

The lower half contains a MapView control.

Looking specifically at some scenarios:

If the text is small, I want the map to take up more space, i.e. more than 50%. So perhaps 20% text, 80% map.

If the text is larger, it only takes up a MAXIMUM of 50% of the screen space, and then scrolls. So 50% map, 50% text.

At the moment I've assigned weights to the two parts, and that isn't too bad, but if the text is small, the map doesn't expand to take the space, and the layout has a wasted gap that the map could usefully use.

I've tried loads of combinations but can't see how to make this happen. It seems to be a common experience for me that I know what I want, but can't see how to get the available views to deliver it. I'm hoping there's a nice easy way to do this.

Please feel free to make me look like a fool and point out the obvious attribute I've missed :-)

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

As far as I can see there's no way to do this just in declarative XML and it needs doing in the code. I set the text section height to wrap_content, weight to 0 (no resizing), and have the map set to weight=1 (i.e. take up the remaining space). I then check if the text section (in a ScrollView) is taking up too much space and if so, shrink it back. This code would need changing to support a different layout orientation.

```<code>private void fixLayoutProportions()
{
    float maxPercentageOfScreenForText = 50/100;
    LinearLayout container = (LinearLayout)findViewById(R.id.container);
    ScrollView eventText = (ScrollView)findViewById(R.id.text_scroller);
    int heightAvailable = container.getHeight();
    int scrollerHeight = eventText.getHeight();
    if ( scrollerHeight>(heightAvailable*maxPercentageOfScreenForText) )      // Text section using too much space
    {
        eventText.getLayoutParams().height = (int)(heightAvailable*maxPercentageOfScreenForText) ;
        eventText.invalidate();
    }
}
</code>```

答: I haven't tested this, but I'd try setting your ScrollView to have android:layout_weight="1" and your MapView to have android:layout_weight="0" and a android:minHeight="240dp". The hope is that minHeight will have precedence over layout_weight.

Body:
Imagine a full Android device screen, I want it split in to two sections:

The upper half has text in it, which may be larger than the space available (or not) and so the text will scroll (i.e. TextView inside a ScrollView)

The lower half contains a MapView control.

Looking specifically at some scenarios:

If the text is small, I want the map to take up more space, i.e. more than 50%. So perhaps 20% text, 80% map.

If the text is larger, it only takes up a MAXIMUM of 50% of the screen space, and then scrolls. So 50% map, 50% text.

At the moment I've assigned weights to the two parts, and that isn't too bad, but if the text is small, the map doesn't expand to take the space, and the layout has a wasted gap that the map could usefully use.

I've tried loads of combinations but can't see how to make this happen. It seems to be a common experience for me that I know what I want, but can't see how to get the available views to deliver it. I'm hoping there's a nice easy way to do this.

Please feel free to make me look like a fool and point out the obvious attribute I've missed :-)

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

As far as I can see there's no way to do this just in declarative XML and it needs doing in the code. I set the text section height to wrap_content, weight to 0 (no resizing), and have the map set to weight=1 (i.e. take up the remaining space). I then check if the text section (in a ScrollView) is taking up too much space and if so, shrink it back. This code would need changing to support a different layout orientation.

private void fixLayoutProportions()
{
    float maxPercentageOfScreenForText = 50/100;
    LinearLayout container = (LinearLayout)findViewById(R.id.container);
    ScrollView eventText = (ScrollView)findViewById(R.id.text_scroller);
    int heightAvailable = container.getHeight();
    int scrollerHeight = eventText.getHeight();
    if ( scrollerHeight>(heightAvailable*maxPercentageOfScreenForText) )      // Text section using too much space
    {
        eventText.getLayoutParams().height = (int)(heightAvailable*maxPercentageOfScreenForText) ;
        eventText.invalidate();
    }
}


问:
Repairing pdfs with damaged xref table
Are there any solutions (preferably in Python) that can repair pdfs with damaged xref tables?

I have a pdf that I tried to convert to a png in Ghostscript and received the following error:

**** Error:  An error occurred while reading an XREF table.
   **** The file has been damaged.  This may have been caused
   **** by a problem while converting or transfering the file.

However, I am able to open the pdf in Preview on my Mac and when I export the pdf using Preview, I am able to convert the exported pdf.

Is there any way to repair pdfs without having to manually open them and export them?

答:
If the file renders as expected in Ghostscript then you can run it through GS to the pdfwrite device and create a new PDF file which won't be damaged.

Preview is (like Acrobat) almost certainly silently repairing the problem in the background. Ghostscript will be doing the same, but unlike other applications we feel you need to know that the file has a problem. Firstly so that you know its broken, secondly so that if the file renders incorrectly in Ghostscript (or indeed, other applications) you know why.

Note that there are two main reasons for a damaged xref; firstly the developer of the application didn't read the specification carefully enough and the file offsets in the xref are correct, but the format is incorrect (this is not uncommon and a repair by GS will be harmless), secondly the file genuinely has been damaged in transit, or by editing it.

In the latter case there may be other problems and Ghostscript will try to warn you about those too. If you don't get any other warnings or errors, then its probably just a malformed xref table.

Title: Repairing pdfs with damaged xref table


问:
Component Interaction Angular 2
Hi I have two components, a list component, and an edit component and service.
part of my Svc:

```<code>.....

    // Observable string sources
    private _updatedArray = new Subject<string>();

      // Service message commands
    setColDefs(columns: any) {
       this._updatedArray.next(columns);
       console.log(columns);
    }

getColDef(): Observable<any> {
    return this._updatedArray.asObservable();
}
</code>```

And am calling my service in my list as below,

```<code>import { Svc } from '../services/mySvc.svc'

.....

this._listCompSvc.setColDefs(columns);
</code>```

Until here its working perfect. I set the column values and the console.log in my svc showing the columns I want. but the issue comes in the edit component, when am getting the values(subscribing). my edit component code:

```<code>import { Svc } from '../services/mySvc.svc';
..

export class EditComponent implements OnInit{
    private _colDefs: any;
    constructor(
        private _editCompSvc: Svc
        ){}

    ngOnInit() {
        this._editCompSvc.getColDef().subscribe(
          columns => {
              console.log(columns);
        });
    }
</code>```

....

But somehow my console.log in edit, not displaying any data. I want to return my columns value here as per i set in my list component. Any idea guys? Thanks in advance.

Module:

```<code>import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

export class Module { }
</code>```

答:
This is one way of doing it : load service in parent component and share it with all child

Parent Component

```<code>import { Svc } from '../services/mySvc.svc'
@Component({
.......
    providers: [Svc]
    template:`<child1></child1>
                <child2></child2>`
})
export class TerminalComponent implements OnInit {
</code>```

In Both Child Component

```<code>import { Svc } from '../services/mySvc.svc'
@Component({
selector: 'child1',
......
})
export class Child1Component implements OnInit {
constructor(private _editCompSvc: Svc){}
}

import { Svc } from '../services/mySvc.svc'
@Component({
selector: 'child1',
......
})
export class Child2Component implements OnInit {
constructor(private _editCompSvc: Svc){}
}
</code>```

Another way is to load service in route module / or the module in which all these components are loaded.
Now there is no need to add this line providers: [Svc] in components.

import { Svc } from '../services/mySvc.svc'
@NgModule({
        .........
        providers: [Svc]
}

Title: Component Interaction Angular 2

Body:
Hi I have two components, a list component, and an edit component and service.
part of my Svc:

.....

    // Observable string sources
    private _updatedArray = new Subject<string>();

      // Service message commands
    setColDefs(columns: any) {
       this._updatedArray.next(columns);
       console.log(columns);
    }

getColDef(): Observable<any> {
    return this._updatedArray.asObservable();
}

And am calling my service in my list as below,

import { Svc } from '../services/mySvc.svc'

.....

this._listCompSvc.setColDefs(columns);

Until here its working perfect. I set the column values and the console.log in my svc showing the columns I want. but the issue comes in the edit component, when am getting the values(subscribing). my edit component code:

import { Svc } from '../services/mySvc.svc';
..

export class EditComponent implements OnInit{
    private _colDefs: any;
    constructor(
        private _editCompSvc: Svc
        ){}

    ngOnInit() {
        this._editCompSvc.getColDef().subscribe(
          columns => {
              console.log(columns);
        });
    }

....

But somehow my console.log in edit, not displaying any data. I want to return my columns value here as per i set in my list component. Any idea guys? Thanks in advance.

Module:

import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

export class Module { }

Body:
This is one way of doing it : load service in parent component and share it with all child

Parent Component

import { Svc } from '../services/mySvc.svc'
@Component({
.......
    providers: [Svc]
    template:`<child1></child1>
                <child2></child2>`
})
export class TerminalComponent implements OnInit {

In Both Child Component

import { Svc } from '../services/mySvc.svc'
@Component({
selector: 'child1',
......
})
export class Child1Component implements OnInit {
constructor(private _editCompSvc: Svc){}
}

import { Svc } from '../services/mySvc.svc'
@Component({
selector: 'child1',
......
})
export class Child2Component implements OnInit {
constructor(private _editCompSvc: Svc){}
}

Another way is to load service in route module / or the module in which all these components are loaded.
Now there is no need to add this line providers: [Svc] in components.

import { Svc } from '../services/mySvc.svc'
@NgModule({
        .........
        providers: [Svc]
}


问:
appending elements in jquery
i am trying to append a div to other div here :

```<code> <script>if($(window).width()>500){
            $("body").append("<?php include('includes/middle.php') ?>");
    }
    </script>
</code>```

Which becomes:

```<code><script>if($(window).width()>500){
            $("body").append("<div class='middle'>
                <div class='middleOne'>

             <a href='http://localhost/jhandwa/story/11-illustrations-that-perfectly-capture-how-life-changes-when-we-grow-up'>
               <img src='https://files.brightside.me/files/news/part_31/310360/12086810-10111660-1-0-1487765591-1487765607-0-1488442321-0-1488458395-1488458410-650-1-1488458410-650-0c369e17e2-1488484030.jpg'>
               <div class='miniTitle'>11 Illustrations That Perfectly Capture How Life Changes When We Grow Up<br /><span>2017-03-17 17:12:36</span></div>
            </a>
        </div>
               <div class='middleOne'>

             <a href='http://localhost/jhandwa/story/10-things-you-didnt-know-about-the-us-secret-service'>
               <img src='https://www.whitehouse.gov/sites/whitehouse.gov/files/images/first-family/44_barack_obama%5B1%5D.jpg'>
               <div class='miniTitle'>10 Things You Didn't Know About<br /><span>2017-03-17 15:15:29</span></div>
            </a>
        </div>
               <div class='middleOne'>

             <a href='http://localhost/jhandwa/story/who-is-actually-dumb-and-dumber-after-watching-these-crime-serials'>
               <img src='https://s-media-cache-ak0.pinimg.com/originals/36/45/e6/3645e66b26b611a30fabf923f7247d23.jpg'>
               <div class='miniTitle'>Who is Actually 'dumb' and 'dumber' after this? <br /><span>2017-02-28 00:00:00</span></div>
            </a>
        </div>

   </div>");
    }
    </script>
</code>```

what am i doing wrong here? i feel its something wrong because of double or single quotes.why isn't it working?

答:
This script can not execute because your PHP file have multiple line. And multiple line will make your JS syntax wrong.

You need include this php file in a hidden script, and use jQuery to get this div content and append into body.

And as @Hyder B say, you need put this script execute when document has been ready.

You can try this way:

```<code><div id="included_content" style="display:none">
    <?php include('includes/middle.php') ?>
</div>

<script>
$(document).ready(function() {
    if($(window).width() > 500){
            $("body").append($("#included_content").html());
    }
});
</script>
</code>```

Title: appending elements in jquery

Body:
i am trying to append a div to other div here :

Which becomes:

what am i doing wrong here? i feel its something wrong because of double or single quotes.why isn't it working?

Body:
This script can not execute because your PHP file have multiple line. And multiple line will make your JS syntax wrong.

You need include this php file in a hidden script, and use jQuery to get this div content and append into body.

And as @Hyder B say, you need put this script execute when document has been ready.

You can try this way:

<div id="included_content" style="display:none">
    <?php include('includes/middle.php') ?>
</div>

<script>
$(document).ready(function() {
    if($(window).width() > 500){
            $("body").append($("#included_content").html());
    }
});
</script>


问:
C# "Parameter is not valid." creating new bitmap
if I try to create a bitmap bigger than 19000 px I get the error: Parameter is not valid.
How can I workaround this??</p>

```<code>System.Drawing.Bitmap myimage= new System.Drawing.Bitmap(20000, 20000);
</code>```

答:
Set the PixelFormat when you new a bitmap, like:

```<code>new Bitmap(2000, 40000,PixelFormat.Format16bppRgb555)
</code>```

and with the exact number above, it works for me. This may partly solve the problem.

Body:
if I try to create a bitmap bigger than 19000 px I get the error: Parameter is not valid.
How can I workaround this??

System.Drawing.Bitmap myimage= new System.Drawing.Bitmap(20000, 20000);

Body:
Set the PixelFormat when you new a bitmap, like:

new Bitmap(2000, 40000,PixelFormat.Format16bppRgb555)

and with the exact number above, it works for me. This may partly solve the problem.


问:
The dependency `SinchVerification-Swift` is not used in any concrete target
I am trying to use SinchVerification in my IOS app. However after I do pod install I get this error:

The dependency SinchVerification-Swift is not used in any concrete target.

What does this mean? What should I do?

答:
Here is usually caused by lost the target in Podfile. And if the Podfile is not in the same dir wiht .xcodeproj, you have also to add project 'path/to/Project.xcodeproj' to specify it.

```<code>platform :ios, '8.1'
use_frameworks!
pod 'SinchVerification-Swift'
target 'your target name.'
</code>```

Body:
Here is usually caused by lost the target in Podfile. And if the Podfile is not in the same dir wiht .xcodeproj, you have also to add project 'path/to/Project.xcodeproj' to specify it.

platform :ios, '8.1'
use_frameworks!
pod 'SinchVerification-Swift'
target 'your target name.'


问:
Accessing IntelliJ IDEA functionality via API
I need to be able to add a svn precommit check to ensure that all java files being committed are properly indented - adhering to our project specific settings. We use IntelliJ IDEA 9.0 for our development. I was wondering if it is possibe to directly access IntelliJ IDEA 9.0's indentation functionality via an API so that I can call it from svn pre-commit hook. Any better ideas? (I don't intend to write plugins)</p>

答: Commit dialog already has certain Before commit actions including Reformat code. Just make sure it's enabled. There should be also an API to provide custom actions for this dialog which will be performed by plug-ins. Check the IDEA Community edition source code to see how to use it.


问:
viewport resize event for flash player
I am new to all of this and can't figure out how to resize the flash player I use for my home media server when the window is resized or orientation changes. I am basing the player size on the size of the viewport. I have searched and tried various versions but they don't work which is most likely due to my lack of knowledge.
Most of the code below was already done, I have commented what I added here for reference.

Link to a sample

viewport.js (added by me)

```<code>var width = $(window).width();
var height = $(window).height();
</code>```

html

```<code><html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Gizmo play_flash</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
 <script type="text/javascript" src="scripts/jwplayer.js"></script>
<script type="text/javascript" src="jquery/jquery.js"></script>
<script type="text/javascript" src="scripts/viewport.js"></script>
<noscript><meta http-equiv="refresh" content="2; URL=noscript.html"></noscript>
</head>

<body style="margin: 0; padding: 0; background-color: #000000">
<div id="outer">

    <div class="player_wrapper" style="width: 100%; height: 100%; margin:0px auto;">
        <div id="player">
            Loading the video player ...
        </div>
    </div>

    <script type="text/javascript">
        jwplayer('player').setup({
            'flashplayer': 'scripts/player.swf',
            'file': '[File.FlashLink]',
            'autostart': 'true',
            'duration': '[File.Duration]',
            'provider': 'scripts/jrmediaprovider.swf',
            'skin': 'scripts/glow.zip',
                    <!--begin mod-->
            'width': width - 5,
            'height': height - 5
                    <!--endmod-->
        });

        jwplayer('player').onComplete(
            function(event) {
                try {
                    window.Gizmo.onComplete();
                } catch (err) { }
            }
        );
    </script>
</div>
</body>
</html>
</code>```

答:
Using the DOM API to detect viewport resize:</p>

```<code>window.addEventListener('resize', (ev) => {
  console.log(window.innerWidth, window.innerHeight);
});
</code>```

Title: viewport resize event for flash player

Body:
I am new to all of this and can't figure out how to resize the flash player I use for my home media server when the window is resized or orientation changes. I am basing the player size on the size of the viewport. I have searched and tried various versions but they don't work which is most likely due to my lack of knowledge.
Most of the code below was already done, I have commented what I added here for reference.

Link to a sample

viewport.js (added by me)

var width = $(window).width();
var height = $(window).height();

html

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Gizmo play_flash</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />

<meta http-equiv="refresh" content="2; URL=noscript.html">

            Loading the video player ...

Body:
Using the DOM API to detect viewport resize:

window.addEventListener('resize', (ev) => {
  console.log(window.innerWidth, window.innerHeight);
});


答:
Try this:</p>

```<code>if($(window).width()>500){
    $.ajax({
       url: 'includes/middle.php',
       success: function(html) {
          $("body").append(html);
       }
    });
}
</code>```

Title: appending elements in jquery

Body:
Try this:

if($(window).width()>500){
    $.ajax({
       url: 'includes/middle.php',
       success: function(html) {
          $("body").append(html);
       }
    });
}


问:
oddly a uibuttons text label won't change
This is very strange. My view is receiving a notification with an index number that I use to find a UIbutton by tag and then change its text label. The only trouble is the text will not change. I've put in break points and the code is being executed.

Is there some peculiarity with variable scopes when using notifications?

```<code>- (void)receiveEvent:(NSNotification *)notification {

    int pass = [[[notification userInfo] valueForKey:@"index"] intValue];
    NSLog(@"button index is %i", pass);

    UIButton *changebut = (UIButton *) [self.view viewWithTag:pass];
    ButtonStatusModel *m= [self.buttoneventpendingarray objectAtIndex:pass];
    NSLog(@"current but status = %i",m.btnstatus);
    if (m.btnstatus==3 ) {
        //this should change the label but it does not;
        [changebut setTitle:@"playing" forState:UIControlStateNormal];
        m.btnstatus=2;
        NSLog(@"should set text to 'playing");
        //[engine addActionToQue:buttonid actionSample:actionsample action:1];

    }else if (m.btnstatus==1) {

        //this should change the label but it does not;
        [changebut setTitle:@"idle" forState:UIControlStateNormal];
        NSLog(@"should set text to 'idle");
        m.btnstatus=0;
        //[engine addActionToQue:buttonid actionSample:actionsample action:0];

    }

}
</code>```

EDIT 1
Thanks to commenters  I've determined that even though my reciveevent function in on my main view controller the function is not being executed from the main thread (dont really understand this) and so thats why the button label will not change.

I used the following code to determine if it was the main thread or not. I think now to change the button label I need to call perform selector on main thread? Is this the correct thing to do? If so I need to pass a function 2 variables, I dont see how perform selector on main thread accomodates this.

```<code>-(void) updatebutton:(int)tag changeto:(int) val
{

    if ([NSThread isMainThread]) {
         {
             NSLog(@"is main thread");
        }
    } else {
         NSLog(@"is not thread");
        [self performSelectorOnMainThread:@selector( /*function with 2 parameters here*/) withObject:nil waitUntilDone:YES];

    }

}
</code>```

EDIT 3*

Using blocks instead of main selector helped me out of my problem.

I really don't understand the whole main thread though. I assumed that if code was in my view controller that any executed code would be performed on the main thread. That seems to be  big fat wrong. I would appreciate a little enlightenment on the matter.

Heres what I used anyway

```<code>-(void) updatebutton:(int)tag changeto:(int) val
{
    UIButton *changebut = (UIButton *) [self.view viewWithTag:tag];

    if ([NSThread isMainThread]) {
         {
             NSLog(@"is main thread");

             if (val==2) {
                 [changebut setTitle:@"playing" forState:UIControlStateNormal];

             }

             if (val==0) {

                     [changebut setTitle:@"idle" forState:UIControlStateNormal];
             }

        }
    } else {
         NSLog(@"is not thread");
        //[self performSelectorOnMainThread:@selector(updatebutton::) withObject:nil waitUntilDone:YES];

        if (val==2) {

            dispatch_async(dispatch_get_main_queue(), ^{
                [changebut setTitle:@"playing" forState:UIControlStateNormal];
            });
        }

        if (val==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [changebut setTitle:@"idle" forState:UIControlStateNormal];
            });
        }

    }

}
</code>```

答:
Try putting

```<code>  [changebut setTitle:@"idle" forState:UIControlStateNormal];
</code>```

in the -viewDidAppear method. If it doesn't work either, make sure that all the outlets are connected in IB. Moreover, try adding a few spaces as the button title in your .xib file (if you have one).

Body:
This is very strange. My view is receiving a notification with an index number that I use to find a UIbutton by tag and then change its text label. The only trouble is the text will not change. I've put in break points and the code is being executed.

Is there some peculiarity with variable scopes when using notifications?

- (void)receiveEvent:(NSNotification *)notification {

    int pass = [[[notification userInfo] valueForKey:@"index"] intValue];
    NSLog(@"button index is %i", pass);

    UIButton *changebut = (UIButton *) [self.view viewWithTag:pass];
    ButtonStatusModel *m= [self.buttoneventpendingarray objectAtIndex:pass];
    NSLog(@"current but status = %i",m.btnstatus);
    if (m.btnstatus==3 ) {
        //this should change the label but it does not;
        [changebut setTitle:@"playing" forState:UIControlStateNormal];
        m.btnstatus=2;
        NSLog(@"should set text to 'playing");
        //[engine addActionToQue:buttonid actionSample:actionsample action:1];

    }else if (m.btnstatus==1) {

        //this should change the label but it does not;
        [changebut setTitle:@"idle" forState:UIControlStateNormal];
        NSLog(@"should set text to 'idle");
        m.btnstatus=0;
        //[engine addActionToQue:buttonid actionSample:actionsample action:0];

    }

}

EDIT 1
Thanks to commenters  I've determined that even though my reciveevent function in on my main view controller the function is not being executed from the main thread (dont really understand this) and so thats why the button label will not change.

I used the following code to determine if it was the main thread or not. I think now to change the button label I need to call perform selector on main thread? Is this the correct thing to do? If so I need to pass a function 2 variables, I dont see how perform selector on main thread accomodates this.

-(void) updatebutton:(int)tag changeto:(int) val
{

    if ([NSThread isMainThread]) {
         {
             NSLog(@"is main thread");
        }
    } else {
         NSLog(@"is not thread");
        [self performSelectorOnMainThread:@selector( /*function with 2 parameters here*/) withObject:nil waitUntilDone:YES];

    }

}

EDIT 3*

Using blocks instead of main selector helped me out of my problem.

I really don't understand the whole main thread though. I assumed that if code was in my view controller that any executed code would be performed on the main thread. That seems to be  big fat wrong. I would appreciate a little enlightenment on the matter.

Heres what I used anyway

-(void) updatebutton:(int)tag changeto:(int) val
{
    UIButton *changebut = (UIButton *) [self.view viewWithTag:tag];

    if ([NSThread isMainThread]) {
         {
             NSLog(@"is main thread");

             if (val==2) {
                 [changebut setTitle:@"playing" forState:UIControlStateNormal];

             }

             if (val==0) {

                     [changebut setTitle:@"idle" forState:UIControlStateNormal];
             }

        }
    } else {
         NSLog(@"is not thread");
        //[self performSelectorOnMainThread:@selector(updatebutton::) withObject:nil waitUntilDone:YES];

        if (val==2) {

            dispatch_async(dispatch_get_main_queue(), ^{
                [changebut setTitle:@"playing" forState:UIControlStateNormal];
            });
        }

        if (val==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [changebut setTitle:@"idle" forState:UIControlStateNormal];
            });
        }

    }

}

Body:
Try putting

  [changebut setTitle:@"idle" forState:UIControlStateNormal];

in the -viewDidAppear method. If it doesn't work either, make sure that all the outlets are connected in IB. Moreover, try adding a few spaces as the button title in your .xib file (if you have one).