问:
How to set ForeignKey and Index properties using IEntityTypeConfiguration in EF Core 2.0
I am attempting to use the EntityConfiguration interface which is new in EF Core 2.0.

Addendum Probably helpful to see the Message class

```<code>public class Message
{
    public int MessageId { get; set; }

    [Required]
    public string MessageForUserId { get; set; }
    public virtual ApplicationUser MessageForUser { get; set; }

    [Required]
    public string MessageFromUserId { get; set; }

    public virtual ApplicationUser MessageFromUser { get; set; }

    [Required]
    public string MessageContent { get; set; }

    public bool MessageRead { get; set; }

    [Required]
    public DateTime MessageCreatedOn { get; set; }

    public DateTime? MessageReadOn { get; set; }
}
</code>```

and the AppUser class

```<code>public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Gender Gender { get; set; }
    public SubscriptionLevel SubscriptionLevel { get; set; }
    public NotificationType NotificationType { get; set; }
    public string AvatarUrl { get; set; }
    public ICollection<Message> UserMessages { get; set; }
    public ICollection<Message> SentMessages { get; set; }
    public ICollection<IdentityUserClaim<string>> Claims { get;  set; }
}
</code>```

Here is how the entity is defined in my OnModelCreating method.

```<code>builder.Entity<Message>()
            .HasOne(x => x.MessageForUser)
            .WithMany(x => x.UserMessages)
            .HasForeignKey(x => x.MessageForUserId)
            .OnDelete(DeleteBehavior.Restrict);

builder.Entity<Message>()
            .HasOne(x => x.MessageFromUser)
            .WithMany(x => x.SentMessages)
            .HasForeignKey(x => x.MessageFromUserId)
            .OnDelete(DeleteBehavior.Cascade);
</code>```

My IEntityTypeConfiguration

```<code>public class AppUserConfig : IEntityTypeConfiguration<ApplicationUser>
{
    public void Configure(EntityTypeBuilder<ApplicationUser> builder)
    {
        builder.Property(u => u.FirstName).HasMaxLength(31);
        builder.Property(u => u.FirstName).IsRequired();

        builder.Property(u => u.LastName).HasMaxLength(55);
        builder.Property(u => u.LastName).IsRequired();

        builder.Property(u => u.DateOfBirth).HasColumnType("datetime");
        builder.Property(u => u.DateOfBirth).IsRequired();

        builder.Property(u => u.Gender).IsRequired();
    }
}
</code>```

The EF 6 way had a HasForeignKey method off builder which is no longer available and I cant seem to find any way to add them.

Here is how the migration built the table from my OnModelCreating method. I'd like to put most of these items in my configuration class.

```<code>migrationBuilder.CreateIndex(
            name: "IX_Messages_MessageForUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageForUserId");

migrationBuilder.CreateIndex(
            name: "IX_Messages_MessageFromUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageFromUserId");

migrationBuilder.AddForeignKey(
            name: "FK_Messages_AspNetUsers_MessageForUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageForUserId",
            principalSchema: "AppContext",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);

migrationBuilder.AddForeignKey(
            name: "FK_Messages_AspNetUsers_MessageFromUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageFromUserId",
            principalSchema: "AppContext",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);
</code>```

There still is a HasIndex method, but I'm not sure how to duplicate what the migration is producing in the lambda expression for HasIndex.

答:
HasForeignKey() is still available in EF Core, just like you did in EF6. The misconception is, that it is not available on EntityTypeBuilder<T>, but on ReferenceNavigationBuilder<T,K>, which is the return type from WithMany().

```<code>public class PostConfiguration : IEntityTypeConfiguration<Post>
{
    public void Configure(EntityTypeBuilder<Post> builder)
    {
        builder.HasOne(y => y.Blog)
                .WithMany(x => x.Posts)
                .HasForeignKey(x => x.BlogForeignKey);
    }
}

public class ApplicationContext :DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.ApplyConfiguration(new PostConfiguration());
    }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogForeignKey { get; set; }
    public Blog Blog { get; set; }
}
</code>```

Body:
I am attempting to use the EntityConfiguration interface which is new in EF Core 2.0.

Addendum Probably helpful to see the Message class

public class Message
{
    public int MessageId { get; set; }

    [Required]
    public string MessageForUserId { get; set; }
    public virtual ApplicationUser MessageForUser { get; set; }

    [Required]
    public string MessageFromUserId { get; set; }

    public virtual ApplicationUser MessageFromUser { get; set; }

    [Required]
    public string MessageContent { get; set; }

    public bool MessageRead { get; set; }

    [Required]
    public DateTime MessageCreatedOn { get; set; }

    public DateTime? MessageReadOn { get; set; }
}

and the AppUser class

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Gender Gender { get; set; }
    public SubscriptionLevel SubscriptionLevel { get; set; }
    public NotificationType NotificationType { get; set; }
    public string AvatarUrl { get; set; }
    public ICollection<Message> UserMessages { get; set; }
    public ICollection<Message> SentMessages { get; set; }
    public ICollection<IdentityUserClaim<string>> Claims { get;  set; }
}

Here is how the entity is defined in my OnModelCreating method.

builder.Entity<Message>()
            .HasOne(x => x.MessageForUser)
            .WithMany(x => x.UserMessages)
            .HasForeignKey(x => x.MessageForUserId)
            .OnDelete(DeleteBehavior.Restrict);

builder.Entity<Message>()
            .HasOne(x => x.MessageFromUser)
            .WithMany(x => x.SentMessages)
            .HasForeignKey(x => x.MessageFromUserId)
            .OnDelete(DeleteBehavior.Cascade);

My IEntityTypeConfiguration

public class AppUserConfig : IEntityTypeConfiguration<ApplicationUser>
{
    public void Configure(EntityTypeBuilder<ApplicationUser> builder)
    {
        builder.Property(u => u.FirstName).HasMaxLength(31);
        builder.Property(u => u.FirstName).IsRequired();

        builder.Property(u => u.LastName).HasMaxLength(55);
        builder.Property(u => u.LastName).IsRequired();

        builder.Property(u => u.DateOfBirth).HasColumnType("datetime");
        builder.Property(u => u.DateOfBirth).IsRequired();

        builder.Property(u => u.Gender).IsRequired();
    }
}

The EF 6 way had a HasForeignKey method off builder which is no longer available and I cant seem to find any way to add them.

Here is how the migration built the table from my OnModelCreating method. I'd like to put most of these items in my configuration class.

migrationBuilder.CreateIndex(
            name: "IX_Messages_MessageForUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageForUserId");

migrationBuilder.CreateIndex(
            name: "IX_Messages_MessageFromUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageFromUserId");

migrationBuilder.AddForeignKey(
            name: "FK_Messages_AspNetUsers_MessageForUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageForUserId",
            principalSchema: "AppContext",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Restrict);

migrationBuilder.AddForeignKey(
            name: "FK_Messages_AspNetUsers_MessageFromUserId",
            schema: "AppContext",
            table: "Messages",
            column: "MessageFromUserId",
            principalSchema: "AppContext",
            principalTable: "AspNetUsers",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

There still is a HasIndex method, but I'm not sure how to duplicate what the migration is producing in the lambda expression for HasIndex.

Body:
HasForeignKey() is still available in EF Core, just like you did in EF6. The misconception is, that it is not available on EntityTypeBuilder<T>, but on ReferenceNavigationBuilder<T,K>, which is the return type from WithMany().

public class PostConfiguration : IEntityTypeConfiguration<Post>
{
    public void Configure(EntityTypeBuilder<Post> builder)
    {
        builder.HasOne(y => y.Blog)
                .WithMany(x => x.Posts)
                .HasForeignKey(x => x.BlogForeignKey);
    }
}

public class ApplicationContext :DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.ApplyConfiguration(new PostConfiguration());
    }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogForeignKey { get; set; }
    public Blog Blog { get; set; }
}


来源: stackexchange

问:
Change a value in a column in several data frames with different columns length in R
I am trying to change the name of a country in several data frames at the same time, but each data frame has different column lengths. For example:

```<code>df1 <- data.frame(country = c('Austria','UK'), year = c(2015,2012), data = c(10,12))
df2 <- data.frame(country = c('Austria','UK'), year = c(2015,2012), prop = c(0.5,0.2), gender = c('male','female'))
df3 <- data.frame(country = c('Austria','UK'), year = c(2015,2012))
</code>```

I need to change "UK" to "United Kingdom" in all the data frames. I am doing the following:

```<code>aList <- list(df1,df2,df3)

lapply(aList, function(df){
  df$new_country <- df%>% mutate (new_country = ifelse(df$country == 'UK', 'United Kingdom', df$country))
})
</code>```

But I do not get the changes. I see this in the console:

```<code>[[1]]
  country year data    new_country
1 Austria 2015   10              1
2      UK 2012   12 United Kingdom

[[2]]
  country year prop gender    new_country
1 Austria 2015  0.5   male              1
2      UK 2012  0.2 female United Kingdom

[[3]]
  country year    new_country
1 Austria 2015              1
2      UK 2012 United Kingdom
</code>```

But I do not see the values in the list when I open the list, and the value of Austria is 1 and it should be Austria. Can anyone help?

答:
data.table solution:</p>

