问:
How to resolve the ViewModel RunTimeException
My ViewModel class is throwing a RunTimeException.  It basically cannot create an instance of the ViewModel class.  Here is the stacktrace:

```<code>2019-05-29 01:27:56.700 9698-9698/com.example.cryptpass_kt E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.cryptpass_kt, PID: 9698
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cryptpass_kt/com.example.cryptpass_kt.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.cryptpass_kt.EntryViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.cryptpass_kt.EntryViewModel
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:208)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
        at com.example.cryptpass_kt.MainActivity.onCreate(MainActivity.kt:40)
        at android.app.Activity.performCreate(Activity.java:6980)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2806)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
        at com.example.cryptpass_kt.MainActivity.onCreate(MainActivity.kt:40)
        at android.app.Activity.performCreate(Activity.java:6980)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2806)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.RuntimeException: cannot find implementation for com.example.cryptpass_kt.EntryDatabase. EntryDatabase_Impl does not exist
        at androidx.room.Room.getGeneratedImplementation(Room.java:94)
        at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:667)
        at com.example.cryptpass_kt.EntryDatabase$Companion.getInstance(EntryDatabase.kt:17)
        at com.example.cryptpass_kt.EntryRepository.<init>(EntryRepository.kt:12)
        at com.example.cryptpass_kt.EntryViewModel.<init>(EntryViewModel.kt:8)
</code>```

The error points to 4 different locations in the app, which are all rooted in the same problem.  For example, these lines in the onCreate() method of my MainActivity.kt are in the stacktrace:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    ...
    viewModel = ViewModelProviders.of(this).get(EntryViewModel::class.java)
    viewModel.allEntries.observe(this, Observer { entries -> adapter.submitList(entries) })

    ...
}
</code>```

I've followed some of the suggestions in SO, such as initializing the ViewModel object as lateinit and not null but so far it hasn't made any changes to the situation

EntryViewModel.kt

```<code>class EntryViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: EntryRepository = EntryRepository(application)
    val allEntries: LiveData<List<Entry>>

    init {
        allEntries = repository.allEntries!!
    }

    fun insert(entry: Entry) {
        repository.insert(entry)
    }

    fun update(entry: Entry) {
        repository.update(entry)
    }

    fun delete(entry: Entry) {
        repository.update(entry)
    }

    fun deleteAll() {
        repository.deleteAllEntries()
    }
}
</code>```

EntryDatabase.kt

```<code>@Database(entities = [Entry::class], version = 1)
abstract class EntryDatabase : RoomDatabase() {

    abstract fun entryDAO(): EntryDAO

    companion object{
        private var instance: EntryDatabase? = null

        @Synchronized
        fun getInstance(context: Context): EntryDatabase{
            if(instance == null){instance = Room.databaseBuilder<EntryDatabase>(context.applicationContext, EntryDatabase::class.java, "entry_database").fallbackToDestructiveMigration().build()}

            return instance as EntryDatabase
        }
    }
}
</code>```

And I have all of the necessary gradle dependencies:

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha05'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.android.support:design:28.1.0'

    implementation "android.arch.lifecycle:extensions:2.2.0-alpha01"
    implementation "android.arch.persistence.room:runtime:2.1.0-beta01"
    implementation "android.arch.paging:runtime:2.1.0-beta01"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'io.sentry:sentry-android:1.7.16'
    implementation 'org.slf4j:slf4j-nop:1.7.25'
}
</code>```

答:
In the stacktrace you posted exceptions were put one in another. So the last one is main root of the problem:

```<code>Caused by: java.lang.RuntimeException: cannot find implementation for com.example.cryptpass_kt.EntryDatabase. EntryDatabase_Impl does not exist
at androidx.room.Room...
</code>```

As I can see from stacktrace, there is error while you trying to get instance of your database. I don't think it is good idea to get database reference in ViewModel constructor, but it's not essential.

About your database code: there are some possible reasons.

1. Dependencies.

As I saw in other answers from similar questions (I think, this one is the best) you should add some gradle dependencies:

```<code>// Extensions = ViewModel + LiveData
implementation "android.arch.lifecycle:extensions:1.1.0"
kapt "android.arch.lifecycle:compiler:1.1.0"
// Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
</code>```

If I get it right, Kotlin just need some additional dependencies (use keyword kapt instead of implementation for it).

2. Annotations.

Another possible reason: you didn't place Entity annotation to your Entry class (as said in this answer). Another needed annotation is Database, but you already have it.

Body:
My ViewModel class is throwing a RunTimeException.  It basically cannot create an instance of the ViewModel class.  Here is the stacktrace:

2019-05-29 01:27:56.700 9698-9698/com.example.cryptpass_kt E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.cryptpass_kt, PID: 9698
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cryptpass_kt/com.example.cryptpass_kt.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.cryptpass_kt.EntryViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.cryptpass_kt.EntryViewModel
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:208)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
        at com.example.cryptpass_kt.MainActivity.onCreate(MainActivity.kt:40)
        at android.app.Activity.performCreate(Activity.java:6980)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2806)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
        at com.example.cryptpass_kt.MainActivity.onCreate(MainActivity.kt:40)
        at android.app.Activity.performCreate(Activity.java:6980)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2806)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6703)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: java.lang.RuntimeException: cannot find implementation for com.example.cryptpass_kt.EntryDatabase. EntryDatabase_Impl does not exist
        at androidx.room.Room.getGeneratedImplementation(Room.java:94)
        at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:667)
        at com.example.cryptpass_kt.EntryDatabase$Companion.getInstance(EntryDatabase.kt:17)
        at com.example.cryptpass_kt.EntryRepository.<init>(EntryRepository.kt:12)
        at com.example.cryptpass_kt.EntryViewModel.<init>(EntryViewModel.kt:8)

The error points to 4 different locations in the app, which are all rooted in the same problem.  For example, these lines in the onCreate() method of my MainActivity.kt are in the stacktrace:

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    viewModel = ViewModelProviders.of(this).get(EntryViewModel::class.java)
    viewModel.allEntries.observe(this, Observer { entries -> adapter.submitList(entries) })

    ...
}

I've followed some of the suggestions in SO, such as initializing the ViewModel object as lateinit and not null but so far it hasn't made any changes to the situation

EntryViewModel.kt

class EntryViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: EntryRepository = EntryRepository(application)
    val allEntries: LiveData<List<Entry>>

    init {
        allEntries = repository.allEntries!!
    }

    fun insert(entry: Entry) {
        repository.insert(entry)
    }

    fun update(entry: Entry) {
        repository.update(entry)
    }

    fun delete(entry: Entry) {
        repository.update(entry)
    }

    fun deleteAll() {
        repository.deleteAllEntries()
    }
}

EntryDatabase.kt

@Database(entities = [Entry::class], version = 1)
abstract class EntryDatabase : RoomDatabase() {

    abstract fun entryDAO(): EntryDAO

    companion object{
        private var instance: EntryDatabase? = null

        @Synchronized
        fun getInstance(context: Context): EntryDatabase{
            if(instance == null){instance = Room.databaseBuilder<EntryDatabase>(context.applicationContext, EntryDatabase::class.java, "entry_database").fallbackToDestructiveMigration().build()}

            return instance as EntryDatabase
        }
    }
}

And I have all of the necessary gradle dependencies:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha05'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.android.support:design:28.1.0'

    implementation "android.arch.lifecycle:extensions:2.2.0-alpha01"
    implementation "android.arch.persistence.room:runtime:2.1.0-beta01"
    implementation "android.arch.paging:runtime:2.1.0-beta01"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    implementation 'io.sentry:sentry-android:1.7.16'
    implementation 'org.slf4j:slf4j-nop:1.7.25'
}

Body:
In the stacktrace you posted exceptions were put one in another. So the last one is main root of the problem:

Caused by: java.lang.RuntimeException: cannot find implementation for com.example.cryptpass_kt.EntryDatabase. EntryDatabase_Impl does not exist
at androidx.room.Room...

As I can see from stacktrace, there is error while you trying to get instance of your database. I don't think it is good idea to get database reference in ViewModel constructor, but it's not essential.

About your database code: there are some possible reasons.

1. Dependencies.

As I saw in other answers from similar questions (I think, this one is the best) you should add some gradle dependencies:

