问:
Get generated SQL for a DbContext.SaveChanges in Entity Framework Core
In Entity Framework Core, is it possible to see the SQL that will be applied when the SaveChanges() method is called on the DbContext?

答:
You can use DbContextOptionsBuilder.UseLoggerFactory(loggerFactory) method to log all sql output.By using constructor Injection like below

```<code>public class DemoContext : ObjContext
{
    private readonly ILoggerFactory _loggerFactory;

    public DemoContext() { }

    public DemoContext(ILoggerFactory loggerFactory)
    {
        _loggerFactory = loggerFactory;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder.UseLoggerFactory(_loggerFactory);
    }
}

using (var context = new DemoContext(_loggerFactory))
{
    var Employees = context.Employee.ToList();
}
</code>```

Or

I suggest a few other ways of viewing the SQL generated is to use reflection to create an ObjectQuery object and then call the ToTraceString() method to actually store the query results.

```<code>using (var context = new EntityContext())
{
    var query = context.Customers.Where(c => c.Id == 1);
    var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
}
</code>```

Use SQL Logging

Using The DbContext.Database.Log property can be set to a delegate for any method that takes a string.

Log SQL to the Console.

```<code>using (var context = new EntityContext())
{
    context.Database.Log = Console.Write;
}
</code>```

Log SQL to Visual Studio Output panel.

```<code>using (var context = new EntityContext())
{
    context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

}
</code>```

Body:
You can use DbContextOptionsBuilder.UseLoggerFactory(loggerFactory) method to log all sql output.By using constructor Injection like below

public class DemoContext : ObjContext
{
    private readonly ILoggerFactory _loggerFactory;

    public DemoContext() { }

    public DemoContext(ILoggerFactory loggerFactory)
    {
        _loggerFactory = loggerFactory;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder.UseLoggerFactory(_loggerFactory);
    }
}

using (var context = new DemoContext(_loggerFactory))
{
    var Employees = context.Employee.ToList();
}

Or

I suggest a few other ways of viewing the SQL generated is to use reflection to create an ObjectQuery object and then call the ToTraceString() method to actually store the query results.

using (var context = new EntityContext())
{
    var query = context.Customers.Where(c => c.Id == 1);
    var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString();
}

Use SQL Logging

Using The DbContext.Database.Log property can be set to a delegate for any method that takes a string.

Log SQL to the Console.

using (var context = new EntityContext())
{
    context.Database.Log = Console.Write;
}

Log SQL to Visual Studio Output panel.

using (var context = new EntityContext())
{
    context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

}


来源: stackexchange

问:
Pass variable to laravel model boot
I use laravel 5.8 for my application. I have variables call "lot" and when I delete one, I want to perform other actions.

So I use deleting function on my model, everything works OK.

But know I have a function on my controller to delete many "lots" and I want actions to be perform only when all "lots" have been delete and not on every "lots" delete.

So I wonder if there is a way to achieve this ? Maybe we can pass a variable to boot functions to trigger or not the function ?

My model looks like this :

```<code>protected static function boot()
{
    parent::boot();

    static::deleted(function($modele) {

        Etage::doesntHave('lots')->delete();

    }
 }
</code>```

答:
Model events are been designed to work for single models.

You should use Laravel Events instead, not tied to Models.

In EventServiceProvider.php register a new Event/Listener in the $listens array, like

```<code>LotsDeleted::class => PerformOtherAction::class
</code>```

Create those classes with php artisan event:generate

Then, when you have finished deleting all your Lot objects, trigger the event with

```<code>event(new LotsDeleted());
</code>```

The handle() function of your listener will be called and you can perform other actions.

ContentLicense: CC BY-SA 4.0

Title: Pass variable to laravel model boot

Body:
I use laravel 5.8 for my application. I have variables call "lot" and when I delete one, I want to perform other actions.

So I use deleting function on my model, everything works OK.

But know I have a function on my controller to delete many "lots" and I want actions to be perform only when all "lots" have been delete and not on every "lots" delete.

So I wonder if there is a way to achieve this ? Maybe we can pass a variable to boot functions to trigger or not the function ?

My model looks like this :

