问:
Downloading attachments to directory with IMAP in PHP, randomly works
I found PHP code online to download attachments to a directory using IMAP from here. http://www.nerdydork.com/download-pop3imap-email-attachments-with-php.html

I modified it slightly changing

```<code>        $structure = imap_fetchstructure($mbox, $jk);
        $parts = ($structure->parts);
</code>```

to

```<code>        $structure = imap_fetchstructure($mbox, $jk);
        $parts = ($structure);
</code>```

to get it to run properly, as otherwise I got an error about how stdClass doesn't define a property called $parts. Doing that, I was able to download all the attachments. I tested it again recently though, and it didn't work. Well, it didn't work 6 times, worked the 7th, and then hasn't worked since. I'm thinking it has something to do with me screwing up the parts handling, since count($parts) keeps returning 1 for each message, so it's not finding any attachments I think.

Since it downloaded the attachments at one point with no issues, I feel confident that the area things are getting screwed up is right here. Before this block of code is a for loop that goes through each message in the box, and after it is loop that just goes through $parts for each imap structure. Thanks for any help you can provide. I looked at the imap_fetchstructure page on php.net and can't figure out what I'm doing wrong.

Edit: I just double-checked the folder after typing up my question and it all popped up. I feel like I'm going nuts. I hadn't run the code since a few minutes before I started typing this, and it doesn't make sense to me that it would take this long to trigger. I have some 800 messages in the mailbox, but I figured since it printed my statement at the very end of the PHP that all of the file creation work was done.

答:
```<code>    //may this help you...good luck
    date_default_timezone_set('UTC');
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    ini_set('memory_limit', '-1');
    ini_set('max_execution_time', 0);
    set_time_limit(3000);
    $fName = [];
    if ($subject=='xyz subject' || $subject=='xyz subject')$folder_name = $subject;
    else$folder_name = substr($subject,stripos($subject,':')+2);
    $list = glob('downloads/xyz/'.$folder_name.'/*');
    foreach($list as  $key => $filename){$explodeName = explode('/', $filename);$fName[] = $explodeName[2];}
    foreach($list as $file){if(is_file($file))unlink($file);}

    $hostname = '{imap.gmail.com:993/imap/ssl}Inbox';
    $username = 'xyz.xyz@xyz.com';
    $password = '*******************';

    $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
    $emails   = imap_search($inbox, 'SUBJECT "'.$subject.'"');
    foreach ($emails as $key => $value) {

        $overview = imap_fetch_overview($inbox,$value,0);
        $message_date = new DateTime($overview[0]->date);
        $date = $message_date->format('Ymd');
        $message = imap_fetchbody($inbox,$value,2);
        $structure = imap_fetchstructure($inbox, $value);
        $attachments = [];
        if(isset($structure->parts) && count($structure->parts))
        {
            for($i = 0; $i < count($structure->parts); $i++)
            {
                $attachments[$i] = array(
                        'is_attachment' => false,
                        'filename' => '',
                        'name' => '',
                        'attachment' => ''
                    );
                if($structure->parts[$i]->ifdparameters)
                {
                    foreach($structure->parts[$i]->dparameters as $object)
                    {
                        if(strtolower($object->attribute) == 'filename')
                        {
                            $attachments[$i]['is_attachment'] = true;
                            $attachments[$i]['filename'] = $object->value;
                        }
                    }
                }

                if($structure->parts[$i]->ifparameters)
                {
                    foreach($structure->parts[$i]->parameters as $object)
                    {
                        if(strtolower($object->attribute) == 'name')
                        {
                            $attachments[$i]['is_attachment'] = true;
                            $attachments[$i]['name'] = $object->value;
                        }
                    }
                }

                if($attachments[$i]['is_attachment'])
                {
                    $attachments[$i]['attachment'] = imap_fetchbody($inbox, $value, $i+1);
                    if($structure->parts[$i]->encoding == 3) //3 = BASE64 encoding
                    {
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    elseif($structure->parts[$i]->encoding == 4) //4 = QUOTED-PRINTABLE encoding
                    {
                        $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                    }
                }
            }
            foreach($attachments as $attachment)//iterate through each attachment and save it
            {
                if($attachment['is_attachment'] == 1)
                {
                    $filename = $attachment['name'];
                    if(empty($filename)) $filename = $attachment['filename'];
                    if(empty($filename)) $filename = time() . ".dat";
                    $new_fileName = $date.'-'.$value.'-'.$filename;
                    if(!in_array($new_fileName, $fName))
                    {
                        $folder='./downloads/xyz/'.$folder_name.'/';
                        if(!is_dir($folder))mkdir($folder);
                        $fp = fopen("./". $folder ."/". $date . "-". $value."-". $filename, "w+");
                        fwrite($fp, $attachment['attachment']);
                        fclose($fp);
                    }
                }
            }
        }
        imap_mail_move($inbox,$overview[0]->msgno,'xyz_label');
        imap_expunge($inbox);

        /*  ->Always try to read/open the email by subject/or according to need
            ->Move or Delete Old/not required mail, so that u don't need to search/load lots of email
            ->Avoiding unnecessary and old email of the same subject , is to move/delete the same.
        */
    }
    imap_close($inbox);//Never forget to close the connection
</code>```

Body:
I found PHP code online to download attachments to a directory using IMAP from here. http://www.nerdydork.com/download-pop3imap-email-attachments-with-php.html

I modified it slightly changing

        $structure = imap_fetchstructure($mbox, $jk);
        $parts = ($structure->parts);

to

        $structure = imap_fetchstructure($mbox, $jk);
        $parts = ($structure);

to get it to run properly, as otherwise I got an error about how stdClass doesn't define a property called $parts. Doing that, I was able to download all the attachments. I tested it again recently though, and it didn't work. Well, it didn't work 6 times, worked the 7th, and then hasn't worked since. I'm thinking it has something to do with me screwing up the parts handling, since count($parts) keeps returning 1 for each message, so it's not finding any attachments I think.

Since it downloaded the attachments at one point with no issues, I feel confident that the area things are getting screwed up is right here. Before this block of code is a for loop that goes through each message in the box, and after it is loop that just goes through $parts for each imap structure. Thanks for any help you can provide. I looked at the imap_fetchstructure page on php.net and can't figure out what I'm doing wrong.

Edit: I just double-checked the folder after typing up my question and it all popped up. I feel like I'm going nuts. I hadn't run the code since a few minutes before I started typing this, and it doesn't make sense to me that it would take this long to trigger. I have some 800 messages in the mailbox, but I figured since it printed my statement at the very end of the PHP that all of the file creation work was done.


来源: stackexchange

问:
How to increase the vertical spacing between a Material UI FormLabel and Slider?
I'm working on a map with an image overlay that has adjustable opacity. Here is the component code:

```<code>import React from 'react'
import PropTypes from 'prop-types'
import { MapWithGroundOverlay } from './MapWithGroundOverlay'
import { withStyles } from '@material-ui/core/styles'
import Box from '@material-ui/core/Box'
import FormLabel from '@material-ui/core/FormLabel'
import Slider from '@material-ui/lab/Slider'
import Grid from '@material-ui/core/Grid'
import Paper from '@material-ui/core/Paper'

const styles = theme => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
  label: {
    padding: theme.spacing(3),
  }
})

class AdjustableGroundoverlay extends React.PureComponent {
  constructor(props, context) {
    super(props, context)
    this.state = {opacity: 0.5}
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event, value) {
    this.setState(state => ({
      opacity: value
    }));
  }

  render() {
    return (
      <Grid container className={this.props.classes.root} spacing={2}>
        <Grid item xs={12}>
          <MapWithGroundOverlay
            googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}&v=3.exp&libraries=geometry,drawing,places`}
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `600px` }} />}
            mapElement={<div style={{ height: `100%` }} />}
            opacity={this.state.opacity}
          />
        </Grid>
        <Grid item xs={6}>
          <Paper className={this.props.classes.paper}>
            <Box flexDirection="column">
              <FormLabel className={this.props.classes.label}>Overlay opacity</FormLabel>
              <Slider
                value={this.state.opacity}
                min={0}
                max={1}
                onChange={this.handleChange}
              />
            </Box>
          </Paper>
        </Grid>
      </Grid>
    );
  }
}

AdjustableGroundoverlay.propTypes = {
  classes: PropTypes.object.isRequired,
}

export default withStyles(styles)(AdjustableGroundoverlay)
</code>```

The problem is that the FormLabel and Slider are too close together. If I hover over them, I see that the Slider has a negative margin of -24px:

It seems like the content of the FormLabel therefore sits directly on top of it:

I've tried to change the styling of the Slider by adding these classes to the component in accordance with https://material-ui.com/api/slider/#css:

```<code>          <Slider
            classes={{container: {marginTop: -12}}}
            value={this.state.opacity}
            min={0}
            max={1}
            onChange={this.handleChange}
          />
</code>```

but the spacing between the FormLabel and the Slider remains the same. Any idea what is wrong with this implementation?

Update
I've noticed in the console that there is this error:

I'm not sure why the key 'container' is not valid though since it is mentioned in https://material-ui.com/api/slider/#css.

答:
I resolved this by putting the slider in a Box with mt set to 1:

```<code>      <Paper className={this.props.classes.paper}>
        <Box flexDirection="column">
          <FormLabel className={this.props.classes.label}>Overlay opacity</FormLabel>
          <Box mt={1}>
            <Slider
              value={this.state.opacity}
              min={0}
              max={1}
              onChange={this.handleChange}
            />
          </Box>
        </Box>
      </Paper>
