问:
EF Core with GraphQL
I'm currently exploring the GraphQL development and I'm currently exploring what kind of SQL queries are Generated via EF Core and I observed that no matter that my GraphQL query includes only a few fields the EF Core sends SQL Select for all fields of the Entity.

This is the code I'm using now:

```<code>public class DoctorType : ObjectGraphType<Doctors>
{
    public DoctorType()
    {
            Field(d => d.PrefixTitle);
            Field(d => d.FName);
            Field(d => d.MName);
            Field(d => d.LName);
            Field(d => d.SufixTitle);
            Field(d => d.Image);
            Field(d => d.EGN);
            Field(d => d.Description);
            Field(d => d.UID_Code);
    }
}

public class Doctors : ApplicationUser
{
    public string Image { get; set; }
    [StringLength(50)]
    public string UID_Code { get; set; }
}
</code>```

the query I'm using is

```<code>{
  doctors{
    fName
    lName
  }
}
</code>```

The SQL generated selects all fields of the Doctor entity.

Is there any way to further optimize that the generated SQL query from EF Core?

I'm guessing this happens because the DoctorType inherits from ObjectGraphType<Doctors> and not from some Projection of the Doctor, but I can't think of a clever workaround of this?

Any suggestions?

EDIT:

I'm using GraphQL.NET (graphql-dotnet) by Joe McBride version 2.4.0

EDIT 2:

Either I'm doing it wrong or I don't know.

As one of the comments suggested i downloaded GraphQL.EntityFramework Nuget package by SimonCropp

I did all the configuration needed for it:

```<code>        services.AddDbContext<ScheduleDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection"));
        });

        using (var myDataContext = new ScheduleDbContext())
        {
            EfGraphQLConventions.RegisterInContainer(services, myDataContext);
        }
</code>```

My Object graph Type is looking as follows

```<code>public class SpecializationType : EfObjectGraphType<Specializations>
{
    public SpecializationType(IEfGraphQLService graphQlService)
        :base(graphQlService)
    {
        Field(p => p.SpecializationId);
        Field(p => p.Code);
        Field(p => p.SpecializationName);
    }
}
</code>```

My query looks is:

```<code>public class RootQuery : EfObjectGraphType
{
    public RootQuery(IEfGraphQLService efGraphQlService,
        ScheduleDbContext dbContext) : base(efGraphQlService)
    {
        Name = "Query";

        AddQueryField<SpecializationType, Specializations>("specializationsQueryable", resolve: ctx => dbContext.Specializations);

    }
}
</code>```

and I'm using this graphQL query

```<code>{
  specializationsQueryable
  {
    specializationName
  }
}
</code>```

The debug log show that the generated SQL query is

```<code>SELECT `s`.`SpecializationId`, `s`.`Code`, `s`.`SpecializationName`
FROM `Specializations` AS `s`
</code>```

even though I want only specializationName field and I'm expecting it to be:

```<code>SELECT `s`.`SpecializationName`
FROM `Specializations` AS `s`
</code>```

UPDATE

I guess so far I didn't understand how graphQL really worked. I thought that there is some behind the scene fetch of data but there isn't.

The primary fetch is done in the query's field resolver :

```<code>FieldAsync<ListGraphType<DoctorType>>("doctors", resolve: async ctx => await doctorServices.ListAsync());
</code>```

and as long the result to the resolver is the full object in my case the resolver return List of Doctors entity, it will query the Database for the whole entity (all fields). No optimisations are done out of the box from GraphQL doesn't matter if you return IQueryable or else of the entity you are querying.

Every conclusion here is thought of mine it is not 100% guaranteed right

So what I've did is create a group of Helper methods which are creating an selection Expression to use in the LINQ query. The helpers are using resolver's context.SubFields property to get the fields needed.

The problem is that you need for every level of the query only the leaves, say some query "specializations" with "SpecializationName" and "Code" and the "Doctors" with their "Name" and else. In this case in the RootQuery specializations field's resolver you need only the Specializations entity projection so: SpecializationName and Code , then when it goes to fetch all Doctors from the "doctors" Field in SpecializationType the resolver's context has different SubFields which should be used for the projection of the Doctor.

The problem with the above is, when you use query batches i guess even if you dont the thing is that the Doctors Field in  SpecializationType needs the SpecializationId fetched in the RootQuery specializations Field.

I guess i didn't explain good what i went through.

Base line is as far as I understand we have to dynamically create selectors which the linq should use to project the entity.

I'm posting my approach here:

```<code>    public class RootQuery : EfObjectGraphType
{
    public RootQuery(IEfGraphQLService efGraphQlService, ISpecializationGraphQlServices specializationServices,
        IDoctorGraphQlServices doctorServices, ScheduleDbContext dbContext) : base(efGraphQlService)
    {
        Name = "Query";

        FieldAsync<ListGraphType<SpecializationType>>("specializations"
            , resolve: async ctx => {

                var selectedFields = GraphQLResolverContextHelpers.GetFirstLevelLeavesNamesPascalCase(ctx.SubFields);
                var expression = BuildLinqSelectorObject.DynamicSelectGenerator<Specializations>(selectedFields.ToArray());

                return await specializationServices.ListAsync(selector: expression);
            });
    }
}
</code>```

SpecializationType

```<code> public class SpecializationType : EfObjectGraphType<Specializations>
{
    public SpecializationType(IEfGraphQLService graphQlService
        , IDataLoaderContextAccessor accessor, IDoctorGraphQlServices doctorServices)
        : base(graphQlService)
    {
        Field(p => p.SpecializationId);
        Field(p => p.Code);
        Field(p => p.SpecializationName);
        Field<ListGraphType<DoctorType>, IEnumerable<Doctors>>()
            .Name("doctors")
            .ResolveAsync(ctx =>
            {

                var selectedFields = GraphQLResolverContextHelpers.GetFirstLevelLeavesNamesPascalCase(ctx.SubFields);
                selectedFields = GraphQLResolverContextHelpers.AppendParrentNodeToEachItem(selectedFields, parentNode: "Doctor");
                selectedFields = selectedFields.Union(new[] { "Specializations_SpecializationId" });

                var expression = BuildLinqSelectorObject.BuildSelector<SpecializationsDoctors, SpecializationsDoctors>(selectedFields);

                var doctorsLoader = accessor.Context
                    .GetOrAddCollectionBatchLoader<int, Doctors>(
                        "GetDoctorsBySpecializationId"
                        , (collection, token) =>
                        {
                            return doctorServices.GetDoctorsBySpecializationIdAsync(collection, token, expression);
                        });
                return doctorsLoader.LoadAsync(ctx.Source.SpecializationId);
            });
    }
}
</code>```

DoctorsServices:

```<code>public class DoctorGraphQlServices : IDoctorGraphQlServices
{
    public ScheduleDbContext _dbContext { get; set; }

    public DoctorGraphQlServices(ScheduleDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<List<Doctors>> ListAsync(int? specializationId = null)
    {
        var doctors = _dbContext.Doctors.AsQueryable();

        if(specializationId != null)
        {
            doctors = doctors.Where(d => d.Specializations.Any(s => s.Specializations_SpecializationId == specializationId));
        }

        return await doctors.ToListAsync();
    }

    public async Task<ILookup<int, Doctors>> GetDoctorsBySpecializationIdAsync(IEnumerable<int> specializationIds, CancellationToken token, Expression<Func<SpecializationsDoctors, SpecializationsDoctors>> selector = null)
    {
        var doctors = await _dbContext.SpecializationsDoctors
            .Include(s => s.Doctor)
            .Where(spDocs => specializationIds.Any(sp => sp == spDocs.Specializations_SpecializationId))
            .Select(selector: selector)
            .ToListAsync();

        return doctors.ToLookup(i => i.Specializations_SpecializationId, i => i.Doctor);
    }

}
</code>```

SpecializationServices

```<code>public class SpeciaizationGraphQlServices : ISpecializationGraphQlServices
{

    public ScheduleDbContext _dbContext { get; set; }

    public SpeciaizationGraphQlServices(ScheduleDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<dynamic> ListAsync(string doctorId = null, Expression<Func<Specializations, Specializations>> selector = null)
    {
        var specializations = _dbContext.Specializations.AsQueryable();

        if (!string.IsNullOrEmpty(doctorId))
        {
            specializations = specializations.Where(s => s.Doctors.Any(d => d.Doctors_Id == doctorId));
        }

        return await specializations.Select(selector).ToListAsync();

    }

    public async Task<ILookup<string, Specializations>> GetSpecializationsByDoctorIdAsync(IEnumerable<string> doctorIds, CancellationToken token)
    {
        var specializations = await _dbContext.SpecializationsDoctors
            .Include(s => s.Specialization)
            .Where(spDocs => doctorIds.Any(sp => sp == spDocs.Doctors_Id))
            .ToListAsync();

        return specializations.ToLookup(i => i.Doctors_Id, i => i.Specialization);
    }

    public IQueryable<Specializations> List(string doctorId = null)
    {
        var specializations = _dbContext.Specializations.AsQueryable();

        if (!string.IsNullOrEmpty(doctorId))
        {
            specializations = specializations.Where(s => s.Doctors.Any(d => d.Doctors_Id == doctorId));
        }

        return specializations;
    }
}
</code>```

This post has become pretty large, sorry for the span..

答:
To enable automatic fields projection, having your DB context set up as usual for .NET 6, add hotchocolate server:

```<code>dotnet add package HotChocolate.Data.EntityFramework
</code>```

Expose some data to it:

```<code>public class MyQueries
{
    [UseProjection] // Enables field projection
    public IQueryable<Book> Books([Service] MyContext db) => db.Books;
}
</code>```

Enable it in Program.cs:

```<code>builder.Services.AddGraphQLServer().AddQueryType<MyQueries>().AddProjections();
...
app.MapGraphQL("/graphql");
</code>```

That should be enough to ensure automatic db fields projection. Now you can run GraphQL queries via builder generated at /graphql/, while monitoring SQL via MyContext.Database.Log = Console.Write;

Title: EF Core with GraphQL

Body:
I'm currently exploring the GraphQL development and I'm currently exploring what kind of SQL queries are Generated via EF Core and I observed that no matter that my GraphQL query includes only a few fields the EF Core sends SQL Select for all fields of the Entity.

This is the code I'm using now:

