问:
Angular dynamic component inside leaflet popup - ngFor not working
I have followed this solution, to create dynamic component inside leaflet popup. I can able to render my component. But when I try to use  *ngFor getting following error

My parent component code to render popup

```<code>let popup = L.popup();
        this.zone.run(() => {
            if (this.componentRef) {
                this.componentRef.destroy();
            }
            const compFactory = this.resolver.resolveComponentFactory(
                LeafletPopupComponent
            );
            this.componentRef = compFactory.create(this.injector);
            if (this.appRef["attachView"]) {
                // since 2.3.0
                this.appRef["attachView"](this.componentRef.hostView);
                this.componentRef.onDestroy(() => {
                    this.appRef["detachView"](this.componentRef.hostView);
                });
            } else {
                this.appRef["registerChangeDetector"](
                    this.componentRef.changeDetectorRef
                );
                this.componentRef.onDestroy(() => {
                    this.appRef["unregisterChangeDetector"](
                        this.componentRef.changeDetectorRef
                    );
                });
            }
            this.componentRef.instance.parent_text = "msg from parent";
            this.componentRef.instance.items = [
                "workstation 1",
                "workstation 2"
            ];
            let div = document.createElement("div");
            div.appendChild(this.componentRef.location.nativeElement);
            popup.setContent(div);
        });
        this.markerObj.bindPopup(popup).addTo(this.map);
</code>```

dynamic component html code

```<code><div class="container">
    <h5>Step 1</h5>
    <span>Name the selected type of workstation</span>
    {{ parent_text }}
    <div class="form-group w-100" *ngIf="items?.length">
        <select class="form-control">
            <option value="">Select</option>
            <option *ngFor="let item of items" [value]="item">
                {{item}}
            </option>
        </select>
    </div>
    <h5>Step 2</h5>
    <a> Mark Area <i class="fa fa-pencil"></i></a>
</div>
</code>```

dynamic component ts file

```<code>export class LeafletPopupComponent{
    @Input() items;
    @Input() parent_text: string;
    constructor() {}
}
</code>```

Note I can successfully render parent_text message from parent component.
Please help on this.

答:
Please ensure that the module the component belongs to imports CommonModule. And then try to debug it via json pipe.

Step 1

    Name the selected type of workstation
    {{ items | json }}
    {{ parent_text }}

```

Body:
I have followed this solution, to create dynamic component inside leaflet popup. I can able to render my component. But when I try to use  *ngFor getting following error

My parent component code to render popup

let popup = L.popup();
        this.zone.run(() => {
            if (this.componentRef) {
                this.componentRef.destroy();
            }
            const compFactory = this.resolver.resolveComponentFactory(
                LeafletPopupComponent
            );
            this.componentRef = compFactory.create(this.injector);
            if (this.appRef["attachView"]) {
                // since 2.3.0
                this.appRef["attachView"](this.componentRef.hostView);
                this.componentRef.onDestroy(() => {
                    this.appRef["detachView"](this.componentRef.hostView);
                });
            } else {
                this.appRef["registerChangeDetector"](
                    this.componentRef.changeDetectorRef
                );
                this.componentRef.onDestroy(() => {
                    this.appRef["unregisterChangeDetector"](
                        this.componentRef.changeDetectorRef
                    );
                });
            }
            this.componentRef.instance.parent_text = "msg from parent";
            this.componentRef.instance.items = [
                "workstation 1",
                "workstation 2"
            ];
            let div = document.createElement("div");
            div.appendChild(this.componentRef.location.nativeElement);
            popup.setContent(div);
        });
        this.markerObj.bindPopup(popup).addTo(this.map);

dynamic component html code

Step 1

    Name the selected type of workstation
    {{ parent_text }}

        <select class="form-control">
            <option value="">Select</option>
            <option *ngFor="let item of items" [value]="item">
                {{item}}
            </option>
        </select>

Step 2

     Mark Area

dynamic component ts file

export class LeafletPopupComponent{
    @Input() items;
    @Input() parent_text: string;
    constructor() {}
}

Note I can successfully render parent_text message from parent component.
Please help on this.

Body:
Please ensure that the module the component belongs to imports CommonModule. And then try to debug it via json pipe.

<div class="container">
    <h5>Step 1</h5>
    <span>Name the selected type of workstation</span>
    {{ items | json }} <!-- <- add this -->
    {{ parent_text }}
</div>


来源: stackexchange

问:
Django - How to get that an object attribute be automatically updated depending on the actual date?
I need that an object attribute be automatically updated past some puntual date and time. I have a class and a method within this class to try to perform this, but the issue here is that I need to call the method (or access a @property) to this be applied.

The code is something like this:

```<code>class Foo(models.Model):
    status =  models.CharField()
    expiring_time = models.DateTimeField()

    def is_active(self):
        date = datetime.datetime.now()
        if date > self.expiring_time:
            self.status = "expired"
        self.save()
</code>```

I found some similar questions but none of them seems to get the point that I'm looking for. I heard about celery to perform scheduled tasks, but as I understood this just be keep calling the method and is not the same that I'm looking for.

I would like to know if is there a way to keep this method "always active", or what could be a way to achieve this?

答:
You can maybe use the post_init signal inside your Model.

This signal is sent right after your instance has been initialized.

```<code>from django.db.models.signals import post_init
from django.dispatch import receiver

class Foo(models.Model):
    status =  models.CharField()
    expiring_time = models.DateTimeField()

@receiver(post_save, sender=User)
def is_active(sender, instance, **kwargs):
    date = datetime.datetime.now()
    if date > instance.expiring_time:
        instance.status = "expired"
    instance.save()
</code>```

Caution : this signal will executes this function each time the instance is returned ; even during a queryset iteration. It may cause performance issues.

Take a look to the doc : https://docs.djangoproject.com/en/3.0/ref/signals/#post-init

Another way would be to call this function each time you instanciate your Foo model. It will take your business logic outside of your Model.

ContentLicense: CC BY-SA 4.0

Body:
I need that an object attribute be automatically updated past some puntual date and time. I have a class and a method within this class to try to perform this, but the issue here is that I need to call the method (or access a @property) to this be applied.

The code is something like this:

class Foo(models.Model):
    status =  models.CharField()
    expiring_time = models.DateTimeField()

    def is_active(self):
        date = datetime.datetime.now()
        if date > self.expiring_time:
            self.status = "expired"
        self.save()

I found some similar questions but none of them seems to get the point that I'm looking for. I heard about celery to perform scheduled tasks, but as I understood this just be keep calling the method and is not the same that I'm looking for.

I would like to know if is there a way to keep this method "always active", or what could be a way to achieve this?

Body:
You can maybe use the post_init signal inside your Model.

This signal is sent right after your instance has been initialized.

from django.db.models.signals import post_init
from django.dispatch import receiver

class Foo(models.Model):
    status =  models.CharField()
    expiring_time = models.DateTimeField()

@receiver(post_save, sender=User)
def is_active(sender, instance, **kwargs):
    date = datetime.datetime.now()
    if date > instance.expiring_time:
        instance.status = "expired"
    instance.save()

Caution : this signal will executes this function each time the instance is returned ; even during a queryset iteration. It may cause performance issues.

Take a look to the doc : https://docs.djangoproject.com/en/3.0/ref/signals/#post-init

Another way would be to call this function each time you instanciate your Foo model. It will take your business logic outside of your Model.


问:
Can you suggest a canvas library capable of SIMPLE 3d
What I need to do is create a simple preview of a minecraft "dude" with the correct texture applied.

I'm not concerned with complex animations (yet) or detailed lighting (yet) but I'd like to make it using canvas and not rely on WebGL(not really that widely supported yet).

What technologies would you recommend for this set of limitations?

Ah, also, I don't need to edit or save the skin or whatever, just a simple display.

答: THREE.js is a popular javascript 3D library, it supports both canvas and WebGL</p>

ContentLicense: CC BY-SA 3.0


问:
My c++ program does not appear to evualuate the comparison between a string, and a variable which I have but input into using getline
I have a string variable called input which i use getline to input text into. When I try to compare the variable input to another string such as if(input == "new game") it does not appear to evaluate the comparison. I know that it is actually inputing the correct text because when I use cout on input it outputs correctly (typing in "new game" will output "new game"). I looked up problems with getline and I read that cin leaves behind the \n in an input string which is picked up by getline. I tried using cin.ignore(), cin.clear(), and cin.sync() but they do not appear to fix the issue. Besides, there isn't any input that comes before getline(cin, input) anyway. The code in question is blow, any help is appreciated, thanks!

```<code>int main(){
string input;
while(input != "quit"){
    getline(cin, input);
    if(input == "new game"){
        town(player);
    }
    if(input == "load game"){
        cout << "enter save file: " << endl;
        load(player);
    }
}
return 0;
</code>```

}

答:
I Foud the error, You forgot to include string module in the beginning.
just include string and it will work fine.

```<code>  #include <iostream>
  #include <string>
  using namespace std;
      int main(){
        string input;
          while(input != "quit"){
            getline(cin, input);
           if(input == "new game"){
             town(player);
         }
           if(input == "load game"){
             cout << "enter save file: " << endl;
             load(player);
         }
      }
    return 0;
  }
</code>```

Body:
I have a string variable called input which i use getline to input text into. When I try to compare the variable input to another string such as if(input == "new game") it does not appear to evaluate the comparison. I know that it is actually inputing the correct text because when I use cout on input it outputs correctly (typing in "new game" will output "new game"). I looked up problems with getline and I read that cin leaves behind the \n in an input string which is picked up by getline. I tried using cin.ignore(), cin.clear(), and cin.sync() but they do not appear to fix the issue. Besides, there isn't any input that comes before getline(cin, input) anyway. The code in question is blow, any help is appreciated, thanks!

int main(){
string input;
while(input != "quit"){
    getline(cin, input);
    if(input == "new game"){
        town(player);
    }
    if(input == "load game"){
        cout << "enter save file: " << endl;
        load(player);
    }
}
return 0;

}

Body:
I Foud the error, You forgot to include string module in the beginning.
just include string and it will work fine.

  #include <iostream>
  #include <string>
  using namespace std;
      int main(){
        string input;
          while(input != "quit"){
            getline(cin, input);
           if(input == "new game"){
             town(player);
         }
           if(input == "load game"){
             cout << "enter save file: " << endl;
             load(player);
         }
      }
    return 0;
  }


问:
UITextView textContainer exclusion path not working when it's middle of view controller
I have my UIView in the middle of the View Controller and I am setting the exclusion path as follow

```<code>    -(void) viewDidLayoutSubviews
    {
      UIBezierPath *exludedPath = [UIBezierPath bezierPathWithRect:aRect];
      self.textView.textContainer.exclusionPaths = @[excludedPath];
    }
</code>```

here aRect has same x and y as UITextView and reasonable height and width

this code does work when my UITextView is at the top of the view controller but doesn't when it's somewhere in the middle of the view controller.

Is it the viewController life time issue? or some property of the view controller that's causing this?

答: To anyone looking at this question, I had the same issue and figured out that the rect was incorrect. Say your image view's rect is (20, 30, 50, 50) and the text view's rect is (20, 30, 300, 400). The bezier path's rect should be (0,0,50,50), not (20, 30, 50, 50). That is, pass the bounds and not the actual frame.</p>

Body:
I have my UIView in the middle of the View Controller and I am setting the exclusion path as follow

    -(void) viewDidLayoutSubviews
    {
      UIBezierPath *exludedPath = [UIBezierPath bezierPathWithRect:aRect];
      self.textView.textContainer.exclusionPaths = @[excludedPath];
    }

here aRect has same x and y as UITextView and reasonable height and width

this code does work when my UITextView is at the top of the view controller but doesn't when it's somewhere in the middle of the view controller.

Is it the viewController life time issue? or some property of the view controller that's causing this?


问:
Background image set in CSS not working in Edge mobile but work in Chrome
I have this CSS in a Razor Page project:

```<code>    body {
        background: url('../images/graphics/myimage.jpeg') no-repeat center center fixed;
        padding-bottom: 20px;
    }
</code>```

The main body tag and link to the style sheet are in _Layout.cshtml.

The background image works fine everywhere except for pages other than index.cshtml in the mobile version of MS Edge browser; it works just fine in Chrome mobile. Works fine in all desktop browsers too.

I've only tested on Android.

答:
According to your description, I come to the following conclusions:

Try restarting your Edge mobile and cleaning up its cache.

Check whether the image cache settings of Edge are limited;

Perhaps the Edge mobile belongs to the third-party software on your phone, so its speed is slightly slower. In addition, its compatibility with your phone's operating system affects the page rendering process.You could try different models of mobile phones to test.

For more:this link.

If the background image still cannot be loaded in edge mobile, hopefully you could provide information about the more code or settings that is related to browser loading.

Body:
I have this CSS in a Razor Page project:

    body {
        background: url('../images/graphics/myimage.jpeg') no-repeat center center fixed;
        padding-bottom: 20px;
    }

The main body tag and link to the style sheet are in _Layout.cshtml.

The background image works fine everywhere except for pages other than index.cshtml in the mobile version of MS Edge browser; it works just fine in Chrome mobile. Works fine in all desktop browsers too.

I've only tested on Android.


问:
Running out of memory using images and PageView with SwiftUI
I am writing an app that shows users large pictures that they can flick through and zoom in, similar to the photos app or a book. I am trying to write this with SwiftUI. I have been following the SwiftUI tutorials on apples site  and I have adapted the code to read a json file to create an array of "Imageslides" - a way to hold the images and information about them. I have then used PageView and PageViewController to display the ContentView> ContentView displays the image and some buttons that show text about the images I am displaying. My problem is when I swipe through the pages the memory goes up and up until the app crashes. Now, if I was using UIKit I could use

```<code>if let imgPath = Bundle.main.path(forResource: name, ofType: nil)
    {
        return UIImage(contentsOfFile: imgPath)
    }
</code>```

But I can't see how to use contentsOfFile using Image in swiftUI, or another way that will let the images get out of memory when not needed. I have the images in a resources folder, not in the assets library.
Thanks for your help.

```<code>//data.swift - reading from json, mainly from apple's tutorials
import Foundation
import UIKit
import SwiftUI

let imageData: [Imageslide] = load("imageData.json")

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}