// Extensions = ViewModel + LiveData
implementation "android.arch.lifecycle:extensions:1.1.0"
kapt "android.arch.lifecycle:compiler:1.1.0"
// Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"

If I get it right, Kotlin just need some additional dependencies (use keyword kapt instead of implementation for it).

2. Annotations.

Another possible reason: you didn't place Entity annotation to your Entry class (as said in this answer). Another needed annotation is Database, but you already have it.


来源: stackexchange

问:
Add validation class to parent element in angular 6 template driven form
Overview:

I am trying to find a nice way to add a class to an inputs parent element

I currently have this code:

        Prop Label
        <input type="text" [(ngModel)]="model.prop" #prop="ngModel" required />

which works fine!

Problem:

I want to be able to do it in a more generic way i.e.

using a directive to set the parent class (can't seem to find how to pass prop.invalid to it?)

setting the parent element to receive the classes at a global level instead of the input

Note: I am not using reactive forms

答:
You can add a custom attribute directive to the
 element that will check it's child <input> validity.

Regarding the problems you've mentioned in your question:

using a directive to set the parent class: use Renderer2 class to add/remove error class to
 element

(can't seem to find how to pass prop.invalid to it?): you'll get a reference to the <input> by using @ContentChild, finding it by NgModel class.

setting the parent element to receive the classes at a global level instead of the input: not sure what is the problem, looks like the first one. add a comment to this answer if needed.

Live Stackblitz DEMO

These are the changes you need to make:

HTML:

```<code><p requiredValidator>
    <label>Prop Label</label>
  <br>
  <input type="text" [(ngModel)]="model.prop" #prop="ngModel" required />
</p>
</code>```

Directive:

```<code>import { Directive, ElementRef, Renderer2, ViewChild, ContentChild, AfterContentInit } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
  selector: '[requiredValidator]'
})
export class RequiredValidatorDirective implements AfterContentInit {
  element: ElementRef;
  renderer: Renderer2;
  @ContentChild(NgModel) input: NgModel;

  constructor(element: ElementRef, renderer: Renderer2) {
    this.element = element;
    this.renderer = renderer;
  }

  ngAfterContentInit() {
    this.input.valueChanges.subscribe(() => {
      if (this.input.invalid  && (this.input.dirty || this.input.touched)) {
        this.addErrorClass();
      } else {
        this.removeErrorClass();
      }
    })
  }

  addErrorClass(): void {
    this.renderer.addClass(this.element.nativeElement, 'error');
  }

  removeErrorClass(): void {
    this.renderer.removeClass(this.element.nativeElement, 'error');
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can add a custom attribute directive to the <p> element that will check it's child <input> validity.

Regarding the problems you've mentioned in your question:

using a directive to set the parent class: use Renderer2 class to add/remove error class to <p> element

(can't seem to find how to pass prop.invalid to it?): you'll get a reference to the <input> by using @ContentChild, finding it by NgModel class.

setting the parent element to receive the classes at a global level instead of the input: not sure what is the problem, looks like the first one. add a comment to this answer if needed.

Live Stackblitz DEMO

These are the changes you need to make:

HTML:

<p requiredValidator>
    <label>Prop Label</label>
  <br>
  <input type="text" [(ngModel)]="model.prop" #prop="ngModel" required />
</p>

Directive:

import { Directive, ElementRef, Renderer2, ViewChild, ContentChild, AfterContentInit } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
  selector: '[requiredValidator]'
})
export class RequiredValidatorDirective implements AfterContentInit {
  element: ElementRef;
  renderer: Renderer2;
  @ContentChild(NgModel) input: NgModel;

  constructor(element: ElementRef, renderer: Renderer2) {
    this.element = element;
    this.renderer = renderer;
  }

  ngAfterContentInit() {
    this.input.valueChanges.subscribe(() => {
      if (this.input.invalid  && (this.input.dirty || this.input.touched)) {
        this.addErrorClass();
      } else {
        this.removeErrorClass();
      }
    })
  }

  addErrorClass(): void {
    this.renderer.addClass(this.element.nativeElement, 'error');
  }

  removeErrorClass(): void {
    this.renderer.removeClass(this.element.nativeElement, 'error');
  }
}


问:
Publishing a Self-Hosting Owin app in Azure App Service
I have an existing ASP.Net WebApi OWIN Self-hosting web application. The application is a simple console application and outputs a .exe file and some dlls.

Currently, the application can be hosted in two ways

By simply running the exe file. (Which will run as a console
application)

As windows service using Topshelf library.

The services can be consumed by accessing a configured URL and a port number.
Ex: http://www.demoapp.com:8080

Below code is the entry point of the application.

```<code>public class WebServer
{
    private IDisposable app;

    public void Start()
    {
        app = WebApp.Start<Startup>(url: "http://demoapp.com:8080");
    }

    public void Stop()
    {
        app?.Dispose();
    }
}
</code>```

Requirement

Now there is a requirement to host the application in Azure AppServices.
How can I achieve this without modifying existing code as much as possible?
Appreciated if you can provide a step by step instruction.

答:
It seems that the feature is not supported now.

You could vote up this issue to promote it to be achieved.

Body:
I have an existing ASP.Net WebApi OWIN Self-hosting web application. The application is a simple console application and outputs a .exe file and some dlls.

Currently, the application can be hosted in two ways

By simply running the exe file. (Which will run as a console
application)

As windows service using Topshelf library.

The services can be consumed by accessing a configured URL and a port number.
Ex: http://www.demoapp.com:8080

Below code is the entry point of the application.

public class WebServer
{
    private IDisposable app;

    public void Start()
    {
        app = WebApp.Start<Startup>(url: "http://demoapp.com:8080");
    }

    public void Stop()
    {
        app?.Dispose();
    }
}

Requirement

Now there is a requirement to host the application in Azure AppServices.
How can I achieve this without modifying existing code as much as possible?
Appreciated if you can provide a step by step instruction.


问:
Deep copying data structures in golang
I want to duplicate an instance of a data structure. Since go does not have any builtins, I am using a third party library: https://github.com/emirpasic/gods.

For example, I may try use deep copy with a hash set.

```<code>var c, d hashset.Set
c = *hashset.New()
c.Add(1)
deepcopy.Copy(d, c)
c.Add(2)
fmt.Println(c.Contains(2))
fmt.Println(d.Contains(2))
fmt.Println(c.Contains(1))
fmt.Println(d.Contains(1))
</code>```

However, the content of the hash set is not copied at all. I know deep copy modules can't copy unexported values, but since there is no builtin "copy constructor" in the library, does it mean it is not possible to fully duplicate a data structure instance with the library without modifying its code? (Similar problem happens with some other libraries I looked into).

I am new to golang and does not feel right, since similar things can be easily achieved for example in C++. I know I could write my own version or modify their code, but it is too much work than expected and that's why I think there should be an idiomatic way.

PS: For people who may say "there is no need of such functionality", I am distributing some complex state with some data structures to parallel calculation threads, they use the states directly and must not interfere with each other.

答:
If the package your are using does not provide a copy function for the data stucture, then I would write my own type-safe copy function. Moreover, I would not worry about unexported fields, because there must be a reason why the developer has decided to hide those fields to users.

In your example:

```<code>func NewHashSetCopy(src *hashset.Set) *hashset.Set{
    dst := *hashset.New()
    iterator := src.Iter()
    for elem := range iterator {
        dst.Add(elem)
    }
    return dst
}
</code>```

Title: Deep copying data structures in golang

Body:
I want to duplicate an instance of a data structure. Since go does not have any builtins, I am using a third party library: https://github.com/emirpasic/gods.

For example, I may try use deep copy with a hash set.

var c, d hashset.Set
c = *hashset.New()
c.Add(1)
deepcopy.Copy(d, c)
c.Add(2)
fmt.Println(c.Contains(2))
fmt.Println(d.Contains(2))
fmt.Println(c.Contains(1))
fmt.Println(d.Contains(1))

However, the content of the hash set is not copied at all. I know deep copy modules can't copy unexported values, but since there is no builtin "copy constructor" in the library, does it mean it is not possible to fully duplicate a data structure instance with the library without modifying its code? (Similar problem happens with some other libraries I looked into).

I am new to golang and does not feel right, since similar things can be easily achieved for example in C++. I know I could write my own version or modify their code, but it is too much work than expected and that's why I think there should be an idiomatic way.

PS: For people who may say "there is no need of such functionality", I am distributing some complex state with some data structures to parallel calculation threads, they use the states directly and must not interfere with each other.

Body:
If the package your are using does not provide a copy function for the data stucture, then I would write my own type-safe copy function. Moreover, I would not worry about unexported fields, because there must be a reason why the developer has decided to hide those fields to users.

In your example:

func NewHashSetCopy(src *hashset.Set) *hashset.Set{
    dst := *hashset.New()
    iterator := src.Iter()
    for elem := range iterator {
        dst.Add(elem)
    }
    return dst
}


问:
Problems when submitting a form in TYPO3 v9.5
In TYPO3 versions before v9, when using the native form, I always disabled the cache of that specific "contact" page (where the form was placed). If I didn't disable the cace, the form wouldn't redirect to my "confirmation" (v6/v7) or "redirect" page (v8), but instead it would simply reload the (filled-out) form (on the same page).

So, to bypass this and to make sure that the form actually got submitted and forwarded to the correct confirmation page, I always disabled the cache (Page Properties -> Page -> Behaviour -> Disable cache).

In TYPO3 v9 however, this option has been removed, and adding config.no_cache = 1 into that specific page (in a TS template), doesn't seem to do the (same) trick.

I would expect that the form, after clicking the submit button, would forward to the confirmation (redirect) page which I configured insde the form itself. That confirmation page isn't usergroup-protected or anything, it's simply a sub-page of the "contact" page (containing the form) itself.

答:
As Mathias Brodola righfully points out, this seems to be a problem in Chrome only. I found this following plugin - that completely disables autocomplete support for a form - to be helpful in this matter. It solved my issue (however, it does completely disable auto-complete support for the form):
https://github.com/terrylinooo/jquery.disableAutoFill</p>


问:
Codeigniter session is not working on PHP 7
I am using codeigniter version 3.0.6 on PHP 5.6 and it works fine. but when I run same project on PHP 7.1 , codeigniter session is not working. I set session like below

```<code>$login_session = $this->session->set_userdata("user_session",$session_data);
</code>```

when I print  $login_session  it is blank on PHP 7

答:
Session id is different in php 7.1 and not pass the regex checking.

A simple fix:
In system/libraries/Session/Session.php arround line 133

```<code>OR ! preg_match('/^[0-9a-f]{40}$/', $_COOKIE[$this->_config['cookie_name']])
</code>```

remove '{40}$'

```<code>OR ! preg_match('/^[0-9a-f]/', $_COOKIE[$this->_config['cookie_name']])
</code>```

The problem is that the session id is deleted from cookie because the regex mismatch. So the session id always renew.

This can fix the regular expression and prevent it run the line
"unset($_COOKIE[$this->_config['cookie_name']]);"

It totally works for me !

FYI. Find this after I fix it myself.
https://github.com/bcit-ci/CodeIgniter/issues/4830

ContentLicense: CC BY-SA 3.0

Body:
I am using codeigniter version 3.0.6 on PHP 5.6 and it works fine. but when I run same project on PHP 7.1 , codeigniter session is not working. I set session like below

$login_session = $this->session->set_userdata("user_session",$session_data);

when I print  $login_session  it is blank on PHP 7

Body:
Session id is different in php 7.1 and not pass the regex checking.

A simple fix:
In system/libraries/Session/Session.php arround line 133

OR ! preg_match('/^[0-9a-f]{40}$/', $_COOKIE[$this->_config['cookie_name']])

remove '{40}$'

OR ! preg_match('/^[0-9a-f]/', $_COOKIE[$this->_config['cookie_name']])

The problem is that the session id is deleted from cookie because the regex mismatch. So the session id always renew.

This can fix the regular expression and prevent it run the line
"unset($_COOKIE[$this->_config['cookie_name']]);"

It totally works for me !

FYI. Find this after I fix it myself.
https://github.com/bcit-ci/CodeIgniter/issues/4830


答:
Unfortunately or not, there is no way to do this in Go. First tool that comes to mind is reflection (package reflect), but using reflection you can only read unexported fields, but you can't set them. See How to clone a structure with unexported field?

The only way to clone structures with unexported fields would be to use package unsafe (see an example here: Access unexported fields in golang/reflect?), but as its name says: it's unsafe and you should stay away from it as much as possible. Programs created using unsafe has no guarantee that they continue to work with newer Go releases, or that they behave the same on every platform.

In general the only and proper way to support cloning in Go is if the package itself supports such operations.

Note #1:

This does not mean that in some specific case you can't "mimic" cloning by creating a new value and building its state manually. For example you can clone a map by creating a new map, iterating over the key-value pairs of the original and setting them in the new map.

Note #2:

Do note that you can make "exact" copies of structs having unexported fields by simply assigning them to another struct variable (of the same type), which will properly copy the unexported fields too.

Like in this example:

```<code>type person struct {
    Name string
    age  *int
}

age := 22
p := &person{"Bob", &age}
fmt.Println(p)

p2 := new(person)
*p2 = *p
fmt.Println(p2)
</code>```

Which will output (try it on the Go Playground):

```<code>&{Bob 0x414020}
&{Bob 0x414020}
</code>```

Which we can even generalize using reflect without relying on the concrete type:

```<code>type person struct {
    Name string
    age  *int
}

age := 22
p := &person{"Bob", &age}
fmt.Println(p)

v := reflect.ValueOf(p).Elem()
vp2 := reflect.New(v.Type())
vp2.Elem().Set(v)
fmt.Println(vp2)
</code>```

Try this one on the Go Playground.

But what we can't do is change the person.age unexported field to point to something else. Without help of the declaring package, it can only be nil or the same pointer value (pointing to the object as the original field).

Also see related: Quicker way to deepcopy objects in golang

Title: Deep copying data structures in golang

Body:
Unfortunately or not, there is no way to do this in Go. First tool that comes to mind is reflection (package reflect), but using reflection you can only read unexported fields, but you can't set them. See How to clone a structure with unexported field?

The only way to clone structures with unexported fields would be to use package unsafe (see an example here: Access unexported fields in golang/reflect?), but as its name says: it's unsafe and you should stay away from it as much as possible. Programs created using unsafe has no guarantee that they continue to work with newer Go releases, or that they behave the same on every platform.

In general the only and proper way to support cloning in Go is if the package itself supports such operations.

Note #1:

This does not mean that in some specific case you can't "mimic" cloning by creating a new value and building its state manually. For example you can clone a map by creating a new map, iterating over the key-value pairs of the original and setting them in the new map.

Note #2:

Do note that you can make "exact" copies of structs having unexported fields by simply assigning them to another struct variable (of the same type), which will properly copy the unexported fields too.

Like in this example:

type person struct {
    Name string
    age  *int
}

age := 22
p := &person{"Bob", &age}
fmt.Println(p)

p2 := new(person)
*p2 = *p
fmt.Println(p2)

Which will output (try it on the Go Playground):

&{Bob 0x414020}
&{Bob 0x414020}

Which we can even generalize using reflect without relying on the concrete type:

type person struct {
    Name string
    age  *int
}

age := 22
p := &person{"Bob", &age}
fmt.Println(p)

v := reflect.ValueOf(p).Elem()
vp2 := reflect.New(v.Type())
vp2.Elem().Set(v)
fmt.Println(vp2)

Try this one on the Go Playground.

But what we can't do is change the person.age unexported field to point to something else. Without help of the declaring package, it can only be nil or the same pointer value (pointing to the object as the original field).

Also see related: Quicker way to deepcopy objects in golang


问:
Show column value only once
I have data like this:

And I want to show like this

All employees have the same position As Manager but I want to show once.

答:
You can do something like the following, but you should do it only for display purposes:

```<code>WITH a (ename, position, deptno) AS (SELECT 'KING', 'Manager', 10 FROM dual
                                     UNION ALL
                                     SELECT 'BLAKE', 'Manager', 30 FROM dual
                                     UNION ALL
                                     SELECT 'CLARK', 'Manager', 10 FROM dual
                                     UNION ALL
                                     SELECT 'ALLEN', 'Manager', 30 FROM dual
                                     UNION ALL
                                     SELECT 'WARD', 'Manager', 30 FROM dual)
SELECT ENAME
     , CASE WHEN position = MAX(position) over (ORDER BY ROWNUM
                                                 ROWS BETWEEN 1 preceding AND 1 preceding)
            THEN NULL
            ELSE position
       END position
     , deptno
  FROM a
</code>```

That will display NULL for the column POSITION if the value is the same as in the previous row.

Title: Show column value only once

Body:
You can do something like the following, but you should do it only for display purposes:

WITH a (ename, position, deptno) AS (SELECT 'KING', 'Manager', 10 FROM dual
                                     UNION ALL
                                     SELECT 'BLAKE', 'Manager', 30 FROM dual
                                     UNION ALL
                                     SELECT 'CLARK', 'Manager', 10 FROM dual
                                     UNION ALL
                                     SELECT 'ALLEN', 'Manager', 30 FROM dual
                                     UNION ALL
                                     SELECT 'WARD', 'Manager', 30 FROM dual)
SELECT ENAME
     , CASE WHEN position = MAX(position) over (ORDER BY ROWNUM
                                                 ROWS BETWEEN 1 preceding AND 1 preceding)
            THEN NULL
            ELSE position
       END position
     , deptno
  FROM a

That will display NULL for the column POSITION if the value is the same as in the previous row.


问:
Getting errors whenever dealing with null or NaN types when working on csv files with pandas
I am trying to replace all the Country ISO codes to Full Country Names to keep everything consistent as part of cleaning some data. I managed to find the pycountry package, which helps a ton! There are some fields on the CSV file that are empty, which I believe is causing some issues when running my code below.

Also, an additional question, not sure if it's just me, but there are times when CSV reads empty files as null/NaN or simply empty. I don't really know what went wrong there, but if possible I would like to change all those empty cells into one "thing" or type for ease of filtering/dropping it out.

df = pd.read_csv("file.csv")
#use pycountry to match the Nationalities as actual country names
import pycountry
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]

def country_flag(df):
    if (len(df['Nationality'])==2 and df['Nationality'] in list_alpha_2):
        return pycountry.countries.get(alpha_2=df['Nationality']).name
    elif (len(df['Nationality'])==3 and df['Nationality'] in list_alpha_3):
        return pycountry.countries.get(alpha_3=df['Nationality']).name
    elif (len(df['Nationality'])>3):
        return df['Nationality']
    else:
        return '#N/A'

df['Nationality']=df.apply(country_flag,axis =1)
df
```

<p>I was expecting the result to be something like:</p>

```
0   AF  100 Afghanistan

1           #N/A

2   AUS 140 Australia

3    Germany    400 Germany
```

<p>The error message I am getting is </p>

<pre class="lang-py prettyprint-override"><code>TypeError: ("object of type 'float' has no len()", 'occurred at index 0')
</code>```

Yet, there shouldn't be any float type values in the 'Nationality' column I am working on. I am guessing this is simply the empty/null/NaN values being considered a float type?

答:
One thing to watch out for is when pandas is reading from a data source and tries to automatically assign a data type to a column, it will sometimes assign a different data type than what you would expect depending upon if there are empty values or not in the data source.

A classical example is integer values that are converted to float values.

If you have a CSV file with this exact content (note missing value in row 2 of column A):

```<code>ColA,ColB
0,2
,1
5,4
</code>```

then reading the file with

res_df=pandas.read_csv(filename)
```

will create a dataframe with floats in the column A and integers in the column B.
This is due to the fact that there is no canonical way to assign an "empty" value to an integer, whereas a float can just be set as NaN (not a number).

But if that value was present, you would get 2 columns of integers.

Just something to be aware of, as it may easily be forgotten, and then suddenly you are getting floats instead of integers in your code and be confused about it.

Body:
I am trying to replace all the Country ISO codes to Full Country Names to keep everything consistent as part of cleaning some data. I managed to find the pycountry package, which helps a ton! There are some fields on the CSV file that are empty, which I believe is causing some issues when running my code below.

Also, an additional question, not sure if it's just me, but there are times when CSV reads empty files as null/NaN or simply empty. I don't really know what went wrong there, but if possible I would like to change all those empty cells into one "thing" or type for ease of filtering/dropping it out.

df = pd.read_csv("file.csv")
#use pycountry to match the Nationalities as actual country names
import pycountry
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]

def country_flag(df):
    if (len(df['Nationality'])==2 and df['Nationality'] in list_alpha_2):
        return pycountry.countries.get(alpha_2=df['Nationality']).name
    elif (len(df['Nationality'])==3 and df['Nationality'] in list_alpha_3):
        return pycountry.countries.get(alpha_3=df['Nationality']).name
    elif (len(df['Nationality'])>3):
        return df['Nationality']
    else:
        return '#N/A'

df['Nationality']=df.apply(country_flag,axis =1)
df

I was expecting the result to be something like:

0   AF  100 Afghanistan

1           #N/A

2   AUS 140 Australia

3    Germany    400 Germany

The error message I am getting is

TypeError: ("object of type 'float' has no len()", 'occurred at index 0')

Yet, there shouldn't be any float type values in the 'Nationality' column I am working on. I am guessing this is simply the empty/null/NaN values being considered a float type?

Body:
One thing to watch out for is when pandas is reading from a data source and tries to automatically assign a data type to a column, it will sometimes assign a different data type than what you would expect depending upon if there are empty values or not in the data source.

A classical example is integer values that are converted to float values.

If you have a CSV file with this exact content (note missing value in row 2 of column A):

ColA,ColB
0,2
,1
5,4

then reading the file with

res_df=pandas.read_csv(filename)

will create a dataframe with floats in the column A and integers in the column B.
This is due to the fact that there is no canonical way to assign an "empty" value to an integer, whereas a float can just be set as NaN (not a number).

But if that value was present, you would get 2 columns of integers.

Just something to be aware of, as it may easily be forgotten, and then suddenly you are getting floats instead of integers in your code and be confused about it.


问:
Reproducibility and performance in PyTorch
The documentation states:

Deterministic mode can have a performance impact, depending on your model.

My question is, what is meant by performance here. Processing speed or model quality (i.e. minimal loss)? In other words, when setting manual seeds and making the model perform in a deterministic way, does that cause longer training time until minimal loss is found, or is that minimal loss worse than when the model is non-deterministic?

For completeness' sake, I manually make the model deterministic by setting all of these properties:

```<code>def set_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(seed)
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
</code>```

答: "performance" in this context refer to run-time</p>

Body:
The documentation states:

Deterministic mode can have a performance impact, depending on your model.

My question is, what is meant by performance here. Processing speed or model quality (i.e. minimal loss)? In other words, when setting manual seeds and making the model perform in a deterministic way, does that cause longer training time until minimal loss is found, or is that minimal loss worse than when the model is non-deterministic?

For completeness' sake, I manually make the model deterministic by setting all of these properties:

def set_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    np.random.seed(seed)
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)