protected static function boot()
{
    parent::boot();

    static::deleted(function($modele) {

        Etage::doesntHave('lots')->delete();

    }
 }

Body:
Model events are been designed to work for single models.

You should use Laravel Events instead, not tied to Models.

In EventServiceProvider.php register a new Event/Listener in the $listens array, like

LotsDeleted::class => PerformOtherAction::class

Create those classes with php artisan event:generate

Then, when you have finished deleting all your Lot objects, trigger the event with

event(new LotsDeleted());

The handle() function of your listener will be called and you can perform other actions.


问:
Why does Bootstrap not working with chrome
im new to web-development and front-end i downloaded bootstrap and puted some code to test it it works fine with firefox but not in chrome it appears like a non styled html code so if there any solution

<!DOCTYPE html>

 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">

 <link rel="stylesheet" href="css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

My First Bootstrap Page

Resize this responsive page to see the effect!

    Link

    Link

    Link

    Disabled

```

the result in chrome

答:
It's a CORS issue. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Since you are loading CSS and JavaScript file from the same origin where the HTML file is in, you need to omit the integrity and crossorigin property in <link> and

My First Bootstrap Page

Resize this responsive page to see the effect!

      Link

      Link

      Link

      Disabled

```

Body:
im new to web-development and front-end i downloaded bootstrap and puted some code to test it it works fine with firefox but not in chrome it appears like a non styled html code so if there any solution

<!DOCTYPE html>

 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">

 <link rel="stylesheet" href="css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

My First Bootstrap Page

Resize this responsive page to see the effect!

    Link

    Link

    Link

    Disabled

the result in chrome

Body:
It's a CORS issue. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Since you are loading CSS and JavaScript file from the same origin where the HTML file is in, you need to omit the integrity and crossorigin property in <link> and <script> tag.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/bootstrap.min.css">
  <script src="js/bootstrap.min.js"></script>
</head>

<body>

  <div class="jumbotron text-center">
    <h1>My First Bootstrap Page</h1>
    <p>Resize this responsive page to see the effect!</p>
  </div>
  <ul class="nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="#">Disabled</a>
    </li>
  </ul>

</body>

</html>


问:
Keras VGG16 with flow_from_directory val_acc not rising
I use keras and import VGG16 network with imagenet weights to classify male/female photos.

Strcture of directories is:

split_1/train/male/*.jpg

split_1/train/female/*.jpg

split_1/val/female/*.jpg

split_1/val/male/*.jpg

I tried most of the solutions I found over the internet but none of them worked:

changing batch_size

changing optimizers

changing class_mode/loss function

setting every layer to trainable

copying every layer from VGG to my sequential

import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras import applications

[...]

img_width, img_height = 224, 224

top_model_weights_path = "%s_retry2.h5" % split
train_data_dir = "%s/train" % split
validation_data_dir = "%s/val" % split
batch_size = 48
nb_train_samples = 4000
nb_validation_samples = ( 299 // batch_size ) * batch_size
epochs = 5

def train_top_model():
    datagen = ImageDataGenerator(
        horizontal_flip=True,
        shear_range=0.2,
        rescale=1. / 255)

    vdatagen = ImageDataGenerator(rescale=1./255)

    traingen = datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='categorical',
        follow_links=True,
        shuffle=True)

     valgen = vdatagen.flow_from_directory(
        validation_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='categorical',
        follow_links=True,
        shuffle=True)

    vgg_model = applications.VGG16(input_shape=(224,224,3), weights="imagenet", include_top=False)
    model = Sequential()
    model.add(vgg_model)
    model.add(Flatten())
    model.add(Dense(2, activation='softmax'))
    model.compile(optimizer="rmsprop", loss='categorical_crossentropy', metrics=['accuracy'])

    history = model.fit_generator(traingen,
              epochs=epochs,
              steps_per_epoch=nb_train_samples // batch_size,
              validation_data=valgen,
              validation_steps=nb_validation_samples // batch_size)

```

It reports actual amount of images so it finds the jpgs properly.
Accuracy in val keeps being "random" and the same (~50%) during entire training.

答:
Try reducing the learning rate, it may be the case where your model is overshooting the minima every time and hence not able to converge.

If any kind of hyper parameter tuning doesn't work then you need to fix your data but i think male/female classification data shouldn't be that tough to learn for a CNN model with pre-trained weights.

Body:
I use keras and import VGG16 network with imagenet weights to classify male/female photos.

Strcture of directories is:

split_1/train/male/*.jpg

split_1/train/female/*.jpg

split_1/val/female/*.jpg

split_1/val/male/*.jpg

I tried most of the solutions I found over the internet but none of them worked:

changing batch_size

changing optimizers

changing class_mode/loss function

setting every layer to trainable

copying every layer from VGG to my sequential

import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras import applications

[...]

img_width, img_height = 224, 224

top_model_weights_path = "%s_retry2.h5" % split
train_data_dir = "%s/train" % split
validation_data_dir = "%s/val" % split
batch_size = 48
nb_train_samples = 4000
nb_validation_samples = ( 299 // batch_size ) * batch_size
epochs = 5

def train_top_model():
    datagen = ImageDataGenerator(
        horizontal_flip=True,
        shear_range=0.2,
        rescale=1. / 255)

    vdatagen = ImageDataGenerator(rescale=1./255)

    traingen = datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='categorical',
        follow_links=True,
        shuffle=True)

     valgen = vdatagen.flow_from_directory(
        validation_data_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='categorical',
        follow_links=True,
        shuffle=True)

    vgg_model = applications.VGG16(input_shape=(224,224,3), weights="imagenet", include_top=False)
    model = Sequential()
    model.add(vgg_model)
    model.add(Flatten())
    model.add(Dense(2, activation='softmax'))
    model.compile(optimizer="rmsprop", loss='categorical_crossentropy', metrics=['accuracy'])

    history = model.fit_generator(traingen,
              epochs=epochs,
              steps_per_epoch=nb_train_samples // batch_size,
              validation_data=valgen,
              validation_steps=nb_validation_samples // batch_size)

It reports actual amount of images so it finds the jpgs properly.
Accuracy in val keeps being "random" and the same (~50%) during entire training.


答:
How Many sample do you have per class???
It seems that you don't have enough data to fine tune these large scale parameters that VGG16 has. (138 million if you trainable all the layers)

I suggest :
1. for gender classification problem, Try to use an official dataset such as IMDB-WIKI
2. If you wanna use your own data first collect more label sample and after that augment all of them
3. finally, Use state of the art CNN architectures such as Xception (you can load imagenet pre-traind of xception in keras) freeze 20 first layers and fune tune others

Title: Keras VGG16 with flow_from_directory val_acc not rising


问:
I want to call my script when command not found in bash (cmder)?
If the Command is not found in bash(cmder).
Then i need to call my batch or shell file.
and execute custom code to print result instead of default
bash: foo: command not found

Is there any settings in cmder or any possible other way to achieve this case.
If there is any other console emulator that can able to achieve this case?

答:
you can check if command is callable with

```<code>if ! type COMMAND &>/dev/null; then
   # not callable - here your script
fi
</code>```

or after the call, if command not found (exitcode =  127)

```<code>COMMAND
if [[ "$?" == 127 ]]; then
   # command unknown  - here your script
fi
</code>```

Body:
you can check if command is callable with

if ! type COMMAND &>/dev/null; then
   # not callable - here your script
fi

or after the call, if command not found (exitcode =  127)

COMMAND
if [[ "$?" == 127 ]]; then
   # command unknown  - here your script
fi


问:
dyld`__abort_with_payload: Without an error message
When I start my app with Xcode, I have a crash, but without an error.

The app is just stopping on this thread:

What can I do to have more information about the issue?

答:
I've had this situation after updating Xcode to v10.2.1 and Swift to v5.0.

If you are using Carthage + RxSwift, the new RxSwift uses RxRelay.framework. You should go to your /Carthage/Build directory find that framework and drag it to your project. Don't forget also add it to your carthage copy-frameworks script:
$(SRCROOT)/Carthage/Build/iOS/RxRelay.framework

It was resolved thanks to fred's answer.


问:
Get the requesting user in controller method of ASP.NET app
I am currently working on an ASP.NET Web app with angular as a front end. As a base, the new template present in VisualStudio 2019 for ASP.NET angular, with Individual Authentication.

This runs on dotnet core 3.0 Preview 4.

First a user is created through the register interface of the template application. Then when a request is made to a controller of the backend, I would like to get the ApplicationUser that made the request.

Is that possible? Do I need to put any sort of token in the header of the http request in the frontend? Do I need to do anything special in the backend?

Currently, the http request in the controller looks like this.

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from "@angular/router";
import { error } from 'protractor';

@Component({
  selector: 'app-classes-component',
  templateUrl: './classes.component.html'
})
export class ClassesComponent {
  public classes: Class[];
  public http: HttpClient;
  public baseUrl: string;
  public courseCodeValue: string;

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string, private router: Router) {
    this.http = http;
    this.baseUrl = baseUrl;
    this.refreshCourses();
  }

  public refreshCourses() {
    this.http.get<Class[]>(this.baseUrl + 'api/Courses/GetCourses').subscribe(result => {
      this.classes = result;
    }, error => console.error(error));
  }
}
```

<p>The Controller looks like this:</p>

<pre class="lang-py prettyprint-override"><code>    [Authorize]
    [Route("api/[controller]")]
    public class CoursesController : Controller
    {

        private readonly UserManager<ApplicationUser> _userManager;

        public CoursesController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpGet("[action]")]
        public IEnumerable<CourseDto> GetCourses()
        {
            var user = _userManager.GetUserAsync(User).Result;

            // Here the user is null
            return user.Courses.Select(item => new CourseDto
            {
                CourseCode = item.CourseCode,
                CurrentGrade = item.CurrentGrade
            });

        }
    }
</code>```

The issue is that when I try to get the user that is making the http request with the usermanager, I get null. So I was wondering if I was missing something. Like prehaps some sort of token in the header of the request? Am I doing something wrong on the controller side?

EDIT: here is the Startup.cs code

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();
            services.AddMvc(options => options.EnableEndpointRouting = false)
                .AddNewtonsoftJson();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseAuthentication();
            app.UseIdentityServer();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }
```

答:
You can use "User.Identity.Name" to get the UserId of the User making the request then pass it to FindByIdAsync().

var user = await _userManager.FindByIdAsync(User.Identity.Name);

or a db hit against the UserId(User.Identity.Name);

which ever works best for you.

Please let me know if this works.

Body:
I am currently working on an ASP.NET Web app with angular as a front end. As a base, the new template present in VisualStudio 2019 for ASP.NET angular, with Individual Authentication.

This runs on dotnet core 3.0 Preview 4.

First a user is created through the register interface of the template application. Then when a request is made to a controller of the backend, I would like to get the ApplicationUser that made the request.

Is that possible? Do I need to put any sort of token in the header of the http request in the frontend? Do I need to do anything special in the backend?

Currently, the http request in the controller looks like this.

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from "@angular/router";
import { error } from 'protractor';

@Component({
  selector: 'app-classes-component',
  templateUrl: './classes.component.html'
})
export class ClassesComponent {
  public classes: Class[];
  public http: HttpClient;
  public baseUrl: string;
  public courseCodeValue: string;

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string, private router: Router) {
    this.http = http;
    this.baseUrl = baseUrl;
    this.refreshCourses();
  }

  public refreshCourses() {
    this.http.get<Class[]>(this.baseUrl + 'api/Courses/GetCourses').subscribe(result => {
      this.classes = result;
    }, error => console.error(error));
  }
}

The Controller looks like this:

    [Authorize]
    [Route("api/[controller]")]
    public class CoursesController : Controller
    {

        private readonly UserManager<ApplicationUser> _userManager;

        public CoursesController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpGet("[action]")]
        public IEnumerable<CourseDto> GetCourses()
        {
            var user = _userManager.GetUserAsync(User).Result;

            // Here the user is null
            return user.Courses.Select(item => new CourseDto
            {
                CourseCode = item.CourseCode,
                CurrentGrade = item.CurrentGrade
            });

        }
    }

The issue is that when I try to get the user that is making the http request with the usermanager, I get null. So I was wondering if I was missing something. Like prehaps some sort of token in the header of the request? Am I doing something wrong on the controller side?

EDIT: here is the Startup.cs code

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<ApplicationUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();
            services.AddMvc(options => options.EnableEndpointRouting = false)
                .AddNewtonsoftJson();

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseAuthentication();
            app.UseIdentityServer();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }


问:
Replace Default WordPress Logo with the Current Theme Logo in WordPress Login Page
I'm trying to replace the WordPress login logo with the active theme logo. The active theme is using the default "Customizer" options for the logo.

I'm using the following code

```<code>function my_custom_login_logo() {
echo '<style type="text/css">
h1 a {background-image:url(https://broproud.com/wp-content/uploads/2018/08/cropped-150-Width-Logo.png) !important; margin:0 auto;}
</style>';
}
add_filter( 'login_head', 'my_custom_login_logo' );
</code>```

I know, I can change the logo, with this code, but how can I display the active theme logo automatically? What kind of function is required?

答:
First step is to add an action to the login_enqueue_scripts, this is (as stated above) done by adding a code snippet to the themes function.php.

After that you'll find 2 things:

if you have a non-square logo it will become very small

if you click on it you'll go to wordpress.org

Both can be easily solved in the same snippet with pure css:

```<code><style type="text/css">
  body.login div#login h1 a {
    background-image: url(PATH TO YOUR LOGO);
    padding-bottom: 30px;
    margin: 0;
    width: 100%;
    background-size: contain;
    pointer-events: none;
  }
</style>
<?php
} add_action( 'login_enqueue_scripts', 'custom_login_logo' );
</code>```

Body:
I'm trying to replace the WordPress login logo with the active theme logo. The active theme is using the default "Customizer" options for the logo.

I'm using the following code

function my_custom_login_logo() {
echo '';
}
add_filter( 'login_head', 'my_custom_login_logo' );

I know, I can change the logo, with this code, but how can I display the active theme logo automatically? What kind of function is required?

Body:
First step is to add an action to the login_enqueue_scripts, this is (as stated above) done by adding a code snippet to the themes function.php.

After that you'll find 2 things:

if you have a non-square logo it will become very small

if you click on it you'll go to wordpress.org

Both can be easily solved in the same snippet with pure css:

<style type="text/css">
  body.login div#login h1 a {
    background-image: url(PATH TO YOUR LOGO);
    padding-bottom: 30px;
    margin: 0;
    width: 100%;
    background-size: contain;
    pointer-events: none;
  }
</style>
<?php
} add_action( 'login_enqueue_scripts', 'custom_login_logo' );


问:
My JavaScript is not changing color or dimensions as I expected
I am trying to use JavaScript in an Android webview. I used following code. I did not get color changed or offset height of body.

```<code>        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new myJavaScriptInterface(webview), "jsInterface");

        webview.loadUrl("file:///android_asset/sample/contents.html");
        //webview.loadData("file:///android_asset/sample",convertStreamToString(inputStream), "text/html", "UTF-8");

    webview.loadUrl("javascript:" +
                "document.getElementsByTagName('p')[0].style.color='red';" +
                 "");

        wbview.loadUrl("javascript:window.jsInterface.EchoText(document.body.offsetHeight);");

        //webview.
}
class myJavaScriptInterface
{
    WebView mywebview;
    public myJavaScriptInterface(WebView webview)
    {
        this.mywebview=webview;
    }
    public void EchoText(String message)
    {
        Toast.makeText(mywebview.getContext(), message, Toast.LENGTH_SHORT).show();
    }
}
</code>```

What am I missing?

答:
I think this is because your page is not loaded (still loading) when you are using webview.loadUrl("javascript:" + ...) statements.

Try the following...

```<code>webview.loadUrl("file:///android_asset/sample/contents.html");
webview.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView webview, String url) {
        webview.loadUrl("javascript:" +
            "document.getElementsByTagName('p')[0].style.color='red';");
        wbview.loadUrl("javascript:" +
            "window.jsInterface.EchoText(document.body.offsetHeight);");
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use JavaScript in an Android webview. I used following code. I did not get color changed or offset height of body.

        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new myJavaScriptInterface(webview), "jsInterface");

        webview.loadUrl("file:///android_asset/sample/contents.html");
        //webview.loadData("file:///android_asset/sample",convertStreamToString(inputStream), "text/html", "UTF-8");

    webview.loadUrl("javascript:" +
                "document.getElementsByTagName('p')[0].style.color='red';" +
                 "");

        wbview.loadUrl("javascript:window.jsInterface.EchoText(document.body.offsetHeight);");

        //webview.
}
class myJavaScriptInterface
{
    WebView mywebview;
    public myJavaScriptInterface(WebView webview)
    {
        this.mywebview=webview;
    }
    public void EchoText(String message)
    {
        Toast.makeText(mywebview.getContext(), message, Toast.LENGTH_SHORT).show();
    }
}

What am I missing?

Body:
I think this is because your page is not loaded (still loading) when you are using webview.loadUrl("javascript:" + ...) statements.

Try the following...

webview.loadUrl("file:///android_asset/sample/contents.html");
webview.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView webview, String url) {
        webview.loadUrl("javascript:" +
            "document.getElementsByTagName('p')[0].style.color='red';");
        wbview.loadUrl("javascript:" +
            "window.jsInterface.EchoText(document.body.offsetHeight);");
    }
});


问:
Execute two schedulers simultaneously with spring-boot @scheduled annotation
I have 2 schedulers, which executes at a fixedDelay of 5s.

I have 2 use-cases:

If If - condition BusinessLogic class is true, then I want to sleep both the schedulers for a time of 3 secs, which means both the schedulers should execute now after 8 secs [5 secs + 3 secs].

If code qualifies the else condition, then both the schedulers should continue to execute at fixed delay of 5 secs.

Code:

Scheduler class:

```<code>import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestSchedulers {

    @Autowired
    private BusinessLogic businessLogic;

    @Scheduled(fixedDelay = 5000)
    public void scheduler1(){
        Date currentDate = new Date();
        System.out.println("Started Sceduler 1 at " + currentDate);
        String schedulerName = "Scheduler one";
        businessLogic.logic(schedulerName);
    }
    @Scheduled(fixedDelay = 5000)
    public void scheduler2(){
        Date currentDate= new Date();
        System.out.println("Started Sceduler 2 at " + currentDate);
        String schedulerName = "Scheduler two";
        businessLogic.logic(schedulerName);
    }
}
</code>```

Business logic class:

```<code>import java.util.Random;

import org.springframework.stereotype.Service;

@Service
public class BusinessLogic {

    public void logic(String schedulerName) {
        if(randomGen() < 100){
            System.out.println("\nExecuting If condition for [" + schedulerName + "]");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else if(randomGen() > 100){
            System.out.println("\nExecuting Else condition for [" + schedulerName + "]");
        }
    }

    //Generate random numbers

    public int randomGen(){
        Random rand = new Random();
        int randomNum = rand.nextInt((120 - 90) + 1) + 90;
        return randomNum;
    }

}
</code>```

The problem

Both the schedulers are not starting at the same time.

When the if part is executing, then only one schedulers sleep for extra 3 secs, but I want both theschedulers to do so.

Log for reference:

```<code>Started Sceduler 1 at Sun May 26 12:34:53 IST 2019

Executing If condition for [Scheduler one]
2019-05-26 12:34:53.266  INFO 9028 --- [           main] project.project.App                      : Started App in 1.605 seconds (JVM running for 2.356)
Started Sceduler 2 at Sun May 26 12:34:56 IST 2019

Executing If condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:01 IST 2019

Executing Else condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:04 IST 2019

Executing Else condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:06 IST 2019

Executing If condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:09 IST 2019

Executing Else condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:14 IST 2019

Executing If condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:17 IST 2019

Executing If condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:22 IST 2019

Executing Else condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:25 IST 2019

Executing Else condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:27 IST 2019
</code>```

please help..

答: In each scheduler you invoke if(randomGen() < 100) independently of each other. So for one scheduler it could give result > 100 and for other < 100 or for both it could be the same. What you will need to do is to run randomGen() outside of the schedulers and store the single result in a way that both schedulers can access it and then they will rely on the same value in their if(randomGenValue < 100) statement and will behave the same way

Body:
I have 2 schedulers, which executes at a fixedDelay of 5s.

I have 2 use-cases:

If If - condition BusinessLogic class is true, then I want to sleep both the schedulers for a time of 3 secs, which means both the schedulers should execute now after 8 secs [5 secs + 3 secs].

If code qualifies the else condition, then both the schedulers should continue to execute at fixed delay of 5 secs.

Code:

Scheduler class:

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestSchedulers {

    @Autowired
    private BusinessLogic businessLogic;

    @Scheduled(fixedDelay = 5000)
    public void scheduler1(){
        Date currentDate = new Date();
        System.out.println("Started Sceduler 1 at " + currentDate);
        String schedulerName = "Scheduler one";
        businessLogic.logic(schedulerName);
    }
    @Scheduled(fixedDelay = 5000)
    public void scheduler2(){
        Date currentDate= new Date();
        System.out.println("Started Sceduler 2 at " + currentDate);
        String schedulerName = "Scheduler two";
        businessLogic.logic(schedulerName);
    }
}

Business logic class:

import java.util.Random;

import org.springframework.stereotype.Service;

@Service
public class BusinessLogic {

    public void logic(String schedulerName) {
        if(randomGen() < 100){
            System.out.println("\nExecuting If condition for [" + schedulerName + "]");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else if(randomGen() > 100){
            System.out.println("\nExecuting Else condition for [" + schedulerName + "]");
        }
    }

    //Generate random numbers

    public int randomGen(){
        Random rand = new Random();
        int randomNum = rand.nextInt((120 - 90) + 1) + 90;
        return randomNum;
    }

}

The problem

Both the schedulers are not starting at the same time.

When the if part is executing, then only one schedulers sleep for extra 3 secs, but I want both theschedulers to do so.

Log for reference:

Started Sceduler 1 at Sun May 26 12:34:53 IST 2019

Executing If condition for [Scheduler one]
2019-05-26 12:34:53.266  INFO 9028 --- [           main] project.project.App                      : Started App in 1.605 seconds (JVM running for 2.356)
Started Sceduler 2 at Sun May 26 12:34:56 IST 2019

Executing If condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:01 IST 2019

Executing Else condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:04 IST 2019

Executing Else condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:06 IST 2019

Executing If condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:09 IST 2019

Executing Else condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:14 IST 2019

Executing If condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:17 IST 2019

Executing If condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:22 IST 2019

Executing Else condition for [Scheduler one]
Started Sceduler 2 at Sun May 26 12:35:25 IST 2019

Executing Else condition for [Scheduler two]
Started Sceduler 1 at Sun May 26 12:35:27 IST 2019

please help..


问:
VSCode: How to export a python file that was imported from a Jupyter Notebook back to Jupyter format?
Probably a silly question, but I couldn't find it. Visual Studio Code editor has a really nice way to work with Jupyter Notebooks. I can edit the cells directly in vscode and run them. Now it would be easy to work with version control.

But I couldn't find a way to convert it back to a Notebook! How do I generate a notebook back from the generated python file?

I understand that the notebook wouldn't have the output cells in it.

答:
If you need more control over how conversion to ipynb is done (or you need to have cross-references) then you can give a try to Pandoctools. It can export VSCode *.py documents to any Pandoc output format or to Jupyter notebook.

For example you can create and register Jupyter kernel. For example is can be named "nn". That should be the same kernel that you selected in VSCode (there you select it by path but VSCode still uses installed kernels specs under the hood). Then add hat to the Python file, split document to cells, provide settings and set Markdown cells (commented metadata line would export to pdf instead of ipynb; I recommend to open ipynb in nteract native app):

```<code>"""
---
kernels-map:
  py: nn
jupyter:
  kernelspec:
    display_name: nn
    language: python
    name: nn
pandoctools:
  # out: "*.pdf"
  out: "*.ipynb"
...

# Markdown section title 1

Some **static** Markdown text.
"""

# %% {echo=False}
import IPython.display as ds
import math
import sugartex as stex

# %% {markdown}
"""
# Markdown section title 2

The quick brown Fox jumps over the lazy dog.
"""

# %%
ds.Markdown(stex.pre(f'''

Some **dynamic** Markdown text with SugarTeX formula: ˎα^˱{math.pi:1.3f}˲ˎ.
It works because of the `Markdown` display option and `sugartex` Pandoc filter.
Acually `stex.pre` is redundant here but it is needed when the text is imported
or read from somewhere instead of being written in the same document.

'''))
</code>```

Then convert the file via pandoctools: drag and drop file to pandoctools shortcut/executable or "open with" pandoctools executable.

Also see:

Two introduction articles are at the beginning of this README,

examples of input to output conversion that have cross-references!

how to use Pandoctools and it's CLI,

how to use Knitty that collects Jupyter outputs and change it's settings.

Body:
If you need more control over how conversion to ipynb is done (or you need to have cross-references) then you can give a try to Pandoctools. It can export VSCode *.py documents to any Pandoc output format or to Jupyter notebook.

For example you can create and register Jupyter kernel. For example is can be named "nn". That should be the same kernel that you selected in VSCode (there you select it by path but VSCode still uses installed kernels specs under the hood). Then add hat to the Python file, split document to cells, provide settings and set Markdown cells (commented metadata line would export to pdf instead of ipynb; I recommend to open ipynb in nteract native app):

"""
---
kernels-map:
  py: nn
jupyter:
  kernelspec:
    display_name: nn
    language: python
    name: nn
pandoctools:
  # out: "*.pdf"
  out: "*.ipynb"
...

# Markdown section title 1

Some **static** Markdown text.
"""

# %% {echo=False}
import IPython.display as ds
import math
import sugartex as stex

# %% {markdown}
"""
# Markdown section title 2

The quick brown Fox jumps over the lazy dog.
"""

# %%
ds.Markdown(stex.pre(f'''

Some **dynamic** Markdown text with SugarTeX formula: ˎα^˱{math.pi:1.3f}˲ˎ.
It works because of the `Markdown` display option and `sugartex` Pandoc filter.
Acually `stex.pre` is redundant here but it is needed when the text is imported
or read from somewhere instead of being written in the same document.

'''))

Then convert the file via pandoctools: drag and drop file to pandoctools shortcut/executable or "open with" pandoctools executable.

Also see:

Two introduction articles are at the beginning of this README,

examples of input to output conversion that have cross-references!

how to use Pandoctools and it's CLI,

how to use Knitty that collects Jupyter outputs and change it's settings.


问:
Type mismatch: cannot convert from Mono<A> to Mono<B>
Type mismatch: cannot convert from Mono to Mono. Wants to add error messge to B then i wants to return Mono of B.</p>

```<code>public  Mono<B> case1(){
    A a = new A();
    a.setName("srihari");
    B b = new B();
    a.setName("G SRIHARI");
    Mono<A> mono = Mono.error(new RuntimeException("HARISRI"));

    return mono.onErrorResume(d->{
         b.setErrorMessage(d.getMessage());
        return Mono.just(b);
    }).subscribeOn(Schedulers.elastic());
</code>```

答:
As you can see in the signature of onErrorResume(), the fallback function can only result in a Mono of the same type as the source Mono. This is for good reason.

What if you instead had Mono mono = Mono.just(new A());. Now, no error will be thrown, so the fallback function will never be invoked. Therefore, you still have a Mono, not a Mono.

This isn't really anything special with Reactor. Consider the same kind of flow with a try catch:

public B foo() {
  try {
    // throw new RuntimeException();
    return new A();
  } catch (Exception e) {
    return new B();
  }
}
```

Obviously, this code does not compile because if an error is not thrown, A will be returned, but the method must return B. This is essentially what you are trying to write but with Reactor.

Body:
Type mismatch: cannot convert from Mono to Mono. Wants to add error messge to B then i wants to return Mono of B.

public  Mono case1(){
    A a = new A();
    a.setName("srihari");
    B b = new B();
    a.setName("G SRIHARI");
    Mono mono = Mono.error(new RuntimeException("HARISRI"));

    return mono.onErrorResume(d->{
         b.setErrorMessage(d.getMessage());
        return Mono.just(b);
    }).subscribeOn(Schedulers.elastic());

Body:
As you can see in the signature of onErrorResume(), the fallback function can only result in a Mono of the same type as the source Mono. This is for good reason.

What if you instead had Mono<A> mono = Mono.just(new A());. Now, no error will be thrown, so the fallback function will never be invoked. Therefore, you still have a Mono<A>, not a Mono<B>.

This isn't really anything special with Reactor. Consider the same kind of flow with a try catch:

public B foo() {
  try {
    // throw new RuntimeException();
    return new A();
  } catch (Exception e) {
    return new B();
  }
}

Obviously, this code does not compile because if an error is not thrown, A will be returned, but the method must return B. This is essentially what you are trying to write but with Reactor.


问:
Upgrade QT 5.4 or Qt 5.5 - Install and run - Ubuntu 14 and 15
I have searched all day in order to use Qt 5.4 or Qt 5.5.
I have two machines, one running Ubuntu 15 and the other Ubuntu 14, but got the same results.
I have installed the program through the download-online package, and now I have beautiful /opt/Qt/5.4/ and /opt/Qt/5.5 folders.

That's all. I am stuck in here. If I run qmake -version, the reply is:

```<code>Using Qt version 5.2.1 in /usr/lib/x86_64-linux-gnu
</code>```

Also, if I run qtchooser -list-versions, I get:

```<code>4
5
default
qt4-x86_64 linux-gnu
qt4
qt5-x86_64 linux-gnu
qt5
</code>```

I have to use SuperCollider 3.7 for an important project, and I need Q t5.4 or higher. Is there anybody who can tell me what to do after installing the package to make programs see Qt 5.4 or higher?

I even tried to build from the source code, but in that case init-repository doesn't work.

Luca

答:
As I was digging in the right way to change the default choice for qt session in my old ubuntu 14.04 LTS, I did find this old topic as best match for my own question.

So here my answer for any 14.04 living in 2019 : the default package qmake point on qtchooser, which looks for its conf in /usr/lib/x86_64-linux-gnu/qt* directories

The default conf is in /usr/lib/x86_64-linux-gnu/qt-default/ .
If you haven't this, look at your "qtchooser -print-env" result to see what's your own path. I think that a good practice to set this as system default should be to create a link from the xdg default to your ubuntu standard default (as it works for me) :

```<code>sudo mkdir -p /etc/xdg/qtchooser/
cd /etc/xdg/qtchooser/
ln -s /usr/lib/x86_64-linux-gnu/qt-default/qtchooser/default.conf default.conf
</code>```

As far I can see, there's no more things as "Managers Kits" in qtcreator

Body:
I have searched all day in order to use Qt 5.4 or Qt 5.5.
I have two machines, one running Ubuntu 15 and the other Ubuntu 14, but got the same results.
I have installed the program through the download-online package, and now I have beautiful /opt/Qt/5.4/ and /opt/Qt/5.5 folders.

That's all. I am stuck in here. If I run qmake -version, the reply is:

Using Qt version 5.2.1 in /usr/lib/x86_64-linux-gnu

Also, if I run qtchooser -list-versions, I get:

4
5
default
qt4-x86_64 linux-gnu
qt4
qt5-x86_64 linux-gnu
qt5

I have to use SuperCollider 3.7 for an important project, and I need Q t5.4 or higher. Is there anybody who can tell me what to do after installing the package to make programs see Qt 5.4 or higher?

I even tried to build from the source code, but in that case init-repository doesn't work.

Luca

Body:
As I was digging in the right way to change the default choice for qt session in my old ubuntu 14.04 LTS, I did find this old topic as best match for my own question.

So here my answer for any 14.04 living in 2019 : the default package qmake point on qtchooser, which looks for its conf in /usr/lib/x86_64-linux-gnu/qt* directories

The default conf is in /usr/lib/x86_64-linux-gnu/qt-default/ .
If you haven't this, look at your "qtchooser -print-env" result to see what's your own path. I think that a good practice to set this as system default should be to create a link from the xdg default to your ubuntu standard default (as it works for me) :

sudo mkdir -p /etc/xdg/qtchooser/
cd /etc/xdg/qtchooser/
ln -s /usr/lib/x86_64-linux-gnu/qt-default/qtchooser/default.conf default.conf

As far I can see, there's no more things as "Managers Kits" in qtcreator


问:
Using a For Loop to change an If statement
Just a real quick one. I has a list of variables which only change by 1 digit. I want my if statement to refer to each individual variable, but I'm not sure how to go about it. Can you help me out?

```<code>CheckGabba1 = IntVar()
CheckGabba2 = IntVar()
CheckGabba3 = IntVar()
## etc. (x10)

## There are items in these lists (This is just to show that they are lists)
AllEventsGabba = []
SelectedEventsGabba = []

NumEvents = 10
ListIndex = 0

for EventCheck in range(NumEvents):
   if (CheckGabba(ListIndex + 1)).get() == 1:
      SelectedEventsGabba.append(AllEventsGabba[ListIndex])
      ListIndex += 1
   else:
      ListIndex += 1
</code>```

Obviously (CheckGabba(ListIndex + 1) is wrong, but I'm not sure what it needs to be replaced with to get the loop to autonomously check each variable, rather than hard-writing (Which I can do, but would prefer not to).

答:
I'm not sure if I completely understood your question, but to me it looks something like this:</p>

```<code># Create a dict of the variables that you want to check later
CheckGabba = {i: IntVar() for i in range(10)}

# Then use a list comprehension to filter the data
SelectedEventsGabba = [event for event in CheckGabba.items() if event == 1]

</code>```

Body:
Just a real quick one. I has a list of variables which only change by 1 digit. I want my if statement to refer to each individual variable, but I'm not sure how to go about it. Can you help me out?

CheckGabba1 = IntVar()
CheckGabba2 = IntVar()
CheckGabba3 = IntVar()
## etc. (x10)

## There are items in these lists (This is just to show that they are lists)
AllEventsGabba = []
SelectedEventsGabba = []

NumEvents = 10
ListIndex = 0

for EventCheck in range(NumEvents):
   if (CheckGabba(ListIndex + 1)).get() == 1:
      SelectedEventsGabba.append(AllEventsGabba[ListIndex])
      ListIndex += 1
   else:
      ListIndex += 1

Obviously (CheckGabba(ListIndex + 1) is wrong, but I'm not sure what it needs to be replaced with to get the loop to autonomously check each variable, rather than hard-writing (Which I can do, but would prefer not to).

Body:
I'm not sure if I completely understood your question, but to me it looks something like this:

# Create a dict of the variables that you want to check later
CheckGabba = {i: IntVar() for i in range(10)}

# Then use a list comprehension to filter the data
SelectedEventsGabba = [event for event in CheckGabba.items() if event == 1]


问:
Is necessary to add pickup date and return date in car page?
I have problem in doing search page that will execute pickup date and return date.It is important to add pickup date and return date in car table in database??Or i can add it to another table??

```<code>Car.php

    </body>
        <table align='center' width='40%' border='0' cellpadding='0' cellspacing='0'>
            <tr>
                <form action="search.php" method="post" enctype="multipart/form-data">
                <td><input type="date" name="Pickup_date" placeholder="Pickup_date" style='height:38px' required /></td>
                <td><input type="date" name="Return_date" placeholder="Return_date" style='height:38px' required    /></td>
                <td><input type="submit" name="submitbook" value="Search" style='background-color: blue; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px;'/></td>
    </div>
    </form>
    </table>

// Attempt select query execution
  $sql = "SELECT * FROM car";
  if($result = mysqli_query($link, $sql)){
  if(mysqli_num_rows($result) > 0){
  echo "<table>";
echo "<tr>";
    echo "<th>Id</th>";
    echo "<th>Name</th>";
    echo "<th>Price(RM)</th>";
    echo "<th>Colour</th>";
    echo "<th>Mode</th>";
    echo "<th>Image</th>";
    echo "<th>Status</th>";
    echo "<th>Add to Booking</th>";
    echo "</tr>";

    while($row = mysqli_fetch_array($result)){
    echo "<tr>";
    echo "<td>" . $row['car_id'] . "</td>";
    echo "<td>" . $row['car_name'] . "</td>";
    echo "<td>" . $row['car_price'] . "</td>";
    echo "<td>" . $row['car_colour'] . "</td>";
    echo "<td>" . $row['car_mode'] . "</td>";
    echo "<td><img src='" . $row['car_image'] . "' height='100'
    width='100'></td>";
    echo "<td>" . $row['car_status'] . "</td>";
    echo "<td><button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button></td>";

echo "</tr>";

Search.php

$search=$_GET['s'];
$query="select *from car where car_name like '%$search%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "<table>";
        echo "<tr>";
            echo "<th>Id</th>";
            echo "<th>Name</th>";
            echo "<th>Price(RM)</th>";
            echo "<th>Colour</th>";
            echo "<th>Mode</th>";
            echo "<th>Image</th>";
            echo "<th>Status</th>";

        echo "</tr>";
    while($row = mysqli_fetch_array($result)){
        echo "<tr>";
            echo "<td>" . $row['car_id'] . "</td>";
            echo "<td>" . $row['car_name'] . "</td>";
            echo "<td>" . $row['car_price'] . "</td>";
            echo "<td>" . $row['car_colour'] . "</td>";
            echo "<td>" . $row['car_mode'] . "</td>";
            echo "<td><img src='" . $row['car_image'] . "' height='100' width='100'></td>";
            echo "<td>" . $row['car_status'] . "</td>";
            echo "</tr>";
</code>```

Sorry for this countless question that i want to ask.I am very new to php language.How to make this "book" button in car.php can redirect to booking.php?I want my search box can execute based on pickup date and return
date in car.php and when it is execute, it will redirect to search.php.
I click button search but it displays "could not able to execute".

答:
I will give you the solution for your current issues but you must know that you need to follow the PHP Standards Recommendations and also consider to run some validations before executing database queries.

This is an old school coding style, I strongly recommend you do this using the new standards. Please have a look at this example of a simple PHP 7 shopping cart and this is another example using MySQL.

Now, answering your questions:

I would recommend a relational table for pickup and return dates.

```<code>uid | car_uid | pickup_date | return_date
</code>```

And you use "car_uid" to create a relation with "cars" tables. Then for the query you use "JOIN".

Your form action is going to search.php so in this file, you need to read the values from the form in car.php (Pickup_date and Return_date).

For example (in search.php):

```<code>$pickup_date = $_GET['Pickup_date'];
$return_date = $_GET['Return_date'];
</code>```

And then create the query:

```<code>"SELECT * FROM cars WHERE pickup_date = '".$pickup_date."' AND return_date = '".$return_date."'";
</code>```

I see that for your "Book" button you are calling a JavaScript function called "booking_car()", this should work if your function is correct. Example:

```<code>function booking_car(car_id) {
    window.open('booking.php?id=' + car_id, '_self');
}
</code>```

And then you need to get the id in "booking.php"

```<code>$car_id = $_GET['car_id'];
</code>```

And run the query to book the car.

Body:
I have problem in doing search page that will execute pickup date and return date.It is important to add pickup date and return date in car table in database??Or i can add it to another table??

Car.php

                <form action="search.php" method="post" enctype="multipart/form-data">
                <input type="date" name="Pickup_date" placeholder="Pickup_date" style='height:38px' required />
                <input type="date" name="Return_date" placeholder="Return_date" style='height:38px' required    />
                <input type="submit" name="submitbook" value="Search" style='background-color: blue; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 14px;'/>

    </form>

// Attempt select query execution
  $sql = "SELECT * FROM car";
  if($result = mysqli_query($link, $sql)){
  if(mysqli_num_rows($result) > 0){
  echo "
";
echo "
";
    echo "Id	";
    echo "Name	";
    echo "Price(RM)	";
    echo "Colour	";
    echo "Mode	";
    echo "Image	";
    echo "Status	";
    echo "Add to Booking	";
    echo "
";

    while($row = mysqli_fetch_array($result)){
    echo "
";
    echo "" . $row['car_id'] . "	";
    echo "" . $row['car_name'] . "	";
    echo "" . $row['car_price'] . "	";
    echo "" . $row['car_colour'] . "	";
    echo "" . $row['car_mode'] . "	";
    echo "	";
    echo "" . $row['car_status'] . "	";
    echo "<button onclick=\"booking_car('" . $row['car_id'] .
    "')\">Book</button>	";

echo "
";

Search.php

$search=$_GET['s'];
$query="select *from car where car_name like '%$search%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "
";
        echo "
";
            echo "Id	";
            echo "Name	";
            echo "Price(RM)	";
            echo "Colour	";
            echo "Mode	";
            echo "Image	";
            echo "Status	";

        echo "
";
    while($row = mysqli_fetch_array($result)){
        echo "
";
            echo "" . $row['car_id'] . "	";
            echo "" . $row['car_name'] . "	";
            echo "" . $row['car_price'] . "	";
            echo "" . $row['car_colour'] . "	";
            echo "" . $row['car_mode'] . "	";
            echo "	";
            echo "" . $row['car_status'] . "	";
            echo "
";

Sorry for this countless question that i want to ask.I am very new to php language.How to make this "book" button in car.php can redirect to booking.php?I want my search box can execute based on pickup date and return
date in car.php and when it is execute, it will redirect to search.php.
I click button search but it displays "could not able to execute".

Body:
I will give you the solution for your current issues but you must know that you need to follow the PHP Standards Recommendations and also consider to run some validations before executing database queries.

This is an old school coding style, I strongly recommend you do this using the new standards. Please have a look at this example of a simple PHP 7 shopping cart and this is another example using MySQL.

Now, answering your questions:

I would recommend a relational table for pickup and return dates.

uid | car_uid | pickup_date | return_date

And you use "car_uid" to create a relation with "cars" tables. Then for the query you use "JOIN".

Your form action is going to search.php so in this file, you need to read the values from the form in car.php (Pickup_date and Return_date).

For example (in search.php):

$pickup_date = $_GET['Pickup_date'];
$return_date = $_GET['Return_date'];

And then create the query:

"SELECT * FROM cars WHERE pickup_date = '".$pickup_date."' AND return_date = '".$return_date."'";

I see that for your "Book" button you are calling a JavaScript function called "booking_car()", this should work if your function is correct. Example:

function booking_car(car_id) {
    window.open('booking.php?id=' + car_id, '_self');
}

And then you need to get the id in "booking.php"

$car_id = $_GET['car_id'];

And run the query to book the car.


问:
Click event not triggering for every iteration of for loop
I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.

Manually clicking 10 times will generate 10 tabs. But see the following code:

```<code>for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}
</code>```

I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see

Edit:
@Jesse
See my utility full code:

```<code>var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
    // console.log(`${i.getFullYear()}-${i.getMonth()}`);
    // var dd=`${i.getFullYear()}-${i.getMonth()}`;
    var dd=new Date(i).toISOString().substr(0,7);
    console.log(dd);
    document.querySelector("input#picker.form-control").value=dd;
    var type='Supplementary'
    document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
    document.querySelector('#reg1').click();

}
</code>```

答:
Somehow you have to execute the subsequence clicking in an asynchronous manner. I got this work by this:

```<code>let i=0;
(function doClick(){
  document.querySelector('#reg1').click();
  i++;
  if(i<10) setTimeout(() => doClick());
})()
</code>```

Another approach using async function:

```<code>(async function doClick() {
  for(let i=0;i<10;i++) {
    document.querySelector('#reg1').click();
    await new Promise(setTimeout);
  }
})()
</code>```

Body:
I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.

Manually clicking 10 times will generate 10 tabs. But see the following code:

for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}

I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see

Edit:
@Jesse
See my utility full code:

var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
    // console.log(`${i.getFullYear()}-${i.getMonth()}`);
    // var dd=`${i.getFullYear()}-${i.getMonth()}`;
    var dd=new Date(i).toISOString().substr(0,7);
    console.log(dd);
    document.querySelector("input#picker.form-control").value=dd;
    var type='Supplementary'
    document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
    document.querySelector('#reg1').click();

}

Body:
Somehow you have to execute the subsequence clicking in an asynchronous manner. I got this work by this:

let i=0;
(function doClick(){
  document.querySelector('#reg1').click();
  i++;
  if(i<10) setTimeout(() => doClick());
})()

Another approach using async function:

(async function doClick() {
  for(let i=0;i<10;i++) {
    document.querySelector('#reg1').click();
    await new Promise(setTimeout);
  }
})()


问:
Zxing QR code scanner code is not working in a fragment
I am trying to develop QR code scanner App using Zxing library in Kotlin. I am able to open the camera and scan the QR code but not getting response.

I also tried this tutorial for implementation but did not get helped.

```<code>class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val mScanner = IntentIntegrator(activity)
        mScanner.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        mScanner.setBeepEnabled(true)
        mScanner.initiateScan()

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                Toast.makeText(activity, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(activity, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}
</code>```

I want to get response in a toast but when I tried to use debugger I am unable to go to onActivityResult() and the camera closes quickly.

答:
Your fragment is not requesting the activity result. As you instantiate IntentIntegrator(activity) with the activity, it'll run activity.startActivityForResult(intent, REQUEST_CODE). Therefore you'll not receive the result within your fragment.

If you're still using android.app.Fragment, you only have to make sure to use your fragment to instantiate IntentIntegrator(this@HomeFragment). Like this you'll get the result within your fragment, as it'll run fragment.startActivityForResult(intent, REQUEST_CODE) internally.

If you're using the androidx.fragment.app.Fragment, you might need to copy the sources for IntentIntegrator into your app and adapt the code to use the AndroidX fragment instead of the framework type.

Body:
I am trying to develop QR code scanner App using Zxing library in Kotlin. I am able to open the camera and scan the QR code but not getting response.

I also tried this tutorial for implementation but did not get helped.

class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val mScanner = IntentIntegrator(activity)
        mScanner.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        mScanner.setBeepEnabled(true)
        mScanner.initiateScan()

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                Toast.makeText(activity, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(activity, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

I want to get response in a toast but when I tried to use debugger I am unable to go to onActivityResult() and the camera closes quickly.


问:
What is the most elegant way to cast a variable you just received as an argument?
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

```<code>public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}
</code>```

Or am I missing the point here? Is there a better way to handle this in general?

答:
```<code>Graphics2D g2 = (Graphics2D)g;
</code>```

There is no need to be fancy about it.

You will always receive a G2D in the paint method.

I even like to call the Graphics parameter g2 and then cast to a Graphics2D named g to make using it simpler.

OwnerDisplayName: spligak

ContentLicense: CC BY-SA 2.5

Body:
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}

Or am I missing the point here? Is there a better way to handle this in general?

Body:
Graphics2D g2 = (Graphics2D)g;

There is no need to be fancy about it.

You will always receive a G2D in the paint method.

I even like to call the Graphics parameter g2 and then cast to a Graphics2D named g to make using it simpler.

OwnerDisplayName: jjnguy


问:
Load XML file to server
I have a simple php application that uses, among others, an hourly updated external XML file.

I need to use only one of the file's fields, thus, I used simplexml_load_file().

The problem is that this function only works with files currently saved on the server and not external ones.

How can I download the XML file periodically on the server (a download on every refresh would work too)? Thanks.

答:
```<code><?php
copy('http://www.example.com/', 'local-file.xml');
?>
</code>```

copy can do this in a memory-light manner (it doesn't need to load the entire file into memory like for example file_get_contents).

Title: Load XML file to server

Body:
<?php
copy('http://www.example.com/', 'local-file.xml');
?>

copy can do this in a memory-light manner (it doesn't need to load the entire file into memory like for example file_get_contents).


问:
Fixed width number formatting python 3
How do I get an integer to fill 0's to a fixed width in python 3.2 using the format attribute?
Example:

```<code>a = 1
print('{0:3}'.format(a))
</code>```

gives '  1' instead of '001' I want. In python 2.x, I know that this can be done using

```<code>print "%03d" % number.
</code>```

I checked the python 3 string documentation but wasn't able to get this.

http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language

Thanks.

答:
There is built-in string method .zfill for filling 0-s:</p>

```<code>>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'
</code>```

Title: Fixed width number formatting python 3

Body:
How do I get an integer to fill 0's to a fixed width in python 3.2 using the format attribute?
Example:

a = 1
print('{0:3}'.format(a))

gives '  1' instead of '001' I want. In python 2.x, I know that this can be done using

print "%03d" % number.

I checked the python 3 string documentation but wasn't able to get this.

http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language

Thanks.

Body:
There is built-in string method .zfill for filling 0-s:

>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'


问:
Data structure for counting occurrences
Say I have an array

```<code>[bob, alice, jeff, bob, bob]
</code>```

I would like to transform this array into

```<code>[bob, alice, jeff, bob1, bob2]
</code>```

That is, determining occurrences.

```<code>// iterate through array
// check if element is in finalArray
     // if not add to finalArray
// if found in final array
    // add in duplicateArray
   // check instances of element in duplicateArray and add that number to element
   // insert element+updated number to finalArray
</code>```

This is my implementation of the above algorithm

```<code>     ArrayList<String> list = new ArrayList<>();
    list.add("Bob");
    list.add("Jane");
    list.add("Smith");
    list.add("Bob");
    list.add("Bob");
    list.add("Jane");
    list.add("Smithery");

    ArrayList<String> finalList = new ArrayList<>();
    ArrayList<String> tempList = new ArrayList<>();

    for(String name : list) {
        if(finalList.contains(name)) {
            int count = 0;
            tempList.add(name);
            for(int i=0; i < tempList.size(); i++) {
                if(tempList.get(i) == name) {
                    count++;
                }
            }
            String tempName = name + count;
            finalList.add(tempName);
        } else {
            finalList.add(name);
        }
    }
    for(String name: finalList) {
        System.out.println(name);
    }
</code>```

My question is although ArrayList, and other data structure have .contains method, do any data structures have methods that return the number of instances of the element in the data structure?

答:
```<code>List<String> data = ...;
List<String> finalData = new ArrayList<>();
Map<String, Integer> counts = new HashMap<>();

for(String s : data) {
    counts.merge(s, 1, Integer::sum);  // Keep track of occurences seen

    int occurences = counts.get(s);  // Get how many there are for s

    if(occurences == 1) {
        finalData.add(s);
    }
    else {  // if more than 1, change the string
        finalData.add(s + (occurences - 1));
    }
}
</code>```

Now the real question is, what happens when you have "Bob" in the List twice, and "Bob1" is also in the original list...

Title: Data structure for counting occurrences

Body:
Say I have an array

[bob, alice, jeff, bob, bob]

I would like to transform this array into

[bob, alice, jeff, bob1, bob2]

That is, determining occurrences.

// iterate through array
// check if element is in finalArray
     // if not add to finalArray
// if found in final array
    // add in duplicateArray
   // check instances of element in duplicateArray and add that number to element
   // insert element+updated number to finalArray

This is my implementation of the above algorithm

     ArrayList<String> list = new ArrayList<>();
    list.add("Bob");
    list.add("Jane");
    list.add("Smith");
    list.add("Bob");
    list.add("Bob");
    list.add("Jane");
    list.add("Smithery");

    ArrayList<String> finalList = new ArrayList<>();
    ArrayList<String> tempList = new ArrayList<>();

    for(String name : list) {
        if(finalList.contains(name)) {
            int count = 0;
            tempList.add(name);
            for(int i=0; i < tempList.size(); i++) {
                if(tempList.get(i) == name) {
                    count++;
                }
            }
            String tempName = name + count;
            finalList.add(tempName);
        } else {
            finalList.add(name);
        }
    }
    for(String name: finalList) {
        System.out.println(name);
    }

My question is although ArrayList, and other data structure have .contains method, do any data structures have methods that return the number of instances of the element in the data structure?

Body:
List<String> data = ...;
List<String> finalData = new ArrayList<>();
Map<String, Integer> counts = new HashMap<>();

for(String s : data) {
    counts.merge(s, 1, Integer::sum);  // Keep track of occurences seen

    int occurences = counts.get(s);  // Get how many there are for s

    if(occurences == 1) {
        finalData.add(s);
    }
    else {  // if more than 1, change the string
        finalData.add(s + (occurences - 1));
    }
}

Now the real question is, what happens when you have "Bob" in the List twice, and "Bob1" is also in the original list...


问:
How to set CardViews from ArrayList in ListView
So I'm working with my android app that takes data from firebase, basically a list of cars that I save into an ArrayList of a specific class. I want to show a list of CardView with one car object each, in other words, that each card displays the info about that car (model, km, price, etc). I know that the way I should do this is using a ListView in my layout, but I cant get the adapter to work.

The idea is that it shows something like this, but with car photos and stuff:
enter image description here

I'm not very familiarized with this type of structure since I started working on it recently, but I think I'm understand how it works. I made the cardview layout model to display each car and tried to make the ViewHolder class. Thanks in advice! My code:

Vehicle class:

    public class Vehicle {

    int anio, cv, kms, puertas;
    double precio;
    String combustible, foto, marca, modelo, palanca;

    public Vehicle() {

    } //setters and getters are too, but I omitted them
```

<p>My <code>cardview_template.xml</code></p>

<pre class="lang-xml prettyprint-override"><code>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:padding="16dp"
    >

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cv"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/car_photo"
                android:src="@drawable/ic_home_icon"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/marca"
                android:text="Mercedes-Benz"
                android:layout_toRightOf="@+id/car_photo"
                android:layout_alignParentTop="true"
                android:textSize="30sp"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/kms"
                android:text="128000"
                android:layout_toRightOf="@+id/car_photo"
                android:layout_below="@+id/marca"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/precio"
                android:text="2018"
                android:layout_toRightOf="@+id/car_photo"
                android:layout_below="@+id/kms"
                />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

Part of the code that's in the method onCreate() in mi MainActivity:
I EDITED THE CODE. SEE IN THE EDIT BELOW

And finally, the class I used for the adapter. I think the problem is here:
I EDITED THE CLASS. SEE IN THE EDIT BELOW

EDIT
So following the advices, I changed the ListView with a RecyclerView, but it didn't work neither. I do not get any errors: CardViews simply do not appear in my RecyclerView.

Here's my new adapter class and the new code in the MainActivity onCreate()

Adapter:

```<code>public class VehicleListAdapter extends RecyclerView.Adapter<VehicleListAdapter.VehicleViewHolder> {

private ArrayList<Vehicle> mVehicleList;

public static class VehicleViewHolder extends  RecyclerView.ViewHolder {

    public ImageView mImageView;
    public TextView mTextView1;
    public TextView mTextView2;
    public TextView mTextView3;

    public VehicleViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.car_photo);
        mTextView1 = itemView.findViewById(R.id.marca);
        mTextView2 = itemView.findViewById(R.id.modelo);
        mTextView3 = itemView.findViewById(R.id.precio);
    }
}

public VehicleListAdapter(ArrayList<Vehicle> vehicleslist) {
    mVehicleList = vehicleslist;
}

@NonNull
@Override
public VehicleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    //Links the cardview layout and prepares the ViewHolder
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_template, parent, false);
    VehicleViewHolder vvh = new VehicleViewHolder(v);
    return vvh;
}

@Override
public void onBindViewHolder(@NonNull VehicleViewHolder holder, int position) {
    /*
    *   Links the layout elements with the variables in this class
    *   and put the object values in them
    */
    Vehicle currentVehicle = mVehicleList.get(position);

    //Uses Picasso librarie to set the image in the holder's ImageView
    Picasso.get().load(currentVehicle.foto).into(holder.mImageView);

    holder.mTextView1.setText(currentVehicle.getMarca());
    holder.mTextView2.setText(currentVehicle.getModelo());
    holder.mTextView3.setText(String.valueOf(currentVehicle.getPrecio()));
}