final class ImageStore {
    typealias _ImageDictionary = [String: CGImage]
    fileprivate var images: _ImageDictionary = [:]

    fileprivate static var scale = 2

    static var shared = ImageStore()

    func image(name: String) -> Image {
        let index = _guaranteeImage(name: name)

        return Image(images.values[index], scale: CGFloat(ImageStore.scale), label: Text(name))
    }

    static func loadImage(name: String) -> CGImage {
        guard
            let url = Bundle.main.url(forResource: name, withExtension: "png"),
            let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
            let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
        else {
            fatalError("Couldn't load image \(name).jpg from main bundle.")
        }
        return image
    }

    fileprivate func _guaranteeImage(name: String) -> _ImageDictionary.Index {
        if let index = images.index(forKey: name) { return index }

        images[name] = ImageStore.loadImage(name: name)
        return images.index(forKey: name)!
    }
}

</code>```

```<code>//imageslide.swift - abstract for holding my image slide and button info

import SwiftUI

struct buttonInfo: Hashable, Codable{
    var text: String? = nil
    var coords: [Int]? = nil
    public enum CodingKeys : String, CodingKey {
        case text, coords
    }
    init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      self.text = try container.decodeIfPresent(String.self, forKey: .text)
      self.coords = try container.decodeIfPresent([Int].self, forKey: .coords)
    }
      func encode(to encoder: Encoder) throws {
      var container = encoder.container(keyedBy: CodingKeys.self)
      try container.encode(self.text, forKey: .text)
      try container.encode(self.coords, forKey: .coords)
    }
}

struct Imageslide: Hashable, Codable, Identifiable {

    public var imagename: String
   public var id: Int
    public var noButtons: Int

    public var buttoninfo: [buttonInfo]? = nil

    public enum CodingKeys : String, CodingKey {
        case imagename, id, noButtons, buttoninfo
        case imageslide = "Imageslide"
    }
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let imageslide = try container.nestedContainer(keyedBy:
        CodingKeys.self, forKey: .imageslide)
        self.imagename = try imageslide.decode(String.self, forKey: .imagename)
        self.id = try imageslide.decode(Int.self, forKey: .id)
        self.noButtons = try imageslide.decode(Int.self, forKey: .id)
        self.buttoninfo = try imageslide.decodeIfPresent([buttonInfo].self, forKey: .buttoninfo)
    }

   func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
     var imageslide = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .imageslide)
     try imageslide.encode(self.imagename, forKey: .imagename)
     try imageslide.encode(self.id, forKey: .id)
     try imageslide.encode(self.noButtons, forKey: .noButtons)
    try imageslide.encode(self.buttoninfo, forKey: .buttoninfo)
    }
}

extension Imageslide {
    var image: Image {
        ImageStore.shared.image(name: imagename)
    }
}

struct ButtonDataStore: Codable{
    var buttonData: [buttonInfo]
}

</code>```

```<code>//contentview.swift - used to show the images and buttons
import SwiftUI

struct ContentView: View {
    var imageslide: Imageslide
    @State private var button1Visible = true
    @State var scale: CGFloat = 1.0

    var body: some View {

        ZStack {

            Image(uiImage: (UIImage(named: imageslide.imagename)!))
           //   imageslide.image
                //   Image(imageslide.imagename)
                .resizable()
           .frame(width: 2732/2, height: 2048/2)
      //Pinch to zoom code goes here

                .background(/*@START_MENU_TOKEN@*/Color.black/*@END_MENU_TOKEN@*/)

                    .edgesIgnoringSafeArea(.all)
                .statusBar(hidden: true)

            if (imageslide.noButtons != 0)
            {
                if imageslide.buttoninfo != nil
                {
                    ForEach(imageslide.buttoninfo!, id: \.self) {count in

                        ButtonView(text: count.text!, xcoord: count.coords![0], ycoord: count.coords![1], xcoordo: count.coords![2], ycoordo: count.coords![3])
                    }
                }
        }
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

        //ContentView(imageslide: imageData[0])
        ContentView(imageslide: imageData[1]).previewLayout(
            .fixed(width: 2732/2, height: 2048/2)
        )
    }
}
}

</code>```

```<code>//PageViewController.swift

import SwiftUI
import UIKit

struct PageViewController: UIViewControllerRepresentable {
    var controllers: [UIViewController]
    @Binding var currentPage: Int

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIPageViewController {
         let pageViewController = UIPageViewController(
             transitionStyle: .scroll,
             navigationOrientation: .horizontal)
        pageViewController.dataSource = context.coordinator
        pageViewController.delegate = context.coordinator

         return pageViewController
     }

    func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
        pageViewController.setViewControllers(
             [controllers[currentPage]], direction: .forward, animated: true)
    }

    class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
        var parent: PageViewController

        init(_ pageViewController: PageViewController) {
            self.parent = pageViewController
        }

    func pageViewController(
        _ pageViewController: UIPageViewController,
        viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = parent.controllers.firstIndex(of: viewController) else {
            return nil
        }
        if index == 0 {
            return parent.controllers.last
        }
        return parent.controllers[index - 1]
    }

    func pageViewController(
        _ pageViewController: UIPageViewController,
        viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = parent.controllers.firstIndex(of: viewController) else {
            return nil
        }
        if index + 1 == parent.controllers.count {
            return parent.controllers.first
        }
        return parent.controllers[index + 1]

    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed,
            let visibleViewController = pageViewController.viewControllers?.first,
            let index = parent.controllers.firstIndex(of: visibleViewController)
        {
            parent.currentPage = index
        }
    }
}

}

</code>```

```<code>//pageview.swift
import SwiftUI

struct PageView<Page: View>: View {
    var viewControllers: [UIHostingController<Page>]

    @State var currentPage = 0

    init(_ views: [Page]) {
        self.viewControllers = views.map { UIHostingController(rootView: $0) }
    }