问:
log4net: udp appender to splunk only logs first character
I have a simple application which should forward all logs to a splunk server. For this I use log4net with the udp appender.

The problem is only the first character seems logged in splunk:

Image: https://imgur.com/7BULi1l

I traced the request with wireshark:

```<code>¬)yElb!
J
ÿ-X,Ñ[date=2019-05-27 15:00:27,489] [level=INFO ] [environment=xxx] [hostname=xxx] [type=web] [logger=SplunkLogger] [message=Working on 634726506325099884]
</code>```

There is another tool we use that is using log4net too and this one works without problems. Sadly I have no access to the source. So I think the splunk server is configured correctly.

log4net.conf

```<code><?xml version="1.0" encoding="utf-8"?>
<log4net>

  <root>
    <level value="INFO" />
    <appender-ref ref="SplunkAppender" />
    <appender-ref ref="FileAppender" />
  </root>

  <logger name="SecurityLogging">
    <level value="ERROR" />
  </logger>

    <appender name="SplunkAppender" type="log4net.Appender.UdpAppender">
      <threshold value="INFO" />
      <remoteAddress value="xxxx" />
      <remotePort value="xxxx" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[date=%date] [level=%-5level] [environment=xxxx] [hostname=%property{log4net:HostName}] [type=web] [logger=%logger] [message=%message]" />
      </layout>
    </appender>

    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log-file.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[date=%date] [level=%-5level] [environment=xxxx] [hostname=%property{log4net:HostName}] [type=web] [logger=%logger] [message=%message]" />
      </layout>
    </appender>

</log4net>
</code>```