public class DoctorType : ObjectGraphType<Doctors>
{
    public DoctorType()
    {
            Field(d => d.PrefixTitle);
            Field(d => d.FName);
            Field(d => d.MName);
            Field(d => d.LName);
            Field(d => d.SufixTitle);
            Field(d => d.Image);
            Field(d => d.EGN);
            Field(d => d.Description);
            Field(d => d.UID_Code);
    }
}

public class Doctors : ApplicationUser
{
    public string Image { get; set; }
    [StringLength(50)]
    public string UID_Code { get; set; }
}

the query I'm using is

{
  doctors{
    fName
    lName
  }
}

The SQL generated selects all fields of the Doctor entity.

Is there any way to further optimize that the generated SQL query from EF Core?

I'm guessing this happens because the DoctorType inherits from ObjectGraphType<Doctors> and not from some Projection of the Doctor, but I can't think of a clever workaround of this?

Any suggestions?

EDIT:

I'm using GraphQL.NET (graphql-dotnet) by Joe McBride version 2.4.0

EDIT 2:

Either I'm doing it wrong or I don't know.

As one of the comments suggested i downloaded GraphQL.EntityFramework Nuget package by SimonCropp

I did all the configuration needed for it:

        services.AddDbContext<ScheduleDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection"));
        });

        using (var myDataContext = new ScheduleDbContext())
        {
            EfGraphQLConventions.RegisterInContainer(services, myDataContext);
        }

My Object graph Type is looking as follows

public class SpecializationType : EfObjectGraphType<Specializations>
{
    public SpecializationType(IEfGraphQLService graphQlService)
        :base(graphQlService)
    {
        Field(p => p.SpecializationId);
        Field(p => p.Code);
        Field(p => p.SpecializationName);
    }
}

My query looks is:

public class RootQuery : EfObjectGraphType
{
    public RootQuery(IEfGraphQLService efGraphQlService,
        ScheduleDbContext dbContext) : base(efGraphQlService)
    {
        Name = "Query";

        AddQueryField<SpecializationType, Specializations>("specializationsQueryable", resolve: ctx => dbContext.Specializations);

    }
}

and I'm using this graphQL query

{
  specializationsQueryable
  {
    specializationName
  }
}

The debug log show that the generated SQL query is

SELECT `s`.`SpecializationId`, `s`.`Code`, `s`.`SpecializationName`
FROM `Specializations` AS `s`

even though I want only specializationName field and I'm expecting it to be:

SELECT `s`.`SpecializationName`
FROM `Specializations` AS `s`

UPDATE

I guess so far I didn't understand how graphQL really worked. I thought that there is some behind the scene fetch of data but there isn't.

The primary fetch is done in the query's field resolver :

FieldAsync<ListGraphType<DoctorType>>("doctors", resolve: async ctx => await doctorServices.ListAsync());

and as long the result to the resolver is the full object in my case the resolver return List of Doctors entity, it will query the Database for the whole entity (all fields). No optimisations are done out of the box from GraphQL doesn't matter if you return IQueryable or else of the entity you are querying.

Every conclusion here is thought of mine it is not 100% guaranteed right

So what I've did is create a group of Helper methods which are creating an selection Expression to use in the LINQ query. The helpers are using resolver's context.SubFields property to get the fields needed.

The problem is that you need for every level of the query only the leaves, say some query "specializations" with "SpecializationName" and "Code" and the "Doctors" with their "Name" and else. In this case in the RootQuery specializations field's resolver you need only the Specializations entity projection so: SpecializationName and Code , then when it goes to fetch all Doctors from the "doctors" Field in SpecializationType the resolver's context has different SubFields which should be used for the projection of the Doctor.

The problem with the above is, when you use query batches i guess even if you dont the thing is that the Doctors Field in  SpecializationType needs the SpecializationId fetched in the RootQuery specializations Field.

I guess i didn't explain good what i went through.

Base line is as far as I understand we have to dynamically create selectors which the linq should use to project the entity.

I'm posting my approach here:

    public class RootQuery : EfObjectGraphType
{
    public RootQuery(IEfGraphQLService efGraphQlService, ISpecializationGraphQlServices specializationServices,
        IDoctorGraphQlServices doctorServices, ScheduleDbContext dbContext) : base(efGraphQlService)
    {
        Name = "Query";

        FieldAsync<ListGraphType<SpecializationType>>("specializations"
            , resolve: async ctx => {

                var selectedFields = GraphQLResolverContextHelpers.GetFirstLevelLeavesNamesPascalCase(ctx.SubFields);
                var expression = BuildLinqSelectorObject.DynamicSelectGenerator<Specializations>(selectedFields.ToArray());

                return await specializationServices.ListAsync(selector: expression);
            });
    }
}

SpecializationType

 public class SpecializationType : EfObjectGraphType<Specializations>
{
    public SpecializationType(IEfGraphQLService graphQlService
        , IDataLoaderContextAccessor accessor, IDoctorGraphQlServices doctorServices)
        : base(graphQlService)
    {
        Field(p => p.SpecializationId);
        Field(p => p.Code);
        Field(p => p.SpecializationName);
        Field<ListGraphType<DoctorType>, IEnumerable<Doctors>>()
            .Name("doctors")
            .ResolveAsync(ctx =>
            {

                var selectedFields = GraphQLResolverContextHelpers.GetFirstLevelLeavesNamesPascalCase(ctx.SubFields);
                selectedFields = GraphQLResolverContextHelpers.AppendParrentNodeToEachItem(selectedFields, parentNode: "Doctor");
                selectedFields = selectedFields.Union(new[] { "Specializations_SpecializationId" });

                var expression = BuildLinqSelectorObject.BuildSelector<SpecializationsDoctors, SpecializationsDoctors>(selectedFields);

                var doctorsLoader = accessor.Context
                    .GetOrAddCollectionBatchLoader<int, Doctors>(
                        "GetDoctorsBySpecializationId"
                        , (collection, token) =>
                        {
                            return doctorServices.GetDoctorsBySpecializationIdAsync(collection, token, expression);
                        });
                return doctorsLoader.LoadAsync(ctx.Source.SpecializationId);
            });
    }
}

DoctorsServices:

public class DoctorGraphQlServices : IDoctorGraphQlServices
{
    public ScheduleDbContext _dbContext { get; set; }

    public DoctorGraphQlServices(ScheduleDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<List<Doctors>> ListAsync(int? specializationId = null)
    {
        var doctors = _dbContext.Doctors.AsQueryable();

        if(specializationId != null)
        {
            doctors = doctors.Where(d => d.Specializations.Any(s => s.Specializations_SpecializationId == specializationId));
        }

        return await doctors.ToListAsync();
    }

    public async Task<ILookup<int, Doctors>> GetDoctorsBySpecializationIdAsync(IEnumerable<int> specializationIds, CancellationToken token, Expression<Func<SpecializationsDoctors, SpecializationsDoctors>> selector = null)
    {
        var doctors = await _dbContext.SpecializationsDoctors
            .Include(s => s.Doctor)
            .Where(spDocs => specializationIds.Any(sp => sp == spDocs.Specializations_SpecializationId))
            .Select(selector: selector)
            .ToListAsync();

        return doctors.ToLookup(i => i.Specializations_SpecializationId, i => i.Doctor);
    }

}

SpecializationServices

public class SpeciaizationGraphQlServices : ISpecializationGraphQlServices
{

    public ScheduleDbContext _dbContext { get; set; }