</code>```

Now there is more spacing between the label and the slider:

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a map with an image overlay that has adjustable opacity. Here is the component code:

import React from 'react'
import PropTypes from 'prop-types'
import { MapWithGroundOverlay } from './MapWithGroundOverlay'
import { withStyles } from '@material-ui/core/styles'
import Box from '@material-ui/core/Box'
import FormLabel from '@material-ui/core/FormLabel'
import Slider from '@material-ui/lab/Slider'
import Grid from '@material-ui/core/Grid'
import Paper from '@material-ui/core/Paper'

const styles = theme => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
  label: {
    padding: theme.spacing(3),
  }
})

class AdjustableGroundoverlay extends React.PureComponent {
  constructor(props, context) {
    super(props, context)
    this.state = {opacity: 0.5}
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event, value) {
    this.setState(state => ({
      opacity: value
    }));
  }

  render() {
    return (
      <Grid container className={this.props.classes.root} spacing={2}>
        <Grid item xs={12}>
          <MapWithGroundOverlay
            googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}&v=3.exp&libraries=geometry,drawing,places`}
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `600px` }} />}
            mapElement={<div style={{ height: `100%` }} />}
            opacity={this.state.opacity}
          />
        </Grid>
        <Grid item xs={6}>
          <Paper className={this.props.classes.paper}>
            <Box flexDirection="column">
              <FormLabel className={this.props.classes.label}>Overlay opacity</FormLabel>
              <Slider
                value={this.state.opacity}
                min={0}
                max={1}
                onChange={this.handleChange}
              />
            </Box>
          </Paper>
        </Grid>
      </Grid>
    );
  }
}

AdjustableGroundoverlay.propTypes = {
  classes: PropTypes.object.isRequired,
}

export default withStyles(styles)(AdjustableGroundoverlay)

The problem is that the FormLabel and Slider are too close together. If I hover over them, I see that the Slider has a negative margin of -24px:

It seems like the content of the FormLabel therefore sits directly on top of it:

I've tried to change the styling of the Slider by adding these classes to the component in accordance with https://material-ui.com/api/slider/#css:

          <Slider
            classes={{container: {marginTop: -12}}}
            value={this.state.opacity}
            min={0}
            max={1}
            onChange={this.handleChange}
          />

but the spacing between the FormLabel and the Slider remains the same. Any idea what is wrong with this implementation?

Update
I've noticed in the console that there is this error:

I'm not sure why the key 'container' is not valid though since it is mentioned in https://material-ui.com/api/slider/#css.

Body:
I resolved this by putting the slider in a Box with mt set to 1:

      <Paper className={this.props.classes.paper}>
        <Box flexDirection="column">
          <FormLabel className={this.props.classes.label}>Overlay opacity</FormLabel>
          <Box mt={1}>
            <Slider
              value={this.state.opacity}
              min={0}
              max={1}
              onChange={this.handleChange}
            />
          </Box>
        </Box>
      </Paper>

Now there is more spacing between the label and the slider:


答:
Assuming that we need to do this on the 'm_quintile' list column, pull the column and map through the list, grouped by 'QM' get the mean of 'score1'

```<code>nested_results %>%
    pull(m_quintile) %>%
    map(~ .x %>%
               group_by(QM) %>%
               summarise(Ave = mean(score1)))
</code>```

Or after extracting the column, bind_rows into a single dataset with an identifier column (.id), grouped by 'QM', 'grp', get the mean of 'score1'

```<code>nested_results %>%
   pull(m_quintile) %>%
   bind_rows(, .id = 'grp') %>%
   group_by(grp, QM) %>%
   summarise(Ave = mean(score1))
</code>```

Title: group_by and manipulate nested tibbles

Body:
I have some data and I compute some quantiles based on the scores of some variables. I create the nested tibble using the code below:

Code:

nested_results <- df %>%
  as_tibble() %>%
  mutate(date2 = as.Date(date2)) %>%
  group_by(period) %>%
  nest(.key = "data") %>%
  mutate(m_quintile = map(data, ~select(.x, score1, ID, date2)),
         m_quintile = map(m_quintile, ~mutate(.x, QM = ntile(score1, 2))),
         r_quintile = map(data, ~select(.x, score2, ID, date2)),
         r_quintile = map(r_quintile, ~mutate(.x, QR = ntile(score2, 2))))

Now I want to group_by the column QM and then take the average. I can expand them out using the following:

x <- nested_results$m_quintile[[4]]

x %>%
  group_by(QM) %>%
  summarise(ave = mean(score1))

Which gives me:

# A tibble: 2 x 2
     QM   ave
  <int> <dbl>
1     1 0.644
2     2 0.956

So I want to perform this but over all of the lists in the data.

Data:

df <- structure(list(ID = c("38480210", "95810210", "62937750", "02376R10",
"75884910", "36357610", "31561610", "03076C10", "63707110", "42193310",
"22822V10", "69370C10", "03349M10", "69365610", "72348410", "31190010",
"57174810", "25674610", "02503Y10", "02376R10", "92343E10", "63707110",
"30219G10", "02376R10", "75121210", "61945C10", "11012210", "01741R10",
"62937750", "93114210", "G491BT10", "82981J10", "05361110", "87612E10",
"69370C10", "62949110", "74251V10", "20588710", "30161N10", "98310W10",
"17290810", "44919P50", "78440X10", "56357140", "91704710", "95810210",
"02079K30", "86764P10", "48666K10", "G6543110", "12503M10", "02313510",
"74432010", "44107P10", "88731730", "74331510", "24906P10", "01858110",
"25667710", "60819010", "65249B10", "23355L10", "03349M10", "02376R10",
"44919P50", "88355610", "35461310", "15189T10", "21683110", "17177930",
"60871R20", "89417E10", "03349M10", "06738310", "45337C10", "12738710",
"73763010", "69074210", "H8498910", "69076840", "H2717810", "88579Y10",
"06405810", "88431510", "82655210", "36955010", "23355L10", "30219G10",
"89364110", "31421110", "10113710", "72378710", "77669610", "60871R20",
"12503M10", "83269640", "43258910", "43644010", "87150310", "02376R10"
), date1 = structure(c(14425, 16282, 16555, 14517, 14060, 16009,
14852, 16311, 17347, 14943, 14456, 17896, 16282, 17256, 16860,
17500, 13909, 16708, 14547, 14578, 17682, 16009, 17835, 17317,
14729, 15005, 16982, 16769, 14609, 15399, 17651, 16220, 16402,
16282, 17225, 14609, 14120, 15705, 17044, 16343, 14757, 16860,
15338, 16678, 16038, 14152, 17105, 15552, 17105, 17317, 15856,
16891, 13999, 16220, 17197, 15736, 17651, 17409, 15978, 14609,
16982, 15217, 16678, 16738, 15644, 16493, 17044, 16101, 15884,
16678, 15155, 16038, 15308, 16038, 15705, 16402, 17562, 15125,
15338, 14638, 16070, 16800, 16555, 13969, 16190, 14211, 16070,
14244, 16070, 16101, 16920, 16038, 14334, 15947, 17743, 17347,
14790, 15611, 17378, 17225), class = "Date"), X1 = c(0.0386907942593098,
0.0822307392954826, 0.00774113647639751, 0.456043899059296, -0.110843725502491,
0.0870561078190804, -0.0045542698353529, 0.0563545450568199,
0.00979493372142315, 0.112359501421452, 0.19650287926197, -0.0415076464414597,
0.0489177219569683, 0.129585191607475, 0.0380033850669861, 0.115392759442329,
0.0483566299080849, -0.125885099172592, -0.170278623700142, 0.120593711733818,
0.110884040594101, 0.0393035411834717, 0.0206293966621161, 0.138198047876358,
0.0571495816111565, 0.0612886361777782, 0.0311018992215395, -0.138095214962959,
-0.0137844579294324, -0.0371577367186546, -0.0949702933430672,
0.00815372075885534, 0.0567769445478916, 0.0283002480864525,
0.0251093730330467, 0.0126581704244018, 0.0771583765745163, -0.0120562827214599,
-0.0794527605175972, 0.00395354209467769, -0.0462215766310692,
-0.144782453775406, 0.015947800129652, -0.0333899334073067, 0.0300950203090906,
-0.217901706695557, 0.00726317288354039, 0.0145262870937586,
-0.0980149358510971, -0.15625, 0.0735411867499352, 0.0744226351380348,
-0.0324600748717785, 0.028904378414154, 0.00331502850167453,
0.079360157251358, 0.00059627863811329, -0.0638279989361763,
0.0461367033421993, 0.158714607357979, -0.0510033145546913, -0.13095235824585,
-0.0496198311448097, 0.190316736698151, -0.0712639763951302,
0.0382557362318039, 0.0085659408941865, 0.00949091091752052,
0.283668667078018, -0.121414542198181, -0.0340835973620415, 0.0514483749866486,
-0.0790285691618919, 0.0195272620767355, -0.056249987334013,
0.0512534826993942, 0.0601202398538589, 0.00951375812292099,
-0.0283822026103735, -0.171889260411263, 0.0880646035075188,
-0.0379358939826488, 0.0564114898443222, -0.0941470116376877,
0.0303062964230776, -0.143401876091957, 0.0657545104622841, -0.0439923293888569,
0.0287503190338612, -0.0663194432854652, 0.16533762216568, -0.131995305418968,
0.0266022328287363, -0.0189772360026836, -0.0666859075427055,
-0.0744622349739075, -0.00493999244645238, 0.0300560463219881,
0.0969911441206932, 0.0499435178935528), score1 = c(0.889709759542928,
0.903469924523747, 0.936274855415902, 0.840172917716411, 0.938323955852229,
0.907836986338914, 0.945157831453149, 0.979324203073073, 0.920940353945943,
0.894110161051458, 0.908847794881057, 0.97475724651739, 0.937118479686145,
0.980120977458591, 0.623303306607424, 0.758760289975453, 0.834341187444698,
0.797212924462504, 0.825647909001716, 0.840172917716411, 0.768103754483029,
0.941304519974329, 0.814586219311369, 0.988945234241073, 0.895889262055934,
0.953934207350125, 0.707089430822071, 0.951597633344339, 0.961769494932988,
0.990656146898528, 0.913191248231833, 0.836173815309104, 0.645645826100038,
0.61526193432501, 0.926878672415338, 0.798406831947735, 0.715894830193448,
0.609914447070846, 0.982037009964077, 0.958260690099507, 0.911602782396998,
0.994929081364825, 0.942357992461572, 0.915166869000075, 0.959259622259605,
0.471048178589481, 0.965151413031517, 0.962644520224149, 0.728328414533729,
0.844767123989088, 0.880744018935896, 0.960509971835405, 0.901561159073948,
0.933375301286572, 0.941222955392298, 0.788692675853074, 0.975021500943698,
0.854282162746391, 0.975017263736014, 0.865895403465366, 0.933743132976269,
0.00716484468589074, 0.660694331374853, 0.975355558211521, 0.989302607548638,
0.752631808056627, 0.975284876200517, 0.983936335902952, 0.911492029660943,
0.839999214552006, 0.93598101241571, 0.991730259396069, 0.961880715763936,
0.911068572578018, 0.894289026496564, 0.953439004423798, 0.973516036989061,
0.727264493223711, 0.863272896776261, 0.916593316222779, 0.968803082797289,
0.983502534473476, 0.767304310790636, 0.98164412008614, 0.790234444674146,
0.917347388087877, 0.932513138540991, 0.922235640070869, 0.928466316777634,
0.947699254256095, 0.968973518894286, 0.915476983039877, 0.965341200374593,
0.964086556353561, 0.941095916152213, 0.993534425279995, 0.973964970619073,
0.849059697982275, 0.956578344330122, 0.988945234241073), score2 = c(0.760647198307699,
0.935547201829489, 0.99188287953172, 0.704417398608422, 0.902493763886597,
0.957521348656098, 0.991560272871509, 0.92735166103028, 0.767863082641417,
0.902764742861846, 0.899520282689611, 0.924089953437449, 0.968664643612792,
0.866970855643533, 0.901476962756387, 0.94755176837048, 0.902095296676105,
0.925442465985343, 0.867683186989228, 0.704417398608422, 0.689251219536623,
0.895182904019693, 0.925420151447255, 0.973787880226641, 0.971649355774121,
0.836836284054653, 0.874290288656945, 0.642108765156155, 0.9479805690219,
0.986001188878182, 0.900173154373532, 0.931572233567178, 0.204373496689057,
0.748226591771599, 0.911326831765278, 0.745529165807053, 0.966520301934851,
0.8984684314108, 0.996410303573447, 0.944913839452991, 0.820108952795389,
0.993871872926776, 0.977233364779766, 0.958314403117101, 0.954658754872084,
0.408524852242646, 0.926462982377825, 0.901657771925462, 0.244783410018176,
0.976437829472092, 0.905634213631591, 0.927502557897019, 0.891598180696963,
0.987697157506651, 0.938150919267463, 0.926776348475605, 0.985851315815003,
0.982498338035899, 0.985805489731244, 0.908490790573957, 0.679883185186743,
0.00993418025804333, 0.843573469386974, 0.981867470724874, 0.958967224214118,
0.983500414398743, 0.574198183132523, 0.965866545328729, 0.966640899395171,
0.589766758440325, 0.945728847589739, 0.995058520927149, 0.978123949182993,
0.987534808983012, 0.89453102403482, 0.982809219062493, 0.730292876688027,
0.962628956020742, 0.8586064303671, 0.930644808280356, 0.983088940653883,
0.968752883224036, 0.887189900705482, 0.983184857078597, 0.779431248014471,
0.955492602558785, 0.987272896987165, 0.976334384370231, 0.917912611981472,
0.894706435230544, 0.999499942620125, 0.948601238374727, 0.995016927685647,
0.972298506885195, 0.673023784571769, 0.999064451129489, 0.998527621099781,
0.981617931351593, 0.900129909322293, 0.973787880226641), period = c("July_2008_June_2009",
"July_2014_June_2015", "July_2014_June_2015", "July_2009_June_2010",
"July_2007_June_2008", "July_2013_June_2014", "July_2010_June_2011",
"July_2014_June_2015", "July_2016_June_2017", "July_2010_June_2011",
"July_2009_June_2010", "July_2018_June_2019", "July_2014_June_2015",
"July_2016_June_2017", "July_2015_June_2016", "July_2017_June_2018",
"July_2007_June_2008", "July_2015_June_2016", "July_2009_June_2010",
"July_2009_June_2010", "July_2017_June_2018", "July_2013_June_2014",
"July_2018_June_2019", "July_2016_June_2017", "July_2009_June_2010",
"July_2010_June_2011", "July_2015_June_2016", "July_2015_June_2016",
"July_2009_June_2010", "July_2011_June_2012", "July_2017_June_2018",
"July_2013_June_2014", "July_2014_June_2015", "July_2014_June_2015",
"July_2016_June_2017", "July_2009_June_2010", "July_2008_June_2009",
"July_2012_June_2013", "July_2016_June_2017", "July_2014_June_2015",
"July_2009_June_2010", "July_2015_June_2016", "July_2011_June_2012",
"July_2015_June_2016", "July_2013_June_2014", "July_2008_June_2009",
"July_2016_June_2017", "July_2012_June_2013", "July_2016_June_2017",
"July_2016_June_2017", "July_2012_June_2013", "July_2015_June_2016",
"July_2007_June_2008", "July_2013_June_2014", "July_2016_June_2017",
"July_2012_June_2013", "July_2017_June_2018", "July_2017_June_2018",
"July_2013_June_2014", "July_2009_June_2010", "July_2015_June_2016",
"July_2011_June_2012", "July_2015_June_2016", "July_2015_June_2016",
"July_2012_June_2013", "July_2014_June_2015", "July_2016_June_2017",
"July_2013_June_2014", "July_2012_June_2013", "July_2015_June_2016",
"July_2010_June_2011", "July_2013_June_2014", "July_2011_June_2012",
"July_2013_June_2014", "July_2012_June_2013", "July_2014_June_2015",
"July_2017_June_2018", "July_2010_June_2011", "July_2011_June_2012",
"July_2009_June_2010", "July_2013_June_2014", "July_2015_June_2016",
"July_2014_June_2015", "July_2007_June_2008", "July_2013_June_2014",
"July_2008_June_2009", "July_2013_June_2014", "July_2008_June_2009",
"July_2013_June_2014", "July_2013_June_2014", "July_2015_June_2016",
"July_2013_June_2014", "July_2008_June_2009", "July_2013_June_2014",
"July_2018_June_2019", "July_2016_June_2017", "July_2009_June_2010",
"July_2012_June_2013", "July_2017_June_2018", "July_2016_June_2017"
), date2 = c("2008-02-22", "2014-03-03", "2014-04-01", "2009-03-02",
"2007-03-06", "2012-11-16", "2010-02-22", "2014-01-28", "2016-03-16",
"2010-03-18", "2009-03-04", "2018-01-22", "2014-02-27", "2016-02-11",
"2014-12-10", "2017-03-06", "2007-02-28", "2015-02-17", "2009-03-02",
"2009-03-02", "2016-08-11", "2013-03-20", "2018-02-01", "2016-02-22",
"2008-11-24", "2009-11-18", "2015-02-13", "2015-02-23", "2009-04-01",
"2011-02-17", "2017-02-23", "2013-04-02", "2013-09-10", "2014-02-14",
"2016-01-19", "2008-11-26", "2008-03-07", "2012-03-23", "2016-02-10",
"2014-03-03", "2009-02-27", "2015-02-20", "2011-02-25", "2015-02-24",
"2013-03-01", "2008-02-29", "2016-02-22", "2012-02-24", "2016-02-29",
"2015-12-21", "2012-02-29", "2015-03-02", "2007-02-28", "2013-03-01",
"2016-05-05", "2012-02-09", "2017-02-24", "2017-02-03", "2013-02-27",
"2009-03-02", "2015-02-27", "2010-08-30", "2015-02-27", "2015-02-23",
"2012-02-24", "2013-10-28", "2016-02-18", "2013-04-02", "2012-04-11",
"2015-02-25", "2009-12-02", "2013-02-12", "2011-03-01", "2013-04-23",
"2012-02-28", "2014-02-21", "2017-02-15", "2010-02-17", "2011-02-28",
"2009-02-24", "2013-03-01", "2015-02-12", "2014-02-21", "2007-03-01",
"2012-10-29", "2008-02-22", "2013-02-28", "2008-02-14", "2013-02-27",
"2013-02-28", "2014-12-17", "2013-02-22", "2008-02-28", "2012-11-21",
"2018-02-27", "2016-02-29", "2009-02-26", "2012-02-21", "2017-02-24",
"2016-02-29")), row.names = c(NA, -100L), .internal.selfref = <pointer: 0x0000000008ec1ef0>, class = "data.frame")

Body:
Assuming that we need to do this on the 'm_quintile' list column, pull the column and map through the list, grouped by 'QM' get the mean of 'score1'

nested_results %>%
    pull(m_quintile) %>%
    map(~ .x %>%
               group_by(QM) %>%
               summarise(Ave = mean(score1)))

Or after extracting the column, bind_rows into a single dataset with an identifier column (.id), grouped by 'QM', 'grp', get the mean of 'score1'

nested_results %>%
   pull(m_quintile) %>%
   bind_rows(, .id = 'grp') %>%
   group_by(grp, QM) %>%
   summarise(Ave = mean(score1))


问:
Necessity of const specifier in cast
Suppose I have some code like this:

```<code>void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...
</code>```

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

答:
It depends what you are trying to do.  Your code snippet is confusing for the following reasons:

The function takes a non-const pointer, which means the function may wish to change the contents pointed-to by 'ptr'.

Then, upon entering the function, you cast 'ptr' to a const pointer.  So now the compiler believes that the function has no intention of modifying the contents pointed to by ptr.  It is thus normal for an error to occur when the program invokes:

```<code>azaza->some_field = 123; // not allowed !
</code>```

Depending on your intent, you can write the function in one of two forms:

Option #1: The function does not intend to modify what's pointed-to by ptr:

```<code>void foo( const void * ptr ) {
    const struct some * azaza = (const struct some *) ptr ;
    // ... do something other than writing to 'azaza', for example:
    printf("Some field: %d\n", azaza->some_field ) ;
</code>```

}

Option #2: The function does intend to modify what's pointed-to by ptr:

```<code>void foo(void * ptr ) {
    struct some * azaza = (struct some *) ptr ;
    // ... write to 'azaza', for example:
    azaza->some_field = 123 ;
}
</code>```

Title: Necessity of const specifier in cast

Body:
Suppose I have some code like this:

void foo (void *ptr) {
    const struct some *azaza = (const struct some *)ptr;
    azaza->some_field = 123; // inadvertently assignment => error
    // ...

Is the const specifier really needed in cast?

EDIT: foo is callback function with a particular prototype that I can't change (it's not in my code).