答:
After finding out, that the sent udp request was different between .net and .net core, I had the assumption that maybe the encoding seems to be the problem.

Adding

```<code><encoding value="utf-8" />
</code>```

to the appender section did solve the problem.

Body:
I have a simple application which should forward all logs to a splunk server. For this I use log4net with the udp appender.

The problem is only the first character seems logged in splunk:

Image: https://imgur.com/7BULi1l

I traced the request with wireshark:

¬)yElb!
J
ÿ-X,Ñ[date=2019-05-27 15:00:27,489] [level=INFO ] [environment=xxx] [hostname=xxx] [type=web] [logger=SplunkLogger] [message=Working on 634726506325099884]

There is another tool we use that is using log4net too and this one works without problems. Sadly I have no access to the source. So I think the splunk server is configured correctly.

log4net.conf

<?xml version="1.0" encoding="utf-8"?>
<log4net>

  <root>
    <level value="INFO" />
    <appender-ref ref="SplunkAppender" />
    <appender-ref ref="FileAppender" />
  </root>

  <logger name="SecurityLogging">
    <level value="ERROR" />
  </logger>

    <appender name="SplunkAppender" type="log4net.Appender.UdpAppender">
      <threshold value="INFO" />
      <remoteAddress value="xxxx" />
      <remotePort value="xxxx" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[date=%date] [level=%-5level] [environment=xxxx] [hostname=%property{log4net:HostName}] [type=web] [logger=%logger] [message=%message]" />
      </layout>
    </appender>

    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log-file.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[date=%date] [level=%-5level] [environment=xxxx] [hostname=%property{log4net:HostName}] [type=web] [logger=%logger] [message=%message]" />
      </layout>
    </appender>