    public SpeciaizationGraphQlServices(ScheduleDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<dynamic> ListAsync(string doctorId = null, Expression<Func<Specializations, Specializations>> selector = null)
    {
        var specializations = _dbContext.Specializations.AsQueryable();

        if (!string.IsNullOrEmpty(doctorId))
        {
            specializations = specializations.Where(s => s.Doctors.Any(d => d.Doctors_Id == doctorId));
        }

        return await specializations.Select(selector).ToListAsync();

    }

    public async Task<ILookup<string, Specializations>> GetSpecializationsByDoctorIdAsync(IEnumerable<string> doctorIds, CancellationToken token)
    {
        var specializations = await _dbContext.SpecializationsDoctors
            .Include(s => s.Specialization)
            .Where(spDocs => doctorIds.Any(sp => sp == spDocs.Doctors_Id))
            .ToListAsync();

        return specializations.ToLookup(i => i.Doctors_Id, i => i.Specialization);
    }

    public IQueryable<Specializations> List(string doctorId = null)
    {
        var specializations = _dbContext.Specializations.AsQueryable();

        if (!string.IsNullOrEmpty(doctorId))
        {
            specializations = specializations.Where(s => s.Doctors.Any(d => d.Doctors_Id == doctorId));
        }

        return specializations;
    }
}

This post has become pretty large, sorry for the span..

Body:
To enable automatic fields projection, having your DB context set up as usual for .NET 6, add hotchocolate server:

dotnet add package HotChocolate.Data.EntityFramework

Expose some data to it:

public class MyQueries
{
    [UseProjection] // Enables field projection
    public IQueryable<Book> Books([Service] MyContext db) => db.Books;
}

Enable it in Program.cs:

builder.Services.AddGraphQLServer().AddQueryType<MyQueries>().AddProjections();
...
app.MapGraphQL("/graphql");

That should be enough to ensure automatic db fields projection. Now you can run GraphQL queries via builder generated at /graphql/, while monitoring SQL via MyContext.Database.Log = Console.Write;


来源: stackexchange

问:
flutter unsafe unchecked operation and overtiding a deprecated api errors
I am getting the following errors:

```<code>Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.13.4/android/src/main/java/io/flutter/plugins/firebase/cloudfirestore/CloudFirestorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/share-0.6.3+6/android/src/main/java/io/flutter/plugins/share/SharePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/path_provider-1.6.5/android/src/main/java/io/flutter/plugins/pathprovider/PathProviderPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/square_in_app_payments-1.3.0/android/src/main/java/sqip/flutter/internal/CardEntryModule.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code>```

Steps taken to resolve this:

Updated dependencies to the following:

```<code>cupertino_icons: ^0.1.3
  firebase_core: ^0.4.4+2
  firebase_auth: ^0.15.5+2
  google_sign_in: ^4.1.4
  image_picker: ^0.6.3+4
  cloud_firestore: ^0.13.4
  percent_indicator: ^2.1.1+1
  uuid: ^2.0.4
  share: ^0.6.3+6
  path_provider: ^1.6.5
  barcode_scan: ^2.0.1
  intl: ^0.16.1
  square_in_app_payments: ^1.3.0
  http: ^0.12.0+4
  firebase_storage: ^3.1.3
  firebase_crashlytics: ^0.1.3
  firebase_dynamic_links: ^0.5.0+11
</code>```

Updated gradle file to:

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:3.5.3'
    classpath 'com.google.gms:google-services:4.3.3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'io.fabric.tools:gradle:1.31.0'
}
</code>```

Also changed grade wrapper to gradle-6.0.1-all.zip.

but no luck. I have spend entire day to resolve this but have run out of options. Anyone can help, please?

My App/Gradle file:

```<code>    def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
//    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
    throw new FileNotFoundException ("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 29
    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "my application package name"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode  18 //flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            multiDexKeepFile file('multidex-config.txt')
            minifyEnabled true //  - true done
            useProguard false //  - true done

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

}

apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
</code>```

答:
Add this to your project level build.gradle. in allprojects. See below for better understanding.

```<code>gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.compilerArgs << "-Xlint:deprecation"
    }
}
</code>```

finally it will be like this below:

```<code>allprojects {
repositories {
    google()
    mavenCentral()
}
gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.compilerArgs << "-Xlint:deprecation"
    }
  }
}
</code>```

and Set multiDexEnabled to true in your project/android/app/build.gradle file.

```<code>defaultConfig {
  ......
   multiDexEnabled true
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting the following errors:

Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/cloud_firestore-0.13.4/android/src/main/java/io/flutter/plugins/firebase/cloudfirestore/CloudFirestorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/share-0.6.3+6/android/src/main/java/io/flutter/plugins/share/SharePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/path_provider-1.6.5/android/src/main/java/io/flutter/plugins/pathprovider/PathProviderPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: /Users/D/flutter/.pub-cache/hosted/pub.dartlang.org/square_in_app_payments-1.3.0/android/src/main/java/sqip/flutter/internal/CardEntryModule.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Steps taken to resolve this:

Updated dependencies to the following:

cupertino_icons: ^0.1.3
  firebase_core: ^0.4.4+2
  firebase_auth: ^0.15.5+2
  google_sign_in: ^4.1.4
  image_picker: ^0.6.3+4
  cloud_firestore: ^0.13.4
  percent_indicator: ^2.1.1+1
  uuid: ^2.0.4
  share: ^0.6.3+6
  path_provider: ^1.6.5
  barcode_scan: ^2.0.1
  intl: ^0.16.1
  square_in_app_payments: ^1.3.0
  http: ^0.12.0+4
  firebase_storage: ^3.1.3
  firebase_crashlytics: ^0.1.3
  firebase_dynamic_links: ^0.5.0+11

Updated gradle file to:

dependencies {
    classpath 'com.android.tools.build:gradle:3.5.3'
    classpath 'com.google.gms:google-services:4.3.3'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'io.fabric.tools:gradle:1.31.0'
}

Also changed grade wrapper to gradle-6.0.1-all.zip.

but no luck. I have spend entire day to resolve this but have run out of options. Anyone can help, please?

My App/Gradle file:

    def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
//    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
    throw new FileNotFoundException ("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 29
    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "my application package name"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode  18 //flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    signingConfigs {
        release {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            multiDexKeepFile file('multidex-config.txt')
            minifyEnabled true //  - true done
            useProguard false //  - true done

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

}

apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'

Body:
Add this to your project level build.gradle. in allprojects. See below for better understanding.

gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.compilerArgs << "-Xlint:deprecation"
    }
}

finally it will be like this below:

allprojects {
repositories {
    google()
    mavenCentral()
}
gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.compilerArgs << "-Xlint:deprecation"
    }
  }
}

and Set multiDexEnabled to true in your project/android/app/build.gradle file.

defaultConfig {
  ......
   multiDexEnabled true
}


问:
PackageNotInstalledError: Package is not installed in prefix
conda update conda >> successful

conda update anaconda >> gives me error saying package is not installed in prefix.

I have single installation of Python distribution on my system. How do I solve this issue?

```<code>(base) C:\Users\asukumari>conda info
</code>```

```<code> active environment : base
active env location : C:\Users\asukumari\AppData\Local\Continuum\anaconda3
        shell level : 1
   user config file : C:\Users\asukumari\.condarc  populated config files : C:\Users\asukumari\.condarc
      conda version : 4.5.9
conda-build version : 3.4.1
     python version : 3.6.4.final.0
   base environment : C:\Users\asukumari\AppData\Local\Continuum\anaconda3  (writable)
       channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                      https://repo.anaconda.com/pkgs/main/noarch
                      https://repo.anaconda.com/pkgs/free/win-64
                      https://repo.anaconda.com/pkgs/free/noarch
                      https://repo.anaconda.com/pkgs/r/win-64
                      https://repo.anaconda.com/pkgs/r/noarch
                      https://repo.anaconda.com/pkgs/pro/win-64
                      https://repo.anaconda.com/pkgs/pro/noarch
                      https://repo.anaconda.com/pkgs/msys2/win-64
                      https://repo.anaconda.com/pkgs/msys2/noarch
      package cache : C:\Users\asukumari\AppData\Local\Continuum\anaconda3\pkgs
                      C:\Users\asukumari\AppData\Local\conda\conda\pkgs
   envs directories : C:\Users\asukumari\AppData\Local\Continuum\anaconda3\envs
                      C:\Users\asukumari\AppData\Local\conda\conda\envs
                      C:\Users\asukumari\.conda\envs
           platform : win-64
         user-agent : conda/4.5.9 requests/2.18.4 CPython/3.6.4 Windows/10 Windows/10.0.16299
      administrator : False
         netrc file : None
       offline mode : False
</code>```

答:
This worked for me:

conda update -n base -c defaults conda
```

Body:
conda update conda >> successful

conda update anaconda >> gives me error saying package is not installed in prefix.

I have single installation of Python distribution on my system. How do I solve this issue?

(base) C:\Users\asukumari>conda info

 active environment : base
active env location : C:\Users\asukumari\AppData\Local\Continuum\anaconda3
        shell level : 1
   user config file : C:\Users\asukumari\.condarc  populated config files : C:\Users\asukumari\.condarc
      conda version : 4.5.9
conda-build version : 3.4.1
     python version : 3.6.4.final.0
   base environment : C:\Users\asukumari\AppData\Local\Continuum\anaconda3  (writable)
       channel URLs : https://repo.anaconda.com/pkgs/main/win-64
                      https://repo.anaconda.com/pkgs/main/noarch
                      https://repo.anaconda.com/pkgs/free/win-64
                      https://repo.anaconda.com/pkgs/free/noarch
                      https://repo.anaconda.com/pkgs/r/win-64
                      https://repo.anaconda.com/pkgs/r/noarch
                      https://repo.anaconda.com/pkgs/pro/win-64
                      https://repo.anaconda.com/pkgs/pro/noarch
                      https://repo.anaconda.com/pkgs/msys2/win-64
                      https://repo.anaconda.com/pkgs/msys2/noarch
      package cache : C:\Users\asukumari\AppData\Local\Continuum\anaconda3\pkgs
                      C:\Users\asukumari\AppData\Local\conda\conda\pkgs
   envs directories : C:\Users\asukumari\AppData\Local\Continuum\anaconda3\envs
                      C:\Users\asukumari\AppData\Local\conda\conda\envs
                      C:\Users\asukumari\.conda\envs
           platform : win-64
         user-agent : conda/4.5.9 requests/2.18.4 CPython/3.6.4 Windows/10 Windows/10.0.16299
      administrator : False
         netrc file : None
       offline mode : False


问:
java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher
i'm trying run my app on Lollipop devices, after Lollipop the app run fine, but, in 5.0 or less version of Android my app crash and this error returned:

Process: com.myApp.agr1010, PID: 4353 java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher

But, my Build.Gradle already include MultiDexEnable true

This my Build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.myApp.agr1010"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 3
        versionName "0.8.9-Alpha Release"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation('com.google.guava:guava:29.0-jre')
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'com.google.android.gms:play-services-auth:18.1.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'androidx.work:work-runtime:2.4.0'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.0-rc01' // Material Design Google
    implementation 'androidx.core:core:1.3.1'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.android.support:multidex:1.0.3'
    // and a lot of implementation...
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.firebase-perf'
apply plugin: 'com.google.firebase.crashlytics'
</code>```

And my complete logCat:

```<code>E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
    Process: com.myApp.agr1010, PID: 4353
    java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher
        at com.google.common.base.Splitter.on(Splitter.java:127)
        at io.grpc.internal.GrpcUtil.<clinit>(GrpcUtil.java:197)
        at io.grpc.internal.AbstractManagedChannelImplBuilder.<clinit>(AbstractManagedChannelImplBuilder.java:90)
        at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:46)
        at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:26)
        at io.grpc.ManagedChannelBuilder.forTarget(ManagedChannelBuilder.java:76)
        at com.google.firebase.firestore.remote.GrpcCallProvider.initChannel(GrpcCallProvider.java:113)
        at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6(GrpcCallProvider.java:256)
        at com.google.firebase.firestore.remote.GrpcCallProvider$$Lambda$5.call(GrpcCallProvider.java)
        at com.google.android.gms.tasks.zzz.run(com.google.android.gms:play-services-tasks@@17.0.2:2)
        at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0(ThrottledForwardingExecutor.java:54)
        at com.google.firebase.firestore.util.ThrottledForwardingExecutor$$Lambda$1.run(ThrottledForwardingExecutor.java)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)
</code>```

I already tried add MultiDex to Androidx and android support, but, same problem happens again, how i can solve this?

答:
If you replace

```<code>implementation('com.google.guava:guava:29.0-jre')
</code>```

for this

```<code>implementation ('com.google.guava:guava') {
    version {
        strictly '29.0-android'
    }
}
</code>```

it should work. (You can use this guava version, or any later version)

Body:
i'm trying run my app on Lollipop devices, after Lollipop the app run fine, but, in 5.0 or less version of Android my app crash and this error returned:

Process: com.myApp.agr1010, PID: 4353 java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher

But, my Build.Gradle already include MultiDexEnable true

