问:
Could not find a method onClick(View) in the activity class TintContextWrapper for onClick if using themes
I'm getting the Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton exception recently after adding the ability to select a dark or light theme for my app.

I do set the theme in the manifest and then I use following BaseActivity:

```<code>public abstract class BaseActivity extends AppCompatActivity
{
    private final int mLightTheme;
    private final int mDarkTheme;

    public BaseActivity(int lightTheme, int darkTheme)
    {
        mLightTheme = lightTheme;
        mDarkTheme = darkTheme;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(MainApp.getPrefs().darkTheme() ? mDarkTheme : mLightTheme);
        super.onCreate(savedInstanceState);
    }
}
</code>```

Any ideas what else could cause this issue? I got the issue from a device running 4.2.2...

NOT working solutions

similar issues suggest to remove the theme tag from the xml file => I'm not using it in my xml, so this is not the case for me

Stacktrace

```<code>java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'btBack'
    at android.view.View$1.onClick(View.java:3602)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    ... 11 more
    java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
For me magically worked setCompatVectorFromResourcesEnabled(true); like this:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    super.onCreate(savedInstanceState);
    ...
}
</code>```

Actually, it should be called only once and this could be done in Application class, not necessarily in Activity.

Honestly, I had this code line for other reasons but when tried to remove it, I got exactly this bug with onClick. So I put this line back and wow! Like a charm.

Body:
I'm getting the Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton exception recently after adding the ability to select a dark or light theme for my app.

I do set the theme in the manifest and then I use following BaseActivity:

public abstract class BaseActivity extends AppCompatActivity
{
    private final int mLightTheme;
    private final int mDarkTheme;

    public BaseActivity(int lightTheme, int darkTheme)
    {
        mLightTheme = lightTheme;
        mDarkTheme = darkTheme;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(MainApp.getPrefs().darkTheme() ? mDarkTheme : mLightTheme);
        super.onCreate(savedInstanceState);
    }
}

Any ideas what else could cause this issue? I got the issue from a device running 4.2.2...

NOT working solutions

similar issues suggest to remove the theme tag from the xml file => I'm not using it in my xml, so this is not the case for me

Stacktrace

java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'btBack'
    at android.view.View$1.onClick(View.java:3602)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    ... 11 more
    java.lang.NoSuchMethodException: onClick [class android.view.View]
    at java.lang.Class.getConstructorOrMethod(Class.java:460)
    at java.lang.Class.getMethod(Class.java:915)
    at android.view.View$1.onClick(View.java:3595)
    at android.view.View.performClick(View.java:4220)
    at android.view.View$PerformClick.run(View.java:17513)
    at android.os.Handler.handleCallback(Handler.java:800)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5455)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:966)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:733)
    at dalvik.system.NativeStart.main(Native Method)

Body:
For me magically worked setCompatVectorFromResourcesEnabled(true); like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    super.onCreate(savedInstanceState);
    ...
}

Actually, it should be called only once and this could be done in Application class, not necessarily in Activity.

Honestly, I had this code line for other reasons but when tried to remove it, I got exactly this bug with onClick. So I put this line back and wow! Like a charm.


来源: stackexchange

问:
Angular detect the form change
I have a template driven form with some fields. This form won't show up until some condition evaluates to true. And I would like to get notified when the value of any of those fields changes. So I have the following code:

The HTML:

```<code><form *ngIf="aCondition" #myForm="ngForm">
...
</form>
</code>```

The component:

```<code>@ViewChild('myForm') myForm: NgForm

aCondition: boolean = false;

ngOnInit() {
    this.myForm.form.valueChanges.subscribe(...);
}

changeCondition() {
    this.aCondition = true;
    this.myForm.form.valueChanges.subscribe(...);
}
</code>```

But in both event/function, this.myForm is undefined. Any ideas?

答:
to get reference of ViewChild with ngIf , you have to use a setter, it's called when the condition is true

```<code>private myForm: NgForm;

@ViewChild('myForm') set formRef(formRef: NgForm) {
 this.myForm= formref;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular detect the form change

Body:
I have a template driven form with some fields. This form won't show up until some condition evaluates to true. And I would like to get notified when the value of any of those fields changes. So I have the following code:

The HTML:

<form *ngIf="aCondition" #myForm="ngForm">
...
</form>

The component:

@ViewChild('myForm') myForm: NgForm

aCondition: boolean = false;

ngOnInit() {
    this.myForm.form.valueChanges.subscribe(...);
}

changeCondition() {
    this.aCondition = true;
    this.myForm.form.valueChanges.subscribe(...);
}

But in both event/function, this.myForm is undefined. Any ideas?

Body:
to get reference of ViewChild with ngIf , you have to use a setter, it's called when the condition is true

private myForm: NgForm;

@ViewChild('myForm') set formRef(formRef: NgForm) {
 this.myForm= formref;
}


问:
Reduce framerate of a video to have a GIF feeling in Swift
I have been trying to drop the framerate of a video to 10 or 15 frames per second. There are some OBJC related questions from 4/5 years ago. I could not find anything in swift..

This is what I am working on Playground:

```<code>import Cocoa
import AVKit

var assetWriter:AVAssetWriter?
var assetReader:AVAssetReader?
let bitrate:NSNumber = NSNumber(value:8000000)

func compressFile(urlToCompress: URL, outputURL: URL, completion:@escaping (URL)->Void){

    var videoFinished = false

    let asset = AVAsset(url: urlToCompress);

    do{
        assetReader = try AVAssetReader(asset: asset)
    } catch{
        assetReader = nil
    }

    guard let reader = assetReader else{
        fatalError("Could not initalize asset reader probably failed its try catch")
    }

    let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first!

    let videoReaderSettings: [String:Any] =  [(kCVPixelBufferPixelFormatTypeKey as String?)!:kCVPixelFormatType_32ARGB ]

    let videoSettings:[String:Any] = [
        AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey:bitrate],
        AVVideoCodecKey: AVVideoCodecType.h264,
        AVVideoHeightKey: videoTrack.naturalSize.height,
        AVVideoWidthKey: videoTrack.naturalSize.width
    ]

    let assetReaderVideoOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings)

    if reader.canAdd(assetReaderVideoOutput){
        reader.add(assetReaderVideoOutput)
    }else{
        fatalError("Couldn't add video output reader")
    }

    let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
    videoInput.transform = videoTrack.preferredTransform

    let videoInputQueue = DispatchQueue(label: "videoQueue")

    do{
        assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mov)
        assetWriter?.movieTimeScale = 1
    }catch{
        assetWriter = nil
    }
    guard let writer = assetWriter else{
        fatalError("assetWriter was nil")
    }

    writer.shouldOptimizeForNetworkUse = true
    writer.add(videoInput)

    writer.startWriting()
    reader.startReading()
    writer.startSession(atSourceTime: CMTime.zero)

    let closeWriter:()->Void = {
        // if (audioFinished && videoFinished){
        if (videoFinished){
            assetWriter?.finishWriting(completionHandler: {

                checkFileSize(sizeUrl: (assetWriter?.outputURL)!, message: "The file size of the compressed file is: ")
                completion((assetWriter?.outputURL)!)

            })

            assetReader?.cancelReading()

        }
    }

    videoInput.requestMediaDataWhenReady(on: videoInputQueue) {
        while(videoInput.isReadyForMoreMediaData){
            let sample = assetReaderVideoOutput.copyNextSampleBuffer()

            if (sample != nil){
                videoInput.append(sample!)
            }else{
                videoInput.markAsFinished()

                DispatchQueue.main.async {
                    videoFinished = true
                    closeWriter()
                }
                break;
            }
        }

    }

}

func checkFileSize(sizeUrl: URL, message:String){
    let data = NSData(contentsOf: sizeUrl)!
    print(message, (Double(data.length) / 1048576.0), " mb")
}

