问:
Excel Generated by EPPlus is Corrupted
I'm using the following code to add a background image to Excel using EPplus.The document opens fine in polaris office but when using Excel it gives the following error

We found a problem with some content in 'filename.xlsx'. Do you want to try to recover as much as we can

Code

```<code> foreach (var file in Filelist)
                {

                    // Load workbook
                    //var fileInfo = new FileInfo(@file);
                    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    //ExcelPackage pkg = new ExcelPackage(fs);

                    using (var package = new ExcelPackage(fs))
                    {

                        // Itterate through workbook sheets
                        foreach (var sheet in package.Workbook.Worksheets)
                        {

                            sheet.BackgroundImage.Image = bmp;
                            sheet.Protection.IsProtected = false;

                        }

                        package.SaveAs(new FileInfo(Path.GetFileNameWithoutExtension(file)+".xlsx"));
                    }
                    fs.Close();
                }
</code>```

I checked related SO questions , some mentioned that the issue might be due to saving multiple times.I made sure that the Loop is hit only once for a single file.

Update:
Code for Bitmap Generation

```<code> using (Graphics g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                SizeF textSize = g.MeasureString("Sample", new Font(DefaultFont.FontFamily, 80));
                g.DrawString("Sample", new Font("Tahoma", 80), Brushes.Red, -(textSize.Width / 2), -(textSize.Height / 2));
            }
</code>```

答:
Works fine in my example:

```<code>class EPPTest
{
public void CreateExcel(string filename)
{
    var fi = new FileInfo(filename);

    using (var excel = new ExcelPackage(fi) )
    using (var img = CreateImage() )
    {
        if( excel.Workbook.Worksheets.Count == 0 )
        {
            excel.Workbook.Worksheets.Add("MySheet");
        }

        foreach (var sheet in excel.Workbook.Worksheets)
        {

            sheet.BackgroundImage.Image = img;
            sheet.Protection.IsProtected = false;

        }

        excel.Save();// As(new FileInfo(Path.GetFileNameWithoutExtension(file) + ".xlsx"));
    }
}

public Image CreateImage()
{
    Bitmap img = new Bitmap(400, 400);

    using (Graphics g = Graphics.FromImage(img))
    using ( Font f = new Font("Tahoma", 80))
    {
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        SizeF textSize = g.MeasureString("Sample", f);
        g.DrawString("Sample", f, Brushes.Red, 0, (textSize.Height ));
    }

    return img;
}
</code>```

}

Here is the output:

Title: Excel Generated by EPPlus is Corrupted

Body:
I'm using the following code to add a background image to Excel using EPplus.The document opens fine in polaris office but when using Excel it gives the following error

We found a problem with some content in 'filename.xlsx'. Do you want to try to recover as much as we can

Code

 foreach (var file in Filelist)
                {

                    // Load workbook
                    //var fileInfo = new FileInfo(@file);
                    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    //ExcelPackage pkg = new ExcelPackage(fs);

                    using (var package = new ExcelPackage(fs))
                    {

                        // Itterate through workbook sheets
                        foreach (var sheet in package.Workbook.Worksheets)
                        {

                            sheet.BackgroundImage.Image = bmp;
                            sheet.Protection.IsProtected = false;

                        }

                        package.SaveAs(new FileInfo(Path.GetFileNameWithoutExtension(file)+".xlsx"));
                    }
                    fs.Close();
                }

I checked related SO questions , some mentioned that the issue might be due to saving multiple times.I made sure that the Loop is hit only once for a single file.

Update:
Code for Bitmap Generation

 using (Graphics g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                SizeF textSize = g.MeasureString("Sample", new Font(DefaultFont.FontFamily, 80));
                g.DrawString("Sample", new Font("Tahoma", 80), Brushes.Red, -(textSize.Width / 2), -(textSize.Height / 2));
            }

Body:
Works fine in my example:

class EPPTest
{
public void CreateExcel(string filename)
{
    var fi = new FileInfo(filename);

    using (var excel = new ExcelPackage(fi) )
    using (var img = CreateImage() )
    {
        if( excel.Workbook.Worksheets.Count == 0 )
        {
            excel.Workbook.Worksheets.Add("MySheet");
        }

        foreach (var sheet in excel.Workbook.Worksheets)
        {

            sheet.BackgroundImage.Image = img;
            sheet.Protection.IsProtected = false;

        }

        excel.Save();// As(new FileInfo(Path.GetFileNameWithoutExtension(file) + ".xlsx"));
    }
}

public Image CreateImage()
{
    Bitmap img = new Bitmap(400, 400);

    using (Graphics g = Graphics.FromImage(img))
    using ( Font f = new Font("Tahoma", 80))
    {
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        SizeF textSize = g.MeasureString("Sample", f);
        g.DrawString("Sample", f, Brushes.Red, 0, (textSize.Height ));
    }

    return img;
}

}

Here is the output:


来源: stackexchange

问:
Compare and Count Variable Dates?
Using the given statement below I am Receiving the Value of Course end date which is in varchar and coming from MySQL I tried to convert this to date format in $ced & $newformat...all goes fine but when I am trying to compare course end date with the current date it's not comparing... it's only comparing the date and not comparing with year and month

```<code> $enddate = $get_students_row['course_end_date'];
 $ced = strtotime("$enddate");
 $newformat = date('d/m/Y',$ced);
 $currentdate = date('d/m/Y');
</code>```

The function is if $newformat is less than and eqals to current date then field become red

```<code><tr <?php if(($newformat <= $currentdate)): ?> style="color:red;" <?php endif; ?>>
</code>```

But its not working as excepted its make row red but its only comapring with current date not with month and year....Also i was looking for to get Total count of $newformat.

My Code

```<code>                <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>

                   <td><?php  echo $students_rollno_class;?></td>
                   <td><?php  echo $students_admission_no;?> </td>
                   <td><?php  echo $students_firstname;?></td>
                   <td><?php  echo $students_contact;?></td>
                   <td><?php  echo $students_reference_no;?></td>
                   <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
                   <td><?php  echo $newformat;?></td>

               </tr><?php
                    }
                   ?>
</code>```

答:
$newformat and $currentdate are just simple strings for PHP. And comparing two strings would not give the answer you expect. So it's better to use UNIX time format.

try this:

```<code><tr <?php if(($ced <= time())){
   $totalCount++;
   echo 'style="color:red;" ';
<?php } ?>>
</code>```

My
 Code

```<code> <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
     <td><?php  echo $students_rollno_class;?></td>
     <td><?php  echo $students_admission_no;?> </td>
     <td><?php  echo $students_firstname;?></td>
     <td><?php  echo $students_contact;?></td>
     <td><?php  echo $students_reference_no;?></td>
     <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
     <td><?php  echo $newformat;?></td>
 </tr><?php } ?>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Compare and Count Variable Dates?

Body:
Using the given statement below I am Receiving the Value of Course end date which is in varchar and coming from MySQL I tried to convert this to date format in $ced & $newformat...all goes fine but when I am trying to compare course end date with the current date it's not comparing... it's only comparing the date and not comparing with year and month

 $enddate = $get_students_row['course_end_date'];
 $ced = strtotime("$enddate");
 $newformat = date('d/m/Y',$ced);
 $currentdate = date('d/m/Y');

The function is if $newformat is less than and eqals to current date then field become red

<tr <?php if(($newformat <= $currentdate)): ?> style="color:red;" <?php endif; ?>>

But its not working as excepted its make row red but its only comapring with current date not with month and year....Also i was looking for to get Total count of $newformat.

My Code

                <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>

                   <?php  echo $students_rollno_class;?>
                   <?php  echo $students_admission_no;?>
                   <?php  echo $students_firstname;?>
                   <?php  echo $students_contact;?>
                   <?php  echo $students_reference_no;?>
                   <?php  echo date('d/m/Y', strtotime($students_date));?>
                   <?php  echo $newformat;?>

<?php
                    }
                   ?>

Body:
$newformat and $currentdate are just simple strings for PHP. And comparing two strings would not give the answer you expect. So it's better to use UNIX time format.

try this:

<tr <?php if(($ced <= time())){
   $totalCount++;
   echo 'style="color:red;" ';
<?php } ?>>

My <tr> Code

 <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>
     <td><?php  echo $students_rollno_class;?></td>
     <td><?php  echo $students_admission_no;?> </td>
     <td><?php  echo $students_firstname;?></td>
     <td><?php  echo $students_contact;?></td>
     <td><?php  echo $students_reference_no;?></td>
     <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
     <td><?php  echo $newformat;?></td>
 </tr><?php } ?>


问:
Run-time error '1004' when adding validation to DataBodyRange
I copy a cell validation from one workbook to another. An error occurs and I think it's due to the formula of the validation (because other validations are copied without problem), though I don't know why.

The validation formula is:

```<code>=OR(INDIRECT("tblRoutingLine[@OperationNoteMaster]")="";COUNTIF(INDIRECT("tblOperationNoteMaster[OperationNoteMasterID]");INDIRECT("tblRoutingLine[@OperationNoteMaster]"))=1)
</code>```

My code (snippet) is:

```<code>Set valMasterColumnValidation = wbkMDRoutingRCGFileMaster.Worksheets(strTableWorksheet).ListObjects(1).ListColumns(colNewColumn.Name).DataBodyRange(1, 1).Validation
If intColumnValidationType <> 999 Then
    For j = 1 To colNewColumn.DataBodyRange.Cells.Count
        With colNewColumn.DataBodyRange(j, 1).Validation
            .Add Type:=valMasterColumnValidation.Type, _
                AlertStyle:=valMasterColumnValidation.AlertStyle, _
                Operator:=valMasterColumnValidation.Operator, _
                Formula1:=Replace(valMasterColumnValidation.Formula1, ";", ","), _
                Formula2:=Replace(valMasterColumnValidation.Formula2, ";", ",")
            .IgnoreBlank = valMasterColumnValidation.IgnoreBlank
            .InCellDropdown = valMasterColumnValidation.InCellDropdown
            .ErrorTitle = valMasterColumnValidation.ErrorTitle
            .ErrorMessage = valMasterColumnValidation.ErrorMessage
            .ShowError = valMasterColumnValidation.ShowError
        End With
    Next j