@Override
public int getItemCount() {
    return mVehicleList.size();
}
</code>```

MainActivity:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
(...)
    //Prepares the recycler view and shows the data
    mRecyclerView = findViewById(R.id.recyclerView);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(this);
    mAdapter = new VehicleListAdapter(vehiclesList);

    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
}
</code>```

EDIT2

Ok so I've come across a very strange thing. If I put a debug point anywhere in the onCreate() and then execute the app debugging, it works just fine. I'm completely lost.

If I don't do this, it shows like this:

It works both in the emulator and my actual phone.

答:
I know that the way I should do this is using a ListView in my layout, but I cant get the adapter to work.

Actually you need to know that Android apps are given with certain amount of RAM to work with, which will be less if you consider handling images. Hence using ListView is not suggested for Image Handling, specially for huge number of images. The solution to this is using RecyclerView, instead of ListView.

Also if you need to use RecyclerView, you need to extend RecyclerViewAdapter for the Adapter Class, which will have its own ViewHolder, subclass.

RecyclerView is easy to use, but difficult initially. After practising you will get the hang of it.

You can follow this youtube link RecyclerView + CardView - Part 1 - LAYOUTS AND CUSTOM OBJECTS - Android Studio Tutorial

If you still have some queries please comment, I would be happy to answer.