    var body: some View {
         PageViewController(controllers: viewControllers, currentPage: $currentPage)
    }
}

struct PageView_Previews: PreviewProvider {
    static var previews: some View {

        PageView(imageData.map {ContentView(imageslide: $0)})
    }
}
</code>```

Sample of the JSON I am using.

```<code>   {
      "Imageslide":{
         "imagename":"MOS_SHB_1",
         "id":1001,
         "noButtons":0
      }
   },
   {
      "Imageslide":{
         "imagename":"MOS_SHB_2",
         "id":1002,
         "noButtons":0
      }
   },
   {
      "Imageslide":{
         "imagename":"MOS_SHB_3",
         "id":1003,
         "noButtons":1,
         "buttoninfo":[
            {
               "text":"The two halves of the arch touched for the first time. Workers riveted both top and bottom sections of the arch together, and the arch became self-supporting, allowing the support cables to be removed. On 20 August 1930 the joining of the arches was celebrated by flying the flags of Australia and the United Kingdom from the jibs of the creeper cranes.",
               "coords":[
                  -150,
                  220,
                  200,
                  200
               ]
            }
         ]
      }
   },
</code>```

答:
Create UIImage as before

```<code>let imageModel = UIImage(contentsOfFile: imgPath)
</code>```

and use it in body as a model for Image view

```<code>Image(uiImage: imageModel ?? UIImage())
</code>```

Body:
I am writing an app that shows users large pictures that they can flick through and zoom in, similar to the photos app or a book. I am trying to write this with SwiftUI. I have been following the SwiftUI tutorials on apples site  and I have adapted the code to read a json file to create an array of "Imageslides" - a way to hold the images and information about them. I have then used PageView and PageViewController to display the ContentView> ContentView displays the image and some buttons that show text about the images I am displaying. My problem is when I swipe through the pages the memory goes up and up until the app crashes. Now, if I was using UIKit I could use

if let imgPath = Bundle.main.path(forResource: name, ofType: nil)
    {
        return UIImage(contentsOfFile: imgPath)
    }

But I can't see how to use contentsOfFile using Image in swiftUI, or another way that will let the images get out of memory when not needed. I have the images in a resources folder, not in the assets library.
Thanks for your help.

//data.swift - reading from json, mainly from apple's tutorials
import Foundation
import UIKit
import SwiftUI

let imageData: [Imageslide] = load("imageData.json")

func load<T: Decodable>(_ filename: String) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}

final class ImageStore {
    typealias _ImageDictionary = [String: CGImage]
    fileprivate var images: _ImageDictionary = [:]

    fileprivate static var scale = 2

    static var shared = ImageStore()

    func image(name: String) -> Image {
        let index = _guaranteeImage(name: name)

        return Image(images.values[index], scale: CGFloat(ImageStore.scale), label: Text(name))
    }

    static func loadImage(name: String) -> CGImage {
        guard
            let url = Bundle.main.url(forResource: name, withExtension: "png"),
            let imageSource = CGImageSourceCreateWithURL(url as NSURL, nil),
            let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil)
        else {
            fatalError("Couldn't load image \(name).jpg from main bundle.")
        }
        return image
    }

    fileprivate func _guaranteeImage(name: String) -> _ImageDictionary.Index {
        if let index = images.index(forKey: name) { return index }

        images[name] = ImageStore.loadImage(name: name)
        return images.index(forKey: name)!
    }
}

//imageslide.swift - abstract for holding my image slide and button info

import SwiftUI

struct buttonInfo: Hashable, Codable{
    var text: String? = nil
    var coords: [Int]? = nil
    public enum CodingKeys : String, CodingKey {
        case text, coords
    }
    init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      self.text = try container.decodeIfPresent(String.self, forKey: .text)
      self.coords = try container.decodeIfPresent([Int].self, forKey: .coords)
    }
      func encode(to encoder: Encoder) throws {
      var container = encoder.container(keyedBy: CodingKeys.self)
      try container.encode(self.text, forKey: .text)
      try container.encode(self.coords, forKey: .coords)
    }
}

struct Imageslide: Hashable, Codable, Identifiable {

    public var imagename: String
   public var id: Int
    public var noButtons: Int

    public var buttoninfo: [buttonInfo]? = nil

    public enum CodingKeys : String, CodingKey {
        case imagename, id, noButtons, buttoninfo
        case imageslide = "Imageslide"
    }
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let imageslide = try container.nestedContainer(keyedBy:
        CodingKeys.self, forKey: .imageslide)
        self.imagename = try imageslide.decode(String.self, forKey: .imagename)
        self.id = try imageslide.decode(Int.self, forKey: .id)
        self.noButtons = try imageslide.decode(Int.self, forKey: .id)
        self.buttoninfo = try imageslide.decodeIfPresent([buttonInfo].self, forKey: .buttoninfo)
    }

   func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy: CodingKeys.self)
     var imageslide = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .imageslide)
     try imageslide.encode(self.imagename, forKey: .imagename)
     try imageslide.encode(self.id, forKey: .id)
     try imageslide.encode(self.noButtons, forKey: .noButtons)
    try imageslide.encode(self.buttoninfo, forKey: .buttoninfo)
    }
}

extension Imageslide {
    var image: Image {
        ImageStore.shared.image(name: imagename)
    }
}

struct ButtonDataStore: Codable{
    var buttonData: [buttonInfo]
}

//contentview.swift - used to show the images and buttons
import SwiftUI

struct ContentView: View {
    var imageslide: Imageslide
    @State private var button1Visible = true
    @State var scale: CGFloat = 1.0

    var body: some View {

        ZStack {

            Image(uiImage: (UIImage(named: imageslide.imagename)!))
           //   imageslide.image
                //   Image(imageslide.imagename)
                .resizable()
           .frame(width: 2732/2, height: 2048/2)
      //Pinch to zoom code goes here

                .background(/*@START_MENU_TOKEN@*/Color.black/*@END_MENU_TOKEN@*/)

                    .edgesIgnoringSafeArea(.all)
                .statusBar(hidden: true)

            if (imageslide.noButtons != 0)
            {
                if imageslide.buttoninfo != nil
                {
                    ForEach(imageslide.buttoninfo!, id: \.self) {count in

                        ButtonView(text: count.text!, xcoord: count.coords![0], ycoord: count.coords![1], xcoordo: count.coords![2], ycoordo: count.coords![3])
                    }
                }
        }
        }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

        //ContentView(imageslide: imageData[0])
        ContentView(imageslide: imageData[1]).previewLayout(
            .fixed(width: 2732/2, height: 2048/2)
        )
    }
}
}

//PageViewController.swift

import SwiftUI
import UIKit

struct PageViewController: UIViewControllerRepresentable {
    var controllers: [UIViewController]
    @Binding var currentPage: Int

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIPageViewController {
         let pageViewController = UIPageViewController(
             transitionStyle: .scroll,
             navigationOrientation: .horizontal)
        pageViewController.dataSource = context.coordinator
        pageViewController.delegate = context.coordinator

         return pageViewController
     }

    func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
        pageViewController.setViewControllers(
             [controllers[currentPage]], direction: .forward, animated: true)
    }

    class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
        var parent: PageViewController

        init(_ pageViewController: PageViewController) {
            self.parent = pageViewController
        }

    func pageViewController(
        _ pageViewController: UIPageViewController,
        viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = parent.controllers.firstIndex(of: viewController) else {
            return nil
        }
        if index == 0 {
            return parent.controllers.last
        }
        return parent.controllers[index - 1]
    }

    func pageViewController(
        _ pageViewController: UIPageViewController,
        viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = parent.controllers.firstIndex(of: viewController) else {
            return nil
        }
        if index + 1 == parent.controllers.count {
            return parent.controllers.first
        }
        return parent.controllers[index + 1]

    }

    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed,
            let visibleViewController = pageViewController.viewControllers?.first,
            let index = parent.controllers.firstIndex(of: visibleViewController)
        {
            parent.currentPage = index
        }
    }
}

}

//pageview.swift
import SwiftUI

struct PageView<Page: View>: View {
    var viewControllers: [UIHostingController<Page>]

    @State var currentPage = 0

    init(_ views: [Page]) {
        self.viewControllers = views.map { UIHostingController(rootView: $0) }
    }

    var body: some View {
         PageViewController(controllers: viewControllers, currentPage: $currentPage)
    }
}

struct PageView_Previews: PreviewProvider {
    static var previews: some View {

        PageView(imageData.map {ContentView(imageslide: $0)})
    }
}

Sample of the JSON I am using.

   {
      "Imageslide":{
         "imagename":"MOS_SHB_1",
         "id":1001,
         "noButtons":0
      }
   },
   {
      "Imageslide":{
         "imagename":"MOS_SHB_2",
         "id":1002,
         "noButtons":0
      }
   },
   {
      "Imageslide":{
         "imagename":"MOS_SHB_3",
         "id":1003,
         "noButtons":1,
         "buttoninfo":[
            {
               "text":"The two halves of the arch touched for the first time. Workers riveted both top and bottom sections of the arch together, and the arch became self-supporting, allowing the support cables to be removed. On 20 August 1930 the joining of the arches was celebrated by flying the flags of Australia and the United Kingdom from the jibs of the creeper cranes.",
               "coords":[
                  -150,
                  220,
                  200,
                  200
               ]
            }
         ]
      }
   },

Body:
Create UIImage as before

let imageModel = UIImage(contentsOfFile: imgPath)

and use it in body as a model for Image view

Image(uiImage: imageModel ?? UIImage())


问:
Stripe Connect redirect uri issue for multitenant application
I am following the steps in Stripe connect oaunth. Everything worked fine till there was issue on redirecting after the auth as my application is Multitenant(with multiple subdomains).
We can pass a param called redirect_uri which should exactly match one of the redirect_uris that we have already added in our stripe account's platform settings.

```<code>https://connect.stripe.com/oauth/authorize?response_type=code&client_id=<my_client_id>&scope=read_write&redirect_uri=https://subdomain.staging.domain.com
</code>```

Here comes the issue that the call to stripe will be made from one of the subdomains and it is not practical to enter each and every subdomains as there are plenty of them and it has potential to grow in number as well.

Any possible solutions?

答:
The workaround on this was having the state param which stripe returns to the redirect URI we specifies.

I have sent the subdomain name as the state param. Then from stripe redirected to a controller action(this url was given as the redirect URI) where there was no authentication required. From this controller action, using the returned state param, the url to the required method(with subdomain in the url) was created and redirected. This served my need!

Body:
I am following the steps in Stripe connect oaunth. Everything worked fine till there was issue on redirecting after the auth as my application is Multitenant(with multiple subdomains).
We can pass a param called redirect_uri which should exactly match one of the redirect_uris that we have already added in our stripe account's platform settings.

https://connect.stripe.com/oauth/authorize?response_type=code&client_id=<my_client_id>&scope=read_write&redirect_uri=https://subdomain.staging.domain.com

Here comes the issue that the call to stripe will be made from one of the subdomains and it is not practical to enter each and every subdomains as there are plenty of them and it has potential to grow in number as well.

Any possible solutions?


问:
how to run unit tests for a play framework application within intellij
I tried running unit test on the play framework java starter example within intellij but it doesn't seem to work.

I downloaded the project and imported it into intellij via the SBT import.

When I tried running the tests from intellij I got "Class not found: "UnitTest"Empty test suite"

If I run the SBT test task, the tests are running and passing.

When I go bask to running the tests from intellij after running the SBT test task, the test run and pass.
It's like intellij is not compiling the project

I am working with intellij ultimate edition version 2018.2 and have the scala plugin (v 2018.2.11)

How can I make this work?

Edit (in respose to @hce)

I upgraded intellij to the latest version: 2018.3.2 (couldn't find 2018.3.5) but I still experience similar problems.

I started with a newly downloaded starter project.
import the sbt project:

Then tried to compile and got an error:

I managed to solve the compilation problem by configuring intellij to use the play2 compiler ("Use play2 compiler for this project")

I then tried running the tests and but intellij complains it can't find the class

this is the run configuration that was created by intellij. the class name (UnitTest) is marked red...

Is it any different in your environment?

Is there anything wrong in my process?

答:
I use Scala plugin and Play Framework. I can run tests in 3 ways:

simple run 1 test from IDE (but I can't run all tests in package by this way)

run tests from sbt

run tests with use this configuration (it's allow run tests with coverage):

Sorry for my English.


问:
How to implement the Luhn alorithm in OCL
I am trying to find the Luhn algorithm in OCL to check the validity of ISIN. Can anyone provide a code example would it be great!   </p>

答:
In the German Wikipedia article about the Luhns algorithm (https://de.wikipedia.org/wiki/Luhn-Algorithmus) you can find an example to calculate the value for an ident of 446-667-651. The algorithm below calculates the correct value of 40.

```<code>let list = '446667651'.ToCharArray.strToInt in
Sequence{1..list->size}
->Collect(i|
    if (list->size-i).Mod(2)=0 then
        list.at(i)
    else
        (list.at(i)*2).Mod(9)
    endif)