compressFile(urlToCompress: URL(fileURLWithPath: "/Users/koraybirand/Desktop/video.mp4"), outputURL: URL(fileURLWithPath: "/Users/koraybirand/Desktop/video5.mp4")) { (URL) in

}
</code>```

答:
Just used NextLevelSessionExporter... States that it is just for IOS but works on Mac Os X as well... Just modify:

```<code>internal func createVideoComposition()
.......
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate))
</code>```

replace frameRate with you own desired value

Body:
I have been trying to drop the framerate of a video to 10 or 15 frames per second. There are some OBJC related questions from 4/5 years ago. I could not find anything in swift..

This is what I am working on Playground:

import Cocoa
import AVKit

var assetWriter:AVAssetWriter?
var assetReader:AVAssetReader?
let bitrate:NSNumber = NSNumber(value:8000000)

func compressFile(urlToCompress: URL, outputURL: URL, completion:@escaping (URL)->Void){

    var videoFinished = false

    let asset = AVAsset(url: urlToCompress);

    do{
        assetReader = try AVAssetReader(asset: asset)
    } catch{
        assetReader = nil
    }

    guard let reader = assetReader else{
        fatalError("Could not initalize asset reader probably failed its try catch")
    }

    let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first!

    let videoReaderSettings: [String:Any] =  [(kCVPixelBufferPixelFormatTypeKey as String?)!:kCVPixelFormatType_32ARGB ]

    let videoSettings:[String:Any] = [
        AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey:bitrate],
        AVVideoCodecKey: AVVideoCodecType.h264,
        AVVideoHeightKey: videoTrack.naturalSize.height,
        AVVideoWidthKey: videoTrack.naturalSize.width
    ]

    let assetReaderVideoOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings)

    if reader.canAdd(assetReaderVideoOutput){
        reader.add(assetReaderVideoOutput)
    }else{
        fatalError("Couldn't add video output reader")
    }

    let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
    videoInput.transform = videoTrack.preferredTransform

    let videoInputQueue = DispatchQueue(label: "videoQueue")

    do{
        assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mov)
        assetWriter?.movieTimeScale = 1
    }catch{
        assetWriter = nil
    }
    guard let writer = assetWriter else{
        fatalError("assetWriter was nil")
    }

    writer.shouldOptimizeForNetworkUse = true
    writer.add(videoInput)

    writer.startWriting()
    reader.startReading()
    writer.startSession(atSourceTime: CMTime.zero)

    let closeWriter:()->Void = {
        // if (audioFinished && videoFinished){
        if (videoFinished){
            assetWriter?.finishWriting(completionHandler: {

                checkFileSize(sizeUrl: (assetWriter?.outputURL)!, message: "The file size of the compressed file is: ")
                completion((assetWriter?.outputURL)!)

            })

            assetReader?.cancelReading()

        }
    }

    videoInput.requestMediaDataWhenReady(on: videoInputQueue) {
        while(videoInput.isReadyForMoreMediaData){
            let sample = assetReaderVideoOutput.copyNextSampleBuffer()

            if (sample != nil){
                videoInput.append(sample!)
            }else{
                videoInput.markAsFinished()

                DispatchQueue.main.async {
                    videoFinished = true
                    closeWriter()
                }
                break;
            }
        }

    }

}

func checkFileSize(sizeUrl: URL, message:String){
    let data = NSData(contentsOf: sizeUrl)!
    print(message, (Double(data.length) / 1048576.0), " mb")
}

compressFile(urlToCompress: URL(fileURLWithPath: "/Users/koraybirand/Desktop/video.mp4"), outputURL: URL(fileURLWithPath: "/Users/koraybirand/Desktop/video5.mp4")) { (URL) in

}

Body:
Just used NextLevelSessionExporter... States that it is just for IOS but works on Mac Os X as well... Just modify:

internal func createVideoComposition()
.......
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate))

replace frameRate with you own desired value


问:
Can you IFERROR Importxml
I'm a beginner. I have the formula below which works to pull in the payment date from the table for stocks with a dividend (A9 is the stock ticker), but doesn't for stocks w/out a dividend (no table).

I get:

```<code>#value -"unable to parse query string from function query parameter 2: no column:Col6"
</code>```

I would like it to return 0.00 when there is no dividend.  Thanks

```<code>=QUERY(IMPORTXML(CONCATENATE("https://www.nasdaq.com/symbol/",A9,"/dividend-history"),"//tbody//tr[1]"),"select Col6 LIMIT 1")
</code>```

答:
Wrapping in IFERROR should be adequate:

```<code>=iferror(QUERY(IMPORTXML(CONCATENATE("https://www.nasdaq.com/symbol/",A9,"/dividend-history"),"//tbody//tr[1]"),"select Col6 LIMIT 1"),"")
</code>```

but if you must have 0.00 then:

```<code>=iferror(QUERY(IMPORTXML(CONCATENATE("https://www.nasdaq.com/symbol/",A9,"/dividend-history"),"//tbody//tr[1]"),"select Col6 LIMIT 1"),"0.00")
</code>```

Returns Text (for the sake of the required format).

Title: Can you IFERROR Importxml

Body:
I'm a beginner. I have the formula below which works to pull in the payment date from the table for stocks with a dividend (A9 is the stock ticker), but doesn't for stocks w/out a dividend (no table).

I get:

#value -"unable to parse query string from function query parameter 2: no column:Col6"

I would like it to return 0.00 when there is no dividend.  Thanks

=QUERY(IMPORTXML(CONCATENATE("https://www.nasdaq.com/symbol/",A9,"/dividend-history"),"//tbody//tr[1]"),"select Col6 LIMIT 1")

Body:
Wrapping in IFERROR should be adequate:

=iferror(QUERY(IMPORTXML(CONCATENATE("https://www.nasdaq.com/symbol/",A9,"/dividend-history"),"//tbody//tr[1]"),"select Col6 LIMIT 1"),"")

but if you must have 0.00 then:

=iferror(QUERY(IMPORTXML(CONCATENATE("https://www.nasdaq.com/symbol/",A9,"/dividend-history"),"//tbody//tr[1]"),"select Col6 LIMIT 1"),"0.00")

Returns Text (for the sake of the required format).


问:
For a shared resource accessed by two threads, how to arrange priority?
Is there a way to give one thread priority over another when accessing the resource?</p>

答:
No, and simply speaking: it makes no sense. Unless both threads try to get the ressource at EXACTLY the same time (very rare) a priority wont help, unless th thread with higher priority can "steal" the ressource already in use.

Basically you can never have more than one item waiting, so what use is a priority? With 3+ threads it makes logical sense, with 2 it is simply without any benefit.

ContentLicense: CC BY-SA 3.0


问:
Cannot change theme dynamically
I'm trying to change the theme of an app dynamically. But I can change it only when the app is alive. Means, when I kill the app and open it again, the default theme is applied.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
        public ArrayList<FTPFile> listfile=null;
        Intent men;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
            String choice=preferences.getString("CurrentTheme",null);

                Toast.makeText(getApplicationContext(),"Its"+ choice,Toast.LENGTH_SHORT).show();
           if(choice=="Light")
               this.setTheme(R.style.AppThemeLight);
           else
               this.setTheme(R.style.AppTheme);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
}
</code>```

AndroidManifest.xml

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity"  android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".file_explorer"  android:theme="@style/AppTheme" />
    <activity android:name=".settings"  android:theme="@style/AppTheme" />
</application>
</code>```

Code that changes value to shared preferences

```<code>SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
Editor editor=preferences.edit();
 RadioGroup rg=findViewById(R.id.radgrp);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.light:
                        Log.d("MRR","Light");
                        editor.putString("CurrentTheme","Light");
                        editor.apply();
                        break;
                    case R.id.dark:
                        Log.d("MRR","Dark");
                        editor.putString("CurrentTheme","Dark");
                        editor.apply();
                }
            }
        });
</code>```

答:
Put the code that changes the Theme in a new function outside of onCreate()/onStart()/onResume()

Example:

```<code>package ...;

import ..;