Body:
So I'm working with my android app that takes data from firebase, basically a list of cars that I save into an ArrayList of a specific class. I want to show a list of CardView with one car object each, in other words, that each card displays the info about that car (model, km, price, etc). I know that the way I should do this is using a ListView in my layout, but I cant get the adapter to work.

The idea is that it shows something like this, but with car photos and stuff:
enter image description here

I'm not very familiarized with this type of structure since I started working on it recently, but I think I'm understand how it works. I made the cardview layout model to display each car and tried to make the ViewHolder class. Thanks in advice! My code:

Vehicle class:

    public class Vehicle {

    int anio, cv, kms, puertas;
    double precio;
    String combustible, foto, marca, modelo, palanca;

    public Vehicle() {

    } //setters and getters are too, but I omitted them

My cardview_template.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:padding="16dp"
    >

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cv"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/car_photo"
                android:src="@drawable/ic_home_icon"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/marca"
                android:text="Mercedes-Benz"
                android:layout_toRightOf="@+id/car_photo"
                android:layout_alignParentTop="true"
                android:textSize="30sp"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/kms"
                android:text="128000"
                android:layout_toRightOf="@+id/car_photo"
                android:layout_below="@+id/marca"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/precio"
                android:text="2018"
                android:layout_toRightOf="@+id/car_photo"
                android:layout_below="@+id/kms"
                />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Part of the code that's in the method onCreate() in mi MainActivity:
I EDITED THE CODE. SEE IN THE EDIT BELOW

And finally, the class I used for the adapter. I think the problem is here:
I EDITED THE CLASS. SEE IN THE EDIT BELOW

EDIT
So following the advices, I changed the ListView with a RecyclerView, but it didn't work neither. I do not get any errors: CardViews simply do not appear in my RecyclerView.

Here's my new adapter class and the new code in the MainActivity onCreate()

Adapter:

public class VehicleListAdapter extends RecyclerView.Adapter<VehicleListAdapter.VehicleViewHolder> {

private ArrayList<Vehicle> mVehicleList;

public static class VehicleViewHolder extends  RecyclerView.ViewHolder {

    public ImageView mImageView;
    public TextView mTextView1;
    public TextView mTextView2;
    public TextView mTextView3;

    public VehicleViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.car_photo);
        mTextView1 = itemView.findViewById(R.id.marca);
        mTextView2 = itemView.findViewById(R.id.modelo);
        mTextView3 = itemView.findViewById(R.id.precio);
    }
}