->Sum
</code>```

Maybe you need some adaptions for calculating the value for ISINs.

Body:
In the German Wikipedia article about the Luhns algorithm (https://de.wikipedia.org/wiki/Luhn-Algorithmus) you can find an example to calculate the value for an ident of 446-667-651. The algorithm below calculates the correct value of 40.

let list = '446667651'.ToCharArray.strToInt in
Sequence{1..list->size}
->Collect(i|
    if (list->size-i).Mod(2)=0 then
        list.at(i)
    else
        (list.at(i)*2).Mod(9)
    endif)
->Sum

Maybe you need some adaptions for calculating the value for ISINs.


问:
Efficient way to iterate over cursor object with Pymongo / MongoDB
I prefilter 3 collections and build a single new collection from it. To do this i iterate over the cursor objects like this (monate, wochen, tage are justs lists containing relevant datetime objects:

```<code>monate_final = collection1.find({"NewDate": {"$in": list(monate)}})
wochen_final = collection2.find({"NewDate": {"$in": list(wochen)}})
tage_final = collection3.find({"NewDate": {"$in": list(tage)}})

master_list = [monate_final, wochen_final, tage_final]

for collection in master_list:
    for document in collection:
        self.target.insert_one(document)
</code>```

The code works, but since the the final collections contains > 100 millions records, the process just takes forever. I did not find a more efficient way to do this. Building a pandas DataFrame and then use insert_many() does not work due to memory limitation. Can anyone help me?

答:
I don't have enough reputation to make this as a comment.

I have not validated this. But you could make an aggregation pipeline which filters your collections. And the final step in the pipeline is the $out operator to save all documents in the pipeline into the new collection.

https://docs.mongodb.com/manual/reference/operator/aggregation/out/

I'm not deep into the inner workings from MongoDB. But I would expect the pipeline to be run completely DB side which would greatly improve the performance of the operation.

Wish you luck solving this! (Don't forget to add your solution for other people :D )

Body:
I prefilter 3 collections and build a single new collection from it. To do this i iterate over the cursor objects like this (monate, wochen, tage are justs lists containing relevant datetime objects:

monate_final = collection1.find({"NewDate": {"$in": list(monate)}})
wochen_final = collection2.find({"NewDate": {"$in": list(wochen)}})
tage_final = collection3.find({"NewDate": {"$in": list(tage)}})

master_list = [monate_final, wochen_final, tage_final]

for collection in master_list:
    for document in collection:
        self.target.insert_one(document)

The code works, but since the the final collections contains > 100 millions records, the process just takes forever. I did not find a more efficient way to do this. Building a pandas DataFrame and then use insert_many() does not work due to memory limitation. Can anyone help me?


问:
Creating a system overlay window (always on top)
I'm trying to create an always-op-top button/clickable-image
which stays on top of all the windows all the time.

The proof of
concept is

here - Smart Taskbar (on AppBrain)

and here V1.4.0 Sidebar style SWKey - Button savior (on xda-developers)

I have been successful and have a running service now. The service
displays some text on top left corner of screen all the time while
user can freely interact with rest of apps in normal manner.

What I'm
doing is subclass ViewGroup and add it to root window manager with
flag TYPE_SYSTEM_OVERLAY. Now I want to add a button/clickable-image
in place of this text which can receive touch events on itself. I
tried overriding "onTouchEvent" for the whole ViewGroup but it does
not receive any event.

How can I receive events only on certain parts
of my always-on-top view group? Kindly suggest.

```<code>public class HUD extends Service {
    HUDView mView;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
        mView = new HUDView(this);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                0,
//              WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                      | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.TOP;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(mView, params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_LONG).show();
        if(mView != null)
        {
            ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mView);
            mView = null;
        }
    }
}

class HUDView extends ViewGroup {
    private Paint mLoadPaint;

    public HUDView(Context context) {
        super(context);
        Toast.makeText(getContext(),"HUDView", Toast.LENGTH_LONG).show();

        mLoadPaint = new Paint();
        mLoadPaint.setAntiAlias(true);
        mLoadPaint.setTextSize(10);
        mLoadPaint.setARGB(255, 255, 0, 0);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText("Hello World", 5, 15, mLoadPaint);
    }