</log4net>

Body:
After finding out, that the sent udp request was different between .net and .net core, I had the assumption that maybe the encoding seems to be the problem.

Adding

<encoding value="utf-8" />

to the appender section did solve the problem.


问:
Sending signal. PID: 6939 SIG: 9 with zxing QR code scanner
I'm developing an app with an embedded QR code reader, after that the code is scanned, I have to start another activity (named CodaActivity.class) with a parameter taken from the qrcode.

I started from a tutorial found here:(https://www.androidtutorialonline.com/android-qr-code-scanner/)
and I tryied to customize it for my needs.

this is the code of the QRCodeScannerActivity:

```<code>import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;

public class QrCodeScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView mScannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();

            } else {
                requestPermission();
            }
        }

    }

    private boolean checkPermission() {
        return ( ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA ) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{CAMERA},
                                                            REQUEST_CAMERA);
                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(QrCodeScannerActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(mScannerView == null) {
                    mScannerView = new ZXingScannerView(this);
                    setContentView(mScannerView);
                }
                mScannerView.setResultHandler(this);
                mScannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mScannerView.stopCamera();
    }
    @Override
    public void handleResult(Result rawResult) {

        final String testoLink = rawResult.getText();
        String[] risultato = testoLink.split(":");
        risultato[1] = risultato[1].trim();
        Log.e("QRCodeScanner", rawResult.getText());
        Intent intent = new Intent(QrCodeScannerActivity.this, CodaActivity.class);
        Bundle b = new Bundle();
        b.putString("medico", risultato[1]);
        intent.putExtras(b);
        startActivity(intent);
        finish();

    }

}
</code>```

But after I scan the QR code (of course with a physical device), the debbugger exit with the following message:

```<code>I/art: Object allocation is busy now, so prior to grow the heap. New heap size is 33 MB
I/art: current process_level is : 0
I/art: current process_level is : 0
I/art: current process_level is : 0
I/art: current process_level is : 0
I/art: current process_level is : 0
I/Process: Sending signal. PID: 8310 SIG: 9
Application terminated.
</code>```

the app in the phone still remain up, but goes to a different activity.
Why? and why I got no errors!
Thanks for any answer

答:
After much testing and with another phone (with oreo) I finally found that I was wrong to split the string, the token was wrong but with the previous phone (android 6) no exception was thrown, so I couldn't figure out what was happening. furthermore, looking more closely at the code, I inserted the finish () statement before the startActivity () call ...

I hope this can help someone.

Body:
I'm developing an app with an embedded QR code reader, after that the code is scanned, I have to start another activity (named CodaActivity.class) with a parameter taken from the qrcode.

I started from a tutorial found here:(https://www.androidtutorialonline.com/android-qr-code-scanner/)
and I tryied to customize it for my needs.

this is the code of the QRCodeScannerActivity:

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;

public class QrCodeScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView mScannerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();

            } else {
                requestPermission();
            }
        }

    }

    private boolean checkPermission() {
        return ( ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA ) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{CAMERA},
                                                            REQUEST_CAMERA);
                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(QrCodeScannerActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(mScannerView == null) {
                    mScannerView = new ZXingScannerView(this);
                    setContentView(mScannerView);
                }
                mScannerView.setResultHandler(this);
                mScannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mScannerView.stopCamera();
    }
    @Override
    public void handleResult(Result rawResult) {

        final String testoLink = rawResult.getText();
        String[] risultato = testoLink.split(":");
        risultato[1] = risultato[1].trim();
        Log.e("QRCodeScanner", rawResult.getText());
        Intent intent = new Intent(QrCodeScannerActivity.this, CodaActivity.class);
        Bundle b = new Bundle();
        b.putString("medico", risultato[1]);
        intent.putExtras(b);
        startActivity(intent);
        finish();

    }

}

But after I scan the QR code (of course with a physical device), the debbugger exit with the following message:

I/art: Object allocation is busy now, so prior to grow the heap. New heap size is 33 MB
I/art: current process_level is : 0
I/art: current process_level is : 0
I/art: current process_level is : 0
I/art: current process_level is : 0
I/art: current process_level is : 0
I/Process: Sending signal. PID: 8310 SIG: 9
Application terminated.

the app in the phone still remain up, but goes to a different activity.
Why? and why I got no errors!
Thanks for any answer


问:
what is the procedure in SQL server to not execute anything(T SQL commands) but outputs the commands it would execute
what is the procedure in SQL server to not execute anything(T SQL commands) but outputs the commands it would execute</p>

答: Are you thinking of SET SHOWPLAN_TEXT ON?


问:
How to force an HTML form to validate without submitting it via jQuery
I have this form in my app and I will submit it via AJAX, but I want to use HTML for client-side validation. So I want to be able to force the form validation, perhaps via jQuery.

I want to trigger the validation without submitting the form. Is it possible?

答:
I think the best approach

will be using jQuery Validation plugin which uses best practice for form validation and it also has good browser support. So you don't need to worry about browser compatibility issues.

And we can use jQuery validation valid() function which checks whether the selected form is valid or whether all selected elements are valid without submitting the form.

```<code><form id="myform">
   <input type="text" name="name" required>
   <br>
   <button type="button">Validate!</button>
</form>
<script>
  var form = $( "#myform" );
  form.validate();
  $( "button" ).click(function() {
    console.log( "Valid: " + form.valid() );
  });
</script>
</code>```

Body:
I think the best approach

will be using jQuery Validation plugin which uses best practice for form validation and it also has good browser support. So you don't need to worry about browser compatibility issues.

And we can use jQuery validation valid() function which checks whether the selected form is valid or whether all selected elements are valid without submitting the form.

<form id="myform">
   <input type="text" name="name" required>
   <br>
   <button type="button">Validate!</button>
</form>
<script>
  var form = $( "#myform" );
  form.validate();
  $( "button" ).click(function() {
    console.log( "Valid: " + form.valid() );
  });
</script>


问:
Getting indexPath of tableView inside tableViewCell file during cell creation/dequeueing
I am creating a scrollable view filled with monthly calendars. I'm using a collection view to display a calendar inside a table view full of calendars. So each table view cell is a calendar for a specific month, and each collection view cell is a day. I have a separate swift file for the tableview cell from the view controller. Since each tableview cell is going to look different (because different months), the tableview cell needs to know which row it is placed in inside the tableview during its creation in dequeque cell function.

```<code>tableView.dequeueReusableCell(withIdentifier: "CalendarTableViewCell", for: indexPath)
</code>```

I need to get the indexPath in the "for: indexPath" parameter inside the tableview cell file because the collectionview inside the tableview cell gets created when the tableview cell is dequeued. The contents of the collection view depends on which tableview row it's in. So how do I get that parameter?