public VehicleListAdapter(ArrayList<Vehicle> vehicleslist) {
    mVehicleList = vehicleslist;
}

@NonNull
@Override
public VehicleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    //Links the cardview layout and prepares the ViewHolder
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_template, parent, false);
    VehicleViewHolder vvh = new VehicleViewHolder(v);
    return vvh;
}

@Override
public void onBindViewHolder(@NonNull VehicleViewHolder holder, int position) {
    /*
    *   Links the layout elements with the variables in this class
    *   and put the object values in them
    */
    Vehicle currentVehicle = mVehicleList.get(position);

    //Uses Picasso librarie to set the image in the holder's ImageView
    Picasso.get().load(currentVehicle.foto).into(holder.mImageView);

    holder.mTextView1.setText(currentVehicle.getMarca());
    holder.mTextView2.setText(currentVehicle.getModelo());
    holder.mTextView3.setText(String.valueOf(currentVehicle.getPrecio()));
}

@Override
public int getItemCount() {
    return mVehicleList.size();
}

MainActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
(...)
    //Prepares the recycler view and shows the data
    mRecyclerView = findViewById(R.id.recyclerView);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(this);
    mAdapter = new VehicleListAdapter(vehiclesList);

    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
}

EDIT2

Ok so I've come across a very strange thing. If I put a debug point anywhere in the onCreate() and then execute the app debugging, it works just fine. I'm completely lost.