    @Override
    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
        Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
        return true;
    }
}
</code>```

答:
This is an old Question but recently Android has a support for Bubbles. Bubbles are soon going to be launched but currently developers can start using them.They are designed to be an alternative to using SYSTEM_ALERT_WINDOW. Apps like (Facebook Messenger and MusiXMatch use the same concept).

Bubbles are created via the Notification API, you send your notification as normal. If you want it to bubble you need to attach some extra data to it. For more information about Bubbles you can go to the official Android Developer Guide on Bubbles.

Body:
I'm trying to create an always-op-top button/clickable-image
which stays on top of all the windows all the time.

The proof of
concept is

here - Smart Taskbar (on AppBrain)

and here V1.4.0 Sidebar style SWKey - Button savior (on xda-developers)

I have been successful and have a running service now. The service
displays some text on top left corner of screen all the time while
user can freely interact with rest of apps in normal manner.

What I'm
doing is subclass ViewGroup and add it to root window manager with
flag TYPE_SYSTEM_OVERLAY. Now I want to add a button/clickable-image
in place of this text which can receive touch events on itself. I
tried overriding "onTouchEvent" for the whole ViewGroup but it does
not receive any event.

How can I receive events only on certain parts
of my always-on-top view group? Kindly suggest.

public class HUD extends Service {
    HUDView mView;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();
        mView = new HUDView(this);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                0,
//              WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                      | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.TOP;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.addView(mView, params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_LONG).show();
        if(mView != null)
        {
            ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mView);
            mView = null;
        }
    }
}

class HUDView extends ViewGroup {
    private Paint mLoadPaint;

    public HUDView(Context context) {
        super(context);
        Toast.makeText(getContext(),"HUDView", Toast.LENGTH_LONG).show();

        mLoadPaint = new Paint();
        mLoadPaint.setAntiAlias(true);
        mLoadPaint.setTextSize(10);
        mLoadPaint.setARGB(255, 255, 0, 0);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText("Hello World", 5, 15, mLoadPaint);
    }

    @Override
    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
        Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
        return true;
    }
}


问:
Why does viewModelScope.launch run on the main thread by default
While I was learning coroutines and how to properly use them in an android app I found something I was surprised about.

When launching a coroutine using viewModelScope.launch { } and setting a breakpoint inside the launch lambda I noticed my app wasn't responsive anymore because it was still on the main thread.

This confuses me because the docs of viewModelScope.launch { } clearly state:

Launches a new coroutine without blocking the current thread

Isn't the current thread the main thread ? What is the whole purpose of launch if it doesn't run on a different thread by default ?

I was able to run it on anther thread using viewModelScope.launch(Dispatchers.IO){ } which works as I was expecting, namely on another thread.

What I am trying to accomplish from the launch method is to call a repository and do some IO work namely call a webservice and store the data in a room db. So I was thinking of calling viewModelScope.launch(Dispatchers.IO){ } do all the work on a different thread and in the end update the LiveData result.

viewModelScope.launch(Dispatchers.IO){
    liveData.postValue(someRepository.someWork())
}

So my second question is, is this the way to go ?

答:
So my second question is, is this the way to go ?

I would expect two things to be different in your current approach.

1.) First step would be to define the scheduler of the background operation via withContext.

```<code>class SomeRepository {
    suspend fun doWork(): SomeResult = withContext(Dispatchers.IO) {
        ...
    }
}
</code>```

This way, the operation itself runs on a background thread, but you didn't force your original scope to be "off-thread".

2.) Jetpack Lifecycle KTX provides the liveData { coroutine builder so that you don't have to postValue to it manually.

```<code>val liveData: LiveData<SomeResult> = liveData {
    emit(someRepository.someWork())
}
</code>```

Which in a ViewModel, you would use like so:

```<code>val liveData: LiveData<SomeResult> = liveData(context = viewModelScope.coroutineContext) {
    withContext(Dispatchers.IO) {
        emit(someRepository.someWork())
    }
}
</code>```

And now you can automatically trigger data-loading via observing, and not having to manually invoke viewModelScope.launch {}.

Body:
So my second question is, is this the way to go ?

I would expect two things to be different in your current approach.

1.) First step would be to define the scheduler of the background operation via withContext.

class SomeRepository {
    suspend fun doWork(): SomeResult = withContext(Dispatchers.IO) {
        ...
    }
}

This way, the operation itself runs on a background thread, but you didn't force your original scope to be "off-thread".

2.) Jetpack Lifecycle KTX provides the liveData { coroutine builder so that you don't have to postValue to it manually.

val liveData: LiveData<SomeResult> = liveData {
    emit(someRepository.someWork())
}

Which in a ViewModel, you would use like so:

val liveData: LiveData<SomeResult> = liveData(context = viewModelScope.coroutineContext) {
    withContext(Dispatchers.IO) {
        emit(someRepository.someWork())
    }
}

And now you can automatically trigger data-loading via observing, and not having to manually invoke viewModelScope.launch {}.


问:
How to find objects in floor plan image in Tkinter python through svg file?
I have a vectorized floorplan image. I want to identify the objects in the image through the vector data in the SVG file of that image. The SVG code does not have any close points(z) in between them. So I am unable to understand when does the point moves to the other object? Can somebody help me, please?

I have very little knowledge about these SVG files and using them in Tkinter. So please somebody help me or suggest me what can I do?

This is the vector data of the image.
vector data of the image

答:
use in conjunction with SO floorplan question.
Jump to z_final_floorplan.svg for final file.

A

Create 4 files:

```<code>w_original_floorplan.svg
x_rough_static_floorplan.svg
y_rough_live_floorplan.svg
z_final_floorplan.svg
</code>```

w_original_floorplan.svg and x_rough_static_floorplan.svg are identical apart from filename.

y_rough_live_floorplan.svg and z_final_floorplan.svg are empty; to be populated.

Copy x_rough_static_floorplan.svg to y_rough_live_floorplan.svg.

Open y_rough_live_floorplan.svg on browser using server.

x_rough_static_floorplan.svg find all M and replace with two newlines / symbol M (case sensitive). shift + enter shift + enter /M

B

[this section takes the time]

Take away 1st '/' in path in y_rough_live_floorplan.svg [shows blackout_floorplan]

Label x_rough_static_floorplan.svg code section blackout_floorplan where code is.

(this file is used as rough-work, so being xml / svg valid is irrelevant)

In y_rough_live_floorplan.svg find next '/' and delete it [shows floorplan_top_left_whiteout]

Label x_rough_static_floorplan.svg code section floorplan_top_left_whiteout where code is.

Have x_rough_static_floorplan.svg and y_rough_live_floorplan.svg open in 2 windows, will be going back and forth to each of them. Keep repeating until at end.

(hint: find tool seems to be on switching from files in vscode, so you can use find / and next one cmd + g easily) Maybe handy to have a paper printout of original svg as reference and label the names of objects you create e.g.bath, sink, table, as you go along (don’t be fooled by this, one table is 'table'. Is 2nd chair chair2, chair_2, chair_two etc.?) etc..

C

Reorder the whole labels and corresponding code in path x_rough_static_floorplan.svg so the labels are ordered next to each other, but in the order they are found in the path:

e.g.

…

floorplan

bath

sink

table_chairs

sofa

…

Use the 'find' tool here. This process, itself will require a temp file to copy and paste to rather than reorder within the file working on. And rewrite temp to file working on. Might be good idea to create checklist of objects and cross-off as done.
E.g. floorplan, bath, table_chairs, sink…

D

Create path elements from your grouped objects, putting each id as id=“floorplan_main”, id=“bath”, id=“sink” etc.. etc..

Bear in mind, the data of how this is drawn is really, really bad. Really they should be drawn with rect elements for a rectangle when possible and a lot of the path data is very unnecessary, but that’s obviously how the application generates the svg.

Body:
use in conjunction with SO floorplan question.
Jump to z_final_floorplan.svg for final file.

A

Create 4 files:

w_original_floorplan.svg
x_rough_static_floorplan.svg
y_rough_live_floorplan.svg
z_final_floorplan.svg

w_original_floorplan.svg and x_rough_static_floorplan.svg are identical apart from filename.

y_rough_live_floorplan.svg and z_final_floorplan.svg are empty; to be populated.

Copy x_rough_static_floorplan.svg to y_rough_live_floorplan.svg.

Open y_rough_live_floorplan.svg on browser using server.

x_rough_static_floorplan.svg find all M and replace with two newlines / symbol M (case sensitive). shift + enter shift + enter /M

B

[this section takes the time]

Take away 1st '/' in path in y_rough_live_floorplan.svg [shows blackout_floorplan]

Label x_rough_static_floorplan.svg code section blackout_floorplan where code is.

(this file is used as rough-work, so being xml / svg valid is irrelevant)

In y_rough_live_floorplan.svg find next '/' and delete it [shows floorplan_top_left_whiteout]

Label x_rough_static_floorplan.svg code section floorplan_top_left_whiteout where code is.

Have x_rough_static_floorplan.svg and y_rough_live_floorplan.svg open in 2 windows, will be going back and forth to each of them. Keep repeating until at end.

(hint: find tool seems to be on switching from files in vscode, so you can use find / and next one cmd + g easily) Maybe handy to have a paper printout of original svg as reference and label the names of objects you create e.g.bath, sink, table, as you go along (don’t be fooled by this, one table is 'table'. Is 2nd chair chair2, chair_2, chair_two etc.?) etc..

C

Reorder the whole labels and corresponding code in path x_rough_static_floorplan.svg so the labels are ordered next to each other, but in the order they are found in the path:

e.g.

…

floorplan

bath

sink

table_chairs

sofa

…

Use the 'find' tool here. This process, itself will require a temp file to copy and paste to rather than reorder within the file working on. And rewrite temp to file working on. Might be good idea to create checklist of objects and cross-off as done.
E.g. floorplan, bath, table_chairs, sink…

D

Create path elements from your grouped objects, putting each id as id=“floorplan_main”, id=“bath”, id=“sink” etc.. etc..

Bear in mind, the data of how this is drawn is really, really bad. Really they should be drawn with rect elements for a rectangle when possible and a lot of the path data is very unnecessary, but that’s obviously how the application generates the svg.


问:
Using AJAX with multiple submit buttons
I have a html form which includes 2 submit buttons.

These two submit buttons connect to a php file which runs statements based on the submits. The php file runs correctly, although when I use AJAX to send the data and to prevent to redirect, the information does not reach the php file, despite the php statements working fine when I am testing.

Interesting, when I use a PHP with just one submit and without if/else the information reaches the php for processing without redirection, so the problem probably lies with the two submits, and because my AJAX can't handle or distinguish the submits.

I attach my code

HTML

```<code><input type="submit" name="first_submit" value="Frist" />
<input type="submit" name="second_submit" value="Second" />
</code>```

AJAX

```<code><script>
     $(function () {
    $('#form').on('submit', function (e) {
        $.ajax({
            type: 'post',
            url: 'test.php',
            data: $(this).serialize(),
            success: function () {
                location.reload();
            }
        });
        e.preventDefault();
    });
});
    </script>
</code>```

PHP

```<code>if (isset($_POST['first_submit'])) {
             //do something

    }
    elseif (isset($_POST['second_submit'])) {
               //do something
    }

    else {
    //do something
    }

?>
</code>```

答:
You can create and Use some session variable to achieve it easily.

E.g. $_SESSION['validate'].

HTML and PHP Code for buttons

```<code><button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>
</code>```

jquery and ajax Script

```<code><script>
    $(document).ready(function(){

        $("#form").on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'handler-file.php',
                data:  new FormData(this),
                dataType: "json",
                enctype: 'multipart/form-data',
                contentType: false,
                cache: false,
                processData:false,
                error:function(error){
                    //your required code or alert
                    alert(error.responseText);
                },
                success: function(response){
                    if(response.status=='1')
                    {
                        //your required code or alert
                        $('#first_submit').hide();
                        $('#second_submit').show();
                    }
                    else if(response.status=='2')
                    {
                        //your required code or alert
                        $('#first_submit').show();
                        $('#second_submit').hide();
                    }
                    else
                    {
                        //your required code or alert
                    }
                }
            });
        });

    });
    </script>
</code>```

Handler PHP File

```<code><?php
session_start();

$result['status']='0';
$result['error']='';

if(!isset($_SESSION['validate']))
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-02 file missing!]';
    }
    else
    {
        //your other code
        $_SESSION['validate'] = true;
        $result['status']='1';
    }
}
else if($_SESSION['validate']==true)
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-03 Validation file missing!]';
    }
    else
    {
        //your other code
        unset($_SESSION['validate']);
        $result['status']='2';
    }
}
else
{
    $result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);