```<code>library(data.table)
df1 <- data.table(country = c('Austria','UK'), year = c(2015,2012), data = c(10,12))
df2 <- data.table(country = c('Austria','UK'), year = c(2015,2012), prop = c(0.5,0.2), gender = c('male','female'))
df3 <- data.table(country = c('Austria','UK'), year = c(2015,2012))

aList <- list(df1,df2,df3)

bList <- lapply(aList, function(x) x[,lapply(.SD, function(x) gsub("UK", "United Kingdom", x))])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to change the name of a country in several data frames at the same time, but each data frame has different column lengths. For example:

df1 <- data.frame(country = c('Austria','UK'), year = c(2015,2012), data = c(10,12))
df2 <- data.frame(country = c('Austria','UK'), year = c(2015,2012), prop = c(0.5,0.2), gender = c('male','female'))
df3 <- data.frame(country = c('Austria','UK'), year = c(2015,2012))

I need to change "UK" to "United Kingdom" in all the data frames. I am doing the following:

aList <- list(df1,df2,df3)

lapply(aList, function(df){
  df$new_country <- df%>% mutate (new_country = ifelse(df$country == 'UK', 'United Kingdom', df$country))
})

But I do not get the changes. I see this in the console:

[[1]]
  country year data    new_country
1 Austria 2015   10              1
2      UK 2012   12 United Kingdom

[[2]]
  country year prop gender    new_country
1 Austria 2015  0.5   male              1
2      UK 2012  0.2 female United Kingdom

[[3]]
  country year    new_country
1 Austria 2015              1
2      UK 2012 United Kingdom

But I do not see the values in the list when I open the list, and the value of Austria is 1 and it should be Austria. Can anyone help?

Body:
data.table solution:

library(data.table)
df1 <- data.table(country = c('Austria','UK'), year = c(2015,2012), data = c(10,12))
df2 <- data.table(country = c('Austria','UK'), year = c(2015,2012), prop = c(0.5,0.2), gender = c('male','female'))
df3 <- data.table(country = c('Austria','UK'), year = c(2015,2012))

aList <- list(df1,df2,df3)

bList <- lapply(aList, function(x) x[,lapply(.SD, function(x) gsub("UK", "United Kingdom", x))])


问:
"Cannot read property 'offsetWidth' of undefined or null reference" after commenting out div
I'm getting the error "Cannot read property 'offsetWidth' of undefined or null reference" in my website since I commented out 2 divs in a bootstrap carousel. This carousel was developed by someone else who is unavailable to me. I don't see how commenting out a div would cause this error. It does not occur when the divs are left in.

```<code><!-- Carousel -->
<div id="homepage-slider">
  <div id="feature-wrap">
      <div class="iosSlider">
          <div     class="slider">
            {2}
            <div class="item" id="2">
                <a href="{0}/{1}/products/test1"><img     src="{0}/Content/images/home/index/myPic.jpg" style="width: 100%;" /></a>
            </div>
            <div class="item" id="3">
                <a href="{0}/{1}/products/test2"><img src="{0}/Content/images/home/index/myPic2.jpg" style="width: 100%;" /></a>
            </div>
            <div class="item" id="4">
                <a href="https://myPage.myCompany.com/"     target="_blank"><img src="{0}/Content/images/home/index/myPic3.jpg"     style="width: 100%;" /></a>
            </div>  <!-- Commenting out this div         -->
          </div>
          <div class="iosSliderButtons">
              {3}
              <div class="button"></div>
              <div class="button"></div>
              <div class="button"></div> <!-- Commenting out this div -->
          </div>
      </div>
      <div id="nextSlide"></div>
      <div id="previousSlide"></div>
    </div>
</div>
</code>```

This HTML is called from another file, called Index.cshtml like so:

```<code> <div id="view-home">
 @Html.Raw(Resources.HtmlContent.HomePageContent.FormatWith(host,

 currentWebAlias, myHTML1, myHTML2))
 </div>
</code>```

myHTML1 & myHTML2 are set earlier in the file, and this HTML is then used to populate the placeholders (marked {2} and {3}) in the page above.

I'm also getting a similar error, except it refers to 'unobtrusive'.
This all works fine when the divs are not commented out, but I don't see how removing a div would cause these errors to occur all of a sudden.

Any help greatly appreciated!

答:
Commenting out a div can cause an error since that element is referenced in carrousel plugin. To be precise since javascript cannot find that element which is now undefined, accessing elements property of undefined causes this error.

Whoever wrote this plugin did not have in mind for you to play around with its structure, since he made it error prone.

This property is most likely used in calculation for carrousel plugin slide effects, you can check more about it here https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

Body:
I'm getting the error "Cannot read property 'offsetWidth' of undefined or null reference" in my website since I commented out 2 divs in a bootstrap carousel. This carousel was developed by someone else who is unavailable to me. I don't see how commenting out a div would cause this error. It does not occur when the divs are left in.

            {2}

              {3}

This HTML is called from another file, called Index.cshtml like so:

 @Html.Raw(Resources.HtmlContent.HomePageContent.FormatWith(host,

 currentWebAlias, myHTML1, myHTML2))

myHTML1 & myHTML2 are set earlier in the file, and this HTML is then used to populate the placeholders (marked {2} and {3}) in the page above.

I'm also getting a similar error, except it refers to 'unobtrusive'.
This all works fine when the divs are not commented out, but I don't see how removing a div would cause these errors to occur all of a sudden.

Any help greatly appreciated!


问:
VBA Create a new workbook with a button click
I'm trying to create a macro that creates a new workbook when pressing a button on the already existing workbook. I would like to save the newly created workbook in the same folder as the exiting workbook and give it a new name? Could somebody help me please?

Thank you very much in advance!

That's the code I have until now but it doesn't work as I want it (object not found and doesn't save it in the same folder):

```<code>Sub CreateNewWorkBook()

'Adding New Workbook
Workbooks.Add
'Saving the Workbook
 ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\Test.xls"
 ActiveWorkbook.Close savechanges:=False

End Sub
</code>```

答:
Try the following code from:

https://msdn.microsoft.com/en-us/library/office/aa221273(v=office.11).aspx

```<code>Sub AddNew()
Set NewBook = Workbooks.Add
    With NewBook
        .Title = "All Sales" 'You can modify this value.
        .Subject = "Sales" 'You can modify this value.
        .SaveAs Filename:="Allsales.xls"
    End With
End Sub
</code>```

To get the path of the file there is already a question about that:

How to get the path of current worksheet in VBA?

Body:
I'm trying to create a macro that creates a new workbook when pressing a button on the already existing workbook. I would like to save the newly created workbook in the same folder as the exiting workbook and give it a new name? Could somebody help me please?

Thank you very much in advance!

That's the code I have until now but it doesn't work as I want it (object not found and doesn't save it in the same folder):

Sub CreateNewWorkBook()

'Adding New Workbook
Workbooks.Add
'Saving the Workbook
 ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\Test.xls"
 ActiveWorkbook.Close savechanges:=False

End Sub

Body:
Try the following code from:

https://msdn.microsoft.com/en-us/library/office/aa221273(v=office.11).aspx

Sub AddNew()
Set NewBook = Workbooks.Add
    With NewBook
        .Title = "All Sales" 'You can modify this value.
        .Subject = "Sales" 'You can modify this value.
        .SaveAs Filename:="Allsales.xls"
    End With
End Sub

To get the path of the file there is already a question about that:

How to get the path of current worksheet in VBA?


问:
How to upgrade Appium 1.5.3 to Appium 1.8.1
I have tried with command:

```<code>npm -install -g appium@1.6
</code>```

but when I restart Appium, it is still in 1.5.3 version.

答:
If you have an old version of Appium server than you can update it without uninstalling it by executing following command in terminal or command prompt

```<code>npm -g update appium
</code>```

This will update your Appium version to the latest version.

In case you want to update to a specific version than execute the following command:

```<code>npm update -g appium@1.6
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have tried with command:

npm -install -g appium@1.6

but when I restart Appium, it is still in 1.5.3 version.

Body:
If you have an old version of Appium server than you can update it without uninstalling it by executing following command in terminal or command prompt

npm -g update appium

This will update your Appium version to the latest version.

In case you want to update to a specific version than execute the following command:

npm update -g appium@1.6


问:
Apache and backslashes in mod_rewrite
I want to process all incoming requests through a single script (index.php in web-root).

So, the following is what currently happens: http://localhost/foo/bar/baz

Is routed by Apache (through .htaccess) to: http://localhost/index.php?url=foo/bar/baz

This works well, however, in Firefox I am able to do this: http://localhost/foo\ -> notice the backslash.

And Apache, instead of doing: /index.php?url=foo\

Emits a generic error page saying:

Object not found! The requested URL
  was not found on this server. If you
  entered the URL manually please check
  your spelling and try again.

If you think this is a server error,
  please contact the webmaster.

Error 404 localhost Apache/2.2.14
  (Win32) DAV/2 mod_ssl/2.2.14
  OpenSSL/0.9.8l mod_autoindex_color
  PHP/5.3.1 mod_apreq2-20090110/2.7.1
  mod_perl/2.0.4 Perl/v5.10.1

Directly going to: http://localhost/index.php?url=foo\ works without issues, however.

All the sites that I've seen on the internet seem to be able to handle backslashes gracefully (e.g., http://stackoverflow.com/tags/php\\\\\).

I consider this behavior a bug and I want to force Apache to forward backslashes correctly.
Here's my .htaccess file in its entirety:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [L]
</code>```

How can I make this work properly?

Edit: I just tried this on my webhost and this is handled properly by them. Makes me think it's some setting in httpd.conf.

答: Probably need AcceptPathInfo off to not get those tolerated as forward slashes.</p>

ContentLicense: CC BY-SA 2.5

Title: Apache and backslashes in mod_rewrite

Body:
I want to process all incoming requests through a single script (index.php in web-root).

So, the following is what currently happens: http://localhost/foo/bar/baz

Is routed by Apache (through .htaccess) to: http://localhost/index.php?url=foo/bar/baz

This works well, however, in Firefox I am able to do this: http://localhost/foo\ -> notice the backslash.

And Apache, instead of doing: /index.php?url=foo\

Emits a generic error page saying:

Object not found! The requested URL
  was not found on this server. If you
  entered the URL manually please check
  your spelling and try again.

If you think this is a server error,
  please contact the webmaster.

Error 404 localhost Apache/2.2.14
  (Win32) DAV/2 mod_ssl/2.2.14
  OpenSSL/0.9.8l mod_autoindex_color
  PHP/5.3.1 mod_apreq2-20090110/2.7.1
  mod_perl/2.0.4 Perl/v5.10.1

Directly going to: http://localhost/index.php?url=foo\ works without issues, however.

All the sites that I've seen on the internet seem to be able to handle backslashes gracefully (e.g., http://stackoverflow.com/tags/php\\\\\).

I consider this behavior a bug and I want to force Apache to forward backslashes correctly.
Here's my .htaccess file in its entirety:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [L]

How can I make this work properly?

Edit: I just tried this on my webhost and this is handled properly by them. Makes me think it's some setting in httpd.conf.


问:
Django image attribute has no file associated with it REST API
I have a model Employee with an ImageField, and I return REST API response of the model but it shows this error

```<code>The 'face_image' attribute has no file associated with it.
</code>```

My API generates a response this way:
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

```<code>@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response(data, status=status.HTTP_200_OK)
</code>```

The following is the model:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

```<code>class Employee(models.Model):
    ...
    face_image = models.ImageField(upload_to='face_image/', blank=True)

    def face_image_url(self):
        if self.face_image and hasattr(self.face_image, 'url'):
            return self.face_image.url

    def as_dict(self):
        return {"id":self.id,
                ...
                "face_image":self.face_image.url, <-- causes no file associated
                ...}