This my Build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.myApp.agr1010"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 3
        versionName "0.8.9-Alpha Release"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation('com.google.guava:guava:29.0-jre')
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'com.google.android.gms:play-services-auth:18.1.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.navigation:navigation-fragment:2.3.0'
    implementation 'androidx.navigation:navigation-ui:2.3.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'androidx.work:work-runtime:2.4.0'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.0-rc01' // Material Design Google
    implementation 'androidx.core:core:1.3.1'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.android.support:multidex:1.0.3'
    // and a lot of implementation...
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.firebase-perf'
apply plugin: 'com.google.firebase.crashlytics'

And my complete logCat:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
    Process: com.myApp.agr1010, PID: 4353
    java.lang.NoClassDefFoundError: com.google.common.base.CharMatcher
        at com.google.common.base.Splitter.on(Splitter.java:127)
        at io.grpc.internal.GrpcUtil.<clinit>(GrpcUtil.java:197)
        at io.grpc.internal.AbstractManagedChannelImplBuilder.<clinit>(AbstractManagedChannelImplBuilder.java:90)
        at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:46)
        at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget(OkHttpChannelProvider.java:26)
        at io.grpc.ManagedChannelBuilder.forTarget(ManagedChannelBuilder.java:76)
        at com.google.firebase.firestore.remote.GrpcCallProvider.initChannel(GrpcCallProvider.java:113)
        at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6(GrpcCallProvider.java:256)
        at com.google.firebase.firestore.remote.GrpcCallProvider$$Lambda$5.call(GrpcCallProvider.java)
        at com.google.android.gms.tasks.zzz.run(com.google.android.gms:play-services-tasks@@17.0.2:2)
        at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0(ThrottledForwardingExecutor.java:54)
        at com.google.firebase.firestore.util.ThrottledForwardingExecutor$$Lambda$1.run(ThrottledForwardingExecutor.java)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

I already tried add MultiDex to Androidx and android support, but, same problem happens again, how i can solve this?

Body:
If you replace

implementation('com.google.guava:guava:29.0-jre')

for this

implementation ('com.google.guava:guava') {
    version {
        strictly '29.0-android'
    }
}

it should work. (You can use this guava version, or any later version)


问:
Attempted to drop columns containing foreign keys and received error message
I am using phpMyAdmin version 3.3.10.3 to manage my database.

I am using InnoDB and foreign key contraints.

I have attempted to drop several columns from a table. These columns are foreign keys referencing other tables.

```<code>ALTER TABLE `product`
  DROP `c_status_id`,
  DROP `o_certification_id`,
  DROP `g_free_certification_id`,
  DROP `gm_certification_id`,
  DROP `n_certification_id`;
</code>```

Upon attempt of the query I received the following error message.

```<code>#1025 - Error on rename of ' /#sql-ea2_38d9f' to ' /product' (errno: 150
</code>```

答:
You must first drop the foreign key relationship before you drop the column referenced in the relationship.

```<code>ALTER TABLE 'TABLE_NAME' DROP FOREIGN KEY 'NAME_OF_FOREIGN_KEY'
</code>```

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

ContentLicense: CC BY-SA 3.0

Body:
I am using phpMyAdmin version 3.3.10.3 to manage my database.

I am using InnoDB and foreign key contraints.

I have attempted to drop several columns from a table. These columns are foreign keys referencing other tables.

ALTER TABLE `product`
  DROP `c_status_id`,
  DROP `o_certification_id`,
  DROP `g_free_certification_id`,
  DROP `gm_certification_id`,
  DROP `n_certification_id`;

Upon attempt of the query I received the following error message.

#1025 - Error on rename of ' /#sql-ea2_38d9f' to ' /product' (errno: 150

Body:
You must first drop the foreign key relationship before you drop the column referenced in the relationship.

ALTER TABLE 'TABLE_NAME' DROP FOREIGN KEY 'NAME_OF_FOREIGN_KEY'

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html


问:
PowerShell module installed manually. cmdlets found with help but not recognized when executed
I have a machine i would like to install a module on, specifically SwisPowerShell for working with SolarWinds. Internet is disabled on it so i cant use install-module, so i manually downloaded the .nupkg from another machine and went through the steps of unpacking the files into the correct folders. https://learn.microsoft.com/en-us/powershell/scripting/gallery/how-to/working-with-packages/manual-download?view=powershell-7.2. all the .dll files and the windows powershell datafile i have tried in both directories "C:\Program Files\WindowsPowerShell\Modules\SwisPowerShell\3.1.0.343" and "C:\Users\username\Documents\WindowsPowerShell\Modules\SwisPowerShell\3.1.0.343". Importing the module with "import-module -name SwisPowerShell -Global -force -Verbose" shows that everything loads correctly, but then running "get-module SwisPowerShell -Verbose" returns nothing. even loading each dll individually with "add-type -path "C:...\somefile.dll" shows nothing. running "get-module -ListAvailable" shows the module in both (or either) directories as they should be. using "get-help cmdletname" and "get-command cmdletname" shows the correct cmdlet definitions. trying to run any of the cmdlets returns "The term 'connect-swis' is not recognized as the name of a cmdlet, function... yada yadda" for all of the cmdlets. its like powershell sees the files but refuses to use them. Am i missing a step that tells powershell that this is a valid module to use? could it be blocked somehow? what extra steps does install-module do that a manual install does not that i could try?</p>

答: Try running process monitor while installing on another machine.  You might find out it's doing some registry changes too.</p>


问:
Migration to react-router-dom v6
I've had a problem with migration between react-router-dom v5 to v6. After update my package I do a few upgrades in the code. Below is my version of code in v5 and with v6 and also Routing component which give me a problem.

v5

```<code>export default function App() {
  return (
    <div className="App">
      <Switch>
        <AppContextProvider>
          <Routing />
        </AppContextProvider>
      </Switch>
    </div>
  );
}
</code>```

v6

```<code>export default function App() {
  return (
    <div className="App">
      <AppContextProvider>
        <Routes>
          <Routing />
        </Routes>
      </AppContextProvider>
    </div>
  );
}
</code>```

<Routing /> component

```<code>const Routing = (): JSX.Element => {
  return (
    <>
      {publicRouting.map(({ path, component }, i) => (
        <Route key={i} path={path} element={component} />
      ))}
      {isAuthenticated() && (
        <Main>
          {routing.map(({ path, component }, i) => (
            <Route  key={i} path={path} element={component} />
          ))}
        </Main>
      )}
    </>
  );
};
</code>```

Right now console throw me this error:

```<code>index.tsx:19 Uncaught Error: [Routing] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
</code>```

can someone tell me how to solve this problem? It looks like this component has incompatible type and cannot go as children between Routes component, but why they changed it? How to correct my Routing component?

Thanks for any help!

答:
In react-router-dom v6 the Routes component can have only Route or React.Fragment as a valid child, and the Route component can only have Routes or another Route component as parent.

The Routes component effectively replaced the RRDv5 Switch component in that it handles the route matching and rendering logic, and is now required to directly wrap the Route components it's managing.

Move the Routes component into Routing to wrap directly the Route components being mapped.

```<code>export default function App() {
  return (
    <div className="App">
      <AppContextProvider>
        <Routing />
      </AppContextProvider>
    </div>
  );
}
</code>```

...

```<code>const Routing = (): JSX.Element => {
  return (
    <>
      <Routes>
        {publicRouting.map(({ path, component }, i) => (
          <Route key={i} path={path} element={component} />
        ))}
      </Routes>
      {isAuthenticated() && (
        <Main>
          <Routes>
            {routing.map(({ path, component }, i) => (
              <Route  key={i} path={path} element={component} />
            ))}
          </Routes>
        </Main>
      )}
    </>
  );
};
</code>```

Title: Migration to react-router-dom v6

Body:
I've had a problem with migration between react-router-dom v5 to v6. After update my package I do a few upgrades in the code. Below is my version of code in v5 and with v6 and also Routing component which give me a problem.

v5

export default function App() {
  return (

      <Switch>
        <AppContextProvider>
          <Routing />
        </AppContextProvider>
      </Switch>

  );
}

v6

export default function App() {
  return (

      <AppContextProvider>
        <Routes>
          <Routing />
        </Routes>
      </AppContextProvider>

  );
}

<Routing /> component

const Routing = (): JSX.Element => {
  return (
    <>
      {publicRouting.map(({ path, component }, i) => (
        <Route key={i} path={path} element={component} />
      ))}
      {isAuthenticated() && (

          {routing.map(({ path, component }, i) => (
            <Route  key={i} path={path} element={component} />
          ))}

      )}
    </>
  );
};

Right now console throw me this error:

index.tsx:19 Uncaught Error: [Routing] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

can someone tell me how to solve this problem? It looks like this component has incompatible type and cannot go as children between Routes component, but why they changed it? How to correct my Routing component?

Thanks for any help!

Body:
In react-router-dom v6 the Routes component can have only Route or React.Fragment as a valid child, and the Route component can only have Routes or another Route component as parent.

The Routes component effectively replaced the RRDv5 Switch component in that it handles the route matching and rendering logic, and is now required to directly wrap the Route components it's managing.

Move the Routes component into Routing to wrap directly the Route components being mapped.

export default function App() {
  return (
    <div className="App">
      <AppContextProvider>
        <Routing />
      </AppContextProvider>
    </div>
  );
}

...

const Routing = (): JSX.Element => {
  return (
    <>
      <Routes>
        {publicRouting.map(({ path, component }, i) => (
          <Route key={i} path={path} element={component} />
        ))}
      </Routes>
      {isAuthenticated() && (
        <Main>
          <Routes>
            {routing.map(({ path, component }, i) => (
              <Route  key={i} path={path} element={component} />
            ))}
          </Routes>
        </Main>
      )}
    </>
  );
};


问:
Asp.net Error while trying to create a bundle - Only application relative URLs (~/url) are allowed
I am getting an error, when trying to include a css file in the bundle, it says that Asp.net MVC Bundle - Only application relative URLs (~/url) are allowed.

Here is the code:

```<code>bundles.Add(new StyleBundle("~/bundles/lib/anim_css").Include(
                "~Vendor/lib/animate/animate.min.css", new CssRewriteUrlTransform()));
</code>```

Where the Vendor folder is the source folder of that css. That folder is included in the project, being like that ...ProjectFolderName/Vendor

This did not help

答: ~Vendor/lib/animate/animate.min.css is not a legal relative URL. It needs to be ~/Vendor/lib/animate/animate.min.css