End If
</code>```

答:
Solution (part of the code above):</p>

```<code>Formula1:=valMasterColumnValidation.Formula1, _
Formula2:=valMasterColumnValidation.Formula2,
</code>```

Body:
I copy a cell validation from one workbook to another. An error occurs and I think it's due to the formula of the validation (because other validations are copied without problem), though I don't know why.

The validation formula is:

=OR(INDIRECT("tblRoutingLine[@OperationNoteMaster]")="";COUNTIF(INDIRECT("tblOperationNoteMaster[OperationNoteMasterID]");INDIRECT("tblRoutingLine[@OperationNoteMaster]"))=1)

My code (snippet) is:

Set valMasterColumnValidation = wbkMDRoutingRCGFileMaster.Worksheets(strTableWorksheet).ListObjects(1).ListColumns(colNewColumn.Name).DataBodyRange(1, 1).Validation
If intColumnValidationType <> 999 Then
    For j = 1 To colNewColumn.DataBodyRange.Cells.Count
        With colNewColumn.DataBodyRange(j, 1).Validation
            .Add Type:=valMasterColumnValidation.Type, _
                AlertStyle:=valMasterColumnValidation.AlertStyle, _
                Operator:=valMasterColumnValidation.Operator, _
                Formula1:=Replace(valMasterColumnValidation.Formula1, ";", ","), _
                Formula2:=Replace(valMasterColumnValidation.Formula2, ";", ",")
            .IgnoreBlank = valMasterColumnValidation.IgnoreBlank
            .InCellDropdown = valMasterColumnValidation.InCellDropdown
            .ErrorTitle = valMasterColumnValidation.ErrorTitle
            .ErrorMessage = valMasterColumnValidation.ErrorMessage
            .ShowError = valMasterColumnValidation.ShowError
        End With
    Next j
End If

Body:
Solution (part of the code above):

Formula1:=valMasterColumnValidation.Formula1, _
Formula2:=valMasterColumnValidation.Formula2,


问:
How to get ion-slide index on click?
I want to get slide index on click, I have ion-slides and its options are per page 2.5 slide. When I try to get active index it getting zero(0).

here my code

```<code>@ViewChild(IonSlides, { static: false }) slides: IonSlides;
slideOpts = {
  slidesPerView: 2.5,
  zoom: false,
  slideShadows: true
};

getIndex() {
    this.slides.getActiveIndex().then((index) => {
      this.currentIndex = index;
      console.log(this.currentIndex);
    })
}
</code>```

here my HTML

```<code><ion-slides [options]="slideOpts" #slides>
  <ion-slide *ngFor="let item of items">
    <p>{{item.name}}</p>
  </ion-slide>
</ion-slides>
</code>```

答:
Use let i=index to get index id. You can get an index like this:

```<code>slideOpts = {
    slidesPerView: 2.5,
    zoom: false,
    slideShadows: true
  };

  items = [
    {
      name: 'test1'
    },
    {
      name: 'test1'
    },
    {
      name: 'test1'
    },
    {
      name: 'test1'
    }
  ]

getSlideIndex(i: number) {
    console.log(i);
}
</code>```

in Html

```<code><ion-slides [options]="slideOpts">
    <ion-slide *ngFor="let item of items; let i=index">
      <ion-row>
        <ion-button (click)="getSlideIndex(i)">
          {{item.name}}
        </ion-button>
      </ion-row>
    </ion-slide>
</ion-slides>
</code>```

hope it helps you :)

Title: How to get ion-slide index on click?

Body:
I want to get slide index on click, I have ion-slides and its options are per page 2.5 slide. When I try to get active index it getting zero(0).

here my code

@ViewChild(IonSlides, { static: false }) slides: IonSlides;
slideOpts = {
  slidesPerView: 2.5,
  zoom: false,
  slideShadows: true
};

getIndex() {
    this.slides.getActiveIndex().then((index) => {
      this.currentIndex = index;
      console.log(this.currentIndex);
    })
}

here my HTML

<ion-slides [options]="slideOpts" #slides>
  <ion-slide *ngFor="let item of items">

{{item.name}}

  </ion-slide>
</ion-slides>

Body:
Use let i=index to get index id. You can get an index like this:

slideOpts = {
    slidesPerView: 2.5,
    zoom: false,
    slideShadows: true
  };

  items = [
    {
      name: 'test1'
    },
    {
      name: 'test1'
    },
    {
      name: 'test1'
    },
    {
      name: 'test1'
    }
  ]

getSlideIndex(i: number) {
    console.log(i);
}

in Html

<ion-slides [options]="slideOpts">
    <ion-slide *ngFor="let item of items; let i=index">
      <ion-row>
        <ion-button (click)="getSlideIndex(i)">
          {{item.name}}
        </ion-button>
      </ion-row>
    </ion-slide>
</ion-slides>

hope it helps you :)


问:
Javascript - Taking a global variable, modifying it in a function - THEN taking that modified result to use in another function
I'm creating the javascript for a rock-paper-scissors game. (Full link to the code below with comments to explain.)
https://jsfiddle.net/rueeazy/8b5nw2ce/15/

I'm building a RPS game that runs 5 different times and displays the winner of me v the computer after 5 rounds. Right now the game is being played in google chrome dev tools with the results being logged through the console.

```<code>let myScore = 0
let pcScore = 0

function playRound(playerSelection, computerSelection) {
          if (computerSelection == 'Paper' && playerSelection =='paper') {
              return 'It\'s a tie!';
          } else if (computerSelection == 'Paper' && playerSelection == 'rock') {
              return 'You lose! Paper beats rock!';
         pcScore ++;
          } else if (computerSelection == 'Paper' && playerSelection == 'scissors') {
              return 'You win! Scissors beats paper!';
          myScore ++;
          } else if (computerSelection == 'Rock' && playerSelection == 'paper') {
              return 'You win! Paper beats rock!';
              myScore ++;
          } else if (computerSelection == 'Rock' && playerSelection == 'rock') {
              return 'It\'s a tie!';
          } else if (computerSelection == 'Rock' && playerSelection == 'scissors') {
              return 'You lose! Rock beats scissors!';
              pcScore ++;
          } else if (computerSelection == 'Scissors' && playerSelection == 'paper') {
              return 'You lose! Scissors beats paper!'
              pcScore ++;
          } else if (computerSelection == 'Scissors' && playerSelection == 'rock') {
              return 'You win! Rock beats scissors!'
              myScore ++;
          } else (computerSelection == 'Scissors' && playerSelection == 'scissors')
              return 'It\'s a tie!'
          }

function winner() {
        if (myScore > pcScore) {
            return 'You Won!';
        } else if (myScore = pcScore) {
            return 'You tied!';
        } else pcScore > myScore
            return 'The computer won!'
        }
</code>```

I am supposed to track the score via the [console.log] after each round and display the winner. And I loop this process in function game() 5 times and keep a tally of who won more rounds - and display the winner at the end. But when I call function game() in the console - it ALWAYS displays "the computer won" so I don't believe winner() is receiving the updated result of myScore/pcScore from playRound().

```<code>function game() {
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        return winner()
      }
</code>```

The part I'm having trouble with is getting the new results of pc/my score from the function playRound() to winner() so that I can display the true winner in game().

I've tried making myScore and pcScore global variables that apply to every function in hopes that they would first be effected in playRound() and then from playRound() to winner() but that didn't seem to work. So I put myScore and pcScore inside the playRound() function - but don't know the correct way to define myScore and pcScore inside winner() and game().

I hope this makes sense - I appreciate the help!

答:
you try to increase score after returning from the function ;

```<code>...
else if (computerSelection == 'Paper' && playerSelection == 'rock') {
              return 'You lose! Paper beats rock!';
         pcScore ++;
          }
...
</code>```

this should be

```<code>...
else if (computerSelection == 'Paper' && playerSelection == 'rock') {
         pcScore ++;
              return 'You lose! Paper beats rock!';
          }
...
</code>```

Body:
I'm creating the javascript for a rock-paper-scissors game. (Full link to the code below with comments to explain.)
https://jsfiddle.net/rueeazy/8b5nw2ce/15/

I'm building a RPS game that runs 5 different times and displays the winner of me v the computer after 5 rounds. Right now the game is being played in google chrome dev tools with the results being logged through the console.

let myScore = 0
let pcScore = 0

function playRound(playerSelection, computerSelection) {
          if (computerSelection == 'Paper' && playerSelection =='paper') {
              return 'It\'s a tie!';
          } else if (computerSelection == 'Paper' && playerSelection == 'rock') {
              return 'You lose! Paper beats rock!';
         pcScore ++;
          } else if (computerSelection == 'Paper' && playerSelection == 'scissors') {
              return 'You win! Scissors beats paper!';
          myScore ++;
          } else if (computerSelection == 'Rock' && playerSelection == 'paper') {
              return 'You win! Paper beats rock!';
              myScore ++;
          } else if (computerSelection == 'Rock' && playerSelection == 'rock') {
              return 'It\'s a tie!';
          } else if (computerSelection == 'Rock' && playerSelection == 'scissors') {
              return 'You lose! Rock beats scissors!';
              pcScore ++;
          } else if (computerSelection == 'Scissors' && playerSelection == 'paper') {
              return 'You lose! Scissors beats paper!'
              pcScore ++;
          } else if (computerSelection == 'Scissors' && playerSelection == 'rock') {
              return 'You win! Rock beats scissors!'
              myScore ++;
          } else (computerSelection == 'Scissors' && playerSelection == 'scissors')
              return 'It\'s a tie!'
          }

function winner() {
        if (myScore > pcScore) {
            return 'You Won!';
        } else if (myScore = pcScore) {
            return 'You tied!';
        } else pcScore > myScore
            return 'The computer won!'
        }

I am supposed to track the score via the [console.log] after each round and display the winner. And I loop this process in function game() 5 times and keep a tally of who won more rounds - and display the winner at the end. But when I call function game() in the console - it ALWAYS displays "the computer won" so I don't believe winner() is receiving the updated result of myScore/pcScore from playRound().

function game() {
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        console.log(playRound(playerSelection, computerPlay()));
        return winner()
      }

The part I'm having trouble with is getting the new results of pc/my score from the function playRound() to winner() so that I can display the true winner in game().

I've tried making myScore and pcScore global variables that apply to every function in hopes that they would first be effected in playRound() and then from playRound() to winner() but that didn't seem to work. So I put myScore and pcScore inside the playRound() function - but don't know the correct way to define myScore and pcScore inside winner() and game().

I hope this makes sense - I appreciate the help!

Body:
you try to increase score after returning from the function ;

...
else if (computerSelection == 'Paper' && playerSelection == 'rock') {
              return 'You lose! Paper beats rock!';
         pcScore ++;
          }
...

this should be

...
else if (computerSelection == 'Paper' && playerSelection == 'rock') {
         pcScore ++;
              return 'You lose! Paper beats rock!';
          }
...


问:
Assertj-swagger throws org.assertj.core.error.AssertJMultipleFailuresError Multiple Failures when executing test
I have a spring boot api application and I used springfox to generate swaggerv2 api documentation and I created a test to see if my api definitions are correct.

Heres how my configuration looks like:

```<code>@Configuration
@EnableSwagger2
public class SpringFoxConfig {