Body:
It depends what you are trying to do.  Your code snippet is confusing for the following reasons:

The function takes a non-const pointer, which means the function may wish to change the contents pointed-to by 'ptr'.

Then, upon entering the function, you cast 'ptr' to a const pointer.  So now the compiler believes that the function has no intention of modifying the contents pointed to by ptr.  It is thus normal for an error to occur when the program invokes:

azaza->some_field = 123; // not allowed !

Depending on your intent, you can write the function in one of two forms:

Option #1: The function does not intend to modify what's pointed-to by ptr:

void foo( const void * ptr ) {
    const struct some * azaza = (const struct some *) ptr ;
    // ... do something other than writing to 'azaza', for example:
    printf("Some field: %d\n", azaza->some_field ) ;

}

Option #2: The function does intend to modify what's pointed-to by ptr:

void foo(void * ptr ) {
    struct some * azaza = (struct some *) ptr ;
    // ... write to 'azaza', for example:
    azaza->some_field = 123 ;
}


问:
*UPDATE* Crystal Reports: Select Expert Formula not pulling all data
gurus.

I have below formula that I have been at it for a while now.

```<code> ({?Position}='ALL' or {Command.category} like {?Position} & "*") and
 ({?Day_Night}='ALL' or {?Day_Night}={command.day} or {?Day_Night}=
 {command.night})
</code>```

The formula only works for two selections, "All" and "day", but the "night" selection doesn't show all the data. I have also tried pairing the position and day selections, but it did not work.

UPDATE
So what I noticed is that when the "Night" parameter is selected, the report is omitting any NULL record for the Day field. the Day field could either be NULL or not, so the Night parameter needs to count the day reocrds as long as the night is greater than 0. The Day parameter doesn't do this and I don't know why?

Another formula that I tried:

```<code>if {?Day_Night} = 'All' then
({?Position}='ALL' or {Command.category} like {?Position} & "*") and {?
Day_Night}='All'
else if {?Day_Night}={command.day} then
({?Position}='ALL' or {Command.category} like {?Position} & "*") and {?
Day_Night}={command.day}
else if {?Day_Night}={command.night} then
({?Position}='ALL' or {Command.category} like {?Position} & "*") and ({?
Day_Night}={command.night} and
(not isnull({Command.day}) or isnull({Command.Day}))
)
</code>```

Any suggestion, please?

答:
Your formula doesn't make any sense to me as you are directly comparing parameter field to database field, which won't return any result.

Normally select expert need to be used to fetch data from database, so your case would be. Take below as the example.

```<code>if {?Day_Night}="day"
Then {command.day}
</code>```

This will fetch data, in the same way for night aswell.

Body:
gurus.

I have below formula that I have been at it for a while now.

 ({?Position}='ALL' or {Command.category} like {?Position} & "*") and
 ({?Day_Night}='ALL' or {?Day_Night}={command.day} or {?Day_Night}=
 {command.night})

The formula only works for two selections, "All" and "day", but the "night" selection doesn't show all the data. I have also tried pairing the position and day selections, but it did not work.

UPDATE
So what I noticed is that when the "Night" parameter is selected, the report is omitting any NULL record for the Day field. the Day field could either be NULL or not, so the Night parameter needs to count the day reocrds as long as the night is greater than 0. The Day parameter doesn't do this and I don't know why?

Another formula that I tried:

if {?Day_Night} = 'All' then
({?Position}='ALL' or {Command.category} like {?Position} & "*") and {?
Day_Night}='All'
else if {?Day_Night}={command.day} then
({?Position}='ALL' or {Command.category} like {?Position} & "*") and {?
Day_Night}={command.day}
else if {?Day_Night}={command.night} then
({?Position}='ALL' or {Command.category} like {?Position} & "*") and ({?
Day_Night}={command.night} and
(not isnull({Command.day}) or isnull({Command.Day}))
)

Any suggestion, please?

Body:
Your formula doesn't make any sense to me as you are directly comparing parameter field to database field, which won't return any result.

Normally select expert need to be used to fetch data from database, so your case would be. Take below as the example.

if {?Day_Night}="day"
Then {command.day}

This will fetch data, in the same way for night aswell.


问:
How to get Distinct List
I found online soluton like this:

```<code>import 'package:queries/collections.dart';

void main() {
  List<String> list = ["a", "a", "b", "c", "b", "d"];
  var result = new Collection(list).distinct();
  print(result.toList());
}
</code>```

But, I don't know how to convert var result back to List<Widget>.

答:
There is a way that is a lot easier and does not require any additional imports.

You can convert your List to a Set which inherently only contains distinct elements and then convert that Set back to a List.

If you are using Dart 2.3 or higher (environment: sdk: ">=2.3.0 <3.0.0"), you can use the following idiomatic version:

```<code>List<String> list = ['a', 'a', 'b', 'c', 'b', 'd'];
List result = [...{...list}];
</code>```

The ... spread operator for iterables was just introduced with Dart 2.3.

Otherwise, you can just use old syntax:

```<code>List<String> list = ["a", "a", "b", "c", "b", "d"];
List result = list.toSet().toList();
</code>```

Title: How to get Distinct List

Body:
I found online soluton like this:

import 'package:queries/collections.dart';

void main() {
  List<String> list = ["a", "a", "b", "c", "b", "d"];
  var result = new Collection(list).distinct();
  print(result.toList());
}

But, I don't know how to convert var result back to List<Widget>.

Body:
There is a way that is a lot easier and does not require any additional imports.

You can convert your List to a Set which inherently only contains distinct elements and then convert that Set back to a List.

If you are using Dart 2.3 or higher (environment: sdk: ">=2.3.0 <3.0.0"), you can use the following idiomatic version:

List<String> list = ['a', 'a', 'b', 'c', 'b', 'd'];
List result = [...{...list}];

The ... spread operator for iterables was just introduced with Dart 2.3.

Otherwise, you can just use old syntax:

List<String> list = ["a", "a", "b", "c", "b", "d"];
List result = list.toSet().toList();


问:
Clarification on why my JS closure is not returning properly?
I'm working on a solution for Two-Sum (perhaps a bit overengineered, but it's mostly to get me comfortable with recursion and closures) and I'm trying to avoid having a counter globally if necessary. However, my function is returning undefined and I don't really know what I'm doing wrong.

So I wrapped my functionality (originally innerFunction was the entirety of the function and startingIndex was global) in an inner function, set returnArray to grab the base case once the recursion in innerFunction finishes, and return... returnArray. It doesn't seem to matter where I assign returnArray to the return value of innerFunction, it still isn't defined. There has to be something about the execution contexts that I'm missing and I'm sure it's obvious but I'm drawing a blank.

function twoSum(numArr, target) {
  let startingIndex = 0;
  let returnArray = [];

  function innerFunction(array, integer) {
    let startNum = array.shift();
    let subtractedNum = integer - startNum;
    let found = array.findIndex(function(element) {
      return element === subtractedNum
    })

    if (found >= 0) {
      //found is the index of the shortened array
      //add 1 for the initial shift
      //add starting index, which doubles to track the amount of shifts thus far
      let endingIndex = found + 1 + startingIndex
      return [startingIndex, endingIndex];
    } else {
      startingIndex++;
      innerFunction(array, integer);
    }
  }
  returnArray = innerFunction(numArr, target)
  return returnArray;
}

console.log(twoSum([4,2,5,7,8,1,9,12,3], 15));```

I expect, say, twoSum([4,2,5,7,8,1,9,12,3], 15) to output [3,4] as it was before I wrapped the function. What am I missing?

答:
Your innerFunction returns nothing in else branch, but you assigning return value from its call to a returnArray variable.

You must return result of recursion call too:

```<code> } else {
     startingIndex++;
     return innerFunction(array, integer);
 }