Body:
I am getting an error, when trying to include a css file in the bundle, it says that Asp.net MVC Bundle - Only application relative URLs (~/url) are allowed.

Here is the code:

bundles.Add(new StyleBundle("~/bundles/lib/anim_css").Include(
                "~Vendor/lib/animate/animate.min.css", new CssRewriteUrlTransform()));

Where the Vendor folder is the source folder of that css. That folder is included in the project, being like that ...ProjectFolderName/Vendor

This did not help


问:
ID repeats how do i reduce
I have two tables and a linking table between them,
One of users and one of vacations and a linking table of likes,
I try to bring up all the vacations that a certain user did not like
And I get the same vacation twice because two other people liked her.
Is there a way NSQL will bring me just one of them.

These are the users

```<code>id  u_name

1   Gabi    Ashkenazi
2   Johnny  Tribiani
3   Bernie  Stinson
4   Goku    son
5   Bo  Bennett
</code>```

These are the vacations

```<code>id  v_name

1   Venice
2   Rome
3   Maldives
4   Tokyo
5   Israel
6   Berlin
7   Prague
8   never Land
</code>```

And the linking table looks like this

```<code>
id  u_id   v_id
5   2       7
3   1       6
4   2       5
9   4       4

</code>```

答:
Would something like this work for you? Find all the vacations that Johnny likes and then return the list that he doesn't like:</p>
```<code>SELECT *
FROM Vacations
WHERE v_name not IN
(
  SELECT v_name
  FROM Users
  JOIN Linking
  ON Users.ID = Linking.U_id
  JOIN Vacations On Linking.v_id = Vacations.ID
  WHERE Users.ID = 2
);
</code>```

Title: ID repeats how do i reduce

Body:
I have two tables and a linking table between them,
One of users and one of vacations and a linking table of likes,
I try to bring up all the vacations that a certain user did not like
And I get the same vacation twice because two other people liked her.
Is there a way NSQL will bring me just one of them.

These are the users

id  u_name

1   Gabi    Ashkenazi
2   Johnny  Tribiani
3   Bernie  Stinson
4   Goku    son
5   Bo  Bennett

These are the vacations

id  v_name

1   Venice
2   Rome
3   Maldives
4   Tokyo
5   Israel
6   Berlin
7   Prague
8   never Land

And the linking table looks like this

id  u_id   v_id
5   2       7
3   1       6
4   2       5
9   4       4

Body:
Would something like this work for you? Find all the vacations that Johnny likes and then return the list that he doesn't like:

SELECT *
FROM Vacations
WHERE v_name not IN
(
  SELECT v_name
  FROM Users
  JOIN Linking
  ON Users.ID = Linking.U_id
  JOIN Vacations On Linking.v_id = Vacations.ID
  WHERE Users.ID = 2
);


问:
Understanding an array of pointers to an object in c++
There are 3 types of planes.

A nA321 which has a max capacity of 10 containers

nB777 which has a max capacity of 32 containers

nB787 which has a max capacity of 40 containers

I want to index through the list and create an Airplane object and store the respective value. My for loop will create a new Airplane object that is set to 10. How can I dynamically set the respective plane types to the corresponding max capacity? The code currently outputs the address, for example:

Airplane 1 maximum load 0xffe

I am trying to print the following:

```<code>Airplane 1 maximum load 10
Airplane 2 maximum load 10
Airplane 3 maximum load 10
Airplane 4 maximum load 10
Airplane 5 maximum load 32
Airplane 6 maximum load 32
Airplane 7 maximum load 40
</code>```

My code

```<code>#include <iostream>

using namespace std;

class Airplane
{
    public:
        Airplane(int n); // the maximum capacity of the airplane
        int maxLoad(void) const;
        int currentLoad(void) const;
        bool addContainers(int n);
    private:
        const int maxContainers;
        int numContainers;
};

Airplane::Airplane(int n):maxContainers(n){
    n = maxContainers;
}

int Airplane::maxLoad(void) const{
    return maxContainers;
}

int Airplane::currentLoad(void) const{
    return numContainers;
}

class Airline
{
    public:
        Airline(int nA321, int nB777, int nB787);
        ~Airline(void);
        void addShipment(int size);
        void printSummary(void) const; // prints a list of airplanes with their current and maximum load.

    private:
        const int nAirplanes; // total # of airplanes used by airline
        Airplane** airplaneList; // array of pointers to Airplane objects
};

Airline::Airline(int nA321, int nB777, int nB787):nAirplanes(nA321 + nB777 + nB787){
    airplaneList = new Airplane*[nAirplanes];
    for ( int i = 0; i < this->nAirplanes; i++ ){
        airplaneList[i] = new Airplane(10);
        airplaneList[i] -> maxLoad();
        cout << "Airline " << i+1 << " maximum load " << airplaneList[i] << endl;
    }
}

Airline::~Airline(void){}

int main(void)
{
    // create an Airline with 4 A321, 2 B777 and 1 B787
    Airline airline(4,2,1);
    cout << "Assignment complete" << endl;
}
</code>```

答:
You can use runtime polymorphism:

Make your Airplane class virtual pure, so you cannot really instantiate an Airplane.

```<code>    virtual int maxLoad() const = 0;
</code>```

Add 3 subclasses to your Airplane class, one for each type of plane. These subclasses will define the maximum number of containers, for example, using an static inline const member.

```<code>    static inline const int maxContainers{10};
</code>```

  They will also implement the maxLoad virtual method to return maxContainers.

```<code>    virtual int maxLoad() const override { return maxContainers; }
</code>```

For each airline, keep the airplaneList as an array of Airplane*, but then assign a specific plane instance to each of those pointers:

```<code>    airplaneList = new Airplane*[nAirplanes];
    int size = 0;
    for (int i = 0; i < nA321; i++, size++) { airplaneList[size] = new A321(); }
    for (int i = 0; i < nB777; i++, size++) { airplaneList[size] = new B777(); }
    for (int i = 0; i < nB787; i++, size++) { airplaneList[size] = new B787(); }
</code>```

And two important points regarding destructors:

Make Airplane destructor virtual.

 Since airplaneList is an array of Airplane pointers created through new, at some point we should do a delete of each of those pointers, and that is going to invoke the Airplane destructor; however, since we actually created instances of subclasses of Airplane (e.g. with new A321()), we need the destructor of the subclass to be executed.

 That won't be possible if the Airplane destructor is not virtual.

```<code>    virtual ~Airplane() {};
</code>```

Airline constructor is doing a new[] for the airplane list, and a new for each airplane. Airline destructor should do the correspondings delete[] and delete.

```<code>Airline::~Airline()
{
    for (int i = 0; i < nAirplanes; i++) { delete airplaneList[i]; }
    delete[] airplaneList;
}
</code>```

[Demo]

```<code>// Outputs:
//
//   Airplane 1 (A321): maximum load = 10
//   Airplane 2 (A321): maximum load = 10
//   Airplane 3 (A321): maximum load = 10
//   Airplane 4 (A321): maximum load = 10
//   Airplane 5 (B777): maximum load = 32
//   Airplane 6 (B777): maximum load = 32
//   Airplane 7 (B787): maximum load = 40
//   Assignment complete
</code>```

As an aside note, using a std::vector for the airplaneList, and smart pointers (e.g. std::unique_ptr) to the airplane instances would simplify the code a lot:

You wouldn't need the heap allocation for the airplane list.

You wouldn't need to care about deleting the heap instances for the airplanes and the airplane list.

[Demo]

class Airline
{
public:
    Airline(int nA321, int nB777, int nB787);
    ~Airline() {}
    void addShipment(int size);
    void printSummary(void) const; // prints a list of airplanes with their current and maximum load.

private:
    int nAirplanes{}; // total # of airplanes used by airline
    std::vector<std::unique_ptr<Airplane>> airplaneList{}; // array of pointers to Airplane objects
};