</code>```

?>

It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.

Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.

Hope it helps!

Title: Using AJAX with multiple submit buttons

Body:
I have a html form which includes 2 submit buttons.

These two submit buttons connect to a php file which runs statements based on the submits. The php file runs correctly, although when I use AJAX to send the data and to prevent to redirect, the information does not reach the php file, despite the php statements working fine when I am testing.

Interesting, when I use a PHP with just one submit and without if/else the information reaches the php for processing without redirection, so the problem probably lies with the two submits, and because my AJAX can't handle or distinguish the submits.

I attach my code

HTML

<input type="submit" name="first_submit" value="Frist" />
<input type="submit" name="second_submit" value="Second" />

AJAX

PHP

if (isset($_POST['first_submit'])) {
             //do something

    }
    elseif (isset($_POST['second_submit'])) {
               //do something
    }

    else {
    //do something
    }

?>

Body:
You can create and Use some session variable to achieve it easily.

E.g. $_SESSION['validate'].

HTML and PHP Code for buttons

<button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>

jquery and ajax Script

<script>
    $(document).ready(function(){

        $("#form").on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'handler-file.php',
                data:  new FormData(this),
                dataType: "json",
                enctype: 'multipart/form-data',
                contentType: false,
                cache: false,
                processData:false,
                error:function(error){
                    //your required code or alert
                    alert(error.responseText);
                },
                success: function(response){
                    if(response.status=='1')
                    {
                        //your required code or alert
                        $('#first_submit').hide();
                        $('#second_submit').show();
                    }
                    else if(response.status=='2')
                    {
                        //your required code or alert
                        $('#first_submit').show();
                        $('#second_submit').hide();
                    }
                    else
                    {
                        //your required code or alert
                    }
                }
            });
        });

    });
    </script>

Handler PHP File

<?php
session_start();

$result['status']='0';
$result['error']='';

if(!isset($_SESSION['validate']))
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-02 file missing!]';
    }
    else
    {
        //your other code
        $_SESSION['validate'] = true;
        $result['status']='1';
    }
}
else if($_SESSION['validate']==true)
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-03 Validation file missing!]';
    }
    else
    {
        //your other code
        unset($_SESSION['validate']);
        $result['status']='2';
    }
}
else
{
    $result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);

?>

It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.

Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.

Hope it helps!


问:
Go modules without remote repository?
I'm trying to get Go modules working without involving a remote repository.

src is a local directory that contains all my projects, also projects that are written in other languages than Go. For simplicity I have only show the two directories relevant for my question:

```<code>src
 ├── client
 │   ├── go.mod
 │   └── main.go
 └── lib
     ├── go.mod
     └── lib.go
</code>```

The go.mod files are created by running the command go mod init client in src/client and go mod init lib in src/lib.

src/client/main.go:

```<code>package main

import "lib"

func main() {
    lib.Hello()
}
</code>```

src/lib/lib.go:

```<code>package lib

import "fmt"

func Hello() {
    fmt.Println("Hello World")
}
</code>```

What I'm trying to do is using the library lib.go in my main.go, but no matter what I put in the import path, this error is shown:

```<code>main.go:3:8: package lib is not in GOROOT (/usr/lib/go/src/lib)
</code>```

Go version is go1.14.3

How do I correctly import Go code from local folders?

答:
You can use replace directive.

Project structure:

```<code>root
 ├── client
 │   ├── go.mod
 │   └── main.go
 └── lib
     ├── go.mod
     └── lib.go
</code>```

go.mod of root/lib module:

```<code>module github.com/owner/root/lib

go 1.13
</code>```

go.mod of root/client module:

```<code>module github.com/owner/root/client

go 1.13

require github.com/owner/root/lib v0.0.0

replace github.com/owner/root/lib => ../lib
</code>```

This is terrible, do you really have to do this for every import if
there is no VCS?

No. replace directive replaces the contents of a specific version of a module and includes packages that belong to substitute module.

```<code>root
 ├── client
 │   ├── go.mod
 │   └── main.go
 └── lib
     ├── utils
     │   └── util.go
     ├── libs
     │   └── lib.go
     └── go.mod
</code>```
```<code>package main

import (
    "github.com/owner/root/lib/utils"
    "github.com/owner/root/lib/libs"
)

func main() {
    //...
}

</code>```

Title: Go modules without remote repository?

Body:
I'm trying to get Go modules working without involving a remote repository.

src is a local directory that contains all my projects, also projects that are written in other languages than Go. For simplicity I have only show the two directories relevant for my question:

src
 ├── client
 │   ├── go.mod
 │   └── main.go
 └── lib
     ├── go.mod
     └── lib.go

The go.mod files are created by running the command go mod init client in src/client and go mod init lib in src/lib.

src/client/main.go:

package main

import "lib"

func main() {
    lib.Hello()
}

src/lib/lib.go:

package lib

import "fmt"

func Hello() {
    fmt.Println("Hello World")
}

What I'm trying to do is using the library lib.go in my main.go, but no matter what I put in the import path, this error is shown:

main.go:3:8: package lib is not in GOROOT (/usr/lib/go/src/lib)

Go version is go1.14.3

How do I correctly import Go code from local folders?

Body:
You can use replace directive.

Project structure:

root
 ├── client
 │   ├── go.mod
 │   └── main.go
 └── lib
     ├── go.mod
     └── lib.go

go.mod of root/lib module:

module github.com/owner/root/lib

go 1.13

go.mod of root/client module:

module github.com/owner/root/client

go 1.13

require github.com/owner/root/lib v0.0.0

replace github.com/owner/root/lib => ../lib

This is terrible, do you really have to do this for every import if
there is no VCS?

No. replace directive replaces the contents of a specific version of a module and includes packages that belong to substitute module.

root
 ├── client
 │   ├── go.mod
 │   └── main.go
 └── lib
     ├── utils
     │   └── util.go
     ├── libs
     │   └── lib.go
     └── go.mod

package main

import (
    "github.com/owner/root/lib/utils"
    "github.com/owner/root/lib/libs"
)

func main() {
    //...
}


问:
How to add module to package.json if it is already a global package?
I would like to have redux-thunk in my package.json, but use the globally installed version (not in my project-specific node_modules folder). Do I need to add it to my package.json manually? Using npm install -g redux-thunk doesn't add the package to my package.json. Also, when I run my react app and import redux-thunk, I get a module not found error even though redux-thunk is installed globally. Is this because I am required to have the package in my project's node_modules folder and not in the global installation location?

答:
the -g flag installs it globally. If you want to add it to your package.json file go to the directory where your package.json file is and run:

```<code>npm install redux-thunk
</code>```

Body:
the -g flag installs it globally. If you want to add it to your package.json file go to the directory where your package.json file is and run:

npm install redux-thunk


问:
DynamoDb query on stored date
I have resolving template that will get start date as date from appsync query. But my date saved in Dynamo is having datetime stamp. How we can compare these two dates without time. Below is my resolver template query:</p>

```<code> "version": "2018-05-29",
 "operation": "Query",
 "query": {
  "expression": "Id = :Id and startDate =:date",
  "expressionValues": {
    #set( $Id =
      $util.dynamodb.toDynamoDBJson("fixture#${ctx.args.input.Id}") )
    ":Id": $Id,
    #set( $date = $util.dynamodb.toDynamoDBJson($ctx.args.input.date)
    ":date": $date
  }
}
</code>```

答:
DynamoDB does not understand dates. Based on your requirements, there are two ways you can achieve this depending upon the format of the timestamp in your DynamoDB.

1 - If you store timestamp as "milliseconds/seconds since epoch", you can convert the AWSDate (which is ISO8601) to Epoch milliseconds/seconds timestamp using

$util.time.parseISO8601ToEpochMilliSeconds("2018-02-01T17:21:05.180+08:00")

and then use filter with BETWEEN :startDate AND :endDate to query your table based on the input date.
Please note that

endDate(seconds) = startDate + 86400

or

endDate(milliseconds) = startDate + 86400000

2 - If you use String representation of timestamp, then you might need to add Global Secondary Index (GSI) with a date field as attribute of keytype "range". There are some very good explanation and suggested solution on this link, this link and this link.

I hope this helps you.

Title: DynamoDb query on stored date

Body:
I have resolving template that will get start date as date from appsync query. But my date saved in Dynamo is having datetime stamp. How we can compare these two dates without time. Below is my resolver template query:

 "version": "2018-05-29",
 "operation": "Query",
 "query": {
  "expression": "Id = :Id and startDate =:date",
  "expressionValues": {
    #set( $Id =
      $util.dynamodb.toDynamoDBJson("fixture#${ctx.args.input.Id}") )
    ":Id": $Id,
    #set( $date = $util.dynamodb.toDynamoDBJson($ctx.args.input.date)
    ":date": $date
  }
}


问:
IntelliJ IDEA Android app XML tags not found

Issue: IntelliJ can't find any XML tags (marked in red by IntelliJ)

Steps followed: Open IntelliJ -> Create a new project -> Android -> Empty Activity -> Let Gradle sync

Surprising part: The code compiles perfectly and even runs on an Android phone connected via ADB.

So, I believe it is an issue regarding the IDE and nothing else. Please help me out.

Thanks

答:
In my case I had too same problem. First try cleaning the project Build>Clean. Then try clearing the cache and then restart your android project. For this goto File>Invalidate Cache and Restart.
Hope it solves! </p>


问:
Create single pandas dataframe from a list of dataframes
I have a list of about 25 dfs and all of the columns are the same. Although the row count is different, I am only interested in the first row of each df.
How can I iterate through the list of dfs, copy the first row from each and concatenate them all into a single df?</p>

答:
Select first row by position with DataFrame.iloc and [[0]] for one row DataFrames and join together by concat:

```<code>df = pd.concat([x.iloc[[0]] for x in dfs], ignore_index=True)
</code>```

Or use DataFrame.head for one row DataFrames:

```<code>df = pd.concat([x.head(1) for x in dfs], ignore_index=True)
</code>```

Body:
Select first row by position with DataFrame.iloc and [[0]] for one row DataFrames and join together by concat:

df = pd.concat([x.iloc[[0]] for x in dfs], ignore_index=True)

Or use DataFrame.head for one row DataFrames:

df = pd.concat([x.head(1) for x in dfs], ignore_index=True)


问:
RegEx in Notepad++ to find and replace strings
I'm trying to find and replace strings using RegEx on Notepad++, but cannot identify the right expression to do it:

Here is the data:

```<code>TRAIN-II
TRAIN
TRAIN-I
AIRPLANE-II
AIRPLANE
AIRPLANE-I
SHIP-II
SHIP
SHIP-I
</code>```

Well, I want to keep only the string which has "-II" as suffix. In simpler words, I want to retain only:

```<code>TRAIN-II
AIRPLANE-II
SHIP-II
</code>```

Can anyone please help?

答:
Use a regex to mark the lines, then remove unmarked lines.

Open the search window and then the "Mark" tab.
Enter -II$ into the "Find what" box. Select "Regular expressions". Select "Match case" if the "II" must be in upper case. Select "Bookmark line". Click on "Mark all". Expect to see the wanted lines marked with a blue circle. Use menu => Search => Bookmark => Remove unmarked lines.

Body:
I'm trying to find and replace strings using RegEx on Notepad++, but cannot identify the right expression to do it:

Here is the data:

TRAIN-II
TRAIN
TRAIN-I
AIRPLANE-II
AIRPLANE
AIRPLANE-I
SHIP-II
SHIP
SHIP-I

Well, I want to keep only the string which has "-II" as suffix. In simpler words, I want to retain only:

TRAIN-II
AIRPLANE-II
SHIP-II

Can anyone please help?


问:
Path to Deno is not correct WebStorm
I am trying to run a simple Deno project in WebStorm. I have installed Deno and enabled the Deno support for this project.

Also added an environment variable of the Deno bin folder with name: DENO_INSTALL_DIR

But while setting the run configuration it's showing an error: Path to Deno is not correct

Please give me a solution regarding this problem. Thanks in advance.

答:
In my case bin path after default installation on ubintu is is on location: $HOME/.deno/bin/deno
You should have this path in your DENO_INSTALL_DIR environment variable, depending on your OS.

Title: Path to Deno is not correct WebStorm


问:
Rails rescue inactive or unreachable
I have the following code in Rails routing:

```<code>    class LegacyRedirector
      InvalidUrlError = Class.new(ActionController::RoutingError)

      def call(params, request)
        URI.parse(request.path)
      rescue URI::InvalidURIError => e
        raise InvalidUrlError.new(e.message)
      end
    end