</code>```

How do I solve this REST response handling imagefield without file ? I tried to follow some ways in here Django The 'image' attribute has no file associated with it but I cant accomplish with the helper function.

If I remove the imagefield, it will generate a response this way https://imgur.com/a/JzQrD. But I want the imagefield to be in the structure, how to handle in this does not exist file situation

答:
Here:

"face_image":self.face_image.url, <-- causes no file associated

You don't actually use your face_image_url method.

It should be:

```<code>`"face_image":self.face_image_url()
</code>```

As I said above, I think it's really a bad idea to handle the serialization of your model like you did. I strongly advise you to take a look at the serializers.

Body:
I have a model Employee with an ImageField, and I return REST API response of the model but it shows this error

The 'face_image' attribute has no file associated with it.

My API generates a response this way:
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['GET'])
def get_employee(request):
    data = [emp.as_dict() for emp in Employee.objects.all()]
    return Response(data, status=status.HTTP_200_OK)

The following is the model:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    ...
    face_image = models.ImageField(upload_to='face_image/', blank=True)

    def face_image_url(self):
        if self.face_image and hasattr(self.face_image, 'url'):
            return self.face_image.url

    def as_dict(self):
        return {"id":self.id,
                ...
                "face_image":self.face_image.url, <-- causes no file associated
                ...}

How do I solve this REST response handling imagefield without file ? I tried to follow some ways in here Django The 'image' attribute has no file associated with it but I cant accomplish with the helper function.

If I remove the imagefield, it will generate a response this way https://imgur.com/a/JzQrD. But I want the imagefield to be in the structure, how to handle in this does not exist file situation

Body:
Here:

"face_image":self.face_image.url, <-- causes no file associated

You don't actually use your face_image_url method.

It should be:

`"face_image":self.face_image_url()

As I said above, I think it's really a bad idea to handle the serialization of your model like you did. I strongly advise you to take a look at the serializers.


问:
Mark variable as not NULL after BOOST_REQUIRE in PVS-Studio
I'm using PVS-Studio to analyze my Testcode. There are often constructs of the form

```<code>const noAnimal* animal = dynamic_cast<noAnimal*>(...);
BOOST_REQUIRE(animal);
BOOST_REQUIRE_EQUAL(animal->GetSpecies(), ...);
</code>```

However I still get a warning V522 There might be dereferencing of a potential null pointer 'animal' for the last line.

I know it is possible, to mark functions as "not returning NULL" but is it also possible to mark a function as a valid NULL check or make PVS-Studio somehow else aware that animal can't be NULL after BOOST_REQUIRE(animal);?

This also happens if the pointer is checked via any assert flavour first.

答:
Thank you for the interesting example. We'll think, what we can do with the BOOST_REQUIRE macro.

At the moment, I can advise you the following solution:

Somewhere after

```<code>#include <boost/test/included/unit_test.hpp>
</code>```

you can write:

```<code>#ifdef PVS_STUDIO
  #undef BOOST_REQUIRE
  #define BOOST_REQUIRE(expr) do { if (!(expr)) throw "PVS-Studio"; } while (0)
#endif
</code>```

This way, you will give a hint to the analyzer, that the false condition causes the abort of the control flow.
It is not the most beautiful solution, but I think it was worth telling you about.

Body:
I'm using PVS-Studio to analyze my Testcode. There are often constructs of the form

const noAnimal* animal = dynamic_cast<noAnimal*>(...);
BOOST_REQUIRE(animal);
BOOST_REQUIRE_EQUAL(animal->GetSpecies(), ...);

However I still get a warning V522 There might be dereferencing of a potential null pointer 'animal' for the last line.

I know it is possible, to mark functions as "not returning NULL" but is it also possible to mark a function as a valid NULL check or make PVS-Studio somehow else aware that animal can't be NULL after BOOST_REQUIRE(animal);?

This also happens if the pointer is checked via any assert flavour first.

Body:
Thank you for the interesting example. We'll think, what we can do with the BOOST_REQUIRE macro.

At the moment, I can advise you the following solution:

Somewhere after

#include <boost/test/included/unit_test.hpp>

you can write:

#ifdef PVS_STUDIO
  #undef BOOST_REQUIRE
  #define BOOST_REQUIRE(expr) do { if (!(expr)) throw "PVS-Studio"; } while (0)
#endif

This way, you will give a hint to the analyzer, that the false condition causes the abort of the control flow.
It is not the most beautiful solution, but I think it was worth telling you about.


问:
Retrieve Non-Duplicate Data With Criteria
I wish to retrieve non-duplicate data with criteria based on 2 tables in SQL Server database.

Table Subject

```
ID       NAME                                       COURSE
-------  -----------------------------------------  ---------------------------------
SUB1234  SOFTWARE QUALITY AND PROCESS MANAGEMENT    AUPAS AMERICAN UNIVERSITY PROGRAM
SUB2234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 1  AUPAS AMERICAN UNIVERSITY PROGRAM
SUB3234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 2  AUPAS AMERICAN UNIVERSITY PROGRAM
```

Table Result

```<code>ID       SUBJECT  RESULT
-------  -------  ------
STU0001  SUB1234  NULL
</code>```

Desired Output:

Get SUB2234 and SUB3234 from table Subject when ID = STU0001 and Course = AUPAS AMERICAN UNIVERSITY PROGRAM.

Using query below, I only able to retrieve non-duplicate data.

```<code>SELECT SUB.ID, SUB.NAME
FROM SUBJECT SUB LEFT JOIN
     RESULT RES
     ON RES.SUBJECT = SUB.ID
WHERE RES.SUBJECT IS NULL;
</code>```

答:
This query gets the desired result.

```<code>SELECT SUB.ID, SUB.NAME
  FROM SUBJECT SUB
 WHERE NOT EXISTS (SELECT 1
                     FROM RESULT RES
                    WHERE RES.ID = 'STU0001'
                      AND RES.SUBJECT = SUB.ID)
   AND SUB.COURSE = 'AUPAS AMERICAN UNIVERSITY PROGRAM';