Airline::Airline(int nA321, int nB777, int nB787)
: nAirplanes(nA321 + nB777 + nB787)
{
    for (auto i = 0; i < nA321; i++) { airplaneList.emplace_back(std::make_unique<A321>()); }
    for (auto i = 0; i < nB777; i++) { airplaneList.emplace_back(std::make_unique<B777>()); }
    for (auto i = 0; i < nB787; i++) { airplaneList.emplace_back(std::make_unique<B787>()); }

    for (size_t i = 0; i < airplaneList.size(); i++)
    {
        std::cout
            << "Airplane " << i+1
            << " (" << airplaneList[i]->getName() << ")"
            << ": maximum load = " << airplaneList[i]->maxLoad() << "\n";
    }
}
```

Body:
There are 3 types of planes.

A nA321 which has a max capacity of 10 containers

nB777 which has a max capacity of 32 containers

nB787 which has a max capacity of 40 containers

I want to index through the list and create an Airplane object and store the respective value. My for loop will create a new Airplane object that is set to 10. How can I dynamically set the respective plane types to the corresponding max capacity? The code currently outputs the address, for example:

Airplane 1 maximum load 0xffe

I am trying to print the following:

Airplane 1 maximum load 10
Airplane 2 maximum load 10
Airplane 3 maximum load 10
Airplane 4 maximum load 10
Airplane 5 maximum load 32
Airplane 6 maximum load 32
Airplane 7 maximum load 40

My code

#include <iostream>

using namespace std;

class Airplane
{
    public:
        Airplane(int n); // the maximum capacity of the airplane
        int maxLoad(void) const;
        int currentLoad(void) const;
        bool addContainers(int n);
    private:
        const int maxContainers;
        int numContainers;
};

Airplane::Airplane(int n):maxContainers(n){
    n = maxContainers;
}

int Airplane::maxLoad(void) const{
    return maxContainers;
}

int Airplane::currentLoad(void) const{
    return numContainers;
}

class Airline
{
    public:
        Airline(int nA321, int nB777, int nB787);
        ~Airline(void);
        void addShipment(int size);
        void printSummary(void) const; // prints a list of airplanes with their current and maximum load.

    private:
        const int nAirplanes; // total # of airplanes used by airline
        Airplane** airplaneList; // array of pointers to Airplane objects
};

Airline::Airline(int nA321, int nB777, int nB787):nAirplanes(nA321 + nB777 + nB787){
    airplaneList = new Airplane*[nAirplanes];
    for ( int i = 0; i < this->nAirplanes; i++ ){
        airplaneList[i] = new Airplane(10);
        airplaneList[i] -> maxLoad();
        cout << "Airline " << i+1 << " maximum load " << airplaneList[i] << endl;
    }
}

Airline::~Airline(void){}

int main(void)
{
    // create an Airline with 4 A321, 2 B777 and 1 B787
    Airline airline(4,2,1);
    cout << "Assignment complete" << endl;
}

Body:
You can use runtime polymorphism:

Make your Airplane class virtual pure, so you cannot really instantiate an Airplane.

    virtual int maxLoad() const = 0;

Add 3 subclasses to your Airplane class, one for each type of plane. These subclasses will define the maximum number of containers, for example, using an static inline const member.

    static inline const int maxContainers{10};

  They will also implement the maxLoad virtual method to return maxContainers.

    virtual int maxLoad() const override { return maxContainers; }

For each airline, keep the airplaneList as an array of Airplane*, but then assign a specific plane instance to each of those pointers:

    airplaneList = new Airplane*[nAirplanes];
    int size = 0;
    for (int i = 0; i < nA321; i++, size++) { airplaneList[size] = new A321(); }
    for (int i = 0; i < nB777; i++, size++) { airplaneList[size] = new B777(); }
    for (int i = 0; i < nB787; i++, size++) { airplaneList[size] = new B787(); }

And two important points regarding destructors:

Make Airplane destructor virtual.

 Since airplaneList is an array of Airplane pointers created through new, at some point we should do a delete of each of those pointers, and that is going to invoke the Airplane destructor; however, since we actually created instances of subclasses of Airplane (e.g. with new A321()), we need the destructor of the subclass to be executed.

 That won't be possible if the Airplane destructor is not virtual.

    virtual ~Airplane() {};

Airline constructor is doing a new[] for the airplane list, and a new for each airplane. Airline destructor should do the correspondings delete[] and delete.

Airline::~Airline()
{
    for (int i = 0; i < nAirplanes; i++) { delete airplaneList[i]; }
    delete[] airplaneList;
}

[Demo]

// Outputs:
//
//   Airplane 1 (A321): maximum load = 10
//   Airplane 2 (A321): maximum load = 10
//   Airplane 3 (A321): maximum load = 10
//   Airplane 4 (A321): maximum load = 10
//   Airplane 5 (B777): maximum load = 32
//   Airplane 6 (B777): maximum load = 32
//   Airplane 7 (B787): maximum load = 40
//   Assignment complete

As an aside note, using a std::vector for the airplaneList, and smart pointers (e.g. std::unique_ptr) to the airplane instances would simplify the code a lot:

You wouldn't need the heap allocation for the airplane list.

You wouldn't need to care about deleting the heap instances for the airplanes and the airplane list.

[Demo]

class Airline
{
public:
    Airline(int nA321, int nB777, int nB787);
    ~Airline() {}
    void addShipment(int size);
    void printSummary(void) const; // prints a list of airplanes with their current and maximum load.

private:
    int nAirplanes{}; // total # of airplanes used by airline
    std::vector<std::unique_ptr<Airplane>> airplaneList{}; // array of pointers to Airplane objects
};

Airline::Airline(int nA321, int nB777, int nB787)
: nAirplanes(nA321 + nB777 + nB787)
{
    for (auto i = 0; i < nA321; i++) { airplaneList.emplace_back(std::make_unique<A321>()); }
    for (auto i = 0; i < nB777; i++) { airplaneList.emplace_back(std::make_unique<B777>()); }
    for (auto i = 0; i < nB787; i++) { airplaneList.emplace_back(std::make_unique<B787>()); }

    for (size_t i = 0; i < airplaneList.size(); i++)
    {
        std::cout
            << "Airplane " << i+1
            << " (" << airplaneList[i]->getName() << ")"
            << ": maximum load = " << airplaneList[i]->maxLoad() << "\n";
    }
}


问:
Convert QString to text with substitutes for HTML special characters (e.g. tags)
The user will be able to put in some text into a QLineEdit in a Qt environment. However, these input texts can contain HTML special characters. My aim is to convert this text by replacing all HTML special character occurences with substitutes.

A similar case is found in PHP with the htmlspecialchars() function http://php.net/manual/en/function.htmlspecialchars.php.

The main reason I want to do this is because I want to display the user input in a richtext QTextEdit and I don't want the user to be able to change HTML and I wish to be able to use HTML special characters without too much hassle.

How can this be achieved?

答:
In Qt5, it's QString::toHtmlEscaped, e.g.:

```<code>QString a = "Hello, <span class=\"name\">Bear</span>!";
// a will contain: Hello, <span class="name">Bear</span>!

QString b = a.toHtmlEscaped();
// b will contain: Hello, <span class="name">Bear</span>!
</code>```

This is direct equivalent of the htmlspecialchars in PHP. It replaces the  Qt::escape function (mentioned by Amartel), which does the same thing but is now obsolete.

The Qt::convertFromPlainText function (also mentioned by Amartel) still exists in Qt 5, but it does more than PHP's htmlspecialchars. Not only it replaces < with <, > with >, & with &, " with " but also does additional handling of whitespace characters (space, tab, line feed, etc) to make the generated HTML look visually similarly to the original plain text. Particularly, it may put
…
/
 for linefeeds, non-breaking spaces for spaces and multiple non-breaking spaces for tabs. I.e. this function is not just htmlspecialchars, it's even more comprehensive than nl2br(htmlspecialchars($s)) combination.

Note that unlike the PHP's htmlspecialchars with ENT_QUOTES, none of the Qt functions listed in this answer replace single quote (') with '/'. So, for example, QString html = ""; won't be safe, only QString html = ""; will. (However, as < is replaced and ' has no special meaning outside <…>, something like QString html = "" + s.toHtmlEscaped() + ""; would also be safe.)

Body:
In Qt5, it's QString::toHtmlEscaped, e.g.:

QString a = "Hello, <span class=\"name\">Bear</span>!";
// a will contain: Hello, <span class="name">Bear</span>!

QString b = a.toHtmlEscaped();
// b will contain: Hello, &lt;span class=&quot;name&quot;&gt;Bear&lt;/span&gt;!

This is direct equivalent of the htmlspecialchars in PHP. It replaces the  Qt::escape function (mentioned by Amartel), which does the same thing but is now obsolete.

The Qt::convertFromPlainText function (also mentioned by Amartel) still exists in Qt 5, but it does more than PHP's htmlspecialchars. Not only it replaces < with &lt;, > with &gt;, & with &amp;, " with &quot; but also does additional handling of whitespace characters (space, tab, line feed, etc) to make the generated HTML look visually similarly to the original plain text. Particularly, it may put <p>…</p>/<br> for linefeeds, non-breaking spaces for spaces and multiple non-breaking spaces for tabs. I.e. this function is not just htmlspecialchars, it's even more comprehensive than nl2br(htmlspecialchars($s)) combination.

Note that unlike the PHP's htmlspecialchars with ENT_QUOTES, none of the Qt functions listed in this answer replace single quote (') with &apos;/&#039;. So, for example, QString html = "<img alt='" + s.toHtmlEscaped() + "'>"; won't be safe, only QString html = "<img alt=\"" + s.toHtmlEscaped() + "\">"; will. (However, as < is replaced and ' has no special meaning outside <…>, something like QString html = "<b>" + s.toHtmlEscaped() + "</b>"; would also be safe.)


问:
Out Of Memory exception on System.Drawing.Image.FromFile()
I have an image uploader and cropper which creates thumbnails and I occasionally get an Out Of Memory exception on the following line:

```<code>Dim bm As Bitmap = System.Drawing.Image.FromFile(imageFile)
</code>```

The occurance of the error is tiny and very rare, but I always like to know what might be causing it. The imageFile variable is just a Server.MapPath to the path of the image.

I was curious if anyone had experience this issue previously and if they had any ideas what might be causing it? Is it the size of the image perhaps?

I can post the code if necessary and any supporting information I have, but would love to hear people's opinions on this one.

答:
I hit the same issue today while creating Thumbnail images for a folder full of images. It turns out that the "Out Of Memory" occured exactly at the same point each time. When I looked at the folder with the images to be converted I found that the file that was creating the problem was thumbs.db. I added some code to make sure that only image files were being converted and the issue was resolved.

My code is basically

```<code>For Each imageFile as FileInfo in fileList
If imageFile.Extension = ".jpg" Or imageFile.Extension = ".gif" Then
    ...proceed with the conversion
End If
Next
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
I have an image uploader and cropper which creates thumbnails and I occasionally get an Out Of Memory exception on the following line:

Dim bm As Bitmap = System.Drawing.Image.FromFile(imageFile)

The occurance of the error is tiny and very rare, but I always like to know what might be causing it. The imageFile variable is just a Server.MapPath to the path of the image.

I was curious if anyone had experience this issue previously and if they had any ideas what might be causing it? Is it the size of the image perhaps?

I can post the code if necessary and any supporting information I have, but would love to hear people's opinions on this one.

Body:
I hit the same issue today while creating Thumbnail images for a folder full of images. It turns out that the "Out Of Memory" occured exactly at the same point each time. When I looked at the folder with the images to be converted I found that the file that was creating the problem was thumbs.db. I added some code to make sure that only image files were being converted and the issue was resolved.

My code is basically

For Each imageFile as FileInfo in fileList
If imageFile.Extension = ".jpg" Or imageFile.Extension = ".gif" Then
    ...proceed with the conversion
End If
Next

Hope this helps.


问:
Django How to Look up querydict in template?
when i look inside querydict it with {{get_copy}} it shows

```<code><QueryDict: {'grub_id__in': ['Yelek', 'Tunik', 'Tulum', 'Tshirt']}>
</code>```

as i know that how to look up querydict

```<code>{%for key,val in get_copy.items%}
{{key}}{{val}}
{%endfor%}
</code>```

but it shows only one of val value

output:

```<code>grub_id__in Tshirt
</code>```

答:
From the QueryDict.items() of QueryDict objects[Django-doc]

Like dict.items(), except this uses the same last-value logic as getitem() and returns an iterator object instead of a view object.

And the QueryDict.__getitem__(key) as stated

Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist.

So you can use QueryDict.getlist(key, default=None) as stated

Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list.

In your views.py