If I don't do this, it shows like this:

It works both in the emulator and my actual phone.


问:
Python webbrowser.open() to open Chrome browser
According to the documentation http://docs.python.org/3.3/library/webbrowser.html it's supposed to open in the default browser, but for some reason on my machine it opens IE. I did a google search and I came across an answer that said I need to register browsers, but I'm not sure how to use webbrowser.register() and the documentation doesn't seem to be very clear. How do I register Chrome so that urls I pass to webbrowser.open() open in Chrome instead of IE?</p>

答:
Here's a somewhat robust way to get the path to Chrome.

(Note that you should do this only if you specifically need Chrome, and not the default browser, or Chromium, or something else.)

```<code>def try_find_chrome_path():
    result = None
    if _winreg:
        for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
            try: result = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
            except WindowsError: pass
            if result is not None:
                result_split = shlex.split(result, False, True)
                result = result_split[0] if result_split else None
                if os.path.isfile(result):
                    break
                result = None
    else:
        expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
        for parent in os.environ.get('PATH', '').split(os.pathsep):
            path = os.path.join(parent, expected)
            if os.path.isfile(path):
                result = path
                break
    return result
</code>```

Body:
Here's a somewhat robust way to get the path to Chrome.

(Note that you should do this only if you specifically need Chrome, and not the default browser, or Chromium, or something else.)