    @Value("${my.app.version}")
    private String appVersion;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("My App").select()
                .apis(RequestHandlerSelectors.basePackage("my.com.app.controller"))
                .paths(regex("/api/MyAppName.*")).build()
                .globalOperationParameters(
                        Arrays.asList(new ParameterBuilder().name("UserKey").description("Unique user key.")
                                .modelRef(new ModelRef("string")).parameterType("header").required(true).build()))
                .apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("My App API Documentaion")
                .description("This documentation is for the MyApp.").version(appVersion)
                .license("MyApp.cc").licenseUrl("https://myapp.com/").build();
    }

    private ApiKey apiKey() {
        return new ApiKey("apiKey", "APIKEY", "header");
    }
}
</code>```

Here's how my test looks:

```<code>    @Test
    public void shouldFindNoDifferences() {
        File implFirstSwaggerLocation = new File(
            MyTest.class.getResource("/swagger.json").getFile());
        File designFirstSwaggerLocation = new File(
            MyTest.class.getResource("/swagger.yaml").getFile());
        SwaggerAssertions.assertThat(implFirstSwaggerLocation.getAbsolutePath())
            .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
    }
</code>```

It's exactly what they have from their examples. When I run my test It throws this exception below:

```<code>Stack trace:
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (1 failure)
-- failure 1 --
[Checking Paths]
Expecting:
  <["/api/myAppName",
    "/api/myAppName/eventTypes",
    "/api/myAppName/initialize",
    "/api/myAppName/latest/{type}/{user}",
    "/api/myAppName/stats/due/{ids}/custom/{days}",
    "/api/myAppName/stats/due/{ids}/{period}",
    "/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/api/myAppName/stats/orgs/{id}/{period}",
    "/api/myAppName/stats/{ids}/{period}",
    "/api/myAppName/stats/{ids}/{period}/{days}",
    "/api/myAppName/summarize",
    "/api/myAppName/{id}",
    "/api/myAppName/{source}/events",
    "/api/myAppName/{source}/events/batch"]>
