问:
How to measure the area of a polygon in ggplot2?

Hi everyone,
I have a number of samples that I would like to draw a polygon for each of them to illustrate the shape of the data. My data look likes this:

```<code>01 0.31707317

02 0.12195122

03 0.09756098

04 0.07317073

05 0.07317073

06 0.07317073

07 0.07317073

08 0.07317073

09 0.04878049

10 0.04878049
</code>```

I can easily draw a radar chart using radarchart, which looks like this:

But I am trying to measure the area of the results shape and use that as a measure of data shape. This is where I struggle.

I tried to save the resulting figure as a vector and use the points there but it looks like I can not pass the chart into a vector. Then I tried rgdal package to exprt my figure as a shapefile and use the coordinates there:

```<code>coorddf <- SpatialPointsDataFrame(radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , pfcol=rgb(0.2,0.5,0.5, 0.2))
, data = radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , cglcol = "white", pfcol=rgb(0.2,0.5,0.5, 0.2))

writeOGR(coorddf, dsn = '.', layer = 'mypoints', driver = "ESRI Shapefile")
</code>```

Which was not a good idea because my data does not have values that can be used as lat and long points..

Any suggestions?

Body:
Hi everyone,
I have a number of samples that I would like to draw a polygon for each of them to illustrate the shape of the data. My data look likes this:

01 0.31707317

02 0.12195122

03 0.09756098

04 0.07317073

05 0.07317073

06 0.07317073

07 0.07317073

08 0.07317073

09 0.04878049

10 0.04878049

I can easily draw a radar chart using radarchart, which looks like this:

But I am trying to measure the area of the results shape and use that as a measure of data shape. This is where I struggle.

I tried to save the resulting figure as a vector and use the points there but it looks like I can not pass the chart into a vector. Then I tried rgdal package to exprt my figure as a shapefile and use the coordinates there:

coorddf <- SpatialPointsDataFrame(radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , pfcol=rgb(0.2,0.5,0.5, 0.2))
, data = radarchart(as.data.frame(ttradar), pcol=rgb(0.2,0.5,0.5) , cglcol = "white", pfcol=rgb(0.2,0.5,0.5, 0.2))

writeOGR(coorddf, dsn = '.', layer = 'mypoints', driver = "ESRI Shapefile")

Which was not a good idea because my data does not have values that can be used as lat and long points..

Any suggestions?

Body:
To expand on @G5W's excellent point:

library(dplyr)
library(ggplot2)

df <- structure(
  list(
    V1 = 1:10,
    V2 = c(
      0.31707317,
      0.12195122,
      0.09756098,
      0.07317073,
      0.07317073,
      0.07317073,
      0.07317073,
      0.07317073,
      0.04878049,
      0.04878049
    )
  ),
  .Names = c("V1", "V2"),
  class = "data.frame",
  row.names = c(NA, -10L))

You can calculate each triangle from its neighbor to the right using dplyr::lead:

areas <- df %>%
  setNames(c("variable", "value")) %>%
  mutate(nextval = lead(value, default = value[1]),
         angle   = (1/10) * (2*pi),
                   # change 1/n to number of variables
         area    = value*nextval*sin(angle)/2)

   variable      value    nextval     angle         area
1         1 0.31707317 0.12195122 0.6283185 0.0113640813
2         2 0.12195122 0.09756098 0.6283185 0.0034966406
3         3 0.09756098 0.07317073 0.6283185 0.0020979843
4         4 0.07317073 0.07317073 0.6283185 0.0015734881
5         5 0.07317073 0.07317073 0.6283185 0.0015734881
6         6 0.07317073 0.07317073 0.6283185 0.0015734881
7         7 0.07317073 0.07317073 0.6283185 0.0015734881
8         8 0.07317073 0.04878049 0.6283185 0.0010489921
9         9 0.04878049 0.04878049 0.6283185 0.0006993281
10       10 0.04878049 0.31707317 0.6283185 0.0045456327

A couple things: notice that I used the default = value[1] to make sure that the NA that would be caused at the end to wrap around to using the first value instead. Also you need to use angles in radians, so that's just 1/n * 2pi. Now that we have all the triangle areas, we can add them:

areas %>% summarise(total = sum(area))

       total
1 0.02954661

This approach is easily extended to multiple groups to compare.

df <- expand.grid(var = 1:8, grp = c("a", "b")) %>%
  mutate(value = runif(length(var), 0.25, 1)) %>%
  group_by(grp) %>%
  mutate(nextval = lead(value, default = value[1]),
         angle = (1/8)*(2*pi),
         area = value*nextval*sin(angle)/2) %>%
  mutate(total = sum(area))

# A tibble: 16 x 7
# Groups:   grp [2]
     var    grp     value   nextval     angle       area     total
   <int> <fctr>     <dbl>     <dbl>     <dbl>      <dbl>     <dbl>
 1     1      a 0.3101167 0.6831233 0.7853982 0.07489956 0.5689067
 2     2      a 0.6831233 0.4166692 0.7853982 0.10063417 0.5689067
 3     3      a 0.4166692 0.4756976 0.7853982 0.07007730 0.5689067
 4     4      a 0.4756976 0.3426595 0.7853982 0.05763002 0.5689067
 5     5      a 0.3426595 0.3107870 0.7853982 0.03765135 0.5689067
 6     6      a 0.3107870 0.3001208 0.7853982 0.03297721 0.5689067
 7     7      a 0.3001208 0.9039894 0.7853982 0.09592115 0.5689067
 8     8      a 0.9039894 0.3101167 0.7853982 0.09911594 0.5689067
 9     1      b 0.9888119 0.3481213 0.7853982 0.12170243 1.1749789
10     2      b 0.3481213 0.8513316 0.7853982 0.10478143 1.1749789
11     3      b 0.8513316 0.9928401 0.7853982 0.29883611 1.1749789
12     4      b 0.9928401 0.6372992 0.7853982 0.22370605 1.1749789
13     5      b 0.6372992 0.8303906 0.7853982 0.18710303 1.1749789
14     6      b 0.8303906 0.3607232 0.7853982 0.10590379 1.1749789
15     7      b 0.3607232 0.2786354 0.7853982 0.03553575 1.1749789
16     8      b 0.2786354 0.9888119 0.7853982 0.09741033 1.1749789

df %>%
  ggplot(aes(var, value)) +
  geom_polygon() +
  geom_text(aes(0,0, label = round(total, 2)), color = "white") +
  facet_grid(~grp) +
  scale_y_continuous("", limits = c(0, 1), expand = c(0,0)) +
  scale_x_continuous("", breaks = 1:8, expand = c(0,0)) +
  theme_minimal() +
  coord_radar()

If you're doing a lot of these, it's worth looking at the ggradar package: http://www.ggplot2-exts.org/ggradar.html

Since I was just doing this one-off, I used a polar coordinate modification from Erwan Le Pennec:
http://www.cmap.polytechnique.fr/~lepennec/R/Radar/RadarAndParallelPlots.html

coord_radar <- function (theta = "x", start = 0, direction = 1)
{
  theta <- match.arg(theta, c("x", "y"))
  r <- if (theta == "x")
    "y"
  else "x"
  ggproto("CoordRadar", CoordPolar, theta = theta, r = r, start = start,
          direction = sign(direction),
          is_linear = function(coord) TRUE)
}


来源: stackexchange

问:
java how to delay time at while grammar
While grammar is infinitely repeat when if condition not meeted.

What I want is delay that between start of while grammar and finish of while grammar.

example,

want code.java

```<code>int count = 1, sum = 0;
while (count < 11){
   count ++;
   System.out.println(count);
   //(after 30 seconds...) what i want is this code.
}
</code>```

therefore, i want same output with down code.

1

(after 30 seconds delay..)

2

(after 30 seconds delay..)

...

10

(after 30 seconds delay..)

Please answer. how to delay time between running while grammar?

答:
If you just want your program to pause for 30 seconds at the end of each iteration of the loop then you can use Thread#sleep for that:

```<code>int count = 1, sum = 0;
while (count < 11) {
    count ++;
    System.out.println(count);
    Thread.sleep(30000);  // 30 seconds = 30K milliseconds
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: java how to delay time at while grammar

Body:
While grammar is infinitely repeat when if condition not meeted.

What I want is delay that between start of while grammar and finish of while grammar.

example,

want code.java

int count = 1, sum = 0;
while (count < 11){
   count ++;
   System.out.println(count);
   //(after 30 seconds...) what i want is this code.
}

therefore, i want same output with down code.

1

(after 30 seconds delay..)

2

(after 30 seconds delay..)

...

10

(after 30 seconds delay..)

Please answer. how to delay time between running while grammar?

Body:
If you just want your program to pause for 30 seconds at the end of each iteration of the loop then you can use Thread#sleep for that:

int count = 1, sum = 0;
while (count < 11) {
    count ++;
    System.out.println(count);
    Thread.sleep(30000);  // 30 seconds = 30K milliseconds
}


问:
HTML inside PHP file not loading external CSS file
I haven't coded for a long time and my skills are basic.
I got a php file. It's a section file from a wordpress theme i am customizing.

My problem is. Made the code to link to an external css file to customize the social media icons, but it's not loading the CSS!

Here's the code:

```<code><!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />
 </head>
 <body>

          <div class="footer-social-icons">
    <h4 class="_14">Follow us on</h4>
    <ul class="social-icons">
        <li><a href="" class="social-icon"> <i class="fa fa-facebook"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-twitter"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-rss"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-youtube"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-linkedin"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-google-plus"></i></a></li>
    </ul>
</div>
</code>```

Here's the whole file code in case you need it:

```<code><!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />
 </head>
 <body>