Sorry for the long explanation, please help if possible. Thank you!

答:
Create an array in UITableViewCell subclass and use that array in collection view data source methods.

```<code>class MonthCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    let datesArray = [String]()
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datesArray.count
    }
}
</code>```

In tableView cellForRowAt method assign the date values and reload the collectionView

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! MonthCell
    cell.datesArray = []//dates based on indexPath
    cell.collectionView.reloadData()
    return cell
}
</code>```

Or

Assign a reference to the table view cell index path in tableView cellForRowAt method

```<code>class MonthCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var tableIndexPath:IndexPath?
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let tableIndexPath {
            // return value based on tableIndexPath
        } else {
            return 0
        }
    }
}
</code>```

//cellForRowAt

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MonthCell") as! MonthCell
    cell.tableIndexPath = indexPath
    cell.collectionView.reloadData()
    return cell
}
</code>```

Body:
I am creating a scrollable view filled with monthly calendars. I'm using a collection view to display a calendar inside a table view full of calendars. So each table view cell is a calendar for a specific month, and each collection view cell is a day. I have a separate swift file for the tableview cell from the view controller. Since each tableview cell is going to look different (because different months), the tableview cell needs to know which row it is placed in inside the tableview during its creation in dequeque cell function.

tableView.dequeueReusableCell(withIdentifier: "CalendarTableViewCell", for: indexPath)

I need to get the indexPath in the "for: indexPath" parameter inside the tableview cell file because the collectionview inside the tableview cell gets created when the tableview cell is dequeued. The contents of the collection view depends on which tableview row it's in. So how do I get that parameter?

Sorry for the long explanation, please help if possible. Thank you!

Body:
Create an array in UITableViewCell subclass and use that array in collection view data source methods.

class MonthCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    let datesArray = [String]()
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datesArray.count
    }
}

In tableView cellForRowAt method assign the date values and reload the collectionView

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! MonthCell
    cell.datesArray = []//dates based on indexPath
    cell.collectionView.reloadData()
    return cell
}

Or

Assign a reference to the table view cell index path in tableView cellForRowAt method

class MonthCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var tableIndexPath:IndexPath?
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let tableIndexPath {
            // return value based on tableIndexPath
        } else {
            return 0
        }
    }
}

//cellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MonthCell") as! MonthCell
    cell.tableIndexPath = indexPath
    cell.collectionView.reloadData()
    return cell
}


问:
Deleting a cell in tableview, the cell also can be reused,why?
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?</p>

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}
</code>```

答:
I think You can use

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d",indexPath.row];

instead of

NSString * CellIdentifier=tempmodel.PDFName;

please replace it & check it. I think it's helpful to you.

Body:
at first,i delete one cell in tableView,then i want to add another new cell in the tableView,but the  new cell is not new,it is just the cell which i delete. i know what dequeueReusableCellWithIdentifier means.i think when  delete one cell,the cache in dequeueReusableCellWithIdentifier is also deleted.why not?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"table reload");

    PDFModel* tempmodel=[PDFArray objectAtIndex:indexPath.row];
    NSString * CellIdentifier=tempmodel.PDFName;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSLog(@"cell %x",cell);
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
       //custom the cell
        cell.text=...
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete)
    {
         [PDFArray removeObjectAtIndex:indexPath.row];
         NSMutableArray* array=[[NSMutableArray alloc] init];
         [array addObject:indexPath];
         [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationRight];

    }
}


问:
Least repeating chararcter in a string
I'm trying to find the least repeating character in a string ,it works for some input but it fails for some input.

```<code>Map<Character, Integer> map = new HashMap<Character, Integer> ();

    String s = "abcdabcdabcdacd";
    char[] chars = s.toCharArray();

    for (Character ch: chars) {
        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }

    Set<Character> keys = map.keySet();

    for (Character ch: keys) {
        if (map.get(ch) ==1) {
            System.out.println(ch + " ");
        }
    }
</code>```

I expect the output to be b but it doesn't show anything.
If i give aabaa as the input then it shows b and that's correct.

答:
You have to read the whole map to get the min occurrence, so you can't print in the loop, you should instead collect chars with min occurence, and then print them.</p>

```<code>    public static void main(String[] args) {
        Map<Character, Integer> map = new HashMap<>();

        String s = "abcdaybcdabcdacdz";
        char[] chars = s.toCharArray();

        for (Character ch: chars) {
            if (map.containsKey(ch)) {
                map.put(ch, map.get(ch) + 1);
            } else {
                map.put(ch, 1);
            }
        }

        List<Character> reps = new ArrayList<>();

        Integer count = chars.length;
        Set<Entry<Character, Integer>> entries = map.entrySet();
        for (Entry<Character, Integer> entry : entries) {
            Integer n = entry.getValue();
            Character c = entry.getKey();
            if(n==count) {
                reps.add(c);
            }else if (n<count) {
                reps = new ArrayList<>();
                reps.add(c);
                count = n;
            }
        }

        for (Character character : reps) {
            System.out.println(character);
        }

    }
</code>```

Title: Least repeating chararcter in a string

Body:
I'm trying to find the least repeating character in a string ,it works for some input but it fails for some input.

Map<Character, Integer> map = new HashMap<Character, Integer> ();

    String s = "abcdabcdabcdacd";
    char[] chars = s.toCharArray();

    for (Character ch: chars) {
        if (map.containsKey(ch)) {
            map.put(ch, map.get(ch) + 1);
        } else {
            map.put(ch, 1);
        }
    }

    Set<Character> keys = map.keySet();

    for (Character ch: keys) {
        if (map.get(ch) ==1) {
            System.out.println(ch + " ");
        }
    }

I expect the output to be b but it doesn't show anything.
If i give aabaa as the input then it shows b and that's correct.

Body:
You have to read the whole map to get the min occurrence, so you can't print in the loop, you should instead collect chars with min occurence, and then print them.

    public static void main(String[] args) {
        Map<Character, Integer> map = new HashMap<>();

        String s = "abcdaybcdabcdacdz";
        char[] chars = s.toCharArray();

        for (Character ch: chars) {
            if (map.containsKey(ch)) {
                map.put(ch, map.get(ch) + 1);
            } else {
                map.put(ch, 1);
            }
        }

        List<Character> reps = new ArrayList<>();

        Integer count = chars.length;
        Set<Entry<Character, Integer>> entries = map.entrySet();
        for (Entry<Character, Integer> entry : entries) {
            Integer n = entry.getValue();
            Character c = entry.getKey();
            if(n==count) {
                reps.add(c);
            }else if (n<count) {
                reps = new ArrayList<>();
                reps.add(c);
                count = n;
            }
        }

        for (Character character : reps) {
            System.out.println(character);
        }

    }


问:
white space between images in owl carousel 2
I am trying simple slider in owl carousel but there's space between images. How to remove space between images in owl- carousel 2? I tried to increase items but it removes the arrow button.
In mobile view, space is even more between two images. Please help.
Thank you

main.js

```<code>$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
        autoWidth:false,
        items:3,
        loop:true,
        margin:10,
        autoplay:true,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        dots: false,
        stagePadding:40,
        nav:true,
        navText: ['<i class="fas fa-chevron-left" aria-hidden="true"></i>','<i class="fas fa-chevron-right" aria-hidden="true"></i>'],
        responsive:{
            0:{
                items:2
            },
            600:{
                items:2
            },
            1000:{
                items:5
            }
        }
    })
  });
</code>```

style.css

```<code>  .owl-carousel .item img{
    height:120px;
    width:120px;
}

.owl-item .active{
    height:120px;
    width:120px;
}
.owl-carousel .item{
    text-align: center;
}

/* owl nav */
.owl-prev i, .owl-next i {
    color: #000000;
}

.owl-prev, .owl-next {
    position:absolute;
    top: 0;
    height:30%;
    -webkit-border-radius: 40px;
    -moz-border-radius: 40px;
    border-radius: 30px;
    background: #869791;

}

.owl-prev {
    left:0;
    top: 42px;
}

.owl-next {
    right:0;
    top: 42px;
}
/* removing blue outline from buttons */
.owl-next:focus, .owl-prev:focus
 {
     outline: none;
}