public class MainActivity(){
    protected void onCreate(){
        //...Your code...
    }
    protected void onStart(){
        //...Your code, if you have onStart()...
    }
    protected void onResume(){
        //...Your code, if you have onResume()...
    }
    changeTheme(int themeMode){
        //Add the code as I have told below
    }
}
</code>```

Call the function when the radiobutton's state is changed by the user.

(This is important as the listener is called for the first time even if you don't change it manually).

To check whether it was the user who changed it, and not the value in SharedPreferences, use onClickListener for the radio button instead of onCheckChangedListener.This way you know for sure the user has changed the value and not the value in SharedPreferences. Inside the OnClickListener, change the state of the radio button, to simulate the working of the radio button, and do the SharedPreferences value updation. This is just a workaround for the problem you have mentioned, do not use it if your app uses the radio button's state often to do other work, as these Listeners nested within themselves will take lot of space and CPU cycles.

Title: Cannot change theme dynamically

Body:
I'm trying to change the theme of an app dynamically. But I can change it only when the app is alive. Means, when I kill the app and open it again, the default theme is applied.

MainActivity.java

public class MainActivity extends AppCompatActivity {
        public ArrayList<FTPFile> listfile=null;
        Intent men;
        @Override
        protected void onCreate(Bundle savedInstanceState) {

            SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
            String choice=preferences.getString("CurrentTheme",null);

                Toast.makeText(getApplicationContext(),"Its"+ choice,Toast.LENGTH_SHORT).show();
           if(choice=="Light")
               this.setTheme(R.style.AppThemeLight);
           else
               this.setTheme(R.style.AppTheme);
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
}

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    tools:ignore="GoogleAppIndexingWarning">
    <activity android:name=".MainActivity"  android:theme="@style/AppTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".file_explorer"  android:theme="@style/AppTheme" />
    <activity android:name=".settings"  android:theme="@style/AppTheme" />
</application>

Code that changes value to shared preferences

SharedPreferences preferences=getSharedPreferences("ThemePreferences",MODE_PRIVATE);
Editor editor=preferences.edit();
 RadioGroup rg=findViewById(R.id.radgrp);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.light:
                        Log.d("MRR","Light");
                        editor.putString("CurrentTheme","Light");
                        editor.apply();
                        break;
                    case R.id.dark:
                        Log.d("MRR","Dark");
                        editor.putString("CurrentTheme","Dark");
                        editor.apply();
                }
            }
        });

Body:
Put the code that changes the Theme in a new function outside of onCreate()/onStart()/onResume()

Example:

package ...;

import ..;

public class MainActivity(){
    protected void onCreate(){
        //...Your code...
    }
    protected void onStart(){
        //...Your code, if you have onStart()...
    }
    protected void onResume(){
        //...Your code, if you have onResume()...
    }
    changeTheme(int themeMode){
        //Add the code as I have told below
    }
}

Call the function when the radiobutton's state is changed by the user.

(This is important as the listener is called for the first time even if you don't change it manually).

To check whether it was the user who changed it, and not the value in SharedPreferences, use onClickListener for the radio button instead of onCheckChangedListener.This way you know for sure the user has changed the value and not the value in SharedPreferences. Inside the OnClickListener, change the state of the radio button, to simulate the working of the radio button, and do the SharedPreferences value updation. This is just a workaround for the problem you have mentioned, do not use it if your app uses the radio button's state often to do other work, as these Listeners nested within themselves will take lot of space and CPU cycles.


问:
How to publish API hidden behind spring cloud gateway/custom gateway in WSO2 API Manager
Let me briefly describe the context. Near future will bring changes which means in short introducing API Management solution for the company (large). A lot of different systems around, SOAP, REST, some other protocols.

The goal is to have one marketplace when user/customer could easily search through those mess. The case is that most of the avaliable APIS/Services are behind departments gateways, there are many of services behind such GW coupled by deparment context mostly. The main goal of GW's is to protect backend services in a way that those gateways verifies token with Identity & Authorization Provider (one common for company).

How can i publish those services which are behind those gateways? There are no swagger definition available for most of them. I have some concept idea but would be more than happy to know production solution for that case.

答:
By using wso2 API Manager You can publish REST, SOAP, Websocket API's and you can provide different types of authentication like OAuth2, JWT, etc.

You can provide Scope(Authorization) for each API's

If you are a beginner wso2 API Manager is shipped with Pizza Shack API for learning purpose. Start the wso2 API management server and visit https://localhost:9443/publisher with authentication admin:admin. Once you visit the publisher portal it'll guide you to publish API.

Here is the link for documentation regarding the publishing of API's https://docs.wso2.com/display/AM210/API+Publishing

How can i publish those services which are behind those gateways?
  There are no swagger definition available for most of them. I have
  some concept idea but would be more than happy to know production
  solution for that case.

The swagger definition is another way of publishing API in API manager if you have already swagger definition you can just import. But whatever API's you'll publish in API manager inside it stores as a Swagger definition.

If you are using Wso2 API manager for Production use please refer the following:https://docs.wso2.com/display/AM260/Product+Administration which will describe the necessary changes and fine-tuning to be done for production.

Further if you can have multitenant setup, in which each tenant will have a separate store which is a great feature https://wso2.com/library/articles/2016/08/article-multi-tenant-api-management-with-wso2-api-manager/


问:
CQRS and Event Sourcing Guide
I want to create a CQRS and Event Sourcing architecture that is very cheap and very flexible and very uncomplicated.

I want to make sure that events never fail to at least reach the publisher/event store, ever, ever, because that's where business is.

Now, i have several options in mind:

Azure

With azure, i seem to not know what to use.

Azure service bus

Azure Function

Azure webjob (i suppose this can be replaced with Azure functions)

?? (something else i forgot or dont know?)

How reliable are these azure server-less solutions??

Custom

For this i am thinking of using RabbitMQ, the problem is the cost of a virtual machine to run it.

All in all, i want:

Ability to replay the messages/events in case of failure.

Ability to easily add subscribers.

Ability to select the subscribers upon which to replay the messages.

The Event store should be able to store very large sizes of event messages (or how else shall queue an image or file??).

The event store MUST NEVER EVER get chocked, or sleep.

Speed of implementation/prototyping would be an added
advantage.

What does your experience suggest?

What about other alternatives? (eg: apache-kafka)?

答:
Your requirements are too vague to make the optimal choice. You need to consider a lot of things, one of them would be, for instance, the numbers of events per one aggregate, the number of aggregates (note that this has to be statistical). Those are important primarily because if you allow tens of thousands of events for each aggregate then you would need to have snapshotting which adds complexity which you might not need.

But for regular use cases you could just use a relational database like Postgres as your (linearizable) event store. It also has a listen/notify functionality to you would not really need any message bus either and your application could be written in a reactive way.

Title: CQRS and Event Sourcing Guide


问:
How to share a SharePoint folder with an external user without requiring a Microsoft account
TL;DR:

How can I programatically share a SharePoint online folder with an external user such that the user only requires an access code and doesn't require a Microsoft account.

Full version:
I'm using SharePoint online. I want to share folders within the SharedDocuments list with external users. This is simple from the SharePoint front end - select the folder, choose Share, enter external users email address and select Copy Link.

SharePoint will generate a url which I can send to the external user. The external user visits the url to request an access code to be sent via email. Entering the access code allows the user to access the folder. User doesn't need a Microsoft account. Perfect.

I want to implement this in code (c# and csom). Specifically I want to be able to specify a folder and external email address(s) and retrieve the sharing URL.

I've tried:

Microsoft.SharePoint.Client.Web.CreateOrganizationSharingLink()
clientContext.Web.ShareDocument()
DocumentSharingManager.UpdateDocumentSharingInfo()
WebSharingManager.UpdateWebSharingInformation()

These methods all generate a link - however the link requires a Microsoft account. It's different to the link generated in the UI (above).

Is it possible to generate the access-code only link?

答:
You can install this library from Nuget OfficeDevPnP.Core. It includes an extension method for Web object to create anonymous URL.

Usage:
string sharedUrl = web.CreateAnonymousLinkForDocument("directUrlToTheItem", ExternalSharingDocumentOption.View);


问:
Manipulate some of the numeric value columns in a data frame that includes characters as well
I have a data frame with both character and numeric columns. In some of the numeric columns, I would like to test if the value is grater than 1 and if so, I would like to change it to 1.

I have managed to turn all different from 0 values to 1 but that includes characters and a column I want to leave untouched as well...

Example data frame:

```<code>> species<- c("Pinus halepensis", "Majorana syriaca", "Iris
> palaestina","Velezia fasciculata")
> rarness<- c("F", "CC", "F", "O")
> endangered<-c(0,0,0,6.8) plot1<- c(1,2,1,1) plot2<- c(0,1,0,0)
> df<-as.data.frame(cbind(species, rarness, endangered, plot1, plot2))
</code>```

This does not work for some reason:

```<code>Test<-df %>%
  mutate(plot1 = ifelse(plot1 > 1, 1, plot1))
</code>```

This works but changes characters as well

```<code>df[df>1]<-1
</code>```

I would like the columns "plot1" and "Plot2" to consist only of characters 0 and 1 while others remain the same.

Thanks!

Idan

答:
Mostly, that is because you have factors in your dataframe columns. You need to change the columns to numeric first before converting them to 1/0.

```<code>library(dplyr)

df %>%
 mutate_at(vars(plot1, plot2), ~as.integer(as.numeric(as.character(.)) > 1))

#              species rarness endangered plot1 plot2
#1    Pinus halepensis       F        0.0     0     0
#2    Majorana syriaca      CC        0.0     1     0
#3     Iris palaestina       F        0.0     0     0
#4 Velezia fasciculata       O        6.8     0     0
</code>```

Or similar using base R would be

```<code>df[4:5] <- lapply(df[4:5], function(x) as.integer(as.numeric(as.character(x)) > 1))
</code>```

Body:
I have a data frame with both character and numeric columns. In some of the numeric columns, I would like to test if the value is grater than 1 and if so, I would like to change it to 1.

I have managed to turn all different from 0 values to 1 but that includes characters and a column I want to leave untouched as well...

Example data frame:

> species<- c("Pinus halepensis", "Majorana syriaca", "Iris
> palaestina","Velezia fasciculata")
> rarness<- c("F", "CC", "F", "O")
> endangered<-c(0,0,0,6.8) plot1<- c(1,2,1,1) plot2<- c(0,1,0,0)
> df<-as.data.frame(cbind(species, rarness, endangered, plot1, plot2))

This does not work for some reason:

Test<-df %>%
  mutate(plot1 = ifelse(plot1 > 1, 1, plot1))

This works but changes characters as well

df[df>1]<-1

I would like the columns "plot1" and "Plot2" to consist only of characters 0 and 1 while others remain the same.

Thanks!

Idan

Body:
Mostly, that is because you have factors in your dataframe columns. You need to change the columns to numeric first before converting them to 1/0.

library(dplyr)

df %>%
 mutate_at(vars(plot1, plot2), ~as.integer(as.numeric(as.character(.)) > 1))

#              species rarness endangered plot1 plot2
#1    Pinus halepensis       F        0.0     0     0
#2    Majorana syriaca      CC        0.0     1     0
#3     Iris palaestina       F        0.0     0     0
#4 Velezia fasciculata       O        6.8     0     0

Or similar using base R would be

df[4:5] <- lapply(df[4:5], function(x) as.integer(as.numeric(as.character(x)) > 1))


问:
What's the fastest way to read from System.in in Java?
I am reading bunch of integers separated by space or newlines from the standard in using Scanner(System.in).

Is there any faster way of doing this in Java?

答:
StringTokenizer is a much faster way of reading string input separated by tokens.

Check below example to read a string of integers separated by space and store in arraylist,

```<code>String str = input.readLine(); //read string of integers using BufferedReader e.g. "1 2 3 4"
List<Integer> list = new ArrayList<>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
    list.add(Integer.parseInt(st.nextToken()));
}
</code>```

Body:
StringTokenizer is a much faster way of reading string input separated by tokens.

Check below example to read a string of integers separated by space and store in arraylist,

String str = input.readLine(); //read string of integers using BufferedReader e.g. "1 2 3 4"
List<Integer> list = new ArrayList<>();
StringTokenizer st = new StringTokenizer(str, " ");
while (st.hasMoreTokens()) {
    list.add(Integer.parseInt(st.nextToken()));
}


问:
How can I display an arraylist in a JList?
I want to display the all the details of elements in arraylist bikes in a Jlist. I've been trying to figure out how to do this for a while but I just can't crack it. The Jlist is part of a panel called pnlBikesTab.

ArrayList and JList

```<code> ArrayList<Bike> bikes = new ArrayList<Bike>();
 JList<String> lstBikes ;