to contain only:
  <["/v2/api/myAppName/stats/orgs/{id}/{period}",
    "/v2/api/myAppName/{source}/events/batch",
    "/v2/api/myAppName/initialize",
    "/v2/api/myAppName/eventTypes",
    "/v2/api/myAppName/stats/due/{ids}/{period}",
    "/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/v2/api/myAppName/{source}/events",
    "/v2/api/myAppName/{id}",
    "/v2/api/myAppName/latest/{type}/{user}",
    "/v2/api/myAppName/stats/due/{ids}/custom/{days}",
    "/v2/api/myAppName/stats/{ids}/{period}",
    "/v2/api/myAppName",
    "/v2/api/myAppName/summarize",
    "/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
elements not found:
  <["/v2/api/myAppName/stats/orgs/{id}/{period}",
    "/v2/api/myAppName/{source}/events/batch",
    "/v2/api/myAppName/initialize",
    "/v2/api/myAppName/eventTypes",
    "/v2/api/myAppName/stats/due/{ids}/{period}",
    "/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/v2/api/myAppName/{source}/events",
    "/v2/api/myAppName/{id}",
    "/v2/api/myAppName/latest/{type}/{user}",
    "/v2/api/myAppName/stats/due/{ids}/custom/{days}",
    "/v2/api/myAppName/stats/{ids}/{period}",
    "/v2/api/myAppName",
    "/v2/api/myAppName/summarize",
    "/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
and elements not expected:
  <["/api/myAppName",
    "/api/myAppName/eventTypes",
    "/api/myAppName/initialize",
    "/api/myAppName/latest/{type}/{user}",
    "/api/myAppName/stats/due/{ids}/custom/{days}",
    "/api/myAppName/stats/due/{ids}/{period}",
    "/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/api/myAppName/stats/orgs/{id}/{period}",
    "/api/myAppName/stats/{ids}/{period}",
    "/api/myAppName/stats/{ids}/{period}/{days}",
    "/api/myAppName/summarize",
    "/api/myAppName/{id}",
    "/api/myAppName/{source}/events",
    "/api/myAppName/{source}/events/batch"]>
at DocumentationDrivenValidator.validatePaths(DocumentationDrivenValidator.java:108)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at io.github.robwin.swagger.test.DocumentationDrivenValidator.validateSwagger(DocumentationDrivenValidator.java:88)
    at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:75)
    at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:87)
    at my.com.app.definitions.MyTest.shouldFindNoDifferences(MyTest.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
</code>```

I think I'm missing something.

答:
It was my carelessness that resulted to this problem but thanks to Roddy's comment I was able to notice my mistake.

In my assertj-swagger.properties file there contains assertj.swagger.pathsPrependExpected=/v2 property that causes this issue.

Body:
I have a spring boot api application and I used springfox to generate swaggerv2 api documentation and I created a test to see if my api definitions are correct.

Heres how my configuration looks like:

@Configuration
@EnableSwagger2
public class SpringFoxConfig {

    @Value("${my.app.version}")
    private String appVersion;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("My App").select()
                .apis(RequestHandlerSelectors.basePackage("my.com.app.controller"))
                .paths(regex("/api/MyAppName.*")).build()
                .globalOperationParameters(
                        Arrays.asList(new ParameterBuilder().name("UserKey").description("Unique user key.")
                                .modelRef(new ModelRef("string")).parameterType("header").required(true).build()))
                .apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("My App API Documentaion")
                .description("This documentation is for the MyApp.").version(appVersion)
                .license("MyApp.cc").licenseUrl("https://myapp.com/").build();
    }

    private ApiKey apiKey() {
        return new ApiKey("apiKey", "APIKEY", "header");
    }
}

Here's how my test looks:

    @Test
    public void shouldFindNoDifferences() {
        File implFirstSwaggerLocation = new File(
            MyTest.class.getResource("/swagger.json").getFile());
        File designFirstSwaggerLocation = new File(
            MyTest.class.getResource("/swagger.yaml").getFile());
        SwaggerAssertions.assertThat(implFirstSwaggerLocation.getAbsolutePath())
            .isEqualTo(designFirstSwaggerLocation.getAbsolutePath());
    }

It's exactly what they have from their examples. When I run my test It throws this exception below:

Stack trace:
org.assertj.core.error.AssertJMultipleFailuresError:
Multiple Failures (1 failure)
-- failure 1 --
[Checking Paths]
Expecting:
  <["/api/myAppName",
    "/api/myAppName/eventTypes",
    "/api/myAppName/initialize",
    "/api/myAppName/latest/{type}/{user}",
    "/api/myAppName/stats/due/{ids}/custom/{days}",
    "/api/myAppName/stats/due/{ids}/{period}",
    "/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/api/myAppName/stats/orgs/{id}/{period}",
    "/api/myAppName/stats/{ids}/{period}",
    "/api/myAppName/stats/{ids}/{period}/{days}",
    "/api/myAppName/summarize",
    "/api/myAppName/{id}",
    "/api/myAppName/{source}/events",
    "/api/myAppName/{source}/events/batch"]>
to contain only:
  <["/v2/api/myAppName/stats/orgs/{id}/{period}",
    "/v2/api/myAppName/{source}/events/batch",
    "/v2/api/myAppName/initialize",
    "/v2/api/myAppName/eventTypes",
    "/v2/api/myAppName/stats/due/{ids}/{period}",
    "/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/v2/api/myAppName/{source}/events",
    "/v2/api/myAppName/{id}",
    "/v2/api/myAppName/latest/{type}/{user}",
    "/v2/api/myAppName/stats/due/{ids}/custom/{days}",
    "/v2/api/myAppName/stats/{ids}/{period}",
    "/v2/api/myAppName",
    "/v2/api/myAppName/summarize",
    "/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
elements not found:
  <["/v2/api/myAppName/stats/orgs/{id}/{period}",
    "/v2/api/myAppName/{source}/events/batch",
    "/v2/api/myAppName/initialize",
    "/v2/api/myAppName/eventTypes",
    "/v2/api/myAppName/stats/due/{ids}/{period}",
    "/v2/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/v2/api/myAppName/{source}/events",
    "/v2/api/myAppName/{id}",
    "/v2/api/myAppName/latest/{type}/{user}",
    "/v2/api/myAppName/stats/due/{ids}/custom/{days}",
    "/v2/api/myAppName/stats/{ids}/{period}",
    "/v2/api/myAppName",
    "/v2/api/myAppName/summarize",
    "/v2/api/myAppName/stats/{ids}/{period}/{days}"]>
and elements not expected:
  <["/api/myAppName",
    "/api/myAppName/eventTypes",
    "/api/myAppName/initialize",
    "/api/myAppName/latest/{type}/{user}",
    "/api/myAppName/stats/due/{ids}/custom/{days}",
    "/api/myAppName/stats/due/{ids}/{period}",
    "/api/myAppName/stats/orgs/most/{ids}/{period}",
    "/api/myAppName/stats/orgs/{id}/{period}",
    "/api/myAppName/stats/{ids}/{period}",
    "/api/myAppName/stats/{ids}/{period}/{days}",
    "/api/myAppName/summarize",
    "/api/myAppName/{id}",
    "/api/myAppName/{source}/events",
    "/api/myAppName/{source}/events/batch"]>
at DocumentationDrivenValidator.validatePaths(DocumentationDrivenValidator.java:108)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at io.github.robwin.swagger.test.DocumentationDrivenValidator.validateSwagger(DocumentationDrivenValidator.java:88)
    at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:75)
    at io.github.robwin.swagger.test.SwaggerAssert.isEqualTo(SwaggerAssert.java:87)
    at my.com.app.definitions.MyTest.shouldFindNoDifferences(MyTest.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

I think I'm missing something.


问:
Linux At Command running docker-compose

Goal: I am trying to schedule a 'docker-compose up' at a scheduled time

Operating System: Linux Ubuntu 18.04

I have tried using the 'at' command in linux but I am trying to set variables and couldn't get it to quite work.

Attempts below:

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above does not run the docker-compose

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above runs docker-compose command immediately but not in 2 minutes
```

<pre class="lang-sh prettyprint-override"><code># run.sh

# SET LOGFILE LOCATION
LOG_FILE="/var/log/at/test.log"

FLIGHT_FILE="flight.yaml" docker-compose up --abort-on-container-exit >> "${LOG_FILE}"
</code>```

If there is a better way than using the 'at' command I am also open to that.

Thank you in advance

答:
There are 2 possible approaches -

Single file-

Create a file /etc/systemd/system/dc-test.service

```<code>[Unit]
Description=My Docker Compose runner

[Service]
User=%I
Restart=always
RestartSec=600s
ExecStart=/bin/bash /home/user/run.sh
</code>```

Above will run the script ever 600 seconds.

Multi File (with service timers)

You need to create two files, one for service, other for timer with same name.

example:

/etc/systemd/system/dc-test.service

```<code>[Unit]
Description=My Docker Compose runner

[Service]
Type=oneshot
ExecStart=/bin/bash /home/user/run.sh
</code>```

/etc/systemd/system/dc-test.timer

```<code>[Unit]
Description=Docker Compose Timer

[Timer]
OnUnitActiveSec=600s
OnBootSec=600s

[Install]
WantedBy=timers.target
</code>```

In both the approaches you will need to run systemctl daemon-reload after you are done creating files.

Title: Linux At Command running docker-compose

Body:
Goal: I am trying to schedule a 'docker-compose up' at a scheduled time

Operating System: Linux Ubuntu 18.04

I have tried using the 'at' command in linux but I am trying to set variables and couldn't get it to quite work.

Attempts below:

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above does not run the docker-compose

sudo echo "KEY='VALUE' DIRECTION='D' sh run.sh" | at now + 2 minute
# Above runs docker-compose command immediately but not in 2 minutes

# run.sh

# SET LOGFILE LOCATION
LOG_FILE="/var/log/at/test.log"

FLIGHT_FILE="flight.yaml" docker-compose up --abort-on-container-exit >> "${LOG_FILE}"

If there is a better way than using the 'at' command I am also open to that.

Thank you in advance

Body:
There are 2 possible approaches -

Single file-

Create a file /etc/systemd/system/dc-test.service

[Unit]
Description=My Docker Compose runner

[Service]
User=%I
Restart=always
RestartSec=600s
ExecStart=/bin/bash /home/user/run.sh

Above will run the script ever 600 seconds.

Multi File (with service timers)

You need to create two files, one for service, other for timer with same name.

example:

/etc/systemd/system/dc-test.service

[Unit]
Description=My Docker Compose runner

[Service]
Type=oneshot
ExecStart=/bin/bash /home/user/run.sh

/etc/systemd/system/dc-test.timer

[Unit]
Description=Docker Compose Timer

[Timer]
OnUnitActiveSec=600s
OnBootSec=600s

[Install]
WantedBy=timers.target

In both the approaches you will need to run systemctl daemon-reload after you are done creating files.


问:
Not identifying read only checkbox is checked in JQuery/Javascript
I have parameters with edit and save option.For instance in below table

Parametername   Type1             Type2             Type3

Test           rdb(checkBox)     rdb(checkBox)   rdb(checkBox)  Edit(Button)

If i click edit button, row will be enabled and i need to select any one type check box and save the type.While saving the type i assigned checkbox value as rdb='t'.This 't' will save it in data base.Now i am facing issue with this.Whenever selecting checkbox,value is going as null.Below code i am using.

Mange_Page.html.erb

```<code><script>
    $('.editoidbtn').click(function() {
        var $this = $(this);
        var oid = $this.closest('tr').find('td:first-child').filter(function() {
            return $(this).find('.editoidbtn').length === 0;
        });
        var oidName = $this.closest('tr').find('td:first-child').next().filter(function() {
            return $(this).find('.editoidbtn').length === 0;
        });
        var expected = $this.closest('tr').find('td:first-child').next().next().filter(function() {
            return $(this).find('.editoidbtn').length === 0;
        });

        if ($this.html() === 'Edit') {
            $this.html('Save');
            oid.attr('contenteditable', true);
            oidName.attr('contenteditable', true);
            expected.attr('contenteditable', true);
            $this.closest("tr").find("input[name='rd_b']").attr('disabled', false);
            $this.closest("tr").find("input[name='rd_v']").attr('disabled', false);
            $this.closest("tr").find("input[name='rd_c']").attr('disabled', false);
            $this.closest("tr").find("input[name='review']").attr('disabled', false);
            $this.closest('tr').css('border',  " solid skyblue");
        }
        else {

            if ($this.html() === 'Save') {
                saveRows($this);
                $this.html('Edit');
                oid.attr('contenteditable', false);
                oidName.attr('contenteditable', false);
                expected.attr('contenteditable', false);
                $this.closest("tr").find("input[name='rd_b']").attr('disabled', true);
                $this.closest("tr").find("input[name='rd_v']").attr('disabled', true);
                $this.closest("tr").find("input[name='rd_c']").attr('disabled', true);
                $this.closest("tr").find("input[name='review']").attr('disabled', true);
                $this.closest('tr').css('border', 'none');
            }
        }
    });

</code>```

Java script

```<code>function saveRows($this){

    tr181 = $('#TR_protocol').is(":visible");
    snmp = $('#SN_protocol').is(":visible");

    var values = [];
    var $row = $this.closest("tr"),
    $tds = $row.find("td");
  count = 0;
  $.each($tds, function() {
   values[count]=$(this).text();
    count++;
  });

  if(tr181){
   var parameter_name = values[0].trim();
   var expected_value = values[1].trim();
    if($row.find("input[name='rd_b']").attr('checked')){
      var rdb = 't'
     }else{
       rdb =null;
     }
    if($row.find("input[name=rd_v]").attr('checked')){
    var rdv = 't'
    }else{
     rdv =null;
    }
    if($row.find("input[name=rd_c]").attr('checked')){
      var rdc = 't'
    }else{
      rdc =null;
    }
    if($row.find("input[name=reviews]").attr('checked')){
        var review = null;
      }

    $.ajax({
      type: "POST",
      contentType: "application/json",
      url: "/configuration/update_parameter",
      data: JSON.stringify({
        parameter_name: parameter_name,
        expected_value: expected_value,
        rdb: rdb,
        rdv: rdv,
        rdc: rdc,
        review: review,
       }),
        beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
        success: function (result) {
        if (result === 'false') {
            alert('Parameter not Updated  !!!');
            return false;
         } else {
            alert('Parameter Updated successfully  !!!');
          }
        }
     });
   }
 }
 }

</code>```

From below part i am getting Ajax response as nil.When i click save button control is going to else part eventhough i have sleeted checkbox.It has to go with value 't'.

```<code>if($row.find("input[name='rd_b']").attr('checked')){
      var rdb = 't'
     }else{
       rdb =null;
     }
</code>```

答:
I think the issue is your code for checking the value if checked or not?

Have you try to used,

```<code>example: .find("input[name=rd_v]").is(':checked') # returns true or false
</code>```

Body:
I think the issue is your code for checking the value if checked or not?

Have you try to used,

example: .find("input[name=rd_v]").is(':checked') # returns true or false


问:
I am using redux in react native application to fetch and display data but its not updating on data change from backend
I am using Redux in my React-Native application.
I am fetching the data from api call and on success rendoring it on ListItem.
I am able to fetch and display data but data is not auto updating unless and until I revisit the page.
Even values are not storing into the app
I am calling method from actions in constructor and componentDidMount method.
Can you Please check the code and tell me where am I going wrong.

Here is action.js

```<code>import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './types';

export const fetchingProductRequest = () => ({
    type : FETCHING_PRODUCT_REQUEST
});

export const fetchingProductSuccess = (json) => ({
    type : FETCHING_PRODUCT_SUCCESS,
    payload : json
});

export const fetchingProductFailure = (error) => ({
    type : FETCHING_PRODUCT_FAILURE,
    payload : error
});

export const fetchProduct = () => {
    return async dispatch => {
        dispatch(fetchingProductRequest());
        try {
            let response = await fetch("http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop");
            let json = await response.json();
            dispatch(fetchingProductSuccess(json));
        } catch(error) {
            dispatch(fetchingProductFailure(error));
        }
    }
}
</code>```

My reducer.js

```<code>import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './../actions/types';

const initialState = {
    loading : false,
    errorMessage : '',
    shops: []
}

const products = ( state = initialState, action ) => {
    switch(action.type) {
        case FETCHING_PRODUCT_REQUEST :
            return { ...state, loading: true} ;
        case FETCHING_PRODUCT_SUCCESS :
            return { ...this.state, loading: false, shops: action.payload };
        case FETCHING_PRODUCT_FAILURE :
            return { ...state, loading: false, errorMessage: action.payload};
    }
};