</code>```

Basically the query gets all the subjects where course = 'AUPAS AMERICAN UNIVERSITY PROGRAM' and excludes the ones the students is already associated with.

Hope this helps!

Body:
I wish to retrieve non-duplicate data with criteria based on 2 tables in SQL Server database.

Table Subject

ID       NAME                                       COURSE
-------  -----------------------------------------  ---------------------------------
SUB1234  SOFTWARE QUALITY AND PROCESS MANAGEMENT    AUPAS AMERICAN UNIVERSITY PROGRAM
SUB2234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 1  AUPAS AMERICAN UNIVERSITY PROGRAM
SUB3234  SOFTWARE QUALITY AND PROCESS MANAGEMENT 2  AUPAS AMERICAN UNIVERSITY PROGRAM

Table Result

ID       SUBJECT  RESULT
-------  -------  ------
STU0001  SUB1234  NULL

Desired Output:

Get SUB2234 and SUB3234 from table Subject when ID = STU0001 and Course = AUPAS AMERICAN UNIVERSITY PROGRAM.

Using query below, I only able to retrieve non-duplicate data.

SELECT SUB.ID, SUB.NAME
FROM SUBJECT SUB LEFT JOIN
     RESULT RES
     ON RES.SUBJECT = SUB.ID
WHERE RES.SUBJECT IS NULL;

Body:
This query gets the desired result.

SELECT SUB.ID, SUB.NAME
  FROM SUBJECT SUB
 WHERE NOT EXISTS (SELECT 1
                     FROM RESULT RES
                    WHERE RES.ID = 'STU0001'
                      AND RES.SUBJECT = SUB.ID)
   AND SUB.COURSE = 'AUPAS AMERICAN UNIVERSITY PROGRAM';

Basically the query gets all the subjects where course = 'AUPAS AMERICAN UNIVERSITY PROGRAM' and excludes the ones the students is already associated with.

Hope this helps!


问:
optimise code into linq expression
I have an observable collection I want to remove an element from.  I have tried using the linq .Where syntax but i am getting stuck with the casting.

```<code>public class Atc
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string ParentDescriptions { get; set; }
}
</code>```

i have defined the observable collection of medicines,

```<code>public ObservableCollection<Atc> MedicinesObservableCollection
</code>```

and i have a method to filter out the item from the collection that works:

```<code>private void RemoveMedicineListItem(string code)
{
    var filteredCollection = new ObservableCollection<Atc>();
    foreach (var item in MedicinesObservableCollection)
    {
        if (item.Code != code)
        {
            filteredCollection.Add(item);
        }
    }
    MedicinesObservableCollection = filteredCollection;
}
</code>```

I have tried:

```<code>(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);
</code>```

but this gets a runtime exception
System.InvalidCastException: 'Unable to cast object of type 'WhereEnumerableIterator1[Atc]' to type 'System.Collections.ObjectModel.ObservableCollection1[Atc]'.'

i get this is something to do with the linq enumerables but i am out of my depth.

答:
All the answers are correct but when using ObservableCollection it would be better to do a remove on the same object rather then creating a new list.

```<code>MedicinesObservableCollection.Remove(MedicinesObservableCollection.FirstOrDefault(x => x.Code == code));
</code>```

This is because recreating the collection might force all the items in the list to be re-rendered and this way only one item will be removed from the same collection.

Title: optimise code into linq expression

Body:
I have an observable collection I want to remove an element from.  I have tried using the linq .Where syntax but i am getting stuck with the casting.

public class Atc
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string ParentDescriptions { get; set; }
}

i have defined the observable collection of medicines,

public ObservableCollection<Atc> MedicinesObservableCollection

and i have a method to filter out the item from the collection that works:

private void RemoveMedicineListItem(string code)
{
    var filteredCollection = new ObservableCollection<Atc>();
    foreach (var item in MedicinesObservableCollection)
    {
        if (item.Code != code)
        {
            filteredCollection.Add(item);
        }
    }
    MedicinesObservableCollection = filteredCollection;
}

I have tried:

(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);

but this gets a runtime exception
System.InvalidCastException: 'Unable to cast object of type 'WhereEnumerableIterator1[Atc]' to type 'System.Collections.ObjectModel.ObservableCollection1[Atc]'.'

i get this is something to do with the linq enumerables but i am out of my depth.

Body:
All the answers are correct but when using ObservableCollection it would be better to do a remove on the same object rather then creating a new list.

MedicinesObservableCollection.Remove(MedicinesObservableCollection.FirstOrDefault(x => x.Code == code));

This is because recreating the collection might force all the items in the list to be re-rendered and this way only one item will be removed from the same collection.


问:
DOS Batch menu goes to Error level 1 when pressing Enter key
I have made a DOS Batch menu for my BBS and Echomail Hub.
The original version did not contain any Error level lines and when the user would press enter the batch would crash to prompt . I added the Error level Lines to Each GOTO group and now When the user presses enter it goes to the Error screen where pressing enter again takes the user back to the main menu instead of crashing to prompt.
There has got to be a cleaner way to "loop" back to the primary menu when the user presses enter with no other command other than displaying the Error screen. I researched here and found a "Quotation" fix for other batch menus but that did not work at all and rendered the bach non functional .
Here is a copy of my batch .
Primary concern : How to loop bach to menu when pressing enter with no other command.
Thanks </p>

```<code>ECHO OFF
:menu
CLS
Type c:\MYSTIC\DOSMENU.ANS
SET /P M=Choose 1-22 =(
IF %M%==1 GOTO exit
IF %M%==2 GOTO nodelists
IF %M%==3 GOTO purge
IF %M%==4 GOTO mailin
IF %M%==5 GOTO back
IF %M%==6 GOTO Netrunner
IF %M%==7 GOTO kill
IF %M%==8 GOTO TOP
IF %M%==9 GOTO fidopoll
IF %M%==10 GOTO BOX
IF %M%==11 GOTO fig
IF %M%==12 GOTO CMD
IF %M%==13 GOTO MIS404
IF %M%==14 GOTO MIS2404
IF %M%==15 GOTO MIS606
IF %M%==16 GOTO MIS2606
IF %M%==17 GOTO MRC
IF %M%==18 GOTO DOORPARTY
IF %M%==19 GOTO FORCEHUB
IF %M%==20 GOTO MISHUB
IF %M%==21 GOTO MIS2HUB
IF %M%==22 GOTO HUBCONFIG
IF %M%==  GOTO MENU
:exit
ECHO OFF
exit
IF ERRORLEVEL 1 GOTO Error

;Start of BBS Commands
;Import All Node Listings
:nodelists
c:
cd\mystic
start mutil nodelists
IF ERRORLEVEL 1 GOTO Error
goto menu

;Purge all Old EchoMail
:purge
c:
cd\mystic
start mutil purge
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Process mailin Mutil
:mailin
c:
cd\mystic
start mutil mailin
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Backup BBS and Hub
:back
c:
cd\mystic
start mysticbu
IF ERRORLEVEL 1 GOTO Error
goto menu

;Load Netrunner
:netrunner
c:
cd\nr20b18w
start netrunner.exe
IF ERRORLEVEL 1 GOTO Error
goto menu

;Kill all Busy nodes
:kill
cd\
c:
cd\mystic
start fidopoll killbusy
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Gernerate Top Callers Report
:TOP
c:
CD\Mystic
START fidopoll killbusy
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Forced Fidopoll of all Nodes on the BBS
:Fidopoll
c:
cd\mystic
start fidopoll forced
IF ERRORLEVEL 1 GOTO Error
goto menu

;Load DOSBox
:BOX
c:
Cd\PROGRAM FILES (x86)\DOSBOX-0.74\
start DOSBOX
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start BBS Config Program
:fig
c:
cd\mystic
START mystic -cfg
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Goto CMD/Prompt
:CMD
c:
CD\
START CMD
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start standard mystic internet server for the BBS
:MIS404
c:
CD\MYSTIC
start mystickeep.bat
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start Mystic internet server II BBS
:MIS2404
c:
CD\MYSTIC
start MIS2 SERVER
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start Standard MIS for the file server
:MIS606
c:
CD\mysticfs
START MIS
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start MIS II for the file Server
:MIS2606
c:
CD\MysticFS
START MIS2 SERVER
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Load Mystic Relay Chat
:MRC
c:
CD\MYSTIC
START MRC2
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Load DoorParty Service
:DOORPARTY
C:
CD\"Program Files (x86)\DoorParty Connector"
START doorparty-connector.exe
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start of Hub Commands

;Load FSXnet Config
:HUBCONFIG
D:
CD\MYSTIC
start MYSTIC -CFG
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Fidopoll Force FSXNet Hub
:FORCEHUB
D:\
CD\MYSTIC
START FIDOPOLL FORCED
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Load Standard MIS for FSXHub
:MISHUB
D:
CD\MYSTIC
start mystickeep.bat
IF ERRORLEVEL 1 GOTO Error
goto menu

;Load MIS II for FSXHub
:MIS2HUB
D:\
CD\MYSTIC
start MIS2 SERVER
IF ERRORLEVEL 1 GOTO Error
goto menu

:Error
ECHO OFF
Type c:\MYSTIC\ERROR.ANS
ECHO off
PAUSE
GOTO Menu

;End DosMenu script
</code>```

<p>`</p>

答:
I am not going to delve into your code at all, so I will give a much shorter version here.

Firstly, see that I used setlocal enableddelayedexpansion and not going to explain it all as there is lots of info if you run from cmdline setlocal /?
Also note I added the no input tag. This means if no input as been added, it will skip to that portion which ads a message why it returned to prompt.

```<code>@echo off
setlocal enabledelayedexpansion
goto MENU
:NOINPUT
cls
echo You have not typed in a valid selection.
:MENU
echo Please enter a choice:
SET /P "M=select 1 to 22"
set var=%M%
IF !var!==1 GOTO OPTION1
IF !var!==2 GOTO OPTION2
IF "!var!"==""  GOTO NOINPUT
:OPTION1
echo this is option 1
pause
exit
:OPTION2
echo this is option 2
exit
</code>```

Body:
I have made a DOS Batch menu for my BBS and Echomail Hub.
The original version did not contain any Error level lines and when the user would press enter the batch would crash to prompt . I added the Error level Lines to Each GOTO group and now When the user presses enter it goes to the Error screen where pressing enter again takes the user back to the main menu instead of crashing to prompt.
There has got to be a cleaner way to "loop" back to the primary menu when the user presses enter with no other command other than displaying the Error screen. I researched here and found a "Quotation" fix for other batch menus but that did not work at all and rendered the bach non functional .
Here is a copy of my batch .
Primary concern : How to loop bach to menu when pressing enter with no other command.
Thanks

ECHO OFF
:menu
CLS
Type c:\MYSTIC\DOSMENU.ANS
SET /P M=Choose 1-22 =(
IF %M%==1 GOTO exit
IF %M%==2 GOTO nodelists
IF %M%==3 GOTO purge
IF %M%==4 GOTO mailin
IF %M%==5 GOTO back
IF %M%==6 GOTO Netrunner
IF %M%==7 GOTO kill
IF %M%==8 GOTO TOP
IF %M%==9 GOTO fidopoll
IF %M%==10 GOTO BOX
IF %M%==11 GOTO fig
IF %M%==12 GOTO CMD
IF %M%==13 GOTO MIS404
IF %M%==14 GOTO MIS2404
IF %M%==15 GOTO MIS606
IF %M%==16 GOTO MIS2606
IF %M%==17 GOTO MRC
IF %M%==18 GOTO DOORPARTY
IF %M%==19 GOTO FORCEHUB
IF %M%==20 GOTO MISHUB
IF %M%==21 GOTO MIS2HUB
IF %M%==22 GOTO HUBCONFIG
IF %M%==  GOTO MENU
:exit
ECHO OFF
exit
IF ERRORLEVEL 1 GOTO Error

;Start of BBS Commands
;Import All Node Listings
:nodelists
c:
cd\mystic
start mutil nodelists
IF ERRORLEVEL 1 GOTO Error
goto menu

;Purge all Old EchoMail
:purge
c:
cd\mystic
start mutil purge
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Process mailin Mutil
:mailin
c:
cd\mystic
start mutil mailin
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Backup BBS and Hub
:back
c:
cd\mystic
start mysticbu
IF ERRORLEVEL 1 GOTO Error
goto menu

;Load Netrunner
:netrunner
c:
cd\nr20b18w
start netrunner.exe
IF ERRORLEVEL 1 GOTO Error
goto menu

;Kill all Busy nodes
:kill
cd\
c:
cd\mystic
start fidopoll killbusy
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Gernerate Top Callers Report
:TOP
c:
CD\Mystic
START fidopoll killbusy
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Forced Fidopoll of all Nodes on the BBS
:Fidopoll
c:
cd\mystic
start fidopoll forced
IF ERRORLEVEL 1 GOTO Error
goto menu

;Load DOSBox
:BOX
c:
Cd\PROGRAM FILES (x86)\DOSBOX-0.74\
start DOSBOX
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start BBS Config Program
:fig
c:
cd\mystic
START mystic -cfg
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Goto CMD/Prompt
:CMD
c:
CD\
START CMD
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start standard mystic internet server for the BBS
:MIS404
c:
CD\MYSTIC
start mystickeep.bat
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start Mystic internet server II BBS
:MIS2404
c:
CD\MYSTIC
start MIS2 SERVER
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start Standard MIS for the file server
:MIS606
c:
CD\mysticfs
START MIS
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start MIS II for the file Server
:MIS2606
c:
CD\MysticFS
START MIS2 SERVER
IF ERRORLEVEL 1 GOTO Error
GOTO Menu

;Load Mystic Relay Chat
:MRC
c:
CD\MYSTIC
START MRC2
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Load DoorParty Service
:DOORPARTY
C:
CD\"Program Files (x86)\DoorParty Connector"
START doorparty-connector.exe
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Start of Hub Commands

;Load FSXnet Config
:HUBCONFIG
D:
CD\MYSTIC
start MYSTIC -CFG
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Fidopoll Force FSXNet Hub
:FORCEHUB
D:\
CD\MYSTIC
START FIDOPOLL FORCED
IF ERRORLEVEL 1 GOTO Error
GOTO MENU

;Load Standard MIS for FSXHub
:MISHUB
D:
CD\MYSTIC
start mystickeep.bat
IF ERRORLEVEL 1 GOTO Error
goto menu

;Load MIS II for FSXHub
:MIS2HUB
D:\
CD\MYSTIC
start MIS2 SERVER
IF ERRORLEVEL 1 GOTO Error
goto menu

:Error
ECHO OFF
Type c:\MYSTIC\ERROR.ANS
ECHO off
PAUSE
GOTO Menu

;End DosMenu script

`

Body:
I am not going to delve into your code at all, so I will give a much shorter version here.

Firstly, see that I used setlocal enableddelayedexpansion and not going to explain it all as there is lots of info if you run from cmdline setlocal /?
Also note I added the no input tag. This means if no input as been added, it will skip to that portion which ads a message why it returned to prompt.

@echo off
setlocal enabledelayedexpansion
goto MENU
:NOINPUT
cls
echo You have not typed in a valid selection.
:MENU
echo Please enter a choice:
SET /P "M=select 1 to 22"
set var=%M%
IF !var!==1 GOTO OPTION1
IF !var!==2 GOTO OPTION2
IF "!var!"==""  GOTO NOINPUT
:OPTION1
echo this is option 1
pause
exit
:OPTION2
echo this is option 2
exit


问:
Switching places in Bootstrap navigation
as you can see in this JSFiddle I have created a responsive navigation menu using Bootstrap. However, I want to know how do I get the social icons to appear on the right side on small devices and the navigation button on the left side. I am sorry I am new to this and I Googled it but can't find a solution.

You can see an example of what I am trying to achieve here (the top black navigation menu.)

Here is the HTML code:-

```<code><nav class="navbar navbar-default navbar-static-top">
<div class="container">
    <div class="navbar-header">
        <button type="button" data-target="#navbarCollapse5" data-toggle="collapse" class="navbar-toggle">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <i class="fa fa-facebook" aria-hidden="true"></i>
        <i class="fa fa-youtube-play" aria-hidden="true"></i>
        <i class="fa fa-twitter" aria-hidden="true"></i>
        <i class="fa fa-google-plus" aria-hidden="true"></i>
        <i class="fa fa-pinterest-p" aria-hidden="true"></i>
        <i class="fa fa-instagram" aria-hidden="true"></i>
        <i class="fa fa-heart" aria-hidden="true"></i>
        <i class="fa fa-tumblr" aria-hidden="true"></i>
        <i class="fa fa-soundcloud" aria-hidden="true"></i>
        <i class="fa fa-vimeo-square" aria-hidden="true"></i>
        <i class="fa fa-linkedin" aria-hidden="true"></i>
        <i class="fa fa-rss" aria-hidden="true"></i>
    </div>
    <div id="navbarCollapse5" class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <form>
                <input type="text" name="search" placeholder="Search Text Here...">
                <button><i class="fa fa-search" aria-hidden="true"></i></button>
            </form>
        </ul>
    </div>
</div>
</code>```

答:
You can use css media queries for this.
Something like this,

```<code>@media (min-width: 500px) {
   .cls1 {
     float: left;
   }
}

@media (min-width: 501px) {
   .cls2 {
      float: right;
   }
}
</code>```

I've updated your fiddle.

Body:
as you can see in this JSFiddle I have created a responsive navigation menu using Bootstrap. However, I want to know how do I get the social icons to appear on the right side on small devices and the navigation button on the left side. I am sorry I am new to this and I Googled it but can't find a solution.

You can see an example of what I am trying to achieve here (the top black navigation menu.)

Here is the HTML code:-

        <button type="button" data-target="#navbarCollapse5" data-toggle="collapse" class="navbar-toggle">
            Toggle navigation

        </button>

            <form>
                <input type="text" name="search" placeholder="Search Text Here...">
                <button></button>
            </form>

Body:
You can use css media queries for this.
Something like this,

@media (min-width: 500px) {
   .cls1 {
     float: left;
   }
}

@media (min-width: 501px) {
   .cls2 {
      float: right;
   }
}

I've updated your fiddle.


问:
Rotating animation based on prewiously obtained positions
I need to rotate image by some fixed degree after each click on it. Im using this code:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true"
     >
    <rotate
        android:fromDegrees="0"
        android:toDegrees="-45"
        android:duration="500"

        android:toYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"/>
</set>
</code>```

Also tried this:

```<code>ObjectAnimator imageViewObjectAnimator = ObjectAnimator.ofFloat(img,
                "rotation", 0f, 45f);

        imageViewObjectAnimator.setDuration(1000);
        imageViewObjectAnimator.start();
</code>```

But every time animation starts from its initial position, ignoring positions that was obtained by prewiosly animation. So, -  how basicaly keep spining the image in one direction by 45 degrees after each click???

答:
Have you tried using a matrix to rotate an ImageView? Here's some sample code I pulled from an old app of mine:

```<code>Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX);
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);
</code>```

Just add an onTouchListener to the ImageView, define the first 2 lines outside of it and the last 2 inside the listener. Then every time you press, it will rotate by the pivot amount.

Body:
I need to rotate image by some fixed degree after each click on it. Im using this code:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:fillAfter="true"
     >
    <rotate
        android:fromDegrees="0"
        android:toDegrees="-45"
        android:duration="500"

        android:toYScale="0.0"
        android:pivotX="50%"
        android:pivotY="50%"/>
</set>

Also tried this:

ObjectAnimator imageViewObjectAnimator = ObjectAnimator.ofFloat(img,
                "rotation", 0f, 45f);

        imageViewObjectAnimator.setDuration(1000);
        imageViewObjectAnimator.start();

But every time animation starts from its initial position, ignoring positions that was obtained by prewiosly animation. So, -  how basicaly keep spining the image in one direction by 45 degrees after each click???

Body:
Have you tried using a matrix to rotate an ImageView? Here's some sample code I pulled from an old app of mine:

Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX);
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);