def try_find_chrome_path():
    result = None
    if _winreg:
        for subkey in ['ChromeHTML\\shell\\open\\command', 'Applications\\chrome.exe\\shell\\open\\command']:
            try: result = _winreg.QueryValue(_winreg.HKEY_CLASSES_ROOT, subkey)
            except WindowsError: pass
            if result is not None:
                result_split = shlex.split(result, False, True)
                result = result_split[0] if result_split else None
                if os.path.isfile(result):
                    break
                result = None
    else:
        expected = "google-chrome" + (".exe" if os.name == 'nt' else "")
        for parent in os.environ.get('PATH', '').split(os.pathsep):
            path = os.path.join(parent, expected)
            if os.path.isfile(path):
                result = path
                break
    return result


问:
Cannot access variable inside inner class without making it Final
The code asks the user if they want to delete the entry from the recyclerview / mysql database. The functionality works, however if the user selects no the item is still getting deleted from the recycler-view (temporarily) until the screen is refreshed then it comes back. I tried moving the removeItem(position) method into the yes/no method. However it states the variable must be made final. If I make it final it breaks the functionality. How can I arrange this code in a way where when the user clicks no the viewholder isnt removed?</p>

```<code> /**
 * Method which removes a row from the recycler-view view-holder. Also captured the cbtId Primary Key which is sent
  * via Retrofit to the server to ensure the correct row is deleted from the database.
 * @param position
 */
public void removeItem(int position) {
    cbtId = mWorkoutLogList.get(position).getCbtId();
    mWorkoutLogList.remove(position);
    mWorkoutLogAdapter.notifyItemRemoved(position);
}

/**
 * On click method which calls the deleteLog() method to delete the row from the recycler view.
 * @param position
 */
@Override
public void onDeleteClick(int position) {

    deleteLog(position);

}

/**
 * Method which uses Retrofit to send a call to the MYSQL server to delete a workout log.
 */
private void deleteLog(int position){

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Are you Sure?");
    builder.setMessage("Deleted Workout Logs cannot be restored.");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            Call<WorkoutLogList> call = RetrofitClient.getInstance().getApi().deleteLog(cbtId);
            call.enqueue(new Callback<WorkoutLogList>() {
                @Override
                public void onResponse(Call<WorkoutLogList> call, Response<WorkoutLogList> response) {
                    removeItem(position);
                }

                @Override
                public void onFailure(Call<WorkoutLogList> call, Throwable t) {

                }
            });
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    AlertDialog ad = builder.create();
    ad.show();

}
</code>```