export default products;
</code>```

product.js

```<code>import * as React from 'react';

import { FlatList , ActivityIndicator} from 'react-native';

import { ListItem } from 'react-native-elements';

import { fetchProduct } from './../../actions/products';

import { connect } from 'react-redux';

import propTypes from 'prop-types';

class Product extends React.Component {

  constructor(props) {
    super(props);
    this.props.fetchProduct();
    this.state = {
      loading : true,
      shops : '',
     isFetching: false,
     active : true,
    }
   }

   fetchProducts() {
    const shopid = 13;
    fetch(`http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop`)
        .then(response => response.json())
          .then((responseJson)=> {
              this.setState({
                 loading: false,
                 shops: responseJson
              })
             alert(JSON.stringify(this.state.shops));
        })
    .catch(error=>console.log(error)) //to catch the errors if any
   }

    componentDidMount(){
      // this.fetchProducts();
      this.props.fetchProduct().then(this.setState({loading : false}));
    }

  renderItem = ({ item }) => (
  <ListItem
    title={item.name}
    subtitle={item.name}
    leftAvatar={{
      source: item.avatar && { uri: item.avatar },
      title: item.name[0]
    }}
    bottomDivider
    chevron
  />
)

render () {
    if(!this.state.loading)
    {
      if(this.props.shopsInfo.loading)
      {
        return (
        <ActivityIndicator/>
        )
      }
      else
      {
        return (
        <FlatList
                vertical
                showsVerticalScrollIndicator={false}
                data={this.props.shopsInfo.shops}
                renderItem={this.renderItem}
              />
      )
      }
    }
    else
    {
      return (
        <ActivityIndicator/>
        )
    }
  }
}

Product.propTypes = {
  fetchProduct:  propTypes.func.isRequired
};

const mapStateToProps = (state) => {
  return { shopsInfo: state };
}

function mapDispatchToProps (dispatch) {
  return {
    fetchProduct: () => dispatch(fetchProduct())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Product);
</code>```

答:
1. Not updating on data change from backend.

You have to call an api on regular interval to get updated data. Redux implementation doesn't mean it will fetch data from server whenever there is any change.

2. Even values are not storing into the app

If you are expecting redux will store data even if you will close/kill an application than it will not. You have persist data in-order to use it or store it in cache. Take a look at redux-persist

Body:
I am using Redux in my React-Native application.
I am fetching the data from api call and on success rendoring it on ListItem.
I am able to fetch and display data but data is not auto updating unless and until I revisit the page.
Even values are not storing into the app
I am calling method from actions in constructor and componentDidMount method.
Can you Please check the code and tell me where am I going wrong.

Here is action.js

import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './types';

export const fetchingProductRequest = () => ({
    type : FETCHING_PRODUCT_REQUEST
});

export const fetchingProductSuccess = (json) => ({
    type : FETCHING_PRODUCT_SUCCESS,
    payload : json
});

export const fetchingProductFailure = (error) => ({
    type : FETCHING_PRODUCT_FAILURE,
    payload : error
});

export const fetchProduct = () => {
    return async dispatch => {
        dispatch(fetchingProductRequest());
        try {
            let response = await fetch("http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop");
            let json = await response.json();
            dispatch(fetchingProductSuccess(json));
        } catch(error) {
            dispatch(fetchingProductFailure(error));
        }
    }
}

My reducer.js

import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './../actions/types';

const initialState = {
    loading : false,
    errorMessage : '',
    shops: []
}

const products = ( state = initialState, action ) => {
    switch(action.type) {
        case FETCHING_PRODUCT_REQUEST :
            return { ...state, loading: true} ;
        case FETCHING_PRODUCT_SUCCESS :
            return { ...this.state, loading: false, shops: action.payload };
        case FETCHING_PRODUCT_FAILURE :
            return { ...state, loading: false, errorMessage: action.payload};
    }
};

export default products;

product.js

import * as React from 'react';

import { FlatList , ActivityIndicator} from 'react-native';

import { ListItem } from 'react-native-elements';

import { fetchProduct } from './../../actions/products';

import { connect } from 'react-redux';

import propTypes from 'prop-types';

class Product extends React.Component {

  constructor(props) {
    super(props);
    this.props.fetchProduct();
    this.state = {
      loading : true,
      shops : '',
     isFetching: false,
     active : true,
    }
   }

   fetchProducts() {
    const shopid = 13;
    fetch(`http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop`)
        .then(response => response.json())
          .then((responseJson)=> {
              this.setState({
                 loading: false,
                 shops: responseJson
              })
             alert(JSON.stringify(this.state.shops));
        })
    .catch(error=>console.log(error)) //to catch the errors if any
   }

    componentDidMount(){
      // this.fetchProducts();
      this.props.fetchProduct().then(this.setState({loading : false}));
    }

  renderItem = ({ item }) => (
  <ListItem
    title={item.name}
    subtitle={item.name}
    leftAvatar={{
      source: item.avatar && { uri: item.avatar },
      title: item.name[0]
    }}
    bottomDivider
    chevron
  />
)

render () {
    if(!this.state.loading)
    {
      if(this.props.shopsInfo.loading)
      {
        return (
        <ActivityIndicator/>
        )
      }
      else
      {
        return (
        <FlatList
                vertical
                showsVerticalScrollIndicator={false}
                data={this.props.shopsInfo.shops}
                renderItem={this.renderItem}
              />
      )
      }
    }
    else
    {
      return (
        <ActivityIndicator/>
        )
    }
  }
}

Product.propTypes = {
  fetchProduct:  propTypes.func.isRequired
};

const mapStateToProps = (state) => {
  return { shopsInfo: state };
}

function mapDispatchToProps (dispatch) {
  return {
    fetchProduct: () => dispatch(fetchProduct())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Product);


问:
React useState not triggering re-render of child component
I cant seem to figure out why my MovieDetailCard component will not re-render when the movie state changes. I am passing in the movie object. When I update the state the log outputs correctly in the useEffect but the MovieDetailsCard never receives the updated object.

```<code>    const MovieDetails = () => {
    const [movie, setMovie] = useState({});
    const { id } = useParams();
    const { poster } = useParams();

  useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, []);

  useEffect(() => {
    console.log(movie); // this successfully outputs when movie updates
  }, [movie]);

  return (
    <div className="row">
      <div className="col s12 m6">
        <MovieDetailsCard poster={poster} movie={movie} /> // this does not update
      </div>
      <div className="col s12 m6">
        <CastCrewCard />
      </div>
    </div>
  );
};
</code>```

Below is the MovieDeatailsCard. In the useEffect the console.log(movie) always returns null.

```<code>const MovieDetailsCard = ({ poster, movie }) => {
  useEffect(() => {
    console.log("in details");

    console.log(movie);
  }, []);
  return (
    <div className="card">
      <div className="card-content">
        <div className="row">
          <div className="col s6">
            <span className="card-title">Movie Title</span>
          </div>
          <div className="col s6 favouriteButton">
            <FavouriteButton className="waves-effect waves-light btn">
              <i className="material-icons">favorite</i>
            </FavouriteButton>
          </div>
        </div>

        <div className="row">
          <div className="col s12 m6">
            <img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />
          </div>
          <div className="col s12 m6">
            <p>{movie.title}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MovieDetailsCard;
</code>```

答:
By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

refer: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect

If you want to run an effect and clean it up only once (on mount and
  unmount), you can pass an empty array ([]) as a second argument. This
  tells React that your effect doesn’t depend on any values from props
  or state, so it never needs to re-run. This isn’t handled as a special
  case — it follows directly from how the dependencies array always
  works.

try updating useEffect dependendecy to include [id]:

```<code> useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, [id]);

</code>```

Body:
I cant seem to figure out why my MovieDetailCard component will not re-render when the movie state changes. I am passing in the movie object. When I update the state the log outputs correctly in the useEffect but the MovieDetailsCard never receives the updated object.

    const MovieDetails = () => {
    const [movie, setMovie] = useState({});
    const { id } = useParams();
    const { poster } = useParams();

  useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, []);

  useEffect(() => {
    console.log(movie); // this successfully outputs when movie updates
  }, [movie]);

  return (

        <MovieDetailsCard poster={poster} movie={movie} /> // this does not update

        <CastCrewCard />

  );
};

Below is the MovieDeatailsCard. In the useEffect the console.log(movie) always returns null.

const MovieDetailsCard = ({ poster, movie }) => {
  useEffect(() => {
    console.log("in details");

    console.log(movie);
  }, []);
  return (

            Movie Title

            <FavouriteButton className="waves-effect waves-light btn">
              favorite
            </FavouriteButton>

            <img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />

{movie.title}

  );
};

export default MovieDetailsCard;

Body:
By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

refer: https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect

If you want to run an effect and clean it up only once (on mount and
  unmount), you can pass an empty array ([]) as a second argument. This
  tells React that your effect doesn’t depend on any values from props
  or state, so it never needs to re-run. This isn’t handled as a special
  case — it follows directly from how the dependencies array always
  works.

try updating useEffect dependendecy to include [id]:

 useEffect(() => {
    const fetchMovie = async () => {
      const response = await fetch(
        `http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
      );

      const data = await response.json();

      setMovie({ ...data });
    };

    fetchMovie();
  }, [id]);


问:
How to change style in specific row in Element UI Table
I'm using Element UI for my web app.
In my app, there is a table component, that is made by el-table component provided by Element UI.

And I would like to change style for the only specific row.

Firstly, please take a look at the screenshot and my code, later, I will explain what I would like to do specifically with them.

These are the screenshot of table in my app and my code.

```<code><template>
  <el-table
    :data="tableData"
    height="250"
    style="width: 100%">
    <el-table-column
      prop="date"
      label="Date"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="Name"
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label="Address">
    </el-table-column>
  </el-table>
</template>

<script>
  export default {
    data() {
      return {
        tableData: [{
          date: '2016-05-03',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-02',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-04',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-01',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-08',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-06',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }, {
          date: '2016-05-07',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles'
        }],
      }
    }
  }
</script>
</code>```