</code>```

Body:
I'm working on a solution for Two-Sum (perhaps a bit overengineered, but it's mostly to get me comfortable with recursion and closures) and I'm trying to avoid having a counter globally if necessary. However, my function is returning undefined and I don't really know what I'm doing wrong.

So I wrapped my functionality (originally innerFunction was the entirety of the function and startingIndex was global) in an inner function, set returnArray to grab the base case once the recursion in innerFunction finishes, and return... returnArray. It doesn't seem to matter where I assign returnArray to the return value of innerFunction, it still isn't defined. There has to be something about the execution contexts that I'm missing and I'm sure it's obvious but I'm drawing a blank.

function twoSum(numArr, target) {
  let startingIndex = 0;
  let returnArray = [];

  function innerFunction(array, integer) {
    let startNum = array.shift();
    let subtractedNum = integer - startNum;
    let found = array.findIndex(function(element) {
      return element === subtractedNum
    })

    if (found >= 0) {
      //found is the index of the shortened array
      //add 1 for the initial shift
      //add starting index, which doubles to track the amount of shifts thus far
      let endingIndex = found + 1 + startingIndex
      return [startingIndex, endingIndex];
    } else {
      startingIndex++;
      innerFunction(array, integer);
    }
  }
  returnArray = innerFunction(numArr, target)
  return returnArray;
}

console.log(twoSum([4,2,5,7,8,1,9,12,3], 15));

I expect, say, twoSum([4,2,5,7,8,1,9,12,3], 15) to output [3,4] as it was before I wrapped the function. What am I missing?

Body:
Your innerFunction returns nothing in else branch, but you assigning return value from its call to a returnArray variable.

You must return result of recursion call too:

 } else {
     startingIndex++;
     return innerFunction(array, integer);
 }


问:
Is it necessary to create a Copy Constructor for derived classes?
If i have a base class with a complex data member, let's say char*, and at the end of my inheritance chain I have another class with the same kind of DM, do i have to implement the CCTORs of all the other classes on the way?

for example:

Animal Class:

```<code>class Animal
{
    int age;
    char* name;
    Animal() { ... }
    Animal(const Animal &animal) { ..deep copying name..}
}
</code>```

Mammal Class:

```<code>class Mammal : public Animal
{
    int height;
    Mammal() { ... }
}
</code>```

Horse Class:

```<code>class Horse : public Mammal
{
    char* color;
    Horse() { ... }
    Horse(const Horse &horse ) { ..deep copying color..}
}
</code>```

Do i need to implement a CCTOR in Mammal, even though it has only an int as a data member?

Basically my question is: when copying a complex object (built from several classes), does the compiler activate the CCTOR of each part separately?

Edit:
To be clear, i want to copy a Horse object. If i write my code as above, will its name be deep copied as well?

答:
Do i need to implement a CCTOR in Mammal, even though it has only an int as a data member?

No.

when copying a complex object (built from several classes), does the compiler activate the CCTOR of each part separately?

Yes.

See e.g. https://en.cppreference.com/w/cpp/language/copy_constructor#Implicitly-defined_copy_constructor:

For non-union class types (class and struct), the constructor performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization.

(Emphasis mine.)

It's like the base object is just another member of the class. If Animal works like a proper value type (has a copy constructor, assignment operator, and destructor that do the right thing), you don't have to do anything special in derived classes like Mammal.

Note, however, that modern C++ style strives to keep member management out of constructors. That is, e.g. Horse shouldn't be concerned with allocating (and deallocating) memory for color in its constructors (and destructor).

Instead every member should manage itself (you'll have to change the type of color to something else, e.g. std::string), so the compiler-generated default copy constructor and destructor work just fine.

Body:
If i have a base class with a complex data member, let's say char*, and at the end of my inheritance chain I have another class with the same kind of DM, do i have to implement the CCTORs of all the other classes on the way?

for example:

Animal Class:

class Animal
{
    int age;
    char* name;
    Animal() { ... }
    Animal(const Animal &animal) { ..deep copying name..}
}

Mammal Class:

class Mammal : public Animal
{
    int height;
    Mammal() { ... }
}

Horse Class:

class Horse : public Mammal
{
    char* color;
    Horse() { ... }
    Horse(const Horse &horse ) { ..deep copying color..}
}

Do i need to implement a CCTOR in Mammal, even though it has only an int as a data member?

Basically my question is: when copying a complex object (built from several classes), does the compiler activate the CCTOR of each part separately?

Edit:
To be clear, i want to copy a Horse object. If i write my code as above, will its name be deep copied as well?


答:
No you don't.  By default (like Mammal), the copy constructor will invoke the copy constructor of each base class (in order), and then the copy constructor of each member variable (in order).  Thus the copy constructor for Mammal is fine.

Note my point about "copy constructor of each member variable".  Of course the copy constructor of char* does nothing - but if you wrap char* inside a class with a suitable copy constructor, then Animal and Horse can both use that class for their member variable - and won't need their own copy constructor.

In fact of course, std::string is already provided for you (but I assume you have a more complex case in reality).

Title: Is it necessary to create a Copy Constructor for derived classes?


问:
Typescript error in server file for NextJS
I'm using the following package versions:

next v8.1.1-canary.42

@types/next v8.0.5

server.js

```<code>import next from 'next';
const app = next({ dev: isDevelopment });
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": ["node_modules"]
}
</code>```

I get the following Typescript error:

```<code>Cannot invoke an expression whose type lacks a call signature. Type 'typeof import(".../node_modules/next/types/index")' has no compatible call signatures.
</code>```

I can't understand what's going on here. Can anyone help explain this error and why one of the core functions for this popular package throws it? Do I need to manually extend some Next types for something that's missing?

答:
Since your code actually works with next v8.1.0 (the latest released version) and @types/next v8.0.0, but breaks with next v8.1.1-canary.42, it might just mean that they introduced some incompatible changes that made the existing .d.ts files out of date. The @types/* packages are maintained by independent volunteers for those packages that don't bother publishing the TypeScript type definitions, and are often late to update, especially if we are talking about some pre-released version.

Can you consider using the latest version of next (v8.1.0)?

As an alternative, you might try to understand what changed between versions, and produce your own .d.ts files to use.

Body:
I'm using the following package versions:

next v8.1.1-canary.42

@types/next v8.0.5

server.js

import next from 'next';
const app = next({ dev: isDevelopment });

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": ["node_modules"]
}

I get the following Typescript error:

Cannot invoke an expression whose type lacks a call signature. Type 'typeof import(".../node_modules/next/types/index")' has no compatible call signatures.

I can't understand what's going on here. Can anyone help explain this error and why one of the core functions for this popular package throws it? Do I need to manually extend some Next types for something that's missing?


问:
Extracting 'href' under 'a' tag
I'm trying to extract a link under "a href="link"..."

As there are multiple rows I iterate over every one of them. The first link per row is the one I need so I use find_all('tr') and find('a').
I know find('a') returns a Nonetype but do not know how to work around this

I had a piece of code that worked but is inefficient (in comments).

```<code>sauce = urllib.request.urlopen('https://morocco.observation.org/soortenlijst_wg_v3.php')
soup = bs.BeautifulSoup(sauce, 'lxml')

tabel = soup.find('table', {'class': 'tablesorter'})
for i in tabel.find_all('tr'):
#     if 'view' in i.get('href'):
#         link_list.append(i.get('href'))

    link = i.find('a')
#<a class="z1" href="/soort/view/164?from=1987-12-05&to=2019-05-31">Common Reed Bunting - <em>Emberiza schoeniclus</em></a>
</code>```

How do I retrieve the link under href and work around the Nonetype getting only /soort/view/164?from=1987-12-05&to=2019-05-31?

Thanks in advance

答:
A logical way is to use nth-of-type to isolate the target column

```<code>import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://morocco.observation.org/soortenlijst_wg_v3.php')
soup = bs(r.content, 'lxml')
base = 'https://morocco.observation.org'
urls = [base + item['href'] for item in soup.select('#mytable_S td:nth-of-type(3) a')]
</code>```

You could also pass a list of classes

```<code>urls = [base + item['href'] for item in soup.select('.z1, .z2,.z3,.z4')]
</code>```

Or even use starts with, ^, operator for class

```<code>urls = [base + item['href'] for item in soup.select('[class^=z]')]
</code>```

Or contains, *, operator for href

```<code>urls = [base + item['href'] for item in soup.select('[href*=view]')]
</code>```

Read about different css selector methods here: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Title: Extracting 'href' under 'a' tag

Body:
I'm trying to extract a link under "a href="link"..."

As there are multiple rows I iterate over every one of them. The first link per row is the one I need so I use find_all('tr') and find('a').
I know find('a') returns a Nonetype but do not know how to work around this

I had a piece of code that worked but is inefficient (in comments).

sauce = urllib.request.urlopen('https://morocco.observation.org/soortenlijst_wg_v3.php')
soup = bs.BeautifulSoup(sauce, 'lxml')

tabel = soup.find('table', {'class': 'tablesorter'})
for i in tabel.find_all('tr'):
#     if 'view' in i.get('href'):
#         link_list.append(i.get('href'))

    link = i.find('a')
#Common Reed Bunting - Emberiza schoeniclus

How do I retrieve the link under href and work around the Nonetype getting only /soort/view/164?from=1987-12-05&to=2019-05-31?

Thanks in advance

Body:
A logical way is to use nth-of-type to isolate the target column

import requests
from bs4 import BeautifulSoup as bs
r = requests.get('https://morocco.observation.org/soortenlijst_wg_v3.php')
soup = bs(r.content, 'lxml')
base = 'https://morocco.observation.org'
urls = [base + item['href'] for item in soup.select('#mytable_S td:nth-of-type(3) a')]

You could also pass a list of classes

urls = [base + item['href'] for item in soup.select('.z1, .z2,.z3,.z4')]

Or even use starts with, ^, operator for class

urls = [base + item['href'] for item in soup.select('[class^=z]')]

Or contains, *, operator for href

urls = [base + item['href'] for item in soup.select('[href*=view]')]

Read about different css selector methods here: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors


问:
validate XML with Schematron
I have the following xml and I would like to unwrap the ph element which is greater than 2.

Input:(xml)

```<code><ul>
 <li>
   <ph>123</ph>
 </li>
 <li>
   <ph>456</ph>
 </li>
 <li>
   <ph>abc</ph>
 </li>
<li>
<ph>xyz</ph>
</li>
</ul>
</code>```

    O/P:

```<code><ul>
 <li>
   <ph>123</ph>
 </li>
 <li>
   <ph>456</ph>
 </li>
 <li>
abc
 </li>
<li>
xyz
</li>
</ul>
</code>```

and the below code doesn't work to get the desired output

```<code><sch:pattern>
        <sch:rule context="*/ph" role="error">
            <sch:assert test="not(node()>2)" sqf:fix="unwrap"><sch:name/> element not
                allowed</sch:assert>
            <sqf:fix id="unwrap">
                <sqf:description>
                    <sqf:title>unwrap <sch:name/> element</sqf:title>
                </sqf:description>
                <sqf:replace select="node()"></sqf:replace>
            </sqf:fix>
        </sch:rule>
</code>```

Regards,
Shil

答:
Ok, assuming that you mean with "greater than 2" the index of the li elements, you could do the following:

Set the context to li[position() gt 2] to get only the li elements with a position greater than 2.

Check if there is a ph element.

Make the unwrap sqf:fix starting from the li element.

The solution would look like this:

    <sch:rule context="li[position() gt 2]">
        <sch:report test="ph" sqf:fix="unwrap">ph element not allowed.</sch:report>
        <sqf:fix id="unwrap">
            <sqf:description>
                <sqf:title>Unwrap ph element.</sqf:title>
            </sqf:description>
            <sqf:replace match="ph" select="node()"/>
        </sqf:fix>
    </sch:rule>
```

Another way would be, to set the context to ul. In this case you would only get one error message and the QuickFix could do the unwrap at once.

Title: validate XML with Schematron

Body:
I have the following xml and I would like to unwrap the ph element which is greater than 2.

Input:(xml)

   <ph>123</ph>

   <ph>456</ph>

   <ph>abc</ph>

<ph>xyz</ph>

    O/P:

   <ph>123</ph>

   <ph>456</ph>

abc

xyz

and the below code doesn't work to get the desired output