Just add an onTouchListener to the ImageView, define the first 2 lines outside of it and the last 2 inside the listener. Then every time you press, it will rotate by the pivot amount.


问:
R View() does not display all columns of data frame
I have been adding columns to a data frame and using View() to check that it did what I expected. I have repeated lines of code along the lines of:

```<code>x$p <- 3 * x$a
x$q <- sqrt(x$b + x$c)
View(x)
</code>```

This worked fine until the number of columns exceeded 100 (there are 47,000 rows). When I added another two columns, dim(x) shows 102 columns, names(x) shows 102 names, summary(x) shows summaries of all the expected columns. However, View(x) only displays the first 100 columns and doesn't display the last two added columns.

If I try View(x[,-(1:10)]) the most recently added columns are displayed.

I can't see any mention in the View documentation of a limit on the number of columns. Can anyone explain what is happening here?

答:
I'm not sure if this has been mentioned before but I found this interesting post from 2012:
https://support.rstudio.com/hc/en-us/community/posts/200669267-view-more-than-first-100-columns-.

This indexing allows you to at least check the other columns and if they even exist.

So just use: datafile[row-row, column-column].

Body:
I have been adding columns to a data frame and using View() to check that it did what I expected. I have repeated lines of code along the lines of:

x$p <- 3 * x$a
x$q <- sqrt(x$b + x$c)
View(x)

This worked fine until the number of columns exceeded 100 (there are 47,000 rows). When I added another two columns, dim(x) shows 102 columns, names(x) shows 102 names, summary(x) shows summaries of all the expected columns. However, View(x) only displays the first 100 columns and doesn't display the last two added columns.

If I try View(x[,-(1:10)]) the most recently added columns are displayed.

I can't see any mention in the View documentation of a limit on the number of columns. Can anyone explain what is happening here?


问:
Android Studio : display date got from another activity
In an activity, I ask my user about a date using a datepicker.
As far as I found, the best way to pass this date to a subsequent activity is to send separately yea, month and day.

In my subsequent activity, I want to display this date, but also this date+ 1 day, + 2 days and so on.

To do it, I taught I can do :

```<code>int mDay = origine.getIntExtra("mDay", 0);
int mMonth= origine.getIntExtra("mMonth", 0);
int mYear = origine.getIntExtra("mYear", 0);
calendrier = new GregorianCalendar(mYear,mMonth,mDay);
</code>```

and then put it in a string using something like

```<code>String strcal01 = sdf.format(new calendrier);
</code>```

This line don't work but it works if I replace "calendrier" by "Date()" (of course with current date and not the date get from the other activity...

What can I do to make it working ?

Thank's a lot for your help.

答:
I don't know if I'm correct by answering to my own question but, thank you Joshua.

I finally, in my "guest" activity, create a calendar named calendrier and display the values using :

```<code>calendrier = new GregorianCalendar(mYear,mMonth,mDay);

cal01=calendrier;
String strcal01 = sdf.format(cal01.getTime());
cal02=calendrier;
cal02.add(Calendar.DAY_OF_YEAR,1);
String strcal02 = sdf.format(cal02.getTime());
</code>```

I think i can be simplified because fore each date, I have 3 lines. But the most important for me now is that it works !

Body:
In an activity, I ask my user about a date using a datepicker.
As far as I found, the best way to pass this date to a subsequent activity is to send separately yea, month and day.

In my subsequent activity, I want to display this date, but also this date+ 1 day, + 2 days and so on.

To do it, I taught I can do :

int mDay = origine.getIntExtra("mDay", 0);
int mMonth= origine.getIntExtra("mMonth", 0);
int mYear = origine.getIntExtra("mYear", 0);
calendrier = new GregorianCalendar(mYear,mMonth,mDay);

and then put it in a string using something like

String strcal01 = sdf.format(new calendrier);

This line don't work but it works if I replace "calendrier" by "Date()" (of course with current date and not the date get from the other activity...

What can I do to make it working ?

Thank's a lot for your help.

Body:
I don't know if I'm correct by answering to my own question but, thank you Joshua.

I finally, in my "guest" activity, create a calendar named calendrier and display the values using :

calendrier = new GregorianCalendar(mYear,mMonth,mDay);