I would like to change background color blue for the row that's Data is 2016-05-03 and 2016-05-04 in the case above.

答:
Add this code on the component stylesheet</p>

```<code>.el-table tr:nth-child(odd) {
    background-color: #845353;
}
</code>```

Body:
I'm using Element UI for my web app.
In my app, there is a table component, that is made by el-table component provided by Element UI.

And I would like to change style for the only specific row.

Firstly, please take a look at the screenshot and my code, later, I will explain what I would like to do specifically with them.

These are the screenshot of table in my app and my code.

<template>
  <el-table
    :data="tableData"
    height="250"
    style="width: 100%">
    <el-table-column
      prop="date"
      label="Date"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="Name"
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label="Address">
    </el-table-column>
  </el-table>
</template>

I would like to change background color blue for the row that's Data is 2016-05-03 and 2016-05-04 in the case above.

Body:
Add this code on the component stylesheet

.el-table tr:nth-child(odd) {
    background-color: #845353;
}


问:
How to add the ImageMagick install to my path on Ubuntu
I have had been on a roller coaster trying to get ImageMagick to work on my Ubuntu slice. I Whenever I try to upload an image I get the following error: /tmp/stream.1170.0 is not recognized by the 'identify' command.

If I type 'which identify' I get: /usr/local/bin/identify

If I run '/usr/local/bin/identify' or just 'identify', I get the following error: /usr/local/bin/identify: error while loading shared libraries: libMagickCore.so.3: cannot open shared object file: No such file or directory

If I run '/usr/bin/identify', ImageMagick is run just fine. How can I set my path to where when Paperclip runs the identify command, it points to /usr/bin/identify? Thanks.

p.s. I have tried adding this to paperclip.rb: Paperclip.options[:command_path] = '/usr/bin' and Paperclip.options[:command_path] = '/usr/local/bin'

答:
Please follow the below steps otherwise.

```<code>$ sudo apt update
$ sudo apt-get install build-essential

$ wget https://www.imagemagick.org/download/ImageMagick.tar.gz
$ tar xvzf ImageMagick.tar.gz

$ cd ImageMagick-7.0.8-26/
</code>```

To run configuration and to compile

```<code>$./configure
$ make
$ sudo make install
</code>```

To create link,

```<code>$ sudo ldconfig /usr/local/lib
</code>```

Check version

```<code>$ magick -version
</code>```

Thanks to Aaron Kili, Author of the below article.

Source: https://www.tecmint.com/install-imagemagick-on-debian-ubuntu/

ContentLicense: CC BY-SA 2.5

Body:
Please follow the below steps otherwise.

$ sudo apt update
$ sudo apt-get install build-essential

$ wget https://www.imagemagick.org/download/ImageMagick.tar.gz
$ tar xvzf ImageMagick.tar.gz

$ cd ImageMagick-7.0.8-26/

To run configuration and to compile

$./configure
$ make
$ sudo make install

To create link,

$ sudo ldconfig /usr/local/lib

Check version

$ magick -version

Thanks to Aaron Kili, Author of the below article.

Source: https://www.tecmint.com/install-imagemagick-on-debian-ubuntu/


问:
Python 3 and Sklearn: Difficulty to use a NOT-sklearn model as a sklearn model
The code below is working. I have just a routine to run a cross validation scheme using a linear model previous defined in sklearn. I do not have a problem with this. My problem is that: if I replace the code model=linear_model.LinearRegression() by the model=RBF('multiquadric') (please see line 14 and 15 in the __main__, it does not work anymore. So my problem is actually in the class RBF where I try to mimic a sklearn model.

If I replace the code described above, I get the following error:

```<code>  FitFailedWarning)
/home/daniel/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details:
ValueError: All arrays must be equal length.

  FitFailedWarning)
</code>```

1) Should I define a score function in the Class RBF?

2) How to do that? I am lost. Since I am inherit BaseEstimator and RegressorMixin, I expected that this was internally solved.

3) Is there something else missing?

```<code>from sklearn import datasets
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn import model_selection
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from scipy.interpolate import Rbf
np.random.seed(0)
from sklearn.base import BaseEstimator, RegressorMixin

class RBF(BaseEstimator, RegressorMixin):
    def __init__(self,function):
        self.function=function
    def fit(self,x,y):
        self.rbf = Rbf(x, y,function=self.function)
    def predict(self,x):
        return self.rbf(x)

if __name__ == "__main__":
    # Load Data
    targetName='HousePrice'
    data=datasets.load_boston()
    featuresNames=list(data.feature_names)
    featuresData=data.data
    targetData = data.target
    df=pd.DataFrame(featuresData,columns=featuresNames)
    df[targetName]=targetData
    independent_variable_list=featuresNames
    dependent_variable=targetName
    X=df[independent_variable_list].values
    y=np.squeeze(df[[dependent_variable]].values)
    # Model Definition
    model=linear_model.LinearRegression()
    #model=RBF('multiquadric')
    # Cross validation routine
    number_splits=5
    score_list=['neg_mean_squared_error','neg_mean_absolute_error','r2']
    kfold = model_selection.KFold(n_splits=number_splits,shuffle=True, random_state=0)
    scalar = StandardScaler()
    pipeline = Pipeline([('transformer', scalar), ('estimator', model)])
    results = model_selection.cross_validate(pipeline, X, y, cv=kfold, scoring=score_list,return_train_score=True)
    for score in score_list:
        print(score+':')
        print('Train: '+'Mean',np.mean(results['train_'+score]),'Standard Error',np.std(results['train_'+score]))
        print('Test: '+'Mean',np.mean(results['test_'+score]),'Standard Error',np.std(results['test_'+score]))
</code>```

答:
Lets look at the documentation here

*args : arrays

x, y, z, …, d, where x, y, z, … are the coordinates of the nodes and d is the array of values at the nodes

So it takes variable length argument with the last argument being the value which is y in your case. Argument k is the kth coordinates of all the data point (same for all other argument z, y, z, ….

Following the documentation, your code should be

```<code>from sklearn import datasets
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn import model_selection
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from scipy.interpolate import Rbf
np.random.seed(0)
from sklearn.base import BaseEstimator, RegressorMixin

class RBF(BaseEstimator, RegressorMixin):
    def __init__(self,function):
        self.function=function
    def fit(self,X,y):
        self.rbf = Rbf(*X.T, y,function=self.function)

    def predict(self,X):
        return self.rbf(*X.T)

# Load Data
data=datasets.load_boston()

X = data.data
y = data.target

number_splits=5
score_list=['neg_mean_squared_error','neg_mean_absolute_error','r2']

kfold = model_selection.KFold(n_splits=number_splits,shuffle=True, random_state=0)
scalar = StandardScaler()

model = RBF(function='multiquadric')

pipeline = Pipeline([('transformer', scalar), ('estimator', model)])

results = model_selection.cross_validate(pipeline, X, y, cv=kfold, scoring=score_list,return_train_score=True)

for score in score_list:
        print(score+':')
        print('Train: '+'Mean',np.mean(results['train_'+score]),'Standard Error',np.std(results['train_'+score]))
        print('Test: '+'Mean',np.mean(results['test_'+score]),'Standard Error',np.std(results['test_'+score]))
</code>```

Output

```<code>neg_mean_squared_error:
Train: Mean -1.552450953914355e-20 Standard Error 7.932530906290208e-21
Test: Mean -23.007377210596463 Standard Error 4.254629143836107
neg_mean_absolute_error:
Train: Mean -9.398502208736061e-11 Standard Error 2.4673749061941226e-11
Test: Mean -3.1319779583728673 Standard Error 0.2162343985534446
r2:
Train: Mean 1.0 Standard Error 0.0
Test: Mean 0.7144217179633185 Standard Error 0.08526294242760363
</code>```

Why *X.T : As we saw, each argument correspond to an axis of all the data points, so we transpose them and then use * operator to expand and pass each of the sub array as an argument to the variable length function.

Looks like the latest implementation has a mode parameter where we can pass the N-D array directly.

Body:
The code below is working. I have just a routine to run a cross validation scheme using a linear model previous defined in sklearn. I do not have a problem with this. My problem is that: if I replace the code model=linear_model.LinearRegression() by the model=RBF('multiquadric') (please see line 14 and 15 in the __main__, it does not work anymore. So my problem is actually in the class RBF where I try to mimic a sklearn model.

If I replace the code described above, I get the following error:

  FitFailedWarning)
/home/daniel/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_validation.py:536: FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details:
ValueError: All arrays must be equal length.

  FitFailedWarning)

1) Should I define a score function in the Class RBF?

2) How to do that? I am lost. Since I am inherit BaseEstimator and RegressorMixin, I expected that this was internally solved.

3) Is there something else missing?

from sklearn import datasets
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn import model_selection
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from scipy.interpolate import Rbf
np.random.seed(0)
from sklearn.base import BaseEstimator, RegressorMixin

class RBF(BaseEstimator, RegressorMixin):
    def __init__(self,function):
        self.function=function
    def fit(self,x,y):
        self.rbf = Rbf(x, y,function=self.function)
    def predict(self,x):
        return self.rbf(x)

if __name__ == "__main__":
    # Load Data
    targetName='HousePrice'
    data=datasets.load_boston()
    featuresNames=list(data.feature_names)
    featuresData=data.data
    targetData = data.target
    df=pd.DataFrame(featuresData,columns=featuresNames)
    df[targetName]=targetData
    independent_variable_list=featuresNames
    dependent_variable=targetName
    X=df[independent_variable_list].values
    y=np.squeeze(df[[dependent_variable]].values)
    # Model Definition
    model=linear_model.LinearRegression()
    #model=RBF('multiquadric')
    # Cross validation routine
    number_splits=5
    score_list=['neg_mean_squared_error','neg_mean_absolute_error','r2']
    kfold = model_selection.KFold(n_splits=number_splits,shuffle=True, random_state=0)
    scalar = StandardScaler()
    pipeline = Pipeline([('transformer', scalar), ('estimator', model)])
    results = model_selection.cross_validate(pipeline, X, y, cv=kfold, scoring=score_list,return_train_score=True)
    for score in score_list:
        print(score+':')
        print('Train: '+'Mean',np.mean(results['train_'+score]),'Standard Error',np.std(results['train_'+score]))
        print('Test: '+'Mean',np.mean(results['test_'+score]),'Standard Error',np.std(results['test_'+score]))