```<code>from django.http import QueryDict
from django.shortcuts import render

def get_copy(request):
    data = QueryDict('grub_id__in=Yelek&grub_id__in=Tunik&grub_id__in=Tulum&grub_id__in=Tshirt')
    return render(request, 'test.html', {'get_copy':data.getlist('grub_id__in')})
</code>```

And in your templates

```<code>{{get_copy}}
</code>```

Output

```<code>['Yelek', 'Tunik', 'Tulum', 'Tshirt']
</code>```

Body:
when i look inside querydict it with {{get_copy}} it shows

<QueryDict: {'grub_id__in': ['Yelek', 'Tunik', 'Tulum', 'Tshirt']}>

as i know that how to look up querydict

{%for key,val in get_copy.items%}
{{key}}{{val}}
{%endfor%}

but it shows only one of val value

output:

grub_id__in Tshirt

Body:
From the QueryDict.items() of QueryDict objects[Django-doc]

Like dict.items(), except this uses the same last-value logic as getitem() and returns an iterator object instead of a view object.

And the QueryDict.__getitem__(key) as stated

Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist.

So you can use QueryDict.getlist(key, default=None) as stated

Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list.

In your views.py

from django.http import QueryDict
from django.shortcuts import render

def get_copy(request):
    data = QueryDict('grub_id__in=Yelek&grub_id__in=Tunik&grub_id__in=Tulum&grub_id__in=Tshirt')
    return render(request, 'test.html', {'get_copy':data.getlist('grub_id__in')})

And in your templates

{{get_copy}}

Output

['Yelek', 'Tunik', 'Tulum', 'Tshirt']


问:
Problem with closing an created with JS and transition property
I'm having trouble opening and closing a dynamically created div with Javascript.

The problems are these:

In the opening phase, the div created does not follow the transition scale 1s rule

When I close the div for the first time it respects the transition and closes correctly, while when I open it a second time the div does not close

Here is the HTML, CSS and JS code:

HTML

```<code>    <!DOCTYPE html>

<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="stile.css">
    </head>
    <body>

        <div id="check">
            <input type="checkbox">
            <label>Ho preso visione dell'<a href="#" class="link">informativa alla privacy</a></label>
        </div>

        <script src="script.js"></script>
    </body>
</html>
</code>```

CSS

```<code>*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

#check {
margin-top: 20px;
margin-bottom: 20px;
}

label {
line-height: 1.5;
margin-left: 5px;
}

#informativa-privacy {
z-index: 200;
transform: scale(0);
position:fixed;
/* margin-top: 100px; */
top: 0;
left: 0;
/* background-color: rgba(0, 0, 0, 0.815); */
height: 100%;
overflow-y: scroll;
transition: all .5s;
}

#informativa-privacy section {
background-color: white;
padding: 10px;
width: 90%;
margin: 20px auto;
}

 #attenzione {
 font-weight: 800;
 margin-bottom: 20px;
 text-align: center;
 }

#informativa-privacy button {
padding: 10px;
background-color: gold;
box-shadow: 0 0 3px black;
outline: none;
border: none;
display: block;
width: 90%;
margin: 10px auto;
font-weight: 800;
}

#overflow {
height: 200px;
overflow-y: scroll;
margin-bottom: 20px;
border: 1px solid blue;
padding: 5px;

}
</code>```

JS

```<code>  function apriPrivacy(linkPrivacy) {

   linkPrivacy.onclick = function (e) {

   e.preventDefault()

   let informativa = document.createElement("div")

   informativa.id = "informativa-privacy"

   document.body.appendChild(informativa)

   let contenutoInformativa = `<section>
   <p id="attenzione">LEGGI CON ATTENZIONE</p>

   <div id="overflow">
   <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
   Asperiores inventore voluptatum quidem impedit voluptas vitae
   ea, amet a autem, quia dicta! Possimus ipsum in earum sapiente
   architecto odit ad, veniam natus ullam sint esse amet. Fugiat
   mollitia, unde eos maxime consequuntur officia. Natus rem
   illum, expedita fugit nam harum, aliquid ducimus ab laboriosam
   obcaecati, necessitatibus alias repellat numquam tempora!
   Mollitia molestias ipsa dicta non aut, voluptates placeat.
   Molestias quibusdam voluptas, tempore deserunt aut cum
   veritatis ducimus quidem deleniti sapiente nostrum
   perferendis. Molestias ab tenetur provident tempore ut
   deserunt nam exercitationem sint labore! Maiores laborum
   molestias animi repellat eos ratione. Iste, laborum ducimus!
   Autem nisi quos nobis mollitia voluptate consectetur, placeat
   minima error earum velit ipsa, numquam blanditiis rerum
   quibusdam eligendi magni enim itaque fugit modi. Modi dolore
   quae commodi rem quidem maxime eos architecto delectus alias?
   Consequatur reprehenderit consequuntur esse tempora architecto
   minus animi deleniti debitis neque, ut reiciendis nemo.</p>
   </div>

   <button>ACCETTA</button>

   </section>`

   informativa.innerHTML = contenutoInformativa

   informativa.style.transition = "transform 1s"

   informativa.style.transform = "scale(1)"

   let bottoneAccetta = document.querySelector("#informativa-
   privacy button")

   bottoneAccetta.onclick = function () {

   informativa.style.transform = "scale(1)"

   informativa.style.transform = "scale(0)"

   }

   }

   }

   let linkPrivacy = document.querySelector("#check a")

   apriPrivacy(linkPrivacy)
</code>```

How can I solve the problem?

答:
OK, here is an answer:

Your code didn't work, because everytime someone clicked the link, a new div was created. Then you selected the first "Accetta" button in the document and set it's onclick property. For the first time, when only one button is in the whole document, it works, but for all other times, you select the first button in the document, but it is not the one that is visible

I have reordered your code. Now the element (informativa) is inserted immediately in the body when you call your function apriPrivacy.

Then comes the EventListener on the linkPrivacy element, in which I add the class open to informativa. In the CSS I changed the following:

```<code>#informativa-privacy {
  z-index: 200;
  transform: scale(0);
  position: fixed;
  /* margin-top: 100px; */
  top: 0;
  left: 0;
  /* background-color: rgba(0, 0, 0, 0.815); */
  height: 100%;
  overflow-y: scroll;
  transition: all .5s, transform 1s;
}

#informativa-privacy.open {
  transform: scale(1);
}
</code>```

Then in the click EventListener on the bottoneAccetta button I remove the class open from informativa and the CSS is responsible for the animation again.

In the following snippet is your complete code working:

function apriPrivacy(linkPrivacy) {
  let informativa = document.createElement("div");

  informativa.id = "informativa-privacy";

  document.body.appendChild(informativa);

  let contenutoInformativa = `

LEGGI CON ATTENZIONE

Lorem ipsum dolor sit amet, consectetur adipisicing elit.
   Asperiores inventore voluptatum quidem impedit voluptas vitae
   ea, amet a autem, quia dicta! Possimus ipsum in earum sapiente
   architecto odit ad, veniam natus ullam sint esse amet. Fugiat
   mollitia, unde eos maxime consequuntur officia. Natus rem
   illum, expedita fugit nam harum, aliquid ducimus ab laboriosam
   obcaecati, necessitatibus alias repellat numquam tempora!
   Mollitia molestias ipsa dicta non aut, voluptates placeat.
   Molestias quibusdam voluptas, tempore deserunt aut cum
   veritatis ducimus quidem deleniti sapiente nostrum
   perferendis. Molestias ab tenetur provident tempore ut
   deserunt nam exercitationem sint labore! Maiores laborum
   molestias animi repellat eos ratione. Iste, laborum ducimus!
   Autem nisi quos nobis mollitia voluptate consectetur, placeat
   minima error earum velit ipsa, numquam blanditiis rerum
   quibusdam eligendi magni enim itaque fugit modi. Modi dolore
   quae commodi rem quidem maxime eos architecto delectus alias?
   Consequatur reprehenderit consequuntur esse tempora architecto
   minus animi deleniti debitis neque, ut reiciendis nemo.

   <button>ACCETTA</button>

`;

  informativa.innerHTML = contenutoInformativa;

  linkPrivacy.onclick = function(e) {

    e.preventDefault();

    informativa.classList.add("open");
  }

  let bottoneAccetta = document.querySelector("#informativa-privacy button");

  bottoneAccetta.onclick = function() {
    informativa.classList.remove("open");
  }

}

let linkPrivacy = document.querySelector("#check a");

apriPrivacy(linkPrivacy);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#check {
  margin-top: 20px;
  margin-bottom: 20px;
}

label {
  line-height: 1.5;
  margin-left: 5px;
}

#informativa-privacy {
  z-index: 200;
  transform: scale(0);
  position: fixed;
  /* margin-top: 100px; */
  top: 0;
  left: 0;
  /* background-color: rgba(0, 0, 0, 0.815); */
  height: 100%;
  overflow-y: scroll;
  transition: all .5s, background-color 0s 1s, transform 1s;
}

#informativa-privacy.open {
  background-color: red;
  transform: scale(1);
}

#informativa-privacy section {
  background-color: white;
  padding: 10px;
  width: 90%;
  margin: 20px auto;
}

#attenzione {
  font-weight: 800;
  margin-bottom: 20px;
  text-align: center;
}

#informativa-privacy button {
  padding: 10px;
  background-color: gold;
  box-shadow: 0 0 3px black;
  outline: none;
  border: none;
  display: block;
  width: 90%;
  margin: 10px auto;
  font-weight: 800;
}

#overflow {
  height: 200px;
  overflow-y: scroll;
  margin-bottom: 20px;
  border: 1px solid blue;
  padding: 5px;
}</code>```

  <input type="checkbox">
  Ho preso visione dell'informativa alla privacy

```

Body:
I'm having trouble opening and closing a dynamically created div with Javascript.

The problems are these:

In the opening phase, the div created does not follow the transition scale 1s rule

When I close the div for the first time it respects the transition and closes correctly, while when I open it a second time the div does not close

Here is the HTML, CSS and JS code:

HTML

    <!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="stile.css">

            <input type="checkbox">
            Ho preso visione dell'informativa alla privacy

CSS

*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

#check {
margin-top: 20px;
margin-bottom: 20px;
}

label {
line-height: 1.5;
margin-left: 5px;
}

#informativa-privacy {
z-index: 200;
transform: scale(0);
position:fixed;
/* margin-top: 100px; */
top: 0;
left: 0;
/* background-color: rgba(0, 0, 0, 0.815); */
height: 100%;
overflow-y: scroll;
transition: all .5s;
}