.caroussel-theme{
    background-color: aquamarine
}
.container-fluid {
    max-width: 1230px;
}
.text-content{
    color:#000000;
    font-size:16px;
    font-family: 'Georgia, 'Times New Roman', Times, serif';
}
div.owl-item > div {
    display:table-cell;
    vertical-align:middle;
}
.owl-stage{
    width:150px;
}
</code>```

Image:
image that shows space between two images

答:
Just set the margin to 0 and done!

```<code>$('.owl-carousel').owlCarousel({
  stagePadding: 0,
  items: 1,
  loop:true,
  margin:0,
  singleItem:true,
  nav:true,
  navText: [
      "<i class='fa fa-caret-left'></i>",
      "<i class='fa fa-caret-right'></i>"
  ],
  dots:true
});
</code>```

and also look for the ratio of the images sometimes that also makes issues

here is my pen
https://codepen.io/nick4434/pen/ZNMawQ

Body:
I am trying simple slider in owl carousel but there's space between images. How to remove space between images in owl- carousel 2? I tried to increase items but it removes the arrow button.
In mobile view, space is even more between two images. Please help.
Thank you

main.js

$(document).ready(function(){
    $('.owl-carousel').owlCarousel({
        autoWidth:false,
        items:3,
        loop:true,
        margin:10,
        autoplay:true,
        autoplayTimeout:2000,
        autoplayHoverPause:true,
        dots: false,
        stagePadding:40,
        nav:true,
        navText: ['',''],
        responsive:{
            0:{
                items:2
            },
            600:{
                items:2
            },
            1000:{
                items:5
            }
        }
    })
  });

style.css

  .owl-carousel .item img{
    height:120px;
    width:120px;
}

.owl-item .active{
    height:120px;
    width:120px;
}
.owl-carousel .item{
    text-align: center;
}

/* owl nav */
.owl-prev i, .owl-next i {
    color: #000000;
}

.owl-prev, .owl-next {
    position:absolute;
    top: 0;
    height:30%;
    -webkit-border-radius: 40px;
    -moz-border-radius: 40px;
    border-radius: 30px;
    background: #869791;

}

.owl-prev {
    left:0;
    top: 42px;
}

.owl-next {
    right:0;
    top: 42px;
}
/* removing blue outline from buttons */
.owl-next:focus, .owl-prev:focus
 {
     outline: none;
}

.caroussel-theme{
    background-color: aquamarine
}
.container-fluid {
    max-width: 1230px;
}
.text-content{
    color:#000000;
    font-size:16px;
    font-family: 'Georgia, 'Times New Roman', Times, serif';
}
div.owl-item > div {
    display:table-cell;
    vertical-align:middle;
}
.owl-stage{
    width:150px;
}

Image:
image that shows space between two images

Body:
Just set the margin to 0 and done!

$('.owl-carousel').owlCarousel({
  stagePadding: 0,
  items: 1,
  loop:true,
  margin:0,
  singleItem:true,
  nav:true,
  navText: [
      "<i class='fa fa-caret-left'></i>",
      "<i class='fa fa-caret-right'></i>"
  ],
  dots:true
});

and also look for the ratio of the images sometimes that also makes issues

here is my pen
https://codepen.io/nick4434/pen/ZNMawQ


问:
Linq Unit Test Suite
There are a set of 101 samples for LINQ here

I am sure I've seen someone make reference to a set of unit tests that test this functionality. It's primarily for someone creating a LINQ provider to make sure they implement everything correctly.

Can anyone provide a link to these unit tests if they exist?

答:
BackLINQ (http://www.raboof.com/Projects/BackLINQ/) is a project which implements a number of LINQ operations against .NET 2.0. The project is open source and they have posted the source code for their unit tests (http://backlinq.googlecode.com/svn/trunk/test/BackLINQ.Tests/EnumerableFixture.cs). You may be able to adapt these tests for your needs.

There is also a CodePlex hosted project called 'A custom implementation of the .NET Standard Query Operators from LINQ' (http://linqsqo.codeplex.com/), which includes the source for a similar test suite.

Title: Linq Unit Test Suite


问:
Docker fails to build in Azure Pipelines with "error MSB1001"
Am facing strange issue. When i build my Dockerfile on windows machine(Laptop) getting below error and also getting same error when i tried to deploy on Azure DevOps.

```<code>Step 7/17 : COPY ["WebApp.csproj", ""]
 ---> 3f3e198d00aa
Step 8/17 : RUN dotnet restore "/WebApp.csproj"
 ---> Running in 51f16f947ffb
MSBUILD : error MSB1001: Unknown switch.
Switch: /WebApp.csproj

For switch syntax, type "MSBuild -help"
The command '/bin/sh -c dotnet restore "/WebApp.csproj"' returned a non-zero code: 1
PS C:\Users\user\Desktop\Directory>
</code>```

But the same Dockerfile works fine when we build it using visual studio it builds and starts running without any errors.

Docker file looks like:

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["WebApp.csproj", ""]
RUN dotnet restore "/WebApp.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "WebApp.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "WebApp.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "WebApp.dll"]
</code>```

答:
Because in your dotnet restore there is / so MSBuild think it's a switch (like /p:) and fails, you just need to remove it:

```<code>RUN dotnet restore "WebApp.csproj"
</code>```

Body:
Am facing strange issue. When i build my Dockerfile on windows machine(Laptop) getting below error and also getting same error when i tried to deploy on Azure DevOps.

Step 7/17 : COPY ["WebApp.csproj", ""]
 ---> 3f3e198d00aa
Step 8/17 : RUN dotnet restore "/WebApp.csproj"
 ---> Running in 51f16f947ffb
MSBUILD : error MSB1001: Unknown switch.
Switch: /WebApp.csproj

For switch syntax, type "MSBuild -help"
The command '/bin/sh -c dotnet restore "/WebApp.csproj"' returned a non-zero code: 1
PS C:\Users\user\Desktop\Directory>

But the same Dockerfile works fine when we build it using visual studio it builds and starts running without any errors.

Docker file looks like:

FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build
WORKDIR /src
COPY ["WebApp.csproj", ""]
RUN dotnet restore "/WebApp.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "WebApp.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "WebApp.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "WebApp.dll"]

Body:
Because in your dotnet restore there is / so MSBuild think it's a switch (like /p:) and fails, you just need to remove it:

RUN dotnet restore "WebApp.csproj"


问:
Assertion in [AfterStep] doesn't set ScenarioContext.Current.TestError
In [AfterStep] I fail test:

```<code>[AfterStep]
public void StopOnUnexpectedBrowserLogs()
{
    Assert.Fail("sth sth");
}
</code>```

and then in [AfterScenario] I want to act when test is failed:

```<code>[AfterScenario]
public void AfterScenario()
    if (ScenarioContext.Current.TestError != null)
    {
       DoSomething();
    }
}
</code>```

however ScenarioContext.Current.TestErrors is always null in that case. How can I force something to be assigned there in [AfterStep] method?

答:
I didn't find solution but only workaround. I tested that any failing asserion in method annotated by [AfterScenario] doesn't set TestError property. TestError property is assigned only if asserion fails in Then,When,Given etc. annotated methods.
Thus I just added a simple public bool SthBadHappened {get;set;} property that I use as my TestError property.

Body:
In [AfterStep] I fail test:

[AfterStep]
public void StopOnUnexpectedBrowserLogs()
{
    Assert.Fail("sth sth");
}

and then in [AfterScenario] I want to act when test is failed:

[AfterScenario]
public void AfterScenario()
    if (ScenarioContext.Current.TestError != null)
    {
       DoSomething();
    }
}

however ScenarioContext.Current.TestErrors is always null in that case. How can I force something to be assigned there in [AfterStep] method?


问:
How to fix "REQUEST_DENIED" while getting current location in cordova
I am trying get current location with address by using Cordova geolocation plugin . but i am getting   below error message.
{error_message: "You must use an API key to authenticate each reque…, please refer to http://g.co/dev/maps-no-account", results: Array(0), status: "REQUEST_DENIED"}
error_message: "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"
results: []
status: "REQUEST_DENIED"

for getting current location. below code i am using please correct my code