<sch:pattern>
        <sch:rule context="*/ph" role="error">
            <sch:assert test="not(node()>2)" sqf:fix="unwrap"><sch:name/> element not
                allowed</sch:assert>
            <sqf:fix id="unwrap">
                <sqf:description>
                    <sqf:title>unwrap <sch:name/> element</sqf:title>
                </sqf:description>
                <sqf:replace select="node()"></sqf:replace>
            </sqf:fix>
        </sch:rule>

Regards,
Shil

Body:
Ok, assuming that you mean with "greater than 2" the index of the li elements, you could do the following:

Set the context to li[position() gt 2] to get only the li elements with a position greater than 2.

Check if there is a ph element.

Make the unwrap sqf:fix starting from the li element.

The solution would look like this:

    <sch:rule context="li[position() gt 2]">
        <sch:report test="ph" sqf:fix="unwrap">ph element not allowed.</sch:report>
        <sqf:fix id="unwrap">
            <sqf:description>
                <sqf:title>Unwrap ph element.</sqf:title>
            </sqf:description>
            <sqf:replace match="ph" select="node()"/>
        </sqf:fix>
    </sch:rule>

Another way would be, to set the context to ul. In this case you would only get one error message and the QuickFix could do the unwrap at once.


问:
How to write semantics in K framework for a language similar to ada-spark
I am working with K framework and trying to write semantics for a language similar to ada-spark and in that, I want to write semantics that involves allocation of memory and value when I declare an integer variable itself. Also

for the same approach, I tried to make a new cell but since the method to customize configuration is not given, hence I could not get a useful result.

答:
In the K tutorial language SIMPLE, the semantics for allocating and initializing an integer variable looks something like this:

```<code>  rule <k> var X:Id; => . ...</k>
       <env> Env => Env[X <- L] </env>
       <store>... .Map => L |-> undefined ...</store>
       <nextLoc> L => L +Int 1 </nextLoc>
</code>```

You can add new configuration cells to your language by adding them to the configuration declaration in your semantics.

For example, SIMPLE defines the following configuration:

```<code>configuration <T color="red">
                <threads color="orange">
                  <thread multiplicity="*" color="yellow">
                    <k color="green"> $PGM:Stmts ~> execute </k>
                    <control color="cyan">
                      <fstack color="blue"> .List </fstack>
                      <xstack color="purple"> .List </xstack>
                    </control>
                    <env color="violet"> .Map </env>
                    <holds color="black"> .Map </holds>
                    <id color="pink"> 0 </id>
                  </thread>
                </threads>
                <genv color="pink"> .Map </genv>
                <store color="white"> .Map </store>
                <busy color="cyan"> .Set </busy>
                <terminated color="red"> .Set </terminated>
                <input color="magenta" stream="stdin"> .List </input>
                <output color="brown" stream="stdout"> .List </output>
                <nextLoc color="gray"> 0 </nextLoc>
              </T>
</code>```

You may wish to refer to the entire K tutorial, which can be found here.

Body:
In the K tutorial language SIMPLE, the semantics for allocating and initializing an integer variable looks something like this:

  rule <k> var X:Id; => . ...</k>
       <env> Env => Env[X <- L] </env>
       <store>... .Map => L |-> undefined ...</store>
       <nextLoc> L => L +Int 1 </nextLoc>

You can add new configuration cells to your language by adding them to the configuration declaration in your semantics.

For example, SIMPLE defines the following configuration:

configuration <T color="red">
                <threads color="orange">
                  <thread multiplicity="*" color="yellow">
                    <k color="green"> $PGM:Stmts ~> execute </k>
                    <control color="cyan">
                      <fstack color="blue"> .List </fstack>
                      <xstack color="purple"> .List </xstack>
                    </control>
                    <env color="violet"> .Map </env>
                    <holds color="black"> .Map </holds>
                    <id color="pink"> 0 </id>
                  </thread>
                </threads>
                <genv color="pink"> .Map </genv>
                <store color="white"> .Map </store>
                <busy color="cyan"> .Set </busy>
                <terminated color="red"> .Set </terminated>
                <input color="magenta" stream="stdin"> .List </input>
                <output color="brown" stream="stdout"> .List </output>
                <nextLoc color="gray"> 0 </nextLoc>
              </T>

You may wish to refer to the entire K tutorial, which can be found here.


问:
how to set background color of ion content
I want to set background color of whole app or a single background color
but what happened if i use div , different device take different height that's why bottom side not cover up and i am unable to set ion content background.</p>

答: Bro u can use   in this case i have a stylesheet global with primary color variable</p>


问:
Remote XML Web services using C#
I have been tasked with creating a Remote Web service. I am asking this question to get the best approach to what I need to accomplish and see if there is code examples out there that  might help.

Task

Create a web service that accepts parameters when on button click of other programs. One is a windows app done in C# and the app is old fortran as400 app. I need to create this web service to acept these parameters coming from the other systems and then in the web services I need to take these parameters and send them to a Stored procedure and with the results create an XML file and post it back to the clients end.

Is this possible and if it is can someone point me to where I can see some examples or provide some help.

答: The de-facto standard today of creating web services in .NET is WCF.</p>

ContentLicense: CC BY-SA 3.0

Title: Remote XML Web services using C#


问:
Valgrind found 3 memory leaks but I can't figure out where they are
I tried to implement the basic String class by myself and it's working fine, but Valgrind says there are 3 memory leaks and I can't figure out where and why. I really tried to delete everything after it isn't used anymore (I have started using Valgrind today).
Now I'm really concerned about my basic C/C++ memory management knowledge. I made a comment to the places in the code where Valgrind found a leak (//VALGRIND). I've also uploaded a screenshot of this error message
click to see the screenshot.

EDIT: I have updated the screenshot, so you can see the full output.

StringT.h

template<typename char_type = char>
class StringT {
public:

 explicit StringT(const char_type *str) {
        if (str != nullptr) {
            size_t len = strlen(str);
            m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 1 of 3
            strcpy(m_str, str);
        }
    }

   ~StringT() {
        delete [] m_str;
    }

StringT(const StringT & other) {
        size_t len = 0;
        if (other.m_str) len = strlen(other.m_str);
        m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 2 of 3
        strcpy(m_str, other.m_str);
    }

    StringT(StringT && other) noexcept {
        m_str = other.m_str;
        other.m_str = nullptr;
    }

     StringT & operator+=(const StringT &other) {
        if (other.m_str == nullptr) //when other str is empty just return current Str
            return *this;

        const size_t mysize{m_str ? strlen(m_str) : 0}; // check if not null then call strlen
        const size_t osize{other.m_str ? strlen(other.m_str) : 0};

        char *newStr = new char_type[osize + mysize + 1]; //VALGRIND: 11 bytes in 1 blocks are definitely lost in loss record 3 of 3
        newStr[0] = '\0'; //strcat searches for '\0', so newStr has to be a valid String

        if (m_str) strcat(newStr, m_str);
        if (other.m_str) strcat(newStr, other.m_str);

        delete[] m_str; //delete old string
        m_str = newStr; //set member to new concatenated str

        return *this;
    }

    size_t length() const {
        if (!m_str) return 0;
        return strlen(m_str);
    }

    friend
    std::ostream &operator<<(std::ostream &out, StringT<> &other) {
        if (other.m_str) out << other.m_str;
        return out;
    }

private:
    char_type *m_str{nullptr};
};
```

<p>main.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>int main() {

    const char *cArr = "Hello";
    const char *cArr2 = "World";
    StringT<char> hello(cArr);
    StringT<char> world(cArr2);
    StringT<char> emptyStr;

    std::cout << "hello: " << hello << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout << "emptyStr: " << emptyStr << std::endl;

    StringT<char> hCopy(hello);
    StringT<char> wMove(std::move(world));

    std::cout << "hCopy: " << hello << std::endl;
    std::cout << "hCopy: " << hCopy << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout<<  "wMove: " << wMove << std::endl;
    std::cout<<  "lenMove: " << wMove.length() << std::endl;
    std::cout<<  "lenEmptyStr: " << emptyStr.length() << std::endl;

    hello += wMove;
    std::cout<<  "hello += world: " << hello << std::endl;

    return 0;
}

</code>```

答:
As already answered, the delete needs to be in the destructor. However, the proper solution to your problem is to not do memory management manually in this case. You should be using std::unique_ptr for your m_str member:

```<code>std::unique_ptr<char_type[]> m_str;
</code>```

This frees you from having to new and delete manually. This also helps protects against memory leaks in case of exceptions. Even if you delete everything you allocated, you can still have memory leaks if an exception occurs between the new and the delete. unique_ptr helps in preventing this kind of leak.

Your class only needs small changes:

```<code>template<typename char_type = char>
class StringT {
public:
    StringT()
    {}

    explicit StringT(const char_type *str)
    {
        if (str != nullptr) {
            size_t len = strlen(str);
            m_str = std::make_unique<char_type[]>(len + 1);
            strcpy(m_str.get(), str);
        }
    }

    StringT(const StringT & other)
    {
        size_t len = 0;
        if (other.m_str)
            len = strlen(other.m_str.get());
        m_str = std::make_unique<char_type[]>(len + 1);
        strcpy(m_str.get(), other.m_str.get());
    }

    StringT(StringT && other) noexcept
    {
        m_str = std::move(other.m_str);
    }

    StringT & operator+=(const StringT &other)
    {
        if (other.m_str == nullptr)
            return *this;

        const size_t mysize{m_str ? strlen(m_str.get()) : 0};
        const size_t osize{strlen(other.m_str.get())};

        auto newStr = std::make_unique<char_type[]>(osize + mysize + 1);
        newStr[0] = '\0';

        if (m_str)
            strcat(newStr.get(), m_str.get());
        strcat(newStr.get(), other.m_str.get());

        m_str = std::move(newStr);
        return *this;
    }

    size_t length() const
    {
        if (!m_str)
            return 0;
        return strlen(m_str.get());
    }

    friend
    std::ostream &operator<<(std::ostream &out, StringT<> &other)
    {
        if (other.m_str)
            out << other.m_str.get();
        return out;
    }

private:
    std::unique_ptr<char_type[]> m_str;
};
</code>```

You will notice that there are no calls to new or delete in this code. m_str will automatically delete allocated memory on its own when needed.