</code>```

Populating Arraylist

```<code> public void Intial(){
//Add 12 bikes
 Bike b1 = new Bike(1, "Mountain", 12, "Not available") ;
    Bike b2 = new Bike(2, "Road", 10, "Available") ;
    Bike b3 = new Bike(3, "City", 8, "Available") ;
    Bike b4 = new Bike(4, "Mountain", 12, "Available") ;
    Bike b5 = new Bike(5, "Road", 10, "Available") ;
    Bike b6 = new Bike(6, "City", 8, "Available") ;
    Bike b7 = new Bike(7, "Mountain", 12, "Available") ;
    Bike b8 = new Bike(8,"Road", 10, "Available") ;
    EBike b9 = new EBike(9, "eBike", 18, "Not available", "Full Power") ;
    EBike b10 = new EBike(10, "eBike", 18, "Available", "Full Power");
    EBike b11 = new EBike(11, "eBike", 14, "Available", "Power Assist") ;
    EBike b12 = new EBike(12, "eBike", 14, "Available", "Power Assist") ;
    bikes.add(b1) ;
    bikes.add(b2) ;
    bikes.add(b3) ;
    bikes.add(b4) ;
    bikes.add(b5) ;
    bikes.add(b6) ;
    bikes.add(b7) ;
    bikes.add(b8) ;
    bikes.add(b9) ;
    bikes.add(b10) ;
    bikes.add(b11) ;
    bikes.add(b12) ;
}
</code>```

Main

```<code> public static void main(String[] args){
        BikeNowGUI fr = new BikeNowGUI();
        fr.Intial();
        fr.setTitle("Bikes") ;
        fr.setLocationRelativeTo(null); //Center frame
        fr.setSize(300, 500);
        fr.setVisible(true);
    }
</code>```

GUI

```<code>public BikeNowGUI(){
        tabs = new JTabbedPane() ;
        //BikesTab Panel
        pnlBikesTab = new JPanel() ;
        lblBikes = new JLabel("Bikes") ;
        pnlBikesTab.add(lblBikes) ;
        lblImages = new JLabel(icons[0]) ;
        pnlBikesTab.add(lblImages) ;
        //Jlist
        ArrayList<Bike> bikes = new ArrayList<Bike>();
        Bike[] items = new Bike[bikes.size()];
        bikes.toArray(items);
        lstBikes = new JList(items);
        pnlBikesTab.add(lstBikes) ;
        tabs.add("Bikes", pnlBikesTab) ;

        //CustomersTab Panel
        pnlCustomersTab = new JPanel();
        tabs.add("Customers", pnlCustomersTab) ;

        //RentsTab Panel
        pnlRentsTab = new JPanel();
        tabs.add("Rents", pnlRentsTab) ;

        add(tabs);
    }
</code>```

答:
@daniu is right. You can use this

lstBikes = new JList(bikes.toArray());

Another thing is that bikes will always return size 0 in BikeNowGUI because you are calling BikeNowGUI first before Initial method. I would suggest you move all the code to Initial method.

Body:
I want to display the all the details of elements in arraylist bikes in a Jlist. I've been trying to figure out how to do this for a while but I just can't crack it. The Jlist is part of a panel called pnlBikesTab.

ArrayList and JList

 ArrayList<Bike> bikes = new ArrayList<Bike>();
 JList<String> lstBikes ;

Populating Arraylist

 public void Intial(){
//Add 12 bikes
 Bike b1 = new Bike(1, "Mountain", 12, "Not available") ;
    Bike b2 = new Bike(2, "Road", 10, "Available") ;
    Bike b3 = new Bike(3, "City", 8, "Available") ;
    Bike b4 = new Bike(4, "Mountain", 12, "Available") ;
    Bike b5 = new Bike(5, "Road", 10, "Available") ;
    Bike b6 = new Bike(6, "City", 8, "Available") ;
    Bike b7 = new Bike(7, "Mountain", 12, "Available") ;
    Bike b8 = new Bike(8,"Road", 10, "Available") ;
    EBike b9 = new EBike(9, "eBike", 18, "Not available", "Full Power") ;
    EBike b10 = new EBike(10, "eBike", 18, "Available", "Full Power");
    EBike b11 = new EBike(11, "eBike", 14, "Available", "Power Assist") ;
    EBike b12 = new EBike(12, "eBike", 14, "Available", "Power Assist") ;
    bikes.add(b1) ;
    bikes.add(b2) ;
    bikes.add(b3) ;
    bikes.add(b4) ;
    bikes.add(b5) ;
    bikes.add(b6) ;
    bikes.add(b7) ;
    bikes.add(b8) ;
    bikes.add(b9) ;
    bikes.add(b10) ;
    bikes.add(b11) ;
    bikes.add(b12) ;
}

Main

 public static void main(String[] args){
        BikeNowGUI fr = new BikeNowGUI();
        fr.Intial();
        fr.setTitle("Bikes") ;
        fr.setLocationRelativeTo(null); //Center frame
        fr.setSize(300, 500);
        fr.setVisible(true);
    }

GUI

public BikeNowGUI(){
        tabs = new JTabbedPane() ;
        //BikesTab Panel
        pnlBikesTab = new JPanel() ;
        lblBikes = new JLabel("Bikes") ;
        pnlBikesTab.add(lblBikes) ;
        lblImages = new JLabel(icons[0]) ;
        pnlBikesTab.add(lblImages) ;
        //Jlist
        ArrayList<Bike> bikes = new ArrayList<Bike>();
        Bike[] items = new Bike[bikes.size()];
        bikes.toArray(items);
        lstBikes = new JList(items);
        pnlBikesTab.add(lstBikes) ;
        tabs.add("Bikes", pnlBikesTab) ;

        //CustomersTab Panel
        pnlCustomersTab = new JPanel();
        tabs.add("Customers", pnlCustomersTab) ;

        //RentsTab Panel
        pnlRentsTab = new JPanel();
        tabs.add("Rents", pnlRentsTab) ;

        add(tabs);
    }


问:
android:singleton instance not garbage collected after application is closed
I have an android activity with a fragment.

In the fragment, I fetch data using retrofit and set a static flag, so that , when I again go to this fragment, I restrict fetching data again.

I also store the data in a singleton instance.

But even after I destroyed the activity/closed the application, the static flag and the instance is still available and the list is also present in the instance, which malfunctions my app.

But I want the instance to be created newly and fetch data at each run.

This is my singleton instance.

```<code>public class Utilities {

    private static Utilities utils = null;

    private List<Data> friendsList;

    public List<Data> getDataList() {
        return dataList;
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }

    private List<Data> dataList;

    public synchronized static Utilities getInstance(){

        if(utils == null){
            utils = new Utilities();
        }
        return utils;
    }
}
</code>```

This is my fragment:

```<code>public class DataFragment extends Fragment
{
    private static boolean hasObtainedData;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)  {

        if(!hasObtainedData){
            getData(v);
        }else{
           recyclerView.setAdapter(new Adapter(utils.getDataList()));
         }
     }

     private void getData(View v) {

         //get Data using Retrofit:
         hasObtainedData = true;
         utils.setDataList(dataListObtainedUsingRetrofit)
         recyclerView.setAdapter(new Adapter(utils.getDataList()));
    }
}
</code>```

This is how, I call my fragment from MainActivity:

```<code>@Override
public void onTabSelected(TabLayout.Tab tab) {
           getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragmentBox, new DataFragment()).commit();
    }