cal01=calendrier;
String strcal01 = sdf.format(cal01.getTime());
cal02=calendrier;
cal02.add(Calendar.DAY_OF_YEAR,1);
String strcal02 = sdf.format(cal02.getTime());

I think i can be simplified because fore each date, I have 3 lines. But the most important for me now is that it works !


问:
Wordpress addon unable to fetch RSS feed from Joomla website
I am developing a new website with Wordpress (4.8.1). I've installed the WP RSS Aggregator addon (4.11.2) to get RSS feed from a previously existing website on Joomla (2.5.17).
The Wordpress installation is on a GNU/Linux Debian Stretch (9.1) OS, served in https by an Apache (2.4.25) server. Joomla is on Squeeze (6.0.10) and Apache (2.2.16) ; the website is served in https but it seems it doesn't work on the RSS feeds (the URL is in https, but the browser tells the connection is not secured).
Here is a snippet of the Apache configuration :

```<code><VirtualHost *:80>
        ServerName intranet.cdg44.fr
        ServerAlias i2.cdg44.fr
        Redirect permanent / https://intranet.cdg44.fr/
</VirtualHost>

<VirtualHost *:443>
        ServerName intranet.cdg44.fr
        SSLEngine On
        SSLCertificateFile /etc/ssl/certs/cdg44.pem
        SSLCertificateKeyFile /etc/ssl/private/ca.key
        <Directory />
                Options FollowSymLinks
                AllowOverride None
                AuthType Kerberos
                AuthName "Kerberos Login"
                KrbMethodNegotiate On
                KrbMethodK5Passwd On
                KrbAuthRealms CDG44.FR
                Krb5KeyTab /etc/krb5.keytab
                require valid-user
        </Directory>
</VirtualHost>
</code>```

(For those two websites, I use authentication with Negociate).

Th WP RSS Aggregator addon tells me :

```<code>Failed to fetch the RSS feed. Error: cURL error 60: SSL certificate problem: unable to get local issuer certificate
</code>```

What can I do to solve my issue ?

EDIT :

Trying to get programmatically the RSS feed :

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
file_get_contents("https://address.website.com/index.php?option=com_content&view=category&id=27&Itemid=241&format=feed&type=rss");
</code>```

Gives this error (by xdebug) :

```<code>Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /home/pyledevehat/workspace/intranet/wp-content/themes/themename/functions.php on line 197
</code>```

My php.ini is well configured :

```<code>allow_url_fopen = On
</code>```

答:
I solved my problem with this code :</p>

```<code>$url = "https://address.website.com/index.php?option=com_content&view=category&id=27&Itemid=241&format=feed&type=rss";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$content = curl_exec($ch);
curl_close($ch);
</code>```

Body:
I am developing a new website with Wordpress (4.8.1). I've installed the WP RSS Aggregator addon (4.11.2) to get RSS feed from a previously existing website on Joomla (2.5.17).
The Wordpress installation is on a GNU/Linux Debian Stretch (9.1) OS, served in https by an Apache (2.4.25) server. Joomla is on Squeeze (6.0.10) and Apache (2.2.16) ; the website is served in https but it seems it doesn't work on the RSS feeds (the URL is in https, but the browser tells the connection is not secured).
Here is a snippet of the Apache configuration :

<VirtualHost *:80>
        ServerName intranet.cdg44.fr
        ServerAlias i2.cdg44.fr
        Redirect permanent / https://intranet.cdg44.fr/
</VirtualHost>

<VirtualHost *:443>
        ServerName intranet.cdg44.fr
        SSLEngine On
        SSLCertificateFile /etc/ssl/certs/cdg44.pem
        SSLCertificateKeyFile /etc/ssl/private/ca.key
        <Directory />
                Options FollowSymLinks
                AllowOverride None
                AuthType Kerberos
                AuthName "Kerberos Login"
                KrbMethodNegotiate On
                KrbMethodK5Passwd On
                KrbAuthRealms CDG44.FR
                Krb5KeyTab /etc/krb5.keytab
                require valid-user
        </Directory>
</VirtualHost>

(For those two websites, I use authentication with Negociate).

Th WP RSS Aggregator addon tells me :

Failed to fetch the RSS feed. Error: cURL error 60: SSL certificate problem: unable to get local issuer certificate

What can I do to solve my issue ?

EDIT :

Trying to get programmatically the RSS feed :

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
file_get_contents("https://address.website.com/index.php?option=com_content&view=category&id=27&Itemid=241&format=feed&type=rss");

Gives this error (by xdebug) :

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /home/pyledevehat/workspace/intranet/wp-content/themes/themename/functions.php on line 197

My php.ini is well configured :

allow_url_fopen = On

Body:
I solved my problem with this code :

$url = "https://address.website.com/index.php?option=com_content&view=category&id=27&Itemid=241&format=feed&type=rss";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$content = curl_exec($ch);
curl_close($ch);


问:
TypeError: data.filter is not a function
I am trying to filter an array of JSON objects, which I get from an API call on my proxy. I am using a Node.js web framework Express to make the API call.

API returns the following:

```<code>{
  data: [
    {
      type: "aaa",
      name: "Cycle",
      id: "c949up9c",
      category: ["A","B"]
    },
    {
      type: "bbb",
      name: "mobile",
      id: "c2rt4Jtu",
      category: ["C","D"]
    },
   ...
   ]
}
</code>```

server.js

```<code>function sortDataByID(data) {
  return data.filter(function(item) {
     return item.id == 'c949up9c';
});
}

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options).pipe(sortDataByID(res));
});
</code>```

I keep getting the following error message.

TypeError: data.filter is not a function

What is the obvious mistake here? Anyone?

答:
I've personally never seen piping to a function. I don't think that should work. In any case:

You can use a callback instead of piping. Try this:

```<code>app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 json: true, //little convenience flag to set the requisite JSON headers
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options, sortDataByID);
</code>```

});

```<code>function sortDataByID(err, response, data){ //the callback must take 3 parameters

    if(err){
        return res.json(err); //make sure there was no error
    }

    if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
        return res.status(400).json(err)
    }

    let dataToReturn =  data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
        return item.id == 'c949up9c';
    }

    res.json(dataToReturn);
}
</code>```

Body:
I am trying to filter an array of JSON objects, which I get from an API call on my proxy. I am using a Node.js web framework Express to make the API call.

API returns the following:

{
  data: [
    {
      type: "aaa",
      name: "Cycle",
      id: "c949up9c",
      category: ["A","B"]
    },
    {
      type: "bbb",
      name: "mobile",
      id: "c2rt4Jtu",
      category: ["C","D"]
    },
   ...
   ]
}

server.js

function sortDataByID(data) {
  return data.filter(function(item) {
     return item.id == 'c949up9c';
});
}

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options).pipe(sortDataByID(res));
});

I keep getting the following error message.

TypeError: data.filter is not a function

What is the obvious mistake here? Anyone?

Body:
I've personally never seen piping to a function. I don't think that should work. In any case:

You can use a callback instead of piping. Try this:

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 json: true, //little convenience flag to set the requisite JSON headers
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options, sortDataByID);

});

function sortDataByID(err, response, data){ //the callback must take 3 parameters

    if(err){
        return res.json(err); //make sure there was no error
    }

    if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
        return res.status(400).json(err)
    }

    let dataToReturn =  data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
        return item.id == 'c949up9c';
    }

    res.json(dataToReturn);
}


问:
Selenium working only for few pages -- Element is not clickable at point
I tried to automate Amazon/novels list page using selenium. It is working sometimes and not working sometimes. I am unable to understand the mistake in the code. It worked fine for some time and scrolled 13 pages out of 20. But from next time, it is not working properly. Till now it didn't scroll complete 20 pages.

```<code>from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup

class App:

    def __init__(self,path='F:\Imaging'):

        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):

        self.driver.execute_script("window.scrollTo(0,5500);")
        sleep(1)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(2)

        for value in range(2,19):

            print(self.driver.current_url)
            sleep(3)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(2)
            load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
            load_more.click()

        sleep(3)

if __name__=='__main__':
    app=App()