Body:
Lets look at the documentation here

*args : arrays

x, y, z, …, d, where x, y, z, … are the coordinates of the nodes and d is the array of values at the nodes

So it takes variable length argument with the last argument being the value which is y in your case. Argument k is the kth coordinates of all the data point (same for all other argument z, y, z, ….

Following the documentation, your code should be

from sklearn import datasets
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn import model_selection
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from scipy.interpolate import Rbf
np.random.seed(0)
from sklearn.base import BaseEstimator, RegressorMixin

class RBF(BaseEstimator, RegressorMixin):
    def __init__(self,function):
        self.function=function
    def fit(self,X,y):
        self.rbf = Rbf(*X.T, y,function=self.function)

    def predict(self,X):
        return self.rbf(*X.T)

# Load Data
data=datasets.load_boston()

X = data.data
y = data.target

number_splits=5
score_list=['neg_mean_squared_error','neg_mean_absolute_error','r2']

kfold = model_selection.KFold(n_splits=number_splits,shuffle=True, random_state=0)
scalar = StandardScaler()

model = RBF(function='multiquadric')

pipeline = Pipeline([('transformer', scalar), ('estimator', model)])

results = model_selection.cross_validate(pipeline, X, y, cv=kfold, scoring=score_list,return_train_score=True)

for score in score_list:
        print(score+':')
        print('Train: '+'Mean',np.mean(results['train_'+score]),'Standard Error',np.std(results['train_'+score]))
        print('Test: '+'Mean',np.mean(results['test_'+score]),'Standard Error',np.std(results['test_'+score]))

Output

neg_mean_squared_error:
Train: Mean -1.552450953914355e-20 Standard Error 7.932530906290208e-21
Test: Mean -23.007377210596463 Standard Error 4.254629143836107
neg_mean_absolute_error:
Train: Mean -9.398502208736061e-11 Standard Error 2.4673749061941226e-11
Test: Mean -3.1319779583728673 Standard Error 0.2162343985534446
r2:
Train: Mean 1.0 Standard Error 0.0
Test: Mean 0.7144217179633185 Standard Error 0.08526294242760363

Why *X.T : As we saw, each argument correspond to an axis of all the data points, so we transpose them and then use * operator to expand and pass each of the sub array as an argument to the variable length function.

Looks like the latest implementation has a mode parameter where we can pass the N-D array directly.


问:
Get and display the selected variation SKU in WooCommerce
I have this code that works for simple product type but not for variable products in WooCommerce:

```<code>add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
}
</code>```

How can I make it work for both simple and variable products?

答:
You need the Variation ID to get the SKU of Variable Product.

If you pass the Variation ID in the below Function, then you can get its SKU.

```<code>$product = new WC_Product_Variation($variation_id);
$product->get_sku();
</code>```

The below code can be used to get the variations of a product. Then lopp the result to get the variation ID and then use that variation ID in the above code to get the result.

```<code>$variations = $product->get_available_variations();
</code>```

Body:
I have this code that works for simple product type but not for variable products in WooCommerce:

add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    return sprintf( '

', $product->get_sku() );
}

How can I make it work for both simple and variable products?

Body:
You need the Variation ID to get the SKU of Variable Product.

If you pass the Variation ID in the below Function, then you can get its SKU.

$product = new WC_Product_Variation($variation_id);
$product->get_sku();

The below code can be used to get the variations of a product. Then lopp the result to get the variation ID and then use that variation ID in the above code to get the result.

$variations = $product->get_available_variations();


问:
How to place a a Shaded Line After DIV Tag in a HTML Page
Please see my image here:

http://www.tiikoni.com/tis/view/?id=10ca264

After placing the chart, my code starts like this as shown below

```<code><label style="font-weight: bold;">Select Period</label>
</code>```

My question is, as you can see from the image, after placing the chart, there is a line inserted.

Please tell me how to keep this line.

答:
use
 tag.

see here the demo

ContentLicense: CC BY-SA 3.0

Body:
Please see my image here:

http://www.tiikoni.com/tis/view/?id=10ca264

After placing the chart, my code starts like this as shown below

Select Period

My question is, as you can see from the image, after placing the chart, there is a line inserted.

Please tell me how to keep this line.

Body:
use <hr/> tag.

see here the demo


问:
Divide by zero runtime error while using a loop
I had gotten a divide by zero runtime error while using a loop and I do not know why. Don't worry, the code is unfinished yet. I am trying to convert an array using the ulj function if you can help. Here's the code:

```<code>import numpy as np
def ulj(x,epsilon = 4*(10**-4),sigma=6):
"""Compute Lennard-Jones potential as a function of inter-atomic distance"""
return epsilon*((((sigma)/(x))**12)-((((sigma)/(x))**6)))

 positions=np.array([0., 7.0,5,6,2,6,2,2,4,3]) # Initial position of the two objects (in atomic            units)

i = 0

x1 = []
x2 = []
while i <(len(positions)):
    x1.append(ulj(positions[i]))

print(x1)
</code>```

Thanks for your help

答:
Change while loop with below code snippet</p>

```<code>while i <(len(positions)):
    print(positions[i])
    x1.append(ulj(positions[i]))
    i = i+1
</code>```

Body:
I had gotten a divide by zero runtime error while using a loop and I do not know why. Don't worry, the code is unfinished yet. I am trying to convert an array using the ulj function if you can help. Here's the code:

import numpy as np
def ulj(x,epsilon = 4*(10**-4),sigma=6):
"""Compute Lennard-Jones potential as a function of inter-atomic distance"""
return epsilon*((((sigma)/(x))**12)-((((sigma)/(x))**6)))

 positions=np.array([0., 7.0,5,6,2,6,2,2,4,3]) # Initial position of the two objects (in atomic            units)

i = 0

x1 = []
x2 = []
while i <(len(positions)):
    x1.append(ulj(positions[i]))

print(x1)

Thanks for your help

Body:
Change while loop with below code snippet

while i <(len(positions)):
    print(positions[i])
    x1.append(ulj(positions[i]))
    i = i+1


问:
mysql update query takes too long
i have a table with 2255440 records,

a cron job works every minute and inserts upto 50-100 records on every execution

inserts are working fine

the problem is that there is another cron job which is also running every minute.. this cron job updates these records according to the data recieved from other server

the problem is that the update query is taking around 6 - 7 seconds per update query

this is the table information and update query example

records are updated with this query

Query:

```<code>UPDATE `$month`
SET `acctstoptime`='$data->acctstoptime',
    `acctsessiontime`='$data->acctsessiontime',
    `acctinputoctets`='$data->acctinputoctets',
    `acctoutputoctets`='$data->acctoutputoctets',
    `acctterminatecause`='$data->acctterminatecause'
WHERE `radacctid`=$data->radacctid
</code>```

答:
Is there a single-column index on column of 'radacctid'?

If not you should create one.

Title: mysql update query takes too long

Body:
i have a table with 2255440 records,

a cron job works every minute and inserts upto 50-100 records on every execution

inserts are working fine

the problem is that there is another cron job which is also running every minute.. this cron job updates these records according to the data recieved from other server

the problem is that the update query is taking around 6 - 7 seconds per update query

this is the table information and update query example

records are updated with this query

Query:

UPDATE `$month`
SET `acctstoptime`='$data->acctstoptime',
    `acctsessiontime`='$data->acctsessiontime',
    `acctinputoctets`='$data->acctinputoctets',
    `acctoutputoctets`='$data->acctoutputoctets',
    `acctterminatecause`='$data->acctterminatecause'
WHERE `radacctid`=$data->radacctid


问:
Should I process a JSON in the frontend or Backend, which is faster?
I am getting a response from an API as a json response.
I am coding in python for backend.

The frontend team needs information from the raw json response for populating a UI so we have to order the json and make it more easier for them to fetch information.

Now I can order the json in a specific format and push to the frontend team or I can pass the raw json response*to the frontend team and let them handle ordering the json and further use for their UI.

Remember my json file size is 15MB.

Which is faster and a better design principle?

Process in the backend then push to frontend or process in the frontend?

答:
Ideally if the file size is 15 mb it will be loaded to the browsers memory which will make it slow, I would suggest to do the operation in backend only.

You can also go through this link for reference.
Difference Between python and Javascript and what to use

One important aspect is that JavaScript is difficult to debug. You
might notice that despite your code being error-free, the program
won’t work (fail silently).


问:
can't connect to mysql8.0 on ubuntu via vmware
I can't appear to make a successful connection with mysql 8.0 that's on Ubunti 18.04 va VMware from my windows 10 host through either visual studio (with the connector/net plugin) or through mysql workbench.

I've set the various test
users to use the mysql_native_password as well as caching_sha2_passwword

updated mysqld.cnf by setting bind-address = 0.0.0.0 (mysql fails when I edit my.cnf, but there's a symbolic link to /etc/mysql/mysql.conf.d/mysqld.cnf that I updated

did GRANT ALL PRIVELEGES like all the tutorials said; did FLUSH

I can ssh through powershell on my windows host but VS Studio 19 and MYSQL Workbench's simple connect feature doesn't work, when it should.

What could be the issue, aside from reverting down to mysql 5.7 because I has that before upgrading and it still didn't work, thanks.

答:
```<code>in the my.cnf file it should have:
[mysql]
bind-address = X.X.X.X
#skip-networking

It should have all three just like that. The "X.X.X.X" is your IP address, or use 0.0.0.0

then restart with "service mysql restart" just as every article on google has suggested and you're set.

Oh, and this only worked for me using the mysql_native_password plugin, not caching_sha2_password. Also, the user was set up with the host as '%' so for instance test@%. Lastly, do everything else above such as the GRANT and FLUSH and you're good to go.
</code>```


问:
How to read data in file which the file inside a file in perl?
I have list2.txt file and inside that file, there are several files like 02x5.txt or 0.3x5.txt etc. Then how to read data inside 02x5.txt file at one time? Inside 02x5.txt, there are height:20, length:5, colour:blue etc.

```<code>inside list2.txt:
02x5.txt
03x5.txt

inside 02x5.txt:
height:20,
length:5,
colour:blue

inside 03x5.txt:
height:25,
length:10,
colour:green
</code>```

```<code>#!/usr/bin/perl
    use strict;
    use warnings;

# Reading a line from a file (or rather from a filehandle)
my $filename = "list2.txt";
    if (open my $data, "<", $filename) {
    while (my $row = <$data>) {
        chomp $row;
        if ($row =~ m/02x5.txt$/ ){
        my $m = $row;
            print "$m\n";
        }
    }
    }
</code>```

How can I read data for height and length from certain txt file?
Thank you

答:
Please see following piece of code which performs tasks you've described, read data stored in hash %data which you can use anyway you desire.

```<code>use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $debug = 1;

my $filename = 'list2.txt';

my %data;

open my $fh, '<', $filename
    or die "Couldn't open $filename";

my @filenames = <$fh>;

close $fh;

chomp @filenames;

foreach $filename(@filenames) {
    open $fh, '<', $filename
        or die "Couldn't open $filename";

    while( <$fh> ) {
        chomp;
        my($k,$v) = split ':';
        $data{$filename}{$k} = $v;
    }

    close $fh;
}

say Dumper(\%data);
</code>```

Output

```<code>$VAR1 = {
          '02x5.txt' => {
                          'colour' => 'blue',
                          'height' => '20, ',
                          'length' => '5, '
                        },
          '03x5.txt' => {
                          'length' => '10, ',
                          'colour' => 'green',
                          'height' => '25, '
                        }
        };
</code>```

Body:
I have list2.txt file and inside that file, there are several files like 02x5.txt or 0.3x5.txt etc. Then how to read data inside 02x5.txt file at one time? Inside 02x5.txt, there are height:20, length:5, colour:blue etc.

inside list2.txt:
02x5.txt
03x5.txt

inside 02x5.txt:
height:20,
length:5,
colour:blue

inside 03x5.txt:
height:25,
length:10,
colour:green

#!/usr/bin/perl
    use strict;
    use warnings;

# Reading a line from a file (or rather from a filehandle)
my $filename = "list2.txt";
    if (open my $data, "<", $filename) {
    while (my $row = <$data>) {
        chomp $row;
        if ($row =~ m/02x5.txt$/ ){
        my $m = $row;
            print "$m\n";
        }
    }
    }

How can I read data for height and length from certain txt file?
Thank you

Body:
Please see following piece of code which performs tasks you've described, read data stored in hash %data which you can use anyway you desire.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $debug = 1;

my $filename = 'list2.txt';

my %data;

open my $fh, '<', $filename
    or die "Couldn't open $filename";

my @filenames = <$fh>;

close $fh;

chomp @filenames;

foreach $filename(@filenames) {
    open $fh, '<', $filename
        or die "Couldn't open $filename";

    while( <$fh> ) {
        chomp;
        my($k,$v) = split ':';
        $data{$filename}{$k} = $v;
    }

    close $fh;
}

say Dumper(\%data);

Output

$VAR1 = {
          '02x5.txt' => {
                          'colour' => 'blue',
                          'height' => '20, ',
                          'length' => '5, '
                        },
          '03x5.txt' => {
                          'length' => '10, ',
                          'colour' => 'green',
                          'height' => '25, '
                        }
        };


问:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
Log Cat:

```<code>no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
</code>```

code:

```<code>    102) public String getID(String note){
    103)      SQLiteDatabase db = this.getWritableDatabase();
    104)      String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
    105)      db.rawQuery(query,null);
    106)      return query;
    107) }
</code>```

I do have a column name hey in my Database
Database Picture

答:
The way that you concatenate the parameter note creates this sql statement:

```<code>SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
</code>```

so hey is considered a column identifier and not a string literal because it is not enclosed inside single quotes.

You could do this instead:

```<code>String  query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'";
</code>```

and it would work.

But the recommended way is passing parameters as a string array like this:

```<code>String  query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {note});
return cursor;
</code>```

This way you don't worry about single quotes as this is taken care of by rawQuery().

I guess you want to return the Cursor object and not the sql query string, right?

Body:
Log Cat:

no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

code:

    102) public String getID(String note){
    103)      SQLiteDatabase db = this.getWritableDatabase();
    104)      String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
    105)      db.rawQuery(query,null);
    106)      return query;
    107) }