</code>```

I tried giving System.gc() at onDestroy() of MainActivity, but still, the singleton instance is alive.

I search many SOF posts based on this, but wasn't able to solve this issue.

Any help will be really useful.

答:
The pointer to the Singleton is static in the Utilities-Class itself, so the Singelton can never be available for GC, unless you set utils = null on leaving MainAcitivity with something like </p>

```<code>Utilities.reset();
</code>```

Body:
I have an android activity with a fragment.

In the fragment, I fetch data using retrofit and set a static flag, so that , when I again go to this fragment, I restrict fetching data again.

I also store the data in a singleton instance.

But even after I destroyed the activity/closed the application, the static flag and the instance is still available and the list is also present in the instance, which malfunctions my app.

But I want the instance to be created newly and fetch data at each run.

This is my singleton instance.

public class Utilities {

    private static Utilities utils = null;

    private List<Data> friendsList;

    public List<Data> getDataList() {
        return dataList;
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }

    private List<Data> dataList;

    public synchronized static Utilities getInstance(){

        if(utils == null){
            utils = new Utilities();
        }
        return utils;
    }
}

This is my fragment:

public class DataFragment extends Fragment
{
    private static boolean hasObtainedData;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)  {

        if(!hasObtainedData){
            getData(v);
        }else{
           recyclerView.setAdapter(new Adapter(utils.getDataList()));
         }
     }

     private void getData(View v) {

         //get Data using Retrofit:
         hasObtainedData = true;
         utils.setDataList(dataListObtainedUsingRetrofit)
         recyclerView.setAdapter(new Adapter(utils.getDataList()));
    }
}

This is how, I call my fragment from MainActivity:

@Override
public void onTabSelected(TabLayout.Tab tab) {
           getSupportFragmentManager().beginTransaction()
                            .replace(R.id.fragmentBox, new DataFragment()).commit();
    }

I tried giving System.gc() at onDestroy() of MainActivity, but still, the singleton instance is alive.

I search many SOF posts based on this, but wasn't able to solve this issue.

Any help will be really useful.

Body:
The pointer to the Singleton is static in the Utilities-Class itself, so the Singelton can never be available for GC, unless you set utils = null on leaving MainAcitivity with something like

Utilities.reset();


问:
Why is my camera so far from rendered model?
I am trying to create my first glTF model in Three.js rendered from Blender and I can not get the camera to display close to the rendered model.

No matter what I do to the Blender camera nothing fixes the problem so it must be the code that has been written in Three.js. Please help! Thx

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title>three.js webglTF - loader</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no,
    minimum-scale=1.0, maximum-scale=1.0">
    <style>
        body {
            font-family: Monospace;
            background-color: #000;
            color: #fff;
            margin: 0px;
            overflow: hidden;
        }
        #info {
            color: #fff;
            position: absolute;
            top: 10px;
            width: 100%;
            text-align: center;
            z-index: 100;
            display:block;
        }
        #info a {
            color: #046;
            font-weight: bold;
        }
    </style>
</head>

<body>

    <script src="../build/three.js"></script>

    <script src="js/libs/inflate.min.js"></script>

    <script src="js/loaders/GLTFLoader.js"></script>
    <script src="js/controls/OrbitControls.js"></script>

    <script src="js/WebGL.js"></script>
    <script src="js/libs/stats.min.js"></script>

    <script>

        if ( WEBGL.isWebGLAvailable() === false ) {

            document.body.appendChild( WEBGL.getWebGLErrorMessage() );

        }

        var container, stats, controls;
        var camera, scene, renderer, light;

        var clock = new THREE.Clock();

        var mixers = [];

        init();
        animate();

        function init() {

            container = document.createElement( 'div' );
            document.body.appendChild( container );

            camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
            window.innerHeight, 1, 2000 );
            camera.position.set( -400, 0, 200 );

            controls = new THREE.OrbitControls( camera );
            controls.target.set( 0, 0, 0 );
            controls.update();

            scene = new THREE.Scene();
            scene.background = new THREE.Color( 0xa0a0a0 );
            scene.fog = new THREE.Fog( 0xa0a0a0, 200, 1000 );

            light = new THREE.HemisphereLight( 0xffffff, 0x444444 );
            light.position.set( 0, 200, 0 );
            scene.add( light );

            light = new THREE.DirectionalLight( 0xffffff );
            light.position.set( 0, 200, 100 );
            light.castShadow = true;
            light.shadow.camera.top = 180;
            light.shadow.camera.bottom = -100;
            light.shadow.camera.left = -120;
            light.shadow.camera.right = 120;
            scene.add( light );

            // scene.add( new THREE.CameraHelper( light.shadow.camera )
            );

            // ground
            var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry(
            2000, 2000 ), new THREE.MeshPhongMaterial( { material:
            0x999999, depthWrite: false } ) );
            mesh.rotation.x = - Math.PI / 2;
            mesh.receiveShadow = true;
            scene.add( mesh );

            var grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000
            );
            grid.material.opacity = 0.2;
            grid.material.transparent = true;
            scene.add( grid );

            // model
            var loader = new THREE.GLTFLoader();

            loader.load( '../The-Raisin/TREE_GLTF.gltf', function ( gltf)
{

            scene.add( gltf.scene );

            }, undefined, function ( error ) {

            console.error( error );

        } );

            renderer = new THREE.WebGLRenderer( { antialias: true } );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.shadowMap.enabled = true;
            container.appendChild( renderer.domElement );

            window.addEventListener( 'resize', onWindowResize, false );

            // stats
            stats = new Stats();
            container.appendChild( stats.dom );

        }

        function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );

        }

        //

        function animate() {

            requestAnimationFrame( animate );

            if ( mixers.length > 0 ) {

                for ( var i = 0; i < mixers.length; i ++ ) {

                    mixers[ i ].update( clock.getDelta() );

                }

            }

            renderer.render( scene, camera );

            stats.update();

        }

    </script>

</body>
</html>
</code>```

Camera is displayed outside of scene.

答:
No matter what I do to the Blender camera nothing fixes the problem

Changing the camera properties in Blender has not effect if you define an own camera object in your application. You have two options:

Access gltf.cameras in your onLoad() callback which represents an array of cameras defined in the glTF asset. If the camera from Blender is exported, you should find it right there.

Improve the parameters of the camera defined in your application with an approach similar to 3D viewers. You usually center your object first and then derive optimal camera parameters from the object's AABB. Try to use the following code from this three.js based glTF viewer:

https://github.com/donmccurdy/three-gltf-viewer/blob/18f43073bbfdbd3c220e2059e548e74c507522d2/src/viewer.js#L218-L246

three.js R104

Body:
I am trying to create my first glTF model in Three.js rendered from Blender and I can not get the camera to display close to the rendered model.

No matter what I do to the Blender camera nothing fixes the problem so it must be the code that has been written in Three.js. Please help! Thx

<!DOCTYPE html>

    <title>three.js webglTF - loader</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no,
    minimum-scale=1.0, maximum-scale=1.0">

Camera is displayed outside of scene.


问:
The IADD function in python, is telling me its an invalid syntax
Every time i try to tell Python to use the Iadd function it is telling me there is an invalid syntax error. I'm not sure what i'm doing to cause this, please help? :)

I've tried moving my code around to try and allow for it work, and searching up information on how to fix it but i cant seem to find anything.

```<code>for Taxon_types in csv_dict_reader:
    int_total_count = int_total_count + 1

    if str_category not in Taxon_types.keys():

        print (Taxon_types[csv_dict_reader[str_category]] == 1)

    else:
        print (Taxon_types[csv_dict_reader[str_category]] += 1)

file_infile.close()
print(Taxon_types)
</code>```

This is the error code I receive

```<code>File "<ipython-input-107-c0acc5958231>", line 17
    print (Taxon_types[csv_dict_reader[str_category]] += 1)
                                                       ^
SyntaxError: invalid syntax
</code>```

My hope is to be able to run this function so that when python filters the data from a CSV so every time it sees a particular type of mark it counts in as a heading and every time after this it marks it next to the heading. E.G. bob 3
Kevin 5

答:
Doing an in-place add inside a function call is not legal syntax:

```<code>>>> i = 1
>>> def f(n):print(n)
...
>>> f(i)
1
>>> f(i += 1)
  File "<stdin>", line 1
    f(i+=1)
        ^
SyntaxError: invalid syntax
</code>```

Instead, you should perform the addition in a separate statement, then call the print function:

```<code>Taxon_types[csv_dict_reader[str_category]] += 1
print (Taxon_types[csv_dict_reader[str_category]])
</code>```

It looks as if the name Taxon_types has two roles in your code - the name that you are using for each row in the csv and a dictionary that is being used to track the appearances of specific values.  That isn't going to work very well - perhaps you want to use separate variables, like this:

```<code>for row in csv_dict_reader:
    int_total_count = int_total_count + 1

    if row[str_category] not in Taxon_types.keys():

        Taxon_types[row[str_category]] = 1
        print(Taxon_types[row[str_category]])

    else:
        Taxon_types[row[str_category]] += 1
        print(Taxon_types[row[str_category]])
</code>```

Have a look at collections.defaultdict - using a defaultdict here will help you to simplify the code.

Body:
Every time i try to tell Python to use the Iadd function it is telling me there is an invalid syntax error. I'm not sure what i'm doing to cause this, please help? :)

I've tried moving my code around to try and allow for it work, and searching up information on how to fix it but i cant seem to find anything.

for Taxon_types in csv_dict_reader:
    int_total_count = int_total_count + 1

    if str_category not in Taxon_types.keys():

        print (Taxon_types[csv_dict_reader[str_category]] == 1)

    else:
        print (Taxon_types[csv_dict_reader[str_category]] += 1)

file_infile.close()
print(Taxon_types)

This is the error code I receive

File "<ipython-input-107-c0acc5958231>", line 17
    print (Taxon_types[csv_dict_reader[str_category]] += 1)
                                                       ^
SyntaxError: invalid syntax

My hope is to be able to run this function so that when python filters the data from a CSV so every time it sees a particular type of mark it counts in as a heading and every time after this it marks it next to the heading. E.G. bob 3
Kevin 5

Body:
Doing an in-place add inside a function call is not legal syntax:

>>> i = 1
>>> def f(n):print(n)
...
>>> f(i)
1
>>> f(i += 1)
  File "<stdin>", line 1
    f(i+=1)
        ^
SyntaxError: invalid syntax

Instead, you should perform the addition in a separate statement, then call the print function:

Taxon_types[csv_dict_reader[str_category]] += 1
print (Taxon_types[csv_dict_reader[str_category]])