# routes.rb
match 'a', to: redirect(LegacyRedirector.new)
</code>```

This is for catching invaild URLs. However when I test it in browser for curl, it would still display  URI::InvalidURIError, not my new error class. It seems the rescue block was never reached, yet I am sure I am rescuing the correct type. How can that be?

```<code>URI::InvalidURIError at /twitter/typeahead-js/wikis/home[
=========================================================

> bad URI(is not URI?): "/twitter/typeahead-js/wikis/home["

lib/gitlab/routing.rb, line 31
------------------------------

``` ruby
>  31           URI.parse(request.path)
   32         rescue URI::InvalidURIError => e
   33           raise InvalidUrlError.new(e.message)
   34         end
```
</code>```

答:
One possible cause could be better_errors.

If an error is raised in a rescue block, its cause would be the original error. better_errors displays that cause instead, meaning the backtrace will not be in the rescue block. This gives you the illusion that it is never rescued.

This was recently fixed, see https://github.com/BetterErrors/better_errors/pull/459 for more details

Title: Rails rescue inactive or unreachable

Body:
I have the following code in Rails routing:

    class LegacyRedirector
      InvalidUrlError = Class.new(ActionController::RoutingError)

      def call(params, request)
        URI.parse(request.path)
      rescue URI::InvalidURIError => e
        raise InvalidUrlError.new(e.message)
      end
    end

# routes.rb
match 'a', to: redirect(LegacyRedirector.new)

This is for catching invaild URLs. However when I test it in browser for curl, it would still display  URI::InvalidURIError, not my new error class. It seems the rescue block was never reached, yet I am sure I am rescuing the correct type. How can that be?

URI::InvalidURIError at /twitter/typeahead-js/wikis/home[
=========================================================

> bad URI(is not URI?): "/twitter/typeahead-js/wikis/home["

lib/gitlab/routing.rb, line 31
------------------------------

``` ruby
>  31           URI.parse(request.path)
   32         rescue URI::InvalidURIError => e
   33           raise InvalidUrlError.new(e.message)
   34         end
```


问:
ReactJS and Typescript - Children components : get children props and refresh children when parent state changed
I need help on ReactJS and Typescript code, with the use of material-ui.

I want to redo the tab system proposed on the following link by creating my own component names: https://material-ui.com/components/tabs/#simple-tabs.

Here is the code I made: https://codepen.io/Answerrer/pen/wvKLLzg.

```<code>interface MyTabPanelProperties {
  label: string;
  value: number;
  index: number;
  children?: React.ReactNode;
}

 type MyTabPanelState = {}

class MyTabPanel extends React.Component<MyTabPanelProperties, MyTabPanelState> {

  render(): JSX.Element {
    const { children, value, index } = this.props;
    const element = (
      <div role="tabpanel" hidden={value !== index} aria-labelledby={'simple-tab'}>
        {children}
      </div>
    );

    return element;
  }
}

interface MyTabsProperties<T = MyTabPanelProperties> {
  value?: number;
  children: React.ReactElement<T> | Array<React.ReactElement<T>> | React.Component<T> | Array<React.Component<T>>;
}

interface MyTabsState {
  value: number;
}

class MyTabs extends React.Component<MyTabsProperties, MyTabsState> {
  constructor(props: MyTabsProperties) {
    super(props);
    this.state = {
      value: this.props.value ? this.props.value : 0
    };
  }

  private checkChildrenName(children: ReactNode, names: string | Array<string>): boolean {
    const childs = React.Children.toArray(children);
    let check = false,
        allNames = new Array<string>();

    if (names instanceof Array) {
      allNames = names;
    } else {
      allNames = names.split(' ');
    }

    if (allNames.length === 0) {
      throw Error('Must specify names for check children');
    }

    check = childs.every((child) => {
      let check = false;
      const name = this.getComponentChildName(child);
      if (name) {
        check = allNames.includes(name);
      }
      return check;
    });

    return check;
  }

  private getComponentChildName(component: any): string | undefined {
    const type = (component.type || {});
    let name = undefined;

    if (component) {
      name = component.displayName ||
      component.name ||
      type.displayName ||
      type.name ||
      undefined;
    }

    return name;
  }

  render(): JSX.Element {
    const { children } = this.props;
    let element: JSX.Element;
    if (this.checkChildrenName(children, 'MyTabPanel')) {
      element = (
        <div>
          <AppBar position='static'>
            <Tabs value='0' onChange={this.handleChange.bind(this)}>
              {React.Children.map(children, (child, index) => {
                return this.renderAppBarTab(child, index);
              })}
            </Tabs>
          </AppBar>
          {children}
        </div>
      );
    } else {
      throw Error('Must use MyTabPanel component in a MyTabs component');
    }
    return element;
  }

  private handleChange(event: React.ChangeEvent<{}>, newValue: number): void {}

  private renderAppBarTab(child, index: number): JSX.Element {
    const label = 'Test';
    const element = (
      <Tab label={label} key={index} />
    );

    return element;
  }

  set value(value:number) {
    this.setState({value: value});
  }
}

ReactDOM.render(
  <React.StrictMode>
    <MyTabs>
      <MyTabPanel label='Tab1'>
        <Typography>Test1</Typography>
      </MyTabPanel>
      <MyTabPanel label='Tab2'>
        <Typography>Test2</Typography>
      </MyTabPanel>
    </MyTabs>
  </React.StrictMode>
  , document.getElementById('root'));
</code>```

I don't know why I can't get it to work on CodePen when my workstation is working fine.

My parent component is MyTabset my children component is MyTabPanel.

I will need your help on the following points:

In my parent component, renderAppBarTab method, I want to retrieve the properties of my children component specifically, the label property (today I have set a hard constant because I don't know what to do)? TypeScript does not allow me to call props on my children, because the type of my child parameter does not suit it. I would like to retrieve the properties of the type used for my children component (MyTabPanelProperties).

I would like to update the hidden property of my children component by modifying the status of my parent component (the value property), as in the example proposed by material-ui.

Anyone have any ideas?

Thanks in advance

答:
I kept looking for a solution and found something: https://codepen.io/Answerrer/pen/ExPxmEN.

```<code>interface MyTabPanelProperties {
  label: string;
  children?: React.ReactNode;
}

 type MyTabPanelState = {}

class MyTabPanel extends React.Component<MyTabPanelProperties, MyTabPanelState> {

  render(): JSX.Element {
    const { children, value, index } = this.props;
    const element = (
      <div role="tabpanel" aria-labelledby={'simple-tab'}>
        {children}
      </div>
    );

    return element;
  }
}

interface MyTabsProperties<T = MyTabPanelProperties> {
  selectedTab?: unknown;
  children: React.ReactElement<T> | Array<React.ReactElement<T>> | React.Component<T> | Array<React.Component<T>>;
}

interface MyTabsState {
  selectedTab?: unknown;
}

class MyTabs extends React.Component<MyTabsProperties, MyTabsState> {
  constructor(props: MyTabsProperties) {
    super(props);

    const { children } = this.props;
    const allChilds = React.Children.toArray(children);
    let selectedChildId;

    if (allChilds.length > 0) {
      selectedChildId = (allChilds[0] as MyTabPanel).props.id;
    } else {
      selectedChildId = 0;
    }

    this.state = {
      selectedTab: this.props.selectedTab ? this.props.selectedTab : selectedChildId
    };
  }

  private checkChildrenName(children: ReactNode, names: string | Array<string>): boolean {
    const childs = React.Children.toArray(children);
    let check = false,
        allNames = new Array<string>();

    if (names instanceof Array) {
      allNames = names;
    } else {
      allNames = names.split(' ');
    }

    if (allNames.length === 0) {
      throw Error('Must specify names for check children');
    }

    check = childs.every((child) => {
      let check = false;
      const name = this.getComponentChildName(child);
      if (name) {
        check = allNames.includes(name);
      }
      return check;
    });

    return check;
  }

  private getComponentChildName(component: any): string | undefined {
    const type = (component.type || {});
    let name = undefined;

    if (component) {
      name = component.displayName ||
      component.name ||
      type.displayName ||
      type.name ||
      undefined;
    }

    return name;
  }

  render(): JSX.Element {
    const { children } = this.props;
    let element: JSX.Element;
    if (this.checkChildrenName(children, 'MyTabPanel')) {
      element = (
        <div>
          <AppBar position='static'>
            <Tabs value='0' onChange={this.handleChange.bind(this)}>
              {React.Children.map(children, (child, index) => {
                return this.renderAppBarTab((child as MyTabPanel), index);
              })}
            </Tabs>
          </AppBar>
          {React.Children.map(children, (child, index) => {
            const id = (child as MyTabPanel).props.id;
            if (selectedTab === id) {
              return child;
            }
          })}
        </div>
      );
    } else {
      throw Error('Must use MyTabPanel component in a MyTabs component');
    }
    return element;
  }

  private handleChange(event: React.ChangeEvent<{}>, selectedTab: unknown): void {
    this.selectedTab = selectedTab;
  }

  set selectedTab(selectedTab: unknown) {
    this.setState({ selectedTab: selectedTab });
  }

  private renderAppBarTab(child:MyTabPanel, index: number): JSX.Element {
    const { label, id } = child.props;
    const element = (
      <Tab label={label} value={id} />
    );

    return element;
  }
}

ReactDOM.render(
  <React.StrictMode>
    <MyTabs>
      <MyTabPanel label='Tab1'>
        <Typography>Test1</Typography>
      </MyTabPanel>
      <MyTabPanel label='Tab2'>
        <Typography>Test2</Typography>
      </MyTabPanel>
    </MyTabs>
  </React.StrictMode>
  , document.getElementById('root'));
</code>```

Instead of changing the status of children, in the parent's render, I displayed only the child to be displayed (the one whose identifier corresponds to the selected tab). It works, for the moment. However, there is something I did that I don't really like because I don't understand and I don't know if I have the right to do it (in any case, no compilation error and execution of my project). I had to cast my children. I don't know if I have the right to do this. Could someone clear me up? Do I have the right to cast my child as I did in my case? Thank you

Body:
I need help on ReactJS and Typescript code, with the use of material-ui.

I want to redo the tab system proposed on the following link by creating my own component names: https://material-ui.com/components/tabs/#simple-tabs.

Here is the code I made: https://codepen.io/Answerrer/pen/wvKLLzg.

interface MyTabPanelProperties {
  label: string;
  value: number;
  index: number;
  children?: React.ReactNode;
}

 type MyTabPanelState = {}

class MyTabPanel extends React.Component<MyTabPanelProperties, MyTabPanelState> {

  render(): JSX.Element {
    const { children, value, index } = this.props;
    const element = (

        {children}

    );

    return element;
  }
}

interface MyTabsProperties<T = MyTabPanelProperties> {
  value?: number;
  children: React.ReactElement<T> | Array<React.ReactElement<T>> | React.Component<T> | Array<React.Component<T>>;
}

interface MyTabsState {
  value: number;
}

class MyTabs extends React.Component<MyTabsProperties, MyTabsState> {
  constructor(props: MyTabsProperties) {
    super(props);
    this.state = {
      value: this.props.value ? this.props.value : 0
    };
  }

  private checkChildrenName(children: ReactNode, names: string | Array<string>): boolean {
    const childs = React.Children.toArray(children);
    let check = false,
        allNames = new Array<string>();

    if (names instanceof Array) {
      allNames = names;
    } else {
      allNames = names.split(' ');
    }

    if (allNames.length === 0) {
      throw Error('Must specify names for check children');
    }

    check = childs.every((child) => {
      let check = false;
      const name = this.getComponentChildName(child);
      if (name) {
        check = allNames.includes(name);
      }
      return check;
    });

    return check;
  }

  private getComponentChildName(component: any): string | undefined {
    const type = (component.type || {});
    let name = undefined;

    if (component) {
      name = component.displayName ||
      component.name ||
      type.displayName ||
      type.name ||
      undefined;
    }

    return name;
  }

  render(): JSX.Element {
    const { children } = this.props;
    let element: JSX.Element;
    if (this.checkChildrenName(children, 'MyTabPanel')) {
      element = (

          <AppBar position='static'>
            <Tabs value='0' onChange={this.handleChange.bind(this)}>
              {React.Children.map(children, (child, index) => {
                return this.renderAppBarTab(child, index);
              })}
            </Tabs>
          </AppBar>
          {children}

      );
    } else {
      throw Error('Must use MyTabPanel component in a MyTabs component');
    }
    return element;
  }

  private handleChange(event: React.ChangeEvent<{}>, newValue: number): void {}

  private renderAppBarTab(child, index: number): JSX.Element {
    const label = 'Test';
    const element = (
      <Tab label={label} key={index} />
    );

    return element;
  }

  set value(value:number) {
    this.setState({value: value});
  }
}

ReactDOM.render(
  <React.StrictMode>
    <MyTabs>
      <MyTabPanel label='Tab1'>
        <Typography>Test1</Typography>
      </MyTabPanel>
      <MyTabPanel label='Tab2'>
        <Typography>Test2</Typography>
      </MyTabPanel>
    </MyTabs>
  </React.StrictMode>
  , document.getElementById('root'));

I don't know why I can't get it to work on CodePen when my workstation is working fine.

My parent component is MyTabset my children component is MyTabPanel.

I will need your help on the following points:

In my parent component, renderAppBarTab method, I want to retrieve the properties of my children component specifically, the label property (today I have set a hard constant because I don't know what to do)? TypeScript does not allow me to call props on my children, because the type of my child parameter does not suit it. I would like to retrieve the properties of the type used for my children component (MyTabPanelProperties).

I would like to update the hidden property of my children component by modifying the status of my parent component (the value property), as in the example proposed by material-ui.

Anyone have any ideas?

Thanks in advance

Body:
I kept looking for a solution and found something: https://codepen.io/Answerrer/pen/ExPxmEN.

interface MyTabPanelProperties {
  label: string;
  children?: React.ReactNode;
}

 type MyTabPanelState = {}

class MyTabPanel extends React.Component<MyTabPanelProperties, MyTabPanelState> {

  render(): JSX.Element {
    const { children, value, index } = this.props;
    const element = (
      <div role="tabpanel" aria-labelledby={'simple-tab'}>
        {children}
      </div>
    );

    return element;
  }
}

interface MyTabsProperties<T = MyTabPanelProperties> {
  selectedTab?: unknown;
  children: React.ReactElement<T> | Array<React.ReactElement<T>> | React.Component<T> | Array<React.Component<T>>;
}

interface MyTabsState {
  selectedTab?: unknown;
}

class MyTabs extends React.Component<MyTabsProperties, MyTabsState> {
  constructor(props: MyTabsProperties) {
    super(props);

    const { children } = this.props;
    const allChilds = React.Children.toArray(children);
    let selectedChildId;

    if (allChilds.length > 0) {
      selectedChildId = (allChilds[0] as MyTabPanel).props.id;
    } else {
      selectedChildId = 0;
    }

    this.state = {
      selectedTab: this.props.selectedTab ? this.props.selectedTab : selectedChildId
    };
  }

  private checkChildrenName(children: ReactNode, names: string | Array<string>): boolean {
    const childs = React.Children.toArray(children);
    let check = false,
        allNames = new Array<string>();

    if (names instanceof Array) {
      allNames = names;
    } else {
      allNames = names.split(' ');
    }

    if (allNames.length === 0) {
      throw Error('Must specify names for check children');
    }

    check = childs.every((child) => {
      let check = false;
      const name = this.getComponentChildName(child);
      if (name) {
        check = allNames.includes(name);
      }
      return check;
    });

    return check;
  }

  private getComponentChildName(component: any): string | undefined {
    const type = (component.type || {});
    let name = undefined;

    if (component) {
      name = component.displayName ||
      component.name ||
      type.displayName ||
      type.name ||
      undefined;
    }

    return name;
  }

  render(): JSX.Element {
    const { children } = this.props;
    let element: JSX.Element;
    if (this.checkChildrenName(children, 'MyTabPanel')) {
      element = (
        <div>
          <AppBar position='static'>
            <Tabs value='0' onChange={this.handleChange.bind(this)}>
              {React.Children.map(children, (child, index) => {
                return this.renderAppBarTab((child as MyTabPanel), index);
              })}
            </Tabs>
          </AppBar>
          {React.Children.map(children, (child, index) => {
            const id = (child as MyTabPanel).props.id;
            if (selectedTab === id) {
              return child;
            }
          })}
        </div>
      );
    } else {
      throw Error('Must use MyTabPanel component in a MyTabs component');
    }
    return element;
  }

  private handleChange(event: React.ChangeEvent<{}>, selectedTab: unknown): void {
    this.selectedTab = selectedTab;
  }

  set selectedTab(selectedTab: unknown) {
    this.setState({ selectedTab: selectedTab });
  }

  private renderAppBarTab(child:MyTabPanel, index: number): JSX.Element {
    const { label, id } = child.props;
    const element = (
      <Tab label={label} value={id} />
    );

    return element;
  }
}

ReactDOM.render(
  <React.StrictMode>
    <MyTabs>
      <MyTabPanel label='Tab1'>
        <Typography>Test1</Typography>
      </MyTabPanel>
      <MyTabPanel label='Tab2'>
        <Typography>Test2</Typography>
      </MyTabPanel>
    </MyTabs>
  </React.StrictMode>
  , document.getElementById('root'));

Instead of changing the status of children, in the parent's render, I displayed only the child to be displayed (the one whose identifier corresponds to the selected tab). It works, for the moment. However, there is something I did that I don't really like because I don't understand and I don't know if I have the right to do it (in any case, no compilation error and execution of my project). I had to cast my children. I don't know if I have the right to do this. Could someone clear me up? Do I have the right to cast my child as I did in my case? Thank you