</code>```

The output for this code which i am getting is:

```<code>    C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Akhil/Scrape/amazon.py
https://www.amazon.in/s/ref=sr_pg_2/257-8503487-3570721?rh=i%3Aaps%2Ck%3Anovels&page=2&keywords=novels&ie=UTF8&qid=1510744188
https://www.amazon.in/s/ref=sr_pg_3?rh=i%3Aaps%2Ck%3Anovels&page=3&keywords=novels&ie=UTF8&qid=1510744197
https://www.amazon.in/s/ref=sr_pg_4?rh=i%3Aaps%2Ck%3Anovels&page=4&keywords=novels&ie=UTF8&qid=1510744204
Traceback (most recent call last):
  File "C:/Users/Akhil/Scrape/amazon.py", line 31, in <module>
    app=App()
  File "C:/Users/Akhil/Scrape/amazon.py", line 11, in __init__
    self.scroll_down()
  File "C:/Users/Akhil/Scrape/amazon.py", line 26, in scroll_down
    load_more.click()
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a title="Next Page" id="pagnNextLink" class="pagnNext" href="/gp/search/ref=sr_pg_5?rh=i%3Aaps%2Ck%3Anovels&page=5&keywords=novels&ie=UTF8&qid=1510744210">...</a> is not clickable at point (809, 8). Other element would receive the click: <a href="/gp/prime/ref=nav_prime_try_btn/257-8503487-3570721" class="nav-a nav-a-2" data-ux-mouseover="true" id="nav-link-prime" tabindex="26">...</a>
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1
</code>```

How to solve this problem?

答:
Try the following code:

```<code>load_more = ui.WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((By.XPATH, "//span[@class="pagnRA"]/a[@title="Next Page"]")))
driver.execute_script("arguments[0].scrollIntoView(true);", load_more)
load_more.click()
</code>```

where timeout -- time in seconds for waiting for the element to be clickable.

Also, import the following at the beginning of the script:

```<code>from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
</code>```

Body:
I tried to automate Amazon/novels list page using selenium. It is working sometimes and not working sometimes. I am unable to understand the mistake in the code. It worked fine for some time and scrolled 13 pages out of 20. But from next time, it is not working properly. Till now it didn't scroll complete 20 pages.

from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup

class App:

    def __init__(self,path='F:\Imaging'):

        self.path=path
        self.driver = webdriver.Chrome('F:\chromedriver')
        self.driver.get('https://www.amazon.in/s/ref=sr_pg_1?rh=i%3Aaps%2Ck%3Anovels&keywords=novels&ie=UTF8&qid=1510727563')
        sleep(1)
        self.scroll_down()
        self.driver.close()

    def scroll_down(self):

        self.driver.execute_script("window.scrollTo(0,5500);")
        sleep(1)
        load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
        load_more.click()
        sleep(2)

        for value in range(2,19):

            print(self.driver.current_url)
            sleep(3)
            self.driver.execute_script("window.scrollTo(0,5500);")
            sleep(2)
            load_more = self.driver.find_element_by_xpath('//span[@class="pagnRA"]/a[@title="Next Page"]')
            load_more.click()

        sleep(3)

if __name__=='__main__':
    app=App()

The output for this code which i am getting is:

    C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Akhil/Scrape/amazon.py
https://www.amazon.in/s/ref=sr_pg_2/257-8503487-3570721?rh=i%3Aaps%2Ck%3Anovels&page=2&keywords=novels&ie=UTF8&qid=1510744188
https://www.amazon.in/s/ref=sr_pg_3?rh=i%3Aaps%2Ck%3Anovels&page=3&keywords=novels&ie=UTF8&qid=1510744197
https://www.amazon.in/s/ref=sr_pg_4?rh=i%3Aaps%2Ck%3Anovels&page=4&keywords=novels&ie=UTF8&qid=1510744204
Traceback (most recent call last):
  File "C:/Users/Akhil/Scrape/amazon.py", line 31, in <module>
    app=App()
  File "C:/Users/Akhil/Scrape/amazon.py", line 11, in __init__
    self.scroll_down()
  File "C:/Users/Akhil/Scrape/amazon.py", line 26, in scroll_down
    load_more.click()
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Akhil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element ... is not clickable at point (809, 8). Other element would receive the click: ...
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)

Process finished with exit code 1

How to solve this problem?

Body:
Try the following code:

load_more = ui.WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((By.XPATH, "//span[@class="pagnRA"]/a[@title="Next Page"]")))
driver.execute_script("arguments[0].scrollIntoView(true);", load_more)
load_more.click()

where timeout -- time in seconds for waiting for the element to be clickable.

Also, import the following at the beginning of the script:

from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


问:
CryptoJS HmacSHA256 Encryption results differ from Python
CryptoJS encrypted string can pass different parameters in python can only pass a string? How to implement the second CryptoJS implementation in python
 ,how to get clientKey2,This will only give the first result.Thanks!

```<code>> saltedPassword=CryptoJS.PBKDF2("key", "salt", {keySize: 8,iterations:500,hasher: CryptoJS.algo.SHA256});
> clientKey1=CryptoJS.HmacSHA256(saltedPassword.toString(), "Client Key")
> clientKey2=CryptoJS.HmacSHA256(saltedPassword, "Client Key")
> clientKey1.toString()
> "857ef8988876a3bb6bcadb85ca257787074e73e830d7dc14c1f838ba46aef1f5"
> clientKey2.toString()
> "9a8574da9b276ee1162dcb92071df587f4513bc03060bda1e9b3897d46233416"
> saltedPassword.toString()
> "6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc"
</code>```

i use this way can get clientKey1,

```<code>import hashlib
import hmac

def HmacSHA256(k,v):
    message = bytes(k).encode('utf-8')
    secret = bytes(v).encode('utf-8')
    signature = hmac.new(secret, message, digestmod=hashlib.sha256).hexdigest()
    return signature

signature = HmacSHA256("6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc","Client Key")

print signature
</code>```

How to get the second result in Python,Thanks!

答:
To get the desired clientKey2 you need to encode the hex digits of your saltedPassword string to bytes. One way to do that which works on both Python 2 & Python 3 is to use binascii.unhexlify.

Your HmacSHA256 function is a bit odd. It won't work on Python 3, since bytes objects don't have an .encode method. In Python 2, bytes is just a synonym for str.

Anyway, here's some code that works on both Python 2 & Python 3.

```<code>from __future__ import print_function
import hashlib
import hmac
import binascii

key = "Client Key".encode()
salted = "6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc"
raw = binascii.unhexlify(salted)

signature = hmac.new(key, salted.encode(), digestmod=hashlib.sha256).hexdigest()
print(signature)

signature = hmac.new(key, raw, digestmod=hashlib.sha256).hexdigest()
print(signature)
</code>```

output

```<code>857ef8988876a3bb6bcadb85ca257787074e73e830d7dc14c1f838ba46aef1f5
9a8574da9b276ee1162dcb92071df587f4513bc03060bda1e9b3897d46233416
</code>```

The output is identical on Python 2 & Python 3.

BTW, it would be simpler to do this task in Python 3, which makes a clean distinction between text and byte strings. Also, the Python 3 hashlib module has a pbkdf2 function.

Body:
CryptoJS encrypted string can pass different parameters in python can only pass a string? How to implement the second CryptoJS implementation in python
 ,how to get clientKey2,This will only give the first result.Thanks!

> saltedPassword=CryptoJS.PBKDF2("key", "salt", {keySize: 8,iterations:500,hasher: CryptoJS.algo.SHA256});
> clientKey1=CryptoJS.HmacSHA256(saltedPassword.toString(), "Client Key")
> clientKey2=CryptoJS.HmacSHA256(saltedPassword, "Client Key")
> clientKey1.toString()
> "857ef8988876a3bb6bcadb85ca257787074e73e830d7dc14c1f838ba46aef1f5"
> clientKey2.toString()
> "9a8574da9b276ee1162dcb92071df587f4513bc03060bda1e9b3897d46233416"
> saltedPassword.toString()
> "6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc"

i use this way can get clientKey1,

import hashlib
import hmac

def HmacSHA256(k,v):
    message = bytes(k).encode('utf-8')
    secret = bytes(v).encode('utf-8')
    signature = hmac.new(secret, message, digestmod=hashlib.sha256).hexdigest()
    return signature

signature = HmacSHA256("6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc","Client Key")

print signature

How to get the second result in Python,Thanks!

Body:
To get the desired clientKey2 you need to encode the hex digits of your saltedPassword string to bytes. One way to do that which works on both Python 2 & Python 3 is to use binascii.unhexlify.

Your HmacSHA256 function is a bit odd. It won't work on Python 3, since bytes objects don't have an .encode method. In Python 2, bytes is just a synonym for str.

Anyway, here's some code that works on both Python 2 & Python 3.

from __future__ import print_function
import hashlib
import hmac
import binascii

key = "Client Key".encode()
salted = "6e441ccd26e6b35198b4b17457dc0266d36b751d0062b5850b0e302ceb1d6dcc"
raw = binascii.unhexlify(salted)

signature = hmac.new(key, salted.encode(), digestmod=hashlib.sha256).hexdigest()
print(signature)

signature = hmac.new(key, raw, digestmod=hashlib.sha256).hexdigest()
print(signature)

output

857ef8988876a3bb6bcadb85ca257787074e73e830d7dc14c1f838ba46aef1f5
9a8574da9b276ee1162dcb92071df587f4513bc03060bda1e9b3897d46233416

The output is identical on Python 2 & Python 3.

BTW, it would be simpler to do this task in Python 3, which makes a clean distinction between text and byte strings. Also, the Python 3 hashlib module has a pbkdf2 function.


问:
how to get dropdown selected rows from gridview in yii2
I am using yii2 advanced framework. There is a select2 dropdown list of companies name.
 In view/companies/index.php

```<code>Select2::widget([
    'id' => 'front_companies_select',
    'name' => 'state_10',
    'data' => $companyNameList,
    'options' => [
        'placeholder' => 'Select ...',
        'multiple' => true
    ],
]);
</code>```

and a button get info

```<code><?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'info']) ?>
</code>```

here is myjsfile

```<code>  $("#getinfo").click(function(){
    var selval = '';
    $("#front_companies_select option:selected").each(function () {
     var $this = $(this);
     if ($this.length) {
      var selText = $this.val();
      selval = selText+','+selval;
    }
  });
    var searchurl = 'index.php?r=companies&id'+selval;
    window.location.replace(searchurl);
    alert (selval); //here I can get id of selected rows but I want complete row
  });
</code>```

I want to show gridview rows of selected companies.
how to solve this ?

答:
you can write on click jquery function for #info and get select2 box user selected values after that you can get current url bind selected values to url that url pass seachmodel values </p>

```<code>$('#info'),on('click',function(){
var selval = '';
$("#front_companies_select option:selected").each(function () {
   var $this = $(this);
   if ($this.length) {
    var selText = $this.val();
    selval = selText+','+selval;
   }
});
var searchurl = 'someurl&searchvalues'+selval;
window.location.replace(searchurl);

});
</code>```

Body:
I am using yii2 advanced framework. There is a select2 dropdown list of companies name.
 In view/companies/index.php

Select2::widget([
    'id' => 'front_companies_select',
    'name' => 'state_10',
    'data' => $companyNameList,
    'options' => [
        'placeholder' => 'Select ...',
        'multiple' => true
    ],
]);

and a button get info

<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'info']) ?>

here is myjsfile

  $("#getinfo").click(function(){
    var selval = '';
    $("#front_companies_select option:selected").each(function () {
     var $this = $(this);
     if ($this.length) {
      var selText = $this.val();
      selval = selText+','+selval;
    }
  });
    var searchurl = 'index.php?r=companies&id'+selval;
    window.location.replace(searchurl);
    alert (selval); //here I can get id of selected rows but I want complete row
  });

I want to show gridview rows of selected companies.
how to solve this ?

Body:
you can write on click jquery function for #info and get select2 box user selected values after that you can get current url bind selected values to url that url pass seachmodel values

$('#info'),on('click',function(){
var selval = '';
$("#front_companies_select option:selected").each(function () {
   var $this = $(this);
   if ($this.length) {
    var selText = $this.val();
    selval = selText+','+selval;
   }
});
var searchurl = 'someurl&searchvalues'+selval;
window.location.replace(searchurl);

});


问:
get src value from multiple images and split to single variables
I am trying to get src value of some images but i will get it only from first one image.. is here way to get value from all images?</p>

```<code><div class="cube-box--cube active">
    <img class="cube-box--cube__img" src="
    {$basePath}/assets/img/animation/scenery2.jpg" alt="scenery2">

    <div class="white-cover"></div>
    <p class="cube-box--cube__text">
      <span class="fix-size">Electrostatics</span>
    Neutral
    </p>