Body:
I tried to implement the basic String class by myself and it's working fine, but Valgrind says there are 3 memory leaks and I can't figure out where and why. I really tried to delete everything after it isn't used anymore (I have started using Valgrind today).
Now I'm really concerned about my basic C/C++ memory management knowledge. I made a comment to the places in the code where Valgrind found a leak (//VALGRIND). I've also uploaded a screenshot of this error message
click to see the screenshot.

EDIT: I have updated the screenshot, so you can see the full output.

StringT.h

template<typename char_type = char>
class StringT {
public:

 explicit StringT(const char_type *str) {
        if (str != nullptr) {
            size_t len = strlen(str);
            m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 1 of 3
            strcpy(m_str, str);
        }
    }

   ~StringT() {
        delete [] m_str;
    }

StringT(const StringT & other) {
        size_t len = 0;
        if (other.m_str) len = strlen(other.m_str);
        m_str = new char_type[len + 1]; //VALGRIND: 6 bytes in 1 blocks are definitely lost in loss record 2 of 3
        strcpy(m_str, other.m_str);
    }

    StringT(StringT && other) noexcept {
        m_str = other.m_str;
        other.m_str = nullptr;
    }

     StringT & operator+=(const StringT &other) {
        if (other.m_str == nullptr) //when other str is empty just return current Str
            return *this;

        const size_t mysize{m_str ? strlen(m_str) : 0}; // check if not null then call strlen
        const size_t osize{other.m_str ? strlen(other.m_str) : 0};

        char *newStr = new char_type[osize + mysize + 1]; //VALGRIND: 11 bytes in 1 blocks are definitely lost in loss record 3 of 3
        newStr[0] = '\0'; //strcat searches for '\0', so newStr has to be a valid String

        if (m_str) strcat(newStr, m_str);
        if (other.m_str) strcat(newStr, other.m_str);

        delete[] m_str; //delete old string
        m_str = newStr; //set member to new concatenated str

        return *this;
    }

    size_t length() const {
        if (!m_str) return 0;
        return strlen(m_str);
    }

    friend
    std::ostream &operator<<(std::ostream &out, StringT<> &other) {
        if (other.m_str) out << other.m_str;
        return out;
    }

private:
    char_type *m_str{nullptr};
};

main.cpp

int main() {

    const char *cArr = "Hello";
    const char *cArr2 = "World";
    StringT<char> hello(cArr);
    StringT<char> world(cArr2);
    StringT<char> emptyStr;

    std::cout << "hello: " << hello << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout << "emptyStr: " << emptyStr << std::endl;

    StringT<char> hCopy(hello);
    StringT<char> wMove(std::move(world));

    std::cout << "hCopy: " << hello << std::endl;
    std::cout << "hCopy: " << hCopy << std::endl;
    std::cout << "world: " << world << std::endl;
    std::cout<<  "wMove: " << wMove << std::endl;
    std::cout<<  "lenMove: " << wMove.length() << std::endl;
    std::cout<<  "lenEmptyStr: " << emptyStr.length() << std::endl;

    hello += wMove;
    std::cout<<  "hello += world: " << hello << std::endl;

    return 0;
}

Body:
As already answered, the delete needs to be in the destructor. However, the proper solution to your problem is to not do memory management manually in this case. You should be using std::unique_ptr for your m_str member:

std::unique_ptr<char_type[]> m_str;

This frees you from having to new and delete manually. This also helps protects against memory leaks in case of exceptions. Even if you delete everything you allocated, you can still have memory leaks if an exception occurs between the new and the delete. unique_ptr helps in preventing this kind of leak.

Your class only needs small changes:

template<typename char_type = char>
class StringT {
public:
    StringT()
    {}

    explicit StringT(const char_type *str)
    {
        if (str != nullptr) {
            size_t len = strlen(str);
            m_str = std::make_unique<char_type[]>(len + 1);
            strcpy(m_str.get(), str);
        }
    }

    StringT(const StringT & other)
    {
        size_t len = 0;
        if (other.m_str)
            len = strlen(other.m_str.get());
        m_str = std::make_unique<char_type[]>(len + 1);
        strcpy(m_str.get(), other.m_str.get());
    }

    StringT(StringT && other) noexcept
    {
        m_str = std::move(other.m_str);
    }

    StringT & operator+=(const StringT &other)
    {
        if (other.m_str == nullptr)
            return *this;

        const size_t mysize{m_str ? strlen(m_str.get()) : 0};
        const size_t osize{strlen(other.m_str.get())};

        auto newStr = std::make_unique<char_type[]>(osize + mysize + 1);
        newStr[0] = '\0';

        if (m_str)
            strcat(newStr.get(), m_str.get());
        strcat(newStr.get(), other.m_str.get());

        m_str = std::move(newStr);
        return *this;
    }

    size_t length() const
    {
        if (!m_str)
            return 0;
        return strlen(m_str.get());
    }

    friend
    std::ostream &operator<<(std::ostream &out, StringT<> &other)
    {
        if (other.m_str)
            out << other.m_str.get();
        return out;
    }

private:
    std::unique_ptr<char_type[]> m_str;
};

You will notice that there are no calls to new or delete in this code. m_str will automatically delete allocated memory on its own when needed.


问:
Error 500 (Internal Server Error) in API Laravel 5.8 and Angular 7
I am running a project on Angular 7 and Laravel 5.8. When i post login form angular form to API Laravel I get error 500 (Internal Server Error) in console .... why?

I tried running the Application on local system, it works perfectly. But when I took it to online serve, the problem started.
Note: Backend API is working perfectly with POSTMAN.

My CORS.php in Laravel is:

```<code>    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin : *');
        header('Access-Control-Allow-Headers : Content-type, X-Auth-Token, Authorization, Origin');
        return $next($request);
    }

</code>```

kernel

```<code>    protected $middleware = [

        \App\Http\Middleware\CORS::class,
    ];

    protected $routeMiddleware = [

        'CORS' => \App\Http\Middleware\CORS::class,
    ];
</code>```

route

```<code>Route::post('login', 'UserController@login');
</code>```

login.service

```<code>export class SandboxUserService {

  private API_URL= environment.apiUrl;

  login(data) {
    return this.http.post(this.API_URL + '/login', data)
  }
</code>```

login.component.ts

```<code> onSubmit() {
    this.SandboxUser.login(this.form).subscribe(
      data => this.handleResponse(data),
       error => this.handleError(error)
    );
  }
  handleResponse(data) {
     this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})

    this.Token.handle(data.access_token);
    this.Auth.changeAuthStatus(true);
    // this.router.navigateByUrl('/admindashboard');
    if(this.form.id == 1){
      this.router.navigateByUrl('/admindashboard');
   }
   else
   {
      this.router.navigateByUrl('/userdashboard');
   }

</code>```

After login, I expect it to redirect me to the dashboard. But it did not respond. So when I inspect, I found this:

Error 500 (Internal Server Error)

答:
Have do you import Sandbox... class properly. In this case I prefer create a new module.
check this way</p>

Body:
I am running a project on Angular 7 and Laravel 5.8. When i post login form angular form to API Laravel I get error 500 (Internal Server Error) in console .... why?

I tried running the Application on local system, it works perfectly. But when I took it to online serve, the problem started.
Note: Backend API is working perfectly with POSTMAN.

My CORS.php in Laravel is:

    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin : *');
        header('Access-Control-Allow-Headers : Content-type, X-Auth-Token, Authorization, Origin');
        return $next($request);
    }

kernel

    protected $middleware = [

        \App\Http\Middleware\CORS::class,
    ];

    protected $routeMiddleware = [

        'CORS' => \App\Http\Middleware\CORS::class,
    ];

route

Route::post('login', 'UserController@login');

login.service

export class SandboxUserService {

  private API_URL= environment.apiUrl;

  login(data) {
    return this.http.post(this.API_URL + '/login', data)
  }

login.component.ts

 onSubmit() {
    this.SandboxUser.login(this.form).subscribe(
      data => this.handleResponse(data),
       error => this.handleError(error)
    );
  }
  handleResponse(data) {
     this.notify.success('Done, you have successfully logged in.', {timeout:2000, position: "rightTop"})

    this.Token.handle(data.access_token);
    this.Auth.changeAuthStatus(true);
    // this.router.navigateByUrl('/admindashboard');
    if(this.form.id == 1){
      this.router.navigateByUrl('/admindashboard');
   }
   else
   {
      this.router.navigateByUrl('/userdashboard');
   }

After login, I expect it to redirect me to the dashboard. But it did not respond. So when I inspect, I found this:

Error 500 (Internal Server Error)


问:
Regex with multiple email address seperated by a semi colon
I am trying to build a regex what would allow multiple emails separated with a semicolon for only one domain.

This is what I have now:

@"^(?>\b[\w+-.%]+@gmail\.com(?:[,;]\s*)?)+\b$"

This allow 1@gmail.com%2@gmail.com or 1@gmail.com&&2@gmail.com. I just want to have it to be allowed with semicolmn seperator as this. 1@gmail.com;2@gmail.com.

答:
If we are having valid emails, which appears so, and then our cases are limited to those listed in the question, we would be just doing a simple replace on % and &&, with an expression similar to:

```<code>(%|&&)|($)
</code>```

If the end of string may not need a ; then this capturing group might just work, if I understand the problem right:

```<code>(%|&&)
</code>```

If we would want to validate, then our expression would become slightly complicated to design.

Test

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(%|&&)|($)";
        string substitution = @";";
        string input = @"1@gmail.com%2@gmail.com
1@gmail.com&&2@gmail.com";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}
</code>```

DEMO

Body:
If we are having valid emails, which appears so, and then our cases are limited to those listed in the question, we would be just doing a simple replace on % and &&, with an expression similar to:

(%|&&)|($)

If the end of string may not need a ; then this capturing group might just work, if I understand the problem right:

(%|&&)

If we would want to validate, then our expression would become slightly complicated to design.

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(%|&&)|($)";
        string substitution = @";";
        string input = @"1@gmail.com%2@gmail.com
1@gmail.com&&2@gmail.com";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

DEMO


问:
Cannot access javascript variable inside symfony controller
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});
```

<p>And my controller: </p>

<pre class="lang-php prettyprint-override"><code>public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}
</code>```

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

答:
You have to get the content of the Request correctly.

Depending on your version of Symfony, other answers might not work and you might have to use:

$request->getContent();

To have access to the associative array containing your data.

(Edit to add my comment): If it does not work, the only other thing on top of my head would be that your IDE autoimport would have imported the wrong "Request" class in your controller ? Make sure you use --> use Symfony\Component\HttpFoundation\Request;

Body:
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});

And my controller:

public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed


问:
How to query non keyword field in elasticsearch
I want to filter records by non keyword field.

I am using aws elasticsearch service, where there are some fields are keyword and some are normal. I want to apply filtration on non keyword (text) data type field.

```<code>GET ES_INDEX_NAME/_search
{
    "query" : {
        "term" : { "listing_group" : "Other"}
    }
}
</code>```

listing_group field name is of text data type.

Thanks in advance !

答:
You can try with match or match_phrase?

For partial match,

```<code>GET ES_INDEX_NAME/_search
{
    "query": {
        "match" : {
            "listing_group" : "Other"
        }
    }
}
</code>```

For phrase match,

```<code>GET ES_INDEX_NAME/_search
{
    "query" : {
        "match_phrase" : {
            "listing_group" : "Other"
        }
    }
}
</code>```

Body:
I want to filter records by non keyword field.

I am using aws elasticsearch service, where there are some fields are keyword and some are normal. I want to apply filtration on non keyword (text) data type field.

GET ES_INDEX_NAME/_search
{
    "query" : {
        "term" : { "listing_group" : "Other"}
    }
}

listing_group field name is of text data type.

Thanks in advance !

Body:
You can try with match or match_phrase?

For partial match,

GET ES_INDEX_NAME/_search
{
    "query": {
        "match" : {
            "listing_group" : "Other"
        }
    }
}

For phrase match,

GET ES_INDEX_NAME/_search
{
    "query" : {
        "match_phrase" : {
            "listing_group" : "Other"
        }
    }
}


问:
How to align imageViews which are created dynamically inside a class and not the xml file
My Problem: I want to create a for loop in the onCreate() method to save imageViews dynamically. I am being able to do everything properly it's just that the imageView is displayed at the top left most corner, i.e i am not being able to assign it it's alignment.

My Code:

```<code>RelativeLayout layout = findViewById(R.id.relativeLayout);