答:
Making the position variable final and moving it to the correct location fixed the issue.

```<code> @Override
    public void onClick(DialogInterface dialog, int which) {
        removeItem(position);
        Call<WorkoutLogList> call = RetrofitClient.getInstance().getApi().deleteLog(cbtId);
        call.enqueue(new Callback<WorkoutLogList>() {
            @Override
            public void onResponse(Call<WorkoutLogList> call, Response<WorkoutLogList> response) {

            }
</code>```

The removeItem(posiiton) method needed to be placed just befor the retrofit database call as this method gets the cbtId, without that id the row could not be removed from the database.

Body:
The code asks the user if they want to delete the entry from the recyclerview / mysql database. The functionality works, however if the user selects no the item is still getting deleted from the recycler-view (temporarily) until the screen is refreshed then it comes back. I tried moving the removeItem(position) method into the yes/no method. However it states the variable must be made final. If I make it final it breaks the functionality. How can I arrange this code in a way where when the user clicks no the viewholder isnt removed?

 /**
 * Method which removes a row from the recycler-view view-holder. Also captured the cbtId Primary Key which is sent
  * via Retrofit to the server to ensure the correct row is deleted from the database.
 * @param position
 */
public void removeItem(int position) {
    cbtId = mWorkoutLogList.get(position).getCbtId();
    mWorkoutLogList.remove(position);
    mWorkoutLogAdapter.notifyItemRemoved(position);
}

/**
 * On click method which calls the deleteLog() method to delete the row from the recycler view.
 * @param position
 */
@Override
public void onDeleteClick(int position) {

    deleteLog(position);

}

/**
 * Method which uses Retrofit to send a call to the MYSQL server to delete a workout log.
 */
private void deleteLog(int position){

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Are you Sure?");
    builder.setMessage("Deleted Workout Logs cannot be restored.");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            Call<WorkoutLogList> call = RetrofitClient.getInstance().getApi().deleteLog(cbtId);
            call.enqueue(new Callback<WorkoutLogList>() {
                @Override
                public void onResponse(Call<WorkoutLogList> call, Response<WorkoutLogList> response) {
                    removeItem(position);
                }

                @Override
                public void onFailure(Call<WorkoutLogList> call, Throwable t) {

                }
            });
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    AlertDialog ad = builder.create();
    ad.show();

}

Body:
Making the position variable final and moving it to the correct location fixed the issue.

 @Override
    public void onClick(DialogInterface dialog, int which) {
        removeItem(position);
        Call<WorkoutLogList> call = RetrofitClient.getInstance().getApi().deleteLog(cbtId);
        call.enqueue(new Callback<WorkoutLogList>() {
            @Override
            public void onResponse(Call<WorkoutLogList> call, Response<WorkoutLogList> response) {

            }

The removeItem(posiiton) method needed to be placed just befor the retrofit database call as this method gets the cbtId, without that id the row could not be removed from the database.