</div>

<div class="cube-box--cube active">
    <img class="cube-box--cube__img" src="
    {$basePath}/assets/img/animation/scenery3.jpg" alt="scenery3">

    <div class="white-cover"></div>
    <p class="cube-box--cube__text">
      <span class="fix-size">Electrostatics</span>
    Neutral
    </p>
</div>

var imgSrc = $('.cube-box--cube').filter('.active').find("img").attr("src");
console.log(imgSrc);
</code>```

答:
You can map all the matches to an array like this

var imgSources = $('.cube-box--cube')
  .filter('.active')
  .find("img")
  .map(function (index, image) {
    return image.src;
  });

Body:
I am trying to get src value of some images but i will get it only from first one image.. is here way to get value from all images?

      Electrostatics
    Neutral

      Electrostatics
    Neutral

var imgSrc = $('.cube-box--cube').filter('.active').find("img").attr("src");
console.log(imgSrc);


问:
Date format in tag
I have an  tag as per the following:

```<code> <a href="#" title="data">cerca </a>
</code>```

which holds a date. It is part of an ASP.NET GridView:

```<code><asp:TemplateField>
  <HeaderTemplate>
    Data Inizio   <a href="#" title="data">cerca </a>
  </HeaderTemplate>
  <ItemTemplate> <%# Eval("iniziodata") %> </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="inizioora" HeaderText="Ora Inizio" SortExpression="inizioora"></asp:BoundField>
<asp:BoundField DataField="finedata" HeaderText="Data Fine" SortExpression="finedata" DataFormatString="{0:dd/MM/yyyy}"></asp:BoundField>
</code>```

I want to format it in dd/MM/yyyy format. How can I do that?

答:
Try in Bound Field

```<code>DataFormatString="{0:d}"
</code>```

or in TemplateField

```<code><a href="#" title="data"><%# Bind("Date", "{0:d}")%></a>
</code>```

Title: Date format in tag

Body:
I have an  tag as per the following:

 cerca

which holds a date. It is part of an ASP.NET GridView:

<asp:TemplateField>
  <HeaderTemplate>
    Data Inizio   cerca
  </HeaderTemplate>
  <ItemTemplate> <%# Eval("iniziodata") %> </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="inizioora" HeaderText="Ora Inizio" SortExpression="inizioora"></asp:BoundField>
<asp:BoundField DataField="finedata" HeaderText="Data Fine" SortExpression="finedata" DataFormatString="{0:dd/MM/yyyy}"></asp:BoundField>

I want to format it in dd/MM/yyyy format. How can I do that?

Body:
Try in Bound Field

DataFormatString="{0:d}"

or in TemplateField

<a href="#" title="data"><%# Bind("Date", "{0:d}")%></a>


问:
How to put the Y-axis of a chart to the right-side of it
I created a chart in Billboard.js which looks like this:

```<code>var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": columns
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": label,
                "position": "outer-center"
            },
        },
        "y": {
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});
</code>```

Now it looks like the classic style, X axis on the bottom and Y axis on the left. I want to move the Y axis on the right of the table.

I've tried many ways to do it but without success like these ones:

-changing its name from y to y2

-adding the same code but with y2:

```<code>"y": {
    "label": {
    "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

"y2": {
    "label": {
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
</code>```

I addied show attribute inside the label like this:

```<code>"y": {
    "label": {
        "show": false,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
"y2": {
    "label": {
        "show": true,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
</code>```

Any ideas?

答:
Try

```<code>var chart = bb.generate({
  "data": {
    "columns": [
    ["data1", 30, 200, 100, 400, 150, 250],
    ["data2", 50, 20, 10, 40, 15, 25]
    ],
    "axes": {
      "data1": "y2" // set additional y axis
    }
  },
  "axis": {
    "y": {
      "show": false // hide default y axis
    },
    "y2": {
      "show": true
    }
  },
  "bindto": "#AdditionalYAxis"
});
</code>```

I have tried it on their demo from github. There is an option axis where you can simply hide the axis. Hope this helps.

Working Example: https://jsfiddle.net/k3o1ws47/

Body:
I created a chart in Billboard.js which looks like this:

var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": columns
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": label,
                "position": "outer-center"
            },
        },
        "y": {
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});

Now it looks like the classic style, X axis on the bottom and Y axis on the left. I want to move the Y axis on the right of the table.

I've tried many ways to do it but without success like these ones:

-changing its name from y to y2

-adding the same code but with y2:

"y": {
    "label": {
    "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

"y2": {
    "label": {
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

I addied show attribute inside the label like this:

"y": {
    "label": {
        "show": false,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
"y2": {
    "label": {
        "show": true,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

Any ideas?

Body:
Try

var chart = bb.generate({
  "data": {
    "columns": [
    ["data1", 30, 200, 100, 400, 150, 250],
    ["data2", 50, 20, 10, 40, 15, 25]
    ],
    "axes": {
      "data1": "y2" // set additional y axis
    }
  },
  "axis": {
    "y": {
      "show": false // hide default y axis
    },
    "y2": {
      "show": true
    }
  },
  "bindto": "#AdditionalYAxis"
});

I have tried it on their demo from github. There is an option axis where you can simply hide the axis. Hope this helps.

Working Example: https://jsfiddle.net/k3o1ws47/


问:
Getting textView margin and setting ImageView margin programatically.
In my current activity i'm trying to get margin of ImageView and write in TextView, but i always recieving "0". Top margin is about 390px.</p>

```<code>final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
int a = Brick_1.getTop();

TextView t = (TextView) findViewById(R.id.tekstas);
t.setText(a+"");
</code>```

答:
Getting margin from a view . Use Below code :

```<code>final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) Brick_1.getLayoutParams();
    int marginTop =  lp.topMargin ;
</code>```

Setting Margin to a view. Use Below Code:

```<code>   TextView t = (TextView) findViewById(R.id.tekstas);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    /** @Firstparam - left margin
     *  @Second param - top margin
     *  @Third param - right margin
     *  @fourth param - bottom margin
     */
    lp.setMargins(0,marginTop,0, 0);
    t.setLayoutParams(layoutParams);
</code>```

Body:
In my current activity i'm trying to get margin of ImageView and write in TextView, but i always recieving "0". Top margin is about 390px.

final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
int a = Brick_1.getTop();

TextView t = (TextView) findViewById(R.id.tekstas);
t.setText(a+"");

Body:
Getting margin from a view . Use Below code :

final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) Brick_1.getLayoutParams();
    int marginTop =  lp.topMargin ;

Setting Margin to a view. Use Below Code:

   TextView t = (TextView) findViewById(R.id.tekstas);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    /** @Firstparam - left margin
     *  @Second param - top margin
     *  @Third param - right margin
     *  @fourth param - bottom margin
     */
    lp.setMargins(0,marginTop,0, 0);
    t.setLayoutParams(layoutParams);


问:
Using variable number of float arguments
I'm trying to implement a flexible constructor for my struct Polynomial :

```<code>struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};
</code>```

The degree of the polynomial is variable.
What I would like is to have a constructor like

```<code>Polynomial(float... _coefficients);
</code>```

I've tried variadic template :

```<code>template<float... Args>
Polynomial(Args... args);
</code>```

But float is a non-type, so I've done :

```<code>template<typename... Args>
Polynomial(Args... args);
</code>```

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

```<code>Polynomial(size_t _degree, ...);
</code>```

But it is really unsafe.

At the moment I'm using :

```<code>Polynomial(std::vector<float>);
</code>```

But this force the call to be like :

```<code>Polynomial P({f1, f2, f3}); // with fn floats
</code>```

So I would like to know if there is a good way to do this.

Thank you !

答:
I think that your way (a vector parameter, or better (IMHO) an initializer list) is a good way.

Another way (simple but with drawbacks) could be the use of narrowing to be sure that Args... are float or types that can be narrowed to float. Something like

```<code>struct Polinomial
 {
   std::vector<double>  v;
   std::size_t          degree;

   template <typename ... Args>
   Polinomial (Args const & ... args)
      : v { float{args}... }, degree { sizeof...(Args) }
    { }
 };
</code>```

It's simple and works, by example

```<code>Polinomial p { 2.3f, 3.5f, 6.7f };
</code>```

but your constructor doesn't accept, by example, integer or double or long double values; so

```<code>Polinomial p { 2.3f, 3.5f, 6.7 };
// ........................^^^  double, error

Polinomial p { 2.3f, 3.5f, 6 };
// ........................^  int, error
</code>```

and probably is too restrictive.

Body:
I'm trying to implement a flexible constructor for my struct Polynomial :

struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};

The degree of the polynomial is variable.
What I would like is to have a constructor like

Polynomial(float... _coefficients);

I've tried variadic template :

template<float... Args>
Polynomial(Args... args);

But float is a non-type, so I've done :

template<typename... Args>
Polynomial(Args... args);

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

Polynomial(size_t _degree, ...);

But it is really unsafe.

At the moment I'm using :

Polynomial(std::vector<float>);

But this force the call to be like :

Polynomial P({f1, f2, f3}); // with fn floats

So I would like to know if there is a good way to do this.

Thank you !

Body:
I think that your way (a vector parameter, or better (IMHO) an initializer list) is a good way.

Another way (simple but with drawbacks) could be the use of narrowing to be sure that Args... are float or types that can be narrowed to float. Something like

struct Polinomial
 {
   std::vector<double>  v;
   std::size_t          degree;

   template <typename ... Args>
   Polinomial (Args const & ... args)
      : v { float{args}... }, degree { sizeof...(Args) }
    { }
 };

It's simple and works, by example

Polinomial p { 2.3f, 3.5f, 6.7f };

but your constructor doesn't accept, by example, integer or double or long double values; so

Polinomial p { 2.3f, 3.5f, 6.7 };
// ........................^^^  double, error

Polinomial p { 2.3f, 3.5f, 6 };
// ........................^  int, error

and probably is too restrictive.