<?php
 global $onetone_animated, $onetone_section_id, $allowedposttags;
 $i                   = $onetone_section_id ;
 $section_title       = onetone_option( 'section_title_'.$i );
 $section_menu        = onetone_option( 'menu_title_'.$i );
 $section_content     = onetone_option( 'section_content_'.$i );
 $content_model       = onetone_option( 'section_content_model_'.$i);
 $section_subtitle    = onetone_option( 'section_subtitle_'.$i );
 $left_content        = onetone_option( 'section_left_content_'.$i );
 $right_content       = onetone_option( 'section_right_content_'.$i );

 if( !isset($section_content) || $section_content=="" )
    $section_content = onetone_option( 'sction_content_'.$i );

        if( $content_model == '0' || $content_model == ''  ):
        ?>

         <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
       <?php
           $section_title_class = '';
           if( $section_subtitle == '' && !(function_exists('is_customize_preview') && is_customize_preview()))
           $section_title_class = 'no-subtitle';
        ?>
       <h2 class="section-title <?php echo esc_attr($section_title_class); ?> <?php echo 'section_title_'.$i;?>"><?php echo wp_kses($section_title, $allowedposttags);?></h2>
        <?php endif;?>
        <?php if( $section_subtitle != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-subtitle <?php echo 'section_subtitle_'.$i;?>"><?php echo do_shortcode(wp_kses($section_subtitle, $allowedposttags));?></div>
         <?php endif;?>
         <div class="home-section-content">

          <div class="footer-social-icons">
    <h4 class="_14">Follow us on</h4>
    <ul class="social-icons">
        <li><a href="" class="social-icon"> <i class="fa fa-facebook"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-twitter"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-rss"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-youtube"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-linkedin"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-google-plus"></i></a></li>
    </ul>
</div>

         <div class="row">
         <div class="col-md-8"><div class="<?php echo $onetone_animated;?> <?php echo 'section_left_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInLeft" data-imageanimation="no"><?php echo do_shortcode($left_content);?></div></div>
         <div class="col-md-4"><div class="<?php echo $onetone_animated;?> <?php echo 'section_right_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInRight" data-imageanimation="no"><?php echo do_shortcode($right_content);?></div></div>
         </div>
          </div>
           <?php
        else:
        ?>
        <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-title <?php echo 'section_title_'.$i;?>"><?php echo esc_attr($section_title);?></div>
        <?php endif;?>

            <div class="home-section-content <?php echo 'section_content_'.$i;?>">
            <?php
            if(function_exists('Form_maker_fornt_end_main'))
             {
                 $section_content = Form_maker_fornt_end_main($section_content);
              }
             echo do_shortcode(wp_kses($section_content, $allowedposttags));
            ?>
            </div>
              <?php
        endif;
        ?>

 </body>
</html>
</code>```

答:
Your files sit under the web server htdocs folder. You can access them over HTTP by specifying their URI.
change href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.php"

to

href="http://localhost/alfasteel.pt/wp-content/themes/onetone/css/socialmedia.php"

Body:
I haven't coded for a long time and my skills are basic.
I got a php file. It's a section file from a wordpress theme i am customizing.

My problem is. Made the code to link to an external css file to customize the social media icons, but it's not loading the CSS!

Here's the code:

<!DOCTYPE html>

 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />

Follow us on

Here's the whole file code in case you need it:

<!DOCTYPE html>

 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />

<?php
 global $onetone_animated, $onetone_section_id, $allowedposttags;
 $i                   = $onetone_section_id ;
 $section_title       = onetone_option( 'section_title_'.$i );
 $section_menu        = onetone_option( 'menu_title_'.$i );
 $section_content     = onetone_option( 'section_content_'.$i );
 $content_model       = onetone_option( 'section_content_model_'.$i);
 $section_subtitle    = onetone_option( 'section_subtitle_'.$i );
 $left_content        = onetone_option( 'section_left_content_'.$i );
 $right_content       = onetone_option( 'section_right_content_'.$i );

 if( !isset($section_content) || $section_content=="" )
    $section_content = onetone_option( 'sction_content_'.$i );

        if( $content_model == '0' || $content_model == ''  ):
        ?>

         <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
       <?php
           $section_title_class = '';
           if( $section_subtitle == '' && !(function_exists('is_customize_preview') && is_customize_preview()))
           $section_title_class = 'no-subtitle';
        ?>
       <h2 class="section-title <?php echo esc_attr($section_title_class); ?> <?php echo 'section_title_'.$i;?>"><?php echo wp_kses($section_title, $allowedposttags);?>

        <?php endif;?>
        <?php if( $section_subtitle != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-subtitle <?php echo 'section_subtitle_'.$i;?>"><?php echo do_shortcode(wp_kses($section_subtitle, $allowedposttags));?>

         <?php endif;?>

Follow us on

<div class="<?php echo $onetone_animated;?> <?php echo 'section_left_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInLeft" data-imageanimation="no"><?php echo do_shortcode($left_content);?>

<div class="<?php echo $onetone_animated;?> <?php echo 'section_right_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInRight" data-imageanimation="no"><?php echo do_shortcode($right_content);?>

           <?php
        else:
        ?>
        <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-title <?php echo 'section_title_'.$i;?>"><?php echo esc_attr($section_title);?>

        <?php endif;?>

            <div class="home-section-content <?php echo 'section_content_'.$i;?>">
            <?php
            if(function_exists('Form_maker_fornt_end_main'))
             {
                 $section_content = Form_maker_fornt_end_main($section_content);
              }
             echo do_shortcode(wp_kses($section_content, $allowedposttags));
            ?>

              <?php
        endif;
        ?>


问:
How to make a video stream published with FMS available from 2 different urls (on the same domain)
I'm publishing a multibitrate stream with adobe live media encoder to flash media server and i have to duplicate it to two different urls within one domain.
Maybe it's possible by configuring apache or maybe there's another way.
Any help'd be appreciated.
Thx in advance.</p>

答:
If anyone needs this info:

 * create a folder in Flash Media Server 4\applications (i called it 1) and copy all files from Flash Media Server 4\applications\live there.

 * in Flash Media Server 4\applications\live\main.asc (if there's no such file - copy one from Flash Media Server 4\samples\applications\live) add the following code:

 + to application.onAppStart = function():

```<code>conn = new NetConnection();
conn.connect("rtmp://server_ip/1");//ip/new application folder name
</code>```

```<code>application.onPublish = function (clientObj, streamObj){
    trace("got a stream : " + streamObj.name);
    if(conn.isConnected){
        ns = new NetStream(conn);
        ns.attach(streamObj);
        ns.publish(streamObj.name);
        trace("publishing through other app");
    }else{
        trace("connection not ready");
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If anyone needs this info:

 * create a folder in Flash Media Server 4\applications (i called it 1) and copy all files from Flash Media Server 4\applications\live there.

 * in Flash Media Server 4\applications\live\main.asc (if there's no such file - copy one from Flash Media Server 4\samples\applications\live) add the following code:

 + to application.onAppStart = function():

conn = new NetConnection();
conn.connect("rtmp://server_ip/1");//ip/new application folder name

application.onPublish = function (clientObj, streamObj){
    trace("got a stream : " + streamObj.name);
    if(conn.isConnected){
        ns = new NetStream(conn);
        ns.attach(streamObj);
        ns.publish(streamObj.name);
        trace("publishing through other app");
    }else{
        trace("connection not ready");
    }
}


问:
Summarising time series columns with condition in R
I am running into a possible aggregate/summarise problem with this time series dataset.

Below is a dataset containing unique instances of a chat from a internet chatting system.

```<code>chatId  agentId beginning_timestamp ending_timestamp    answer
    1   22      4/07/2016 9:00      4/07/2016 9:30      1
    2   22      4/07/2016 9:26      4/07/2016 9:35      5
    3   22      4/07/2016 9:15      4/07/2016 9:19      5
    4   10      4/07/2016 11:17     4/07/2016 12:13     2
    5   10      4/07/2016 11:29     4/07/2016 11:50     1
</code>```

The unique id field is chatId.

agentId is a unique agent who received this chat

beginning_timestamp is the time when the chat started

ending_timestamp is the time when the chat ended

answer is a continous variable used for later analysis

I would like to use dplyr (or anything else) to summarise the following dataset in this manner:

For every group(agentId and chatId), find out if there is another chat that occurred within the same timeframe (from beginning_timestamp plus 5 minutes to ending_timestamp - 5 minutes)

If there is a chat write out the fact that this unique chat occured while there was another chat ongoing.

Here is a resulting dataset with an additional column(multiple_chats = a discrete variable will do) that I would like to make:

```<code>    chatId  agentId beginning_timestamp ending_timestamp    answer   multiple_chats
        1   22      4/07/2016 9:00      4/07/2016 9:30      1          1
        2   22      4/07/2016 9:26      4/07/2016 9:35      5          0
        3   22      4/07/2016 9:15      4/07/2016 9:19      5          1
        4   10      4/07/2016 11:17     4/07/2016 12:13     2          1
        5   10      4/07/2016 11:29     4/07/2016 11:50     1          1
</code>```

Any answers are appreciated.

答:
Looks like some of your overlaps may be different than what you show in your "resulting dataset", but here is a stab at it with some input from here

```<code>df <- data.frame(chatID = 1:5, agentID = c(22,22,22,10,10),
             beginning_timestamp = c('4/07/2016 9:00', '4/07/2016 9:26', '4/07/2016 9:15', '4/07/2016 11:17', '4/07/2016 11:29'),
             ending_timestamp = c('4/07/2016 9:30', '4/07/2016 9:35', '4/07/2016 9:19', '4/07/2016 12:13', '4/07/2016 11:50'),
             answer = c(1,5,5,2,1))
</code>```

l

```<code>ibrary(tidyverse)
library(lubridate)

df %>%
  mutate(beginning_timestamp = mdy_hm(beginning_timestamp),
         ending_timestamp = mdy_hm(ending_timestamp),
         int = interval(beginning_timestamp + minutes(5),
                        ending_timestamp - minutes(5))) -> df

df$multiple_chats = unlist(tapply(df$int, df$agentID,
                           function(x) as.numeric(rowSums(outer(x, x, int_overlaps))>1)))
</code>```

Body:
I am running into a possible aggregate/summarise problem with this time series dataset.

Below is a dataset containing unique instances of a chat from a internet chatting system.

chatId  agentId beginning_timestamp ending_timestamp    answer
    1   22      4/07/2016 9:00      4/07/2016 9:30      1
    2   22      4/07/2016 9:26      4/07/2016 9:35      5
    3   22      4/07/2016 9:15      4/07/2016 9:19      5
    4   10      4/07/2016 11:17     4/07/2016 12:13     2
    5   10      4/07/2016 11:29     4/07/2016 11:50     1

The unique id field is chatId.

agentId is a unique agent who received this chat

beginning_timestamp is the time when the chat started

ending_timestamp is the time when the chat ended

answer is a continous variable used for later analysis

I would like to use dplyr (or anything else) to summarise the following dataset in this manner:

For every group(agentId and chatId), find out if there is another chat that occurred within the same timeframe (from beginning_timestamp plus 5 minutes to ending_timestamp - 5 minutes)

If there is a chat write out the fact that this unique chat occured while there was another chat ongoing.

Here is a resulting dataset with an additional column(multiple_chats = a discrete variable will do) that I would like to make:

    chatId  agentId beginning_timestamp ending_timestamp    answer   multiple_chats
        1   22      4/07/2016 9:00      4/07/2016 9:30      1          1
        2   22      4/07/2016 9:26      4/07/2016 9:35      5          0
        3   22      4/07/2016 9:15      4/07/2016 9:19      5          1
        4   10      4/07/2016 11:17     4/07/2016 12:13     2          1
        5   10      4/07/2016 11:29     4/07/2016 11:50     1          1

Any answers are appreciated.

Body:
Looks like some of your overlaps may be different than what you show in your "resulting dataset", but here is a stab at it with some input from here

df <- data.frame(chatID = 1:5, agentID = c(22,22,22,10,10),
             beginning_timestamp = c('4/07/2016 9:00', '4/07/2016 9:26', '4/07/2016 9:15', '4/07/2016 11:17', '4/07/2016 11:29'),
             ending_timestamp = c('4/07/2016 9:30', '4/07/2016 9:35', '4/07/2016 9:19', '4/07/2016 12:13', '4/07/2016 11:50'),
             answer = c(1,5,5,2,1))

l

ibrary(tidyverse)
library(lubridate)

df %>%
  mutate(beginning_timestamp = mdy_hm(beginning_timestamp),
         ending_timestamp = mdy_hm(ending_timestamp),
         int = interval(beginning_timestamp + minutes(5),
                        ending_timestamp - minutes(5))) -> df

df$multiple_chats = unlist(tapply(df$int, df$agentID,
                           function(x) as.numeric(rowSums(outer(x, x, int_overlaps))>1)))


问:
Basic bag on the return value of a function on matlab
Consider the matlab function that describe in the image.

enter image description here

As I run this function, I get that y = 1 insted of y = 7 as expected.

Why is this happening?

any response will be appreciated.

Thanks!

答:
Because the while gets false from the first iteration and stop.

use while (a>=v(j)) to resolve your issue.


问:
Is there a reducing function in Clojure that performs the equivalent of `first`?
I'm often writing code of the form

```<code>(->> init
     (map ...)
     (filter ...)
     (first))
</code>```

When converting this into code that uses transducers I'll end up with something like

```<code>(transduce (comp (map ...) (filter ...)) (completing #(reduced %2)) nil init)
</code>```

Writing (completing #(reduced %2)) instead of first doesn't sit well with me at all. It needlessly obscures a very straightforward task. Is there a more idiomatic way of performing this task?

答:
medley has find-first with a transducer arity and xforms has a reducing function called last. I think that the combination of the two is what you're after.

```<code>(ns foo.bar
  (:require
   [medley.core :as medley]
   [net.cgrand.xforms.rfs :as rfs]))

(transduce (comp (map ,,,) (medley/find-first ,,,)) rfs/last init)
</code>```

Body:
I'm often writing code of the form

(->> init
     (map ...)
     (filter ...)
     (first))

When converting this into code that uses transducers I'll end up with something like

(transduce (comp (map ...) (filter ...)) (completing #(reduced %2)) nil init)

Writing (completing #(reduced %2)) instead of first doesn't sit well with me at all. It needlessly obscures a very straightforward task. Is there a more idiomatic way of performing this task?

Body:
medley has find-first with a transducer arity and xforms has a reducing function called last. I think that the combination of the two is what you're after.

(ns foo.bar
  (:require
   [medley.core :as medley]
   [net.cgrand.xforms.rfs :as rfs]))

(transduce (comp (map ,,,) (medley/find-first ,,,)) rfs/last init)


问:
Converting massive binary input string into character string C

I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

```<code>char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}
</code>```

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!

答:
From what I can tell, your binaryToString() function does not do what you'd want it to. The print statement just prints the first eight characters from the address pointed to by char* b.

Instead, you can convert the string of 8 bits to an integer, utilizing a standard C function strtol(). There's no need to convert any further, because binary, hex, decimal, etc, are all just representations of the same data! So once the string is converted to a long, you can use that value to represent an ASCII character.

Updating the implementation (as below), you can then leverage it to print a whole sequence.

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

void binaryToString(char* input, char* output){

    char binary[9] = {0}; // initialize string to 0's

    // copy 8 bits from input string
    for (int i = 0; i < 8; i ++){
        binary[i] = input[i];
    }

    *output  = strtol(binary,NULL,2); // convert the byte to a long, using base 2
}

int main()
{

    char inputStr[] = "01100001011100110110010001100110"; // "asdf" in ascii
    char outputStr[20] = {0}; // initialize string to 0's

    size_t iterations = strlen(inputStr) / 8; // get the # of bytes

    // convert each byte into an ascii value
    for (int i = 0; i < iterations; i++){
        binaryToString(&inputStr[i*8], &outputStr[i]);
    }

    printf("%s", outputStr); // print the resulting string
    return 0;
}
</code>```

I compiled this and it seems to work fine. Of course, this can be done cleaner and safer, but this should help you get started.

Body:
I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!

Body:
From what I can tell, your binaryToString() function does not do what you'd want it to. The print statement just prints the first eight characters from the address pointed to by char* b.

Instead, you can convert the string of 8 bits to an integer, utilizing a standard C function strtol(). There's no need to convert any further, because binary, hex, decimal, etc, are all just representations of the same data! So once the string is converted to a long, you can use that value to represent an ASCII character.

Updating the implementation (as below), you can then leverage it to print a whole sequence.

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

void binaryToString(char* input, char* output){

    char binary[9] = {0}; // initialize string to 0's

    // copy 8 bits from input string
    for (int i = 0; i < 8; i ++){
        binary[i] = input[i];
    }

    *output  = strtol(binary,NULL,2); // convert the byte to a long, using base 2
}

int main()
{

    char inputStr[] = "01100001011100110110010001100110"; // "asdf" in ascii
    char outputStr[20] = {0}; // initialize string to 0's

    size_t iterations = strlen(inputStr) / 8; // get the # of bytes

    // convert each byte into an ascii value
    for (int i = 0; i < iterations; i++){
        binaryToString(&inputStr[i*8], &outputStr[i]);
    }

    printf("%s", outputStr); // print the resulting string
    return 0;
}

I compiled this and it seems to work fine. Of course, this can be done cleaner and safer, but this should help you get started.


问:
Select the number of days a record is present within a certain year/month
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

```<code>November  16 days
December  5 days
Total     21 days
</code>```

I've been beating my head against the wall with this one and am fresh out of ideas.

答:
EDIT: Another minor fix or two...

Edited to give the full answer...

```<code>declare @user_start_date datetime
set @user_start_date = '1/1/2011'
declare @user_end_date datetime
set @user_end_date = '1/10/2011'
declare @job_start_date datetime
set @job_start_date = '1/2/2011'
declare @job_end_date datetime
set @job_end_date = '1/11/2011'

declare @nextStartDate datetime;
set @nextStartDate = str(datepart(mm, @user_start_date)) + '/1/' + str(datepart(yyyy, @user_start_date))
declare @nextEndDate datetime;
set @nextEndDate = dateadd(dd,-1,dateadd(mm,1,@nextStartDate))

create table #monthYears(startDate datetime, endDate datetime)
while (@nextStartDate < @user_end_date) begin
    insert into #monthYears values(@nextStartDate, @nextEndDate)
    set @nextStartDate = dateadd(mm,1,@nextStartDate)
    set @nextEndDate = dateadd(dd,-1,dateadd(mm,1,@nextStartDate))
end

-- Print Months
select [month], [year], case when dayCount < 0 then 0 else dayCount end from (
select month(startDate) month, year(startDate) year , datediff(dd,
    case when startDate > @job_start_date then startDate else @job_start_date end,
    case when endDate < @job_end_date then endDate else @job_end_date end) dayCount
from #monthYears) temp

select datediff(dd,
    case when @user_start_date > @job_start_date then @user_start_date else @job_start_date end,
    case when @user_end_date < @job_end_date then @user_end_date else @job_end_date end)
</code>```

Body:
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

November  16 days
December  5 days
Total     21 days

I've been beating my head against the wall with this one and am fresh out of ideas.

Body:
EDIT: Another minor fix or two...

Edited to give the full answer...

declare @user_start_date datetime
set @user_start_date = '1/1/2011'
declare @user_end_date datetime
set @user_end_date = '1/10/2011'
declare @job_start_date datetime
set @job_start_date = '1/2/2011'
declare @job_end_date datetime
set @job_end_date = '1/11/2011'

declare @nextStartDate datetime;
set @nextStartDate = str(datepart(mm, @user_start_date)) + '/1/' + str(datepart(yyyy, @user_start_date))
declare @nextEndDate datetime;
set @nextEndDate = dateadd(dd,-1,dateadd(mm,1,@nextStartDate))

create table #monthYears(startDate datetime, endDate datetime)
while (@nextStartDate < @user_end_date) begin
    insert into #monthYears values(@nextStartDate, @nextEndDate)
    set @nextStartDate = dateadd(mm,1,@nextStartDate)
    set @nextEndDate = dateadd(dd,-1,dateadd(mm,1,@nextStartDate))
end

-- Print Months
select [month], [year], case when dayCount < 0 then 0 else dayCount end from (
select month(startDate) month, year(startDate) year , datediff(dd,
    case when startDate > @job_start_date then startDate else @job_start_date end,
    case when endDate < @job_end_date then endDate else @job_end_date end) dayCount
from #monthYears) temp

select datediff(dd,
    case when @user_start_date > @job_start_date then @user_start_date else @job_start_date end,
    case when @user_end_date < @job_end_date then @user_end_date else @job_end_date end)


问:
Calling method in ParallelFor
I have one certain method bool Method(Myobject Obj) and I want to call him while I'm in ParallelFor() loop. Can I actually do that? Is this thread-safe or something like that? It feels like something wrong to call method like this.

答:
Thread safety is always decided based on context or specific case.
Let's say, that you have this:

```<code>public static bool Even(int i)
{
    return num % 2 == 0;  //true: even, false: odd
}

public static void ThreadSafe()
{
    bool[] arr = new bool[333];

    Parallel.For(0, arr.Length, index =>
    {
        arr[index] = Even(index);
    });
}
</code>```

Now is it thread safe? Yes.
Each index of the array is assigning a value to one related index in arr.
Thus it can be done in parallel.
But what about now?

```<code>   public static void ThreadUnsafe()
   {
       bool[] arr = new bool[333];

       Parallel.For(0, arr.Length, index =>
       {
           arr[index] = Even(index);
           int index2 = (index + 1) < arr.Length ? (index + 1) : index;
           arr[index2] = Even(index);
       });
    }
</code>```

With given index, we can assign two indexes in arr and some other thread can be writing to it as well. It is not thread-safe as we do not know, what will be the result.

Now you can see, that context in which a method is used can determine its thread safety as well.

Also, there are multiple types of thread safety.

Title: Calling method in ParallelFor

Body:
Thread safety is always decided based on context or specific case.
Let's say, that you have this:

public static bool Even(int i)
{
    return num % 2 == 0;  //true: even, false: odd
}

public static void ThreadSafe()
{
    bool[] arr = new bool[333];

    Parallel.For(0, arr.Length, index =>
    {
        arr[index] = Even(index);
    });
}

Now is it thread safe? Yes.
Each index of the array is assigning a value to one related index in arr.
Thus it can be done in parallel.
But what about now?

   public static void ThreadUnsafe()
   {
       bool[] arr = new bool[333];

       Parallel.For(0, arr.Length, index =>
       {
           arr[index] = Even(index);
           int index2 = (index + 1) < arr.Length ? (index + 1) : index;
           arr[index2] = Even(index);
       });
    }

With given index, we can assign two indexes in arr and some other thread can be writing to it as well. It is not thread-safe as we do not know, what will be the result.

Now you can see, that context in which a method is used can determine its thread safety as well.

Also, there are multiple types of thread safety.


问:
1 - 100 prime or not in Java
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

```<code>    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}
</code>```

答:
For starters, it seems your Scanner isn't being used anywhere. Maybe your code is incomplete?

You can replace the Scanner part where you get the input from the user with a for loop that will give the number to you. Like so:

```<code>for(int number = 1; number <= 100; number++) {
    // code for checking if number is prime or not
}
</code>```

Title: 1 - 100 prime or not in Java

Body:
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}

Body:
For starters, it seems your Scanner isn't being used anywhere. Maybe your code is incomplete?

You can replace the Scanner part where you get the input from the user with a for loop that will give the number to you. Like so:

for(int number = 1; number <= 100; number++) {
    // code for checking if number is prime or not
}


问:
How to check if letter in a string appear in another string in the same order

I would love to check if the letters from a text appear in another text in the same order.

```<code>text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False
</code>```

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

答:
i assume your "in order" means the character match in order. In your example text "Ce" name Arsenic should return False and should return True if text is "eC" instead.

first we check if all the character are inside the matching text, if yes, we further check if the matching index are in order, else we just return False

```<code>def check_text(text, name):
    name_lower = name.lower()
    if all(x in name_lower for x in text.lower()):
        char_index = [name_lower.index(x) for x in text.lower()]
        return char_index == sorted(char_index)
    else:
        return False

>>> check_text("Ce", "Arsenic")
False
>>> check_text("eC", "Arsenic")
True
</code>```

Body:
I would love to check if the letters from a text appear in another text in the same order.

text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

Body:
i assume your "in order" means the character match in order. In your example text "Ce" name Arsenic should return False and should return True if text is "eC" instead.

first we check if all the character are inside the matching text, if yes, we further check if the matching index are in order, else we just return False

def check_text(text, name):
    name_lower = name.lower()
    if all(x in name_lower for x in text.lower()):
        char_index = [name_lower.index(x) for x in text.lower()]
        return char_index == sorted(char_index)
    else:
        return False

>>> check_text("Ce", "Arsenic")
False
>>> check_text("eC", "Arsenic")
True


问:
data consistency check : TypeError: argument of type 'NoneType' is not iterable
so basically i am writing a some codes to cross check if my data is consistent.
I have written the below code but it has been showing TypeError: argument of type 'NoneType' is not iterable, i have tried changing the code quite a few times but still the same error comes out. Many thanks.</p>

```<code>def checkdata(sex,school):
    if (sex == 'F') and ('boys school' in school) :
        return 'inconsistent'
    if (sex == 'M') and ('girls school' in school):
        return 'inconsistent'
    return

def Dif() :
    with arcpy.da.UpdateCursor(DATA_SET,
        [sex, school]) as Cursor :
    for Cols in Cursor :

            Data = checkdata(Cols[0], Cols[1])
            if Data is not None:
                print (Data, " ",Cols)
</code>```

答:
In this instance the 'Cursor' variable is None you can check this by printing it before it is used in the loop.

When the loop tries to iterate over None it raises the error shown.

UPDATE:

In that case I would suggest that school is None and the reasoning above holds. Please include the full error message when asking questions like this.

Body:
so basically i am writing a some codes to cross check if my data is consistent.
I have written the below code but it has been showing TypeError: argument of type 'NoneType' is not iterable, i have tried changing the code quite a few times but still the same error comes out. Many thanks.

def checkdata(sex,school):
    if (sex == 'F') and ('boys school' in school) :
        return 'inconsistent'
    if (sex == 'M') and ('girls school' in school):
        return 'inconsistent'
    return

def Dif() :
    with arcpy.da.UpdateCursor(DATA_SET,
        [sex, school]) as Cursor :
    for Cols in Cursor :

            Data = checkdata(Cols[0], Cols[1])
            if Data is not None:
                print (Data, " ",Cols)


问:
Php libraries error in ubuntu
Im having this problem with php in my ubuntu 16 machine.

I have already install them independently with for example:

```<code>sudo aptitude install php7.0-gettext
</code>```

but still getting those errors.

答:
as we know, php can run windos os and unix-like os, so in php, there are two kind of extension： *.dll and *.so,  in config file(php.ini), we also can see it.

*.dll is the extension used on windows

*.so is the exntesion used on unix-like os

on the ubuntu , you should use *.so extension,  not *.dll extension. and you check the dir /usr/lib/php/20151012, you can kwon that.

Title: Php libraries error in ubuntu

Body:
Im having this problem with php in my ubuntu 16 machine.

I have already install them independently with for example:

sudo aptitude install php7.0-gettext

but still getting those errors.


问:
How to dynamically set the argument to $_GET or $_POST?
I'm writing a function in php to check, if all arguments are set. This is for preventing the program to crash when a argument isn't set.

Unfortunately I get this error:

Notice: Undefined variable: _POST

The code running is the following:

```<code># check for the right arguments
function checkArguments($type, $arg_array) {
    # $type is either 'GET' or 'POST'
    # $arg_array is an array with all the arguments names

    foreach($arg_array as $arg) {
        print(${"_" . $type}["name"]);
        $type = "_" . $type;
        if(!isset($$type[$arg])) {
            $missing[] = $arg;
        }
    }
}
</code>```

答:
You could assign them to a temporary variable and use that.</p>

```<code>$arr = $_GET;
if ($type == "POST") $arr = $_POST;
</code>```

Body:
I'm writing a function in php to check, if all arguments are set. This is for preventing the program to crash when a argument isn't set.

Unfortunately I get this error:

Notice: Undefined variable: _POST

The code running is the following:

# check for the right arguments
function checkArguments($type, $arg_array) {
    # $type is either 'GET' or 'POST'
    # $arg_array is an array with all the arguments names

    foreach($arg_array as $arg) {
        print(${"_" . $type}["name"]);
        $type = "_" . $type;
        if(!isset($$type[$arg])) {
            $missing[] = $arg;
        }
    }
}

Body:
You could assign them to a temporary variable and use that.

$arr = $_GET;
if ($type == "POST") $arr = $_POST;


问:
grab the first item in an object array in DJango Templates
I have a django template that has two different querysets passed through to the html template. I want to go through each item in an query set and display the content, I then want to go through the second array while still in the iniital loop and check to see if two peices of info match. If there is a match between the two peices of info, I want to just grab the first result from teh matching info.

I have a query that grabs a list of group items. I have another query that grabs the list of activities. I want to get all the activity objects that are related to the group through the foreignkey and reference to the group within the activity object. From the list of related activities ot the group, I want to grap the first record and display that record only... If a group (a) has 10 activities related tot he group, I want to grab the first one and display it... Here is my code:

html tempalte:

```<code>    <div class="col-12 info-div">
      {% for group in groups %}
        <div class="row">
          <p class="col-12">
            <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
          </p>
          {% for act in activities %}
            {% if act.group.id == group.id %}
            <p class="col-12">
              {{  act.description | first  }}
            </p>
            {% endif %}
          {% endfor %}
        </div>
      {% endfor %}
    </div>
</code>```

the html above just gives me the first letter of each related activity compared to what i want which is the first item where the group in the activity matches the group being looped through

views.py file :

```<code># grab all of the groups you are a member of
groups = Member.objects.filter(user = user).all()
# the following will be the last activity created for each group
activities = GroupActivity.objects.all()
</code>```

models.py

```<code>class Group(models.Model):
    name = models.CharField(max_length = 25)
    description = models.CharField(max_length = 250, null=True)
    created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
class GroupActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE)
    bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True)
    description = models.CharField(max_length=200, default='some action')
    host = models.CharField(max_length=100, null=True)
    reference = models.IntegerField(default=0)
    category = models.SmallIntegerField(default = 1)
    # 1 - general
    # 2 - specific
    # 3 - no validation
    # 4 - validation
    created = models.DateTimeField(auto_now_add=True)
</code>```

答:
Better answer:

```<code>{% for group in groups %}
    <div class="row">
      <p class="col-12">
        <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
      </p>
      {% with group.groupactivity_set.all|first as act %}
        {% if act %}
        <p class="col-12">
          {{  act.description }}
        </p>
        {% endif %}
      {% endwith %}
    </div>
  {% endfor %}
</code>```

Here we are doing everything in the template, as simple as that.

Body:
I have a django template that has two different querysets passed through to the html template. I want to go through each item in an query set and display the content, I then want to go through the second array while still in the iniital loop and check to see if two peices of info match. If there is a match between the two peices of info, I want to just grab the first result from teh matching info.

I have a query that grabs a list of group items. I have another query that grabs the list of activities. I want to get all the activity objects that are related to the group through the foreignkey and reference to the group within the activity object. From the list of related activities ot the group, I want to grap the first record and display that record only... If a group (a) has 10 activities related tot he group, I want to grab the first one and display it... Here is my code:

html tempalte:

      {% for group in groups %}

            {{ group.group.name }}

          {% for act in activities %}
            {% if act.group.id == group.id %}

              {{  act.description | first  }}

            {% endif %}
          {% endfor %}

      {% endfor %}

the html above just gives me the first letter of each related activity compared to what i want which is the first item where the group in the activity matches the group being looped through

views.py file :

# grab all of the groups you are a member of
groups = Member.objects.filter(user = user).all()
# the following will be the last activity created for each group
activities = GroupActivity.objects.all()

models.py

class Group(models.Model):
    name = models.CharField(max_length = 25)
    description = models.CharField(max_length = 250, null=True)
    created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
class GroupActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE)
    bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True)
    description = models.CharField(max_length=200, default='some action')
    host = models.CharField(max_length=100, null=True)
    reference = models.IntegerField(default=0)
    category = models.SmallIntegerField(default = 1)
    # 1 - general
    # 2 - specific
    # 3 - no validation
    # 4 - validation
    created = models.DateTimeField(auto_now_add=True)

Body:
Better answer:

{% for group in groups %}
    <div class="row">
      <p class="col-12">
        <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
      </p>
      {% with group.groupactivity_set.all|first as act %}
        {% if act %}
        <p class="col-12">
          {{  act.description }}
        </p>
        {% endif %}
      {% endwith %}
    </div>
  {% endfor %}

Here we are doing everything in the template, as simple as that.


问:
Addition on dynamic form fields
I have a form that allows a user to add their past employers. The user can push a button and dynamically add a new employer.

Here is what I need to do: Let's say the user adds 2 employers. I need to first add the number of years spent on each job -

EX: Employer 1 - 2005 - 2007 = 2 years.
     Employer 2 - 2010 - 2015 = 5 year.

Now, I need to total both EX: 7 years.

The form fields are named like the following:

ID1_empAppWorkHistoryStartDateYear
ID1_empAppWorkHistoryEndDateYear

ID2_empAppWorkHistoryStartDateYear
ID2_empAppWorkHistoryEndDateYear

How do I loop over the dynamic input names in JavaScript and calculate the total number of years sent on all jobs (there can be up to 5)

答:
What if you just store the entered values in variables at input time; you might need a function triggered by an HTML form event?.
https://www.w3schools.com/tags/ref_eventattributes.asp

At submit time, if not earlier, you could calculate the difference and add it to whatever place you store the total of years :).

Title: Addition on dynamic form fields


问:
Check if a tree is a Binary Search Tree (BST)
I am trying to solve a binary search tree problem, but I can't pass all of the test cases. I need to return true if the tree is a binary search tree, otherwise, I need to return false. Can anyone tell me what I am doing wrong? </p>

```<code>'''
class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
'''

def checkBST(root):
    if root.left == None and root.right == None:
        return True
    if root == None:
        return True
    if root.left != None:
        if root.left.data < root.data:
            return True
    else:
        return False
    if root.right != None:
        if root.right.data > root.data:
            return True
        else:
            return False
    return chckBST(root.left) and chckBST(root) and chckBST(root.right)
</code>```

答:
So the reason you're not passing some of the tests is because you're only checking one level deep. For instance, if there is a tree such that it has a root.left.right.data > root.data, then your code won't catch that. There is a good explanation here

But the gist is:

Your code will pass this

But it won't pass this Notice the right child of 2 > root.data

I think this solution solves it (sorry for answering a Python question with JS code, but I'm sure you'll get the idea):

```<code>function checkBST(root) {
    let isBST = true;
    let BSTUtil = r => {
        let left, right
        if(r.left) // Bottom out on the left side
            left = BSTUtil(r.left)
        if(r.right) // Bottom out on the right side
            right = BSTUtil(r.right)

        if(left > r.data) // Compare with parent
            isBST = false
        if(right < r.data) // Compare with parent
            isBST = false

        // Return MAX from branch
        if(!left && !right)
            return r.data
        else if(!left)
            return Math.max(right, r.data)
        else
            return Math.max(left, right, r.data)
    }
    BSTUtil(root)
    return isBST;
}
</code>```

Also, please don't use this code, it uses O(n) space to solve the problem, and I'm sure I can find a more efficient solution if I spend some time on the question.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to solve a binary search tree problem, but I can't pass all of the test cases. I need to return true if the tree is a binary search tree, otherwise, I need to return false. Can anyone tell me what I am doing wrong?

'''
class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
'''

def checkBST(root):
    if root.left == None and root.right == None:
        return True
    if root == None:
        return True
    if root.left != None:
        if root.left.data < root.data:
            return True
    else:
        return False
    if root.right != None:
        if root.right.data > root.data:
            return True
        else:
            return False
    return chckBST(root.left) and chckBST(root) and chckBST(root.right)

Body:
So the reason you're not passing some of the tests is because you're only checking one level deep. For instance, if there is a tree such that it has a root.left.right.data > root.data, then your code won't catch that. There is a good explanation here

But the gist is:

Your code will pass this

But it won't pass this Notice the right child of 2 > root.data

I think this solution solves it (sorry for answering a Python question with JS code, but I'm sure you'll get the idea):

function checkBST(root) {
    let isBST = true;
    let BSTUtil = r => {
        let left, right
        if(r.left) // Bottom out on the left side
            left = BSTUtil(r.left)
        if(r.right) // Bottom out on the right side
            right = BSTUtil(r.right)

        if(left > r.data) // Compare with parent
            isBST = false
        if(right < r.data) // Compare with parent
            isBST = false

        // Return MAX from branch
        if(!left && !right)
            return r.data
        else if(!left)
            return Math.max(right, r.data)
        else
            return Math.max(left, right, r.data)
    }
    BSTUtil(root)
    return isBST;
}

Also, please don't use this code, it uses O(n) space to solve the problem, and I'm sure I can find a more efficient solution if I spend some time on the question.


问:
How do I join these two selects, what am I doing wrong?
Ok the task at hand is

Obtain the sum of the prizes that have been distributed the exhibitions, until August 31, 2017, for collections and photos. We assume that the awards have never been deserted.

And my code is more or less this

```<code>select t1.exhibitions, t2.exhibitions

from (
  select exhibitions.premioc
  from exhibitions
  where EXISTS (select exhibitions.priceC
          from exhibitions
          join presentCo on exhibitions.id_e = presentCo.id_e
          where presentaco.premiada > 0
          group by exhibitions.priceC
          )
  ) as  t1

left outer join (select exhibitions
      from exhibitions
      where EXISTS (select exhibitions.priceF
          from exhibitions
          join presentFo on exhibitions.id_e = presentFo.id_e
          where presentafo.preiceC > 0
          group by exhibitions.priceF
          )

  ) as "t2"

on t1.exhibitions= t2.exhibitions;
</code>```

My problem is that I kinda don't know enough of the syntax in SQL and fumbling last minute before delivery (school assignment). I have tried to search and get things to work but I have no idea what I am doing wrong with this part. Any pointer would be awesome. Thank you very much for anything

Edit: being way to late in the night when I posted it I never mentioned the real problem, I get SQL Error: ORA-00933: SQL command not properly ended and don't really get why.

答:
for:

sum of all prizes

distributed at exhibitions, until August 31, 2017

a query would look something like this:

```<code>select sum(prize_money)
from exhibitions
where exhibition_date < '2017-09-01'
</code>```

I suspect the answer is much simpler then you first thought

----

Your existing query has several problems that I an see:

```
select t1.exhibitions  <b>-- this column is not returned by subquery t1</b>
, t2.exhibitions

from (
  select exhibitions.premioc  <b>-- only this column is returned by subquery t1</b>
  from exhibitions
  where EXISTS <b>-- when using EXISTS you need a "correlation" inside the where clause of the subquery</b>
         (select exhibitions.priceC
          from exhibitions
          join presentCo on exhibitions.id_e = presentCo.id_e
          where presentaco.premiada > 0  <b>-- there is NO "correlation" here</b>
          group by exhibitions.priceC
          )
  ) as  t1

left outer join (select exhibitions
      from exhibitions
      where EXISTS ( <b>-- when using EXISTS you need a "correlation" inside the where clause of the subquery</b>
          select exhibitions.priceF
          from exhibitions
          join presentFo on exhibitions.id_e = presentFo.id_e
          where presentafo.preiceC > 0  <b>-- there is NO "correlation" here</b>
          group by exhibitions.priceF
          )

  ) as "t2"

on t1.exhibitions= t2.exhibitions;
```

----

I suggest you need to start new, maybe with this as a starting point?

```<code>  SELECT
        exhibitions.id_e
      , COALESCE(c.prize_c, 0) prize_c
      , COALESCE(f.prize_f, 0) prize_f
  FROM exhibitions
  LEFT JOIN (
        SELECT
              presentCo.id_e
            , SUM(prize) prize_c
        FROM presentCo
        GROUP BY
              presentCo.id_e
  ) AS c ON exhibitions.id_e = c.id_e
  LEFT JOIN (
        SELECT
              presentFo.id_e
            , SUM(proze) price_f
        FROM presentFo
        GROUP BY
              presentFo.id_e
  ) AS f ON exhibitions.id_e = presentFo.id_e
</code>```

But I shall not attempt further suggestions unless I see "sample data" (for each table) and, the "expected result"

Body:
Ok the task at hand is

Obtain the sum of the prizes that have been distributed the exhibitions, until August 31, 2017, for collections and photos. We assume that the awards have never been deserted.

And my code is more or less this

select t1.exhibitions, t2.exhibitions

from (
  select exhibitions.premioc
  from exhibitions
  where EXISTS (select exhibitions.priceC
          from exhibitions
          join presentCo on exhibitions.id_e = presentCo.id_e
          where presentaco.premiada > 0
          group by exhibitions.priceC
          )
  ) as  t1

left outer join (select exhibitions
      from exhibitions
      where EXISTS (select exhibitions.priceF
          from exhibitions
          join presentFo on exhibitions.id_e = presentFo.id_e
          where presentafo.preiceC > 0
          group by exhibitions.priceF
          )

  ) as "t2"

on t1.exhibitions= t2.exhibitions;

My problem is that I kinda don't know enough of the syntax in SQL and fumbling last minute before delivery (school assignment). I have tried to search and get things to work but I have no idea what I am doing wrong with this part. Any pointer would be awesome. Thank you very much for anything

Edit: being way to late in the night when I posted it I never mentioned the real problem, I get SQL Error: ORA-00933: SQL command not properly ended and don't really get why.

Body:
for:

sum of all prizes

distributed at exhibitions, until August 31, 2017

a query would look something like this:

select sum(prize_money)
from exhibitions
where exhibition_date < '2017-09-01'

I suspect the answer is much simpler then you first thought

----

Your existing query has several problems that I an see:

select t1.exhibitions  -- this column is not returned by subquery t1
, t2.exhibitions

from (
  select exhibitions.premioc  -- only this column is returned by subquery t1
  from exhibitions
  where EXISTS -- when using EXISTS you need a "correlation" inside the where clause of the subquery
         (select exhibitions.priceC
          from exhibitions
          join presentCo on exhibitions.id_e = presentCo.id_e
          where presentaco.premiada > 0  -- there is NO "correlation" here
          group by exhibitions.priceC
          )
  ) as  t1

left outer join (select exhibitions
      from exhibitions
      where EXISTS ( -- when using EXISTS you need a "correlation" inside the where clause of the subquery
          select exhibitions.priceF
          from exhibitions
          join presentFo on exhibitions.id_e = presentFo.id_e
          where presentafo.preiceC > 0  -- there is NO "correlation" here
          group by exhibitions.priceF
          )

  ) as "t2"

on t1.exhibitions= t2.exhibitions;

----

I suggest you need to start new, maybe with this as a starting point?

  SELECT
        exhibitions.id_e
      , COALESCE(c.prize_c, 0) prize_c
      , COALESCE(f.prize_f, 0) prize_f
  FROM exhibitions
  LEFT JOIN (
        SELECT
              presentCo.id_e
            , SUM(prize) prize_c
        FROM presentCo
        GROUP BY
              presentCo.id_e
  ) AS c ON exhibitions.id_e = c.id_e
  LEFT JOIN (
        SELECT
              presentFo.id_e
            , SUM(proze) price_f
        FROM presentFo
        GROUP BY
              presentFo.id_e
  ) AS f ON exhibitions.id_e = presentFo.id_e

But I shall not attempt further suggestions unless I see "sample data" (for each table) and, the "expected result"


问:
Child components and DI context
I have an app that has various types of searches - however a lot of the functionality between these searches is the same, additionally the view is almost the same with the exception of a few strings (panel titles etc.).

I have a base SearchComponent and a Specialized search component.  The Specialized search components instantiates the base SearchComponent in the markup and sets the appropriate inputs.

Each specialized search component uses a different search strategy i.e. service instance and method and mapping of the results.

Currently I am binding a function reference to the parent when instantiating the base component so that the parent function can be called.  However it looks like the DI context is different so it complains that my injected service in the parent is not found.

How can I solve this?

Example:

In search-base.ts:

```<code>  @Input() execSearchFn: (query) => Observable<any>;
  @Input() mapTableDataFn: (i: any) => any;

executeSearch(e) {  // Triggered by some event
  this.execSearchFn(e.query);  // delegate to parent for specialized search
}
</code>```

In xyz-search.html:

```<code>   <app-search-base #appSearchBase
    searchTitle="XYZ Search"
    [execSearchFn]="execSearch"
    [mapTableDataFn]="mapTableData">
  </app-search-base>
</code>```

In xyz-search.ts:

```<code>constructor(private xyzService: XYZService) {}

execSearch(query: string) {
 return this.xyzService.search(query);  // does not work! xyzService is undefined!
}
</code>```

This works fine, the function in the parent is called but it cannot find any of the injected attributes.

ERROR is "cannot read property search of undefined".  Sure enough xyzService is injected and defined in the constructor but because the call context is from the base component it's undefined in the execSearch function.

The functionality I am aiming for is similar to defining an abstract method in the base class and a subclass defining the exact behavior for that abstract method.  However Angular does not allow Abstract components so have to use the above workaround.  I can in fact create a regular abstract base class but then I cannot re-use the markup.  I need to re-use both base functionality and base markup.

I am guessing the best way to do this would be to Emit an execute event (rather than using a function reference) and then send the results back via an Input()??  This just sounds too convoluted.

答:
Well this was a hard one to understand. Just for clarifictaion that I got it right: you're trying to get an action performed by a child component (here the search-base) and want to react to it in the parent component (here your xyz-search).

This is usually a good example for an output binding on a function. You are currently providing a function as an input variable, giving code to your child component instead of emitting a call as an output from it. This is kind of the dirty way to do it and it has limits. And you found one, because just giving code will lose context.

So here's what I would do. I'd change your functions from input to output, which  can be done in a few easy steps. Here's the parent component.

```<code><app-search-base #appSearchBase
    searchTitle="XYZ Search"
    (onExecSearch)="execSearch($event)"
    [mapTableDataFn]="mapTableData">
 </app-search-base>
</code>```

We only have to use parentheses and call the parents execSearch function with the $event parameter here (this is crucial, so don't forget that). The parentheses change the binding type from input to output. I renamed the child function to onExecSearch to make it clearer that it is called when something happens.

Now in the child component we have to use the given output function through an output event emitter. This is a common angular pattern if you want to call it like that.

```<code>@Output() onExecSearch: new EventEmitter<string>();

executeSearch(e) {
  this.onExecSearch.emit(e.query);
}
</code>```

We can call the provided output function of the parent by emitting a value of the correct type on the onExecSearch emitter. Your parent execSearch function is bound to the emitter and is therefore called when onExecSearch calls its emit function, but this way it will do it with the correct context.

The child component exposes an EventEmitter property with which it
  emits events when something happens. The parent binds to that event
  property and reacts to those events.

Your XYZ-search.ts doesn't even change, it should get called correctly.

For more information, check this tutorial, they can probably explain it a bit better than me.

Title: Child components and DI context

Body:
I have an app that has various types of searches - however a lot of the functionality between these searches is the same, additionally the view is almost the same with the exception of a few strings (panel titles etc.).

I have a base SearchComponent and a Specialized search component.  The Specialized search components instantiates the base SearchComponent in the markup and sets the appropriate inputs.

Each specialized search component uses a different search strategy i.e. service instance and method and mapping of the results.

Currently I am binding a function reference to the parent when instantiating the base component so that the parent function can be called.  However it looks like the DI context is different so it complains that my injected service in the parent is not found.

How can I solve this?

Example:

In search-base.ts:

  @Input() execSearchFn: (query) => Observable<any>;
  @Input() mapTableDataFn: (i: any) => any;

executeSearch(e) {  // Triggered by some event
  this.execSearchFn(e.query);  // delegate to parent for specialized search
}

In xyz-search.html:

   <app-search-base #appSearchBase
    searchTitle="XYZ Search"
    [execSearchFn]="execSearch"
    [mapTableDataFn]="mapTableData">
  </app-search-base>

In xyz-search.ts:

constructor(private xyzService: XYZService) {}

execSearch(query: string) {
 return this.xyzService.search(query);  // does not work! xyzService is undefined!
}

This works fine, the function in the parent is called but it cannot find any of the injected attributes.

ERROR is "cannot read property search of undefined".  Sure enough xyzService is injected and defined in the constructor but because the call context is from the base component it's undefined in the execSearch function.

The functionality I am aiming for is similar to defining an abstract method in the base class and a subclass defining the exact behavior for that abstract method.  However Angular does not allow Abstract components so have to use the above workaround.  I can in fact create a regular abstract base class but then I cannot re-use the markup.  I need to re-use both base functionality and base markup.

I am guessing the best way to do this would be to Emit an execute event (rather than using a function reference) and then send the results back via an Input()??  This just sounds too convoluted.

Body:
Well this was a hard one to understand. Just for clarifictaion that I got it right: you're trying to get an action performed by a child component (here the search-base) and want to react to it in the parent component (here your xyz-search).

This is usually a good example for an output binding on a function. You are currently providing a function as an input variable, giving code to your child component instead of emitting a call as an output from it. This is kind of the dirty way to do it and it has limits. And you found one, because just giving code will lose context.

So here's what I would do. I'd change your functions from input to output, which  can be done in a few easy steps. Here's the parent component.

<app-search-base #appSearchBase
    searchTitle="XYZ Search"
    (onExecSearch)="execSearch($event)"
    [mapTableDataFn]="mapTableData">
 </app-search-base>

We only have to use parentheses and call the parents execSearch function with the $event parameter here (this is crucial, so don't forget that). The parentheses change the binding type from input to output. I renamed the child function to onExecSearch to make it clearer that it is called when something happens.

Now in the child component we have to use the given output function through an output event emitter. This is a common angular pattern if you want to call it like that.

@Output() onExecSearch: new EventEmitter<string>();

executeSearch(e) {
  this.onExecSearch.emit(e.query);
}

We can call the provided output function of the parent by emitting a value of the correct type on the onExecSearch emitter. Your parent execSearch function is bound to the emitter and is therefore called when onExecSearch calls its emit function, but this way it will do it with the correct context.

The child component exposes an EventEmitter property with which it
  emits events when something happens. The parent binds to that event
  property and reacts to those events.

Your XYZ-search.ts doesn't even change, it should get called correctly.

For more information, check this tutorial, they can probably explain it a bit better than me.


问:
Overriding prototype.toString doesn't work
I have the following code.

```<code>function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test);
</code>```

I expect this to print Test, but it prints Test { myTest: 'Test' }. I thought that overriding toString should use that new function whenever it tries to convert to a string. Any ideas why this isn't working?

答:
Based on some of the answers here I was able to solve this by using the following code. Although it's similar to some existing answers it is slightly different so decided to post it here.

```<code>function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test + "");
</code>```

So just adding + "" to the end of the console.log works perfectly and will run the toString function.

Body:
I have the following code.

function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test);

I expect this to print Test, but it prints Test { myTest: 'Test' }. I thought that overriding toString should use that new function whenever it tries to convert to a string. Any ideas why this isn't working?

Body:
Based on some of the answers here I was able to solve this by using the following code. Although it's similar to some existing answers it is slightly different so decided to post it here.

function Test() {
    this.myTest = "Test";
}

Test.prototype.toString = function testToString() {
    return this.myTest;
};

var test = new Test();
console.log(test + "");

So just adding + "" to the end of the console.log works perfectly and will run the toString function.


问:
How do you store "int" values in an NSMutableArray* or NSMutableDictionary*? Chronic problems with JSON data that come in as integers.
How do you store "int" values in an NSMutableArray or NSMutableDictionary?  Chronic problems with JSON data that come in as integers.

Should I try to store these integers as NSNumber objects or just as strings that contain the integer?

How dangerous is it to do a "raw" (int) conversion on the pointers if I know the values will always be Natural Numbers (numbers>=0 including zero for null.)

The integers I'm always working with are Foreign Key Id's from a database.

答:
You need to use NSNumber, as others have said, or use an NSString with the string representaton of the number. It really doesn't matter which, but the NSNumber will be more efficient.

You can't just throw in an int, let it be interpreted as a pointer, and then cast it back on the way out. The reason is that the object (that the int will be interpreted as a pointer to) will be sent the retain message when it is added to the array, and this will definately cause a crash since it will be an invalid pointer.


问:
make html text input field grow as I type?
I can set initial text input size in css, like so:

```<code>width: 50px;
</code>```

But I would like it to grow when I type until it reaches for example 200px.
Can this be done in straight css, html, preferably without javascript?

Do post your js/jquery solutions too of course, but if this is doable without them - that be great.

my try here:

http://jsfiddle.net/jszjz/2/

答:
Which approach you use, of course, depends on what your end goal is. If you want to submit the results with a form then using native form elements means you don't have to use scripting to submit. Also, if scripting is turned off then the fallback still works without the fancy grow-shrink effects. If you want to get the plain text out of a contenteditable element you can always also use scripting like node.textContent to strip out the html that the browsers insert in the user input.

This version uses native form elements with slight refinements on some of the previous posts.

It allows the content to shrink as well.

Use this in combination with CSS for better control.

```<code><html>

<textarea></textarea>
<br>
<input type="text">

<style>

textarea {
  width: 300px;
  min-height: 100px;
}

input {
  min-width: 300px;
}

<script>

document.querySelectorAll('input[type="text"]').forEach(function(node) {
  var minWidth = parseInt(getComputedStyle(node).minWidth) || node.clientWidth;
  node.style.overflowX = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.width = minWidth + 'px';
    node.style.width = node.scrollWidth + 'px';
  };
});
</code>```

You can use something similar with <textarea> elements

```<code>document.querySelectorAll('textarea').forEach(function(node) {
  var minHeight = parseInt(getComputedStyle(node).minHeight) || node.clientHeight;
  node.style.overflowY = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.height = minHeight + 'px';
    node.style.height = node.scrollHeight + 'px';
  };
});
</code>```

This doesn't flicker on Chrome, results may vary on other browsers, so test.

Body:
I can set initial text input size in css, like so:

width: 50px;

But I would like it to grow when I type until it reaches for example 200px.
Can this be done in straight css, html, preferably without javascript?

Do post your js/jquery solutions too of course, but if this is doable without them - that be great.

my try here:

http://jsfiddle.net/jszjz/2/

Body:
Which approach you use, of course, depends on what your end goal is. If you want to submit the results with a form then using native form elements means you don't have to use scripting to submit. Also, if scripting is turned off then the fallback still works without the fancy grow-shrink effects. If you want to get the plain text out of a contenteditable element you can always also use scripting like node.textContent to strip out the html that the browsers insert in the user input.

This version uses native form elements with slight refinements on some of the previous posts.

It allows the content to shrink as well.

Use this in combination with CSS for better control.

<html>

<textarea></textarea>
<br>
<input type="text">

<style>

textarea {
  width: 300px;
  min-height: 100px;
}

input {
  min-width: 300px;
}

<script>

document.querySelectorAll('input[type="text"]').forEach(function(node) {
  var minWidth = parseInt(getComputedStyle(node).minWidth) || node.clientWidth;
  node.style.overflowX = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.width = minWidth + 'px';
    node.style.width = node.scrollWidth + 'px';
  };
});

You can use something similar with <textarea> elements

document.querySelectorAll('textarea').forEach(function(node) {
  var minHeight = parseInt(getComputedStyle(node).minHeight) || node.clientHeight;
  node.style.overflowY = 'auto'; // 'hidden'
  node.onchange = node.oninput = function() {
    node.style.height = minHeight + 'px';
    node.style.height = node.scrollHeight + 'px';
  };
});

This doesn't flicker on Chrome, results may vary on other browsers, so test.


问:
FATAL: no indexes found in '/home/XXXX/searchengine/config/development.sphinx.conf'
sphinx show me this error when i want to ( rake ts:start )
im using rails 5.1.4 and ruby 2.4.1 </p>

```<code>Sphinx 2.2.9-id64-release (rel22-r5006)
Copyright (c) 2001-2015, Andrew Aksyonoff
Copyright (c) 2008-2015, Sphinx Technologies Inc (http://sphinxsearch.com)
using config file '/home/snoura/searchengine/config/development.sphinx.conf'...
FATAL: no indexes found in '/home/snoura/searchengine/config/development.sphinx.conf'

The Sphinx start command failed:
Command: searchd --pidfile --config "/home/snoura/searchengine/config/development.sphinx.conf"
Status:  1
Output:  See above

There may be more information about the failure in /home/snoura/searchengine/log/development.searchd.log.
</code>```

<p>this is what i have in my model Post.rb </p>

```<code>define_index do
indexes content
indexes :name, sortable: true
end
</code>```

答:
Two things to note here.

First: you're using a very old syntax for defining indices (Taryn's comment on your question is spot on). define_index within a model is the approach of Thinking Sphinx v1/v2. Thinking Sphinx v3 (which is the version that supports Rails 3.2 through to 5.x) expects index definitions to live within the app/indices directory. So, you'll want to add a file there (perhaps post_index.rb) which contains the following:

```<code>ThinkingSphinx::Index.define :post, :with => :active_record do
  indexes content
  indexes name, sortable: true
end
</code>```

The full index definition syntax is available in the documentation:
https://freelancing-gods.com/thinking-sphinx/indexing.html

The second thing to note is that you need to have your indices processed before starting the daemon. This means running rake ts:index.

Body:
sphinx show me this error when i want to ( rake ts:start )
im using rails 5.1.4 and ruby 2.4.1

Sphinx 2.2.9-id64-release (rel22-r5006)
Copyright (c) 2001-2015, Andrew Aksyonoff
Copyright (c) 2008-2015, Sphinx Technologies Inc (http://sphinxsearch.com)
using config file '/home/snoura/searchengine/config/development.sphinx.conf'...
FATAL: no indexes found in '/home/snoura/searchengine/config/development.sphinx.conf'

The Sphinx start command failed:
Command: searchd --pidfile --config "/home/snoura/searchengine/config/development.sphinx.conf"
Status:  1
Output:  See above

There may be more information about the failure in /home/snoura/searchengine/log/development.searchd.log.

this is what i have in my model Post.rb

define_index do
indexes content
indexes :name, sortable: true
end

Body:
Two things to note here.

First: you're using a very old syntax for defining indices (Taryn's comment on your question is spot on). define_index within a model is the approach of Thinking Sphinx v1/v2. Thinking Sphinx v3 (which is the version that supports Rails 3.2 through to 5.x) expects index definitions to live within the app/indices directory. So, you'll want to add a file there (perhaps post_index.rb) which contains the following:

ThinkingSphinx::Index.define :post, :with => :active_record do
  indexes content
  indexes name, sortable: true
end

The full index definition syntax is available in the documentation:
https://freelancing-gods.com/thinking-sphinx/indexing.html

The second thing to note is that you need to have your indices processed before starting the daemon. This means running rake ts:index.


答:
Take a look at code below, let me know if something is unclear, ask, don't just read and copy:

```<code>package com.company;

public class Main {

    public static void main(String[] args) {

        out:

        for (int i = 1; i <= 100 ; i++) {
            for (int j = 2; j <= i / 2 ; j++) {
                if (i % j == 0) {
                    System.out.println(i + " is not prime number.");
                    continue out;
                }
            }
            System.out.println(i + " is prime number.");
        }
    }
}
</code>```

So to just walk over the code real quick:

1.) Create labeled block called out:

```<code>out:
</code>```

2.) Create two nested for loops to check for our numbers being prime or not

3.) If statement in the second for loop will check if our number is not prime (if it's divisible by any number from 1 to itself but not those two numbers)

4.) In case our evaluation in if statement is false we continue looping until our second loop condition fails, then we move outside of the loop and print that number is prime:

```<code>System.out.println(i + " is prime number.");
</code>```

5.) In case our evaluation in if statement is true we enter the if block, we print that number is not prime and we move program control back to the labeled block we created earlier

6.) We continue doing this repeatedly until outter loop check condition fails and our program is done with it's work.

Title: 1 - 100 prime or not in Java

Body:
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}

Body:
Take a look at code below, let me know if something is unclear, ask, don't just read and copy:

package com.company;

public class Main {

    public static void main(String[] args) {

        out:

        for (int i = 1; i <= 100 ; i++) {
            for (int j = 2; j <= i / 2 ; j++) {
                if (i % j == 0) {
                    System.out.println(i + " is not prime number.");
                    continue out;
                }
            }
            System.out.println(i + " is prime number.");
        }
    }
}

So to just walk over the code real quick:

1.) Create labeled block called out:

out:

2.) Create two nested for loops to check for our numbers being prime or not

3.) If statement in the second for loop will check if our number is not prime (if it's divisible by any number from 1 to itself but not those two numbers)

4.) In case our evaluation in if statement is false we continue looping until our second loop condition fails, then we move outside of the loop and print that number is prime:

System.out.println(i + " is prime number.");

5.) In case our evaluation in if statement is true we enter the if block, we print that number is not prime and we move program control back to the labeled block we created earlier

6.) We continue doing this repeatedly until outter loop check condition fails and our program is done with it's work.


问:
%matplotlib qt ends in error - calls PyQt5 instead of PyQt4

I am trying to open graphics in a new window using the command %matplotlib qt in ipython/spyder, but it shows following error

```<code>%matplotlib qt
Traceback (most recent call last):

File "<ipython-input-1-4460ac8d7abe>", line 1, in <module>
get_ipython().magic(u'matplotlib qt')

File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2160, in magic
return self.run_line_magic(magic_name, magic_arg_s)

 File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2081, in run_line_magic
result = fn(*args,**kwargs)

 File "<decorator-gen-105>", line 2, in matplotlib

 File "/usr/lib/python2.7/site-packages/IPython/core/magic.py", line 188, in <lambda>
call = lambda f, *a, **k: f(*a, **k)

 File "/usr/lib/python2.7/site-packages/IPython/core/magics/pylab.py", line 100, in matplotlib
gui, backend = self.shell.enable_matplotlib(args.gui)

 File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2950, in enable_matplotlib
pt.activate_matplotlib(backend)

 File "/usr/lib/python2.7/site-packages/IPython/core/pylabtools.py", line 309, in activate_matplotlib
matplotlib.pyplot.switch_backend(backend)

 File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 231, in switch_backend
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 60, in pylab_setup
[backend_name], 0)

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 16, in <module>
from .backend_qt5 import (

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 18, in <module>
import matplotlib.backends.qt_editor.figureoptions as figureoptions

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_editor/figureoptions.py", line 20, in <module>
import matplotlib.backends.qt_editor.formlayout as formlayout

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_editor/formlayout.py", line 56, in <module>
from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 137, in <module>
from PyQt5 import QtCore, QtGui, QtWidgets

ImportError: No module named PyQt5
</code>```

I didn't install PyQt5, but installed PyQt4 in centos 7.4. Also modified the
file matplotlibrc (/usr/lib64/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc) file to change backend and as follows:

```<code> # If you omit this parameter, it will always default to "Agg", which is a
 # non-interactive backend.
 backend      : Qt4Agg

 # If you are using the Qt4Agg backend, you can choose here
 # to use the PyQt4 bindings or the newer PySide bindings to
 # the underlying Qt4 toolkit.
 backend.qt4 : PyQt4        # PyQt4 | PySide
</code>```

But still it calls PyQt5. After running the command "%matplotlib qt", the back-end changed back into Qt5Agg (print matplotlib.rcParams['backend']), even I wrote Qt4Agg in matplotlibrc.

Note:- I tried "%matplotlib qt4" also

```<code>Warning: Cannot change to a different GUI toolkit: qt4. Using qt instead.
</code>```

答:
Please refer to the IPython 5 configuration page. I don't have a IPython 5 and Python 2.7 set up so I cannot give you the exact configuration code. But inorder to make IPython use Qt4 you will have to follow the following steps:

Create configuration files like giving in this page.

The list of configurations that you will need to change are given on this page. Just go through the list and wherever you see an option between qt4 and qt5 just set those values to qt4 in the config files that you created in step 1.

Hope that helps.

Body:
I am trying to open graphics in a new window using the command %matplotlib qt in ipython/spyder, but it shows following error

%matplotlib qt
Traceback (most recent call last):

File "<ipython-input-1-4460ac8d7abe>", line 1, in <module>
get_ipython().magic(u'matplotlib qt')

File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2160, in magic
return self.run_line_magic(magic_name, magic_arg_s)

 File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2081, in run_line_magic
result = fn(*args,**kwargs)

 File "<decorator-gen-105>", line 2, in matplotlib

 File "/usr/lib/python2.7/site-packages/IPython/core/magic.py", line 188, in <lambda>
call = lambda f, *a, **k: f(*a, **k)

 File "/usr/lib/python2.7/site-packages/IPython/core/magics/pylab.py", line 100, in matplotlib
gui, backend = self.shell.enable_matplotlib(args.gui)

 File "/usr/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2950, in enable_matplotlib
pt.activate_matplotlib(backend)

 File "/usr/lib/python2.7/site-packages/IPython/core/pylabtools.py", line 309, in activate_matplotlib
matplotlib.pyplot.switch_backend(backend)

 File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 231, in switch_backend
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 60, in pylab_setup
[backend_name], 0)

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 16, in <module>
from .backend_qt5 import (

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 18, in <module>
import matplotlib.backends.qt_editor.figureoptions as figureoptions

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_editor/figureoptions.py", line 20, in <module>
import matplotlib.backends.qt_editor.formlayout as formlayout

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_editor/formlayout.py", line 56, in <module>
from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore

 File "/usr/lib64/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 137, in <module>
from PyQt5 import QtCore, QtGui, QtWidgets

ImportError: No module named PyQt5

I didn't install PyQt5, but installed PyQt4 in centos 7.4. Also modified the
file matplotlibrc (/usr/lib64/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc) file to change backend and as follows:

 # If you omit this parameter, it will always default to "Agg", which is a
 # non-interactive backend.
 backend      : Qt4Agg

 # If you are using the Qt4Agg backend, you can choose here
 # to use the PyQt4 bindings or the newer PySide bindings to
 # the underlying Qt4 toolkit.
 backend.qt4 : PyQt4        # PyQt4 | PySide

But still it calls PyQt5. After running the command "%matplotlib qt", the back-end changed back into Qt5Agg (print matplotlib.rcParams['backend']), even I wrote Qt4Agg in matplotlibrc.

Note:- I tried "%matplotlib qt4" also

Warning: Cannot change to a different GUI toolkit: qt4. Using qt instead.


问:
What my Regexp should be?
I am trying to get all check constraints from string definition looking like this

```<code>  CREATE TABLE products(
     id INT PRIMARY KEY     NOT NULL,
     price         REAL,
     title         TEXT,
     CONSTRAINT price_check CHECK (  price > 0),
     constraint title_check CHECK (length(title) > 5 AND (price <= 100.0))
  );
</code>```

with following regexp /CONSTRAINT\s+(\w+)\s+CHECK\s+\((.+?)\)/i but it does't match second constraint, only constraint title_check CHECK (length(title) part of it.

How should I change my regexp (if can at all) to get this to work? Specific language dialect of regexp doesn't matter. Thanks for help.

答:
Ruby's Onigmo engine is quite powerful, and allows you to check parentheses nesting.

```<code>/CONSTRAINT\s+(\w+)\s+CHECK\s+(?<paren>\((?:[^()]|\g<paren>)+\))/i
</code>```

The bit at the end, (?<paren>\((?:[^()]|\g<paren>)+\)), is a recursive definition of a balanced parentheses expression: a "paren" is open parenthesis, then either a non-parenthesis character or a "paren", repeating any number of times; then a closed parenthesis; we want one of those now.

Unfortunately, neither Python nor JavaScript allow you to do this.

Title: What my Regexp should be?

Body:
I am trying to get all check constraints from string definition looking like this

  CREATE TABLE products(
     id INT PRIMARY KEY     NOT NULL,
     price         REAL,
     title         TEXT,
     CONSTRAINT price_check CHECK (  price > 0),
     constraint title_check CHECK (length(title) > 5 AND (price <= 100.0))
  );

with following regexp /CONSTRAINT\s+(\w+)\s+CHECK\s+\((.+?)\)/i but it does't match second constraint, only constraint title_check CHECK (length(title) part of it.

How should I change my regexp (if can at all) to get this to work? Specific language dialect of regexp doesn't matter. Thanks for help.

Body:
Ruby's Onigmo engine is quite powerful, and allows you to check parentheses nesting.

/CONSTRAINT\s+(\w+)\s+CHECK\s+(?<paren>\((?:[^()]|\g<paren>)+\))/i

The bit at the end, (?<paren>\((?:[^()]|\g<paren>)+\)), is a recursive definition of a balanced parentheses expression: a "paren" is open parenthesis, then either a non-parenthesis character or a "paren", repeating any number of times; then a closed parenthesis; we want one of those now.

Unfortunately, neither Python nor JavaScript allow you to do this.