I do have a column name hey in my Database
Database Picture

Body:
The way that you concatenate the parameter note creates this sql statement:

SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

so hey is considered a column identifier and not a string literal because it is not enclosed inside single quotes.

You could do this instead:

String  query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'";

and it would work.

But the recommended way is passing parameters as a string array like this:

String  query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {note});
return cursor;

This way you don't worry about single quotes as this is taken care of by rawQuery().

I guess you want to return the Cursor object and not the sql query string, right?


问:
How to access values from the constructor in an array of objects
I have a react component maintoolbar.tsx that has a grid object passed to it as a prop

```<code>import React from 'react';
import { Grid } from '../grid';

interface PropsInterface {
  grid: Grid;
}

const MainToolbar: React.FC<PropsInterface> = (props: PropsInterface) => {
  const { grid } = props;
  const test = grid.mainToolbar.shapes[0].name;
//                                       ^ doesnt return the name
  const newNode = () => {
    grid.newNode();
  };

  return (
    <div className='main-toolbar'>
     ...
    </div>
  );
};

export { MainToolbar };
</code>```

This is what I get returned, but how to do I access the value of this.name??

```<code>class Square {
  constructor(nodes) {
    this.name = 'square';
</code>```

The grid object I'm getting from the props has an array of objects

```<code>import { Square } from './components/square';
class Grid {
  constructor() {
    this.mainToolbar = {
      shapes: [Square],
    };
  }
}
export { Grid };
</code>```

And finally square

```<code>class Square {
  name: string;

  constructor(nodes: NodesInterface) {
    this.name = 'square';
  }
}

export { Square };
</code>```

if a do   console.log(grid.mainToolbar.shapes);
i get this [f] thing ive not seen before

If I do console.log(grid.mainToolbar.shapes[0], ' type ' , typeof grid.mainToolbar.shapes[0]); i get

UPDATE

Adding

```<code>interface MainToolbarInterface {
  [key: string]: any;
}
class Grid
  mainToolbar: MainToolbarInterface;

  constructor() {
    this.mainToolbar = {
      shapes: [new Square(this)],
    };
  }
</code>```

gives me the name, obviously any is not right, what shoujld it be?

答:
In your Grid constructor. You have

constructor() {
  this.mainToolbar = {
    shapes: [Square],
  };
}
```

<p>This is making <code>shapes</code> = an array with the <code>Square</code> class as its first element.</p>

<p>Try </p>

<pre class="lang-js prettyprint-override"><code>constructor() {
  this.mainToolbar = {
    shapes: [new Square()],
  };
}
</code>```

If you were not wanting to initialize it there, and this was the type definition. Then instead

constructor() {
  this.mainToolbar = {
    shapes: [],
  }: {
    shape: Square[]
  };
}
```

<hr>

<p>After update. For the interface type.</p>

<pre class="lang-js prettyprint-override"><code>interface MainToolbarInterface {
  shapes: Array<Square>;
}

class Grid
mainToolbar: MainToolbarInterface;

constructor() {
  this.mainToolbar = {
    shapes: [new Square(this)],
  };
}
</code>```

or shapes: Square[]; if you prefer.

Body:
I have a react component maintoolbar.tsx that has a grid object passed to it as a prop

import React from 'react';
import { Grid } from '../grid';

interface PropsInterface {
  grid: Grid;
}

const MainToolbar: React.FC<PropsInterface> = (props: PropsInterface) => {
  const { grid } = props;
  const test = grid.mainToolbar.shapes[0].name;
//                                       ^ doesnt return the name
  const newNode = () => {
    grid.newNode();
  };

  return (

     ...

  );
};

export { MainToolbar };

This is what I get returned, but how to do I access the value of this.name??

class Square {
  constructor(nodes) {
    this.name = 'square';

The grid object I'm getting from the props has an array of objects

import { Square } from './components/square';
class Grid {
  constructor() {
    this.mainToolbar = {
      shapes: [Square],
    };
  }
}
export { Grid };

And finally square

class Square {
  name: string;

  constructor(nodes: NodesInterface) {
    this.name = 'square';
  }
}

export { Square };

if a do   console.log(grid.mainToolbar.shapes);
i get this [f] thing ive not seen before

If I do console.log(grid.mainToolbar.shapes[0], ' type ' , typeof grid.mainToolbar.shapes[0]); i get

UPDATE

Adding

interface MainToolbarInterface {
  [key: string]: any;
}
class Grid
  mainToolbar: MainToolbarInterface;

  constructor() {
    this.mainToolbar = {
      shapes: [new Square(this)],
    };
  }

gives me the name, obviously any is not right, what shoujld it be?

Body:
In your Grid constructor. You have

constructor() {
  this.mainToolbar = {
    shapes: [Square],
  };
}

This is making shapes = an array with the Square class as its first element.

Try

constructor() {
  this.mainToolbar = {
    shapes: [new Square()],
  };
}

If you were not wanting to initialize it there, and this was the type definition. Then instead

constructor() {
  this.mainToolbar = {
    shapes: [],
  }: {
    shape: Square[]
  };
}

After update. For the interface type.

interface MainToolbarInterface {
  shapes: Array<Square>;
}

class Grid
mainToolbar: MainToolbarInterface;

constructor() {
  this.mainToolbar = {
    shapes: [new Square(this)],
  };
}

or shapes: Square[]; if you prefer.