$scope.init = function () {

```<code>    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {

    if (navigator.connection.type == Connection.NONE) {

    } else {

    }
    var networkConnection = navigator.connection.type;

    if (networkConnection != null) {

        navigator.geolocation.getCurrentPosition(success, error);
    }
    else {
        alert('Please check your network connection and try again.');
    }
}

function success(position) {

    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    getDetails(latitude, longitude);
}

function error(error) {
    alert('Please check your network connection and try again.');
}

function getDetails(latitude, longitude) {

    var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=false";
    $.getJSON(url, function (data) {

        console.log(data);

    });
}
</code>```

Please correct my code i expected out put current location with address. Thanks for advance.

答:
You must use an API key

When you signed up for the maps platform, you should have gotten an access key, which you need to pass with every request to authenticate.

Now, as far as i can see, you don't have that token on your URL parameters. ( You may need to send it with the request headers, check the API docs on how it expects it)

EDIT:

This is the format:

```<code>https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap
</code>```

Try this:

```<code>var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"ADD YOUR KEY HERE" + "&sensor=false";

</code>```

Also, try using template strings rather than having 10s of + in your string

Body:
I am trying get current location with address by using Cordova geolocation plugin . but i am getting   below error message.
{error_message: "You must use an API key to authenticate each reque…, please refer to http://g.co/dev/maps-no-account", results: Array(0), status: "REQUEST_DENIED"}
error_message: "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"
results: []
status: "REQUEST_DENIED"

for getting current location. below code i am using please correct my code

$scope.init = function () {

    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {

    if (navigator.connection.type == Connection.NONE) {

    } else {

    }
    var networkConnection = navigator.connection.type;

    if (networkConnection != null) {

        navigator.geolocation.getCurrentPosition(success, error);
    }
    else {
        alert('Please check your network connection and try again.');
    }
}

function success(position) {

    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    getDetails(latitude, longitude);
}

function error(error) {
    alert('Please check your network connection and try again.');
}

function getDetails(latitude, longitude) {

    var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=false";
    $.getJSON(url, function (data) {

        console.log(data);

    });
}

Please correct my code i expected out put current location with address. Thanks for advance.

Body:
You must use an API key

When you signed up for the maps platform, you should have gotten an access key, which you need to pass with every request to authenticate.

Now, as far as i can see, you don't have that token on your URL parameters. ( You may need to send it with the request headers, check the API docs on how it expects it)

EDIT:

This is the format:

https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap

Try this:

var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"ADD YOUR KEY HERE" + "&sensor=false";

Also, try using template strings rather than having 10s of + in your string


问:
Is it mandatory to check FileExists() before DeleteFile()?
Some time ago, I do not remember where, I read about a best practice in delphi.

Instead of this:

if FileExists(MyFile) then begin
        if not DeleteFile(MyFile) then
                ShowMessage('Unable to delete file');
end;
```

<p>write this:</p>

<pre class="lang-pascal prettyprint-override"><code>if not DeleteFile(MyFile) then
        ShowMessage('Unable to delete file');
</code>```

What are the pro and cons of he second?

答:
Calling FileExists() is pointless.

The file may exist, but not be deletable - e.g. if it is read/only, or locked by another process. It won't be faster than calling DeleteFile().

So the 2nd version is preferred:

```<code>if not DeleteFile(MyFile) then
    ShowMessage('Unable to delete file');
</code>```

Note: DeleteFile() from SysUtils.pas is cross-platform, and returns a boolean for success - since the comments and some answer only deal with the raw API call from Windows.pas.

Body:
Some time ago, I do not remember where, I read about a best practice in delphi.

Instead of this:

if FileExists(MyFile) then begin
        if not DeleteFile(MyFile) then
                ShowMessage('Unable to delete file');
end;

write this:

if not DeleteFile(MyFile) then
        ShowMessage('Unable to delete file');

What are the pro and cons of he second?

Body:
Calling FileExists() is pointless.

The file may exist, but not be deletable - e.g. if it is read/only, or locked by another process. It won't be faster than calling DeleteFile().

So the 2nd version is preferred:

if not DeleteFile(MyFile) then
    ShowMessage('Unable to delete file');

Note: DeleteFile() from SysUtils.pas is cross-platform, and returns a boolean for success - since the comments and some answer only deal with the raw API call from Windows.pas.


问:
How to efficiently syntax
I wrote some code. I realized when I wanted to expand the code below, it would make the syntax wasteful.
how to make it efficient?</p>

```<code>a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))
#This is for 1 digit printed
if b == 1:
   for i in a:
        print(i)
#This is for 2 digit printed
elif b == 2:
    for i in a:
        for j in a:
           print(i,j)

#This is for 3 digit printed
    elif b == 2:
        for i in a:
            for j in a:
                for k in a:
                   print(i,j,k)
</code>```

答:
itertools.product would simplify your code:

```<code>import itertools

a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))

for i in itertools.product(a, repeat=b):
    print(" ".join(i))
</code>```

Title: How to efficiently syntax

Body:
I wrote some code. I realized when I wanted to expand the code below, it would make the syntax wasteful.
how to make it efficient?

a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))
#This is for 1 digit printed
if b == 1:
   for i in a:
        print(i)
#This is for 2 digit printed
elif b == 2:
    for i in a:
        for j in a:
           print(i,j)

#This is for 3 digit printed
    elif b == 2:
        for i in a:
            for j in a:
                for k in a:
                   print(i,j,k)

Body:
itertools.product would simplify your code:

import itertools

a = ['a', 'b', 'c', 'd', 'e']
b = int(input("Number of digit:\n"))

for i in itertools.product(a, repeat=b):
    print(" ".join(i))


问:
Tests stop working under xcode 8 TEST_HOST error
I want to start tests under Xcode 8 and it fail in the beginning. My error is:

Could not determine bundle identifier for MyProjectTest's TEST_HOST:
  "/Users/jakubmazur/Library/Developer/Xcode/DerivedData/MyProject-ejeepybggxvekxajlyngopeahiex/Build/Intermediates/CodeCoverage/Products/Testing-iphonesimulator/MyProject.app"

Any idea what's wrong here? I try to clean project - nothing.
In the Build Settings in my target in Packaging i change Product Bundle Identifier depends on configuration in my schema. It can have something to do with that, but not sure.

-- EDIT

Ok figure how to narrow the problem. When i change settings in scheme to use Build Configuration Debug instead of Testing seems to work, but I need separate configuration for testing.

答:
I too have a project with several schemes, and each of which builds the app using a separate configuration (Debug, AdHoc, etc.) and a separate product name (MyApp, MyApp_Dev, MyApp_Staging, etc.).

Thankfully, they all have the same Module name so my unit test source files can simply use @testable import MyApp, regardless of active scheme).

To overcome the error, I just had to make sure that for each scheme of the app target that I wanted to test, the following two matched:

The App Target's Build Settings > Product Name for that build configuration (.e.g, "Debug"),

The Test Target's Build Settings > Test Host for the same build configuration (the part after $(BUILT_PRODUCTS_DIR)...)

So, if #1 is (for example):

```<code>MyApp-Debug
</code>```

, then #2 must be:

```<code>$(BUILT_PRODUCTS_DIR)/MyApp-Debug.app/MyApp-Debug
</code>```

In my case, my scheme was building the AdHoc configuration with a product name ending with the -DEV (development) suffix, but the test target was looking for a host named ending with a suffix of -STG (staging).

Body:
I too have a project with several schemes, and each of which builds the app using a separate configuration (Debug, AdHoc, etc.) and a separate product name (MyApp, MyApp_Dev, MyApp_Staging, etc.).

Thankfully, they all have the same Module name so my unit test source files can simply use @testable import MyApp, regardless of active scheme).

To overcome the error, I just had to make sure that for each scheme of the app target that I wanted to test, the following two matched:

The App Target's Build Settings > Product Name for that build configuration (.e.g, "Debug"),

The Test Target's Build Settings > Test Host for the same build configuration (the part after $(BUILT_PRODUCTS_DIR)...)

So, if #1 is (for example):

MyApp-Debug

, then #2 must be:

$(BUILT_PRODUCTS_DIR)/MyApp-Debug.app/MyApp-Debug

In my case, my scheme was building the AdHoc configuration with a product name ending with the -DEV (development) suffix, but the test target was looking for a host named ending with a suffix of -STG (staging).


答:
This is probably the way to go, I think. This will print the way you want your elements to be combined. Read more about itertools

import itertools
a = ['a','b','c']
num = 2

if num == 2:
  a = [x for x in itertools.product(a, a)]

print(a)  # prints this : [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
```

Title: How to efficiently syntax