#informativa-privacy section {
background-color: white;
padding: 10px;
width: 90%;
margin: 20px auto;
}

 #attenzione {
 font-weight: 800;
 margin-bottom: 20px;
 text-align: center;
 }

#informativa-privacy button {
padding: 10px;
background-color: gold;
box-shadow: 0 0 3px black;
outline: none;
border: none;
display: block;
width: 90%;
margin: 10px auto;
font-weight: 800;
}

#overflow {
height: 200px;
overflow-y: scroll;
margin-bottom: 20px;
border: 1px solid blue;
padding: 5px;

}

JS

  function apriPrivacy(linkPrivacy) {

   linkPrivacy.onclick = function (e) {

   e.preventDefault()

   let informativa = document.createElement("div")

   informativa.id = "informativa-privacy"

   document.body.appendChild(informativa)

   let contenutoInformativa = `

LEGGI CON ATTENZIONE

Lorem ipsum dolor sit amet, consectetur adipisicing elit.
   Asperiores inventore voluptatum quidem impedit voluptas vitae
   ea, amet a autem, quia dicta! Possimus ipsum in earum sapiente
   architecto odit ad, veniam natus ullam sint esse amet. Fugiat
   mollitia, unde eos maxime consequuntur officia. Natus rem
   illum, expedita fugit nam harum, aliquid ducimus ab laboriosam
   obcaecati, necessitatibus alias repellat numquam tempora!
   Mollitia molestias ipsa dicta non aut, voluptates placeat.
   Molestias quibusdam voluptas, tempore deserunt aut cum
   veritatis ducimus quidem deleniti sapiente nostrum
   perferendis. Molestias ab tenetur provident tempore ut
   deserunt nam exercitationem sint labore! Maiores laborum
   molestias animi repellat eos ratione. Iste, laborum ducimus!
   Autem nisi quos nobis mollitia voluptate consectetur, placeat
   minima error earum velit ipsa, numquam blanditiis rerum
   quibusdam eligendi magni enim itaque fugit modi. Modi dolore
   quae commodi rem quidem maxime eos architecto delectus alias?
   Consequatur reprehenderit consequuntur esse tempora architecto
   minus animi deleniti debitis neque, ut reiciendis nemo.

   <button>ACCETTA</button>

`

   informativa.innerHTML = contenutoInformativa

   informativa.style.transition = "transform 1s"

   informativa.style.transform = "scale(1)"

   let bottoneAccetta = document.querySelector("#informativa-
   privacy button")

   bottoneAccetta.onclick = function () {

   informativa.style.transform = "scale(1)"

   informativa.style.transform = "scale(0)"

   }

   }

   }

   let linkPrivacy = document.querySelector("#check a")

   apriPrivacy(linkPrivacy)

How can I solve the problem?

Body:
OK, here is an answer:

Your code didn't work, because everytime someone clicked the link, a new div was created. Then you selected the first "Accetta" button in the document and set it's onclick property. For the first time, when only one button is in the whole document, it works, but for all other times, you select the first button in the document, but it is not the one that is visible

I have reordered your code. Now the element (informativa) is inserted immediately in the body when you call your function apriPrivacy.

Then comes the EventListener on the linkPrivacy element, in which I add the class open to informativa. In the CSS I changed the following:

#informativa-privacy {
  z-index: 200;
  transform: scale(0);
  position: fixed;
  /* margin-top: 100px; */
  top: 0;
  left: 0;
  /* background-color: rgba(0, 0, 0, 0.815); */
  height: 100%;
  overflow-y: scroll;
  transition: all .5s, transform 1s;
}

#informativa-privacy.open {
  transform: scale(1);
}

Then in the click EventListener on the bottoneAccetta button I remove the class open from informativa and the CSS is responsible for the animation again.

In the following snippet is your complete code working:

function apriPrivacy(linkPrivacy) {
  let informativa = document.createElement("div");

  informativa.id = "informativa-privacy";

  document.body.appendChild(informativa);

  let contenutoInformativa = `<section>
   <p id="attenzione">LEGGI CON ATTENZIONE</p>
   <div id="overflow">
   <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
   Asperiores inventore voluptatum quidem impedit voluptas vitae
   ea, amet a autem, quia dicta! Possimus ipsum in earum sapiente
   architecto odit ad, veniam natus ullam sint esse amet. Fugiat
   mollitia, unde eos maxime consequuntur officia. Natus rem
   illum, expedita fugit nam harum, aliquid ducimus ab laboriosam
   obcaecati, necessitatibus alias repellat numquam tempora!
   Mollitia molestias ipsa dicta non aut, voluptates placeat.
   Molestias quibusdam voluptas, tempore deserunt aut cum
   veritatis ducimus quidem deleniti sapiente nostrum
   perferendis. Molestias ab tenetur provident tempore ut
   deserunt nam exercitationem sint labore! Maiores laborum
   molestias animi repellat eos ratione. Iste, laborum ducimus!
   Autem nisi quos nobis mollitia voluptate consectetur, placeat
   minima error earum velit ipsa, numquam blanditiis rerum
   quibusdam eligendi magni enim itaque fugit modi. Modi dolore
   quae commodi rem quidem maxime eos architecto delectus alias?
   Consequatur reprehenderit consequuntur esse tempora architecto
   minus animi deleniti debitis neque, ut reiciendis nemo.</p>
   </div>
   <button>ACCETTA</button>
   </section>`;

  informativa.innerHTML = contenutoInformativa;

  linkPrivacy.onclick = function(e) {

    e.preventDefault();

    informativa.classList.add("open");
  }

  let bottoneAccetta = document.querySelector("#informativa-privacy button");

  bottoneAccetta.onclick = function() {
    informativa.classList.remove("open");
  }

}

let linkPrivacy = document.querySelector("#check a");

apriPrivacy(linkPrivacy);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#check {
  margin-top: 20px;
  margin-bottom: 20px;
}

label {
  line-height: 1.5;
  margin-left: 5px;
}

#informativa-privacy {
  z-index: 200;
  transform: scale(0);
  position: fixed;
  /* margin-top: 100px; */
  top: 0;
  left: 0;
  /* background-color: rgba(0, 0, 0, 0.815); */
  height: 100%;
  overflow-y: scroll;
  transition: all .5s, background-color 0s 1s, transform 1s;
}

#informativa-privacy.open {
  background-color: red;
  transform: scale(1);
}

#informativa-privacy section {
  background-color: white;
  padding: 10px;
  width: 90%;
  margin: 20px auto;
}

#attenzione {
  font-weight: 800;
  margin-bottom: 20px;
  text-align: center;
}

#informativa-privacy button {
  padding: 10px;
  background-color: gold;
  box-shadow: 0 0 3px black;
  outline: none;
  border: none;
  display: block;
  width: 90%;
  margin: 10px auto;
  font-weight: 800;
}

#overflow {
  height: 200px;
  overflow-y: scroll;
  margin-bottom: 20px;
  border: 1px solid blue;
  padding: 5px;
}

<div id="check">
  <input type="checkbox">
  <label>Ho preso visione dell'<a href="#" class="link">informativa alla privacy</a></label>
</div>


问:
Chrome-extension: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist
My goal is to send a simple message from background.js to content-script (test.js). I followed the example in here: https://developer.chrome.com/docs/extensions/mv3/messaging/#simple, but getting this error in background.js console log:

```<code>11111
33333 undefined
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
</code>```

How to reproduce:

manifest.json

```<code>{
  "name": "myName",
  "description": "myDescription",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
   },
  "permissions": ["storage", "activeTab", "scripting", "notifications", "tabs"],
  "action": {
    "default_popup": "index.html"
  }
}
</code>```

index.html

```<code><!DOCTYPE html>
<html>
<body>
<script src="test.js"></script>
</body>
</html>
</code>```

test.js

```<code>chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log('22222', request, sender);
    sendResponse({farewell: "goodbye"});
  }
);
</code>```

background.js

```<code>chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    console.log('11111');
    chrome.tabs.sendMessage(tabs[0].id, {action: "playSound"}, function(resp) {
        console.log('33333', resp);
    });
});
</code>```

My environment:

```<code>Chrome Version 96.0.4664.93 (Official Build) (x86_64)
chrome://extensions - all other extensions are turned off
OS: Mac Monterey 12.0.1
</code>```

答:
This is for sending message from background script to content script

If someone using message sending code directly from doc (https://developer.chrome.com/docs/extensions/mv3/messaging/#simple) and still getting the error make sure you reload the web page after changing code locally and add return true when receving the message.

```<code>chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log(message);
  return true;
});
</code>```

Body:
My goal is to send a simple message from background.js to content-script (test.js). I followed the example in here: https://developer.chrome.com/docs/extensions/mv3/messaging/#simple, but getting this error in background.js console log:

11111
33333 undefined
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

How to reproduce:

manifest.json

{
  "name": "myName",
  "description": "myDescription",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
   },
  "permissions": ["storage", "activeTab", "scripting", "notifications", "tabs"],
  "action": {
    "default_popup": "index.html"
  }
}

index.html

<!DOCTYPE html>

test.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log('22222', request, sender);
    sendResponse({farewell: "goodbye"});
  }
);

background.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    console.log('11111');
    chrome.tabs.sendMessage(tabs[0].id, {action: "playSound"}, function(resp) {
        console.log('33333', resp);
    });
});

My environment:

Chrome Version 96.0.4664.93 (Official Build) (x86_64)
chrome://extensions - all other extensions are turned off
OS: Mac Monterey 12.0.1

Body:
This is for sending message from background script to content script

If someone using message sending code directly from doc (https://developer.chrome.com/docs/extensions/mv3/messaging/#simple) and still getting the error make sure you reload the web page after changing code locally and add return true when receving the message.

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log(message);
  return true;
});


问:
Is there a way to remove a migration added to sqitch?
In sqitch there is the ADD command to add a new migration.
Is there any command to remove that ADDITION?</p>

答:
This is the way I do it:

revert the change from the database.

Remove it manually from the plan or plan files

Remove manually the scripts in deploy/, verify/ and revert/

My cases have been simple, so the above works without issue. I could see complications if the change you are trying to remove is required by other changes down stream. In that situation or as alternative to above I would look at creating a change that reverses the effect of the change you are trying to undo.