It looks as if the name Taxon_types has two roles in your code - the name that you are using for each row in the csv and a dictionary that is being used to track the appearances of specific values.  That isn't going to work very well - perhaps you want to use separate variables, like this:

for row in csv_dict_reader:
    int_total_count = int_total_count + 1

    if row[str_category] not in Taxon_types.keys():

        Taxon_types[row[str_category]] = 1
        print(Taxon_types[row[str_category]])

    else:
        Taxon_types[row[str_category]] += 1
        print(Taxon_types[row[str_category]])

Have a look at collections.defaultdict - using a defaultdict here will help you to simplify the code.


问:
How to create a DataFrame from mapPartitions iterator?
I have a DataFrame with an id column. I would like to do some computations on the rows for each id (not only aggregations) and output a new DataFrame with one row per id, containing the results of the computations.

I am trying to do this by repartioning on the id and then using mapPartitions:

```<code>df.repartition(col("id")).mapPartitions(iter => {
    val dfSubset = // iter to DataFrame?
    // Computations on dfSubset
})
</code>```

But how do you create a DataFrame from iter? The goal is to then make the computations on the DataFrame dfSubset containing all the rows for an id.

EDIT:

repartition(col("id")) will not create 1 partition per id. We should use groupBy("id") instead.

答:
What you're looking for is to do a groupBy on id and then define your own User Defined Aggregate Function. If you need all columns you can construct a struct of said columns and pass to your aggregate function.

```<code>df
.groupBy("id")
.agg(myUdaf(struct(df.columns.filter(_ != "id").map(col(_)):_*)).as("result")).show()
</code>```

Body:
I have a DataFrame with an id column. I would like to do some computations on the rows for each id (not only aggregations) and output a new DataFrame with one row per id, containing the results of the computations.

I am trying to do this by repartioning on the id and then using mapPartitions:

df.repartition(col("id")).mapPartitions(iter => {
    val dfSubset = // iter to DataFrame?
    // Computations on dfSubset
})

But how do you create a DataFrame from iter? The goal is to then make the computations on the DataFrame dfSubset containing all the rows for an id.

EDIT:

repartition(col("id")) will not create 1 partition per id. We should use groupBy("id") instead.

Body:
What you're looking for is to do a groupBy on id and then define your own User Defined Aggregate Function. If you need all columns you can construct a struct of said columns and pass to your aggregate function.

df
.groupBy("id")
.agg(myUdaf(struct(df.columns.filter(_ != "id").map(col(_)):_*)).as("result")).show()


问:
Get Type from EF Core Context
I am trying to get the type of an entity from a given string. My end goal is to make an interface (UI interface) for users to have a GUI to explore my Database. They basically have a tree of tables and their fields and as they select fields, I want to build up the SQL query on the backend and return the data. I'm getting stuck on how to get the Type.

I'm trying to staple together a solution between these threads:

How do I select correct DbSet in DbContext based on table name

How to get DbSet from entity name in EF Core / .NET Core 2.0

Here's my current attempt(s):

```<code>var type1 = _dbContext.Model.FindEntityType("Chadwick.Database.Entities.Appearances");
var type = _dbContext.Appearances.GetType();
var context = _dbContext.Set(typeof(Appearance)); // this works. I just need to pass in a variable instead of the actual type
var stuff = await context.FromSql("SELECT TOP 100 * FROM Appearances").ToListAsync();
// var data = await _dbContext.Appearances.Select(a => new {a.PlayerId}).Take(100).ToListAsync();
return new OkObjectResult(stuff);
</code>```

Essentially, I will never know that they are after "Appearances", so I can't just provide the exact type, I need to fetch it (by string) from the context.

Is there a way to get the actual type by string?