    for(int i=0;i<3;i++)
    {
        ImageView image = new ImageView(this);
        image.setMaxHeight(200);
        image.setMaxWidth(200);
        //CODE TO ADD THE ALIGNMENT OF THE IMAGE
        image.setImageResource(R.drawable.red);
        layout.addView(image);
    }
</code>```

答:
Try this one:</p>

```<code>for(int i=0;i<3;i++)
    {
        ImageView image = new ImageView(this);
        image.setMaxHeight(200);
        image.setMaxWidth(200);
        //CODE TO ADD THE ALIGNMENT OF THE IMAGE
        image.setImageResource(R.drawable.red);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.MarginLayoutParams.MATCH_PARENT, 200);
        layoutParams.setMargins(40, 40, 40, 40);
        image.setLayoutParams(layoutParams);
        layout.addView(image);
    }
</code>```

Body:
My Problem: I want to create a for loop in the onCreate() method to save imageViews dynamically. I am being able to do everything properly it's just that the imageView is displayed at the top left most corner, i.e i am not being able to assign it it's alignment.

My Code:

RelativeLayout layout = findViewById(R.id.relativeLayout);

    for(int i=0;i<3;i++)
    {
        ImageView image = new ImageView(this);
        image.setMaxHeight(200);
        image.setMaxWidth(200);
        //CODE TO ADD THE ALIGNMENT OF THE IMAGE
        image.setImageResource(R.drawable.red);
        layout.addView(image);
    }

Body:
Try this one:

for(int i=0;i<3;i++)
    {
        ImageView image = new ImageView(this);
        image.setMaxHeight(200);
        image.setMaxWidth(200);
        //CODE TO ADD THE ALIGNMENT OF THE IMAGE
        image.setImageResource(R.drawable.red);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.MarginLayoutParams.MATCH_PARENT, 200);
        layoutParams.setMargins(40, 40, 40, 40);
        image.setLayoutParams(layoutParams);
        layout.addView(image);
    }


问:
Predicting the primary keys exhaustion in MySQL based on rate of insertion
We are running out of primary keys for our table in prod. We do not want that to occur again. So we need a mechanism to alert us when we are running out of primary keys based on the rate of insertion so that we can mitigate that.

I have written a Jenkins job that runs and executes a query on Information schema and extracts the index length, table rows and auto_increment from the MySQL database. But we need to keep track of the previous reading since we want to take diff of it with the current in order to predict when the keys are going to be exhausted.

```<code>        SELECT
        INDEX_LENGTH, TABLE_NAME, AUTO_INCREMENT, TABLE_ROWS
        FROM
        information_schema.TABLES
        ORDER BY
        index_length DESC;
</code>```

I cannot find anything related to the rate of change in Mysql tables that should predict the rate at which the primary keys are being used up. I am also open to use any good alternate approach if anyone thinks of one but keep in mind I have to get a query run by a cron job or Jenkins job that should tell that which tables will be exhausted at the end of this year.

答:
You could simply create a table to store metrics, the values you are currently retrieving along with a timestamp

```<code>    INSERT INTO table_metrics(index_length, table_name, auto_increment, row_count, when)
    SELECT INDEX_LENGTH, TABLE_NAME, AUTO_INCREMENT, TABLE_ROWS, now()
    FROM information_schema.TABLES
    ;
</code>```

and then run a query on that data

```<code>SELECT table_name
    , il_change / daysPassed AS ilGrowthRate
    , ([literal ceiling value] - il_current) / (il_change / daysPassed) AS daysRemaining
    , ...
FROM (
SELECT table_name
    , MAX(index_length) AS il_current
    , MAX(index_length) - MIN(index_length) AS il_change
    , ....
    , DATEDIFF(MAX(when), MIN(when)) AS daysPassed
GROUP BY table_name
) AS subQ
</code>```

This assumes you remove the data for a table when you truncate it so that the metrics start over when the table does; you can of course add conditions to only look at metrics from the last day, week, month, etc... (in which case pruning the metrics table after clears becomes less important).

Body:
We are running out of primary keys for our table in prod. We do not want that to occur again. So we need a mechanism to alert us when we are running out of primary keys based on the rate of insertion so that we can mitigate that.

I have written a Jenkins job that runs and executes a query on Information schema and extracts the index length, table rows and auto_increment from the MySQL database. But we need to keep track of the previous reading since we want to take diff of it with the current in order to predict when the keys are going to be exhausted.

        SELECT
        INDEX_LENGTH, TABLE_NAME, AUTO_INCREMENT, TABLE_ROWS
        FROM
        information_schema.TABLES
        ORDER BY
        index_length DESC;

I cannot find anything related to the rate of change in Mysql tables that should predict the rate at which the primary keys are being used up. I am also open to use any good alternate approach if anyone thinks of one but keep in mind I have to get a query run by a cron job or Jenkins job that should tell that which tables will be exhausted at the end of this year.

Body:
You could simply create a table to store metrics, the values you are currently retrieving along with a timestamp

    INSERT INTO table_metrics(index_length, table_name, auto_increment, row_count, when)
    SELECT INDEX_LENGTH, TABLE_NAME, AUTO_INCREMENT, TABLE_ROWS, now()
    FROM information_schema.TABLES
    ;

and then run a query on that data

SELECT table_name
    , il_change / daysPassed AS ilGrowthRate
    , ([literal ceiling value] - il_current) / (il_change / daysPassed) AS daysRemaining
    , ...
FROM (
SELECT table_name
    , MAX(index_length) AS il_current
    , MAX(index_length) - MIN(index_length) AS il_change
    , ....
    , DATEDIFF(MAX(when), MIN(when)) AS daysPassed
GROUP BY table_name
) AS subQ

This assumes you remove the data for a table when you truncate it so that the metrics start over when the table does; you can of course add conditions to only look at metrics from the last day, week, month, etc... (in which case pruning the metrics table after clears becomes less important).


问:
Resource is not supported in this region cloudformation EFSFileSystem
I've encountered following error message in AWS CloudFormation about EFSFileSystem.

```<code>  EFSMountTargetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref 'VPC'
      GroupDescription: Security group for mount target
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '2049'
        ToPort: '2049'
        CidrIp: 0.0.0.0/0
  EFSFileSystem:
    Type: AWS::EFS::FileSystem
    Properties:
      PerformanceMode: generalPurpose
  EFSMountTargetA:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !Ref 'EFSFileSystem'
      SubnetId: !Ref 'VPCSubnetDataA'
      SecurityGroups: [!Ref 'EFSMountTargetSecurityGroup']
  EFSMountTargetB:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !Ref 'EFSFileSystem'
      SubnetId: !Ref 'VPCSubnetDataB'
      SecurityGroups: [!Ref 'EFSMountTargetSecurityGroup']
</code>```

Please let me know how to use EFSFileSystem or replace in that region?

答:
AWS Elastic File System is not currently available in Mumbai, Hong Kong, Beijing, Ningxia, Osaka, Paris or Stockholm.  I can't tell from your CloudFormation snippet if you're trying to deploy in one of those regions.

References

AWS Regional Product Services

Body:
I've encountered following error message in AWS CloudFormation about EFSFileSystem.

  EFSMountTargetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref 'VPC'
      GroupDescription: Security group for mount target
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '2049'
        ToPort: '2049'
        CidrIp: 0.0.0.0/0
  EFSFileSystem:
    Type: AWS::EFS::FileSystem
    Properties:
      PerformanceMode: generalPurpose
  EFSMountTargetA:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !Ref 'EFSFileSystem'
      SubnetId: !Ref 'VPCSubnetDataA'
      SecurityGroups: [!Ref 'EFSMountTargetSecurityGroup']
  EFSMountTargetB:
    Type: AWS::EFS::MountTarget
    Properties:
      FileSystemId: !Ref 'EFSFileSystem'
      SubnetId: !Ref 'VPCSubnetDataB'
      SecurityGroups: [!Ref 'EFSMountTargetSecurityGroup']

Please let me know how to use EFSFileSystem or replace in that region?