I know I could do something like this, but it seems redundent (there's about 20 tables and will be more)

```<code>public Type GetTypeByName(string name)
{
    switch (name)
    {
        case "Appearances":
            return typeof(Appearance);
        case "AwardsManagers":
            return typeof(AwardsManager);
    }

    return null;
}
</code>```

答:
Basically you need to know the entity class namespace, because the name itself is not enough to uniquely identify the entity type.

Once you know that, you can obtain the EF Core metadata for that entity using the FindEntityType method like in your first attempt:

```<code>var entityType = _dbContext.Model.FindEntityType("Chadwick.Database.Entities." + className);
</code>```

The result of that method is null if no such entity exists, IEntityType instance otherwise. It can be used to obtain other EF Core metadata related to the entity, like properties, navigations, table name etc. And the type of the associated class that you need is provided by the ClrType property:

```<code>var classType = entityType.ClrType;
</code>```

Title: Get Type from EF Core Context

Body:
I am trying to get the type of an entity from a given string. My end goal is to make an interface (UI interface) for users to have a GUI to explore my Database. They basically have a tree of tables and their fields and as they select fields, I want to build up the SQL query on the backend and return the data. I'm getting stuck on how to get the Type.

I'm trying to staple together a solution between these threads:

How do I select correct DbSet in DbContext based on table name

How to get DbSet from entity name in EF Core / .NET Core 2.0

Here's my current attempt(s):

var type1 = _dbContext.Model.FindEntityType("Chadwick.Database.Entities.Appearances");
var type = _dbContext.Appearances.GetType();
var context = _dbContext.Set(typeof(Appearance)); // this works. I just need to pass in a variable instead of the actual type
var stuff = await context.FromSql("SELECT TOP 100 * FROM Appearances").ToListAsync();
// var data = await _dbContext.Appearances.Select(a => new {a.PlayerId}).Take(100).ToListAsync();
return new OkObjectResult(stuff);

Essentially, I will never know that they are after "Appearances", so I can't just provide the exact type, I need to fetch it (by string) from the context.

Is there a way to get the actual type by string?

I know I could do something like this, but it seems redundent (there's about 20 tables and will be more)

public Type GetTypeByName(string name)
{
    switch (name)
    {
        case "Appearances":
            return typeof(Appearance);
        case "AwardsManagers":
            return typeof(AwardsManager);
    }

    return null;
}

Body:
Basically you need to know the entity class namespace, because the name itself is not enough to uniquely identify the entity type.

Once you know that, you can obtain the EF Core metadata for that entity using the FindEntityType method like in your first attempt:

var entityType = _dbContext.Model.FindEntityType("Chadwick.Database.Entities." + className);

The result of that method is null if no such entity exists, IEntityType instance otherwise. It can be used to obtain other EF Core metadata related to the entity, like properties, navigations, table name etc. And the type of the associated class that you need is provided by the ClrType property:

var classType = entityType.ClrType;


问:
Bringing a browser to focus in parallel execution selenium
Can we make sure one particular browser session to bring to front/focus in parallel execution of selenium?
I have a requirement to do keyboard action by pressing enter key , using robot class to handle google payment option in chrome.
And robot key actions are working only when the browser is in focus/front side.

Tried with ((JavascriptExecutor) driver).executeScript("window.focus();"); but no effect.

Also , tried with sikuli , and having the same issue with sikuli too, as it also needs browser to be in focus.
NOT going for an alternative to use Autoit , since our project needs to work on both Windows and MAC.

Your help is much appreciated.

答:
You can send keys (Alt + Tab)to switch to the current session of browser since it was just the window in focus and then moved to state of being not focused on.
Here is the code sample in Java</p>

```<code>Actions action = new Actions(driver);
action.sendKeys(Keys.chord(Keys.ALT, Keys.ENTER)).build().perform();
</code>```

Body:
You can send keys (Alt + Tab)to switch to the current session of browser since it was just the window in focus and then moved to state of being not focused on.
Here is the code sample in Java

Actions action = new Actions(driver);
action.sendKeys(Keys.chord(Keys.ALT, Keys.ENTER)).build().perform();


问:
Service Worker DOMException: Registration failed - storage error
While implement Fire-base cloud messaging in browser with help of Service Worker getting an error  "DOMException: Registration failed - storage error" please help why i am getting this error</p>

答:
This means that your Service Worker has stored so much data that the storage available to it is full, and upon SW installation it tries to store even more which in turn leads to an error.

You have to either manually remove stuff from your storage or use some library that automatically handles these situations for you in a way or another (eg. removes stuff FIFO style).


问:
How to use RecyclerView inside NestedScrollView?
How to use RecyclerView inside NestedScrollView?
RecyclerView content is not visible after setting adapter.

UPDATE layout code updated.

```<code><android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/keyline_1">

    </RelativeLayout>

    <View
        android:id="@+id/separator"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#e5e5e5" />

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

</LinearLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

答:
For androidx it's called androidx.core.widget.NestedScrollView - and it scrolls alike butter with properties isScrollContainer and measureAllChildren enabled:

```<code><!-- Scrolling Content -->
<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:isScrollContainer="true"
    android:measureAllChildren="true"

    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="true"
        android:scrollbarStyle="insideInset"
        android:scrollbars="vertical"
        android:splitMotionEvents="false"
        android:verticalScrollbarPosition="right"/>

</androidx.core.widget.NestedScrollView>
</code>```

Body:
How to use RecyclerView inside NestedScrollView?
RecyclerView content is not visible after setting adapter.

UPDATE layout code updated.

<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/keyline_1">

    </RelativeLayout>

    <View
        android:id="@+id/separator"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#e5e5e5" />

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

</LinearLayout>

</android.support.v4.widget.NestedScrollView>

Body:
For androidx it's called androidx.core.widget.NestedScrollView - and it scrolls alike butter with properties isScrollContainer and measureAllChildren enabled:

<!-- Scrolling Content -->
<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:isScrollContainer="true"
    android:measureAllChildren="true"

    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="true"
        android:scrollbarStyle="insideInset"
        android:scrollbars="vertical"
        android:splitMotionEvents="false"
        android:verticalScrollbarPosition="right"/>

</androidx.core.widget.NestedScrollView>


问:
send value from anchor tag to views
i have blog field in my project. i want to send the post id in to the views.py
tell me what i'm doing wrong

in blog.html

```<code><a href="{% url 'post-detail' post.id %}" class="btn btn-primary">Read
more</a>
</code>```

in urls:

```<code>path('post_detail/<int:pk>/', PostDetailView.as_view(), name='post-
detail')
</code>```

in views:

```<code>class PostDetailView(DetailView):
model = Post

def get_queryset(self):
    queryset = super().get_queryset()
    search = self.request.GET.get('pk')
    if search:
        queryset = Post.objects.filter(page_id=search)
        print(queryset)

    else:
        return queryset.none()
</code>```

答:
add the template properties and it will work.

```<code>template_name = 'app-name-template/single_post.html'
</code>```

also queryset it your case is not needed so remove it.

Title: send value from anchor tag to views

Body:
i have blog field in my project. i want to send the post id in to the views.py
tell me what i'm doing wrong

in blog.html

Read
more

in urls:

path('post_detail/<int:pk>/', PostDetailView.as_view(), name='post-
detail')

in views:

class PostDetailView(DetailView):
model = Post

def get_queryset(self):
    queryset = super().get_queryset()
    search = self.request.GET.get('pk')
    if search:
        queryset = Post.objects.filter(page_id=search)
        print(queryset)

    else:
        return queryset.none()

Body:
add the template properties and it will work.

template_name = 'app-name-template/single_post.html'

also queryset it your case is not needed so remove it.


问:
File writer is writing the string with no "Line breaks"
It is a simple "file writing program" that scans a text file from the given directory and stores its content into a string initialized as " words" . Now, when the content is concatenated into the string. The spaces and the line breaks are preserved. However, when I attempt to write that string words into a file. The spaces are preserved but the lines breaks are lost.
For example:
Original String:
Hello. I am stuck in UMT.
Get me out of here.
File Writing:
Hello, I am stuck in UMT. Get me out of here.
Notice the new line is not preserved? No line break? No " \n" ?</p>

```<code>package testing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Reader{ {

String words="this is a a new file created by me :D \n";
File file = new File("C:/file.txt");

  try {
        Scanner scan= new Scanner(file);
        while(scan.hasNextLine()){
        words= words.concat(scan.nextLine() + "\r ");
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null,
ex);
    }

System.out.println(words);

try {
    FileWriter writer = new FileWriter("D:/newfile.txt");
    writer.write(words);
    writer.close();
} catch (IOException ex) {
    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}

}}
</code>```

答:
\r is carriage return, \n is new line but as a general rule you have to look at the encoding type of your file because the new line character can differ from one encoding to another one.

CR, LF, and CRLF are all commonly used end-of-line characters. In the world of PCs, CRLF is common amongst Windows apps, CR is common on the Classic Mac OS, and LF is common on the modern macOS and Unix-oriented OSes (BSD, Linux, etc). See Wikipedia.

Some more info

if you are facing some of these problems you have to keep in mind that different charecter encodings could have different notation for the new line. For example Word may use UTF-8 and Notepad may use ISO-8859-1 and you default system is setted on another type of encoding and it's not sure that every of this encoding share the same new line character. When you use the \n character you are typing the new line of your system so let's say you are working on windows this can display a new line that you can see in Word, but if you will open the same file on a Mac text editor you can see no new lines if they use different character encodings.

Body:
It is a simple "file writing program" that scans a text file from the given directory and stores its content into a string initialized as " words" . Now, when the content is concatenated into the string. The spaces and the line breaks are preserved. However, when I attempt to write that string words into a file. The spaces are preserved but the lines breaks are lost.
For example:
Original String:
Hello. I am stuck in UMT.
Get me out of here.
File Writing:
Hello, I am stuck in UMT. Get me out of here.
Notice the new line is not preserved? No line break? No " \n" ?

package testing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Reader{ {

String words="this is a a new file created by me :D \n";
File file = new File("C:/file.txt");

  try {
        Scanner scan= new Scanner(file);
        while(scan.hasNextLine()){
        words= words.concat(scan.nextLine() + "\r ");
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null,
ex);
    }

System.out.println(words);

try {
    FileWriter writer = new FileWriter("D:/newfile.txt");
    writer.write(words);
    writer.close();
} catch (IOException ex) {
    Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}

}}


问:
Concurrent Connection Apache and Laravel
I'm a bit confused by a problem that has only become more apparently lately and I'm hoping that someone might be able to point me in the direction of either where I might look for appropriate settings, or if I am running into another problem they have come across before.

I have a Laravel application and a private server that I use for our little museum. Now as the application has become more complex, the lag is noticeable and you can see how it almost lines up the connections, finishing one request before moving along to the next, whether it be api, ajax, view responses, whatever.

I am running Apache 2.4.29 and my Ubuntu Server is 18.04.1.

I have been looking around but not much has helped, in regards to connections settings, if I look at my phpinfo() I see this Max Requests  Per Child: 0 - Keep Alive: on - Max Per Connection: 100 but I believe these are just fine the way they are.

If I check my memory I think it says I have 65 GB of available memory, with 5 being used in caching. When reviewing the live data, the memory never crosses into the GB territory and solely remains in the MB territory. This server is absolutely only used for this Laravel project, so I don't have to worry about messing with other projects, I'd just like to make sure this application is getting the best use it can for its purpose.

I'd appreciate any suggestions, I know there's a chance the terms I am searching for are incorrect, or maybe just outdated, so if there are any potential useful resources out there, I'd appreciate those as well.

Thank you so much!

答:
It's really hard to be able to tell since there a lot of details lacking but here some things that can give you a direction of where to look:

Try downloading htop via apt-get and see what happens on your CPU/RAM load with each request to the server.

Do you use php-fpm to manage the php requests? This might help in finding out if the problem lies in your PHP code or in apache configuration

Did you try deploying to a different server? Do you still see the lagging on the other server as well? If not, this indicates a misconfiguration problem and not an issue with your code.

Do you have other processes that are running in the background and might slow things down? Cron? Laravel Queue?

If you try to install another app on the server (let's say phpmyadmin) is it slow as well or it works fine?

Try to take it from here. Best of luck.


问:
Some Tomcat webapps not opening
I downloaded a couple of webapps and placed them in my /webapps folder.
Some of them I could open by going to http://localhost:8080/app1 and it would open.
However, some others I would do the exact same thing and go to http://localhost:8080/app2 and it will display "HTTP Status 404 - /app2/", even though I am sure it is there.  I've checked that it contains a WEB-INF folder just like app1, and I've even restarted Tomcat to be sure.

My question is: is there anything (perhaps in the web.xml file) that specifies what the URL has to be to start the webapp? Or is it simply just http://localhost:8080/<folder name> ?

P.S. If you want to know exactly what app1 and app2 I am refering to:
app1 (works) = http://assets.devx.com/sourcecode/11237.zip
app2 (doesn't work) = http://www.laliluna.de/download/eclipse-spring-jdbc-tutorial.zip

I've tried a few others as well, some work, some don't.  I'm just wondering if I'm missing something.

答:
The first zip file you mention has a .war file as part of the zip.  The second one is just the source code and it needs to be built into a .war file.

It looks like it is setup to have that done in Eclipse.  Try the File>>Export option and select War file as the export type.

OwnerDisplayName: Steve

LastEditorDisplayName: John Meagher

Title: Some Tomcat webapps not opening

OwnerDisplayName: John Meagher


问:
How put a Confirmation in Hyperlink DataGridView
I want is to have a confirmation before deleting a records in my datagridview. Please check my codes.. Thanks.

here's my asp.net code:

```<code><ItemTemplate><asp:HyperLink ID="hlnk_Delete" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
    NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>
</code>```

Sqldatasource:

```<code><asp:SqlDataSource ID="sds_PublishedBookListings" runat="server" ConnectionString="<%$ ConnectionStrings:learningisfunConnectionString %>"

SelectCommand="SELECT dbo.lif_bookshascategory.lbhc_lc_id,dbo.lif_books.lb_sku, dbo.lif_bookshascategory.lbhc_lb_sku, dbo.lif_category.lc_category, dbo.lif_books.lb_title,
                      dbo.lif_bookshascategory.lbhc_level
FROM         dbo.lif_bookshascategory INNER JOIN
                      dbo.lif_category ON dbo.lif_bookshascategory.lbhc_lc_id = dbo.lif_category.lc_id INNER JOIN
                      dbo.lif_books ON dbo.lif_bookshascategory.lbhc_lb_sku = dbo.lif_books.lb_sku
WHERE     (dbo.lif_books.lb_status = 'publish') and lbhc_level = 1
"

DeleteCommand="DELETE FROM lif_books FROM lif_books INNER JOIN lif_bookshascategory ON lif_books.lb_sku = lif_bookshascategory.lbhc_lb_sku WHERE (lif_books.lb_sku = @lbhc_lb_sku) OR (lif_bookshascategory.lbhc_lb_sku = @lbhc_lb_sku)">
<DeleteParameters>
<asp:Parameter Name="lb_sku" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
</code>```

答: Add to you Hyperlink OnclientClick="confirm('are you sure?'); return false"</p>

Body:
I want is to have a confirmation before deleting a records in my datagridview. Please check my codes.. Thanks.

here's my asp.net code:

<ItemTemplate><asp:HyperLink ID="hlnk_Delete" runat="server" style="width:100px; margin-left:50px; margin-right:100px"
    NavigateUrl='<%# "Components/DeleteBook.aspx?SKU=" + Utility.SKUMask(Eval("lbhc_lb_sku").ToString()) %>'>Delete</asp:HyperLink></ItemTemplate>

Sqldatasource:

<asp:SqlDataSource ID="sds_PublishedBookListings" runat="server" ConnectionString="<%$ ConnectionStrings:learningisfunConnectionString %>"

SelectCommand="SELECT dbo.lif_bookshascategory.lbhc_lc_id,dbo.lif_books.lb_sku, dbo.lif_bookshascategory.lbhc_lb_sku, dbo.lif_category.lc_category, dbo.lif_books.lb_title,
                      dbo.lif_bookshascategory.lbhc_level
FROM         dbo.lif_bookshascategory INNER JOIN
                      dbo.lif_category ON dbo.lif_bookshascategory.lbhc_lc_id = dbo.lif_category.lc_id INNER JOIN
                      dbo.lif_books ON dbo.lif_bookshascategory.lbhc_lb_sku = dbo.lif_books.lb_sku
WHERE     (dbo.lif_books.lb_status = 'publish') and lbhc_level = 1
"

DeleteCommand="DELETE FROM lif_books FROM lif_books INNER JOIN lif_bookshascategory ON lif_books.lb_sku = lif_bookshascategory.lbhc_lb_sku WHERE (lif_books.lb_sku = @lbhc_lb_sku) OR (lif_bookshascategory.lbhc_lb_sku = @lbhc_lb_sku)">
<DeleteParameters>
<asp:Parameter Name="lb_sku" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>


问:
containsAll for nCopies of object in List
I would like to check if an Arraylist contains n copies of the same element.
Here's the problem:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class testMain {
    public static void main(String[] args) {
        myClass myObject = new myClass("haha1");

        ArrayList a = new ArrayList();
        a.add(myObject);
        a.add(new myClass("haha2"));
        a.add(new myClass("haha3"));

        List b;
        b = Collections.nCopies(5, myObject);
        System.out.println(a.containsAll(b)); //prints true
    }

    static private class myClass {
        String a;

        myClass(String a) {
            this.a = a;
        }
    }
}

```

Problem 1: List b has a greater size than list a - should be false

Problem 2: List b has more than one myObject objects (as opposed to Lista - should be false

This doesn't work due to the way containsAll works, since I want to see if the object myObject is contained (in this case) 3 times in List a.

I know I can write my own method that would do exactly what I want, but I was wondering if there is an out of the box solution for this case or what would be the most "elegant" way of handling it.

EDIT: Removed clarification for my use of myClass as it was conflicting with given example.

答:
Use Collections.frequency(a,myObject) == 5 (or Collections.frequency(a,myObject) >= 5 if you don't mind if your Collection has more than 5 instances pf myObject).

int java.util.Collections.frequency(Collection c, Object o)

Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).

Body:
I would like to check if an Arraylist contains n copies of the same element.
Here's the problem:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class testMain {
    public static void main(String[] args) {
        myClass myObject = new myClass("haha1");

        ArrayList a = new ArrayList();
        a.add(myObject);
        a.add(new myClass("haha2"));
        a.add(new myClass("haha3"));

        List b;
        b = Collections.nCopies(5, myObject);
        System.out.println(a.containsAll(b)); //prints true
    }

    static private class myClass {
        String a;

        myClass(String a) {
            this.a = a;
        }
    }
}

Problem 1: List b has a greater size than list a - should be false

Problem 2: List b has more than one myObject objects (as opposed to Lista - should be false

This doesn't work due to the way containsAll works, since I want to see if the object myObject is contained (in this case) 3 times in List a.

I know I can write my own method that would do exactly what I want, but I was wondering if there is an out of the box solution for this case or what would be the most "elegant" way of handling it.

EDIT: Removed clarification for my use of myClass as it was conflicting with given example.


问:
Having an error in DataBinding in kotlin app
I am trying to bind data in my kotlin android app, I was following this tutorial on codelab Link to Codelab I did everything same.

But while importing ActivityMainBinding in MainActitvity.kt file ide keeps on showing me error in red text.

I did enabled dataBinding in app level gradle file Here

```<code>dataBinding {
        enabled = true
    }
</code>```

Here I have imported and initialized dataBinding

```<code>import android.content.Context
import android.databinding.DataBindingUtil
import android.hardware.input.InputManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
//import kotlinx.android.synthetic.main.activity_main.*
import com.example.aboutme.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.done_button.setOnClickListener{
            addNickname(it)
        }
    }

    private fun addNickname(view: View) {

        binding.apply{
            nickname_text.text = binding.nickname_edit.text
            invalidateAll()
            nickname_edit.visibility = View.GONE
            done_button.visibility = View.GONE
            nickname_text.visibility = View.VISIBLE
        }

        //Hide the Keyboard

        val inn = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inn.hideSoftInputFromWindow(view.windowToken, 0)

    }
}
</code>```

Error i get while trying to build gradle anyway. I thought to give it a try.

```<code>Compilation Error
</code>```

I am new To Android.

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

tools:context=".MainActivity">

```<code>        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    <TextView
            android:text="@string/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            style="@style/name_style"/>
    <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@android:drawable/btn_star_big_on"
            android:id="@+id/imageView2"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/nickname_edit" style="@style/name_style" android:hint="what is your nickname"/>
    <Button
            android:text="Done"
            android:layout_gravity="center_horizontal"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/done_button"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/nickname_text" style="@style/name_style"
            android:visibility="gone"/>
    <ScrollView
            android:id="@+id/bio_scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <TextView
                style="@style/name_style"
                android:text="@string/bio"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/bio_text"
                android:lineSpacingMultiplier="1.2"
        />
    </ScrollView>

</LinearLayout>
</layout>
</code>```

error in log

```<code>Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
Unresolved reference: it
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main

> Task :app:buildInfoGeneratorDebug
</code>```

答:
1) You need to add distributionUrl in gradle.wrapper-properties for latest android studio version. Your URL must be

distributionUrl=https://services.gradle.org/distributions/gradle-5.1.1-all.zip

2) data binding dependancy in-app level Gradle file

```<code>kapt 'com.android.databinding:compiler:3.1.0'
</code>```

and also add

```<code>apply plugin: 'kotlin-kapt'
</code>```

3) Add kotlin Gradle plugin project level Gradle dependency.

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:3.4.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.31"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
</code>```

After completing above all just clean, build and rebuild project.

Body:
I am trying to bind data in my kotlin android app, I was following this tutorial on codelab Link to Codelab I did everything same.

But while importing ActivityMainBinding in MainActitvity.kt file ide keeps on showing me error in red text.

I did enabled dataBinding in app level gradle file Here

dataBinding {
        enabled = true
    }

Here I have imported and initialized dataBinding

import android.content.Context
import android.databinding.DataBindingUtil
import android.hardware.input.InputManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
//import kotlinx.android.synthetic.main.activity_main.*
import com.example.aboutme.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.done_button.setOnClickListener{
            addNickname(it)
        }
    }

    private fun addNickname(view: View) {

        binding.apply{
            nickname_text.text = binding.nickname_edit.text
            invalidateAll()
            nickname_edit.visibility = View.GONE
            done_button.visibility = View.GONE
            nickname_text.visibility = View.VISIBLE
        }

        //Hide the Keyboard

        val inn = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inn.hideSoftInputFromWindow(view.windowToken, 0)

    }
}

Error i get while trying to build gradle anyway. I thought to give it a try.

Compilation Error

I am new To Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"

tools:context=".MainActivity">

        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    <TextView
            android:text="@string/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            style="@style/name_style"/>
    <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@android:drawable/btn_star_big_on"
            android:id="@+id/imageView2"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/nickname_edit" style="@style/name_style" android:hint="what is your nickname"/>
    <Button
            android:text="Done"
            android:layout_gravity="center_horizontal"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/done_button"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/nickname_text" style="@style/name_style"
            android:visibility="gone"/>
    <ScrollView
            android:id="@+id/bio_scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <TextView
                style="@style/name_style"
                android:text="@string/bio"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/bio_text"
                android:lineSpacingMultiplier="1.2"
        />
    </ScrollView>

</LinearLayout>
</layout>

error in log

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
Unresolved reference: it
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main

> Task :app:buildInfoGeneratorDebug

Body:
1) You need to add distributionUrl in gradle.wrapper-properties for latest android studio version. Your URL must be

distributionUrl=https://services.gradle.org/distributions/gradle-5.1.1-all.zip

2) data binding dependancy in-app level Gradle file

kapt 'com.android.databinding:compiler:3.1.0'

and also add

apply plugin: 'kotlin-kapt'

3) Add kotlin Gradle plugin project level Gradle dependency.

dependencies {
    classpath 'com.android.tools.build:gradle:3.4.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.31"
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

After completing above all just clean, build and rebuild project.